Compare commits
86 Commits
fret_112_c
...
fret
Author | SHA1 | Date | |
---|---|---|---|
798aa2ceb9 | |||
183ff32beb | |||
89979b64d9 | |||
35da9fdf24 | |||
1bca346b39 | |||
8b90886299 | |||
1bd7d853ac | |||
253048e534 | |||
52cc00fedc | |||
eec998c426 | |||
a328ddfd5f | |||
6a042da5c1 | |||
2e20a22dc6 | |||
bbc83ef6be | |||
48466ac2d7 | |||
ad8cecdba4 | |||
c2afc0186e | |||
4df67db479 | |||
402eff7b47 | |||
a8a6c175c8 | |||
8a79e12f91 | |||
a3e38b6abb | |||
eb04325f09 | |||
cfb8fa2b32 | |||
2889e9bf61 | |||
960764cf85 | |||
e6816cc2de | |||
f3180a35cc | |||
54312b2577 | |||
6d920fd962 | |||
281979ecd8 | |||
c628afaa81 | |||
c548c6bc09 | |||
6e8769907d | |||
bf639e42fa | |||
a05ff97d0c | |||
f09034b7fe | |||
d118eeacbd | |||
57fc441118 | |||
10b5fe8a74 | |||
7f987b037d | |||
58be280a62 | |||
3c586f5047 | |||
9336b932d0 | |||
e0f73778e2 | |||
e5ac5ba825 | |||
2acf3ef301 | |||
28bac2a850 | |||
41586dd8b1 | |||
7420aabeeb | |||
d118ff0056 | |||
dfe4f713b9 | |||
f7a05d2a7c | |||
2593bdf42f | |||
8c8ab7c44e | |||
9cadc5d61c | |||
594554eca0 | |||
267309b954 | |||
35435fbd97 | |||
8fcc54bbdd | |||
1f538f9834 | |||
ba01f600ee | |||
2cb479581d | |||
1fbf948478 | |||
6e1d5695e3 | |||
8d31196614 | |||
4c90144db5 | |||
eeaf7eb43f | |||
68c4887dad | |||
7ca2d43f3d | |||
9f97852e4a | |||
f4e1990387 | |||
d936234976 | |||
795fbff61a | |||
6a9df35e28 | |||
9b9fbc3677 | |||
decae09931 | |||
b812e994a6 | |||
4587f442d0 | |||
c748fecbe2 | |||
7595d25192 | |||
79bca99cc7 | |||
b07f7ccbca | |||
e3f38edd0a | |||
6ad55e3b29 | |||
f7ee38ebb2 |
255
.github/workflows/build_and_test.yml
vendored
255
.github/workflows/build_and_test.yml
vendored
@ -2,10 +2,10 @@ name: build and test
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ main, 'pr/**' ]
|
branches: [ main ]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ main ]
|
branches: [ main ]
|
||||||
workflow_dispatch:
|
|
||||||
env:
|
env:
|
||||||
CARGO_TERM_COLOR: always
|
CARGO_TERM_COLOR: always
|
||||||
|
|
||||||
@ -16,9 +16,6 @@ jobs:
|
|||||||
os: [ubuntu-latest, windows-latest, macOS-latest]
|
os: [ubuntu-latest, windows-latest, macOS-latest]
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
steps:
|
steps:
|
||||||
- name: Install mimetype
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: sudo apt-get install libfile-mimeinfo-perl
|
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
profile: minimal
|
profile: minimal
|
||||||
@ -34,6 +31,9 @@ jobs:
|
|||||||
crate: mdbook-linkcheck
|
crate: mdbook-linkcheck
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: Swatinem/rust-cache@v2
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
- name: Install mimetype
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
run: sudo apt-get install libfile-mimeinfo-perl
|
||||||
- name: Check for binary blobs
|
- name: Check for binary blobs
|
||||||
if: runner.os == 'Linux'
|
if: runner.os == 'Linux'
|
||||||
run: ./scripts/check_for_blobs.sh
|
run: ./scripts/check_for_blobs.sh
|
||||||
@ -49,8 +49,6 @@ jobs:
|
|||||||
run: cargo test
|
run: cargo test
|
||||||
- name: Test libafl no_std
|
- name: Test libafl no_std
|
||||||
run: cd libafl && cargo test --no-default-features
|
run: cd libafl && cargo test --no-default-features
|
||||||
- name: Test libafl_bolts no_std no_alloc
|
|
||||||
run: cd libafl_bolts && cargo test --no-default-features
|
|
||||||
- name: Test libafl_targets no_std
|
- name: Test libafl_targets no_std
|
||||||
run: cd libafl_targets && cargo test --no-default-features
|
run: cd libafl_targets && cargo test --no-default-features
|
||||||
|
|
||||||
@ -63,18 +61,18 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
profile: minimal
|
profile: minimal
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
- name: Remove existing clang and LLVM
|
- name: set mold linker as default linker
|
||||||
run: sudo apt purge llvm* clang*
|
uses: rui314/setup-mold@v1
|
||||||
- name: Install and cache deps
|
- name: Install and cache deps
|
||||||
uses: awalsh128/cache-apt-pkgs-action@v1.1.0
|
uses: awalsh128/cache-apt-pkgs-action@v1.1.0
|
||||||
with:
|
with:
|
||||||
packages: llvm-15 llvm-15-dev clang-15 ninja-build clang-format-13 shellcheck libgtk-3-dev gcc-arm-linux-gnueabi g++-arm-linux-gnueabi libslirp-dev libz3-dev
|
packages: llvm llvm-dev clang ninja-build clang-format-13 shellcheck libgtk-3-dev gcc-arm-linux-gnueabi g++-arm-linux-gnueabi libslirp-dev
|
||||||
- name: get clang version
|
- name: get clang version
|
||||||
run: command -v llvm-config-15 && clang-15 -v
|
run: command -v llvm-config && clang -v
|
||||||
|
- name: Install cargo-hack
|
||||||
|
run: curl -LsSf https://github.com/taiki-e/cargo-hack/releases/latest/download/cargo-hack-x86_64-unknown-linux-gnu.tar.gz | tar xzf - -C ~/.cargo/bin
|
||||||
- name: Add nightly rustfmt and clippy
|
- name: Add nightly rustfmt and clippy
|
||||||
run: rustup toolchain install nightly --component rustfmt --component clippy --component miri --allow-downgrade
|
run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade
|
||||||
- name: Install ucd-generate
|
|
||||||
run: cargo install -f ucd-generate
|
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: Swatinem/rust-cache@v2
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
|
||||||
@ -84,8 +82,6 @@ jobs:
|
|||||||
run: cargo check --features=sancov_pcguard_edges
|
run: cargo check --features=sancov_pcguard_edges
|
||||||
- name: Format
|
- name: Format
|
||||||
run: cargo fmt -- --check
|
run: cargo fmt -- --check
|
||||||
- name: Cleanup
|
|
||||||
run: cargo clean
|
|
||||||
- name: Run clang-format style check for C/C++ programs.
|
- name: Run clang-format style check for C/C++ programs.
|
||||||
run: clang-format-13 -n -Werror --style=file $(find . -type f \( -name '*.cpp' -o -iname '*.hpp' -o -name '*.cc' -o -name '*.cxx' -o -name '*.cc' -o -name '*.h' \) | grep -v '/target/' | grep -v 'libpng-1\.6\.37' | grep -v 'stb_image\.h' | grep -v 'dlmalloc\.c' | grep -v 'QEMU-Nyx')
|
run: clang-format-13 -n -Werror --style=file $(find . -type f \( -name '*.cpp' -o -iname '*.hpp' -o -name '*.cc' -o -name '*.cxx' -o -name '*.cc' -o -name '*.h' \) | grep -v '/target/' | grep -v 'libpng-1\.6\.37' | grep -v 'stb_image\.h' | grep -v 'dlmalloc\.c' | grep -v 'QEMU-Nyx')
|
||||||
- name: run shellcheck
|
- name: run shellcheck
|
||||||
@ -95,64 +91,23 @@ jobs:
|
|||||||
|
|
||||||
# ---- doc check ----
|
# ---- doc check ----
|
||||||
- name: Build Docs
|
- name: Build Docs
|
||||||
run: RUSTFLAGS="--cfg docsrs" cargo +nightly doc --all-features
|
run: cargo doc
|
||||||
- name: Test Docs
|
- name: Test Docs
|
||||||
run: RUSTFLAGS="--cfg docsrs" cargo +nightly test --doc --all-features
|
run: cargo +nightly test --doc --all-features
|
||||||
# ---- build normal and examples ----
|
|
||||||
- name: Run a normal build
|
|
||||||
run: cargo build --verbose
|
|
||||||
- name: Build examples
|
|
||||||
run: cargo build --examples --verbose
|
|
||||||
|
|
||||||
# --- miri undefined behavior test --
|
|
||||||
- name: Run miri tests
|
|
||||||
run: RUST_BACKTRACE=1 MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri test
|
|
||||||
|
|
||||||
# Clean up files to save up disk space
|
|
||||||
- name: Cleanup
|
|
||||||
run: cargo clean
|
|
||||||
|
|
||||||
# --- test embedding the libafl_libfuzzer_runtime library
|
|
||||||
# Fix me plz
|
|
||||||
# - name: Test Build libafl_libfuzzer with embed
|
|
||||||
# run: cargo +nightly test --features=embed-runtime --manifest-path libafl_libfuzzer/Cargo.toml
|
|
||||||
|
|
||||||
ubuntu-check:
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
steps:
|
|
||||||
- name: Remove Dotnet & Haskell
|
|
||||||
run: rm -rf /usr/share/dotnet && rm -rf /opt/ghc
|
|
||||||
- uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
profile: minimal
|
|
||||||
toolchain: stable
|
|
||||||
components: llvm-tools
|
|
||||||
- name: Remove existing clang and LLVM
|
|
||||||
run: sudo apt purge llvm* clang*
|
|
||||||
- name: Install and cache deps
|
|
||||||
uses: awalsh128/cache-apt-pkgs-action@v1.1.0
|
|
||||||
with:
|
|
||||||
packages: llvm-15 llvm-15-dev clang-15 ninja-build clang-format-13 shellcheck libgtk-3-dev gcc-arm-linux-gnueabi g++-arm-linux-gnueabi libslirp-dev libz3-dev
|
|
||||||
- name: get clang version
|
|
||||||
run: command -v llvm-config-15 && clang-15 -v
|
|
||||||
- name: Install cargo-hack
|
|
||||||
run: curl -LsSf https://github.com/taiki-e/cargo-hack/releases/latest/download/cargo-hack-x86_64-unknown-linux-gnu.tar.gz | tar xzf - -C ~/.cargo/bin
|
|
||||||
- name: Install ucd-generate
|
|
||||||
run: cargo install -f ucd-generate
|
|
||||||
- name: Add nightly
|
|
||||||
run: rustup toolchain install nightly --allow-downgrade
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
- uses: Swatinem/rust-cache@v2
|
|
||||||
|
|
||||||
# ---- build and feature check ----
|
# ---- build and feature check ----
|
||||||
|
- name: Run a normal build
|
||||||
|
run: cargo build --verbose
|
||||||
# cargo-hack's --feature-powerset would be nice here but libafl has a too many knobs
|
# cargo-hack's --feature-powerset would be nice here but libafl has a too many knobs
|
||||||
- name: Check each feature
|
- name: Check each feature
|
||||||
# Skipping `python` as it has to be built with the `maturin` tool
|
# Skipping `python` as it has to be built with the `maturin` tool
|
||||||
# `agpl`, `nautilus` require nightly
|
# `agpl`, `nautilus` require nightly
|
||||||
# `sancov_pcguard_edges` is tested seperately
|
# `sancov_pcguard_edges` is tested seperately
|
||||||
run: LLVM_CONFIG=llvm-config-15 cargo hack check --workspace --each-feature --clean-per-run --exclude-features=prelude,agpl,nautilus,python,sancov_pcguard_edges,arm,aarch64,i386,be,systemmode,whole_archive --no-dev-deps --exclude libafl_libfuzzer
|
run: cargo hack check --each-feature --clean-per-run --exclude-features=prelude,agpl,nautilus,python,sancov_pcguard_edges,arm,aarch64,i386,be,systemmode --no-dev-deps
|
||||||
- name: Check nightly features
|
- name: Check nightly features
|
||||||
run: cargo +nightly check --features=agpl && cargo +nightly check --features=nautilus
|
run: cargo +nightly check --features=agpl && cargo +nightly check --features=nautilus
|
||||||
|
- name: Build examples
|
||||||
|
run: cargo build --examples --verbose
|
||||||
|
|
||||||
ubuntu-concolic:
|
ubuntu-concolic:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@ -175,141 +130,45 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
profile: minimal
|
profile: minimal
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
- name: Remove existing clang and LLVM
|
- name: set mold linker as default linker
|
||||||
run: sudo apt purge llvm* clang*
|
uses: rui314/setup-mold@v1
|
||||||
- name: Install deps
|
- name: Install deps
|
||||||
run: sudo apt-get install -y llvm-15 llvm-15-dev clang-15 ninja-build python3-dev python3-pip python3-venv libz3-dev
|
run: sudo apt-get install -y llvm llvm-dev clang ninja-build python3-dev python3-pip python3-venv
|
||||||
- name: Install maturin
|
- name: Install maturin
|
||||||
run: python3 -m pip install maturin
|
run: python3 -m pip install maturin
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: Swatinem/rust-cache@v2
|
- uses: Swatinem/rust-cache@v2
|
||||||
- name: Run a maturin build
|
- name: Run a maturin build
|
||||||
run: export LLVM_CONFIG=llvm-config-15 && cd ./bindings/pylibafl && python3 -m venv .env && . .env/bin/activate && pip install --upgrade --force-reinstall . && ./test.sh
|
run: cd ./bindings/pylibafl && maturin build
|
||||||
- name: Run python test
|
|
||||||
run: . ./bindings/pylibafl/.env/bin/activate && cd ./fuzzers/baby_fuzzer && python3 baby_fuzzer.py 2>&1 | grep "Bye"
|
|
||||||
|
|
||||||
fuzzers:
|
fuzzers:
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-latest]
|
os: [ubuntu-latest, macos-latest]
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
profile: minimal
|
profile: minimal
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
- name: Free Disk Space (Ubuntu)
|
- name: set mold linker as default linker
|
||||||
uses: jlumbroso/free-disk-space@main
|
if: runner.os == 'Linux' # mold only support linux until now
|
||||||
with:
|
uses: rui314/setup-mold@v1
|
||||||
# this might remove tools that are actually needed,
|
|
||||||
# if set to "true" but frees about 6 GB
|
|
||||||
tool-cache: false
|
|
||||||
|
|
||||||
# all of these default to true, but feel free to set to
|
|
||||||
# "false" if necessary for your workflow
|
|
||||||
android: true
|
|
||||||
dotnet: true
|
|
||||||
haskell: true
|
|
||||||
large-packages: false
|
|
||||||
docker-images: true
|
|
||||||
swap-storage: true
|
|
||||||
- name: Add nightly rustfmt and clippy
|
- name: Add nightly rustfmt and clippy
|
||||||
run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade
|
run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade
|
||||||
- name: Add no_std toolchain
|
- name: Add no_std toolchain
|
||||||
run: rustup toolchain install nightly-x86_64-unknown-linux-gnu ; rustup component add rust-src --toolchain nightly-x86_64-unknown-linux-gnu
|
run: rustup toolchain install nightly-x86_64-unknown-linux-gnu ; rustup component add rust-src --toolchain nightly-x86_64-unknown-linux-gnu
|
||||||
- name: Add wasm target
|
- name: Install python
|
||||||
run: rustup target add wasm32-unknown-unknown
|
if: runner.os == 'macOS'
|
||||||
- name: Install ucd-generate
|
run: brew install --force-bottle --overwrite python@3.11
|
||||||
run: cargo install -f ucd-generate
|
|
||||||
- name: Remove obsolete llvm (Linux)
|
|
||||||
run: sudo apt purge llvm* clang*
|
|
||||||
- uses: lyricwulf/abc@v1
|
- uses: lyricwulf/abc@v1
|
||||||
with:
|
with:
|
||||||
linux: llvm-15 llvm-15-dev clang-15 nasm ninja-build gcc-arm-linux-gnueabi g++-arm-linux-gnueabi gcc-aarch64-linux-gnu g++-aarch64-linux-gnu gcc-mipsel-linux-gnu g++-mipsel-linux-gnu gcc-powerpc-linux-gnu g++-powerpc-linux-gnu libc6-dev-i386-cross libc6-dev libc6-dev-i386 lib32gcc-11-dev lib32stdc++-11-dev libgtk-3-dev pax-utils libz3-dev
|
# todo: remove afl++-clang when nyx support samcov_pcguard
|
||||||
- name: Set clang version
|
linux: llvm llvm-dev clang nasm ninja-build gcc-arm-linux-gnueabi g++-arm-linux-gnueabi libgtk-3-dev afl++-clang pax-utils
|
||||||
run: sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-15 100
|
|
||||||
- name: Set clang++ version
|
|
||||||
run: sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-15 100
|
|
||||||
- name: pip install
|
|
||||||
run: python3 -m pip install msgpack jinja2 find_libpython
|
|
||||||
# Note that nproc needs to have coreutils installed on macOS, so the order of CI commands matters.
|
|
||||||
- name: enable mult-thread for `make`
|
|
||||||
run: export MAKEFLAGS="-j$(expr $(nproc) \+ 1)"
|
|
||||||
- name: install cargo-make
|
|
||||||
uses: baptiste0928/cargo-install@v1.3.0
|
|
||||||
with:
|
|
||||||
crate: cargo-make
|
|
||||||
- name: install wasm-pack
|
|
||||||
uses: baptiste0928/cargo-install@v1.3.0
|
|
||||||
with:
|
|
||||||
crate: wasm-pack
|
|
||||||
- name: install chrome
|
|
||||||
uses: browser-actions/setup-chrome@v1
|
|
||||||
with:
|
|
||||||
chrome-version: stable
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
submodules: true # recursively checkout submodules
|
|
||||||
fetch-depth: 0 # to diff with origin/main
|
|
||||||
- uses: Swatinem/rust-cache@v2
|
|
||||||
- name: Symlink Headers
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
# We can't install gcc-multilib which would usually do this for us due to collisions with other packages
|
|
||||||
run: sudo ln -s /usr/include/asm-generic /usr/include/asm
|
|
||||||
- name: Build and run example fuzzers (Linux)
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: RUN_ON_CI=1 LLVM_CONFIG=llvm-config-15 ./scripts/test_all_fuzzers.sh
|
|
||||||
|
|
||||||
qemu_fuzzers:
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
os: [ubuntu-latest]
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
steps:
|
|
||||||
- uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
profile: minimal
|
|
||||||
toolchain: stable
|
|
||||||
- name: Free Disk Space (Ubuntu)
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
uses: jlumbroso/free-disk-space@main
|
|
||||||
with:
|
|
||||||
# this might remove tools that are actually needed,
|
|
||||||
# if set to "true" but frees about 6 GB
|
|
||||||
tool-cache: false
|
|
||||||
|
|
||||||
# all of these default to true, but feel free to set to
|
|
||||||
# "false" if necessary for your workflow
|
|
||||||
android: true
|
|
||||||
dotnet: true
|
|
||||||
haskell: true
|
|
||||||
large-packages: false
|
|
||||||
docker-images: true
|
|
||||||
swap-storage: true
|
|
||||||
- name: Add nightly rustfmt and clippy
|
|
||||||
run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade
|
|
||||||
- name: Add no_std toolchain
|
|
||||||
run: rustup toolchain install nightly-x86_64-unknown-linux-gnu ; rustup component add rust-src --toolchain nightly-x86_64-unknown-linux-gnu
|
|
||||||
- name: Add wasm target
|
|
||||||
run: rustup target add wasm32-unknown-unknown
|
|
||||||
- name: Install ucd-generate
|
|
||||||
run: cargo install -f ucd-generate
|
|
||||||
- name: Remove obsolete llvm (Linux)
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: sudo apt purge llvm* clang*
|
|
||||||
- uses: lyricwulf/abc@v1
|
|
||||||
with:
|
|
||||||
linux: llvm-15 llvm-15-dev clang-15 nasm ninja-build gcc-arm-linux-gnueabi g++-arm-linux-gnueabi gcc-aarch64-linux-gnu g++-aarch64-linux-gnu gcc-mipsel-linux-gnu g++-mipsel-linux-gnu gcc-powerpc-linux-gnu g++-powerpc-linux-gnu libc6-dev-i386-cross libc6-dev libc6-dev-i386 lib32gcc-11-dev lib32stdc++-11-dev libgtk-3-dev pax-utils libz3-dev
|
|
||||||
# update bash for macos to support `declare -A` command`
|
# update bash for macos to support `declare -A` command`
|
||||||
macos: llvm@15 libpng nasm coreutils z3 bash wget
|
macos: llvm libpng nasm coreutils z3 bash
|
||||||
- name: Set clang version
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-15 100
|
|
||||||
- name: Set clang++ version
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-15 100
|
|
||||||
- name: pip install
|
- name: pip install
|
||||||
run: python3 -m pip install msgpack jinja2 find_libpython
|
run: python3 -m pip install msgpack jinja2
|
||||||
# Note that nproc needs to have coreutils installed on macOS, so the order of CI commands matters.
|
# Note that nproc needs to have coreutils installed on macOS, so the order of CI commands matters.
|
||||||
- name: enable mult-thread for `make`
|
- name: enable mult-thread for `make`
|
||||||
run: export MAKEFLAGS="-j$(expr $(nproc) \+ 1)"
|
run: export MAKEFLAGS="-j$(expr $(nproc) \+ 1)"
|
||||||
@ -317,27 +176,16 @@ jobs:
|
|||||||
uses: baptiste0928/cargo-install@v1.3.0
|
uses: baptiste0928/cargo-install@v1.3.0
|
||||||
with:
|
with:
|
||||||
crate: cargo-make
|
crate: cargo-make
|
||||||
- name: install wasm-pack
|
|
||||||
uses: baptiste0928/cargo-install@v1.3.0
|
|
||||||
with:
|
|
||||||
crate: wasm-pack
|
|
||||||
- name: install chrome
|
|
||||||
uses: browser-actions/setup-chrome@v1
|
|
||||||
with:
|
|
||||||
chrome-version: stable
|
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
submodules: true # recursively checkout submodules
|
submodules: true # recursively checkout submodules
|
||||||
fetch-depth: 0 # to diff with origin/main
|
|
||||||
- uses: Swatinem/rust-cache@v2
|
- uses: Swatinem/rust-cache@v2
|
||||||
- name: Symlink Headers
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
# We can't install gcc-multilib which would usually do this for us due to collisions with other packages
|
|
||||||
run: sudo ln -s /usr/include/asm-generic /usr/include/asm
|
|
||||||
- name: Build and run example fuzzers (Linux)
|
- name: Build and run example fuzzers (Linux)
|
||||||
if: runner.os == 'Linux'
|
if: runner.os == 'Linux'
|
||||||
run: RUN_ON_CI=1 RUN_QEMU_FUZZER=1 LLVM_CONFIG=llvm-config-15 ./scripts/test_all_fuzzers.sh
|
run: ./scripts/test_all_fuzzers.sh
|
||||||
|
- name: Build and run example fuzzers (macOS)
|
||||||
|
if: runner.os == 'macOS' # use bash v4
|
||||||
|
run: /usr/local/bin/bash ./scripts/test_all_fuzzers.sh
|
||||||
|
|
||||||
nostd-build:
|
nostd-build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@ -360,8 +208,6 @@ jobs:
|
|||||||
run: cd ./libafl && cargo test --no-default-features
|
run: cd ./libafl && cargo test --no-default-features
|
||||||
- name: libafl armv6m-none-eabi (32 bit no_std) clippy
|
- name: libafl armv6m-none-eabi (32 bit no_std) clippy
|
||||||
run: cd ./libafl && cargo clippy --target thumbv6m-none-eabi --no-default-features
|
run: cd ./libafl && cargo clippy --target thumbv6m-none-eabi --no-default-features
|
||||||
- name: Build no_std no_alloc bolts
|
|
||||||
run: cd ./libafl_bolts && cargo +nightly build -Zbuild-std=core --target aarch64-unknown-none --no-default-features -v --release && cd ../
|
|
||||||
|
|
||||||
build-docker:
|
build-docker:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@ -392,16 +238,10 @@ jobs:
|
|||||||
- name: install cargo-make
|
- name: install cargo-make
|
||||||
run: cargo install --force cargo-make
|
run: cargo install --force cargo-make
|
||||||
- uses: ilammy/msvc-dev-cmd@v1
|
- uses: ilammy/msvc-dev-cmd@v1
|
||||||
- name: install cxx bridge
|
|
||||||
run: cargo install cxxbridge-cmd
|
|
||||||
- name: Build fuzzers/libfuzzer_stb_image
|
|
||||||
run: cd fuzzers/libfuzzer_stb_image && cargo build --release
|
|
||||||
- name: Build fuzzers/frida_libpng
|
- name: Build fuzzers/frida_libpng
|
||||||
run: cd fuzzers/frida_libpng/ && cargo make test
|
run: cd fuzzers/frida_libpng/ && cargo make test
|
||||||
- name: Build fuzzers/frida_gdiplus
|
- name: Build fuzzers/frida_gdiplus
|
||||||
run: cd fuzzers/frida_gdiplus/ && cargo make test
|
run: cd fuzzers/frida_gdiplus/ && cargo make test
|
||||||
- name: Build fuzzers/tinyinst_simple
|
|
||||||
run: cd fuzzers/tinyinst_simple/ && cargo make test
|
|
||||||
|
|
||||||
macos:
|
macos:
|
||||||
runs-on: macOS-latest
|
runs-on: macOS-latest
|
||||||
@ -412,12 +252,8 @@ jobs:
|
|||||||
toolchain: stable
|
toolchain: stable
|
||||||
- name: Add nightly rustfmt and clippy
|
- name: Add nightly rustfmt and clippy
|
||||||
run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade
|
run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade
|
||||||
- name: Install ucd-generate
|
|
||||||
run: cargo install -f ucd-generate
|
|
||||||
- name: Install deps
|
- name: Install deps
|
||||||
run: brew install z3 gtk+3
|
run: brew install z3 gtk+3
|
||||||
- name: Install cxxbridge
|
|
||||||
run: cargo install cxxbridge-cmd
|
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: Swatinem/rust-cache@v2
|
- uses: Swatinem/rust-cache@v2
|
||||||
- name: MacOS Build
|
- name: MacOS Build
|
||||||
@ -438,7 +274,7 @@ jobs:
|
|||||||
toolchain: stable
|
toolchain: stable
|
||||||
- uses: nttld/setup-ndk@v1
|
- uses: nttld/setup-ndk@v1
|
||||||
with:
|
with:
|
||||||
ndk-version: r25b
|
ndk-version: r21e
|
||||||
- name: install ios
|
- name: install ios
|
||||||
run: rustup target add aarch64-apple-ios
|
run: rustup target add aarch64-apple-ios
|
||||||
- name: install android
|
- name: install android
|
||||||
@ -448,7 +284,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: Swatinem/rust-cache@v2
|
- uses: Swatinem/rust-cache@v2
|
||||||
- name: Build iOS
|
- name: Build iOS
|
||||||
run: cargo build --target aarch64-apple-ios && cd libafl_frida && cargo build --target aarch64-apple-ios && cd ..
|
run: cargo build --target aarch64-apple-ios
|
||||||
- name: Build Android
|
- name: Build Android
|
||||||
run: cargo ndk -t arm64-v8a build --release
|
run: cargo ndk -t arm64-v8a build --release
|
||||||
#run: cargo build --target aarch64-linux-android
|
#run: cargo build --target aarch64-linux-android
|
||||||
@ -462,29 +298,28 @@ jobs:
|
|||||||
# run: C:\Rust\.cargo\bin\cargo.exe test --verbose
|
# run: C:\Rust\.cargo\bin\cargo.exe test --verbose
|
||||||
|
|
||||||
freebsd:
|
freebsd:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: macos-12
|
||||||
name: Simple build in FreeBSD
|
name: Simple build in FreeBSD
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Test in FreeBSD
|
- name: Test in FreeBSD
|
||||||
id: test
|
id: test
|
||||||
uses: vmactions/freebsd-vm@v1
|
uses: vmactions/freebsd-vm@v0
|
||||||
with:
|
with:
|
||||||
usesh: true
|
usesh: true
|
||||||
sync: rsync
|
sync: rsync
|
||||||
copyback: false
|
copyback: false
|
||||||
mem: 2048
|
mem: 2048
|
||||||
release: 13.2
|
release: 13.1
|
||||||
prepare: |
|
prepare: |
|
||||||
pkg install -y curl bash sudo llvm16
|
pkg install -y curl bash sudo llvm14
|
||||||
curl https://sh.rustup.rs -sSf | sh -s -- -y
|
curl https://sh.rustup.rs -sSf | sh -s -- -y
|
||||||
|
|
||||||
run: |
|
run: |
|
||||||
freebsd-version
|
freebsd-version
|
||||||
. "$HOME/.cargo/env"
|
. "$HOME/.cargo/env"
|
||||||
rustup toolchain install nightly
|
rustup toolchain install nightly
|
||||||
cargo install -f ucd-generate
|
export LLVM_CONFIG=/usr/local/bin/llvm-config14
|
||||||
export LLVM_CONFIG=/usr/local/bin/llvm-config16
|
|
||||||
pwd
|
pwd
|
||||||
ls -lah
|
ls -lah
|
||||||
echo "local/bin"
|
echo "local/bin"
|
||||||
|
12
.gitignore
vendored
12
.gitignore
vendored
@ -21,8 +21,6 @@ vendor
|
|||||||
*.obj
|
*.obj
|
||||||
|
|
||||||
.cur_input
|
.cur_input
|
||||||
.cur_input_*
|
|
||||||
cur_input
|
|
||||||
.venv
|
.venv
|
||||||
|
|
||||||
crashes
|
crashes
|
||||||
@ -34,8 +32,6 @@ perf.data.old
|
|||||||
.vscode
|
.vscode
|
||||||
test.dict
|
test.dict
|
||||||
|
|
||||||
.idea/
|
|
||||||
|
|
||||||
# Ignore all built fuzzers
|
# Ignore all built fuzzers
|
||||||
fuzzer_*
|
fuzzer_*
|
||||||
AFLplusplus
|
AFLplusplus
|
||||||
@ -50,7 +46,6 @@ a
|
|||||||
forkserver_test
|
forkserver_test
|
||||||
__pycache__
|
__pycache__
|
||||||
*.lafl_lock
|
*.lafl_lock
|
||||||
*.metadata
|
|
||||||
|
|
||||||
*atomic_file_testfile*
|
*atomic_file_testfile*
|
||||||
**/libxml2
|
**/libxml2
|
||||||
@ -59,10 +54,3 @@ __pycache__
|
|||||||
|
|
||||||
libafl_nyx/QEMU-Nyx
|
libafl_nyx/QEMU-Nyx
|
||||||
libafl_nyx/packer
|
libafl_nyx/packer
|
||||||
|
|
||||||
.z3-trace
|
|
||||||
|
|
||||||
# No gdb history
|
|
||||||
.gdb_history
|
|
||||||
# No llvm IR
|
|
||||||
*.ll
|
|
||||||
|
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
[submodule "libafl_concolic/symcc_runtime/symcc"]
|
||||||
|
path = libafl_concolic/symcc_runtime/symcc
|
||||||
|
url = https://github.com/AFLplusplus/symcc.git
|
34
Cargo.toml
34
Cargo.toml
@ -1,48 +1,42 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "2"
|
|
||||||
members = [
|
members = [
|
||||||
"libafl",
|
"libafl",
|
||||||
"libafl_bolts",
|
"libafl_derive",
|
||||||
"libafl_cc",
|
"libafl_cc",
|
||||||
|
"libafl_targets",
|
||||||
|
"libafl_frida",
|
||||||
|
"libafl_qemu",
|
||||||
|
"libafl_tinyinst",
|
||||||
|
"libafl_sugar",
|
||||||
|
"libafl_nyx",
|
||||||
"libafl_concolic/symcc_runtime",
|
"libafl_concolic/symcc_runtime",
|
||||||
"libafl_concolic/symcc_libafl",
|
"libafl_concolic/symcc_libafl",
|
||||||
"libafl_concolic/test/dump_constraints",
|
"libafl_concolic/test/dump_constraints",
|
||||||
"libafl_concolic/test/runtime_test",
|
"libafl_concolic/test/runtime_test",
|
||||||
"libafl_derive",
|
|
||||||
"libafl_frida",
|
|
||||||
"libafl_libfuzzer",
|
|
||||||
"libafl_nyx",
|
|
||||||
"libafl_qemu",
|
|
||||||
"libafl_sugar",
|
|
||||||
"libafl_targets",
|
|
||||||
"libafl_tinyinst",
|
|
||||||
"utils/build_and_test_fuzzers",
|
|
||||||
"utils/deexit",
|
"utils/deexit",
|
||||||
"utils/libafl_benches",
|
|
||||||
"utils/gramatron/construct_automata",
|
"utils/gramatron/construct_automata",
|
||||||
|
"utils/libafl_benches",
|
||||||
]
|
]
|
||||||
default-members = [
|
default-members = [
|
||||||
"libafl",
|
"libafl",
|
||||||
"libafl_bolts",
|
|
||||||
"libafl_cc",
|
|
||||||
"libafl_derive",
|
"libafl_derive",
|
||||||
|
"libafl_cc",
|
||||||
"libafl_targets",
|
"libafl_targets",
|
||||||
]
|
]
|
||||||
exclude = [
|
exclude = [
|
||||||
"bindings",
|
|
||||||
"fuzzers",
|
"fuzzers",
|
||||||
"libafl_qemu/libafl_qemu_build",
|
"bindings",
|
||||||
"libafl_qemu/libafl_qemu_sys",
|
|
||||||
"utils/noaslr",
|
|
||||||
"utils/gdb_qemu",
|
|
||||||
"scripts",
|
"scripts",
|
||||||
|
"libafl_qemu/libafl_qemu_build",
|
||||||
|
"libafl_qemu/libafl_qemu_sys"
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.11.2"
|
version = "0.8.2"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
lto = true
|
lto = true
|
||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
opt-level = 3
|
opt-level = 3
|
||||||
debug = true
|
debug = true
|
||||||
|
|
||||||
|
23
Dockerfile
23
Dockerfile
@ -1,5 +1,5 @@
|
|||||||
# syntax=docker/dockerfile:1.2
|
# syntax=docker/dockerfile:1.2
|
||||||
FROM rust:1.73.0 AS libafl
|
FROM rust:bullseye AS libafl
|
||||||
LABEL "maintainer"="afl++ team <afl@aflplus.plus>"
|
LABEL "maintainer"="afl++ team <afl@aflplus.plus>"
|
||||||
LABEL "about"="LibAFL Docker image"
|
LABEL "about"="LibAFL Docker image"
|
||||||
|
|
||||||
@ -17,11 +17,9 @@ RUN sh -c 'echo set encoding=utf-8 > /root/.vimrc' \
|
|||||||
echo "[build]\nrustc-wrapper = \"${RUSTC_WRAPPER}\"" >> ~/.cargo/config
|
echo "[build]\nrustc-wrapper = \"${RUSTC_WRAPPER}\"" >> ~/.cargo/config
|
||||||
|
|
||||||
RUN rustup component add rustfmt clippy
|
RUN rustup component add rustfmt clippy
|
||||||
RUN rustup default nightly
|
|
||||||
|
|
||||||
# Install clang 11, common build tools
|
# Install clang 11, common build tools
|
||||||
RUN apt update && apt install -y build-essential gdb git wget python3-venv ninja-build lsb-release software-properties-common gnupg
|
RUN apt update && apt install -y build-essential gdb git wget clang clang-tools libc++-11-dev libc++abi-11-dev llvm
|
||||||
RUN wget https://apt.llvm.org/llvm.sh && chmod +x llvm.sh && ./llvm.sh 15
|
|
||||||
|
|
||||||
# Copy a dummy.rs and Cargo.toml first, so that dependencies are cached
|
# Copy a dummy.rs and Cargo.toml first, so that dependencies are cached
|
||||||
WORKDIR /libafl
|
WORKDIR /libafl
|
||||||
@ -30,13 +28,10 @@ COPY Cargo.toml README.md ./
|
|||||||
COPY libafl_derive/Cargo.toml libafl_derive/Cargo.toml
|
COPY libafl_derive/Cargo.toml libafl_derive/Cargo.toml
|
||||||
COPY scripts/dummy.rs libafl_derive/src/lib.rs
|
COPY scripts/dummy.rs libafl_derive/src/lib.rs
|
||||||
|
|
||||||
COPY libafl/Cargo.toml libafl/build.rs libafl/README.md libafl/
|
COPY libafl/Cargo.toml libafl/build.rs libafl/
|
||||||
|
COPY libafl/examples libafl/examples
|
||||||
COPY scripts/dummy.rs libafl/src/lib.rs
|
COPY scripts/dummy.rs libafl/src/lib.rs
|
||||||
|
|
||||||
COPY libafl_bolts/Cargo.toml libafl_bolts/build.rs libafl_bolts/README.md libafl_bolts/
|
|
||||||
COPY libafl_bolts/examples libafl_bolts/examples
|
|
||||||
COPY scripts/dummy.rs libafl_bolts/src/lib.rs
|
|
||||||
|
|
||||||
COPY libafl_frida/Cargo.toml libafl_frida/build.rs libafl_frida/
|
COPY libafl_frida/Cargo.toml libafl_frida/build.rs libafl_frida/
|
||||||
COPY scripts/dummy.rs libafl_frida/src/lib.rs
|
COPY scripts/dummy.rs libafl_frida/src/lib.rs
|
||||||
COPY libafl_frida/src/gettls.c libafl_frida/src/gettls.c
|
COPY libafl_frida/src/gettls.c libafl_frida/src/gettls.c
|
||||||
@ -80,10 +75,6 @@ COPY scripts/dummy.rs libafl_nyx/src/lib.rs
|
|||||||
COPY libafl_tinyinst/Cargo.toml libafl_tinyinst/
|
COPY libafl_tinyinst/Cargo.toml libafl_tinyinst/
|
||||||
COPY scripts/dummy.rs libafl_tinyinst/src/lib.rs
|
COPY scripts/dummy.rs libafl_tinyinst/src/lib.rs
|
||||||
|
|
||||||
# avoid pulling in the runtime, as this is quite an expensive build, until later
|
|
||||||
COPY libafl_libfuzzer/Cargo.toml libafl_libfuzzer/
|
|
||||||
COPY scripts/dummy.rs libafl_libfuzzer/src/lib.rs
|
|
||||||
|
|
||||||
COPY utils utils
|
COPY utils utils
|
||||||
|
|
||||||
RUN cargo build && cargo build --release
|
RUN cargo build && cargo build --release
|
||||||
@ -104,8 +95,6 @@ COPY libafl_cc/src libafl_cc/src
|
|||||||
RUN touch libafl_cc/src/lib.rs
|
RUN touch libafl_cc/src/lib.rs
|
||||||
COPY libafl_derive/src libafl_derive/src
|
COPY libafl_derive/src libafl_derive/src
|
||||||
RUN touch libafl_derive/src/lib.rs
|
RUN touch libafl_derive/src/lib.rs
|
||||||
COPY libafl_bolts/src libafl_bolts/src
|
|
||||||
RUN touch libafl_bolts/src/lib.rs
|
|
||||||
COPY libafl/src libafl/src
|
COPY libafl/src libafl/src
|
||||||
RUN touch libafl/src/lib.rs
|
RUN touch libafl/src/lib.rs
|
||||||
COPY libafl_targets/src libafl_targets/src
|
COPY libafl_targets/src libafl_targets/src
|
||||||
@ -123,10 +112,6 @@ COPY libafl_concolic/symcc_runtime libafl_concolic/symcc_runtime
|
|||||||
COPY libafl_concolic/test libafl_concolic/test
|
COPY libafl_concolic/test libafl_concolic/test
|
||||||
COPY libafl_nyx/src libafl_nyx/src
|
COPY libafl_nyx/src libafl_nyx/src
|
||||||
RUN touch libafl_nyx/src/lib.rs
|
RUN touch libafl_nyx/src/lib.rs
|
||||||
COPY libafl_libfuzzer/src libafl_libfuzzer/src
|
|
||||||
COPY libafl_libfuzzer/libafl_libfuzzer_runtime libafl_libfuzzer/libafl_libfuzzer_runtime
|
|
||||||
COPY libafl_libfuzzer/build.rs libafl_libfuzzer/build.rs
|
|
||||||
RUN touch libafl_libfuzzer/src/lib.rs
|
|
||||||
RUN cargo build && cargo build --release
|
RUN cargo build && cargo build --release
|
||||||
|
|
||||||
# Copy fuzzers over
|
# Copy fuzzers over
|
||||||
|
25
README.md
25
README.md
@ -1,6 +1,6 @@
|
|||||||
# LibAFL, the fuzzer library.
|
# LibAFL, the fuzzer library.
|
||||||
|
|
||||||
<img align="right" src="https://raw.githubusercontent.com/AFLplusplus/Website/main/static/libafl_logo.svg" alt="LibAFL logo" width="250" heigh="250">
|
<img align="right" src="https://github.com/AFLplusplus/Website/raw/master/static/logo_256x256.png" alt="AFL++ Logo">
|
||||||
|
|
||||||
Advanced Fuzzing Library - Slot your own fuzzers together and extend their features using Rust.
|
Advanced Fuzzing Library - Slot your own fuzzers together and extend their features using Rust.
|
||||||
|
|
||||||
@ -10,7 +10,6 @@ LibAFL is written and maintained by
|
|||||||
* [Dominik Maier](https://twitter.com/domenuk) <dominik@aflplus.plus>
|
* [Dominik Maier](https://twitter.com/domenuk) <dominik@aflplus.plus>
|
||||||
* [s1341](https://twitter.com/srubenst1341) <github@shmarya.net>
|
* [s1341](https://twitter.com/srubenst1341) <github@shmarya.net>
|
||||||
* [Dongjia Zhang](https://github.com/tokatoka) <toka@aflplus.plus>
|
* [Dongjia Zhang](https://github.com/tokatoka) <toka@aflplus.plus>
|
||||||
* [Addison Crump](https://github.com/addisoncrump) <me@addisoncrump.info>
|
|
||||||
|
|
||||||
## Why LibAFL?
|
## Why LibAFL?
|
||||||
|
|
||||||
@ -34,7 +33,7 @@ LibAFL offers integrations with popular instrumentation frameworks. At the momen
|
|||||||
|
|
||||||
+ SanitizerCoverage, in [libafl_targets](./libafl_targets)
|
+ SanitizerCoverage, in [libafl_targets](./libafl_targets)
|
||||||
+ Frida, in [libafl_frida](./libafl_frida)
|
+ Frida, in [libafl_frida](./libafl_frida)
|
||||||
+ QEMU user-mode and system mode, including hooks for emulation, in [libafl_qemu](./libafl_qemu)
|
+ QEMU user-mode, in [libafl_qemu](./libafl_qemu)
|
||||||
+ TinyInst, in [libafl_tinyinst](./libafl_tinyinst) by [elbiazo](https://github.com/elbiazo)
|
+ TinyInst, in [libafl_tinyinst](./libafl_tinyinst) by [elbiazo](https://github.com/elbiazo)
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
@ -45,36 +44,36 @@ We highly recommend *not* to use e.g. your Linux distribition package as this is
|
|||||||
Rust directly, instructions can be found [here](https://www.rust-lang.org/tools/install).
|
Rust directly, instructions can be found [here](https://www.rust-lang.org/tools/install).
|
||||||
|
|
||||||
- LLVM tools
|
- LLVM tools
|
||||||
The LLVM tools (including clang, clang++) are needed (newer than LLVM 11.0.0 up to LLVM 17.0.0)
|
The LLVM tools are needed (newer than LLVM 11.0.0 but older than LLVM 15.0.0)
|
||||||
|
|
||||||
- Cargo-make
|
- Cargo-make
|
||||||
We use cargo-make to build the fuzzers in `fuzzers/` directory. You can install it with
|
We use cargo-make to build the fuzzers in `fuzzers/` directory. You can install it with
|
||||||
|
|
||||||
```sh
|
```
|
||||||
cargo install cargo-make
|
cargo install cargo-make
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Clone the LibAFL repository with
|
2. Clone the LibAFL repository with
|
||||||
|
|
||||||
```sh
|
```
|
||||||
git clone https://github.com/AFLplusplus/LibAFL
|
git clone https://github.com/AFLplusplus/LibAFL
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Build the library using
|
3. Build the library using
|
||||||
|
|
||||||
```sh
|
```
|
||||||
cargo build --release
|
cargo build --release
|
||||||
```
|
```
|
||||||
|
|
||||||
4. Build the API documentation with
|
4. Build the API documentation with
|
||||||
|
|
||||||
```sh
|
```
|
||||||
cargo doc
|
cargo doc
|
||||||
```
|
```
|
||||||
|
|
||||||
5. Browse the LibAFL book (WIP!) with (requires [mdbook](https://rust-lang.github.io/mdBook/index.html))
|
5. Browse the LibAFL book (WIP!) with (requires [mdbook](https://github.com/rust-lang/mdBook))
|
||||||
|
|
||||||
```sh
|
```
|
||||||
cd docs && mdbook serve
|
cd docs && mdbook serve
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -82,11 +81,9 @@ We collect all example fuzzers in [`./fuzzers`](./fuzzers/).
|
|||||||
Be sure to read their documentation (and source), this is *the natural way to get started!*
|
Be sure to read their documentation (and source), this is *the natural way to get started!*
|
||||||
|
|
||||||
You can run each example fuzzer with
|
You can run each example fuzzer with
|
||||||
|
```
|
||||||
```sh
|
|
||||||
cargo make run
|
cargo make run
|
||||||
```
|
```
|
||||||
|
|
||||||
as long as the fuzzer directory has `Makefile.toml` file.
|
as long as the fuzzer directory has `Makefile.toml` file.
|
||||||
|
|
||||||
The best-tested fuzzer is [`./fuzzers/libfuzzer_libpng`](./fuzzers/libfuzzer_libpng), a multicore libfuzzer-like fuzzer using LibAFL for a libpng harness.
|
The best-tested fuzzer is [`./fuzzers/libfuzzer_libpng`](./fuzzers/libfuzzer_libpng), a multicore libfuzzer-like fuzzer using LibAFL for a libpng harness.
|
||||||
@ -109,8 +106,6 @@ The best-tested fuzzer is [`./fuzzers/libfuzzer_libpng`](./fuzzers/libfuzzer_lib
|
|||||||
|
|
||||||
+ Blogpost on binary-only fuzzing lib libaf_qemu, [Hacking TMNF - Fuzzing the game server](https://blog.bricked.tech/posts/tmnf/part1/), by [RickdeJager](https://github.com/RickdeJager).
|
+ Blogpost on binary-only fuzzing lib libaf_qemu, [Hacking TMNF - Fuzzing the game server](https://blog.bricked.tech/posts/tmnf/part1/), by [RickdeJager](https://github.com/RickdeJager).
|
||||||
|
|
||||||
+ [A LibAFL Introductory Workshop](https://www.atredis.com/blog/2023/12/4/a-libafl-introductory-workshop), by [Jordan Whitehead](https://github.com/jordan9001)
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
For bugs, feel free to open issues or contact us directly. Thank you for your support. <3
|
For bugs, feel free to open issues or contact us directly. Thank you for your support. <3
|
||||||
|
17
TROPHIES.md
17
TROPHIES.md
@ -1,17 +0,0 @@
|
|||||||
# Bugs found by `libafl` and `libafl_libfuzzer`
|
|
||||||
|
|
||||||
* pdf-rs
|
|
||||||
* <https://github.com/pdf-rs/pdf/issues/183>
|
|
||||||
* <https://github.com/pdf-rs/pdf/issues/184>
|
|
||||||
* <https://github.com/pdf-rs/pdf/issues/185>
|
|
||||||
* <https://github.com/pdf-rs/pdf/issues/186>
|
|
||||||
* <https://github.com/pdf-rs/pdf/issues/187>
|
|
||||||
* <https://github.com/pdf-rs/pdf/issues/189>
|
|
||||||
* nu-shell
|
|
||||||
* https://github.com/nushell/nushell/issues/10365
|
|
||||||
* https://github.com/nushell/nushell/issues/9417
|
|
||||||
* exrs
|
|
||||||
* https://github.com/johannesvollmer/exrs/pull/221
|
|
||||||
* pcre2
|
|
||||||
* https://github.com/PCRE2Project/pcre2/issues/275
|
|
||||||
|
|
1
bindings/pylibafl/.gitignore
vendored
1
bindings/pylibafl/.gitignore
vendored
@ -1 +0,0 @@
|
|||||||
dist/
|
|
@ -1,15 +1,13 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "pylibafl"
|
name = "pylibafl"
|
||||||
version = "0.11.2"
|
version = "0.8.2"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
pyo3 = { version = "0.18.3", features = ["extension-module"] }
|
pyo3 = { version = "0.17", features = ["extension-module"] }
|
||||||
pyo3-log = "0.8.1"
|
libafl_qemu = { path = "../../libafl_qemu", version = "0.8.2", features = ["python"] }
|
||||||
libafl_qemu = { path = "../../libafl_qemu", version = "0.11.2", features = ["python"] }
|
libafl_sugar = { path = "../../libafl_sugar", version = "0.8.2", features = ["python"] }
|
||||||
libafl_sugar = { path = "../../libafl_sugar", version = "0.11.2", features = ["python"] }
|
libafl = { path = "../../libafl", version = "0.8.2", features = ["python"] }
|
||||||
libafl = { path = "../../libafl", version = "0.11.2", features = ["python"] }
|
|
||||||
libafl_bolts = { path = "../../libafl_bolts", version = "0.11.2", features = ["python"] }
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
pyo3-build-config = { version = "0.17" }
|
pyo3-build-config = { version = "0.17" }
|
||||||
|
@ -1,26 +0,0 @@
|
|||||||
[build-system]
|
|
||||||
requires = ["maturin[patchelf]>=0.14.10,<0.15"]
|
|
||||||
build-backend = "maturin"
|
|
||||||
|
|
||||||
[project]
|
|
||||||
name = "PyLibAFL"
|
|
||||||
version = "0.10.1"
|
|
||||||
description = "Advanced Fuzzing Library for Python"
|
|
||||||
readme = "README.md"
|
|
||||||
requires-python = ">=3.8"
|
|
||||||
license = {text = "Apache-2.0"}
|
|
||||||
classifiers = [
|
|
||||||
"License :: OSI Approved :: Apache Software License",
|
|
||||||
"License :: OSI Approved :: MIT License",
|
|
||||||
"Programming Language :: Rust",
|
|
||||||
"Topic :: Security",
|
|
||||||
]
|
|
||||||
|
|
||||||
[project.urls]
|
|
||||||
repository = "https://github.com/AFLplusplus/LibAFL.git"
|
|
||||||
|
|
||||||
[tool.maturin]
|
|
||||||
bindings = "pylibafl"
|
|
||||||
manifest-path = "Cargo.toml"
|
|
||||||
python-source = "python"
|
|
||||||
all-features = true
|
|
@ -1,5 +1,4 @@
|
|||||||
use libafl;
|
use libafl;
|
||||||
use libafl_bolts;
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
use libafl_qemu;
|
use libafl_qemu;
|
||||||
use libafl_sugar;
|
use libafl_sugar;
|
||||||
@ -27,7 +26,7 @@ class BaseFeedback:
|
|||||||
pass
|
pass
|
||||||
def is_interesting(self, state, mgr, input, observers, exit_kind) -> bool:
|
def is_interesting(self, state, mgr, input, observers, exit_kind) -> bool:
|
||||||
return False
|
return False
|
||||||
def append_metadata(self, state, observers, testcase):
|
def append_metadata(self, state, testcase):
|
||||||
pass
|
pass
|
||||||
def discard_metadata(self, state, input):
|
def discard_metadata(self, state, input):
|
||||||
pass
|
pass
|
||||||
@ -85,27 +84,23 @@ def feedback_or_fast(a, b):
|
|||||||
#[pymodule]
|
#[pymodule]
|
||||||
#[pyo3(name = "pylibafl")]
|
#[pyo3(name = "pylibafl")]
|
||||||
pub fn python_module(py: Python, m: &PyModule) -> PyResult<()> {
|
pub fn python_module(py: Python, m: &PyModule) -> PyResult<()> {
|
||||||
pyo3_log::init();
|
|
||||||
|
|
||||||
let modules = py.import("sys")?.getattr("modules")?;
|
let modules = py.import("sys")?.getattr("modules")?;
|
||||||
|
|
||||||
let sugar_module = PyModule::new(py, "sugar")?;
|
let sugar_module = PyModule::new(py, "sugar")?;
|
||||||
libafl_sugar::python_module(py, sugar_module)?;
|
libafl_sugar::python_module(py, sugar_module)?;
|
||||||
m.add_submodule(sugar_module)?;
|
m.add_submodule(sugar_module)?;
|
||||||
|
|
||||||
modules.set_item("pylibafl.sugar", sugar_module)?;
|
modules.set_item("pylibafl.sugar", sugar_module)?;
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
{
|
let qemu_module = PyModule::new(py, "qemu")?;
|
||||||
let qemu_module = PyModule::new(py, "qemu")?;
|
#[cfg(target_os = "linux")]
|
||||||
libafl_qemu::python_module(py, qemu_module)?;
|
libafl_qemu::python_module(py, qemu_module)?;
|
||||||
m.add_submodule(qemu_module)?;
|
#[cfg(target_os = "linux")]
|
||||||
modules.set_item("pylibafl.qemu", qemu_module)?;
|
m.add_submodule(qemu_module)?;
|
||||||
}
|
|
||||||
|
|
||||||
let bolts_module = PyModule::new(py, "libafl_bolts")?;
|
#[cfg(target_os = "linux")]
|
||||||
libafl_bolts::pybind::python_module(py, bolts_module)?;
|
modules.set_item("pylibafl.qemu", qemu_module)?;
|
||||||
m.add_submodule(bolts_module)?;
|
|
||||||
modules.set_item("pylibafl.libafl_bolts", bolts_module)?;
|
|
||||||
|
|
||||||
let libafl_module = PyModule::new(py, "libafl")?;
|
let libafl_module = PyModule::new(py, "libafl")?;
|
||||||
libafl::pybind::python_module(py, libafl_module)?;
|
libafl::pybind::python_module(py, libafl_module)?;
|
||||||
@ -119,6 +114,7 @@ pub fn python_module(py: Python, m: &PyModule) -> PyResult<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
m.add_submodule(libafl_module)?;
|
m.add_submodule(libafl_module)?;
|
||||||
|
|
||||||
modules.set_item("pylibafl.libafl", libafl_module)?;
|
modules.set_item("pylibafl.libafl", libafl_module)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -1,8 +1,5 @@
|
|||||||
from pylibafl.libafl import *
|
from pylibafl.libafl import *
|
||||||
import ctypes
|
import ctypes
|
||||||
import platform
|
|
||||||
|
|
||||||
MAP_SIZE = 4096
|
|
||||||
|
|
||||||
|
|
||||||
class FooObserver(BaseObserver):
|
class FooObserver(BaseObserver):
|
||||||
@ -36,16 +33,11 @@ class FooExecutor(BaseExecutor):
|
|||||||
return (self.h)(input)
|
return (self.h)(input)
|
||||||
|
|
||||||
|
|
||||||
if platform.system() == "Darwin":
|
libc = ctypes.cdll.LoadLibrary("libc.so.6")
|
||||||
libc = ctypes.cdll.LoadLibrary("libc.dylib")
|
|
||||||
else:
|
|
||||||
libc = ctypes.cdll.LoadLibrary("libc.so.6")
|
|
||||||
|
|
||||||
# Get a buffer to use for our map observer
|
area_ptr = libc.calloc(1, 4096)
|
||||||
libc.calloc.restype = ctypes.c_void_p
|
|
||||||
area_ptr = libc.calloc(1, MAP_SIZE)
|
|
||||||
|
|
||||||
observer = StdMapObserverI8("mymap", area_ptr, MAP_SIZE)
|
observer = StdMapObserverI8("mymap", area_ptr, 4096)
|
||||||
|
|
||||||
m = observer.as_map_observer()
|
m = observer.as_map_observer()
|
||||||
|
|
||||||
@ -77,12 +69,7 @@ mgr = SimpleEventManager(monitor.as_monitor())
|
|||||||
|
|
||||||
|
|
||||||
def harness(buf) -> ExitKind:
|
def harness(buf) -> ExitKind:
|
||||||
"""
|
|
||||||
The harness fn that the fuzzer will execute in a loop
|
|
||||||
"""
|
|
||||||
# print(buf)
|
# print(buf)
|
||||||
|
|
||||||
# set the observer map byte from python
|
|
||||||
m[0] = 1
|
m[0] = 1
|
||||||
if len(buf) > 0 and buf[0] == ord("a"):
|
if len(buf) > 0 and buf[0] == ord("a"):
|
||||||
m[1] = 1
|
m[1] = 1
|
||||||
@ -104,6 +91,4 @@ stage_tuple_list = StagesTuple([stage.as_stage()])
|
|||||||
|
|
||||||
fuzzer.add_input(state, executor.as_executor(), mgr.as_manager(), b"\0\0")
|
fuzzer.add_input(state, executor.as_executor(), mgr.as_manager(), b"\0\0")
|
||||||
|
|
||||||
print("Starting to fuzz from python!")
|
|
||||||
|
|
||||||
fuzzer.fuzz_loop(executor.as_executor(), state, mgr.as_manager(), stage_tuple_list)
|
fuzzer.fuzz_loop(executor.as_executor(), state, mgr.as_manager(), stage_tuple_list)
|
||||||
|
@ -1,11 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
timeout 10 python3 ./test.py
|
|
||||||
export exit_code=$?
|
|
||||||
if [ $exit_code -eq 124 ]; then
|
|
||||||
# 124 = timeout happened. All good.
|
|
||||||
exit 0
|
|
||||||
else
|
|
||||||
exit $exit_code
|
|
||||||
fi
|
|
||||||
|
|
1
docs/.gitignore
vendored
1
docs/.gitignore
vendored
@ -1,2 +1 @@
|
|||||||
book
|
book
|
||||||
!listings/**/*
|
|
||||||
|
@ -1,9 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "baby_fuzzer_listing_01"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Your Name <you@example.com>"]
|
|
||||||
edition = "2018"
|
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
|
@ -1,3 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
println!("Hello, world!");
|
|
||||||
}
|
|
@ -1,21 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "baby_fuzzer_listing_02"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Your Name <you@example.com>"]
|
|
||||||
edition = "2018"
|
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
libafl = { path = "path/to/libafl/" }
|
|
||||||
libafl_bolts = { path = "path/to/libafl_bolts/" }
|
|
||||||
|
|
||||||
[profile.dev]
|
|
||||||
panic = "abort"
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
panic = "abort"
|
|
||||||
lto = true
|
|
||||||
codegen-units = 1
|
|
||||||
opt-level = 3
|
|
||||||
debug = true
|
|
@ -1,3 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
println!("Hello, world!");
|
|
||||||
}
|
|
@ -1,24 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "baby_fuzzer_listing_03"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Your Name <you@example.com>"]
|
|
||||||
edition = "2018"
|
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
libafl = { path = "path/to/libafl/" }
|
|
||||||
libafl_bolts = { path = "path/to/libafl_bolts/" }
|
|
||||||
|
|
||||||
[profile.dev]
|
|
||||||
panic = "abort"
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
panic = "abort"
|
|
||||||
lto = true
|
|
||||||
codegen-units = 1
|
|
||||||
opt-level = 3
|
|
||||||
debug = true
|
|
||||||
|
|
||||||
[features]
|
|
||||||
panic = []
|
|
@ -1,26 +0,0 @@
|
|||||||
extern crate libafl;
|
|
||||||
extern crate libafl_bolts;
|
|
||||||
use libafl::{
|
|
||||||
executors::ExitKind,
|
|
||||||
inputs::{BytesInput, HasTargetBytes},
|
|
||||||
};
|
|
||||||
use libafl_bolts::AsSlice;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut harness = |input: &BytesInput| {
|
|
||||||
let target = input.target_bytes();
|
|
||||||
let buf = target.as_slice();
|
|
||||||
if buf.len() > 0 && buf[0] == 'a' as u8 {
|
|
||||||
if buf.len() > 1 && buf[1] == 'b' as u8 {
|
|
||||||
if buf.len() > 2 && buf[2] == 'c' as u8 {
|
|
||||||
panic!("=)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ExitKind::Ok
|
|
||||||
};
|
|
||||||
// To test the panic:
|
|
||||||
let input = BytesInput::new(Vec::from("abc"));
|
|
||||||
#[cfg(feature = "panic")]
|
|
||||||
harness(&input);
|
|
||||||
}
|
|
@ -1,24 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "baby_fuzzer_listing_04"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Your Name <you@example.com>"]
|
|
||||||
edition = "2018"
|
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
libafl = { path = "path/to/libafl/" }
|
|
||||||
libafl_bolts = { path = "path/to/libafl_bolts/" }
|
|
||||||
|
|
||||||
[profile.dev]
|
|
||||||
panic = "abort"
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
panic = "abort"
|
|
||||||
lto = true
|
|
||||||
codegen-units = 1
|
|
||||||
opt-level = 3
|
|
||||||
debug = true
|
|
||||||
|
|
||||||
[features]
|
|
||||||
panic = []
|
|
@ -1,86 +0,0 @@
|
|||||||
/* ANCHOR: use */
|
|
||||||
extern crate libafl;
|
|
||||||
extern crate libafl_bolts;
|
|
||||||
|
|
||||||
use libafl::{
|
|
||||||
corpus::{InMemoryCorpus, OnDiskCorpus},
|
|
||||||
events::SimpleEventManager,
|
|
||||||
executors::{inprocess::InProcessExecutor, ExitKind},
|
|
||||||
fuzzer::StdFuzzer,
|
|
||||||
generators::RandPrintablesGenerator,
|
|
||||||
inputs::{BytesInput, HasTargetBytes},
|
|
||||||
monitors::SimpleMonitor,
|
|
||||||
schedulers::QueueScheduler,
|
|
||||||
state::StdState,
|
|
||||||
};
|
|
||||||
use libafl_bolts::{current_nanos, rands::StdRand, AsSlice};
|
|
||||||
use std::path::PathBuf;
|
|
||||||
/* ANCHOR_END: use */
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut harness = |input: &BytesInput| {
|
|
||||||
let target = input.target_bytes();
|
|
||||||
let buf = target.as_slice();
|
|
||||||
if buf.len() > 0 && buf[0] == 'a' as u8 {
|
|
||||||
if buf.len() > 1 && buf[1] == 'b' as u8 {
|
|
||||||
if buf.len() > 2 && buf[2] == 'c' as u8 {
|
|
||||||
panic!("=)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ExitKind::Ok
|
|
||||||
};
|
|
||||||
// To test the panic:
|
|
||||||
let input = BytesInput::new(Vec::from("abc"));
|
|
||||||
#[cfg(feature = "panic")]
|
|
||||||
harness(&input);
|
|
||||||
|
|
||||||
/* ANCHOR: state */
|
|
||||||
// create a State from scratch
|
|
||||||
let mut state = StdState::new(
|
|
||||||
// RNG
|
|
||||||
StdRand::with_seed(current_nanos()),
|
|
||||||
// Corpus that will be evolved, we keep it in memory for performance
|
|
||||||
InMemoryCorpus::new(),
|
|
||||||
// Corpus in which we store solutions (crashes in this example),
|
|
||||||
// on disk so the user can get them after stopping the fuzzer
|
|
||||||
OnDiskCorpus::new(PathBuf::from("./crashes")).unwrap(),
|
|
||||||
&mut (),
|
|
||||||
&mut (),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
/* ANCHOR_END: state */
|
|
||||||
|
|
||||||
/* ANCHOR: event_manager */
|
|
||||||
// The Monitor trait defines how the fuzzer stats are displayed to the user
|
|
||||||
let mon = SimpleMonitor::new(|s| println!("{s}"));
|
|
||||||
|
|
||||||
// The event manager handles the various events generated during the fuzzing loop
|
|
||||||
// such as the notification of the addition of a new item to the corpus
|
|
||||||
let mut mgr = SimpleEventManager::new(mon);
|
|
||||||
/* ANCHOR_END: event_manager */
|
|
||||||
|
|
||||||
/* ANCHOR: scheduler_fuzzer */
|
|
||||||
// A queue policy to get testcases from the corpus
|
|
||||||
let scheduler = QueueScheduler::new();
|
|
||||||
|
|
||||||
// A fuzzer with feedbacks and a corpus scheduler
|
|
||||||
let mut fuzzer = StdFuzzer::new(scheduler, (), ());
|
|
||||||
/* ANCHOR_END: scheduler_fuzzer */
|
|
||||||
|
|
||||||
/* ANCHOR: executor */
|
|
||||||
// Create the executor for an in-process function
|
|
||||||
let mut executor = InProcessExecutor::new(&mut harness, (), &mut fuzzer, &mut state, &mut mgr)
|
|
||||||
.expect("Failed to create the Executor");
|
|
||||||
/* ANCHOR_END: executor */
|
|
||||||
|
|
||||||
/* ANCHOR: generator */
|
|
||||||
// Generator of printable bytearrays of max size 32
|
|
||||||
let mut generator = RandPrintablesGenerator::new(32);
|
|
||||||
|
|
||||||
// Generate 8 initial inputs
|
|
||||||
state
|
|
||||||
.generate_initial_inputs(&mut fuzzer, &mut executor, &mut generator, &mut mgr, 8)
|
|
||||||
.expect("Failed to generate the initial corpus");
|
|
||||||
/* ANCHOR_END: generator */
|
|
||||||
}
|
|
@ -1,23 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "baby_fuzzer_listing_05"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Your Name <you@example.com>"]
|
|
||||||
edition = "2018"
|
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
libafl = { path = "path/to/libafl/" }
|
|
||||||
|
|
||||||
[profile.dev]
|
|
||||||
panic = "abort"
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
panic = "abort"
|
|
||||||
lto = true
|
|
||||||
codegen-units = 1
|
|
||||||
opt-level = 3
|
|
||||||
debug = true
|
|
||||||
|
|
||||||
[features]
|
|
||||||
panic = []
|
|
@ -1,116 +0,0 @@
|
|||||||
/* ANCHOR: use */
|
|
||||||
extern crate libafl;
|
|
||||||
extern crate libafl_bolts;
|
|
||||||
|
|
||||||
use libafl::{
|
|
||||||
corpus::{InMemoryCorpus, OnDiskCorpus},
|
|
||||||
events::SimpleEventManager,
|
|
||||||
executors::{inprocess::InProcessExecutor, ExitKind},
|
|
||||||
feedbacks::{CrashFeedback, MaxMapFeedback},
|
|
||||||
fuzzer::StdFuzzer,
|
|
||||||
generators::RandPrintablesGenerator,
|
|
||||||
inputs::{BytesInput, HasTargetBytes},
|
|
||||||
monitors::SimpleMonitor,
|
|
||||||
observers::StdMapObserver,
|
|
||||||
schedulers::QueueScheduler,
|
|
||||||
state::StdState,
|
|
||||||
};
|
|
||||||
use libafl_bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice};
|
|
||||||
use std::path::PathBuf;
|
|
||||||
/* ANCHOR_END: use */
|
|
||||||
|
|
||||||
/* ANCHOR: signals */
|
|
||||||
// Coverage map with explicit assignments due to the lack of instrumentation
|
|
||||||
static mut SIGNALS: [u8; 16] = [0; 16];
|
|
||||||
|
|
||||||
fn signals_set(idx: usize) {
|
|
||||||
unsafe { SIGNALS[idx] = 1 };
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
// The closure that we want to fuzz
|
|
||||||
let mut harness = |input: &BytesInput| {
|
|
||||||
let target = input.target_bytes();
|
|
||||||
let buf = target.as_slice();
|
|
||||||
signals_set(0); // set SIGNALS[0]
|
|
||||||
if buf.len() > 0 && buf[0] == 'a' as u8 {
|
|
||||||
signals_set(1); // set SIGNALS[1]
|
|
||||||
if buf.len() > 1 && buf[1] == 'b' as u8 {
|
|
||||||
signals_set(2); // set SIGNALS[2]
|
|
||||||
if buf.len() > 2 && buf[2] == 'c' as u8 {
|
|
||||||
panic!("=)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ExitKind::Ok
|
|
||||||
};
|
|
||||||
/* ANCHOR_END: signals */
|
|
||||||
// To test the panic:
|
|
||||||
let input = BytesInput::new(Vec::from("abc"));
|
|
||||||
#[cfg(feature = "panic")]
|
|
||||||
harness(&input);
|
|
||||||
|
|
||||||
/* ANCHOR: observer */
|
|
||||||
// Create an observation channel using the signals map
|
|
||||||
let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) };
|
|
||||||
/* ANCHOR_END: observer */
|
|
||||||
|
|
||||||
/* ANCHOR: state_with_feedback_and_objective */
|
|
||||||
// Feedback to rate the interestingness of an input
|
|
||||||
let mut feedback = MaxMapFeedback::new(&observer);
|
|
||||||
|
|
||||||
// A feedback to choose if an input is a solution or not
|
|
||||||
let mut objective = CrashFeedback::new();
|
|
||||||
|
|
||||||
// create a State from scratch
|
|
||||||
let mut state = StdState::new(
|
|
||||||
// RNG
|
|
||||||
StdRand::with_seed(current_nanos()),
|
|
||||||
// Corpus that will be evolved, we keep it in memory for performance
|
|
||||||
InMemoryCorpus::new(),
|
|
||||||
// Corpus in which we store solutions (crashes in this example),
|
|
||||||
// on disk so the user can get them after stopping the fuzzer
|
|
||||||
OnDiskCorpus::new(PathBuf::from("./crashes")).unwrap(),
|
|
||||||
&mut feedback,
|
|
||||||
&mut objective,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
/* ANCHOR_END: state_with_feedback_and_objective */
|
|
||||||
|
|
||||||
// The Monitor trait defines how the fuzzer stats are displayed to the user
|
|
||||||
let mon = SimpleMonitor::new(|s| println!("{s}"));
|
|
||||||
|
|
||||||
// The event manager handles the various events generated during the fuzzing loop
|
|
||||||
// such as the notification of the addition of a new item to the corpus
|
|
||||||
let mut mgr = SimpleEventManager::new(mon);
|
|
||||||
|
|
||||||
// A queue policy to get testcasess from the corpus
|
|
||||||
let scheduler = QueueScheduler::new();
|
|
||||||
/* ANCHOR: state_with_feedback_and_objective */
|
|
||||||
|
|
||||||
// A fuzzer with feedbacks and a corpus scheduler
|
|
||||||
let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);
|
|
||||||
/* ANCHOR_END: state_with_feedback_and_objective */
|
|
||||||
|
|
||||||
/* ANCHOR: executor_with_observer */
|
|
||||||
// Create the executor for an in-process function with just one observer
|
|
||||||
let mut executor = InProcessExecutor::new(
|
|
||||||
&mut harness,
|
|
||||||
tuple_list!(observer),
|
|
||||||
&mut fuzzer,
|
|
||||||
&mut state,
|
|
||||||
&mut mgr,
|
|
||||||
)
|
|
||||||
.expect("Failed to create the Executor");
|
|
||||||
/* ANCHOR_END: executor_with_observer */
|
|
||||||
|
|
||||||
// Generator of printable bytearrays of max size 32
|
|
||||||
let mut generator = RandPrintablesGenerator::new(32);
|
|
||||||
|
|
||||||
// Generate 8 initial inputs
|
|
||||||
state
|
|
||||||
.generate_initial_inputs(&mut fuzzer, &mut executor, &mut generator, &mut mgr, 8)
|
|
||||||
.expect("Failed to generate the initial corpus");
|
|
||||||
/* ANCHOR: signals */
|
|
||||||
}
|
|
||||||
/* ANCHOR_END: signals */
|
|
@ -1,24 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "baby_fuzzer_listing_06"
|
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["Your Name <you@example.com>"]
|
|
||||||
edition = "2018"
|
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
libafl = { path = "path/to/libafl/" }
|
|
||||||
libafl_bolts = { path = "path/to/libafl_bolts/" }
|
|
||||||
|
|
||||||
[profile.dev]
|
|
||||||
panic = "abort"
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
panic = "abort"
|
|
||||||
lto = true
|
|
||||||
codegen-units = 1
|
|
||||||
opt-level = 3
|
|
||||||
debug = true
|
|
||||||
|
|
||||||
[features]
|
|
||||||
panic = []
|
|
@ -1,116 +0,0 @@
|
|||||||
/* ANCHOR: use */
|
|
||||||
extern crate libafl;
|
|
||||||
extern crate libafl_bolts;
|
|
||||||
|
|
||||||
use libafl::{
|
|
||||||
corpus::{InMemoryCorpus, OnDiskCorpus},
|
|
||||||
events::SimpleEventManager,
|
|
||||||
executors::{inprocess::InProcessExecutor, ExitKind},
|
|
||||||
feedbacks::{CrashFeedback, MaxMapFeedback},
|
|
||||||
fuzzer::{Fuzzer, StdFuzzer},
|
|
||||||
generators::RandPrintablesGenerator,
|
|
||||||
inputs::{BytesInput, HasTargetBytes},
|
|
||||||
monitors::SimpleMonitor,
|
|
||||||
mutators::scheduled::{havoc_mutations, StdScheduledMutator},
|
|
||||||
observers::StdMapObserver,
|
|
||||||
schedulers::QueueScheduler,
|
|
||||||
stages::mutational::StdMutationalStage,
|
|
||||||
state::StdState,
|
|
||||||
};
|
|
||||||
use libafl_bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice};
|
|
||||||
use std::path::PathBuf;
|
|
||||||
/* ANCHOR_END: use */
|
|
||||||
|
|
||||||
// Coverage map with explicit assignments due to the lack of instrumentation
|
|
||||||
static mut SIGNALS: [u8; 16] = [0; 16];
|
|
||||||
|
|
||||||
fn signals_set(idx: usize) {
|
|
||||||
unsafe { SIGNALS[idx] = 1 };
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
// The closure that we want to fuzz
|
|
||||||
let mut harness = |input: &BytesInput| {
|
|
||||||
let target = input.target_bytes();
|
|
||||||
let buf = target.as_slice();
|
|
||||||
signals_set(0); // set SIGNALS[0]
|
|
||||||
if buf.len() > 0 && buf[0] == 'a' as u8 {
|
|
||||||
signals_set(1); // set SIGNALS[1]
|
|
||||||
if buf.len() > 1 && buf[1] == 'b' as u8 {
|
|
||||||
signals_set(2); // set SIGNALS[2]
|
|
||||||
if buf.len() > 2 && buf[2] == 'c' as u8 {
|
|
||||||
panic!("=)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ExitKind::Ok
|
|
||||||
};
|
|
||||||
// To test the panic:
|
|
||||||
let input = BytesInput::new(Vec::from("abc"));
|
|
||||||
#[cfg(feature = "panic")]
|
|
||||||
harness(&input);
|
|
||||||
|
|
||||||
// Create an observation channel using the signals map
|
|
||||||
let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) };
|
|
||||||
|
|
||||||
// Feedback to rate the interestingness of an input
|
|
||||||
let mut feedback = MaxMapFeedback::new(&observer);
|
|
||||||
|
|
||||||
// A feedback to choose if an input is a solution or not
|
|
||||||
let mut objective = CrashFeedback::new();
|
|
||||||
|
|
||||||
// create a State from scratch
|
|
||||||
let mut state = StdState::new(
|
|
||||||
// RNG
|
|
||||||
StdRand::with_seed(current_nanos()),
|
|
||||||
// Corpus that will be evolved, we keep it in memory for performance
|
|
||||||
InMemoryCorpus::new(),
|
|
||||||
// Corpus in which we store solutions (crashes in this example),
|
|
||||||
// on disk so the user can get them after stopping the fuzzer
|
|
||||||
OnDiskCorpus::new(PathBuf::from("./crashes")).unwrap(),
|
|
||||||
&mut feedback,
|
|
||||||
&mut objective,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
// The Monitor trait defines how the fuzzer stats are displayed to the user
|
|
||||||
let mon = SimpleMonitor::new(|s| println!("{s}"));
|
|
||||||
|
|
||||||
// The event manager handles the various events generated during the fuzzing loop
|
|
||||||
// such as the notification of the addition of a new item to the corpus
|
|
||||||
let mut mgr = SimpleEventManager::new(mon);
|
|
||||||
|
|
||||||
// A queue policy to get testcasess from the corpus
|
|
||||||
let scheduler = QueueScheduler::new();
|
|
||||||
|
|
||||||
// A fuzzer with feedbacks and a corpus scheduler
|
|
||||||
let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);
|
|
||||||
|
|
||||||
// Create the executor for an in-process function with just one observer
|
|
||||||
let mut executor = InProcessExecutor::new(
|
|
||||||
&mut harness,
|
|
||||||
tuple_list!(observer),
|
|
||||||
&mut fuzzer,
|
|
||||||
&mut state,
|
|
||||||
&mut mgr,
|
|
||||||
)
|
|
||||||
.expect("Failed to create the Executor");
|
|
||||||
|
|
||||||
// Generator of printable bytearrays of max size 32
|
|
||||||
let mut generator = RandPrintablesGenerator::new(32);
|
|
||||||
|
|
||||||
// Generate 8 initial inputs
|
|
||||||
state
|
|
||||||
.generate_initial_inputs(&mut fuzzer, &mut executor, &mut generator, &mut mgr, 8)
|
|
||||||
.expect("Failed to generate the initial corpus");
|
|
||||||
|
|
||||||
/* ANCHOR: mutational_stage */
|
|
||||||
// Setup a mutational stage with a basic bytes mutator
|
|
||||||
let mutator = StdScheduledMutator::new(havoc_mutations());
|
|
||||||
let mut stages = tuple_list!(StdMutationalStage::new(mutator));
|
|
||||||
|
|
||||||
fuzzer
|
|
||||||
.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)
|
|
||||||
.expect("Error in the fuzzing loop");
|
|
||||||
/* ANCHOR_END: mutational_stage */
|
|
||||||
}
|
|
@ -25,7 +25,6 @@
|
|||||||
- [Architecture](./design/architecture.md)
|
- [Architecture](./design/architecture.md)
|
||||||
- [Metadata](./design/metadata.md)
|
- [Metadata](./design/metadata.md)
|
||||||
- [Migrating from LibAFL <0.9 to 0.9](./design/migration-0.9.md)
|
- [Migrating from LibAFL <0.9 to 0.9](./design/migration-0.9.md)
|
||||||
- [Migrating from LibAFL <0.11 to 0.11](./design/migration-0.11.md)
|
|
||||||
|
|
||||||
- [Message Passing](./message_passing/message_passing.md)
|
- [Message Passing](./message_passing/message_passing.md)
|
||||||
- [Spawning Instances](./message_passing/spawn_instances.md)
|
- [Spawning Instances](./message_passing/spawn_instances.md)
|
||||||
|
@ -1,8 +1,7 @@
|
|||||||
# Concolic Tracing and Hybrid Fuzzing
|
# Concolic Tracing and Hybrid Fuzzing
|
||||||
|
|
||||||
LibAFL has support for concolic tracing based on the [SymCC](https://github.com/eurecom-s3/symcc) instrumenting compiler.
|
LibAFL has support for concolic tracing based on the [SymCC](https://github.com/eurecom-s3/symcc) instrumenting compiler.
|
||||||
|
|
||||||
For those uninitiated, the following text attempts to describe concolic tracing from the ground up using an example.
|
For those uninitiated, the following attempts to describe concolic tracing from the ground up using an example.
|
||||||
Then, we'll go through the relationship of SymCC and LibAFL concolic tracing.
|
Then, we'll go through the relationship of SymCC and LibAFL concolic tracing.
|
||||||
Finally, we'll walk through building a basic hybrid fuzzer using LibAFL.
|
Finally, we'll walk through building a basic hybrid fuzzer using LibAFL.
|
||||||
|
|
||||||
@ -93,18 +92,18 @@ In hybrid fuzzing, we combine this tracing + solving approach with more traditio
|
|||||||
The concolic tracing support in LibAFL is implemented using SymCC.
|
The concolic tracing support in LibAFL is implemented using SymCC.
|
||||||
SymCC is a compiler plugin for clang that can be used as a drop-in replacement for a normal C or C++ compiler.
|
SymCC is a compiler plugin for clang that can be used as a drop-in replacement for a normal C or C++ compiler.
|
||||||
SymCC will instrument the compiled code with callbacks into a runtime that can be supplied by the user.
|
SymCC will instrument the compiled code with callbacks into a runtime that can be supplied by the user.
|
||||||
These callbacks allow the runtime to construct a trace that is similar to the previous example.
|
These callbacks allow the runtime to construct a trace that similar to the previous example.
|
||||||
|
|
||||||
### SymCC and its Runtimes
|
### SymCC and its Runtimes
|
||||||
|
|
||||||
SymCC ships with 2 runtimes:
|
SymCC ships with 2 runtimes:
|
||||||
|
|
||||||
* A 'simple' runtime that attempts to negate and analytically solve any branch conditions it comes across using [Z3](https://github.com/Z3Prover/z3/wiki) and
|
* a 'simple' runtime that attempts to solve any branches it comes across using [Z3](https://github.com/Z3Prover/z3/wiki) and
|
||||||
* A [QSym](https://github.com/sslab-gatech/qsym)-based runtime, which does a bit more filtering on the expressions and also solves them using Z3.
|
* a [QSym](https://github.com/sslab-gatech/qsym)-based runtime, which does a bit more filtering on the expressions and also solves using Z3.
|
||||||
|
|
||||||
The integration with LibAFL, however, requires you to **BYORT** (_bring your own runtime_) using the [`symcc_runtime`](https://docs.rs/symcc_runtime/0.1/symcc_runtime) crate.
|
The integration with LibAFL, however, requires you to **BYORT** (_bring your own runtime_) using the [`symcc_runtime`](https://docs.rs/symcc_runtime/0.1/symcc_runtime) crate.
|
||||||
This crate allows you to easily build a custom runtime out of the built-in building blocks or create entirely new runtimes with full flexibility.
|
This crate allows you to easily build a custom runtime out of the built-in building blocks or create entirely new runtimes with full flexibility.
|
||||||
Check out the `symcc_runtime` docs for more information on how to build your own runtime.
|
Checkout out the `symcc_runtime` docs for more information on how to build your own runtime.
|
||||||
|
|
||||||
### SymQEMU
|
### SymQEMU
|
||||||
|
|
||||||
@ -124,7 +123,7 @@ There are three main steps involved with building a hybrid fuzzer using LibAFL:
|
|||||||
3. building the fuzzer.
|
3. building the fuzzer.
|
||||||
|
|
||||||
Note that the order of these steps is important.
|
Note that the order of these steps is important.
|
||||||
For example, we need to have a runtime ready before we can do instrumentation with SymCC.
|
For example, we need to have runtime ready before we can do instrumentation with SymCC.
|
||||||
|
|
||||||
### Building a Runtime
|
### Building a Runtime
|
||||||
|
|
||||||
@ -135,12 +134,10 @@ Check out the [example hybrid fuzzer's runtime](https://github.com/AFLplusplus/L
|
|||||||
### Instrumentation
|
### Instrumentation
|
||||||
|
|
||||||
There are two main instrumentation methods to make use of concolic tracing in LibAFL:
|
There are two main instrumentation methods to make use of concolic tracing in LibAFL:
|
||||||
|
* Using an **compile-time** instrumented target with **SymCC**.
|
||||||
* Using a **compile-time** instrumented target with **SymCC**.
|
|
||||||
This only works when the source is available for the target and the target is reasonably easy to build using the SymCC compiler wrapper.
|
This only works when the source is available for the target and the target is reasonably easy to build using the SymCC compiler wrapper.
|
||||||
* Using **SymQEMU** to dynamically instrument the target at **runtime**.
|
* Using **SymQEMU** to dynamically instrument the target at **runtime**.
|
||||||
This avoids building a separate instrumented target with concolic tracing instrumentation and so does not require source code.
|
This avoids a separate instrumented target with concolic tracing instrumentation and does not require source code.
|
||||||
|
|
||||||
It should be noted, however, that the 'quality' of the generated expressions can be significantly worse and SymQEMU generally produces significantly more and significantly more convoluted expressions than SymCC.
|
It should be noted, however, that the 'quality' of the generated expressions can be significantly worse and SymQEMU generally produces significantly more and significantly more convoluted expressions than SymCC.
|
||||||
Therefore, it is recommended to use SymCC over SymQEMU when possible.
|
Therefore, it is recommended to use SymCC over SymQEMU when possible.
|
||||||
|
|
||||||
@ -161,23 +158,23 @@ Make sure you satisfy the [build requirements](https://github.com/eurecom-s3/sym
|
|||||||
|
|
||||||
Build SymQEMU according to its [build instructions](https://github.com/eurecom-s3/symqemu#readme).
|
Build SymQEMU according to its [build instructions](https://github.com/eurecom-s3/symqemu#readme).
|
||||||
By default, SymQEMU looks for the runtime in a sibling directory.
|
By default, SymQEMU looks for the runtime in a sibling directory.
|
||||||
Since we don't have a runtime there, we need to explicitly set the `--symcc-build` argument of the `configure` script to the path of your runtime.
|
Since we don't have a runtime there, we need to let it know the path to your runtime by setting `--symcc-build` argument of the `configure` script to the path of your runtime.
|
||||||
|
|
||||||
### Building the Fuzzer
|
### Building the Fuzzer
|
||||||
|
|
||||||
No matter the instrumentation method, the interface between the fuzzer and the instrumented target should now be consistent.
|
No matter the instrumentation method, the interface between the fuzzer and the instrumented target should now be consistent.
|
||||||
The only difference between using SymCC and SymQEMU should be the binary that represents the target:
|
The only difference between using SymCC and SymQEMU should be the binary that represents the target:
|
||||||
In the case of SymCC it will be the binary that was build with instrumentation and with SymQEMU it will be the emulator binary (eg. `x86_64-linux-user/symqemu-x86_64`), followed by your uninstrumented target binary and its arguments.
|
In the case of SymCC it will be the binary that was build with instrumentation and with SymQEMU it will be the emulator binary (eg. `x86_64-linux-user/symqemu-x86_64`), followed by your uninstrumented target binary and arguments.
|
||||||
|
|
||||||
You can use the [`CommandExecutor`](https://docs.rs/libafl/0.6.0/libafl/executors/command/struct.CommandExecutor.html) to execute your target ([example](https://github.com/AFLplusplus/LibAFL/blob/main/fuzzers/libfuzzer_stb_image_concolic/fuzzer/src/main.rs#L244)).
|
You can use the [`CommandExecutor`](https://docs.rs/libafl/0.6.0/libafl/executors/command/struct.CommandExecutor.html) to execute your target ([example](https://github.com/AFLplusplus/LibAFL/blob/main/fuzzers/libfuzzer_stb_image_concolic/fuzzer/src/main.rs#L244)).
|
||||||
When configuring the command, make sure you pass the `SYMCC_INPUT_FILE` environment variable (set to the input file path), if your target reads input from a file (instead of standard input).
|
When configuring the command, make sure you pass the `SYMCC_INPUT_FILE` environment variable the input file path, if your target reads input from a file (instead of standard input).
|
||||||
|
|
||||||
#### Serialization and Solving
|
#### Serialization and Solving
|
||||||
|
|
||||||
While it is perfectly possible to build a custom runtime that also performs the solving step of hybrid fuzzing in the context of the target process, the intended use of the LibAFL concolic tracing support is to serialize the (filtered and pre-processed) branch conditions using the [`TracingRuntime`](https://docs.rs/symcc_runtime/0.1/symcc_runtime/tracing/struct.TracingRuntime.html).
|
While it is perfectly possible to build a custom runtime that also performs the solving step of hybrid fuzzing in the context of the target process, the intended use of the LibAFL concolic tracing support is to serialize the (filtered and pre-processed) branch conditions using the [`TracingRuntime`](https://docs.rs/symcc_runtime/0.1/symcc_runtime/tracing/struct.TracingRuntime.html).
|
||||||
This serialized representation can be deserialized in the fuzzer process for solving using a [`ConcolicObserver`](https://docs.rs/libafl/0.6.0/libafl/observers/concolic/struct.ConcolicObserver.html) wrapped in a [`ConcolicTracingStage`](https://docs.rs/libafl/0.6.0/libafl/stages/concolic/struct.ConcolicTracingStage.html), which will attach a [`ConcolicMetadata`](https://docs.rs/libafl/0.6.0/libafl/observers/concolic/struct.ConcolicMetadata.html) to every [`TestCase`](https://docs.rs/libafl/0.6.0/libafl/corpus/testcase/struct.Testcase.html).
|
This serialized representation can be deserialized in the fuzzer process for solving using a [`ConcolicObserver`](https://docs.rs/libafl/0.6.0/libafl/observers/concolic/struct.ConcolicObserver.html) wrapped in a [`ConcolicTracingStage`](https://docs.rs/libafl/0.6.0/libafl/stages/concolic/struct.ConcolicTracingStage.html), which will attach a [`ConcolicMetadata`](https://docs.rs/libafl/0.6.0/libafl/observers/concolic/struct.ConcolicMetadata.html) to every [`TestCase`](https://docs.rs/libafl/0.6.0/libafl/corpus/testcase/struct.Testcase.html).
|
||||||
|
|
||||||
The `ConcolicMetadata` can be used to replay the concolic trace and to solve the conditions using an SMT-Solver.
|
The `ConcolicMetadata` can be used to replay the concolic trace and solved using an SMT-Solver.
|
||||||
Most use-cases involving concolic tracing, however, will need to define some policy around which branches they want to solve.
|
Most use-cases involving concolic tracing, however, will need to define some policy around which branches they want to solve.
|
||||||
The [`SimpleConcolicMutationalStage`](https://docs.rs/libafl/0.6.0//libafl/stages/concolic/struct.SimpleConcolicMutationalStage.html) can be used for testing purposes.
|
The [`SimpleConcolicMutationalStage`](https://docs.rs/libafl/0.6.0//libafl/stages/concolic/struct.SimpleConcolicMutationalStage.html) can be used for testing purposes.
|
||||||
It will attempt to solve all branches, like the original simple backend from SymCC, using Z3.
|
It will attempt to solve all branches, like the original simple backend from SymCC, using Z3.
|
||||||
|
@ -17,7 +17,7 @@ If you are on Windows, you'll need to install llvm tools.
|
|||||||
LibAFL uses Frida's [__Stalker__](https://frida.re/docs/stalker/) to trace the execution of your program and instrument your harness.
|
LibAFL uses Frida's [__Stalker__](https://frida.re/docs/stalker/) to trace the execution of your program and instrument your harness.
|
||||||
Thus, you have to compile your harness to a dynamic library. Frida instruments your PUT after dynamically loading it.
|
Thus, you have to compile your harness to a dynamic library. Frida instruments your PUT after dynamically loading it.
|
||||||
|
|
||||||
In our `frida_libpng` example, we load the dynamic library and find the symbol to harness as follows:
|
For example in our `frida_libpng` example, we load the dynamic library and find the symbol to harness as follows:
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
let lib = libloading::Library::new(module_name).unwrap();
|
let lib = libloading::Library::new(module_name).unwrap();
|
||||||
@ -28,9 +28,9 @@ In our `frida_libpng` example, we load the dynamic library and find the symbol t
|
|||||||
|
|
||||||
## `FridaInstrumentationHelper` and Runtimes
|
## `FridaInstrumentationHelper` and Runtimes
|
||||||
|
|
||||||
To use functionalities that Frida offers, we'll first need to obtain a `Gum` object by `Gum::obtain()`.
|
To use functionalities that Frida offers, we'll first need to obtain `Gum` object by `Gum::obtain()`.
|
||||||
|
|
||||||
In LibAFL, we use the `FridaInstrumentationHelper` struct to manage frida-related state. `FridaInstrumentationHelper` is a key component that sets up the [__Transformer__](https://frida.re/docs/stalker/#transformer) that is used to generate the instrumented code. It also initializes the `Runtimes` that offer various instrumentations.
|
In LibAFL, we use the `FridaInstrumentationHelper` struct to manage frida-related state. `FridaInstrumentationHelper` is a key component that sets up the [__Transformer__](https://frida.re/docs/stalker/#transformer) that is used to generate the instrumented code. It also initializes the `Runtimes` that offer various instrumentation.
|
||||||
|
|
||||||
We have `CoverageRuntime` that can track the edge coverage, `AsanRuntime` for address sanitizer, `DrCovRuntime` that uses [__DrCov__](https://dynamorio.org/page_drcov.html) for coverage collection (to be imported in coverage tools like Lighthouse, bncov, dragondance,...), and `CmpLogRuntime` for cmplog instrumentation.
|
We have `CoverageRuntime` that can track the edge coverage, `AsanRuntime` for address sanitizer, `DrCovRuntime` that uses [__DrCov__](https://dynamorio.org/page_drcov.html) for coverage collection (to be imported in coverage tools like Lighthouse, bncov, dragondance,...), and `CmpLogRuntime` for cmplog instrumentation.
|
||||||
All of these runtimes can be slotted into `FridaInstrumentationHelper` at build time.
|
All of these runtimes can be slotted into `FridaInstrumentationHelper` at build time.
|
||||||
@ -53,12 +53,12 @@ Combined with any `Runtime` you'd like to use, you can initialize the `FridaInst
|
|||||||
|
|
||||||
## Running the Fuzzer
|
## Running the Fuzzer
|
||||||
|
|
||||||
After setting up the `FridaInstrumentationHelper` you can obtain the pointer to the coverage map by calling `map_mut_ptr()`.
|
After setting up the `FridaInstrumentationHelper`. You can obtain the pointer to the coverage map by calling `map_ptr_mut()`.
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
|
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr(
|
||||||
"edges",
|
"edges",
|
||||||
frida_helper.map_mut_ptr().unwrap(),
|
frida_helper.map_ptr_mut().unwrap(),
|
||||||
MAP_SIZE,
|
MAP_SIZE,
|
||||||
));
|
));
|
||||||
```
|
```
|
||||||
@ -83,5 +83,5 @@ You can then link this observer to `FridaInProcessExecutor` as follows:
|
|||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
And finally you can run the fuzzer.
|
And, finally you can run the fuzzer.
|
||||||
See the `frida_` examples in [`./fuzzers`](https://github.com/AFLplusplus/LibAFL/tree/main/fuzzers/) for more information and, for linux or full-system, play around with `libafl_qemu`, another binary-only tracer.
|
See the `frida_` examples in [`./fuzzers`](https://github.com/AFLplusplus/LibAFL/tree/main/fuzzers/) for more information and, for linux or full-system, play around with `libafl_qemu`, another binary-only tracer.
|
@ -1,6 +1,6 @@
|
|||||||
# Using LibAFL in `no_std` environments
|
# Using LibAFL in `no_std` environments
|
||||||
|
|
||||||
It is possible to use LibAFL in `no_std` environments e.g. on custom platforms like microcontrollers, kernels, hypervisors, and more.
|
It is possible to use LibAFL in `no_std` environments e.g. custom platforms like microcontrollers, kernels, hypervisors, and more.
|
||||||
|
|
||||||
You can simply add LibAFL to your `Cargo.toml` file:
|
You can simply add LibAFL to your `Cargo.toml` file:
|
||||||
|
|
||||||
@ -16,7 +16,7 @@ cargo build --no-default-features --target aarch64-unknown-none
|
|||||||
|
|
||||||
## Use custom timing
|
## Use custom timing
|
||||||
|
|
||||||
The minimum amount of support LibAFL needs for a `no_std` environment is a monotonically increasing timestamp.
|
The minimum amount of input LibAFL needs for `no_std` is a monotonically increasing timestamp.
|
||||||
For this, anywhere in your project you need to implement the `external_current_millis` function, which returns the current time in milliseconds.
|
For this, anywhere in your project you need to implement the `external_current_millis` function, which returns the current time in milliseconds.
|
||||||
|
|
||||||
```c
|
```c
|
||||||
|
@ -2,12 +2,12 @@
|
|||||||
|
|
||||||
NYX supports both source-based and binary-only fuzzing.
|
NYX supports both source-based and binary-only fuzzing.
|
||||||
|
|
||||||
Currently, `libafl_nyx` only supports [afl++](https://github.com/AFLplusplus/AFLplusplus)'s instruction type. To install it, you can use `sudo apt install aflplusplus`. Or compile from the source:
|
Currently, `libafl_nyx` only supports [afl++](https://github.com/AFLplusplus/AFLplusplus)'s instruction. To install it, you can use `sudo apt install aflplusplus`. Or compile from the source:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/AFLplusplus/AFLplusplus
|
git clone https://github.com/AFLplusplus/AFLplusplus
|
||||||
cd AFLplusplus
|
cd AFLplusplus
|
||||||
make all # this will not compile afl's additional extensions
|
make all # this will not compile afl's additional extension
|
||||||
```
|
```
|
||||||
|
|
||||||
Then you should compile the target with the afl++ compiler wrapper:
|
Then you should compile the target with the afl++ compiler wrapper:
|
||||||
@ -20,9 +20,9 @@ export CXX=afl-clang-fast++
|
|||||||
make
|
make
|
||||||
```
|
```
|
||||||
|
|
||||||
For binary-only fuzzing, Nyx uses intel-PT(Intel® Processor Trace). You can find the list of supported CPUs at <https://www.intel.com/content/www/us/en/support/articles/000056730/processors.html>.
|
For binary-only fuzzing, Nyx uses intel-PT(Intel® Processor Trace). You can find the supported CPU at <https://www.intel.com/content/www/us/en/support/articles/000056730/processors.html>.
|
||||||
|
|
||||||
## Preparing the Nyx working directory
|
## Preparing Nyx working directory
|
||||||
|
|
||||||
This step is used to pack the target into Nyx's kernel. Don't worry, we have a template shell script in our [example](https://github.com/AFLplusplus/LibAFL/blob/main/fuzzers/nyx_libxml2_parallel/setup_libxml2.sh):
|
This step is used to pack the target into Nyx's kernel. Don't worry, we have a template shell script in our [example](https://github.com/AFLplusplus/LibAFL/blob/main/fuzzers/nyx_libxml2_parallel/setup_libxml2.sh):
|
||||||
|
|
||||||
@ -49,7 +49,7 @@ python3 ./packer/packer/nyx_config_gen.py /tmp/nyx_libxml2/ Kernel || exit
|
|||||||
|
|
||||||
## Standalone fuzzing
|
## Standalone fuzzing
|
||||||
|
|
||||||
In the [example fuzzer](https://github.com/AFLplusplus/LibAFL/blob/main/fuzzers/nyx_libxml2_standalone/src/main.rs) you first need to run `./setup_libxml2.sh`. It will prepare your target and create your nyx work directory in `/tmp/libxml2`. After that, you can start to write your code.
|
In the [example fuzzer](https://github.com/AFLplusplus/LibAFL/blob/main/fuzzers/nyx_libxml2_standalone/src/main.rs). First you need to run `./setup_libxml2.sh`, It will prepare your target and create your nyx work directory in `/tmp/libxml2`. After that, you can start write your code.
|
||||||
|
|
||||||
First, to create `Nyxhelper`:
|
First, to create `Nyxhelper`:
|
||||||
|
|
||||||
@ -57,21 +57,22 @@ First, to create `Nyxhelper`:
|
|||||||
let share_dir = Path::new("/tmp/nyx_libxml2/");
|
let share_dir = Path::new("/tmp/nyx_libxml2/");
|
||||||
let cpu_id = 0; // use first cpu
|
let cpu_id = 0; // use first cpu
|
||||||
let parallel_mode = false; // close parallel_mode
|
let parallel_mode = false; // close parallel_mode
|
||||||
let mut helper = NyxHelper::new(share_dir, cpu_id, true, parallel_mode, None).unwrap(); // we don't need to set the last parameter in standalone mode, we just use None, here
|
let mut helper = NyxHelper::new(share_dir, cpu_id, true, parallel_mode, None).unwrap(); // we don't the set the last parameter in standalone mode, we just use None, here
|
||||||
```
|
```
|
||||||
|
|
||||||
Then, fetch `trace_bits`, create an observer and the `NyxExecutor`:
|
Then, fetch `trace_bits`, create an observer and the `NyxExecutor`:
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
let observer = unsafe { StdMapObserver::from_mut_ptr("trace", helper.trace_bits, helper.map_size) };
|
let trace_bits = unsafe { std::slice::from_raw_parts_mut(helper.trace_bits, helper.map_size) };
|
||||||
|
let observer = StdMapObserver::new("trace", trace_bits);
|
||||||
let mut executor = NyxExecutor::new(&mut helper, tuple_list!(observer)).unwrap();
|
let mut executor = NyxExecutor::new(&mut helper, tuple_list!(observer)).unwrap();
|
||||||
```
|
```
|
||||||
|
|
||||||
Finally, use them normally and pass them into `fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)` to start fuzzing.
|
Finally, use them as normal and pass them into `fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)` to start fuzzing.
|
||||||
|
|
||||||
## Parallel fuzzing
|
## Parallel fuzzing
|
||||||
|
|
||||||
In the [example fuzzer](https://github.com/AFLplusplus/LibAFL/blob/main/fuzzers/nyx_libxml2_parallel/src/main.rs) you first need to run `./setup_libxml2.sh` as described before.
|
In the [example fuzzer](https://github.com/AFLplusplus/LibAFL/blob/main/fuzzers/nyx_libxml2_parallel/src/main.rs). First you need to run `./setup_libxml2.sh` as described before.
|
||||||
|
|
||||||
Parallel fuzzing relies on [`Launcher`](../message_passing/spawn_instances.md), so spawn logic should be written in the scoop of anonymous function `run_client`:
|
Parallel fuzzing relies on [`Launcher`](../message_passing/spawn_instances.md), so spawn logic should be written in the scoop of anonymous function `run_client`:
|
||||||
|
|
||||||
@ -90,7 +91,7 @@ let mut helper = NyxHelper::new(
|
|||||||
cpu_id, // current cpu id
|
cpu_id, // current cpu id
|
||||||
true, // open snap_mode
|
true, // open snap_mode
|
||||||
parallel_mode, // open parallel mode
|
parallel_mode, // open parallel mode
|
||||||
Some(parent_cpu_id.id as u32), // the cpu-id of main instance, there is only one main instance, other instances will be treated as secondaries
|
Some(parent_cpu_id.id as u32), // the cpu-id of master instance, there is only one master instance, other instances will be treated as slaved
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
```
|
```
|
||||||
@ -98,11 +99,13 @@ let mut helper = NyxHelper::new(
|
|||||||
Then you can fetch the trace_bits and create an observer and `NyxExecutor`
|
Then you can fetch the trace_bits and create an observer and `NyxExecutor`
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
let observer = unsafe { StdMapObserver::from_mut_ptr("trace", helper.trace_bits, helper.map_size) }
|
let trace_bits =
|
||||||
|
unsafe { std::slice::from_raw_parts_mut(helper.trace_bits, helper.map_size) };
|
||||||
|
let observer = StdMapObserver::new("trace", trace_bits);
|
||||||
let mut executor = NyxExecutor::new(&mut helper, tuple_list!(observer)).unwrap();
|
let mut executor = NyxExecutor::new(&mut helper, tuple_list!(observer)).unwrap();
|
||||||
```
|
```
|
||||||
|
|
||||||
Finally, open a `Launcher` as usual to start fuzzing:
|
Finally, open a `Launcher` as normal to start fuzzing:
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
match Launcher::builder()
|
match Launcher::builder()
|
||||||
@ -118,6 +121,6 @@ match Launcher::builder()
|
|||||||
{
|
{
|
||||||
Ok(()) => (),
|
Ok(()) => (),
|
||||||
Err(Error::ShuttingDown) => println!("Fuzzing stopped by user. Good bye."),
|
Err(Error::ShuttingDown) => println!("Fuzzing stopped by user. Good bye."),
|
||||||
Err(err) => panic!("Failed to run launcher: {err:?}"),
|
Err(err) => panic!("Failed to run launcher: {:?}", err),
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -17,7 +17,7 @@ You can find a complete version of this tutorial as an example fuzzer in [`fuzze
|
|||||||
|
|
||||||
We use cargo to create a new Rust project with LibAFL as a dependency.
|
We use cargo to create a new Rust project with LibAFL as a dependency.
|
||||||
|
|
||||||
```console
|
```sh
|
||||||
$ cargo new baby_fuzzer
|
$ cargo new baby_fuzzer
|
||||||
$ cd baby_fuzzer
|
$ cd baby_fuzzer
|
||||||
```
|
```
|
||||||
@ -25,11 +25,18 @@ $ cd baby_fuzzer
|
|||||||
The generated `Cargo.toml` looks like the following:
|
The generated `Cargo.toml` looks like the following:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
{{#include ../../listings/baby_fuzzer/listing-01/Cargo.toml}}
|
[package]
|
||||||
|
name = "baby_fuzzer"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Your Name <you@example.com>"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
```
|
```
|
||||||
|
|
||||||
In order to use LibAFl we must add it as dependency adding `libafl = { path = "path/to/libafl/" }` under `[dependencies]`.
|
In order to use LibAFl we must add it as dependency adding `libafl = { path = "path/to/libafl/" }` under `[dependencies]`.
|
||||||
That path actually needs to point to the `libafl` directory within the cloned repo, not the root of the repo itself.
|
|
||||||
You can use the LibAFL version from [crates.io](https://crates.io/crates/libafl) if you want, in this case, you have to use `libafl = "*"` to get the latest version (or set it to the current version).
|
You can use the LibAFL version from [crates.io](https://crates.io/crates/libafl) if you want, in this case, you have to use `libafl = "*"` to get the latest version (or set it to the current version).
|
||||||
|
|
||||||
As we are going to fuzz Rust code, we want that a panic does not simply cause the program to exit, but raise an `abort` that can then be caught by the fuzzer.
|
As we are going to fuzz Rust code, we want that a panic does not simply cause the program to exit, but raise an `abort` that can then be caught by the fuzzer.
|
||||||
@ -40,9 +47,27 @@ Alongside this setting, we add some optimization flags for the compilation, when
|
|||||||
The final `Cargo.toml` should look similar to the following:
|
The final `Cargo.toml` should look similar to the following:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
{{#include ../../listings/baby_fuzzer/listing-02/Cargo.toml}}
|
[package]
|
||||||
```
|
name = "baby_fuzzer"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Your Name <you@example.com>"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
libafl = { path = "path/to/libafl/" }
|
||||||
|
|
||||||
|
[profile.dev]
|
||||||
|
panic = "abort"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
panic = "abort"
|
||||||
|
lto = true
|
||||||
|
codegen-units = 1
|
||||||
|
opt-level = 3
|
||||||
|
debug = true
|
||||||
|
```
|
||||||
|
|
||||||
## The function under test
|
## The function under test
|
||||||
|
|
||||||
@ -51,32 +76,52 @@ To start, we create the closure that we want to fuzz. It takes a buffer as input
|
|||||||
`ExitKind` is used to inform the fuzzer about the harness' exit status.
|
`ExitKind` is used to inform the fuzzer about the harness' exit status.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-03/src/main.rs}}
|
extern crate libafl;
|
||||||
|
use libafl::{
|
||||||
|
bolts::AsSlice,
|
||||||
|
inputs::{BytesInput, HasTargetBytes},
|
||||||
|
executors::ExitKind,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn main(){
|
||||||
|
let mut harness = |input: &BytesInput| {
|
||||||
|
let target = input.target_bytes();
|
||||||
|
let buf = target.as_slice();
|
||||||
|
if buf.len() > 0 && buf[0] == 'a' as u8 {
|
||||||
|
if buf.len() > 1 && buf[1] == 'b' as u8 {
|
||||||
|
if buf.len() > 2 && buf[2] == 'c' as u8 {
|
||||||
|
panic!("=)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ExitKind::Ok
|
||||||
|
};
|
||||||
|
// To test the panic:
|
||||||
|
let input = BytesInput::new(Vec::from("abc"));
|
||||||
|
#[cfg(feature = "panic")]
|
||||||
|
harness(&input);
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
To test the crash manually, you can add a feature in `Cargo.toml` that enables the call that triggers the panic:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
{{#include ../../listings/baby_fuzzer/listing-03/Cargo.toml:22:24}}
|
|
||||||
```
|
|
||||||
|
|
||||||
And then run the program with that feature activated:
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ cargo run -F panic
|
|
||||||
```
|
|
||||||
|
|
||||||
And you should see the program crash as expected.
|
|
||||||
|
|
||||||
## Generating and running some tests
|
## Generating and running some tests
|
||||||
|
|
||||||
One of the main components that a LibAFL-based fuzzer uses is the State, a container of the data that will evolve during the fuzzing process.
|
One of the main components that a LibAFL-based fuzzer uses is the State, a container of the data that is evolved during the fuzzing process.
|
||||||
It includes all state, such as the Corpus of inputs, the current RNG state, and potential Metadata for the testcases and run.
|
Includes all State, such as the Corpus of inputs, the current RNG state, and potential Metadata for the testcases and run.
|
||||||
In our `main` we create a basic State instance like the following:
|
In our `main` we create a basic State instance like the following:
|
||||||
|
|
||||||
|
```rust,ignore
|
||||||
```rust
|
// create a State from scratch
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-04/src/main.rs:state}}
|
let mut state = StdState::new(
|
||||||
|
// RNG
|
||||||
|
StdRand::with_seed(current_nanos()),
|
||||||
|
// Corpus that will be evolved, we keep it in memory for performance
|
||||||
|
InMemoryCorpus::new(),
|
||||||
|
// Corpus in which we store solutions (crashes in this example),
|
||||||
|
// on disk so the user can get them after stopping the fuzzer
|
||||||
|
OnDiskCorpus::new(PathBuf::from("./crashes")).unwrap(),
|
||||||
|
&mut (),
|
||||||
|
&mut ()
|
||||||
|
).unwrap();
|
||||||
```
|
```
|
||||||
|
|
||||||
- The first parameter is a random number generator, that is part of the fuzzer state, in this case, we use the default one `StdRand`, but you can choose a different one. We seed it with the current nanoseconds.
|
- The first parameter is a random number generator, that is part of the fuzzer state, in this case, we use the default one `StdRand`, but you can choose a different one. We seed it with the current nanoseconds.
|
||||||
@ -84,26 +129,43 @@ In our `main` we create a basic State instance like the following:
|
|||||||
|
|
||||||
To avoid type annotation error, you can use `InMemoryCorpus::<BytesInput>::new()` to replace `InMemoryCorpus::new()`. If not, type annotation will be automatically inferred when adding `executor`.
|
To avoid type annotation error, you can use `InMemoryCorpus::<BytesInput>::new()` to replace `InMemoryCorpus::new()`. If not, type annotation will be automatically inferred when adding `executor`.
|
||||||
|
|
||||||
- The third parameter is another Corpus that stores the "solution" testcases for the fuzzer. For our purpose, the solution is the input that triggers the panic. In this case, we want to store it to disk under the `crashes` directory, so we can inspect it.
|
- third parameter is another corpus that stores the "solution" testcases for the fuzzer. For our purpose, the solution is the input that triggers the panic. In this case, we want to store it to disk under the `crashes` directory, so we can inspect it.
|
||||||
- The last two parameters are feedback and objective, we will discuss them later.
|
- last two parameters are feedback and objective, we will discuss them later.
|
||||||
|
|
||||||
Another required component is the **EventManager**. It handles some events such as the addition of a testcase to the corpus during the fuzzing process. For our purpose, we use the simplest one that just displays the information about these events to the user using a `Monitor` instance.
|
Another required component is the **EventManager**. It handles some events such as the addition of a testcase to the corpus during the fuzzing process. For our purpose, we use the simplest one that just displays the information about these events to the user using a `Monitor` instance.
|
||||||
|
|
||||||
```rust
|
```rust,ignore
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-04/src/main.rs:event_manager}}
|
// The Monitor trait defines how the fuzzer stats are displayed to the user
|
||||||
|
let mon = SimpleMonitor::new(|s| println!("{}", s));
|
||||||
|
|
||||||
|
// The event manager handle the various events generated during the fuzzing loop
|
||||||
|
// such as the notification of the addition of a new item to the corpus
|
||||||
|
let mut mgr = SimpleEventManager::new(mon);
|
||||||
```
|
```
|
||||||
|
|
||||||
In addition, we have the **Fuzzer**, an entity that contains some actions that alter the State. One of these actions is the scheduling of the testcases to the fuzzer using a **Scheduler**.
|
In addition, we have the **Fuzzer**, an entity that contains some actions that alter the State. One of these actions is the scheduling of the testcases to the fuzzer using a **Scheduler**.
|
||||||
We create it as `QueueScheduler`, a scheduler that serves testcases to the fuzzer in a FIFO fashion.
|
We create it as `QueueScheduler`, a scheduler that serves testcases to the fuzzer in a FIFO fashion.
|
||||||
|
|
||||||
```rust
|
```rust,ignore
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-04/src/main.rs:scheduler_fuzzer}}
|
// A queue policy to get testcasess from the corpus
|
||||||
|
let scheduler = QueueScheduler::new();
|
||||||
|
|
||||||
|
// A fuzzer with feedbacks and a corpus scheduler
|
||||||
|
let mut fuzzer = StdFuzzer::new(scheduler, (), ());
|
||||||
```
|
```
|
||||||
|
|
||||||
Last but not least, we need an **Executor** that is the entity responsible to run our program under test. In this example, we want to run the harness function in-process (without forking off a child, for example), and so we use the `InProcessExecutor`.
|
Last but not least, we need an **Executor** that is the entity responsible to run our program under test. In this example, we want to run the harness function in-process (without forking off a child, for example), and so we use the `InProcessExecutor`.
|
||||||
|
|
||||||
```rust
|
```rust,ignore
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-04/src/main.rs:executor}}
|
// Create the executor for an in-process function
|
||||||
|
let mut executor = InProcessExecutor::new(
|
||||||
|
&mut harness,
|
||||||
|
(),
|
||||||
|
&mut fuzzer,
|
||||||
|
&mut state,
|
||||||
|
&mut mgr,
|
||||||
|
)
|
||||||
|
.expect("Failed to create the Executor");
|
||||||
```
|
```
|
||||||
|
|
||||||
It takes a reference to the harness, the state, and the event manager. We will discuss the second parameter later.
|
It takes a reference to the harness, the state, and the event manager. We will discuss the second parameter later.
|
||||||
@ -113,19 +175,41 @@ Now we have the 4 major entities ready for running our tests, but we still canno
|
|||||||
|
|
||||||
For this purpose, we use a **Generator**, `RandPrintablesGenerator` that generates a string of printable bytes.
|
For this purpose, we use a **Generator**, `RandPrintablesGenerator` that generates a string of printable bytes.
|
||||||
|
|
||||||
```rust
|
```rust,ignore
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-04/src/main.rs:generator}}
|
use libafl::generators::RandPrintablesGenerator;
|
||||||
|
|
||||||
|
// Generator of printable bytearrays of max size 32
|
||||||
|
let mut generator = RandPrintablesGenerator::new(32);
|
||||||
|
|
||||||
|
// Generate 8 initial inputs
|
||||||
|
state
|
||||||
|
.generate_initial_inputs(&mut fuzzer, &mut executor, &mut generator, &mut mgr, 8)
|
||||||
|
.expect("Failed to generate the initial corpus".into());
|
||||||
```
|
```
|
||||||
|
|
||||||
Now you can prepend the necessary `use` directives to your main.rs and compile the fuzzer.
|
Now you can prepend the necessary `use` directives to your main.rs and compile the fuzzer.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-04/src/main.rs:use}}
|
extern crate libafl;
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use libafl::{
|
||||||
|
bolts::{AsSlice, current_nanos, rands::StdRand},
|
||||||
|
corpus::{InMemoryCorpus, OnDiskCorpus},
|
||||||
|
events::SimpleEventManager,
|
||||||
|
executors::{inprocess::InProcessExecutor, ExitKind},
|
||||||
|
fuzzer::StdFuzzer,
|
||||||
|
generators::RandPrintablesGenerator,
|
||||||
|
inputs::{BytesInput, HasTargetBytes},
|
||||||
|
monitors::SimpleMonitor,
|
||||||
|
schedulers::QueueScheduler,
|
||||||
|
state::StdState,
|
||||||
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
When running, you should see something similar to:
|
When running, you should see something similar to:
|
||||||
|
|
||||||
```console
|
```sh
|
||||||
$ cargo run
|
$ cargo run
|
||||||
Finished dev [unoptimized + debuginfo] target(s) in 0.04s
|
Finished dev [unoptimized + debuginfo] target(s) in 0.04s
|
||||||
Running `target/debug/baby_fuzzer`
|
Running `target/debug/baby_fuzzer`
|
||||||
@ -141,22 +225,60 @@ Now we want to turn our simple fuzzer into a feedback-based one and increase the
|
|||||||
**Observer** can record the information about properties of a fuzzing run and then feeds the fuzzer. We use the `StdMapObserver`, the default observer that uses a map to keep track of covered elements. In our fuzzer, each condition is mapped to an entry of such map.
|
**Observer** can record the information about properties of a fuzzing run and then feeds the fuzzer. We use the `StdMapObserver`, the default observer that uses a map to keep track of covered elements. In our fuzzer, each condition is mapped to an entry of such map.
|
||||||
|
|
||||||
We represent such map as a `static mut` variable.
|
We represent such map as a `static mut` variable.
|
||||||
As we don't rely on any instrumentation engine, we have to manually track the satisfied conditions by `signals_set` in our harness:
|
As we don't rely on any instrumentation engine, we have to manually track the satisfied conditions by `singals_set` in our harness:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-05/src/main.rs:signals}}
|
extern crate libafl;
|
||||||
|
use libafl::{
|
||||||
|
bolts::AsSlice,
|
||||||
|
inputs::{BytesInput, HasTargetBytes},
|
||||||
|
executors::ExitKind,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Coverage map with explicit assignments due to the lack of instrumentation
|
||||||
|
static mut SIGNALS: [u8; 16] = [0; 16];
|
||||||
|
|
||||||
|
fn signals_set(idx: usize) {
|
||||||
|
unsafe { SIGNALS[idx] = 1 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The closure that we want to fuzz
|
||||||
|
let mut harness = |input: &BytesInput| {
|
||||||
|
let target = input.target_bytes();
|
||||||
|
let buf = target.as_slice();
|
||||||
|
signals_set(0); // set SIGNALS[0]
|
||||||
|
if buf.len() > 0 && buf[0] == 'a' as u8 {
|
||||||
|
signals_set(1); // set SIGNALS[1]
|
||||||
|
if buf.len() > 1 && buf[1] == 'b' as u8 {
|
||||||
|
signals_set(2); // set SIGNALS[2]
|
||||||
|
if buf.len() > 2 && buf[2] == 'c' as u8 {
|
||||||
|
panic!("=)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ExitKind::Ok
|
||||||
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
The observer can be created directly from the `SIGNALS` map, in the following way:
|
The observer can be created directly from the `SIGNALS` map, in the following way:
|
||||||
|
|
||||||
```rust
|
```rust,ignore
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-05/src/main.rs:observer}}
|
// Create an observation channel using the signals map
|
||||||
|
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS });
|
||||||
```
|
```
|
||||||
|
|
||||||
The observers are usually kept in the corresponding executor as they keep track of information that is valid for just one run. We have then to modify our InProcessExecutor creation to include the observer as follows:
|
The observers are usually kept in the corresponding executor as they keep track of information that is valid for just one run. We have then to modify our InProcessExecutor creation to include the observer as follows:
|
||||||
|
|
||||||
```rust
|
```rust,ignore
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-05/src/main.rs:executor_with_observer}}
|
// Create the executor for an in-process function with just one observer
|
||||||
|
let mut executor = InProcessExecutor::new(
|
||||||
|
&mut harness,
|
||||||
|
tuple_list!(observer),
|
||||||
|
&mut fuzzer,
|
||||||
|
&mut state,
|
||||||
|
&mut mgr,
|
||||||
|
)
|
||||||
|
.expect("Failed to create the Executor".into());
|
||||||
```
|
```
|
||||||
|
|
||||||
Now that the fuzzer can observe which condition is satisfied, we need a way to rate an input as interesting (i.e. worth of addition to the corpus) based on this observation. Here comes the notion of Feedback.
|
Now that the fuzzer can observe which condition is satisfied, we need a way to rate an input as interesting (i.e. worth of addition to the corpus) based on this observation. Here comes the notion of Feedback.
|
||||||
@ -165,23 +287,49 @@ Now that the fuzzer can observe which condition is satisfied, we need a way to r
|
|||||||
|
|
||||||
We use `MaxMapFeedback`, a feedback that implements a novelty search over the map of the MapObserver. Basically, if there is a value in the observer's map that is greater than the maximum value registered so far for the same entry, it rates the input as interesting and updates its state.
|
We use `MaxMapFeedback`, a feedback that implements a novelty search over the map of the MapObserver. Basically, if there is a value in the observer's map that is greater than the maximum value registered so far for the same entry, it rates the input as interesting and updates its state.
|
||||||
|
|
||||||
**Objective Feedback** is another kind of Feedback which decides if an input is a "solution". It will save input to solutions(`./crashes` in our case) rather than corpus when the input is rated interesting. We use `CrashFeedback` to tell the fuzzer that if an input causes the program to crash it is a solution for us.
|
**Objective Feedback** is another kind of Feedback which decide if an input is a "solution". It will save input to solutions(`./crashes` in our case) other than corpus when the input is rated interesting. We use `CrashFeedback` to tell the fuzzer that if an input causes the program to crash it is a solution for us.
|
||||||
|
|
||||||
We need to update our State creation including the feedback state and the Fuzzer including the feedback and the objective:
|
We need to update our State creation including the feedback state and the Fuzzer including the feedback and the objective:
|
||||||
|
|
||||||
```rust
|
```rust,ignore
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-05/src/main.rs:state_with_feedback_and_objective}}
|
extern crate libafl;
|
||||||
```
|
use libafl::{
|
||||||
|
bolts::{current_nanos, rands::StdRand, tuples::tuple_list},
|
||||||
|
corpus::{InMemoryCorpus, OnDiskCorpus},
|
||||||
|
feedbacks::{MaxMapFeedback, CrashFeedback},
|
||||||
|
fuzzer::StdFuzzer,
|
||||||
|
state::StdState,
|
||||||
|
observers::StdMapObserver,
|
||||||
|
};
|
||||||
|
|
||||||
Once again, you need to add the necessary `use` directives for this to work properly:
|
// Feedback to rate the interestingness of an input
|
||||||
|
let mut feedback = MaxMapFeedback::new(&observer);
|
||||||
|
|
||||||
```rust
|
// A feedback to choose if an input is a solution or not
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-05/src/main.rs:use}}
|
let mut objective = CrashFeedback::new();
|
||||||
|
|
||||||
|
// create a State from scratch
|
||||||
|
let mut state = StdState::new(
|
||||||
|
// RNG
|
||||||
|
StdRand::with_seed(current_nanos()),
|
||||||
|
// Corpus that will be evolved, we keep it in memory for performance
|
||||||
|
InMemoryCorpus::new(),
|
||||||
|
// Corpus in which we store solutions (crashes in this example),
|
||||||
|
// on disk so the user can get them after stopping the fuzzer
|
||||||
|
OnDiskCorpus::new(PathBuf::from("./crashes")).unwrap(),
|
||||||
|
&mut feedback,
|
||||||
|
&mut objective
|
||||||
|
).unwrap();
|
||||||
|
|
||||||
|
// ...
|
||||||
|
|
||||||
|
// A fuzzer with feedbacks and a corpus scheduler
|
||||||
|
let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);
|
||||||
```
|
```
|
||||||
|
|
||||||
## The actual fuzzing
|
## The actual fuzzing
|
||||||
|
|
||||||
Now, we can run the program, but the outcome is not so different from the previous one as the random generator does not take into account what we save as interesting in the corpus. To do that, we need to plug a Mutator.
|
Now, after including the correct `use`, we can run the program, but the outcome is not so different from the previous one as the random generator does not take into account what we save as interesting in the corpus. To do that, we need to plug a Mutator.
|
||||||
|
|
||||||
**Stages** perform actions on individual inputs, taken from the corpus.
|
**Stages** perform actions on individual inputs, taken from the corpus.
|
||||||
For instance, the `MutationalStage` executes the harness several times in a row, every time with mutated inputs.
|
For instance, the `MutationalStage` executes the harness several times in a row, every time with mutated inputs.
|
||||||
@ -189,20 +337,28 @@ For instance, the `MutationalStage` executes the harness several times in a row,
|
|||||||
As the last step, we create a MutationalStage that uses a mutator inspired by the havoc mutator of AFL.
|
As the last step, we create a MutationalStage that uses a mutator inspired by the havoc mutator of AFL.
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-06/src/main.rs:mutational_stage}}
|
use libafl::{
|
||||||
|
mutators::scheduled::{havoc_mutations, StdScheduledMutator},
|
||||||
|
stages::mutational::StdMutationalStage,
|
||||||
|
fuzzer::Fuzzer,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ...
|
||||||
|
|
||||||
|
// Setup a mutational stage with a basic bytes mutator
|
||||||
|
let mutator = StdScheduledMutator::new(havoc_mutations());
|
||||||
|
let mut stages = tuple_list!(StdMutationalStage::new(mutator));
|
||||||
|
|
||||||
|
fuzzer
|
||||||
|
.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)
|
||||||
|
.expect("Error in the fuzzing loop");
|
||||||
```
|
```
|
||||||
|
|
||||||
`fuzz_loop` will request a testcase for each iteration to the fuzzer using the scheduler and then it will invoke the stage.
|
`fuzz_loop` will request a testcase for each iteration to the fuzzer using the scheduler and then it will invoke the stage.
|
||||||
|
|
||||||
Again, we need to add the new `use` directives:
|
After adding this code, we have a proper fuzzer, that can run a find the input that panics the function in less than a second.
|
||||||
|
|
||||||
```rust,ignore
|
```text
|
||||||
{{#rustdoc_include ../../listings/baby_fuzzer/listing-06/src/main.rs:use}}
|
|
||||||
```
|
|
||||||
|
|
||||||
After adding this code, we have a proper fuzzer, that can run and find the input that panics the function in less than a second.
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ cargo run
|
$ cargo run
|
||||||
Compiling baby_fuzzer v0.1.0 (/home/andrea/Desktop/baby_fuzzer)
|
Compiling baby_fuzzer v0.1.0 (/home/andrea/Desktop/baby_fuzzer)
|
||||||
Finished dev [unoptimized + debuginfo] target(s) in 1.56s
|
Finished dev [unoptimized + debuginfo] target(s) in 1.56s
|
||||||
|
@ -9,4 +9,4 @@ Examples can be found under `./fuzzer`.
|
|||||||
| baby_fuzzer_nautilus | [nautilus](https://www.ndss-symposium.org/wp-content/uploads/2019/02/ndss2019_04A-3_Aschermann_paper.pdf) is a **coverage guided, grammar based** fuzzer|
|
| baby_fuzzer_nautilus | [nautilus](https://www.ndss-symposium.org/wp-content/uploads/2019/02/ndss2019_04A-3_Aschermann_paper.pdf) is a **coverage guided, grammar based** fuzzer|
|
||||||
|baby_fuzzer_tokens| basic **token level** fuzzer with token level mutations|
|
|baby_fuzzer_tokens| basic **token level** fuzzer with token level mutations|
|
||||||
|baby_fuzzer_with_forkexecutor| example for **InProcessForkExecutor**|
|
|baby_fuzzer_with_forkexecutor| example for **InProcessForkExecutor**|
|
||||||
|baby_no_std|a minimalistic example how to create a libafl based fuzzer that works on **`no_std`** environments like TEEs, Kernels or on bare metal|
|
|baby_no_std|a minimalistic example how to create a libafl based fuzzer that works on **`no_std`** environments like TEEs, Kernels or on barew metal|
|
||||||
|
@ -4,8 +4,8 @@ The Corpus is where testcases are stored. We define a Testcase as an Input and a
|
|||||||
|
|
||||||
A Corpus can store testcases in different ways, for example on disk, or in memory, or implement a cache to speedup on disk storage.
|
A Corpus can store testcases in different ways, for example on disk, or in memory, or implement a cache to speedup on disk storage.
|
||||||
|
|
||||||
Usually, a testcase is added to the Corpus when it is considered as interesting, but a Corpus is used also to store testcases that fulfill an objective (like crashing the program under test for instance).
|
Usually, a testcase is added to the Corpus when it is considered as interesting, but a Corpus is used also to store testcases that fulfill an objective (like crashing the tested program for instance).
|
||||||
|
|
||||||
Related to the Corpus is the way in which the next testcase (the fuzzer would ask for) is retrieved from the Corpus. The taxonomy for this handling in LibAFL is CorpusScheduler, the entity representing the policy to pop testcases from the Corpus, in a FIFO fashion for instance.
|
Related to the Corpus, there is the way in which the fuzzer should ask for the next testcase to fuzz picking it from the Corpus. The taxonomy for this in LibAFL is CorpusScheduler, the entity representing the policy to pop testcases from the Corpus, FIFO for instance.
|
||||||
|
|
||||||
Speaking about the code, [`Corpus`](https://docs.rs/libafl/0/libafl/corpus/trait.Corpus.html) and [`CorpusScheduler`](https://docs.rs/libafl/0/libafl/corpus/trait.CorpusScheduler.html) are traits.
|
Speaking about the code, [`Corpus`](https://docs.rs/libafl/0/libafl/corpus/trait.Corpus.html) and [`CorpusScheduler`](https://docs.rs/libafl/0/libafl/corpus/trait.CorpusScheduler.html) are traits.
|
||||||
|
@ -13,7 +13,7 @@ In Rust, we bind this concept to the [`Executor`](https://docs.rs/libafl/0/libaf
|
|||||||
|
|
||||||
By default, we implement some commonly used Executors such as [`InProcessExecutor`](https://docs.rs/libafl/0/libafl/executors/inprocess/struct.InProcessExecutor.html) in which the target is a harness function providing in-process crash detection. Another Executor is the [`ForkserverExecutor`](https://docs.rs/libafl/0/libafl/executors/forkserver/struct.ForkserverExecutor.html) that implements an AFL-like mechanism to spawn child processes to fuzz.
|
By default, we implement some commonly used Executors such as [`InProcessExecutor`](https://docs.rs/libafl/0/libafl/executors/inprocess/struct.InProcessExecutor.html) in which the target is a harness function providing in-process crash detection. Another Executor is the [`ForkserverExecutor`](https://docs.rs/libafl/0/libafl/executors/forkserver/struct.ForkserverExecutor.html) that implements an AFL-like mechanism to spawn child processes to fuzz.
|
||||||
|
|
||||||
A common pattern when creating an Executor is wrapping an existing one, for instance [`TimeoutExecutor`](https://docs.rs/libafl/0.6.1/libafl/executors/timeout/struct.TimeoutExecutor.html) wraps an executor and installs a timeout callback before calling the original `run` function of the wrapped executor.
|
A common pattern when creating an Executor is wrapping an existing one, for instance [`TimeoutExecutor`](https://docs.rs/libafl/0.6.1/libafl/executors/timeout/struct.TimeoutExecutor.html) wraps an executor and install a timeout callback before calling the original run function of the wrapped executor.
|
||||||
|
|
||||||
## InProcessExecutor
|
## InProcessExecutor
|
||||||
Let's begin with the base case; `InProcessExecutor`.
|
Let's begin with the base case; `InProcessExecutor`.
|
||||||
@ -24,7 +24,7 @@ When you want to execute the harness as fast as possible, you will most probably
|
|||||||
One thing to note here is, when your harness is likely to have heap corruption bugs, you want to use another allocator so that corrupted heap does not affect the fuzzer itself. (For example, we adopt MiMalloc in some of our fuzzers.). Alternatively you can compile your harness with address sanitizer to make sure you can catch these heap bugs.
|
One thing to note here is, when your harness is likely to have heap corruption bugs, you want to use another allocator so that corrupted heap does not affect the fuzzer itself. (For example, we adopt MiMalloc in some of our fuzzers.). Alternatively you can compile your harness with address sanitizer to make sure you can catch these heap bugs.
|
||||||
|
|
||||||
## ForkserverExecutor
|
## ForkserverExecutor
|
||||||
Next, we'll take a look at the `ForkserverExecutor`. In this case, it is `afl-cc` (from AFLplusplus/AFLplusplus) that compiles the harness code, and therefore, we can't use `EDGES_MAP` anymore. Fortunately we have [_a way_](https://github.com/AFLplusplus/AFLplusplus/blob/2e15661f184c77ac1fbb6f868c894e946cbb7f17/instrumentation/afl-compiler-rt.o.c#L270) to tell the forkserver which map to record the coverage in.
|
Next, we'll take a look at the `ForkserverExecutor`. In this case, it is `afl-cc` (from AFLplusplus/AFLplusplus) that compiles the harness code, and therefore, we can't use `EDGES_MAP` anymore. Hopefully, we have [_a way_](https://github.com/AFLplusplus/AFLplusplus/blob/2e15661f184c77ac1fbb6f868c894e946cbb7f17/instrumentation/afl-compiler-rt.o.c#L270) to tell the forkserver which map to record the coverage.
|
||||||
|
|
||||||
As you can see from the forkserver example,
|
As you can see from the forkserver example,
|
||||||
|
|
||||||
@ -48,7 +48,7 @@ See AFL++'s [_documentation_](https://github.com/AFLplusplus/AFLplusplus/blob/st
|
|||||||
Finally, we'll talk about the `InProcessForkExecutor`.
|
Finally, we'll talk about the `InProcessForkExecutor`.
|
||||||
`InProcessForkExecutor` has only one difference from `InprocessExecutor`; It forks before running the harness and that's it.
|
`InProcessForkExecutor` has only one difference from `InprocessExecutor`; It forks before running the harness and that's it.
|
||||||
|
|
||||||
But why do we want to do so? Well, under some circumstances, you may find your harness pretty unstable or your harness wreaks havoc on the global states. In this case, you want to fork it before executing the harness runs in the child process so that it doesn't break things.
|
But why do we want to do so? well, under some circumstances, you may find your harness pretty unstable or your harness wreaks havoc on the global states. In this case, you want to fork it before executing the harness runs in the child process so that it doesn't break things.
|
||||||
|
|
||||||
However, we have to take care of the shared memory, it's the child process that runs the harness code and writes the coverage to the map.
|
However, we have to take care of the shared memory, it's the child process that runs the harness code and writes the coverage to the map.
|
||||||
|
|
||||||
|
@ -10,25 +10,17 @@ The concept of "interestingness" is abstract, but typically it is related to a n
|
|||||||
|
|
||||||
As an example, given an Observer that reports all the sizes of memory allocations, a maximization Feedback can be used to maximize these sizes to sport pathological inputs in terms of memory consumption.
|
As an example, given an Observer that reports all the sizes of memory allocations, a maximization Feedback can be used to maximize these sizes to sport pathological inputs in terms of memory consumption.
|
||||||
|
|
||||||
In terms of code, the library offers the [`Feedback`](https://docs.rs/libafl/0/libafl/feedbacks/trait.Feedback.html) trait.
|
In terms of code, the library offers the [`Feedback`](https://docs.rs/libafl/0/libafl/feedbacks/trait.Feedback.html) and the [`FeedbackState`](https://docs.rs/libafl/0/libafl/feedbacks/trait.FeedbackState.html) traits.
|
||||||
It is used to implement functors that, given the state of the observers from the last execution, tells if the execution was interesting.
|
The first is used to implement functors that, given the state of the observers from the last execution, tells if the execution was interesting. The second is tied with `Feedback` and it is the state of the data that the feedback wants to persist in the fuzzers's state, for instance the cumulative map holding all the edges seen so far in the case of a feedback based on edge coverage.
|
||||||
So to speak, it reduces the observations to a boolean result of [`is_interesting`](https://docs.rs/libafl/0/libafl/feedbacks/trait.Feedback.html#tymethod.is_interesting) - or not.
|
|
||||||
For this, a `Feedback` can store anything it wants to persist in the fuzzers's state.
|
|
||||||
This might be, for instance, the cumulative map of all edges seen so far, in the case of a feedback based on edge coverage.
|
|
||||||
This can be achieved by adding `Metadata` in [`init_state`](https://docs.rs/libafl/0/libafl/feedbacks/trait.Feedback.html#method.init_state) and accessing it later in `is_interesting`.
|
|
||||||
`Feedback` can also add custom metadata to a newly created [`Testcase`](https://docs.rs/libafl/0/libafl/corpus/testcase/struct.Testcase.html) using [`append_metadata`](https://docs.rs/libafl/0.10.1/libafl/feedbacks/trait.Feedback.html#method.append_metadata).
|
|
||||||
|
|
||||||
Multiple Feedbacks can be combined into a boolean expression, considering for instance an execution as interesting if it triggers new code paths or execute in less time compared to the average execution time using [`feedback_or`](https://docs.rs/libafl/*/libafl/macro.feedback_or.html).
|
Multiple Feedbacks can be combined into boolean formula, considering for instance an execution as interesting if it triggers new code paths or execute in less time compared to the average execution time using [`feedback_or`](https://docs.rs/libafl/*/libafl/macro.feedback_or.html).
|
||||||
|
|
||||||
On top, logic operators like `feedback_or` and `feedback_and` have a `_fast` variant (e.g. `feedback_or_fast`) where the second feedback will not be evaluated, if the value of the first feedback operand already answers the `interestingness` question so as to save precious performance.
|
On top, logic operators like `feedback_or` and `feedback_and` have a `_fast` option (`feedback_or_fast` where the second feedback will not be evaluated, if the first part already answers the `interestingness` question, to save precious performance.
|
||||||
|
|
||||||
Using `feedback_and_fast` in combination with [`ConstFeedback`](https://docs.rs/libafl/*/libafl/feedbacks/enum.ConstFeedback.html#method.new), certain feedbacks can be disabled dynamically.
|
Using `feedback_and_fast` in combination with [`ConstFeedback`](https://docs.rs/libafl/*/libafl/feedbacks/enum.ConstFeedback.html#method.new), certain feedbacks can be disabled dynamically.
|
||||||
|
|
||||||
## Objectives
|
## Objectives
|
||||||
|
|
||||||
While feedbacks are commonly used to decide if an [`Input`](https://docs.rs/libafl/*/libafl/inputs/trait.Input.html) should be kept for future mutations, they serve a double-purpose, as so-called `Objective Feedbacks`.
|
While feedbacks are commonly used to decide if an [`Input`](https://docs.rs/libafl/*/libafl/inputs/trait.Input.html) should be kept for future mutations, they serve a double-purpose, as so-called `Objective Feedbacks`.
|
||||||
In this case, the `interestingness` of a feedback indicates if an `Objective` has been hit.
|
In this case, the `interestingness` of a feedback indicates, if an `Objective` has been hit.
|
||||||
Commonly, these objectives would be a crash or a timeout, but they can also be used to detect if specific parts of the program have been reached, for sanitization, or a differential fuzzing success.
|
Commonly, these would be a`crash or a timeout, but they can also be used to find specific parts of the program, for sanitization, or a differential fuzzing success.
|
||||||
Objectives use the same trait as a normal [`Feedback`](https://docs.rs/libafl/0/libafl/feedbacks/trait.Feedback.html) and the implementations can be used interchangeably.
|
|
||||||
|
|
||||||
The only difference is that `interesting` Objectives won't be mutated further, and are counted as `Solutions`, a successful fuzzing campaign.
|
|
||||||
|
@ -6,10 +6,10 @@ In our model of an abstract fuzzer, we define the Input as the internal represen
|
|||||||
|
|
||||||
In the straightforward case, the input of the program is a byte array and in fuzzers such as AFL we store and manipulate exactly these byte arrays.
|
In the straightforward case, the input of the program is a byte array and in fuzzers such as AFL we store and manipulate exactly these byte arrays.
|
||||||
|
|
||||||
But it is not always the case. A program can expect inputs that are not linear byte arrays (e.g. a sequence of syscalls forming a use case or protocol) and the fuzzer does not represent the Input in the same way that the program consumes it.
|
But it is not always the case. A program can expect inputs that are not byte arrays (e.g. a sequence of syscalls) and the fuzzer does not represent the Input in the same way that the program consumes it.
|
||||||
|
|
||||||
In case of a grammar fuzzer for instance, the Input is generally an Abstract Syntax Tree because it is a data structure that can be easily manipulated while maintaining the validity, but the program expects a byte array as input, so just before the execution, the tree is serialized to a sequence of bytes.
|
In case of a grammar fuzzer for instance, the Input is generally an Abstract Syntax Tree because it is a data structure that can be easily manipulated while maintaining the validity, but the program expects a byte array as input, so just before the execution, the tree is serialized to a sequence of bytes.
|
||||||
|
|
||||||
In the Rust code, an [`Input`](https://docs.rs/libafl/*/libafl/inputs/trait.Input.html) is a trait that can be implemented only by structures that are serializable and have only owned data as fields.
|
In the Rust code, an [`Input`](https://docs.rs/libafl/*/libafl/inputs/trait.Input.html) is a trait that can be implemented only by structures that are serializable and have only owned data as fields.
|
||||||
|
|
||||||
While most fuzzers use a normal `BytesInput`, more advanced ones use inputs that include special inputs for grammar fuzzing ([GramatronInput](https://docs.rs/libafl/*/libafl/inputs/gramatron/struct.GramatronInput.html) or `NautilusInput` on Rust nightly), as well as the token-level [EncodedInput](https://docs.rs/libafl/*/libafl/inputs/encoded/struct.EncodedInput.html).
|
While most fuzzer use a normal `BytesInput`], more advanced inputs like inputs include special inputs for grammar fuzzing ([GramatronInput](https://docs.rs/libafl/*/libafl/inputs/gramatron/struct.GramatronInput.html) or `NautilusInput` on nightly), as well as the token-level [EncodedInput](https://docs.rs/libafl/*/libafl/inputs/encoded/struct.EncodedInput.html).
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
# Mutator
|
# Mutator
|
||||||
|
|
||||||
The Mutator is an entity that takes one or more Inputs and generates a new instance of Input derived by its inputs.
|
The Mutator is an entity that takes one or more Inputs and generates a new derived one.
|
||||||
|
|
||||||
Mutators can be composed, and they are generally linked to a specific Input type.
|
Mutators can be composed, and they are generally linked to a specific Input type.
|
||||||
|
|
||||||
There can be, for instance, a Mutator that applies more than a single type of mutation to the input. Consider a generic Mutator for a byte stream, bit flip is just one of the possible mutations but not the only one, there is also, for instance, the random replacement of a byte of the copy of a chunk.
|
There can be, for instance, a Mutator that applies more than a single type of mutation on the input. Consider a generic Mutator for a byte stream, bit flip is just one of the possible mutations but not the only one, there is also, for instance, the random replacement of a byte of the copy of a chunk.
|
||||||
|
|
||||||
In LibAFL, [`Mutator`](https://docs.rs/libafl/*/libafl/mutators/trait.Mutator.html) is a trait.
|
In LibAFL, [`Mutator`](https://docs.rs/libafl/*/libafl/mutators/trait.Mutator.html) is a trait.
|
||||||
|
@ -4,8 +4,8 @@ An Observer is an entity that provides an information observed during the execut
|
|||||||
|
|
||||||
The information contained in the Observer is not preserved across executions, but it may be serialized and passed on to other nodes if an `Input` is considered `interesting`, and added to the `Corpus`.
|
The information contained in the Observer is not preserved across executions, but it may be serialized and passed on to other nodes if an `Input` is considered `interesting`, and added to the `Corpus`.
|
||||||
|
|
||||||
As an example, the coverage map, filled during the execution to report the executed edges used by fuzzers such as AFL and `HonggFuzz` can be considered an observation. Another `Observer` can collect the time spent executing a run, the program output, or a more advanced observation, like maximum stack depth at runtime.
|
As an example, the coverage map, filled during the execution to report the executed edges used by fuzzers such as AFL and `HonggFuzz` can be considered an observation. Another `Observer` can be the time spent executing a run, the program output, or more advanced observation, like maximum stack depth at runtime.
|
||||||
This information is an observation of a dynamic property of the program.
|
This information is not preserved across runs, and it is an observation of a dynamic property of the program.
|
||||||
|
|
||||||
In terms of code, in the library this entity is described by the [`Observer`](https://docs.rs/libafl/0/libafl/observers/trait.Observer.html) trait.
|
In terms of code, in the library this entity is described by the [`Observer`](https://docs.rs/libafl/0/libafl/observers/trait.Observer.html) trait.
|
||||||
|
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
# Stage
|
# Stage
|
||||||
|
|
||||||
A Stage is an entity that operates on a single Input received from the Corpus.
|
A Stage is an entity that operates on a single Input got from the Corpus.
|
||||||
|
|
||||||
For instance, a Mutational Stage, given an input of the corpus, applies a Mutator and executes the generated input one or more times. How many times this has to be done can be scheduled, AFL for instance uses a performance score of the input to choose how many times the havoc mutator should be invoked. This can depend also on other parameters, for instance, the length of the input if we want to just apply a sequential bitflip, or a fixed value.
|
For instance, a Mutational Stage, given an input of the corpus, applies a Mutator and executes the generated input one or more time. How many times this has to be done can be scheduled, AFL for instance uses a performance score of the input to choose how many times the havoc mutator should be invoked. This can depend also on other parameters, for instance, the length of the input if we want to just apply a sequential bitflip, or be a fixed value.
|
||||||
|
|
||||||
A stage can also be an analysis stage, for instance, the Colorization stage of Redqueen that aims to introduce more entropy in a testcase or the Trimming stage of AFL that aims to reduce the size of a testcase.
|
A stage can also be an analysis stage, for instance, the Colorization stage of Redqueen that aims to introduce more entropy in a testcase or the Trimming stage of AFL that aims to reduce the size of a testcase.
|
||||||
|
|
||||||
|
@ -10,6 +10,6 @@ Thinking about similar fuzzers, you can observe that most of the time the data s
|
|||||||
|
|
||||||
Beside the entities previously described, we introduce the [`Testcase`](https://docs.rs/libafl/0.6/libafl/corpus/testcase/struct.Testcase.html) and [`State`](https://docs.rs/libafl/0.6/libafl/state/struct.StdState.html) entities. The Testcase is a container for an Input stored in the Corpus and its metadata (so, in the implementation, the Corpus stores Testcases) and the State contains all the metadata that are evolved while running the fuzzer, Corpus included.
|
Beside the entities previously described, we introduce the [`Testcase`](https://docs.rs/libafl/0.6/libafl/corpus/testcase/struct.Testcase.html) and [`State`](https://docs.rs/libafl/0.6/libafl/state/struct.StdState.html) entities. The Testcase is a container for an Input stored in the Corpus and its metadata (so, in the implementation, the Corpus stores Testcases) and the State contains all the metadata that are evolved while running the fuzzer, Corpus included.
|
||||||
|
|
||||||
The State, in the implementation, contains only owned objects that are serializable, and it is serializable itself. Some fuzzers may want to serialize their state when pausing or just, when doing in-process fuzzing, serialize on crash and deserialize in the new process to continue to fuzz with all the metadata preserved.
|
The State, in the implementation, contains only owned objects that are serializable, and it is serializable itself. Some fuzzers may want to serialize its state when pausing or just, when doing in-process fuzzing, serialize on crash and deserialize in the new process to continue to fuzz with all the metadata preserved.
|
||||||
|
|
||||||
Additionally, we group the entities that are "actions", like the `CorpusScheduler` and the `Feedbacks`, in a common place, the [`Fuzzer'](https://docs.rs/libafl/*/libafl/fuzzer/struct.StdFuzzer.html).
|
Additionally, we group the entities that are "actions", like the `CorpusScheduler` and the `Feedbacks`, in a common place, the [`Fuzzer'](https://docs.rs/libafl/*/libafl/fuzzer/struct.StdFuzzer.html).
|
||||||
|
@ -5,10 +5,10 @@ A metadata in LibAFL is a self-contained structure that holds associated data to
|
|||||||
In terms of code, a metadata can be defined as a Rust struct registered in the SerdeAny register.
|
In terms of code, a metadata can be defined as a Rust struct registered in the SerdeAny register.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
# extern crate libafl_bolts;
|
extern crate libafl;
|
||||||
# extern crate serde;
|
extern crate serde;
|
||||||
|
|
||||||
use libafl_bolts::SerdeAny;
|
use libafl::SerdeAny;
|
||||||
use serde::{Serialize, Deserialize};
|
use serde::{Serialize, Deserialize};
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, SerdeAny)]
|
#[derive(Debug, Serialize, Deserialize, SerdeAny)]
|
||||||
@ -19,7 +19,7 @@ pub struct MyMetadata {
|
|||||||
|
|
||||||
The struct must be static, so it cannot hold references to borrowed objects.
|
The struct must be static, so it cannot hold references to borrowed objects.
|
||||||
|
|
||||||
As an alternative to `derive(SerdeAny)` which is a proc-macro in `libafl_derive` the user can use `libafl_bolts::impl_serdeany!(MyMetadata);`.
|
As an alternative to `derive(SerdeAny)` that is a proc-macro in `libafl_derive` the user can use `libafl::impl_serdeany!(MyMetadata);`.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
@ -1,27 +0,0 @@
|
|||||||
# Migrating from LibAFL <0.11 to 0.11
|
|
||||||
|
|
||||||
We moved the old `libafl::bolts` module to its own crate called `libafl_bolts`.
|
|
||||||
For this, imports for types in LibAFL bolts have changed in version 0.11, everything else should remain the same.
|
|
||||||
|
|
||||||
## Reasons for This Change
|
|
||||||
|
|
||||||
With the change we can now use a lot of low-level features of LibAFL for projects that are unrelated to fuzzing, or just completely different to LibAFL.
|
|
||||||
Some cross-platform things in bolts include
|
|
||||||
|
|
||||||
* SerdeAnyMap: a map that stores and retrieves elements by type and is serializable and deserializable
|
|
||||||
* ShMem: A cross-platform (Windows, Linux, Android, MacOS) shared memory implementation
|
|
||||||
* LLMP: A fast, lock-free IPC mechanism via SharedMap
|
|
||||||
* Core_affinity: A maintained version of `core_affinity` that can be used to get core information and bind processes to cores
|
|
||||||
* Rands: Fast random number generators for fuzzing (like [RomuRand](http://www.romu-random.org/))
|
|
||||||
* MiniBSOD: get and print information about the current process state including important registers.
|
|
||||||
* Tuples: Haskel-like compile-time tuple lists
|
|
||||||
* Os: OS specific stuff like signal handling, windows exception handling, pipes, and helpers for `fork`
|
|
||||||
|
|
||||||
## What changed
|
|
||||||
|
|
||||||
You will need to move all `libafl::bolts::` imports to `libafl_bolts:::` and add the crate dependency in your Cargo.toml (and specify feature flags there).
|
|
||||||
As only exception, the `libafl::bolts::launcher::Launcher` has moved to `libafl::events::launcher::Launcher` since it has fuzzer and `EventManager` specific code.
|
|
||||||
If you are using `prelude`, you may need to also ad `libafl_bolts::prelude`.
|
|
||||||
|
|
||||||
That's it.
|
|
||||||
Enjoy using `libafl_bolts` in other projects.
|
|
@ -75,7 +75,7 @@ where
|
|||||||
```
|
```
|
||||||
|
|
||||||
The executor is constrained to `EM` and `Z`, with each of their respective states being constrained to `E`'s state. It
|
The executor is constrained to `EM` and `Z`, with each of their respective states being constrained to `E`'s state. It
|
||||||
is no longer necessary to explicitly define a generic for the input type, the state type, or the generic type, as these
|
is no longer necessary to explicitly defined a generic for the input type, the state type, or the generic type, as these
|
||||||
are all present as associated types for `E`. Additionally, we don't even need to specify any details about the observers
|
are all present as associated types for `E`. Additionally, we don't even need to specify any details about the observers
|
||||||
(`OT` in the previous version) as the type does not need to be constrained and is not shared by other types.
|
(`OT` in the previous version) as the type does not need to be constrained and is not shared by other types.
|
||||||
|
|
||||||
@ -101,7 +101,7 @@ See `fuzzers/` for examples of these changes.
|
|||||||
If you implemented a Mutator, Executor, State, or another kind of component, you must update your implementation. The
|
If you implemented a Mutator, Executor, State, or another kind of component, you must update your implementation. The
|
||||||
main changes to the API are in the use of "Uses*" for associated types.
|
main changes to the API are in the use of "Uses*" for associated types.
|
||||||
|
|
||||||
In many scenarios, Input, Observer, and State generics have been moved into traits with associated types (namely,
|
In many scenarios, Input, Observers, and State generics have been moved into traits with associated types (namely,
|
||||||
"UsesInput", "UsesObservers", and "UsesState". These traits are required for many existing traits now and are very
|
"UsesInput", "UsesObservers", and "UsesState". These traits are required for many existing traits now and are very
|
||||||
straightforward to implement. In a majority of cases, you will have generics on your custom implementation or a fixed
|
straightforward to implement. In a majority of cases, you will have generics on your custom implementation or a fixed
|
||||||
type to implement this with. Thankfully, Rust will let you know when you need to implement this type.
|
type to implement this with. Thankfully, Rust will let you know when you need to implement this type.
|
||||||
@ -127,7 +127,7 @@ where
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
After 0.9, all `Corpus` implementations are required to implement `UsesInput`. Also `Corpus` no longer has a generic for
|
After 0.9, all `Corpus` implementations are required to implement `UsesInput` and `Corpus` no longer has a generic for
|
||||||
the input type (as it is now provided by the UsesInput impl). The migrated implementation is shown below:
|
the input type (as it is now provided by the UsesInput impl). The migrated implementation is shown below:
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
@ -160,26 +160,3 @@ Now, `Corpus` cannot be accidentally implemented for another type other than tha
|
|||||||
is fixed to the associated type for `UsesInput`.
|
is fixed to the associated type for `UsesInput`.
|
||||||
|
|
||||||
A more complex example of migration can be found in the "Reasons for this change" section of this document.
|
A more complex example of migration can be found in the "Reasons for this change" section of this document.
|
||||||
|
|
||||||
## Observer Changes
|
|
||||||
|
|
||||||
Additionally, we changed the Observer API, as the API in 0.8 led to undefined behavior.
|
|
||||||
At the same time, we used the change to simplify the common case: creating an `StdMapObserver`
|
|
||||||
from libafl_target's `EDGES_MAP`.
|
|
||||||
In the future, instead of using:
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] };
|
|
||||||
let edges_observer = StdMapObserver::new("edges", edges);
|
|
||||||
```
|
|
||||||
|
|
||||||
creating the edges observer is as simple as using the new `std_edges_map_observer` function.
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
let edges_observer = unsafe { std_edges_map_observer("edges") };
|
|
||||||
```
|
|
||||||
|
|
||||||
Alternatively, `StdMapObserver::new` will still work, but now the whole method is marked as `unsafe`.
|
|
||||||
The reason is that the caller has to make sure `EDGES_MAP` (or other maps) are not moved or freed in memory,
|
|
||||||
for the lifetime of the `MapObserver`.
|
|
||||||
This means that the buffer should either be `static` or `Pin`.
|
|
||||||
|
@ -6,7 +6,7 @@ LibAFL, as most of the Rust projects, can be built using `cargo` from the root d
|
|||||||
$ cargo build --release
|
$ cargo build --release
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that the `--release` flag is optional for development, but you need to add it to do fuzzing at a decent speed.
|
Note that the `--release` flag is optional for development, but you needed to add it to fuzzing at a decent speed.
|
||||||
Slowdowns of 10x or more are not uncommon for Debug builds.
|
Slowdowns of 10x or more are not uncommon for Debug builds.
|
||||||
|
|
||||||
The LibAFL repository is composed of multiple crates.
|
The LibAFL repository is composed of multiple crates.
|
||||||
|
@ -10,7 +10,7 @@ libafl = { version = "*" }
|
|||||||
|
|
||||||
## Crate List
|
## Crate List
|
||||||
|
|
||||||
For LibAFL, each crate has its self-contained purpose, and the user may not need to use all of them in their project.
|
For LibAFL, each crate has its self-contained purpose, and the user may not need to use all of them in its project.
|
||||||
Following the naming convention of the folders in the project's root, they are:
|
Following the naming convention of the folders in the project's root, they are:
|
||||||
|
|
||||||
### [`libafl`](https://github.com/AFLplusplus/LibAFL/tree/main/libafl)
|
### [`libafl`](https://github.com/AFLplusplus/LibAFL/tree/main/libafl)
|
||||||
@ -31,35 +31,20 @@ You can choose the features by using `features = ["feature1", "feature2", ...]`
|
|||||||
Out of this list, by default, `std`, `derive`, and `rand_trait` are already set.
|
Out of this list, by default, `std`, `derive`, and `rand_trait` are already set.
|
||||||
You can choose to disable them by setting `default-features = false` in your `Cargo.toml`.
|
You can choose to disable them by setting `default-features = false` in your `Cargo.toml`.
|
||||||
|
|
||||||
### [`libafl_bolts`](https://github.com/AFLplusplus/LibAFL/tree/main/libafl)
|
### libafl_sugar
|
||||||
|
|
||||||
The `libafl_bolts` crate is a minimal tool shed filled with useful low-level rust features, not necessarily related to fuzzers.
|
|
||||||
In it, you'll find highlights like:
|
|
||||||
|
|
||||||
- `core_affinity` to bind the current process to cores
|
|
||||||
- `SerdeAnyMap` a map that can store typed values in a serializable fashion
|
|
||||||
- `minibsod` to dump the current process state
|
|
||||||
- `LLMP`, "low level message passing", a lock-free IPC mechanism
|
|
||||||
- `Rand`, different fast (non-cryptographically secure) RNG implementations like RomuRand
|
|
||||||
- `ShMem`, a platform independent shard memory implementation
|
|
||||||
- `Tuples`, a compiletime tuple implementation
|
|
||||||
|
|
||||||
... and much more.
|
|
||||||
|
|
||||||
### `libafl_sugar`
|
|
||||||
|
|
||||||
The sugar crate abstracts away most of the complexity of LibAFL's API.
|
The sugar crate abstracts away most of the complexity of LibAFL's API.
|
||||||
Instead of high flexibility, it aims to be high-level and easy-to-use.
|
Instead of high flexibility, it aims to be high-level and easy-to-use.
|
||||||
It is not as flexible as stitching your fuzzer together from each individual component, but allows you to build a fuzzer with minimal lines of code.
|
It is not as flexible as stitching your fuzzer together from each individual component, but allows you to build a fuzzer with minimal lines of code.
|
||||||
To see it in action, take a look at the [`libfuzzer_stb_image_sugar` example fuzzer](https://github.com/AFLplusplus/LibAFL/tree/main/fuzzers/libfuzzer_stb_image_sugar).
|
To see it in action, take a look at the [`libfuzzer_stb_image_sugar` example fuzzer](https://github.com/AFLplusplus/LibAFL/tree/main/fuzzers/libfuzzer_stb_image_sugar).
|
||||||
|
|
||||||
### `libafl_derive`
|
### libafl_derive
|
||||||
|
|
||||||
This a proc-macro crate paired with the `libafl` crate.
|
This a proc-macro crate paired with the `libafl` crate.
|
||||||
|
|
||||||
At the moment, it just exposes the `derive(SerdeAny)` macro that can be used to define Metadata structs, see the section about [Metadata](../design/metadata.md) for details.
|
At the moment, it just exposes the `derive(SerdeAny)` macro that can be used to define Metadata structs, see the section about [Metadata](../design/metadata.md) for details.
|
||||||
|
|
||||||
### `libafl_targets`
|
### libafl_targets
|
||||||
|
|
||||||
This crate exposes code to interact with, and to instrument, targets.
|
This crate exposes code to interact with, and to instrument, targets.
|
||||||
To enable and disable features at compile-time, the features are enabled and disabled using feature flags.
|
To enable and disable features at compile-time, the features are enabled and disabled using feature flags.
|
||||||
@ -67,36 +52,36 @@ To enable and disable features at compile-time, the features are enabled and dis
|
|||||||
Currently, the supported flags are:
|
Currently, the supported flags are:
|
||||||
|
|
||||||
- `pcguard_edges` defines the SanitizerCoverage trace-pc-guard hooks to track the executed edges in a map.
|
- `pcguard_edges` defines the SanitizerCoverage trace-pc-guard hooks to track the executed edges in a map.
|
||||||
- `pcguard_hitcounts` defines the SanitizerCoverage trace-pc-guard hooks to track the executed edges with the hitcounts (like AFL) in a map.
|
- `pcguard_hitcounts defines the SanitizerCoverage trace-pc-guard hooks to track the executed edges with the hitcounts (like AFL) in a map.
|
||||||
- `libfuzzer` exposes a compatibility layer with libFuzzer style harnesses.
|
- `libfuzzer` exposes a compatibility layer with libFuzzer style harnesses.
|
||||||
- `value_profile` defines the SanitizerCoverage trace-cmp hooks to track the matching bits of each comparison in a map.
|
- `value_profile` defines the SanitizerCoverage trace-cmp hooks to track the matching bits of each comparison in a map.
|
||||||
|
|
||||||
### `libafl_cc`
|
### libafl_cc
|
||||||
|
|
||||||
This is a library that provides utils to wrap compilers and create source-level fuzzers.
|
This is a library that provides utils wrap compilers and create source-level fuzzers.
|
||||||
|
|
||||||
At the moment, only the Clang compiler is supported.
|
At the moment, only the Clang compiler is supported.
|
||||||
To understand it deeper, look through the tutorials and examples.
|
To understand it deeper, look through the tutorials and examples.
|
||||||
|
|
||||||
### `libafl_frida`
|
### libafl_frida
|
||||||
|
|
||||||
This library bridges LibAFL with Frida as instrumentation backend.
|
This library bridges LibAFL with Frida as instrumentation backend.
|
||||||
With this crate, you can instrument targets on Linux/macOS/Windows/Android for coverage collection.
|
With this crate, you can instrument targets on Linux/macOS/Windows/Android for coverage collection.
|
||||||
Additionally, it supports CmpLog, and AddressSanitizer instrumentation and runtimes for aarch64.
|
Additionally, it supports CmpLog, and AddressSanitizer instrumentation and runtimes for aarch64.
|
||||||
See further information, as well as usage instructions, [later in the book](../advanced_features/frida.md).
|
See further information, as well as usage instructions, [later in the book](../advanced_features/frida.md).
|
||||||
|
|
||||||
### `libafl_qemu`
|
### libafl_qemu
|
||||||
|
|
||||||
This library bridges LibAFL with QEMU user-mode to fuzz ELF cross-platform binaries.
|
This library bridges LibAFL with QEMU user-mode to fuzz ELF cross-platform binaries.
|
||||||
|
|
||||||
It works on Linux and can collect edge coverage without collisions!
|
It works on Linux and can collect edge coverage without collisions!
|
||||||
It also supports a wide range of hooks and instrumentation options.
|
It also supports a wide range of hooks and instrumentation options.
|
||||||
|
|
||||||
### `libafl_nyx`
|
### libafl_nyx
|
||||||
|
|
||||||
[Nyx](https://nyx-fuzz.com/) is a KVM-based snapshot fuzzer. `libafl_nyx` adds these capabilities to LibAFL. There is a specific section explaining usage of libafl_nyx [later in the book](../advanced_features/nyx.md).
|
[Nyx](https://nyx-fuzz.com/) is a KVM-based snapshot fuzzer. `libafl_nyx` adds these capabilities to LibAFL. There is a specific section explaining usage of libafl_nyx [later in the book](../advanced_features/nyx.md).
|
||||||
|
|
||||||
### `libafl_concolic`
|
### libafl_concolic
|
||||||
|
|
||||||
Concolic fuzzing is the combination of fuzzing and a symbolic execution engine.
|
Concolic fuzzing is the combination of fuzzing and a symbolic execution engine.
|
||||||
This can reach greater depth than normal fuzzing, and is exposed in this crate.
|
This can reach greater depth than normal fuzzing, and is exposed in this crate.
|
||||||
|
@ -11,15 +11,15 @@ The first step is to download LibAFL and all dependencies that are not automatic
|
|||||||
> previous command. Additionally, PowerShell-specific examples will use `>`
|
> previous command. Additionally, PowerShell-specific examples will use `>`
|
||||||
> rather than `$`.
|
> rather than `$`.
|
||||||
|
|
||||||
While technically you do not need to install LibAFL, but can use the version from crates.io directly, we do recommend to download or clone the GitHub version.
|
While you technically do not need to install LibAFL, but can use the version from crates.io directly, we do recommend to download or clone the GitHub version.
|
||||||
This gets you the example fuzzers, additional utilities, and latest patches.
|
This gets you the example fuzzers, additional utilities, and latest patches.
|
||||||
The easiest way to do this is to use `git`.
|
The easiest way to do this is to use `git`.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ git clone https://github.com/AFLplusplus/LibAFL.git
|
$ git clone git@github.com:AFLplusplus/LibAFL.git
|
||||||
```
|
```
|
||||||
|
|
||||||
Alternatively, on a UNIX-like machine, you can download a compressed archive and extract it with:
|
You can alternatively, on a UNIX-like machine, download a compressed archive and extract it with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
wget https://github.com/AFLplusplus/LibAFL/archive/main.tar.gz
|
wget https://github.com/AFLplusplus/LibAFL/archive/main.tar.gz
|
||||||
@ -31,7 +31,7 @@ $ ls LibAFL-main # this is the extracted folder
|
|||||||
## Clang installation
|
## Clang installation
|
||||||
|
|
||||||
One of the external dependencies of LibAFL is the Clang C/C++ compiler.
|
One of the external dependencies of LibAFL is the Clang C/C++ compiler.
|
||||||
While most of the code is written in pure Rust, we still need a C compiler because stable Rust still does not support features that some parts of LibAFL may need, such as weak linking, and LLVM builtins linking.
|
While most of the code is in pure Rust, we still need a C compiler because stable Rust still does not support features that some parts of LibAFL may need, such as weak linking, and LLVM builtins linking.
|
||||||
For these parts, we use C to expose the missing functionalities to our Rust codebase.
|
For these parts, we use C to expose the missing functionalities to our Rust codebase.
|
||||||
|
|
||||||
In addition, if you want to perform source-level fuzz testing of C/C++ applications,
|
In addition, if you want to perform source-level fuzz testing of C/C++ applications,
|
||||||
|
@ -4,10 +4,10 @@ Fuzzers are important tools for security researchers and developers alike.
|
|||||||
A wide range of state-of-the-art tools like [AFL++](https://github.com/AFLplusplus/AFLplusplus), [libFuzzer](https://llvm.org/docs/LibFuzzer.html) or [honggfuzz](https://github.com/google/honggfuzz) are available to users. They do their job in a very effective way, finding thousands of bugs.
|
A wide range of state-of-the-art tools like [AFL++](https://github.com/AFLplusplus/AFLplusplus), [libFuzzer](https://llvm.org/docs/LibFuzzer.html) or [honggfuzz](https://github.com/google/honggfuzz) are available to users. They do their job in a very effective way, finding thousands of bugs.
|
||||||
|
|
||||||
From the perspective of a power user, however, these tools are limited.
|
From the perspective of a power user, however, these tools are limited.
|
||||||
Their designs do not treat extensibility as a first-class citizen.
|
Their design does not treat extensibility as a first-class citizen.
|
||||||
Usually, a fuzzer developer can choose to either fork one of these existing tools, or to create a new fuzzer from scratch.
|
Usually, a fuzzer developer can choose to either fork one of these existing tools, or to create a new fuzzer from scratch.
|
||||||
In any case, researchers end up with tons of fuzzers, all of which are incompatible with each other.
|
In any case, researchers end up with tons of fuzzers, all of which are incompatible with each other.
|
||||||
Their outstanding features cannot just be combined for new projects.
|
Their outstanding features can not just be combined for new projects.
|
||||||
By reinventing the wheel over and over, we may completely miss out on features that are complex to reimplement.
|
By reinventing the wheel over and over, we may completely miss out on features that are complex to reimplement.
|
||||||
|
|
||||||
To tackle this issue, we created LibAFL, a library that is _not just another fuzzer_, but a collection of reusable pieces for individual fuzzers.
|
To tackle this issue, we created LibAFL, a library that is _not just another fuzzer_, but a collection of reusable pieces for individual fuzzers.
|
||||||
@ -24,11 +24,11 @@ Some highlight features currently include:
|
|||||||
This means it does not require a specific OS-dependent runtime to function.
|
This means it does not require a specific OS-dependent runtime to function.
|
||||||
Define an allocator and a way to map pages, and you are good to inject LibAFL in obscure targets like embedded devices, hypervisors, or maybe even WebAssembly?
|
Define an allocator and a way to map pages, and you are good to inject LibAFL in obscure targets like embedded devices, hypervisors, or maybe even WebAssembly?
|
||||||
- `adaptable`: Given years of experience fine-tuning *AFLplusplus* and our academic fuzzing background, we could incorporate recent fuzzing trends into LibAFL's design and make it future-proof.
|
- `adaptable`: Given years of experience fine-tuning *AFLplusplus* and our academic fuzzing background, we could incorporate recent fuzzing trends into LibAFL's design and make it future-proof.
|
||||||
To give an example, as opposed to old-school fuzzers, a `BytesInput` is just one of the potential forms of inputs:
|
To give an example, as opposed to old-skool fuzzers, a `BytesInput` is just one of the potential forms of inputs:
|
||||||
feel free to use and mutate an Abstract Syntax Tree instead, for structured fuzzing.
|
feel free to use and mutate an Abstract Syntax Tree instead, for structured fuzzing.
|
||||||
- `scalable`: As part of LibAFL, we developed `Low Level Message Passing`, `LLMP` for short, which allows LibAFL to scale almost linearly over cores. That is, if you chose to use this feature - it is your fuzzer, after all.
|
- `scalable`: As part of LibAFL, we developed `Low Level Message Passing`, `LLMP` for short, which allows LibAFL to scale almost linearly over cores. That is, if you chose to use this feature - it is your fuzzer, after all.
|
||||||
Scaling to multiple machines over TCP is also possible, using LLMP's `broker2broker` feature.
|
Scaling to multiple machines over TCP is also possible, using LLMP's `broker2broker` feature.
|
||||||
- `fast`: We do everything we can at compile time so that the runtime overhead is as minimal as it can get.
|
- `fast`: We do everything we can at compile time so that the runtime overhead is as minimal as it can get.
|
||||||
- `bring your own target`: We support binary-only modes, like (full-system) QEMU-Mode and Frida-Mode with ASan and CmpLog, as well as multiple compilation passes for sourced-based instrumentation.
|
- `bring your own target`: We support binary-only modes, like QEMU-Mode and Frida-Mode with ASAN and CmpLog, as well as multiple compilation passes for sourced-based instrumentation.
|
||||||
Of course, we also support custom instrumentation, as you can see in the Python example based on Google's Atheris.
|
Of course, we also support custom instrumentation, as you can see in the Python example based on Google's Atheris.
|
||||||
- `usable`: This one is on you to decide. Dig right in!
|
- `usable`: This one is on you to decide. Dig right in!
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
# The LibAFL Fuzzing Library
|
# The LibAFL Fuzzing Library
|
||||||
|
|
||||||
<img align="right" src="https://raw.githubusercontent.com/AFLplusplus/Website/main/static/libafl_logo.svg" alt="LibAFL Logo" style="width: 256px; height: auto">
|
<img align="right" src="https://github.com/AFLplusplus/Website/raw/master/static/logo_256x256.png" alt="AFL++ Logo">
|
||||||
|
|
||||||
*by Andrea Fioraldi and Dominik Maier*
|
*by Andrea Fioraldi and Dominik Maier*
|
||||||
|
|
||||||
Welcome to LibAFL, the Advanced Fuzzing Library.
|
Welcome to LibAFL, the Advanced Fuzzing Library.
|
||||||
This book shall be a gentle introduction to the library.
|
This book shall be a gentle introduction into the library.
|
||||||
|
|
||||||
This version of the LibAFL book is coupled with the release 1.0 beta of the library.
|
This version of the LibAFL book is coupled with the release 1.0 beta of the library.
|
||||||
|
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
Configurations for individual fuzzer nodes are relevant for multi node fuzzing.
|
Configurations for individual fuzzer nodes are relevant for multi node fuzzing.
|
||||||
The chapter describes how to run nodes with different configurations
|
The chapter describes how to run nodes with different configurations
|
||||||
in one fuzzing cluster.
|
in one fuzzing cluster.
|
||||||
This allows, for example, a node compiled with ASan, to know that it needs to rerun new testcases for a node without ASan, while the same binary/configuration does not.
|
This allows, for example, a node compiled with ASAN, to know that it needs to rerun new testcases for a node without ASAN, while the same binary/configuration does not.
|
||||||
|
|
||||||
Fuzzers with the same configuration can exchange Observers for new testcases and reuse them without rerunning the input.
|
Fuzzers with the same configuration can exchange Observers for new testcases and reuse them without rerunning the input.
|
||||||
A different configuration indicates, that only the raw input can be exchanged, it must be rerun on the other node to capture relevant observations.
|
A different configuration indicates, that only the raw input can be exchanged, it must be rerun on the other node to capture relevant observations.
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
# Message Passing
|
# Message Passing
|
||||||
|
|
||||||
LibAFL offers a standard mechanism for message passing between processes and machines with a low overhead.
|
LibAFL offers a standard mechanism for message passing over processes and machines with a low overhead.
|
||||||
We use message passing to inform the other connected clients/fuzzers/nodes about new testcases, metadata, and statistics about the current run.
|
We use message passing to inform the other connected clients/fuzzers/nodes about new testcases, metadata, and statistics about the current run.
|
||||||
Depending on individual needs, LibAFL can also write testcase contents to disk, while still using events to notify other fuzzers, using the `CachedOnDiskCorpus` or similar.
|
Depending on individual needs, LibAFL can also write testcase contents to disk, while still using events to notify other fuzzers, using an `OnDiskCorpus`.
|
||||||
|
|
||||||
In our tests, message passing scales very well to share new testcases and metadata between multiple running fuzzer instances for multi-core fuzzing.
|
In our tests, message passing scales very well to share new testcases and metadata between multiple running fuzzer instances for multi-core fuzzing.
|
||||||
Specifically, it scales _a lot_ better than using memory locks on a shared corpus, and _a lot_ better than sharing the testcases via the filesystem, as AFL traditionally does.
|
Specifically, it scales _a lot_ better than using memory locks on a shared corpus, and _a lot_ better than sharing the testcases via the filesystem, as AFL traditionally does.
|
||||||
@ -12,7 +12,7 @@ The `EventManager` interface is used to send Events over the wire using `Low Lev
|
|||||||
|
|
||||||
## Low Level Message Passing (LLMP)
|
## Low Level Message Passing (LLMP)
|
||||||
|
|
||||||
LibAFL comes with a reasonably lock-free message passing mechanism that scales well across cores and, using its _broker2broker_ mechanism, even to connected machines via TCP.
|
LibAFL comes with a reasonably lock-free message passing mechanism that scales well across cores and, using its *broker2broker* mechanism, even to connected machines via TCP.
|
||||||
Most example fuzzers use this mechanism, and it is the best `EventManager` if you want to fuzz on more than a single core.
|
Most example fuzzers use this mechanism, and it is the best `EventManager` if you want to fuzz on more than a single core.
|
||||||
In the following, we will describe the inner workings of `LLMP`.
|
In the following, we will describe the inner workings of `LLMP`.
|
||||||
|
|
||||||
@ -28,12 +28,12 @@ Shared maps, called shared memory for the sake of not colliding with Rust's `map
|
|||||||
Each client, usually a fuzzer trying to share stats and new testcases, maps an outgoing `ShMem` map.
|
Each client, usually a fuzzer trying to share stats and new testcases, maps an outgoing `ShMem` map.
|
||||||
With very few exceptions, only this client writes to this map, therefore, we do not run in race conditions and can live without locks.
|
With very few exceptions, only this client writes to this map, therefore, we do not run in race conditions and can live without locks.
|
||||||
The broker reads from all client's `ShMem` maps.
|
The broker reads from all client's `ShMem` maps.
|
||||||
It periodically checks all incoming client maps and then forwards new messages to its outgoing broadcast-`ShMem`, mapped by all connected clients.
|
It checks all incoming client maps periodically and then forwards new messages to its outgoing broadcast-`ShMem`, mapped by all connected clients.
|
||||||
|
|
||||||
To send new messages, a client places a new message at the end of their shared memory and then updates a static field to notify the broker.
|
To send new messages, a client places a new message at the end of their shared memory and then updates a static field to notify the broker.
|
||||||
Once the outgoing map is full, the sender allocates a new `ShMem` using the respective `ShMemProvider`.
|
Once the outgoing map is full, the sender allocates a new `ShMem` using the respective `ShMemProvider`.
|
||||||
It then sends the information needed to map the newly-allocated page in connected processes to the old page, using an end of page (`EOP`) message.
|
It then sends the information needed to map the newly-allocated page in connected processes to the old page, using an end of page (`EOP`) message.
|
||||||
Once the receiver maps the new page, it flags it as safe for unmapping by the sending process (to avoid race conditions if we have more than a single EOP in a short time), and then continues to read from the new `ShMem`.
|
Once the receiver maps the new page, flags it as safe for unmapping from the sending process (to avoid race conditions if we have more than a single EOP in a short time), and then continues to read from the new `ShMem`.
|
||||||
|
|
||||||
The schema for client's maps to the broker is as follows:
|
The schema for client's maps to the broker is as follows:
|
||||||
|
|
||||||
@ -54,10 +54,10 @@ After the broker received a new message from clientN, (`clientN_out->current_id
|
|||||||
|
|
||||||
The clients periodically, for example after finishing `n` mutations, check for new incoming messages by checking if (`current_broadcast_map->current_id != last_message->message_id`).
|
The clients periodically, for example after finishing `n` mutations, check for new incoming messages by checking if (`current_broadcast_map->current_id != last_message->message_id`).
|
||||||
While the broker uses the same EOP mechanism to map new `ShMem`s for its outgoing map, it never unmaps old pages.
|
While the broker uses the same EOP mechanism to map new `ShMem`s for its outgoing map, it never unmaps old pages.
|
||||||
This additional memory resources serve a good purpose: by keeping all broadcast pages around, we make sure that new clients can join in on a fuzzing campaign at a later point in time.
|
This additional memory overhead serves a good purpose: by keeping all broadcast pages around, we make sure that new clients can join in on a fuzzing campaign at a later point in time
|
||||||
They just need to re-read all broadcasted messages from start to finish.
|
They just need to re-read all broadcasted messages from start to finish.
|
||||||
|
|
||||||
So the outgoing messages flow is like this over the outgoing broadcast `Shmem`:
|
So the outgoing messages flow like this over the outgoing broadcast `Shmem`:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
[broker]
|
[broker]
|
||||||
|
@ -4,18 +4,18 @@ Multiple fuzzer instances can be spawned using different ways.
|
|||||||
|
|
||||||
## Manually, via a TCP port
|
## Manually, via a TCP port
|
||||||
|
|
||||||
The straightforward way to do Multi-Threading is to use the [`LlmpRestartingEventManager`](https://docs.rs/libafl/latest/libafl/events/llmp/struct.LlmpRestartingEventManager.html), specifically to use [`setup_restarting_mgr_std`](https://docs.rs/libafl/latest/libafl/events/llmp/fn.setup_restarting_mgr_std.html).
|
The straightforward way to do Multi-Threading is to use the `LlmpRestartingEventManager`, specifically to use `setup_restarting_mgr_std`.
|
||||||
It abstracts away all the pesky details about restarts on crash handling (for in-memory fuzzers) and multi-threading.
|
It abstracts away all the pesky details about restarts on crash handling (for in-memory fuzzers) and multi-threading.
|
||||||
With it, every instance you launch manually tries to connect to a TCP port on the local machine.
|
With it, every instance you launch manually tries to connect to a TCP port on the local machine.
|
||||||
|
|
||||||
If the port is not yet bound, this instance becomes the broker, binding itself to the port to await new clients.
|
If the port is not yet bound, this instance becomes the broker, itself binding to the port to await new clients.
|
||||||
|
|
||||||
If the port is already bound, the EventManager will try to connect to it.
|
If the port is already bound, the EventManager will try to connect to it.
|
||||||
The instance becomes a client and can now communicate with all other nodes.
|
The instance becomes a client and can now communicate with all other nodes.
|
||||||
|
|
||||||
Launching nodes manually has the benefit that you can have multiple nodes with different configurations, such as clients fuzzing with and without `ASan``.
|
Launching nodes manually has the benefit that you can have multiple nodes with different configurations, such as clients fuzzing with and without ASAN.
|
||||||
|
|
||||||
While it's called "restarting" manager, it uses `fork` on Unix-like operating systems as optimization and only actually restarts from scratch on Windows.
|
While it's called "restarting" manager, it uses `fork` on Unix operating systems as optimization and only actually restarts from scratch on Windows.
|
||||||
|
|
||||||
|
|
||||||
## Automated, with Launcher
|
## Automated, with Launcher
|
||||||
@ -23,7 +23,7 @@ While it's called "restarting" manager, it uses `fork` on Unix-like operating sy
|
|||||||
The Launcher is the lazy way to do multiprocessing.
|
The Launcher is the lazy way to do multiprocessing.
|
||||||
You can use the Launcher builder to create a fuzzer that spawns multiple nodes with one click, all using restarting event managers and the same configuration.
|
You can use the Launcher builder to create a fuzzer that spawns multiple nodes with one click, all using restarting event managers and the same configuration.
|
||||||
|
|
||||||
To use launcher, first you need to write an anonymous function `let mut run_client = |state: Option<_>, mut mgr, _core_id|{}`, which uses three parameters to create an individual fuzzer. Then you can specify the `shmem_provider`,`broker_port`,`monitor`,`cores` and other stuff through `Launcher::builder()`:
|
To use launcher, first you need to write an anonymous function `let mut run_client = |state: Option<_>, mut mgr, _core_id|{}`, which uses three parameters to create individual fuzzer. Then you can specify the `shmem_provider`,`broker_port`,`monitor`,`cores` and other stuff through `Launcher::builder()`:
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
Launcher::builder()
|
Launcher::builder()
|
||||||
@ -42,17 +42,13 @@ To use launcher, first you need to write an anonymous function `let mut run_clie
|
|||||||
This first starts a broker, then spawns `n` clients, according to the value passed to `cores`.
|
This first starts a broker, then spawns `n` clients, according to the value passed to `cores`.
|
||||||
The value is a string indicating the cores to bind to, for example, `0,2,5` or `0-3`.
|
The value is a string indicating the cores to bind to, for example, `0,2,5` or `0-3`.
|
||||||
For each client, `run_client` will be called.
|
For each client, `run_client` will be called.
|
||||||
If the launcher uses `fork`, it will hide child output, unless the settings indicate otherwise, or the `LIBAFL_DEBUG_OUTPUT` env variable is set.
|
On Windows, the Launcher will restart each client, while on Unix, it will use `fork`.
|
||||||
On Windows, the Launcher will restart each client, while on Unix-alikes, it will use `fork`.
|
|
||||||
|
|
||||||
Advanced use-cases:
|
Advanced use-cases:
|
||||||
|
|
||||||
1. To connect multiple nodes together via TCP, you can use the `remote_broker_addr`. this requires the `llmp_bind_public` compile-time feature for `LibAFL`.
|
1. To connect multiple nodes together via TCP, you can use the `remote_broker_addr`. this requires the `llmp_bind_public` compile-time feature for `LibAFL`.
|
||||||
2. To use multiple launchers for individual configurations, you can set `spawn_broker` to `false` on all instances but one.
|
2. To use multiple launchers for individual configurations, you can set `spawn_broker` to `false` on all but one.
|
||||||
3. Launcher will not select the cores automatically, so you need to specify the `cores` that you want.
|
3. Launcher will not select the cores automatically, so you need to specify the `cores` that you want.
|
||||||
4. On `Unix`, you can chose between a forking and non-forking version of Launcher by setting the `fork` feature in LibAFL. Some targets may not like forking, but it is faster than restarting processes from scratch. Windows will never fork.
|
|
||||||
5. For simple debugging, first set the `LIBAFL_DEBUG_OUTPUT` env variable to see if a child process printed anything.
|
|
||||||
6. For further debugging of fuzzer failures, it may make sense to replace `Launcher` temporarily with a [`SimpleEventManager`](https://docs.rs/libafl/latest/libafl/events/simple/struct.SimpleEventManager.html#method.new) and call your harness fn (`run_client(None, mgr, 0);`) directly, so that fuzzing runs in the same thread and is easier to debug, before moving back to `Launcher` after the bugfix.
|
|
||||||
|
|
||||||
For more examples, you can check out `qemu_launcher` and `libfuzzer_libpng_launcher` in [`./fuzzers/`](https://github.com/AFLplusplus/LibAFL/tree/main/fuzzers).
|
For more examples, you can check out `qemu_launcher` and `libfuzzer_libpng_launcher` in [`./fuzzers/`](https://github.com/AFLplusplus/LibAFL/tree/main/fuzzers).
|
||||||
|
|
||||||
|
@ -2,4 +2,4 @@
|
|||||||
|
|
||||||
In this chapter, we will build a custom fuzzer using the [Lain](https://github.com/microsoft/lain) mutator in Rust.
|
In this chapter, we will build a custom fuzzer using the [Lain](https://github.com/microsoft/lain) mutator in Rust.
|
||||||
|
|
||||||
This tutorial will introduce you to writing extensions to LibAFL like Feedbacks and Testcase's metadata.
|
This tutorial will introduce you in writing extensions to LibAFL like Feedbacks and Testcase's metadata.
|
||||||
|
@ -1,51 +1,30 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "fret"
|
name = "fret"
|
||||||
version = "0.8.2"
|
version = "0.8.2"
|
||||||
authors = ["Alwin Berger <alwin.berger@tu-dortmund.de>"]
|
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["std", "snapshot_restore", "singlecore", "restarting", "do_hash_notify_state", "config_stg", "fuzz_int" ]
|
default = ["std", "snapshot_restore", "singlecore", "restarting", "feed_systemtrace", "fuzz_int" ]
|
||||||
std = []
|
std = []
|
||||||
# Exec environemnt basics
|
|
||||||
snapshot_restore = []
|
snapshot_restore = []
|
||||||
snapshot_fast = [ "snapshot_restore" ]
|
snapshot_fast = [ "snapshot_restore" ]
|
||||||
singlecore = []
|
singlecore = []
|
||||||
restarting = ['singlecore']
|
restarting = ['singlecore']
|
||||||
run_until_saturation = []
|
trace_abbs = []
|
||||||
fuzz_int = []
|
systemstate = []
|
||||||
# information capture
|
feed_systemgraph = [ "systemstate" ]
|
||||||
observe_edges = [] # observe cfg edges
|
feed_systemtrace = [ "systemstate" ]
|
||||||
observe_hitcounts = [ "observe_edges" ] # reduces edge granularity
|
|
||||||
observe_systemstate = []
|
|
||||||
do_hash_notify_state = []
|
|
||||||
trace_stg = [ "observe_systemstate" ]
|
|
||||||
# feedbacks
|
|
||||||
feed_stg = [ "trace_stg", "observe_systemstate" ]
|
|
||||||
# feed_stg_edge = [ "feed_stg"]
|
|
||||||
feed_stg_pathhash = [ "feed_stg"]
|
|
||||||
feed_stg_abbhash = [ "feed_stg"]
|
|
||||||
feed_stg_aggregatehash = [ "feed_stg"]
|
|
||||||
mutate_stg = [ "observe_systemstate" ]
|
|
||||||
feed_longest = [ ]
|
feed_longest = [ ]
|
||||||
feed_afl = [ "observe_edges" ]
|
feed_afl = [ ]
|
||||||
feed_genetic = []
|
feed_genetic = [ ]
|
||||||
|
fuzz_int = [ ]
|
||||||
gensize_1 = [ ]
|
gensize_1 = [ ]
|
||||||
gensize_10 = [ ]
|
gensize_10 = [ ]
|
||||||
gensize_100 = [ ]
|
gensize_100 = [ ]
|
||||||
# schedulers
|
observer_hitcounts = []
|
||||||
sched_genetic = []
|
no_hash_state = []
|
||||||
sched_afl = []
|
run_until_saturation = []
|
||||||
sched_stg = []
|
|
||||||
# sched_stg_edge = ['sched_stg'] # every edge in the stg
|
|
||||||
sched_stg_pathhash = ['sched_stg'] # every path in the stg
|
|
||||||
sched_stg_abbhash = ['sched_stg'] # every path of abbs
|
|
||||||
sched_stg_aggregatehash = ['sched_stg'] # every aggregated path (order independent)
|
|
||||||
# overall_configs
|
|
||||||
config_genetic = ["gensize_100","feed_genetic","sched_genetic","trace_stg"]
|
|
||||||
config_afl = ["feed_afl","sched_afl","observe_hitcounts","trace_stg"]
|
|
||||||
config_frafl = ["feed_afl","sched_afl","feed_longest","trace_stg"]
|
|
||||||
config_stg = ["feed_stg_aggregatehash","sched_stg_aggregatehash","mutate_stg"]
|
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
lto = true
|
lto = true
|
||||||
@ -54,12 +33,9 @@ debug = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
libafl = { path = "../../libafl/" }
|
libafl = { path = "../../libafl/" }
|
||||||
libafl_bolts = { path = "../../libafl_bolts/" }
|
|
||||||
libafl_qemu = { path = "../../libafl_qemu/", features = ["arm", "systemmode"] }
|
libafl_qemu = { path = "../../libafl_qemu/", features = ["arm", "systemmode"] }
|
||||||
serde = { version = "1.0", default-features = false, features = ["alloc"] } # serialization lib
|
serde = { version = "1.0", default-features = false, features = ["alloc"] } # serialization lib
|
||||||
hashbrown = { version = "0.14.0", features = ["serde"] } # A faster hashmap, nostd compatible
|
hashbrown = { version = "0.12", features = ["serde", "ahash-compile-time-rng"] } # A faster hashmap, nostd compatible
|
||||||
petgraph = { version="0.6.4", features = ["serde-1"] }
|
petgraph = { version="0.6.0", features = ["serde-1"] }
|
||||||
ron = "0.7" # write serialized data - including hashmaps
|
ron = "0.7" # write serialized data - including hashmaps
|
||||||
rand = "0.5"
|
rand = "0.5"
|
||||||
clap = { version = "4.4.11", features = ["derive"] }
|
|
||||||
csv = "1.3.0"
|
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import csv
|
import csv
|
||||||
import os
|
import os
|
||||||
def_flags="--no-default-features --features std,snapshot_restore,singlecore,restarting,do_hash_notify_state"
|
def_flags="--no-default-features --features std,snapshot_restore,singlecore,restarting,run_until_saturation"
|
||||||
remote="remote/"
|
remote="timedump_253048_1873f6_all/"
|
||||||
RUNTIME=1800
|
RUNTIME=10
|
||||||
TARGET_REPS_A=2
|
TARGET_REPS_A=2
|
||||||
TARGET_REPS_B=2
|
TARGET_REPS_B=2
|
||||||
NUM_NODES=2
|
NUM_NODES=2
|
||||||
@ -16,7 +16,7 @@ rule build_showmap:
|
|||||||
output:
|
output:
|
||||||
directory("bins/target_showmap")
|
directory("bins/target_showmap")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_stg"
|
"cargo build --target-dir {output} {def_flags},systemstate"
|
||||||
|
|
||||||
rule build_random:
|
rule build_random:
|
||||||
output:
|
output:
|
||||||
@ -24,35 +24,47 @@ rule build_random:
|
|||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},feed_longest"
|
"cargo build --target-dir {output} {def_flags},feed_longest"
|
||||||
|
|
||||||
|
rule build_feedlongest:
|
||||||
|
output:
|
||||||
|
directory("bins/target_feedlongest")
|
||||||
|
shell:
|
||||||
|
"cargo build --target-dir {output} {def_flags},feed_longest"
|
||||||
|
|
||||||
rule build_frafl:
|
rule build_frafl:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_frafl")
|
directory("bins/target_frafl")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_frafl,feed_longest"
|
"cargo build --target-dir {output} {def_flags},feed_afl,feed_longest"
|
||||||
|
|
||||||
rule build_afl:
|
rule build_afl:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_afl")
|
directory("bins/target_afl")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_afl,observer_hitcounts"
|
"cargo build --target-dir {output} {def_flags},feed_afl,observer_hitcounts"
|
||||||
|
|
||||||
rule build_stg:
|
rule build_state:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_stg")
|
directory("bins/target_state")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_stg"
|
"cargo build --target-dir {output} {def_flags},feed_systemtrace"
|
||||||
|
|
||||||
rule build_stgpath:
|
rule build_nohashstate:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_stgpath")
|
directory("bins/target_nohashstate")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},feed_stg_abbhash,sched_stg_abbhash,mutate_stg"
|
"cargo build --target-dir {output} {def_flags},feed_systemtrace,no_hash_state"
|
||||||
|
|
||||||
|
rule build_graph:
|
||||||
|
output:
|
||||||
|
directory("bins/target_graph")
|
||||||
|
shell:
|
||||||
|
"cargo build --target-dir {output} {def_flags},feed_systemgraph"
|
||||||
|
|
||||||
rule build_showmap_int:
|
rule build_showmap_int:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_showmap_int")
|
directory("bins/target_showmap_int")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_stg,fuzz_int"
|
"cargo build --target-dir {output} {def_flags},systemstate,fuzz_int"
|
||||||
|
|
||||||
rule build_random_int:
|
rule build_random_int:
|
||||||
output:
|
output:
|
||||||
@ -60,30 +72,35 @@ rule build_random_int:
|
|||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},feed_longest,fuzz_int"
|
"cargo build --target-dir {output} {def_flags},feed_longest,fuzz_int"
|
||||||
|
|
||||||
|
rule build_state_int:
|
||||||
|
output:
|
||||||
|
directory("bins/target_state_int")
|
||||||
|
shell:
|
||||||
|
"cargo build --target-dir {output} {def_flags},feed_systemtrace,fuzz_int"
|
||||||
|
|
||||||
|
rule build_nohashstate_int:
|
||||||
|
output:
|
||||||
|
directory("bins/target_nohashstate_int")
|
||||||
|
shell:
|
||||||
|
"cargo build --target-dir {output} {def_flags},feed_systemtrace,fuzz_int,no_hash_state"
|
||||||
|
|
||||||
rule build_frafl_int:
|
rule build_frafl_int:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_frafl_int")
|
directory("bins/target_frafl_int")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_frafl,fuzz_int"
|
"cargo build --target-dir {output} {def_flags},feed_afl,feed_longest,fuzz_int"
|
||||||
|
|
||||||
rule build_afl_int:
|
rule build_afl_int:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_afl_int")
|
directory("bins/target_afl_int")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_afl,fuzz_int,"
|
"cargo build --target-dir {output} {def_flags},feed_afl,fuzz_int,observer_hitcounts"
|
||||||
|
|
||||||
rule build_stg_int:
|
rule build_feedlongest_int:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_stg_int")
|
directory("bins/target_feedlongest_int")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_stg,fuzz_int"
|
"cargo build --target-dir {output} {def_flags},feed_longest,fuzz_int"
|
||||||
|
|
||||||
rule build_stgpath_int:
|
|
||||||
output:
|
|
||||||
directory("bins/target_stgpath_int")
|
|
||||||
shell:
|
|
||||||
"cargo build --target-dir {output} {def_flags},feed_stg_abbhash,sched_stg_abbhash,mutate_stg,fuzz_int"
|
|
||||||
|
|
||||||
rule build_feedgeneration1:
|
rule build_feedgeneration1:
|
||||||
output:
|
output:
|
||||||
@ -113,20 +130,20 @@ rule build_feedgeneration100:
|
|||||||
output:
|
output:
|
||||||
directory("bins/target_feedgeneration100")
|
directory("bins/target_feedgeneration100")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_genetic,gensize_100"
|
"cargo build --target-dir {output} {def_flags},feed_genetic,gensize_100"
|
||||||
|
|
||||||
rule build_feedgeneration100_int:
|
rule build_feedgeneration100_int:
|
||||||
output:
|
output:
|
||||||
directory("bins/target_feedgeneration100_int")
|
directory("bins/target_feedgeneration100_int")
|
||||||
shell:
|
shell:
|
||||||
"cargo build --target-dir {output} {def_flags},config_genetic,fuzz_int,gensize_100"
|
"cargo build --target-dir {output} {def_flags},feed_genetic,fuzz_int,gensize_100"
|
||||||
|
|
||||||
rule run_bench:
|
rule run_bench:
|
||||||
input:
|
input:
|
||||||
"build/{target}.elf",
|
"build/{target}.elf",
|
||||||
"bins/target_{fuzzer}"
|
"bins/target_{fuzzer}"
|
||||||
output:
|
output:
|
||||||
multiext("timedump/{fuzzer}/{target}#{num}", ".time", ".log") # , ".case"
|
multiext("timedump/{fuzzer}/{target}.{num}", "", ".log") # , ".case"
|
||||||
run:
|
run:
|
||||||
with open('target_symbols.csv') as csvfile:
|
with open('target_symbols.csv') as csvfile:
|
||||||
reader = csv.DictReader(csvfile)
|
reader = csv.DictReader(csvfile)
|
||||||
@ -138,24 +155,25 @@ rule run_bench:
|
|||||||
fuzz_input=line['input_symbol']
|
fuzz_input=line['input_symbol']
|
||||||
fuzz_len=line['input_size']
|
fuzz_len=line['input_size']
|
||||||
bkp=line['return_function']
|
bkp=line['return_function']
|
||||||
|
script="""
|
||||||
|
mkdir -p $(dirname {output[0]})
|
||||||
|
export KERNEL=$(pwd)/{input[0]}
|
||||||
|
export FUZZ_MAIN={fuzz_main}
|
||||||
|
export FUZZ_INPUT={fuzz_input}
|
||||||
|
export FUZZ_INPUT_LEN={fuzz_len}
|
||||||
|
export BREAKPOINT={bkp}
|
||||||
|
export SEED_RANDOM={wildcards.num}
|
||||||
|
export TIME_DUMP=$(pwd)/{output[0]}
|
||||||
|
export CASE_DUMP=$(pwd)/{output[0]}.case
|
||||||
|
export TRACE_DUMP=$(pwd)/{output[0]}.trace
|
||||||
|
export FUZZ_ITERS={RUNTIME}
|
||||||
|
export FUZZER=$(pwd)/{input[1]}/debug/fret
|
||||||
|
set +e
|
||||||
|
../fuzzer.sh > {output[1]} 2>&1
|
||||||
|
exit 0
|
||||||
|
"""
|
||||||
if wildcards.fuzzer.find('random') >= 0:
|
if wildcards.fuzzer.find('random') >= 0:
|
||||||
script="""
|
script="export FUZZ_RANDOM={output[1]}\n"+script
|
||||||
export RUST_BACKTRACE=1
|
|
||||||
mkdir -p $(dirname {output[0]})
|
|
||||||
set +e
|
|
||||||
echo $(pwd)/{input[1]}/debug/fret -n $(pwd)/timedump/{wildcards.fuzzer}/{wildcards.target}#{wildcards.num} -t -a -g -k {input[0]} -c ./target_symbols.csv fuzz --random -t {RUNTIME} -s {wildcards.num}
|
|
||||||
$(pwd)/{input[1]}/debug/fret -n $(pwd)/timedump/{wildcards.fuzzer}/{wildcards.target}#{wildcards.num} -t -a -g -k {input[0]} -c ./target_symbols.csv fuzz --random -t {RUNTIME} -s {wildcards.num} > {output[1]} 2>&1
|
|
||||||
exit 0
|
|
||||||
"""
|
|
||||||
else:
|
|
||||||
script="""
|
|
||||||
export RUST_BACKTRACE=1
|
|
||||||
mkdir -p $(dirname {output[0]})
|
|
||||||
set +e
|
|
||||||
echo $(pwd)/{input[1]}/debug/fret -n $(pwd)/timedump/{wildcards.fuzzer}/{wildcards.target}#{wildcards.num} -t -a -g -k {input[0]} -c ./target_symbols.csv fuzz -t {RUNTIME} -s {wildcards.num}
|
|
||||||
$(pwd)/{input[1]}/debug/fret -n $(pwd)/timedump/{wildcards.fuzzer}/{wildcards.target}#{wildcards.num} -t -a -g -k {input[0]} -c ./target_symbols.csv fuzz -t {RUNTIME} -s {wildcards.num} > {output[1]} 2>&1
|
|
||||||
exit 0
|
|
||||||
"""
|
|
||||||
shell(script)
|
shell(script)
|
||||||
|
|
||||||
rule run_showmap:
|
rule run_showmap:
|
||||||
@ -163,10 +181,10 @@ rule run_showmap:
|
|||||||
"{remote}build/{target}.elf",
|
"{remote}build/{target}.elf",
|
||||||
"bins/target_showmap",
|
"bins/target_showmap",
|
||||||
"bins/target_showmap_int",
|
"bins/target_showmap_int",
|
||||||
"{remote}timedump/{fuzzer}/{target}#{num}.case"
|
"{remote}timedump/{fuzzer}/{target}.{num}.case"
|
||||||
output:
|
output:
|
||||||
"{remote}timedump/{fuzzer}/{target}#{num}_case.trace.ron",
|
"{remote}timedump/{fuzzer}/{target}.{num}.trace.ron",
|
||||||
"{remote}timedump/{fuzzer}/{target}#{num}_case.time",
|
"{remote}timedump/{fuzzer}/{target}.{num}.case.time",
|
||||||
run:
|
run:
|
||||||
with open('target_symbols.csv') as csvfile:
|
with open('target_symbols.csv') as csvfile:
|
||||||
reader = csv.DictReader(csvfile)
|
reader = csv.DictReader(csvfile)
|
||||||
@ -185,9 +203,16 @@ rule run_showmap:
|
|||||||
script="export FUZZER=$(pwd)/{input[1]}/debug/fret\n"
|
script="export FUZZER=$(pwd)/{input[1]}/debug/fret\n"
|
||||||
script+="""
|
script+="""
|
||||||
mkdir -p $(dirname {output})
|
mkdir -p $(dirname {output})
|
||||||
|
export KERNEL=$(pwd)/{input[0]}
|
||||||
|
export FUZZ_MAIN={fuzz_main}
|
||||||
|
export FUZZ_INPUT={fuzz_input}
|
||||||
|
export FUZZ_INPUT_LEN={fuzz_len}
|
||||||
|
export BREAKPOINT={bkp}
|
||||||
|
export TRACE_DUMP=$(pwd)/{output[0]}
|
||||||
|
export DO_SHOWMAP=$(pwd)/{input[3]}
|
||||||
|
export TIME_DUMP=$(pwd)/{output[1]}
|
||||||
set +e
|
set +e
|
||||||
echo $(pwd)/{input[1]}/debug/fret -n $(pwd)/{remote}/timedump/{wildcards.fuzzer}/{wildcards.target}#{wildcards.num}_case -t -a -r -g -k {input[0]} -c ./target_symbols.csv showmap -i {input[3]}
|
../fuzzer.sh
|
||||||
$(pwd)/{input[1]}/debug/fret -n $(pwd)/{remote}/timedump/{wildcards.fuzzer}/{wildcards.target}#{wildcards.num}_case -t -a -r -g -k {input[0]} -c ./target_symbols.csv showmap -i {input[3]}
|
|
||||||
exit 0
|
exit 0
|
||||||
"""
|
"""
|
||||||
if wildcards.fuzzer.find('random') >= 0:
|
if wildcards.fuzzer.find('random') >= 0:
|
||||||
@ -251,22 +276,6 @@ rule clusterfuzz:
|
|||||||
expand("timedump/{fuzzer}/{target}.{num}", fuzzer=['afl','frafl','feedlongest'], target=['waters','watersv2'],num=MY_RANGE_B),
|
expand("timedump/{fuzzer}/{target}.{num}", fuzzer=['afl','frafl','feedlongest'], target=['waters','watersv2'],num=MY_RANGE_B),
|
||||||
expand("timedump/{fuzzer}/{target}.{num}", fuzzer=['afl_int','frafl_int','feedlongest_int'], target=['waters_int','watersv2_int'],num=MY_RANGE_B),
|
expand("timedump/{fuzzer}/{target}.{num}", fuzzer=['afl_int','frafl_int','feedlongest_int'], target=['waters_int','watersv2_int'],num=MY_RANGE_B),
|
||||||
|
|
||||||
rule all_new:
|
|
||||||
input:
|
|
||||||
expand("timedump/{fuzzer}/{target}#{num}.time", fuzzer=['feedgeneration100', 'frafl', 'stg'], target=['waters', 'watersv2'],num=range(0,3)),
|
|
||||||
expand("timedump/{fuzzer}/{target}#{num}.time", fuzzer=['feedgeneration100_int', 'frafl_int', 'stg_int'], target=['waters_int', 'watersv2_int'],num=range(0,3)),
|
|
||||||
expand("timedump/{fuzzer}/{target}#{num}.time", fuzzer=['random', 'stgpath'], target=['waters', 'watersv2'],num=range(0,3)),
|
|
||||||
expand("timedump/{fuzzer}/{target}#{num}.time", fuzzer=['random_int', 'stgpath_int'], target=['waters_int', 'watersv2_int'],num=range(0,3))
|
|
||||||
|
|
||||||
rule all_showmap:
|
|
||||||
input:
|
|
||||||
expand("{remote}timedump/{fuzzer}/{target}#{num}_case.trace.ron",remote=remote, fuzzer=['frafl', 'stg'], target=['watersv2'],num=range(2,3)),
|
|
||||||
expand("{remote}timedump/{fuzzer}/{target}#{num}_case.trace.ron",remote=remote, fuzzer=['frafl_int', 'stg_int'], target=['watersv2_int'],num=range(0,3)),
|
|
||||||
expand("{remote}timedump/{fuzzer}/{target}#{num}_case.trace.ron",remote=remote, fuzzer=['random', 'stgpath'], target=['watersv2'],num=range(0,1)),
|
|
||||||
expand("{remote}timedump/{fuzzer}/{target}#{num}_case.trace.ron",remote=remote, fuzzer=['random_int', 'stgpath_int'], target=['watersv2_int'],num=range(0,1))
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
rule all_bins:
|
rule all_bins:
|
||||||
input:
|
input:
|
||||||
expand("bins/target_{target}{flag}",target=['random','frafl','stg','stgpath','feedgeneration100'],flag=['','_int'])
|
expand("bins/target_{target}{flag}",target=['random','afl','frafl','state','feedgeneration100'],flag=['','_int'])
|
@ -1,17 +0,0 @@
|
|||||||
make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC clean && make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC WATERS_DEMO=1 INTERRUPT_ACTIVATION=1
|
|
||||||
cp ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC/build/RTOSDemo.axf build/waters_int.elf
|
|
||||||
|
|
||||||
make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC clean && make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC WATERS_DEMO=1 INTERRUPT_ACTIVATION=0
|
|
||||||
cp ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC/build/RTOSDemo.axf build/waters.elf
|
|
||||||
|
|
||||||
make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC clean && make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC WATERSV2_DEMO=1 INTERRUPT_ACTIVATION=1
|
|
||||||
cp ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC/build/RTOSDemo.axf build/watersv2_int.elf
|
|
||||||
|
|
||||||
make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC clean && make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC WATERSV2_DEMO=1 INTERRUPT_ACTIVATION=0
|
|
||||||
cp ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC/build/RTOSDemo.axf build/watersv2.elf
|
|
||||||
|
|
||||||
make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC clean && make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC INTERACT_DEMO=1 INTERRUPT_ACTIVATION=1
|
|
||||||
cp ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC/build/RTOSDemo.axf build/interact_int.elf
|
|
||||||
|
|
||||||
make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC clean && make -C ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC INTERACT_DEMO=1 INTERRUPT_ACTIVATION=0
|
|
||||||
cp ../../../../FreeRTOS/FreeRTOS/Demo/CORTEX_M3_MPS2_QEMU_GCC/build/RTOSDemo.axf build/interact.elf
|
|
@ -1,8 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
find $1 -type 'f' -iname "${2}#*.log" | while IFS="" read -r p || [ -n "$p" ]
|
|
||||||
do
|
|
||||||
LINE=$(tail -n 100 $p | grep -io "run time: .* corpus: [0-9]*" | tail -n 1)
|
|
||||||
echo $p: $LINE
|
|
||||||
LINE=$(grep -i "interesting corpus elements" $p | tail -n 1)
|
|
||||||
echo $p: $LINE
|
|
||||||
done
|
|
@ -1,7 +0,0 @@
|
|||||||
Rscript plot_multi.r remote waters ~/code/FRET/LibAFL/fuzzers/FRET/benchmark/remote &
|
|
||||||
Rscript plot_multi.r remote waters_int ~/code/FRET/LibAFL/fuzzers/FRET/benchmark/remote &
|
|
||||||
Rscript plot_multi.r remote watersv2 ~/code/FRET/LibAFL/fuzzers/FRET/benchmark/remote &
|
|
||||||
Rscript plot_multi.r remote watersv2_int ~/code/FRET/LibAFL/fuzzers/FRET/benchmark/remote &
|
|
||||||
Rscript plot_multi.r remote interact ~/code/FRET/LibAFL/fuzzers/FRET/benchmark/remote &
|
|
||||||
Rscript plot_multi.r remote interact_int ~/code/FRET/LibAFL/fuzzers/FRET/benchmark/remote &
|
|
||||||
wait
|
|
@ -1,14 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
find ./remote/timedump -type 'f' -iregex '.*case' | while IFS="" read -r p || [ -n "$p" ]
|
|
||||||
do
|
|
||||||
N=$(dirname "$p")/$(basename -s .case "$p")
|
|
||||||
T="${N}_case.trace.ron"
|
|
||||||
P="${N}_case"
|
|
||||||
echo $N
|
|
||||||
if [ ! -f "$T" ]; then
|
|
||||||
snakemake -c1 "$T"
|
|
||||||
fi
|
|
||||||
if [ ! -f "$P.html" ]; then
|
|
||||||
~/code/FRET/state2gantt/driver.sh "$T"
|
|
||||||
fi
|
|
||||||
done
|
|
@ -11,11 +11,8 @@ registerDoParallel(cl)
|
|||||||
args = commandArgs(trailingOnly=TRUE)
|
args = commandArgs(trailingOnly=TRUE)
|
||||||
|
|
||||||
if (length(args)==0) {
|
if (length(args)==0) {
|
||||||
runtype="remote"
|
runtype="timedump_253048_1873f6_all/timedump"
|
||||||
#target="waters"
|
target="waters_int"
|
||||||
target="watersv2"
|
|
||||||
#target="waters_int"
|
|
||||||
#target="watersv2_int"
|
|
||||||
outputpath="~/code/FRET/LibAFL/fuzzers/FRET/benchmark/"
|
outputpath="~/code/FRET/LibAFL/fuzzers/FRET/benchmark/"
|
||||||
#MY_SELECTION <- c('state', 'afl', 'graph', 'random')
|
#MY_SELECTION <- c('state', 'afl', 'graph', 'random')
|
||||||
SAVE_FILE=TRUE
|
SAVE_FILE=TRUE
|
||||||
@ -23,15 +20,10 @@ if (length(args)==0) {
|
|||||||
runtype=args[1]
|
runtype=args[1]
|
||||||
target=args[2]
|
target=args[2]
|
||||||
outputpath=args[3]
|
outputpath=args[3]
|
||||||
#MY_SELECTION <- args[4:length(args)]
|
MY_SELECTION <- args[4:length(args)]
|
||||||
#if (length(MY_SELECTION) == 0)
|
|
||||||
# MY_SELECTION<-NULL
|
|
||||||
SAVE_FILE=TRUE
|
SAVE_FILE=TRUE
|
||||||
print(runtype)
|
|
||||||
print(target)
|
|
||||||
print(outputpath)
|
|
||||||
}
|
}
|
||||||
worst_cases <- list(waters=0, waters_int=0, tmr=405669, micro_longint=0, gen3=0)
|
worst_cases <- list(waters=0, waters_int=0, tmr=405669, micro_longint=0)
|
||||||
worst_case <- worst_cases[[target]]
|
worst_case <- worst_cases[[target]]
|
||||||
if (is.null(worst_case)) {
|
if (is.null(worst_case)) {
|
||||||
worst_case = 0
|
worst_case = 0
|
||||||
@ -41,12 +33,12 @@ if (is.null(worst_case)) {
|
|||||||
MY_COLORS <- c("green", "blue", "red", "magenta", "orange", "cyan", "pink", "gray", "orange", "black", "yellow","brown")
|
MY_COLORS <- c("green", "blue", "red", "magenta", "orange", "cyan", "pink", "gray", "orange", "black", "yellow","brown")
|
||||||
BENCHDIR=sprintf("~/code/FRET/LibAFL/fuzzers/FRET/benchmark/%s",runtype)
|
BENCHDIR=sprintf("~/code/FRET/LibAFL/fuzzers/FRET/benchmark/%s",runtype)
|
||||||
BASENAMES=Filter(function(x) x!="" && substr(x,1,1)!='.',list.dirs(BENCHDIR,full.names=FALSE))
|
BASENAMES=Filter(function(x) x!="" && substr(x,1,1)!='.',list.dirs(BENCHDIR,full.names=FALSE))
|
||||||
PATTERNS="%s#[0-9]*.time$"
|
PATTERNS="%s.[0-9]*$"
|
||||||
#RIBBON='sd'
|
#RIBBON='sd'
|
||||||
#RIBBON='span'
|
#RIBBON='span'
|
||||||
RIBBON='both'
|
RIBBON='both'
|
||||||
DRAW_WC = worst_case > 0
|
DRAW_WC = worst_case > 0
|
||||||
LEGEND_POS="bottomright"
|
LEGEND_POS="topright"
|
||||||
#LEGEND_POS="bottomright"
|
#LEGEND_POS="bottomright"
|
||||||
CONTINUE_LINE_TO_END=FALSE
|
CONTINUE_LINE_TO_END=FALSE
|
||||||
|
|
||||||
@ -226,11 +218,11 @@ if (length(typenames) == 0) {return()}
|
|||||||
h_ = 500
|
h_ = 500
|
||||||
w_ = h_*4/3
|
w_ = h_*4/3
|
||||||
|
|
||||||
if (SAVE_FILE) {png(file=sprintf("%s/%s_%s.png",outputpath,target,filename), width=w_, height=h_)}
|
if (SAVE_FILE) {png(file=sprintf("%s%s_%s.png",outputpath,target,filename), width=w_, height=h_)}
|
||||||
par(mar=c(4,4,1,1))
|
par(mar=c(4,4,1,1))
|
||||||
par(oma=c(0,0,0,0))
|
par(oma=c(0,0,0,0))
|
||||||
|
|
||||||
plot(c(0,max(one_frame['time'])),c(ylow,yhigh), col='white', xlab="Time [h]", ylab="WORT [insn]", pch='.')
|
plot(c(1,max(one_frame['time'])),c(ylow,yhigh), col='white', xlab="Time [h]", ylab="WORT [insn]", pch='.')
|
||||||
|
|
||||||
for (t in seq_len(length(typenames))) {
|
for (t in seq_len(length(typenames))) {
|
||||||
#proj = one_frame[seq(1, dim(one_frame)[1], by=max(1, length(one_frame[[1]])/(10*w_))),]
|
#proj = one_frame[seq(1, dim(one_frame)[1], by=max(1, length(one_frame[[1]])/(10*w_))),]
|
||||||
@ -296,7 +288,7 @@ if (DRAW_WC) {
|
|||||||
lines(c(0,length(one_frame[[1]])),y=c(worst_case,worst_case), lty='dotted')
|
lines(c(0,length(one_frame[[1]])),y=c(worst_case,worst_case), lty='dotted')
|
||||||
leglines=c(typenames, 'worst observed')
|
leglines=c(typenames, 'worst observed')
|
||||||
}
|
}
|
||||||
legend(LEGEND_POS, legend=leglines,#"bottomright",
|
legend(LEGEND_POS, legend=leglines,#"topleft"
|
||||||
col=c(MY_COLORS_[1:length(typenames)],"black"),
|
col=c(MY_COLORS_[1:length(typenames)],"black"),
|
||||||
lty=c(rep("solid",length(typenames)),"dotted"))
|
lty=c(rep("solid",length(typenames)),"dotted"))
|
||||||
|
|
||||||
@ -309,7 +301,7 @@ par(oma=c(0,0,0,0))
|
|||||||
|
|
||||||
#RIBBON='both'
|
#RIBBON='both'
|
||||||
#MY_SELECTION = c('state_int','generation100_int')
|
#MY_SELECTION = c('state_int','generation100_int')
|
||||||
#MY_SELECTION = c('state','frafl')
|
#MY_SELECTION = c('state_int','frafl_int')
|
||||||
|
|
||||||
if (exists("MY_SELECTION")) {
|
if (exists("MY_SELECTION")) {
|
||||||
plotting(MY_SELECTION, 'custom', MY_COLORS[c(1,2)])
|
plotting(MY_SELECTION, 'custom', MY_COLORS[c(1,2)])
|
||||||
|
@ -22,7 +22,3 @@ watersv2_int,main_waters,FUZZ_INPUT,4096,trigger_Qemu_break
|
|||||||
micro_branchless,main_branchless,FUZZ_INPUT,4,trigger_Qemu_break
|
micro_branchless,main_branchless,FUZZ_INPUT,4,trigger_Qemu_break
|
||||||
micro_int,main_int,FUZZ_INPUT,16,trigger_Qemu_break
|
micro_int,main_int,FUZZ_INPUT,16,trigger_Qemu_break
|
||||||
micro_longint,main_micro_longint,FUZZ_INPUT,16,trigger_Qemu_break
|
micro_longint,main_micro_longint,FUZZ_INPUT,16,trigger_Qemu_break
|
||||||
minimal,main_minimal,FUZZ_INPUT,4096,trigger_Qemu_break
|
|
||||||
gen3,main_minimal,FUZZ_INPUT,4096,trigger_Qemu_break
|
|
||||||
interact,main_interact,FUZZ_INPUT,4096,trigger_Qemu_break
|
|
||||||
interact_int,main_interact,FUZZ_INPUT,4096,trigger_Qemu_break
|
|
||||||
|
|
25
fuzzers/FRET/fuzzer.sh
Executable file
25
fuzzers/FRET/fuzzer.sh
Executable file
@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
|
||||||
|
cd "$parent_path"
|
||||||
|
|
||||||
|
[ -n "$1" -a "$1" != "+" -a -z "$KERNEL" ] && export KERNEL="$1"
|
||||||
|
[ -n "$2" -a "$2" != "+" -a -z "$FUZZ_MAIN" ] && export FUZZ_MAIN="$2"
|
||||||
|
[ -n "$3" -a "$3" != "+" -a -z "$FUZZ_INPUT" ] && export FUZZ_INPUT="$3"
|
||||||
|
[ -n "$4" -a "$4" != "+" -a -z "$FUZZ_INPUT_LEN" ] && export FUZZ_INPUT_LEN="$4"
|
||||||
|
[ -n "$5" -a "$5" != "+" -a -z "$BREAKPOINT" ] && export BREAKPOINT="$5"
|
||||||
|
[ -n "$6" -a "$6" != "+" -a -z "$FUZZ_ITERS" ] && export FUZZ_ITERS="$6"
|
||||||
|
[ -n "$7" -a "$7" != "+" -a -z "$TIME_DUMP" ] && export TIME_DUMP="$7"
|
||||||
|
[ -n "$8" -a "$8" != "+" -a -z "$CASE_DUMP" ] && export CASE_DUMP="$8"
|
||||||
|
[ -n "$9" -a "$9" != "+" -a -z "$DO_SHOWMAP" ] && export DO_SHOWMAP="$9"
|
||||||
|
[ -n "${10}" -a "${10}" != "+" -a -z "$SHOWMAP_TEXTINPUT" ] && export SHOWMAP_TEXTINPUT="${10}"
|
||||||
|
[ -n "${11}" -a "${11}" != "+" -a -z "$TRACE_DUMP" ] && export TRACE_DUMP="${11}"
|
||||||
|
|
||||||
|
[ -z "$FUZZER" ] && export FUZZER=target/debug/fret
|
||||||
|
set +e
|
||||||
|
$FUZZER -icount shift=4,align=off,sleep=off -machine mps2-an385 -monitor null -kernel $KERNEL -serial null -nographic -S -semihosting --semihosting-config enable=on,target=native -snapshot -drive if=none,format=qcow2,file=dummy.qcow2
|
||||||
|
if [ "$exitcode" = "101" ]
|
||||||
|
then
|
||||||
|
exit 101
|
||||||
|
else
|
||||||
|
exit 0
|
||||||
|
fi
|
@ -1,22 +1,21 @@
|
|||||||
use hashbrown::{hash_map::Entry, HashMap};
|
use hashbrown::{hash_map::Entry, HashMap};
|
||||||
use libafl_bolts::{
|
|
||||||
current_nanos,
|
|
||||||
rands::StdRand,
|
|
||||||
tuples::{tuple_list,MatchName},
|
|
||||||
impl_serdeany,
|
|
||||||
Named,
|
|
||||||
};
|
|
||||||
use libafl::{
|
use libafl::{
|
||||||
|
bolts::{
|
||||||
|
current_nanos,
|
||||||
|
rands::StdRand,
|
||||||
|
tuples::{tuple_list},
|
||||||
|
},
|
||||||
executors::{ExitKind},
|
executors::{ExitKind},
|
||||||
fuzzer::{StdFuzzer},
|
fuzzer::{StdFuzzer},
|
||||||
inputs::{BytesInput, HasTargetBytes},
|
inputs::{BytesInput, HasTargetBytes},
|
||||||
observers::{Observer,VariableMapObserver},
|
observers::{Observer,VariableMapObserver},
|
||||||
state::{StdState, HasNamedMetadata},
|
state::{StdState, HasNamedMetadata},
|
||||||
Error,
|
Error,
|
||||||
observers::ObserversTuple, prelude::UsesInput,
|
observers::ObserversTuple, prelude::UsesInput, impl_serdeany,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::{cell::UnsafeCell, cmp::max, env, fs::OpenOptions, io::Write, time::Instant};
|
use std::{cell::UnsafeCell, cmp::max, env, fs::OpenOptions, io::Write, time::Instant};
|
||||||
|
use libafl::bolts::tuples::Named;
|
||||||
|
|
||||||
use libafl_qemu::{
|
use libafl_qemu::{
|
||||||
emu,
|
emu,
|
||||||
@ -25,8 +24,7 @@ use libafl_qemu::{
|
|||||||
helper::{QemuHelper, QemuHelperTuple, QemuInstrumentationFilter},
|
helper::{QemuHelper, QemuHelperTuple, QemuInstrumentationFilter},
|
||||||
};
|
};
|
||||||
use libafl::events::EventFirer;
|
use libafl::events::EventFirer;
|
||||||
use libafl::state::MaybeHasClientPerfMonitor;
|
use libafl::state::HasClientPerfMonitor;
|
||||||
use libafl::prelude::State;
|
|
||||||
use libafl::inputs::Input;
|
use libafl::inputs::Input;
|
||||||
use libafl::feedbacks::Feedback;
|
use libafl::feedbacks::Feedback;
|
||||||
use libafl::SerdeAny;
|
use libafl::SerdeAny;
|
||||||
@ -35,21 +33,11 @@ use libafl::corpus::testcase::Testcase;
|
|||||||
use core::{fmt::Debug, time::Duration};
|
use core::{fmt::Debug, time::Duration};
|
||||||
// use libafl::feedbacks::FeedbackState;
|
// use libafl::feedbacks::FeedbackState;
|
||||||
// use libafl::state::HasFeedbackStates;
|
// use libafl::state::HasFeedbackStates;
|
||||||
|
use libafl::bolts::tuples::MatchName;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
pub static mut FUZZ_START_TIMESTAMP : SystemTime = UNIX_EPOCH;
|
pub static mut FUZZ_START_TIMESTAMP : SystemTime = UNIX_EPOCH;
|
||||||
|
|
||||||
pub const QEMU_ICOUNT_SHIFT : u32 = 5;
|
|
||||||
pub const QEMU_ISNS_PER_SEC : u32 = u32::pow(10, 9) / u32::pow(2, QEMU_ICOUNT_SHIFT);
|
|
||||||
pub const QEMU_ISNS_PER_USEC : u32 = QEMU_ISNS_PER_SEC / 1000000;
|
|
||||||
pub const QEMU_NS_PER_ISN : u32 = 1 << QEMU_ICOUNT_SHIFT;
|
|
||||||
pub const TARGET_SYSCLK_FREQ : u32 = 25 * 1000 * 1000;
|
|
||||||
pub const TARGET_MHZ_PER_MIPS : f32 = TARGET_SYSCLK_FREQ as f32 / QEMU_ISNS_PER_SEC as f32;
|
|
||||||
pub const TARGET_MIPS_PER_MHZ : f32 = QEMU_ISNS_PER_SEC as f32 / TARGET_SYSCLK_FREQ as f32;
|
|
||||||
pub const TARGET_SYSCLK_PER_QEMU_SEC : u32 = (TARGET_SYSCLK_FREQ as f32 * TARGET_MIPS_PER_MHZ) as u32;
|
|
||||||
pub const QEMU_SYSCLK_PER_TARGET_SEC : u32 = (TARGET_SYSCLK_FREQ as f32 * TARGET_MHZ_PER_MIPS) as u32;
|
|
||||||
|
|
||||||
//========== Metadata
|
//========== Metadata
|
||||||
#[derive(Debug, SerdeAny, Serialize, Deserialize)]
|
#[derive(Debug, SerdeAny, Serialize, Deserialize)]
|
||||||
pub struct QemuIcountMetadata {
|
pub struct QemuIcountMetadata {
|
||||||
@ -109,18 +97,16 @@ pub struct QemuClockObserver {
|
|||||||
name: String,
|
name: String,
|
||||||
start_tick: u64,
|
start_tick: u64,
|
||||||
end_tick: u64,
|
end_tick: u64,
|
||||||
dump_path: Option<PathBuf>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl QemuClockObserver {
|
impl QemuClockObserver {
|
||||||
/// Creates a new [`QemuClockObserver`] with the given name.
|
/// Creates a new [`QemuClockObserver`] with the given name.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(name: &'static str, dump_path: Option<PathBuf>) -> Self {
|
pub fn new(name: &'static str) -> Self {
|
||||||
Self {
|
Self {
|
||||||
name: name.to_string(),
|
name: name.to_string(),
|
||||||
start_tick: 0,
|
start_tick: 0,
|
||||||
end_tick: 0,
|
end_tick: 0,
|
||||||
dump_path
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -150,33 +136,36 @@ where
|
|||||||
|
|
||||||
fn post_exec(&mut self, _state: &mut S, _input: &S::Input, _exit_kind: &ExitKind) -> Result<(), Error> {
|
fn post_exec(&mut self, _state: &mut S, _input: &S::Input, _exit_kind: &ExitKind) -> Result<(), Error> {
|
||||||
unsafe { self.end_tick = emu::icount_get_raw() };
|
unsafe { self.end_tick = emu::icount_get_raw() };
|
||||||
if let Some(td) = &self.dump_path {
|
// println!("clock post {}", self.end_tick);
|
||||||
// println!("clock post {}", self.end_tick);
|
// println!("Number of Ticks: {} <- {} {}",self.end_tick - self.start_tick, self.end_tick, self.start_tick);
|
||||||
// println!("Number of Ticks: {} <- {} {}",self.end_tick - self.start_tick, self.end_tick, self.start_tick);
|
let metadata =_state.metadata_mut();
|
||||||
let metadata =_state.metadata_map_mut();
|
let hist = metadata.get_mut::<IcHist>();
|
||||||
let hist = metadata.get_mut::<IcHist>();
|
let timestamp = SystemTime::now().duration_since(unsafe {FUZZ_START_TIMESTAMP}).unwrap().as_millis();
|
||||||
let timestamp = SystemTime::now().duration_since(unsafe {FUZZ_START_TIMESTAMP}).unwrap().as_millis();
|
match hist {
|
||||||
match hist {
|
None => {
|
||||||
None => {
|
metadata.insert(IcHist(vec![(self.end_tick - self.start_tick, timestamp)],
|
||||||
metadata.insert(IcHist(vec![(self.end_tick - self.start_tick, timestamp)],
|
(self.end_tick - self.start_tick, timestamp)));
|
||||||
(self.end_tick - self.start_tick, timestamp)));
|
}
|
||||||
|
Some(v) => {
|
||||||
|
v.0.push((self.end_tick - self.start_tick, timestamp));
|
||||||
|
if (v.1.0 < self.end_tick-self.start_tick) {
|
||||||
|
v.1 = (self.end_tick - self.start_tick, timestamp);
|
||||||
}
|
}
|
||||||
Some(v) => {
|
if v.0.len() >= 100 {
|
||||||
v.0.push((self.end_tick - self.start_tick, timestamp));
|
if let Ok(td) = env::var("TIME_DUMP") {
|
||||||
if v.1.0 < self.end_tick-self.start_tick {
|
|
||||||
v.1 = (self.end_tick - self.start_tick, timestamp);
|
|
||||||
}
|
|
||||||
if v.0.len() >= 100 {
|
|
||||||
let mut file = OpenOptions::new()
|
let mut file = OpenOptions::new()
|
||||||
.read(true)
|
.read(true)
|
||||||
.write(true)
|
.write(true)
|
||||||
.create(true)
|
.create(true)
|
||||||
.append(true)
|
.append(true)
|
||||||
.open(td).expect("Could not open timedump");
|
.open(td).expect("Could not open timedump");
|
||||||
let newv : Vec<(u64, u128)> = Vec::with_capacity(110);
|
let newv : Vec<(u64, u128)> = Vec::with_capacity(100);
|
||||||
for i in std::mem::replace(&mut v.0, newv).into_iter() {
|
for i in std::mem::replace(&mut v.0, newv).into_iter() {
|
||||||
writeln!(file, "{},{}", i.0, i.1).expect("Write to dump failed");
|
writeln!(file, "{},{}", i.0, i.1).expect("Write to dump failed");
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// If we don't write out values we don't need to remember them at all
|
||||||
|
v.0.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -198,7 +187,6 @@ impl Default for QemuClockObserver {
|
|||||||
name: String::from("clock"),
|
name: String::from("clock"),
|
||||||
start_tick: 0,
|
start_tick: 0,
|
||||||
end_tick: 0,
|
end_tick: 0,
|
||||||
dump_path: None
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -215,7 +203,7 @@ pub struct ClockTimeFeedback {
|
|||||||
|
|
||||||
impl<S> Feedback<S> for ClockTimeFeedback
|
impl<S> Feedback<S> for ClockTimeFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor + HasMetadata,
|
S: UsesInput + HasClientPerfMonitor + HasMetadata,
|
||||||
{
|
{
|
||||||
#[allow(clippy::wrong_self_convention)]
|
#[allow(clippy::wrong_self_convention)]
|
||||||
fn is_interesting<EM, OT>(
|
fn is_interesting<EM, OT>(
|
||||||
@ -232,16 +220,15 @@ where
|
|||||||
{
|
{
|
||||||
// TODO Replace with match_name_type when stable
|
// TODO Replace with match_name_type when stable
|
||||||
let observer = observers.match_name::<QemuClockObserver>(self.name()).unwrap();
|
let observer = observers.match_name::<QemuClockObserver>(self.name()).unwrap();
|
||||||
self.exec_time = Some(Duration::from_nanos(observer.last_runtime() << QEMU_ICOUNT_SHIFT)); // Assume a somewhat realistic multiplier of clock, it does not matter
|
self.exec_time = Some(Duration::from_nanos(observer.last_runtime() << 4)); // Assume a somewhat realistic multiplier of clock, it does not matter
|
||||||
Ok(false)
|
Ok(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Append to the testcase the generated metadata in case of a new corpus item
|
/// Append to the testcase the generated metadata in case of a new corpus item
|
||||||
#[inline]
|
#[inline]
|
||||||
fn append_metadata<OT>(
|
fn append_metadata(
|
||||||
&mut self,
|
&mut self,
|
||||||
_state: &mut S,
|
_state: &mut S,
|
||||||
observers: &OT,
|
|
||||||
testcase: &mut Testcase<S::Input>,
|
testcase: &mut Testcase<S::Input>,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
*testcase.exec_time_mut() = self.exec_time;
|
*testcase.exec_time_mut() = self.exec_time;
|
||||||
@ -292,7 +279,7 @@ pub struct QemuClockIncreaseFeedback {
|
|||||||
|
|
||||||
impl<S> Feedback<S> for QemuClockIncreaseFeedback
|
impl<S> Feedback<S> for QemuClockIncreaseFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + HasNamedMetadata + MaybeHasClientPerfMonitor + Debug,
|
S: UsesInput + HasNamedMetadata + HasClientPerfMonitor + Debug,
|
||||||
{
|
{
|
||||||
fn is_interesting<EM, OT>(
|
fn is_interesting<EM, OT>(
|
||||||
&mut self,
|
&mut self,
|
||||||
@ -309,7 +296,7 @@ where
|
|||||||
let observer = _observers.match_name::<QemuClockObserver>("clock")
|
let observer = _observers.match_name::<QemuClockObserver>("clock")
|
||||||
.expect("QemuClockObserver not found");
|
.expect("QemuClockObserver not found");
|
||||||
let clock_state = state
|
let clock_state = state
|
||||||
.named_metadata_map_mut()
|
.named_metadata_mut()
|
||||||
.get_mut::<MaxIcountMetadata>(&self.name)
|
.get_mut::<MaxIcountMetadata>(&self.name)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
if observer.last_runtime() > clock_state.max_icount_seen {
|
if observer.last_runtime() > clock_state.max_icount_seen {
|
||||||
@ -322,7 +309,7 @@ where
|
|||||||
|
|
||||||
/// Append to the testcase the generated metadata in case of a new corpus item
|
/// Append to the testcase the generated metadata in case of a new corpus item
|
||||||
#[inline]
|
#[inline]
|
||||||
fn append_metadata<OT>(&mut self, _state: &mut S, observers: &OT, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
fn append_metadata(&mut self, _state: &mut S, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
||||||
// testcase.metadata_mut().insert(QemuIcountMetadata{runtime: self.last_runtime});
|
// testcase.metadata_mut().insert(QemuIcountMetadata{runtime: self.last_runtime});
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -1,3 +1,4 @@
|
|||||||
|
#![feature(is_sorted)]
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
mod fuzzer;
|
mod fuzzer;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
#![feature(is_sorted)]
|
||||||
//! A libfuzzer-like fuzzer using qemu for binary-only coverage
|
//! A libfuzzer-like fuzzer using qemu for binary-only coverage
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
mod fuzzer;
|
mod fuzzer;
|
||||||
|
@ -4,79 +4,47 @@
|
|||||||
use core::marker::PhantomData;
|
use core::marker::PhantomData;
|
||||||
use std::cmp::{max, min};
|
use std::cmp::{max, min};
|
||||||
|
|
||||||
use hashbrown::HashMap;
|
|
||||||
use libafl_bolts::rands::{
|
|
||||||
StdRand, RandomSeed,
|
|
||||||
Rand
|
|
||||||
};
|
|
||||||
use libafl::{
|
use libafl::{
|
||||||
corpus::{self, Corpus}, fuzzer::Evaluator, mark_feature_time, prelude::{new_hash_feedback, CorpusId, HasBytesVec, MutationResult, Mutator, UsesInput}, stages::Stage, start_timer, state::{HasCorpus, HasMetadata, HasNamedMetadata, HasRand, MaybeHasClientPerfMonitor, UsesState}, Error
|
bolts::rands::Rand,
|
||||||
|
corpus::{Corpus, self},
|
||||||
|
fuzzer::Evaluator,
|
||||||
|
mark_feature_time,
|
||||||
|
stages::{Stage},
|
||||||
|
start_timer,
|
||||||
|
state::{HasClientPerfMonitor, HasCorpus, HasRand, UsesState, HasMetadata},
|
||||||
|
Error, prelude::{HasBytesVec, UsesInput, new_hash_feedback, StdRand, RandomSeed, MutationResult, Mutator},
|
||||||
};
|
};
|
||||||
use libafl::prelude::State;
|
use crate::{systemstate::{FreeRTOSSystemStateMetadata, RefinedFreeRTOSSystemState}, fuzzer::DO_NUM_INTERRUPT, clock::IcHist};
|
||||||
use crate::{clock::{IcHist, QEMU_ISNS_PER_USEC}, fuzzer::{DO_NUM_INTERRUPT, FIRST_INT, MAX_NUM_INTERRUPT}, systemstate::{stg::{STGFeedbackState, STGNodeMetadata}, CaptureEvent, ExecInterval, FreeRTOSSystemStateMetadata, ReducedFreeRTOSSystemState}};
|
|
||||||
|
|
||||||
pub static mut MINIMUM_INTER_ARRIVAL_TIME : u32 = 1000 /*us*/ * QEMU_ISNS_PER_USEC;
|
|
||||||
// one isn per 2**4 ns
|
|
||||||
// virtual insn/sec 62500000 = 1/16 GHz
|
|
||||||
// 1ms = 62500 insn
|
|
||||||
// 1us = 62.5 insn
|
|
||||||
|
|
||||||
pub fn input_bytes_to_interrupt_times(buf: &[u8]) -> Vec<u32> {
|
|
||||||
let len = buf.len();
|
|
||||||
let mut start_tick : u32 = 0;
|
|
||||||
let mut ret = Vec::with_capacity(DO_NUM_INTERRUPT);
|
|
||||||
for i in 0..DO_NUM_INTERRUPT {
|
|
||||||
let mut t : [u8; 4] = [0,0,0,0];
|
|
||||||
if len > (i+1)*4 {
|
|
||||||
for j in 0usize..4usize {
|
|
||||||
t[j]=buf[i*4+j];
|
|
||||||
}
|
|
||||||
start_tick = u32::from_le_bytes(t);
|
|
||||||
if start_tick < FIRST_INT {start_tick=0;}
|
|
||||||
ret.push(start_tick);
|
|
||||||
} else {break;}
|
|
||||||
}
|
|
||||||
ret.sort_unstable();
|
|
||||||
// obey the minimum inter arrival time while maintaining the sort
|
|
||||||
for i in 0..ret.len() {
|
|
||||||
if ret[i]==0 {continue;}
|
|
||||||
for j in i+1..ret.len()-1 {
|
|
||||||
if ret[j]-ret[i] < unsafe{MINIMUM_INTER_ARRIVAL_TIME} {
|
|
||||||
ret[j] = u32::saturating_add(ret[i],unsafe{MINIMUM_INTER_ARRIVAL_TIME});
|
|
||||||
} else {break;}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
|
|
||||||
|
pub const MINIMUM_INTER_ARRIVAL_TIME : u32 = 700 * 1000 * (1 << 4);
|
||||||
|
|
||||||
//======================= Custom mutator
|
//======================= Custom mutator
|
||||||
|
|
||||||
/// The default mutational stage
|
/// The default mutational stage
|
||||||
#[derive(Clone, Debug, Default)]
|
#[derive(Clone, Debug, Default)]
|
||||||
pub struct InterruptShiftStage<E, EM, Z> {
|
pub struct MyStateStage<E, EM, Z> {
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
phantom: PhantomData<(E, EM, Z)>,
|
phantom: PhantomData<(E, EM, Z)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<E, EM, Z> InterruptShiftStage<E, EM, Z>
|
impl<E, EM, Z> MyStateStage<E, EM, Z>
|
||||||
where
|
where
|
||||||
E: UsesState<State = Z::State>,
|
E: UsesState<State = Z::State>,
|
||||||
EM: UsesState<State = Z::State>,
|
EM: UsesState<State = Z::State>,
|
||||||
Z: Evaluator<E, EM>,
|
Z: Evaluator<E, EM>,
|
||||||
Z::State: MaybeHasClientPerfMonitor + HasCorpus + HasRand,
|
Z::State: HasClientPerfMonitor + HasCorpus + HasRand,
|
||||||
{
|
{
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self { phantom: PhantomData }
|
Self { phantom: PhantomData }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<E, EM, Z> Stage<E, EM, Z> for InterruptShiftStage<E, EM, Z>
|
impl<E, EM, Z> Stage<E, EM, Z> for MyStateStage<E, EM, Z>
|
||||||
where
|
where
|
||||||
E: UsesState<State = Z::State>,
|
E: UsesState<State = Z::State>,
|
||||||
EM: UsesState<State = Z::State>,
|
EM: UsesState<State = Z::State>,
|
||||||
Z: Evaluator<E, EM>,
|
Z: Evaluator<E, EM>,
|
||||||
Z::State: MaybeHasClientPerfMonitor + HasCorpus + HasRand + HasMetadata + HasNamedMetadata,
|
Z::State: HasClientPerfMonitor + HasCorpus + HasRand + HasMetadata,
|
||||||
<Z::State as UsesInput>::Input: HasBytesVec
|
<Z::State as UsesInput>::Input: HasBytesVec
|
||||||
{
|
{
|
||||||
fn perform(
|
fn perform(
|
||||||
@ -85,240 +53,166 @@ where
|
|||||||
executor: &mut E,
|
executor: &mut E,
|
||||||
state: &mut Self::State,
|
state: &mut Self::State,
|
||||||
manager: &mut EM,
|
manager: &mut EM,
|
||||||
corpus_idx: CorpusId,
|
corpus_idx: usize,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
let mut _input = state
|
let mut _input = state
|
||||||
.corpus()
|
.corpus()
|
||||||
.get(corpus_idx)?
|
.get(corpus_idx)?
|
||||||
.borrow_mut().clone();
|
.borrow_mut().clone();
|
||||||
let mut newinput = _input.input_mut().as_mut().unwrap().clone();
|
let mut newinput = _input.input_mut().as_mut().unwrap().clone();
|
||||||
|
// let mut tmpinput = _input.input_mut().as_mut().unwrap().clone();
|
||||||
let mut do_rerun = false;
|
let mut do_rerun = false;
|
||||||
// if state.rand_mut().between(1, 100) <= 50 // only attempt the mutation half of the time
|
|
||||||
{
|
{
|
||||||
// need our own random generator, because borrowing rules
|
// need our own random generator, because borrowing rules
|
||||||
let mut myrand = StdRand::new();
|
let mut myrand = StdRand::new();
|
||||||
let mut target_bytes : Vec<u8> = vec![];
|
let mut target_bytes : Vec<u8> = vec![];
|
||||||
{
|
{
|
||||||
let input = _input.input_mut().as_ref().unwrap();
|
let input = _input.input_mut().as_ref().unwrap();
|
||||||
target_bytes = input.bytes().to_vec();
|
|
||||||
let tmp = &mut state.rand_mut();
|
let tmp = &mut state.rand_mut();
|
||||||
myrand.set_seed(tmp.next());
|
myrand.set_seed(tmp.next());
|
||||||
|
target_bytes = input.bytes().to_vec();
|
||||||
}
|
}
|
||||||
|
|
||||||
// produce a slice of absolute interrupt times
|
// produce a slice of absolute interrupt times
|
||||||
let mut interrupt_offsets : [u32; MAX_NUM_INTERRUPT] = [u32::MAX; MAX_NUM_INTERRUPT];
|
let mut interrupt_offsets : [u32; 32] = [0u32; 32];
|
||||||
let mut num_interrupts : usize = 0;
|
let mut num_interrupts : usize = 0;
|
||||||
{
|
{
|
||||||
let t = input_bytes_to_interrupt_times(&target_bytes);
|
let mut start_tick : u32 = 0;
|
||||||
for i in 0..t.len() {interrupt_offsets[i]=t[i];}
|
for i in 0..DO_NUM_INTERRUPT {
|
||||||
num_interrupts=t.len();
|
let mut t : [u8; 4] = [0,0,0,0];
|
||||||
|
if target_bytes.len() > (i+1)*4 {
|
||||||
|
for j in 0 as usize..4 as usize {
|
||||||
|
t[j]=target_bytes[i*4+j];
|
||||||
|
}
|
||||||
|
if i == 0 || true {
|
||||||
|
start_tick = u32::from_le_bytes(t);
|
||||||
|
} else {
|
||||||
|
start_tick = u32::saturating_add(start_tick,max(MINIMUM_INTER_ARRIVAL_TIME,u32::from_le_bytes(t)));
|
||||||
|
}
|
||||||
|
interrupt_offsets[i] = start_tick;
|
||||||
|
num_interrupts = i+1;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
interrupt_offsets.sort_unstable();
|
interrupt_offsets.sort();
|
||||||
|
|
||||||
// println!("Vor Mutator: {:?}", interrupt_offsets[0..num_interrupts].to_vec());
|
// println!("Vor Mutator: {:?}", interrupt_offsets[0..num_interrupts].to_vec());
|
||||||
// let num_i = min(target_bytes.len() / 4, DO_NUM_INTERRUPT);
|
// let num_i = min(target_bytes.len() / 4, DO_NUM_INTERRUPT);
|
||||||
let mut suffix = target_bytes.split_off(4 * num_interrupts);
|
let mut suffix = target_bytes.split_off(4 * num_interrupts);
|
||||||
let mut prefix : Vec<[u8; 4]> = vec![];
|
let mut prefix : Vec<[u8; 4]> = vec![];
|
||||||
// let mut suffix : Vec<u8> = vec![];
|
// let mut suffix : Vec<u8> = vec![];
|
||||||
#[cfg(feature = "mutate_stg")]
|
#[cfg(feature = "feed_systemtrace")]
|
||||||
{
|
{
|
||||||
let metadata = state.metadata_map();
|
let tmp = _input.metadata().get::<FreeRTOSSystemStateMetadata>();
|
||||||
let hist = metadata.get::<IcHist>().unwrap();
|
if tmp.is_some() {
|
||||||
let maxtick : u64 = hist.1.0;
|
let trace = tmp.expect("FreeRTOSSystemStateMetadata not found");
|
||||||
drop(hist);
|
|
||||||
if interrupt_offsets[0] as u64 > maxtick { // place interrupt in reachable range
|
|
||||||
do_rerun = true;
|
|
||||||
for _ in 0..num_interrupts {
|
|
||||||
prefix.push(u32::to_le_bytes(myrand.between(0, min(maxtick, u32::MAX as u64)).try_into().expect("ticks > u32")));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// let choice = myrand.between(1,100);
|
|
||||||
// if choice <= 25 { // 0.5*0.25 = 12.5% of the time fully randomize all interrupts
|
|
||||||
// do_rerun = true;
|
|
||||||
// // let metadata = state.metadata_map();
|
|
||||||
// let hist = metadata.get::<IcHist>().unwrap();
|
|
||||||
// let maxtick : u64 = hist.1.0;
|
|
||||||
// // let maxtick : u64 = (_input.exec_time().expect("No duration found").as_nanos() >> 4).try_into().unwrap();
|
|
||||||
// let mut numbers : Vec<u32> = vec![];
|
|
||||||
// for i in 0..num_interrupts {
|
|
||||||
// prefix.push(u32::to_le_bytes(myrand.between(0, min(maxtick, u32::MAX as u64)).try_into().expect("ticks > u32")));
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// else if choice <= 75 { // 0.5 * 0.25 = 12.5% of cases
|
|
||||||
// let feedbackstate = match state
|
|
||||||
// .named_metadata_map_mut()
|
|
||||||
// .get_mut::<STGFeedbackState>("stgfeedbackstate") {
|
|
||||||
// Some(s) => s,
|
|
||||||
// None => {
|
|
||||||
// panic!("STGfeedbackstate not visible")
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
// let tmp = _input.metadata_map().get::<STGNodeMetadata>();
|
|
||||||
// if tmp.is_some() {
|
|
||||||
// let trace = tmp.expect("STGNodeMetadata not found");
|
|
||||||
// let mut node_indices = vec![];
|
|
||||||
// for i in (0..trace.intervals.len()).into_iter() {
|
|
||||||
// if let Some(abb) = &trace.intervals[i].abb {
|
|
||||||
// if let Some(idx) = feedbackstate.state_abb_hash_index.get(&(abb.get_hash(), trace.intervals[i].start_state)) {
|
|
||||||
// node_indices.push(Some(idx));
|
|
||||||
// continue;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// node_indices.push(None);
|
|
||||||
// }
|
|
||||||
// // let mut marks : HashMap<u32, usize>= HashMap::new(); // interrupt -> block hit
|
|
||||||
// // for i in 0..trace.intervals.len() {
|
|
||||||
// // let curr = &trace.intervals[i];
|
|
||||||
// // let m = interrupt_offsets[0..num_interrupts].iter().filter(|x| (curr.start_tick..curr.end_tick).contains(&((**x) as u64)));
|
|
||||||
// // for k in m {
|
|
||||||
// // marks.insert(*k,i);
|
|
||||||
// // }
|
|
||||||
// // }
|
|
||||||
// // walk backwards trough the trace and try moving the interrupt to a block that does not have an outgoing interrupt edge or ist already hit by a predecessor
|
|
||||||
// for i in (0..num_interrupts).rev() {
|
|
||||||
// let mut lb = FIRST_INT;
|
|
||||||
// let mut ub : u32 = trace.intervals[trace.intervals.len()-1].end_tick.try_into().expect("ticks > u32");
|
|
||||||
// if i > 0 {
|
|
||||||
// lb = u32::saturating_add(interrupt_offsets[i-1],unsafe{MINIMUM_INTER_ARRIVAL_TIME});
|
|
||||||
// }
|
|
||||||
// if i < num_interrupts-1 {
|
|
||||||
// ub = u32::saturating_sub(interrupt_offsets[i+1],unsafe{MINIMUM_INTER_ARRIVAL_TIME});
|
|
||||||
// }
|
|
||||||
// let alternatives : Vec<_> = (0..trace.intervals.len()).filter(|x|
|
|
||||||
// node_indices[*x].is_some() &&
|
|
||||||
// (trace.intervals[*x].start_tick < (lb as u64) && (lb as u64) < trace.intervals[*x].end_tick
|
|
||||||
// || trace.intervals[*x].start_tick > (lb as u64) && trace.intervals[*x].start_tick < (ub as u64))
|
|
||||||
// ).collect();
|
|
||||||
// let not_yet_hit : Vec<_> = alternatives.iter().filter(
|
|
||||||
// |x| feedbackstate.graph.edges_directed(*node_indices[**x].unwrap(), petgraph::Direction::Outgoing).any(|y| y.weight().event != CaptureEvent::ISRStart)).collect();
|
|
||||||
// if not_yet_hit.len() > 0 {
|
|
||||||
// let replacement = &trace.intervals[*myrand.choose(not_yet_hit)];
|
|
||||||
// interrupt_offsets[i] = (myrand.between(replacement.start_tick,
|
|
||||||
// replacement.end_tick)).try_into().expect("ticks > u32");
|
|
||||||
// // println!("chose new alternative, i: {} {} -> {}",i,tmp, interrupt_offsets[i]);
|
|
||||||
// do_rerun = true;
|
|
||||||
// break;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// else { // old version of the alternative search
|
|
||||||
{
|
|
||||||
let tmp = _input.metadata_map().get::<STGNodeMetadata>();
|
|
||||||
if tmp.is_some() {
|
|
||||||
let trace = tmp.expect("STGNodeMetadata not found");
|
|
||||||
|
|
||||||
// calculate hits and identify snippets
|
// calculate hits and identify snippets
|
||||||
let mut last_m = false;
|
let mut last_m = false;
|
||||||
let mut marks : Vec<(&ExecInterval, usize, usize)>= vec![]; // 1: got interrupted, 2: interrupt handler
|
let mut marks : Vec<(&RefinedFreeRTOSSystemState, usize, usize)>= vec![]; // 1: got interrupted, 2: interrupt handler
|
||||||
for i in 0..trace.intervals.len() {
|
for i in 0..trace.inner.len() {
|
||||||
let curr = &trace.intervals[i];
|
let curr = &trace.inner[i];
|
||||||
let m = interrupt_offsets[0..num_interrupts].iter().any(|x| (curr.start_tick..curr.end_tick).contains(&(*x as u64)));
|
let m = interrupt_offsets[0..num_interrupts].iter().any(|x| (curr.start_tick..curr.end_tick).contains(&(*x as u64)));
|
||||||
if m {
|
if m {
|
||||||
marks.push((curr, i, 1));
|
marks.push((curr, i, 1));
|
||||||
// println!("1: {}",curr.current_task.0.task_name);
|
// println!("1: {}",curr.current_task.task_name);
|
||||||
} else if last_m {
|
} else if last_m {
|
||||||
marks.push((curr, i, 2));
|
marks.push((curr, i, 2));
|
||||||
// println!("2: {}",curr.current_task.0.task_name);
|
// println!("2: {}",curr.current_task.task_name);
|
||||||
} else {
|
} else {
|
||||||
marks.push((curr, i, 0));
|
marks.push((curr, i, 0));
|
||||||
}
|
}
|
||||||
last_m = m;
|
last_m = m;
|
||||||
}
|
}
|
||||||
for i in 0..num_interrupts {
|
for i in 0..num_interrupts {
|
||||||
// bounds based on minimum inter-arrival time
|
// bounds based on minimum inter-arrival time
|
||||||
let mut lb = FIRST_INT;
|
let mut lb = 0;
|
||||||
let mut ub : u32 = marks[marks.len()-1].0.end_tick.try_into().expect("ticks > u32");
|
let mut ub : u32 = marks[marks.len()-1].0.end_tick.try_into().expect("ticks > u32");
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
lb = u32::saturating_add(interrupt_offsets[i-1],unsafe{MINIMUM_INTER_ARRIVAL_TIME});
|
lb = u32::saturating_add(interrupt_offsets[i-1],MINIMUM_INTER_ARRIVAL_TIME);
|
||||||
}
|
}
|
||||||
if i < num_interrupts-1 {
|
if i < num_interrupts-1 {
|
||||||
ub = u32::saturating_sub(interrupt_offsets[i+1],unsafe{MINIMUM_INTER_ARRIVAL_TIME});
|
ub = u32::saturating_sub(interrupt_offsets[i+1],MINIMUM_INTER_ARRIVAL_TIME);
|
||||||
}
|
}
|
||||||
// get old hit and handler
|
// get old hit and handler
|
||||||
let old_hit = marks.iter().filter(
|
let old_hit = marks.iter().filter(
|
||||||
|x| x.0.start_tick < (interrupt_offsets[i] as u64) && (interrupt_offsets[i] as u64) < x.0.end_tick
|
|x| x.0.start_tick < (interrupt_offsets[i] as u64) && (interrupt_offsets[i] as u64) < x.0.end_tick
|
||||||
).next();
|
).next();
|
||||||
let old_handler = match old_hit {
|
let old_handler = match old_hit {
|
||||||
Some(s) => if s.1 < num_interrupts-1 && s.1 < marks.len()-1 {
|
Some(s) => if s.1 < num_interrupts-1 && s.1 < marks.len()-1 {
|
||||||
Some(marks[s.1+1])
|
Some(marks[s.1+1])
|
||||||
} else {None},
|
} else {None},
|
||||||
None => None
|
None => None
|
||||||
};
|
};
|
||||||
// find reachable alternatives
|
// find reachable alternatives
|
||||||
let alternatives : Vec<_> = marks.iter().filter(|x|
|
let alternatives : Vec<_> = marks.iter().filter(|x|
|
||||||
x.2 != 2 &&
|
x.2 != 2 &&
|
||||||
(
|
(
|
||||||
x.0.start_tick < (lb as u64) && (lb as u64) < x.0.end_tick
|
x.0.start_tick < (lb as u64) && (lb as u64) < x.0.end_tick
|
||||||
|| x.0.start_tick > (lb as u64) && x.0.start_tick < (ub as u64))
|
|| x.0.start_tick < (ub as u64) && (ub as u64) < x.0.end_tick )
|
||||||
|
).collect();
|
||||||
|
// in cases there are no alternatives
|
||||||
|
if alternatives.len() == 0 {
|
||||||
|
if old_hit.is_none() {
|
||||||
|
// choose something random
|
||||||
|
let untouched : Vec<_> = marks.iter().filter(
|
||||||
|
|x| x.2 == 0
|
||||||
).collect();
|
).collect();
|
||||||
// in cases there are no alternatives
|
if untouched.len() > 0 {
|
||||||
if alternatives.len() == 0 {
|
|
||||||
if old_hit.is_none() {
|
|
||||||
// choose something random
|
|
||||||
let untouched : Vec<_> = marks.iter().filter(
|
|
||||||
|x| x.2 == 0
|
|
||||||
).collect();
|
|
||||||
if untouched.len() > 0 {
|
|
||||||
let tmp = interrupt_offsets[i];
|
|
||||||
let choice = myrand.choose(untouched);
|
|
||||||
interrupt_offsets[i] = myrand.between(choice.0.start_tick, choice.0.end_tick)
|
|
||||||
.try_into().expect("tick > u32");
|
|
||||||
do_rerun = true;
|
|
||||||
}
|
|
||||||
// println!("no alternatives, choose random i: {} {} -> {}",i,tmp,interrupt_offsets[i]);
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
// do nothing
|
|
||||||
// println!("no alternatives, do nothing i: {} {}",i,interrupt_offsets[i]);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let replacement = myrand.choose(alternatives);
|
|
||||||
if (old_hit.map_or(false, |x| x == replacement)) {
|
|
||||||
// use the old value
|
|
||||||
// println!("chose old value, do nothing i: {} {}",i,interrupt_offsets[i]);
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
let extra = if (old_hit.map_or(false, |x| x.1 < replacement.1)) {
|
|
||||||
// move futher back, respect old_handler
|
|
||||||
old_handler.map_or(0, |x| x.0.end_tick - x.0.start_tick)
|
|
||||||
} else { 0 };
|
|
||||||
let tmp = interrupt_offsets[i];
|
let tmp = interrupt_offsets[i];
|
||||||
interrupt_offsets[i] = (myrand.between(replacement.0.start_tick,
|
let choice = myrand.choose(untouched);
|
||||||
replacement.0.end_tick) + extra).try_into().expect("ticks > u32");
|
interrupt_offsets[i] = myrand.between(choice.0.start_tick, choice.0.end_tick)
|
||||||
// println!("chose new alternative, i: {} {} -> {}",i,tmp, interrupt_offsets[i]);
|
.try_into().expect("tick > u32");
|
||||||
do_rerun = true;
|
do_rerun = true;
|
||||||
}
|
}
|
||||||
|
// println!("no alternatives, choose random i: {} {} -> {}",i,tmp,interrupt_offsets[i]);
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
// do nothing
|
||||||
|
// println!("no alternatives, do nothing i: {} {}",i,interrupt_offsets[i]);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
let mut numbers : Vec<u32> = interrupt_offsets[0..num_interrupts].to_vec();
|
}
|
||||||
numbers.sort();
|
let replacement = myrand.choose(alternatives);
|
||||||
// println!("Mutator: {:?}", numbers);
|
if (old_hit.map_or(false, |x| x == replacement)) {
|
||||||
// let mut start : u32 = 0;
|
// use the old value
|
||||||
// for i in 0..numbers.len() {
|
// println!("chose old value, do nothing i: {} {}",i,interrupt_offsets[i]);
|
||||||
// let tmp = numbers[i];
|
continue;
|
||||||
// numbers[i] = numbers[i]-start;
|
} else {
|
||||||
// start = tmp;
|
let extra = if (old_hit.map_or(false, |x| x.1 < replacement.1)) {
|
||||||
// }
|
// move futher back, respect old_handler
|
||||||
for i in 0..numbers.len() {
|
old_handler.map_or(0, |x| x.0.end_tick - x.0.start_tick)
|
||||||
prefix.push(u32::to_le_bytes(numbers[i]));
|
} else { 0 };
|
||||||
}
|
let tmp = interrupt_offsets[i];
|
||||||
}
|
interrupt_offsets[i] = (myrand.between(replacement.0.start_tick,
|
||||||
|
replacement.0.end_tick) + extra).try_into().expect("ticks > u32");
|
||||||
|
// println!("chose new alternative, i: {} {} -> {}",i,tmp, interrupt_offsets[i]);
|
||||||
|
do_rerun = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let mut numbers : Vec<u32> = interrupt_offsets[0..num_interrupts].to_vec();
|
||||||
|
numbers.sort();
|
||||||
|
// println!("Mutator: {:?}", numbers);
|
||||||
|
let mut start : u32 = 0;
|
||||||
|
// for i in 0..numbers.len() {
|
||||||
|
// let tmp = numbers[i];
|
||||||
|
// numbers[i] = numbers[i]-start;
|
||||||
|
// start = tmp;
|
||||||
|
// }
|
||||||
|
for i in 0..numbers.len() {
|
||||||
|
prefix.push(u32::to_le_bytes(numbers[i]));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
#[cfg(not(feature = "trace_stg"))]
|
#[cfg(not(feature = "feed_systemtrace"))]
|
||||||
{
|
{
|
||||||
if myrand.between(1,100) <= 25 { // we have no hint if interrupt times will change anything
|
let metadata = state.metadata();
|
||||||
do_rerun = true;
|
let hist = metadata.get::<IcHist>().unwrap();
|
||||||
let metadata = state.metadata_map();
|
let maxtick : u64 = hist.1.0;
|
||||||
let hist = metadata.get::<IcHist>().unwrap();
|
// let maxtick : u64 = (_input.exec_time().expect("No duration found").as_nanos() >> 4).try_into().unwrap();
|
||||||
let maxtick : u64 = hist.1.0;
|
let mut numbers : Vec<u32> = vec![];
|
||||||
// let maxtick : u64 = (_input.exec_time().expect("No duration found").as_nanos() >> 4).try_into().unwrap();
|
for i in 0..num_interrupts {
|
||||||
let mut numbers : Vec<u32> = vec![];
|
prefix.push(u32::to_le_bytes(myrand.between(0, min(maxtick, u32::MAX as u64)).try_into().expect("ticks > u32")));
|
||||||
for i in 0..num_interrupts {
|
|
||||||
prefix.push(u32::to_le_bytes(myrand.between(0, min(maxtick, u32::MAX as u64)).try_into().expect("ticks > u32")));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -335,12 +229,12 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<E, EM, Z> UsesState for InterruptShiftStage<E, EM, Z>
|
impl<E, EM, Z> UsesState for MyStateStage<E, EM, Z>
|
||||||
where
|
where
|
||||||
E: UsesState<State = Z::State>,
|
E: UsesState<State = Z::State>,
|
||||||
EM: UsesState<State = Z::State>,
|
EM: UsesState<State = Z::State>,
|
||||||
Z: Evaluator<E, EM>,
|
Z: Evaluator<E, EM>,
|
||||||
Z::State: MaybeHasClientPerfMonitor + HasCorpus + HasRand,
|
Z::State: HasClientPerfMonitor + HasCorpus + HasRand,
|
||||||
{
|
{
|
||||||
type State = Z::State;
|
type State = Z::State;
|
||||||
}
|
}
|
@ -44,19 +44,19 @@ where
|
|||||||
{
|
{
|
||||||
const HOOKS_DO_SIDE_EFFECTS: bool = true;
|
const HOOKS_DO_SIDE_EFFECTS: bool = true;
|
||||||
|
|
||||||
fn init_hooks<QT>(&self, _hooks: &QemuHooks<QT, S>)
|
fn init_hooks<QT>(&self, _hooks: &QemuHooks<'_, QT, S>)
|
||||||
where
|
where
|
||||||
QT: QemuHelperTuple<S>,
|
QT: QemuHelperTuple<S>,
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
fn first_exec<QT>(&self, _hooks: &QemuHooks<QT, S>)
|
fn first_exec<QT>(&self, _hooks: &QemuHooks<'_, QT, S>)
|
||||||
where
|
where
|
||||||
QT: QemuHelperTuple<S>,
|
QT: QemuHelperTuple<S>,
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
fn post_exec<OT>(&mut self, emulator: &Emulator, _input: &S::Input, _observers: &mut OT, _exit_kind: &mut ExitKind) {
|
fn post_exec(&mut self, emulator: &Emulator, _input: &S::Input) {
|
||||||
// unsafe { println!("snapshot post {}",emu::icount_get_raw()) };
|
// unsafe { println!("snapshot post {}",emu::icount_get_raw()) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,6 +0,0 @@
|
|||||||
# System-state heuristics
|
|
||||||
## Information flow
|
|
||||||
- ``fuzzer.rs`` resolves symbols and creates ``api_ranges`` and ``isr_ranges``
|
|
||||||
- ``helpers::QemuSystemStateHelper`` captures a series of ``RawFreeRTOSSystemState``
|
|
||||||
- ``observers::QemuSystemStateObserver`` divides this into ``ReducedFreeRTOSSystemState`` and ``ExecInterval``, the first contains the raw states and the second contains information about the flow between states
|
|
||||||
- ``stg::StgFeedback`` builds an stg from the intervals
|
|
@ -1,27 +1,25 @@
|
|||||||
use libafl::SerdeAny;
|
use libafl::SerdeAny;
|
||||||
use libafl_bolts::ownedref::OwnedSlice;
|
use libafl::bolts::ownedref::OwnedSlice;
|
||||||
use libafl::inputs::BytesInput;
|
use libafl::inputs::BytesInput;
|
||||||
use libafl::prelude::UsesInput;
|
use libafl::prelude::UsesInput;
|
||||||
use libafl::state::HasNamedMetadata;
|
use libafl::state::HasNamedMetadata;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use crate::clock::QemuClockObserver;
|
use crate::clock::QemuClockObserver;
|
||||||
use libafl::corpus::Testcase;
|
use libafl::corpus::Testcase;
|
||||||
use libafl_bolts::tuples::MatchName;
|
use libafl::bolts::tuples::MatchName;
|
||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
use std::hash::Hasher;
|
use std::hash::Hasher;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use libafl::events::EventFirer;
|
use libafl::events::EventFirer;
|
||||||
use libafl::state::MaybeHasClientPerfMonitor;
|
use libafl::state::HasClientPerfMonitor;
|
||||||
use libafl::prelude::State;
|
|
||||||
use libafl::feedbacks::Feedback;
|
use libafl::feedbacks::Feedback;
|
||||||
use libafl_bolts::Named;
|
use libafl::bolts::tuples::Named;
|
||||||
use libafl::Error;
|
use libafl::Error;
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
use libafl::{executors::ExitKind, inputs::Input, observers::ObserversTuple, state::HasMetadata};
|
use libafl::{executors::ExitKind, inputs::Input, observers::ObserversTuple, state::HasMetadata};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use super::ExecInterval;
|
use super::RefinedFreeRTOSSystemState;
|
||||||
use super::ReducedFreeRTOSSystemState;
|
|
||||||
use super::FreeRTOSSystemStateMetadata;
|
use super::FreeRTOSSystemStateMetadata;
|
||||||
use super::observers::QemuSystemStateObserver;
|
use super::observers::QemuSystemStateObserver;
|
||||||
use petgraph::prelude::DiGraph;
|
use petgraph::prelude::DiGraph;
|
||||||
@ -36,7 +34,7 @@ use std::cmp::Ordering;
|
|||||||
pub struct SystemStateFeedbackState
|
pub struct SystemStateFeedbackState
|
||||||
{
|
{
|
||||||
known_traces: HashMap<u64,(u64,u64,usize)>, // encounters,ticks,length
|
known_traces: HashMap<u64,(u64,u64,usize)>, // encounters,ticks,length
|
||||||
longest: Vec<ReducedFreeRTOSSystemState>,
|
longest: Vec<RefinedFreeRTOSSystemState>,
|
||||||
}
|
}
|
||||||
impl Named for SystemStateFeedbackState
|
impl Named for SystemStateFeedbackState
|
||||||
{
|
{
|
||||||
@ -45,18 +43,26 @@ impl Named for SystemStateFeedbackState
|
|||||||
"systemstate"
|
"systemstate"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// impl FeedbackState for systemstateFeedbackState
|
||||||
|
// {
|
||||||
|
// fn reset(&mut self) -> Result<(), Error> {
|
||||||
|
// self.longest.clear();
|
||||||
|
// self.known_traces.clear();
|
||||||
|
// Ok(())
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
/// A Feedback reporting novel System-State Transitions. Depends on [`QemuSystemStateObserver`]
|
/// A Feedback reporting novel System-State Transitions. Depends on [`QemuSystemStateObserver`]
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
||||||
pub struct NovelSystemStateFeedback
|
pub struct NovelSystemStateFeedback
|
||||||
{
|
{
|
||||||
last_trace: Option<Vec<ReducedFreeRTOSSystemState>>,
|
last_trace: Option<Vec<RefinedFreeRTOSSystemState>>,
|
||||||
// known_traces: HashMap<u64,(u64,usize)>,
|
// known_traces: HashMap<u64,(u64,usize)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> Feedback<S> for NovelSystemStateFeedback
|
impl<S> Feedback<S> for NovelSystemStateFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor + HasNamedMetadata,
|
S: UsesInput + HasClientPerfMonitor + HasNamedMetadata,
|
||||||
{
|
{
|
||||||
fn is_interesting<EM, OT>(
|
fn is_interesting<EM, OT>(
|
||||||
&mut self,
|
&mut self,
|
||||||
@ -75,13 +81,13 @@ where
|
|||||||
let clock_observer = observers.match_name::<QemuClockObserver>("clocktime") //TODO not fixed
|
let clock_observer = observers.match_name::<QemuClockObserver>("clocktime") //TODO not fixed
|
||||||
.expect("QemuClockObserver not found");
|
.expect("QemuClockObserver not found");
|
||||||
let feedbackstate = match state
|
let feedbackstate = match state
|
||||||
.named_metadata_map_mut()
|
.named_metadata_mut()
|
||||||
.get_mut::<SystemStateFeedbackState>("systemstate") {
|
.get_mut::<SystemStateFeedbackState>("systemstate") {
|
||||||
Some(s) => s,
|
Some(s) => s,
|
||||||
None => {
|
None => {
|
||||||
let n=SystemStateFeedbackState::default();
|
let n=SystemStateFeedbackState::default();
|
||||||
state.named_metadata_map_mut().insert(n, "systemstate");
|
state.named_metadata_mut().insert(n, "systemstate");
|
||||||
state.named_metadata_map_mut().get_mut::<SystemStateFeedbackState>("systemstate").unwrap()
|
state.named_metadata_mut().get_mut::<SystemStateFeedbackState>("systemstate").unwrap()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// let feedbackstate = state
|
// let feedbackstate = state
|
||||||
@ -117,10 +123,10 @@ where
|
|||||||
|
|
||||||
/// Append to the testcase the generated metadata in case of a new corpus item
|
/// Append to the testcase the generated metadata in case of a new corpus item
|
||||||
#[inline]
|
#[inline]
|
||||||
fn append_metadata<OT>(&mut self, _state: &mut S, observers: &OT, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
fn append_metadata(&mut self, _state: &mut S, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
||||||
let a = self.last_trace.take();
|
let a = self.last_trace.take();
|
||||||
match a {
|
match a {
|
||||||
Some(s) => testcase.metadata_map_mut().insert(FreeRTOSSystemStateMetadata::new(s)),
|
Some(s) => testcase.metadata_mut().insert(FreeRTOSSystemStateMetadata::new(s)),
|
||||||
None => (),
|
None => (),
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -142,20 +148,87 @@ impl Named for NovelSystemStateFeedback
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//=========================== Debugging Feedback
|
//=============================
|
||||||
/// A [`Feedback`] meant to dump the system-traces for debugging. Depends on [`QemuSystemStateObserver`]
|
|
||||||
#[derive(Debug)]
|
pub fn match_traces(target: &Vec<RefinedFreeRTOSSystemState>, last: &Vec<RefinedFreeRTOSSystemState>) -> bool {
|
||||||
pub struct DumpSystraceFeedback
|
let mut ret = true;
|
||||||
{
|
if target.len() > last.len() {return false;}
|
||||||
dumpfile: Option<PathBuf>,
|
for i in 0..target.len() {
|
||||||
dump_metadata: bool,
|
ret &= target[i].current_task.task_name==last[i].current_task.task_name;
|
||||||
last_states: Option<HashMap<u64, ReducedFreeRTOSSystemState>>,
|
}
|
||||||
last_trace: Option<Vec<ExecInterval>>,
|
ret
|
||||||
|
}
|
||||||
|
pub fn match_traces_name(target: &Vec<String>, last: &Vec<RefinedFreeRTOSSystemState>) -> bool {
|
||||||
|
let mut ret = true;
|
||||||
|
if target.len() > last.len() {return false;}
|
||||||
|
for i in 0..target.len() {
|
||||||
|
ret &= target[i]==last[i].current_task.task_name;
|
||||||
|
}
|
||||||
|
ret
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> Feedback<S> for DumpSystraceFeedback
|
/// A Feedback reporting novel System-State Transitions. Depends on [`QemuSystemStateObserver`]
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
||||||
|
pub struct HitSystemStateFeedback
|
||||||
|
{
|
||||||
|
target: Option<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> Feedback<S> for HitSystemStateFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor,
|
S: UsesInput + HasClientPerfMonitor,
|
||||||
|
{
|
||||||
|
fn is_interesting<EM, OT>(
|
||||||
|
&mut self,
|
||||||
|
state: &mut S,
|
||||||
|
manager: &mut EM,
|
||||||
|
input: &S::Input,
|
||||||
|
observers: &OT,
|
||||||
|
exit_kind: &ExitKind,
|
||||||
|
) -> Result<bool, Error>
|
||||||
|
where
|
||||||
|
EM: EventFirer<State = S>,
|
||||||
|
OT: ObserversTuple<S>
|
||||||
|
{
|
||||||
|
let observer = observers.match_name::<QemuSystemStateObserver>("systemstate")
|
||||||
|
.expect("QemuSystemStateObserver not found");
|
||||||
|
// Do Stuff
|
||||||
|
match &self.target {
|
||||||
|
Some(s) => {
|
||||||
|
// #[cfg(debug_assertions)] eprintln!("Hit systemstate Feedback trigger");
|
||||||
|
Ok(match_traces_name(s, &observer.last_run))
|
||||||
|
},
|
||||||
|
None => Ok(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Named for HitSystemStateFeedback
|
||||||
|
{
|
||||||
|
#[inline]
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"hit_systemstate"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HitSystemStateFeedback {
|
||||||
|
pub fn new(target: Option<Vec<RefinedFreeRTOSSystemState>>) -> Self {
|
||||||
|
Self {target: target.map(|x| x.into_iter().map(|y| y.current_task.task_name).collect())}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//=========================== Debugging Feedback
|
||||||
|
/// A [`Feedback`] meant to dump the system-traces for debugging. Depends on [`QemuSystemStateObserver`]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct DumpSystraceFeedback
|
||||||
|
{
|
||||||
|
dumpfile: Option<PathBuf>,
|
||||||
|
dump_metadata: bool,
|
||||||
|
last_trace: Option<Vec<RefinedFreeRTOSSystemState>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> Feedback<S> for DumpSystraceFeedback
|
||||||
|
where
|
||||||
|
S: UsesInput + HasClientPerfMonitor,
|
||||||
{
|
{
|
||||||
fn is_interesting<EM, OT>(
|
fn is_interesting<EM, OT>(
|
||||||
&mut self,
|
&mut self,
|
||||||
@ -169,29 +242,28 @@ where
|
|||||||
EM: EventFirer<State = S>,
|
EM: EventFirer<State = S>,
|
||||||
OT: ObserversTuple<S>
|
OT: ObserversTuple<S>
|
||||||
{
|
{
|
||||||
if self.dumpfile.is_none() {return Ok(false)};
|
|
||||||
let observer = observers.match_name::<QemuSystemStateObserver>("systemstate")
|
let observer = observers.match_name::<QemuSystemStateObserver>("systemstate")
|
||||||
.expect("QemuSystemStateObserver not found");
|
.expect("QemuSystemStateObserver not found");
|
||||||
let names : Vec<String> = observer.last_run.iter().map(|x| x.current_task.task_name.clone()).collect();
|
let names : Vec<String> = observer.last_run.iter().map(|x| x.current_task.task_name.clone()).collect();
|
||||||
match &self.dumpfile {
|
match &self.dumpfile {
|
||||||
Some(s) => {
|
Some(s) => {
|
||||||
std::fs::write(s,ron::to_string(&(&observer.last_trace,&observer.last_states)).expect("Error serializing hashmap")).expect("Can not dump to file");
|
std::fs::write(s,ron::to_string(&observer.last_run).expect("Error serializing hashmap")).expect("Can not dump to file");
|
||||||
self.dumpfile = None
|
self.dumpfile = None
|
||||||
},
|
},
|
||||||
None => if self.dump_metadata {println!("{:?}\n{:?}",observer.last_run,names);}
|
None => if !self.dump_metadata {println!("{:?}\n{:?}",observer.last_run,names);}
|
||||||
};
|
};
|
||||||
// if self.dump_metadata {self.last_trace=Some(observer.last_trace.clone());}
|
if self.dump_metadata {self.last_trace=Some(observer.last_run.clone());}
|
||||||
Ok(false)
|
Ok(!self.dump_metadata)
|
||||||
}
|
}
|
||||||
/// Append to the testcase the generated metadata in case of a new corpus item
|
/// Append to the testcase the generated metadata in case of a new corpus item
|
||||||
#[inline]
|
#[inline]
|
||||||
fn append_metadata<OT>(&mut self, _state: &mut S, observers: &OT, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
fn append_metadata(&mut self, _state: &mut S, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
||||||
if !self.dump_metadata {return Ok(());}
|
if !self.dump_metadata {return Ok(());}
|
||||||
// let a = self.last_trace.take();
|
let a = self.last_trace.take();
|
||||||
// match a {
|
match a {
|
||||||
// Some(s) => testcase.metadata_map_mut().insert(FreeRTOSSystemStateMetadata::new(s)),
|
Some(s) => testcase.metadata_mut().insert(FreeRTOSSystemStateMetadata::new(s)),
|
||||||
// None => (),
|
None => (),
|
||||||
// }
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -216,68 +288,12 @@ impl DumpSystraceFeedback
|
|||||||
/// Creates a new [`DumpSystraceFeedback`]
|
/// Creates a new [`DumpSystraceFeedback`]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {dumpfile: None, dump_metadata: false, last_trace: None, last_states: None }
|
Self {dumpfile: None, dump_metadata: false, last_trace: None}
|
||||||
}
|
}
|
||||||
pub fn with_dump(dumpfile: Option<PathBuf>) -> Self {
|
pub fn with_dump(dumpfile: Option<PathBuf>) -> Self {
|
||||||
Self {dumpfile: dumpfile, dump_metadata: false, last_trace: None, last_states: None}
|
Self {dumpfile: dumpfile, dump_metadata: false, last_trace: None}
|
||||||
}
|
}
|
||||||
pub fn metadata_only() -> Self {
|
pub fn metadata_only() -> Self {
|
||||||
Self {dumpfile: None, dump_metadata: true, last_trace: None, last_states: None}
|
Self {dumpfile: None, dump_metadata: true, last_trace: None}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct SystraceErrorFeedback
|
|
||||||
{
|
|
||||||
dump_case: bool
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S> Feedback<S> for SystraceErrorFeedback
|
|
||||||
where
|
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor,
|
|
||||||
{
|
|
||||||
fn is_interesting<EM, OT>(
|
|
||||||
&mut self,
|
|
||||||
_state: &mut S,
|
|
||||||
_manager: &mut EM,
|
|
||||||
_input: &S::Input,
|
|
||||||
observers: &OT,
|
|
||||||
_exit_kind: &ExitKind,
|
|
||||||
) -> Result<bool, Error>
|
|
||||||
where
|
|
||||||
EM: EventFirer<State = S>,
|
|
||||||
OT: ObserversTuple<S>
|
|
||||||
{
|
|
||||||
let observer = observers.match_name::<QemuSystemStateObserver>("systemstate")
|
|
||||||
.expect("QemuSystemStateObserver not found");
|
|
||||||
Ok(self.dump_case&&!observer.success)
|
|
||||||
}
|
|
||||||
/// Append to the testcase the generated metadata in case of a new corpus item
|
|
||||||
#[inline]
|
|
||||||
fn append_metadata<OT>(&mut self, _state: &mut S, _observers: &OT, _testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Discard the stored metadata in case that the testcase is not added to the corpus
|
|
||||||
#[inline]
|
|
||||||
fn discard_metadata(&mut self, _state: &mut S, _input: &S::Input) -> Result<(), Error> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Named for SystraceErrorFeedback
|
|
||||||
{
|
|
||||||
#[inline]
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"SystraceErrorFeedback"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SystraceErrorFeedback
|
|
||||||
{
|
|
||||||
#[must_use]
|
|
||||||
pub fn new(dump_case: bool) -> Self {
|
|
||||||
Self {dump_case}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -2,44 +2,41 @@
|
|||||||
use libafl::SerdeAny;
|
use libafl::SerdeAny;
|
||||||
/// Feedbacks organizing SystemStates as a graph
|
/// Feedbacks organizing SystemStates as a graph
|
||||||
use libafl::inputs::HasBytesVec;
|
use libafl::inputs::HasBytesVec;
|
||||||
use libafl_bolts::rands::RandomSeed;
|
use libafl::bolts::rands::RandomSeed;
|
||||||
use libafl_bolts::rands::StdRand;
|
use libafl::bolts::rands::StdRand;
|
||||||
use libafl::mutators::Mutator;
|
use libafl::mutators::Mutator;
|
||||||
use libafl::mutators::MutationResult;
|
use libafl::mutators::MutationResult;
|
||||||
use libafl::prelude::HasTargetBytes;
|
use libafl::prelude::HasTargetBytes;
|
||||||
use libafl::prelude::UsesInput;
|
use libafl::prelude::UsesInput;
|
||||||
use libafl::state::HasNamedMetadata;
|
use libafl::state::HasNamedMetadata;
|
||||||
use libafl::state::UsesState;
|
use libafl::state::UsesState;
|
||||||
use libafl::prelude::State;
|
|
||||||
use core::marker::PhantomData;
|
use core::marker::PhantomData;
|
||||||
use libafl::state::HasCorpus;
|
use libafl::state::HasCorpus;
|
||||||
use libafl::state::HasSolutions;
|
use libafl::state::HasSolutions;
|
||||||
use libafl::state::HasRand;
|
use libafl::state::HasRand;
|
||||||
use crate::worst::MaxExecsLenFavFactor;
|
use crate::worst::MaxExecsLenFavFactor;
|
||||||
use crate::worst::MaxTimeFavFactor;
|
|
||||||
use libafl::schedulers::MinimizerScheduler;
|
use libafl::schedulers::MinimizerScheduler;
|
||||||
use libafl_bolts::HasRefCnt;
|
use libafl::bolts::HasRefCnt;
|
||||||
use libafl_bolts::AsSlice;
|
use libafl::bolts::AsSlice;
|
||||||
use libafl_bolts::ownedref::OwnedSlice;
|
use libafl::bolts::ownedref::OwnedSlice;
|
||||||
use libafl::inputs::BytesInput;
|
use libafl::inputs::BytesInput;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use crate::clock::QemuClockObserver;
|
use crate::clock::QemuClockObserver;
|
||||||
use libafl::corpus::Testcase;
|
use libafl::corpus::Testcase;
|
||||||
use libafl_bolts::tuples::MatchName;
|
use libafl::bolts::tuples::MatchName;
|
||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
use std::hash::Hasher;
|
use std::hash::Hasher;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use libafl::events::EventFirer;
|
use libafl::events::EventFirer;
|
||||||
use libafl::state::MaybeHasClientPerfMonitor;
|
use libafl::state::HasClientPerfMonitor;
|
||||||
use libafl::feedbacks::Feedback;
|
use libafl::feedbacks::Feedback;
|
||||||
use libafl_bolts::Named;
|
use libafl::bolts::tuples::Named;
|
||||||
use libafl::Error;
|
use libafl::Error;
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
use libafl::{executors::ExitKind, inputs::Input, observers::ObserversTuple, state::HasMetadata};
|
use libafl::{executors::ExitKind, inputs::Input, observers::ObserversTuple, state::HasMetadata};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use super::ExecInterval;
|
use super::RefinedFreeRTOSSystemState;
|
||||||
use super::ReducedFreeRTOSSystemState;
|
|
||||||
use super::FreeRTOSSystemStateMetadata;
|
use super::FreeRTOSSystemStateMetadata;
|
||||||
use super::observers::QemuSystemStateObserver;
|
use super::observers::QemuSystemStateObserver;
|
||||||
use petgraph::prelude::DiGraph;
|
use petgraph::prelude::DiGraph;
|
||||||
@ -47,7 +44,7 @@ use petgraph::graph::NodeIndex;
|
|||||||
use petgraph::Direction;
|
use petgraph::Direction;
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
use libafl_bolts::rands::Rand;
|
use libafl::bolts::rands::Rand;
|
||||||
|
|
||||||
//============================= Data Structures
|
//============================= Data Structures
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
|
||||||
@ -59,25 +56,24 @@ pub struct VariantTuple
|
|||||||
pub input: Vec<u8>, // in the end any kind of input are bytes, regardless of type and lifetime
|
pub input: Vec<u8>, // in the end any kind of input are bytes, regardless of type and lifetime
|
||||||
}
|
}
|
||||||
impl VariantTuple {
|
impl VariantTuple {
|
||||||
fn from(other: &ReducedFreeRTOSSystemState,input: Vec<u8>) -> Self {
|
fn from(other: &RefinedFreeRTOSSystemState,input: Vec<u8>) -> Self {
|
||||||
// VariantTuple{
|
VariantTuple{
|
||||||
// start_tick: other.tick,
|
start_tick: other.start_tick,
|
||||||
// end_tick: other.end_tick,
|
end_tick: other.end_tick,
|
||||||
// input_counter: other.input_counter,
|
input_counter: other.input_counter,
|
||||||
// input: input,
|
input: input,
|
||||||
// }
|
}
|
||||||
todo!()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
||||||
pub struct SysGraphNode
|
pub struct SysGraphNode
|
||||||
{
|
{
|
||||||
base: ReducedFreeRTOSSystemState,
|
base: RefinedFreeRTOSSystemState,
|
||||||
pub variants: Vec<VariantTuple>,
|
pub variants: Vec<VariantTuple>,
|
||||||
}
|
}
|
||||||
impl SysGraphNode {
|
impl SysGraphNode {
|
||||||
fn from(base: ReducedFreeRTOSSystemState, input: Vec<u8>) -> Self {
|
fn from(base: RefinedFreeRTOSSystemState, input: Vec<u8>) -> Self {
|
||||||
SysGraphNode{variants: vec![VariantTuple::from(&base, input)], base:base }
|
SysGraphNode{variants: vec![VariantTuple::from(&base, input)], base:base }
|
||||||
}
|
}
|
||||||
/// unites the variants of this value with another, draining the other if the bases are equal
|
/// unites the variants of this value with another, draining the other if the bases are equal
|
||||||
@ -88,26 +84,25 @@ impl SysGraphNode {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
/// add a Varint from a [`RefinedFreeRTOSSystemState`]
|
/// add a Varint from a [`RefinedFreeRTOSSystemState`]
|
||||||
fn unite_raw(&mut self, other: &ReducedFreeRTOSSystemState, input: &Vec<u8>) -> bool {
|
fn unite_raw(&mut self, other: &RefinedFreeRTOSSystemState, input: &Vec<u8>) -> bool {
|
||||||
if &self.base!=other {return false;}
|
if &self.base!=other {return false;}
|
||||||
self.variants.push(VariantTuple::from(other, input.clone()));
|
self.variants.push(VariantTuple::from(other, input.clone()));
|
||||||
self.variants.dedup();
|
self.variants.dedup();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
/// add a Varint from a [`RefinedFreeRTOSSystemState`], if it's interesting
|
/// add a Varint from a [`RefinedFreeRTOSSystemState`], if it's interesting
|
||||||
fn unite_interesting(&mut self, other: &ReducedFreeRTOSSystemState, input: &Vec<u8>) -> bool {
|
fn unite_interesting(&mut self, other: &RefinedFreeRTOSSystemState, input: &Vec<u8>) -> bool {
|
||||||
// if &self.base!=other {return false;}
|
if &self.base!=other {return false;}
|
||||||
// let interesting =
|
let interesting =
|
||||||
// self.variants.iter().all(|x| x.end_tick-x.start_tick<other.end_tick-other.tick) || // longest variant
|
self.variants.iter().all(|x| x.end_tick-x.start_tick<other.end_tick-other.start_tick) || // longest variant
|
||||||
// self.variants.iter().all(|x| x.end_tick-x.start_tick>other.end_tick-other.tick) || // shortest variant
|
self.variants.iter().all(|x| x.end_tick-x.start_tick>other.end_tick-other.start_tick) || // shortest variant
|
||||||
// self.variants.iter().all(|x| x.input_counter>other.input_counter) || // longest input
|
self.variants.iter().all(|x| x.input_counter>other.input_counter) || // longest input
|
||||||
// self.variants.iter().all(|x| x.input_counter<other.input_counter); // shortest input
|
self.variants.iter().all(|x| x.input_counter<other.input_counter); // shortest input
|
||||||
// if interesting {
|
if interesting {
|
||||||
// let var = VariantTuple::from(other, input.clone());
|
let var = VariantTuple::from(other, input.clone());
|
||||||
// self.variants.push(var);
|
self.variants.push(var);
|
||||||
// }
|
}
|
||||||
// return interesting;
|
return interesting;
|
||||||
todo!()
|
|
||||||
}
|
}
|
||||||
pub fn get_taskname(&self) -> &str {
|
pub fn get_taskname(&self) -> &str {
|
||||||
&self.base.current_task.task_name
|
&self.base.current_task.task_name
|
||||||
@ -115,20 +110,6 @@ impl SysGraphNode {
|
|||||||
pub fn get_input_counts(&self) -> Vec<u32> {
|
pub fn get_input_counts(&self) -> Vec<u32> {
|
||||||
self.variants.iter().map(|x| x.input_counter).collect()
|
self.variants.iter().map(|x| x.input_counter).collect()
|
||||||
}
|
}
|
||||||
pub fn pretty_print(&self) -> String {
|
|
||||||
let mut ret = String::new();
|
|
||||||
ret.push_str(&format!("{}",&self.base.current_task.task_name));
|
|
||||||
ret.push_str(";Rl:");
|
|
||||||
for i in &self.base.ready_list_after {
|
|
||||||
ret.push_str(&format!(";{}",i.task_name));
|
|
||||||
}
|
|
||||||
ret.push_str(";Dl:");
|
|
||||||
for i in &self.base.delay_list_after {
|
|
||||||
ret.push_str(&format!(";{}",i.task_name));
|
|
||||||
}
|
|
||||||
// println!("{}",ret);
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
impl PartialEq for SysGraphNode {
|
impl PartialEq for SysGraphNode {
|
||||||
fn eq(&self, other: &SysGraphNode) -> bool {
|
fn eq(&self, other: &SysGraphNode) -> bool {
|
||||||
@ -167,15 +148,15 @@ impl HasRefCnt for SysGraphMetadata {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
libafl_bolts::impl_serdeany!(SysGraphMetadata);
|
libafl::impl_serdeany!(SysGraphMetadata);
|
||||||
|
|
||||||
pub type GraphMaximizerCorpusScheduler<CS> =
|
pub type GraphMaximizerCorpusScheduler<CS> =
|
||||||
MinimizerScheduler<CS, MaxTimeFavFactor<<CS as UsesState>::State>,SysGraphMetadata>;
|
MinimizerScheduler<CS, MaxExecsLenFavFactor<<CS as UsesState>::State>,SysGraphMetadata>;
|
||||||
|
|
||||||
//============================= Graph Feedback
|
//============================= Graph Feedback
|
||||||
|
|
||||||
/// Improved System State Graph
|
/// Improved System State Graph
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, SerdeAny)]
|
#[derive(Serialize, Deserialize, Clone, Debug, Default, SerdeAny)]
|
||||||
pub struct SysGraphFeedbackState
|
pub struct SysGraphFeedbackState
|
||||||
{
|
{
|
||||||
pub graph: DiGraph<SysGraphNode, ()>,
|
pub graph: DiGraph<SysGraphNode, ()>,
|
||||||
@ -195,7 +176,7 @@ impl SysGraphFeedbackState
|
|||||||
let exit = graph.add_node(exit);
|
let exit = graph.add_node(exit);
|
||||||
Self {graph: graph, entrypoint: entry, exit: exit, name: String::from("SysMap")}
|
Self {graph: graph, entrypoint: entry, exit: exit, name: String::from("SysMap")}
|
||||||
}
|
}
|
||||||
fn insert(&mut self, list: Vec<ReducedFreeRTOSSystemState>, input: &Vec<u8>) {
|
fn insert(&mut self, list: Vec<RefinedFreeRTOSSystemState>, input: &Vec<u8>) {
|
||||||
let mut current_index = self.entrypoint;
|
let mut current_index = self.entrypoint;
|
||||||
for n in list {
|
for n in list {
|
||||||
let mut done = false;
|
let mut done = false;
|
||||||
@ -214,16 +195,17 @@ impl SysGraphFeedbackState
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Try adding a system state path from a [Vec<RefinedFreeRTOSSystemState>], return true if the path was interesting
|
/// Try adding a system state path from a [Vec<RefinedFreeRTOSSystemState>], return true if the path was interesting
|
||||||
fn update(&mut self, list: &Vec<ReducedFreeRTOSSystemState>, input: &Vec<u8>) -> (bool, Vec<NodeIndex>) {
|
fn update(&mut self, list: &Vec<RefinedFreeRTOSSystemState>, input: &Vec<u8>) -> (bool, Vec<NodeIndex>) {
|
||||||
let mut current_index = self.entrypoint;
|
let mut current_index = self.entrypoint;
|
||||||
let mut novel = false;
|
let mut novel = false;
|
||||||
let mut trace : Vec<NodeIndex> = vec![current_index];
|
let mut trace : Vec<NodeIndex> = vec![current_index];
|
||||||
for n in list {
|
for n in list {
|
||||||
let mut matching : Option<NodeIndex> = None;
|
let mut matching : Option<NodeIndex> = None;
|
||||||
for i in self.graph.node_indices() {
|
for i in self.graph.neighbors_directed(current_index, Direction::Outgoing) {
|
||||||
let tmp = &self.graph[i];
|
let tmp = &self.graph[i];
|
||||||
if n == &tmp.base {
|
if n == &tmp.base {
|
||||||
matching = Some(i);
|
matching = Some(i);
|
||||||
|
current_index = i;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -231,20 +213,16 @@ impl SysGraphFeedbackState
|
|||||||
None => {
|
None => {
|
||||||
novel = true;
|
novel = true;
|
||||||
let j = self.graph.add_node(SysGraphNode::from(n.clone(),input.clone()));
|
let j = self.graph.add_node(SysGraphNode::from(n.clone(),input.clone()));
|
||||||
self.graph.update_edge(current_index, j, ());
|
self.graph.add_edge(current_index, j, ());
|
||||||
current_index = j;
|
current_index = j;
|
||||||
},
|
},
|
||||||
Some(i) => {
|
Some(i) => {
|
||||||
novel |= self.graph[i].unite_interesting(&n, input);
|
novel |= self.graph[i].unite_interesting(&n, input);
|
||||||
self.graph.update_edge(current_index, i, ());
|
|
||||||
current_index = i;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
trace.push(current_index);
|
trace.push(current_index);
|
||||||
}
|
}
|
||||||
if current_index != self.entrypoint {
|
self.graph.update_edge(current_index, self.exit, ()); // every path ends in the exit noded
|
||||||
self.graph.update_edge(current_index, self.exit, ()); // every path ends in the exit noded
|
|
||||||
}
|
|
||||||
return (novel, trace);
|
return (novel, trace);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -255,11 +233,6 @@ impl Named for SysGraphFeedbackState
|
|||||||
&self.name
|
&self.name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Default for SysGraphFeedbackState {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl SysGraphFeedbackState
|
impl SysGraphFeedbackState
|
||||||
{
|
{
|
||||||
fn reset(&mut self) -> Result<(), Error> {
|
fn reset(&mut self) -> Result<(), Error> {
|
||||||
@ -289,7 +262,7 @@ impl SysMapFeedback {
|
|||||||
|
|
||||||
impl<S> Feedback<S> for SysMapFeedback
|
impl<S> Feedback<S> for SysMapFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor + HasNamedMetadata,
|
S: UsesInput + HasClientPerfMonitor + HasNamedMetadata,
|
||||||
S::Input: HasTargetBytes,
|
S::Input: HasTargetBytes,
|
||||||
{
|
{
|
||||||
#[allow(clippy::wrong_self_convention)]
|
#[allow(clippy::wrong_self_convention)]
|
||||||
@ -308,13 +281,13 @@ where
|
|||||||
let observer = observers.match_name::<QemuSystemStateObserver>("systemstate")
|
let observer = observers.match_name::<QemuSystemStateObserver>("systemstate")
|
||||||
.expect("QemuSystemStateObserver not found");
|
.expect("QemuSystemStateObserver not found");
|
||||||
let feedbackstate = match state
|
let feedbackstate = match state
|
||||||
.named_metadata_map_mut()
|
.named_metadata_mut()
|
||||||
.get_mut::<SysGraphFeedbackState>("SysMap") {
|
.get_mut::<SysGraphFeedbackState>("SysMap") {
|
||||||
Some(s) => s,
|
Some(s) => s,
|
||||||
None => {
|
None => {
|
||||||
let n=SysGraphFeedbackState::default();
|
let n=SysGraphFeedbackState::default();
|
||||||
state.named_metadata_map_mut().insert(n, "SysMap");
|
state.named_metadata_mut().insert(n, "SysMap");
|
||||||
state.named_metadata_map_mut().get_mut::<SysGraphFeedbackState>("SysMap").unwrap()
|
state.named_metadata_mut().get_mut::<SysGraphFeedbackState>("SysMap").unwrap()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let ret = feedbackstate.update(&observer.last_run, &observer.last_input);
|
let ret = feedbackstate.update(&observer.last_run, &observer.last_input);
|
||||||
@ -324,10 +297,10 @@ where
|
|||||||
|
|
||||||
/// Append to the testcase the generated metadata in case of a new corpus item
|
/// Append to the testcase the generated metadata in case of a new corpus item
|
||||||
#[inline]
|
#[inline]
|
||||||
fn append_metadata<OT>(&mut self, _state: &mut S, _observers: &OT, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
fn append_metadata(&mut self, _state: &mut S, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
||||||
let a = self.last_trace.take();
|
let a = self.last_trace.take();
|
||||||
match a {
|
match a {
|
||||||
Some(s) => testcase.metadata_map_mut().insert(SysGraphMetadata::new(s)),
|
Some(s) => testcase.metadata_mut().insert(SysGraphMetadata::new(s)),
|
||||||
None => (),
|
None => (),
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -1,29 +1,20 @@
|
|||||||
use std::cell::UnsafeCell;
|
use std::cell::UnsafeCell;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
use hashbrown::HashMap;
|
|
||||||
use libafl::prelude::ExitKind;
|
|
||||||
use libafl::prelude::UsesInput;
|
use libafl::prelude::UsesInput;
|
||||||
use libafl_qemu::read_user_reg_unchecked;
|
|
||||||
use libafl_qemu::Emulator;
|
use libafl_qemu::Emulator;
|
||||||
use libafl_qemu::GuestAddr;
|
use libafl_qemu::GuestAddr;
|
||||||
use libafl_qemu::GuestPhysAddr;
|
|
||||||
use libafl_qemu::GuestReg;
|
|
||||||
use libafl_qemu::QemuHooks;
|
use libafl_qemu::QemuHooks;
|
||||||
use libafl_qemu::edges::QemuEdgesMapMetadata;
|
use libafl_qemu::edges::QemuEdgesMapMetadata;
|
||||||
use libafl_qemu::emu;
|
use libafl_qemu::emu;
|
||||||
use libafl_qemu::hooks;
|
use libafl_qemu::hooks;
|
||||||
use libafl_qemu::Hook;
|
|
||||||
// use crate::systemstate::extract_abbs_from_trace;
|
|
||||||
use crate::systemstate::RawFreeRTOSSystemState;
|
use crate::systemstate::RawFreeRTOSSystemState;
|
||||||
use crate::systemstate::CURRENT_SYSTEMSTATE_VEC;
|
use crate::systemstate::CURRENT_SYSTEMSTATE_VEC;
|
||||||
use crate::systemstate::NUM_PRIOS;
|
use crate::systemstate::NUM_PRIOS;
|
||||||
use super::freertos::void_ptr;
|
|
||||||
use super::freertos::TCB_t;
|
use super::freertos::TCB_t;
|
||||||
use super::freertos::rtos_struct::List_Item_struct;
|
use super::freertos::rtos_struct::List_Item_struct;
|
||||||
use super::freertos::rtos_struct::*;
|
use super::freertos::rtos_struct::*;
|
||||||
use super::freertos;
|
use super::freertos;
|
||||||
use super::CaptureEvent;
|
|
||||||
|
|
||||||
use libafl_qemu::{
|
use libafl_qemu::{
|
||||||
helper::{QemuHelper, QemuHelperTuple},
|
helper::{QemuHelper, QemuHelperTuple},
|
||||||
@ -38,64 +29,31 @@ pub static mut INTR_DONE : bool = true;
|
|||||||
// only used when inputs are injected
|
// only used when inputs are injected
|
||||||
pub static mut NEXT_INPUT : Vec<u8> = Vec::new();
|
pub static mut NEXT_INPUT : Vec<u8> = Vec::new();
|
||||||
|
|
||||||
//============================= API symbols
|
|
||||||
|
|
||||||
pub const ISR_SYMBOLS : &'static [&'static str] = &[
|
|
||||||
// ISRs
|
|
||||||
"Reset_Handler","Default_Handler","Default_Handler2","Default_Handler3","Default_Handler4","Default_Handler5","Default_Handler6","vPortSVCHandler","xPortPendSVHandler","xPortSysTickHandler","isr_starter"//,"vTaskGenericNotifyGiveFromISR"
|
|
||||||
];
|
|
||||||
|
|
||||||
//============================= Qemu Helper
|
//============================= Qemu Helper
|
||||||
|
|
||||||
/// A Qemu Helper with reads FreeRTOS specific structs from Qemu whenever certain syscalls occur, also inject inputs
|
/// A Qemu Helper with reads FreeRTOS specific structs from Qemu whenever certain syscalls occur, also inject inputs
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct QemuSystemStateHelper {
|
pub struct QemuSystemStateHelper {
|
||||||
// Address of API functions
|
kerneladdr: u32,
|
||||||
api_fn_addrs: HashMap<GuestAddr, String>,
|
tcb_addr: u32,
|
||||||
api_fn_ranges: Vec<(String, std::ops::Range<GuestAddr>)>,
|
ready_queues: u32,
|
||||||
// Address of interrupt routines
|
input_counter: Option<u64>,
|
||||||
isr_addrs: HashMap<GuestAddr, String>,
|
app_range: Range<u32>,
|
||||||
isr_ranges: Vec<(String, std::ops::Range<GuestAddr>)>,
|
|
||||||
tcb_addr: GuestAddr,
|
|
||||||
ready_queues: GuestAddr,
|
|
||||||
delay_queue: GuestAddr,
|
|
||||||
delay_queue_overflow: GuestAddr,
|
|
||||||
scheduler_lock_addr: GuestAddr,
|
|
||||||
scheduler_running_addr: GuestAddr,
|
|
||||||
critical_addr: GuestAddr,
|
|
||||||
input_counter: Option<GuestAddr>,
|
|
||||||
app_range: Range<GuestAddr>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl QemuSystemStateHelper {
|
impl QemuSystemStateHelper {
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(
|
pub fn new(
|
||||||
api_fn_addrs: HashMap<GuestAddr, String>,
|
kerneladdr: u32,
|
||||||
api_fn_ranges: Vec<(String, std::ops::Range<GuestAddr>)>,
|
tcb_addr: u32,
|
||||||
isr_addrs: HashMap<GuestAddr, String>,
|
ready_queues: u32,
|
||||||
isr_ranges: Vec<(String, std::ops::Range<GuestAddr>)>,
|
input_counter: Option<u64>,
|
||||||
tcb_addr: GuestAddr,
|
app_range: Range<u32>,
|
||||||
ready_queues: GuestAddr,
|
|
||||||
delay_queue: GuestAddr,
|
|
||||||
delay_queue_overflow: GuestAddr,
|
|
||||||
scheduler_lock_addr: GuestAddr,
|
|
||||||
scheduler_running_addr: GuestAddr,
|
|
||||||
critical_addr: GuestAddr,
|
|
||||||
input_counter: Option<GuestAddr>,
|
|
||||||
app_range: Range<GuestAddr>,
|
|
||||||
) -> Self {
|
) -> Self {
|
||||||
QemuSystemStateHelper {
|
QemuSystemStateHelper {
|
||||||
api_fn_addrs,
|
kerneladdr,
|
||||||
api_fn_ranges,
|
|
||||||
isr_addrs,
|
|
||||||
isr_ranges,
|
|
||||||
tcb_addr: tcb_addr,
|
tcb_addr: tcb_addr,
|
||||||
ready_queues: ready_queues,
|
ready_queues: ready_queues,
|
||||||
delay_queue,
|
|
||||||
delay_queue_overflow,
|
|
||||||
scheduler_lock_addr,
|
|
||||||
scheduler_running_addr,
|
|
||||||
critical_addr,
|
|
||||||
input_counter: input_counter,
|
input_counter: input_counter,
|
||||||
app_range,
|
app_range,
|
||||||
}
|
}
|
||||||
@ -106,167 +64,103 @@ impl<S> QemuHelper<S> for QemuSystemStateHelper
|
|||||||
where
|
where
|
||||||
S: UsesInput,
|
S: UsesInput,
|
||||||
{
|
{
|
||||||
fn first_exec<QT>(&self, _hooks: &QemuHooks<QT, S>)
|
fn first_exec<QT>(&self, _hooks: &QemuHooks<'_, QT, S>)
|
||||||
where
|
where
|
||||||
QT: QemuHelperTuple<S>,
|
QT: QemuHelperTuple<S>,
|
||||||
{
|
{
|
||||||
// for wp in self.api_fn_addrs.keys() {
|
_hooks.instruction(self.kerneladdr, exec_syscall_hook::<QT, S>, false);
|
||||||
// _hooks.instruction(*wp, Hook::Function(exec_syscall_hook::<QT, S>), false);
|
#[cfg(feature = "trace_abbs")]
|
||||||
// }
|
_hooks.jmps(Some(gen_jmp_is_syscall::<QT, S>), Some(trace_api_call::<QT, S>));
|
||||||
for wp in self.isr_addrs.keys() {
|
|
||||||
_hooks.instruction(*wp, Hook::Function(exec_isr_hook::<QT, S>), false);
|
|
||||||
}
|
|
||||||
_hooks.jmps(Hook::Function(gen_jmp_is_syscall::<QT, S>), Hook::Function(trace_jmp::<QT, S>));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: refactor duplicate code
|
// TODO: refactor duplicate code
|
||||||
fn pre_exec(&mut self, _emulator: &Emulator, _input: &S::Input) {
|
fn pre_exec(&mut self, _emulator: &Emulator, _input: &S::Input) {
|
||||||
unsafe {
|
unsafe {
|
||||||
CURRENT_SYSTEMSTATE_VEC.clear();
|
CURRENT_SYSTEMSTATE_VEC.clear();
|
||||||
|
let p = LAST_API_CALL.with(|x| x.get());
|
||||||
|
*p = None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn post_exec<OT>(&mut self, emulator: &Emulator, _input: &S::Input, _observers: &mut OT, _exit_kind: &mut ExitKind) {
|
fn post_exec(&mut self, emulator: &Emulator, _input: &S::Input) {
|
||||||
trigger_collection(emulator,(0, 0), CaptureEvent::End, self);
|
trigger_collection(emulator, self)
|
||||||
unsafe {
|
|
||||||
let c = emulator.cpu_from_index(0);
|
|
||||||
let pc = c.read_reg::<i32, u32>(15).unwrap();
|
|
||||||
CURRENT_SYSTEMSTATE_VEC[CURRENT_SYSTEMSTATE_VEC.len()-1].edge = (pc,0);
|
|
||||||
CURRENT_SYSTEMSTATE_VEC[CURRENT_SYSTEMSTATE_VEC.len()-1].capture_point = (CaptureEvent::End,"Breakpoint".to_string());
|
|
||||||
}
|
|
||||||
// Find the first ISREnd of vPortSVCHandler and drop anything before
|
|
||||||
unsafe {
|
|
||||||
let mut index = 0;
|
|
||||||
while index < CURRENT_SYSTEMSTATE_VEC.len() {
|
|
||||||
if CaptureEvent::ISREnd == CURRENT_SYSTEMSTATE_VEC[index].capture_point.0 && CURRENT_SYSTEMSTATE_VEC[index].capture_point.1 == "xPortPendSVHandler" {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
index += 1;
|
|
||||||
}
|
|
||||||
CURRENT_SYSTEMSTATE_VEC.drain(..index);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_freertos_list(systemstate : &mut RawFreeRTOSSystemState, emulator: &Emulator, target: GuestAddr) -> freertos::List_t {
|
|
||||||
let read : freertos::List_t = freertos::emu_lookup::lookup(emulator, target);
|
|
||||||
let listbytes : GuestAddr = GuestAddr::try_from(std::mem::size_of::<freertos::List_t>()).unwrap();
|
|
||||||
|
|
||||||
let mut next_index = read.pxIndex;
|
|
||||||
for _j in 0..read.uxNumberOfItems {
|
|
||||||
// always jump over the xListEnd marker
|
|
||||||
if (target..target+listbytes).contains(&next_index) {
|
|
||||||
let next_item : freertos::MiniListItem_t = freertos::emu_lookup::lookup(emulator, next_index);
|
|
||||||
let new_next_index=next_item.pxNext;
|
|
||||||
systemstate.dumping_ground.insert(next_index,List_MiniItem_struct(next_item));
|
|
||||||
next_index = new_next_index;
|
|
||||||
}
|
|
||||||
let next_item : freertos::ListItem_t = freertos::emu_lookup::lookup(emulator, next_index);
|
|
||||||
// println!("Item at {}: {:?}",next_index,next_item);
|
|
||||||
if next_item.pvContainer != target {
|
|
||||||
// the list is being modified, abort by setting the list empty
|
|
||||||
eprintln!("Warning: attempted to read a list that is being modified");
|
|
||||||
let mut read=read;
|
|
||||||
read.uxNumberOfItems = 0;
|
|
||||||
return read;
|
|
||||||
}
|
|
||||||
// assert_eq!(next_item.pvContainer,target);
|
|
||||||
let new_next_index=next_item.pxNext;
|
|
||||||
let next_tcb : TCB_t= freertos::emu_lookup::lookup(emulator,next_item.pvOwner);
|
|
||||||
// println!("TCB at {}: {:?}",next_item.pvOwner,next_tcb);
|
|
||||||
systemstate.dumping_ground.insert(next_item.pvOwner,TCB_struct(next_tcb.clone()));
|
|
||||||
systemstate.dumping_ground.insert(next_index,List_Item_struct(next_item));
|
|
||||||
next_index=new_next_index;
|
|
||||||
}
|
|
||||||
// Handle edge case where the end marker was not included yet
|
|
||||||
if (target..target+listbytes).contains(&next_index) {
|
|
||||||
let next_item : freertos::MiniListItem_t = freertos::emu_lookup::lookup(emulator, next_index);
|
|
||||||
systemstate.dumping_ground.insert(next_index,List_MiniItem_struct(next_item));
|
|
||||||
}
|
|
||||||
return read;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn trigger_collection(emulator: &Emulator, edge: (GuestAddr, GuestAddr), event: CaptureEvent, h: &QemuSystemStateHelper) {
|
fn trigger_collection(emulator: &Emulator, h: &QemuSystemStateHelper) {
|
||||||
let listbytes : GuestAddr = GuestAddr::try_from(std::mem::size_of::<freertos::List_t>()).unwrap();
|
let listbytes : u32 = u32::try_from(std::mem::size_of::<freertos::List_t>()).unwrap();
|
||||||
let mut systemstate = RawFreeRTOSSystemState::default();
|
let mut systemstate = RawFreeRTOSSystemState::default();
|
||||||
|
unsafe {
|
||||||
match event {
|
// TODO: investigate why can_do_io is not set sometimes, as this is just a workaround
|
||||||
CaptureEvent::APIStart => {
|
let c = emulator.cpu_from_index(0);
|
||||||
let s = h.api_fn_addrs.get(&edge.1).unwrap();
|
let can_do_io = (*c.raw_ptr()).can_do_io;
|
||||||
systemstate.capture_point=(CaptureEvent::APIStart, s.to_string());
|
(*c.raw_ptr()).can_do_io = 1;
|
||||||
},
|
systemstate.qemu_tick = emu::icount_get_raw();
|
||||||
CaptureEvent::APIEnd => {
|
(*c.raw_ptr()).can_do_io = can_do_io;
|
||||||
let s = h.api_fn_addrs.get(&edge.0).unwrap();
|
|
||||||
systemstate.capture_point=(CaptureEvent::APIEnd, s.to_string());
|
|
||||||
},
|
|
||||||
CaptureEvent::ISRStart => {
|
|
||||||
let s = h.isr_addrs.get(&edge.1).unwrap();
|
|
||||||
systemstate.capture_point=(CaptureEvent::ISRStart, s.to_string());
|
|
||||||
},
|
|
||||||
CaptureEvent::ISREnd => {
|
|
||||||
let s = h.isr_addrs.get(&edge.0).unwrap();
|
|
||||||
systemstate.capture_point=(CaptureEvent::ISREnd, s.to_string());
|
|
||||||
},
|
|
||||||
CaptureEvent::End => {systemstate.capture_point=(CaptureEvent::End, "".to_string());},
|
|
||||||
CaptureEvent::Undefined => (),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if systemstate.capture_point.0 == CaptureEvent::Undefined {
|
|
||||||
// println!("Not found: {:#x} {:#x}", edge.0.unwrap_or(0), edge.1.unwrap_or(0));
|
|
||||||
}
|
|
||||||
systemstate.edge = ((edge.0),(edge.1));
|
|
||||||
|
|
||||||
systemstate.qemu_tick = get_icount(emulator);
|
|
||||||
|
|
||||||
let mut buf : [u8; 4] = [0,0,0,0];
|
let mut buf : [u8; 4] = [0,0,0,0];
|
||||||
match h.input_counter {
|
match h.input_counter {
|
||||||
Some(s) => unsafe { emulator.read_mem(s, &mut buf); },
|
Some(s) => unsafe { emulator.read_phys_mem(s, &mut buf); },
|
||||||
None => (),
|
None => (),
|
||||||
};
|
};
|
||||||
systemstate.input_counter = GuestAddr::from_le_bytes(buf);
|
systemstate.input_counter = u32::from_le_bytes(buf);
|
||||||
|
|
||||||
let curr_tcb_addr : freertos::void_ptr = freertos::emu_lookup::lookup(emulator, h.tcb_addr);
|
let curr_tcb_addr : freertos::void_ptr = freertos::emu_lookup::lookup(emulator, h.tcb_addr);
|
||||||
if curr_tcb_addr == 0 {
|
if curr_tcb_addr == 0 {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
// println!("{:?}",std::str::from_utf8(¤t_tcb.pcTaskName));
|
|
||||||
let critical : void_ptr = freertos::emu_lookup::lookup(emulator, h.critical_addr);
|
|
||||||
let suspended : void_ptr = freertos::emu_lookup::lookup(emulator, h.scheduler_lock_addr);
|
|
||||||
let running : void_ptr = freertos::emu_lookup::lookup(emulator, h.scheduler_running_addr);
|
|
||||||
|
|
||||||
systemstate.current_tcb = freertos::emu_lookup::lookup(emulator,curr_tcb_addr);
|
systemstate.current_tcb = freertos::emu_lookup::lookup(emulator,curr_tcb_addr);
|
||||||
// During ISRs it is only safe to extract structs if they are not currently being modified
|
|
||||||
if systemstate.capture_point.0==CaptureEvent::APIStart || systemstate.capture_point.0==CaptureEvent::APIEnd || (critical == 0 && suspended == 0 ) {
|
|
||||||
// Extract delay list
|
|
||||||
let mut target : GuestAddr = h.delay_queue;
|
|
||||||
target = freertos::emu_lookup::lookup(emulator, target);
|
|
||||||
systemstate.delay_list = read_freertos_list(&mut systemstate, emulator, target);
|
|
||||||
|
|
||||||
// Extract delay list overflow
|
unsafe {
|
||||||
let mut target : GuestAddr = h.delay_queue_overflow;
|
LAST_API_CALL.with(|x|
|
||||||
target = freertos::emu_lookup::lookup(emulator, target);
|
match *x.get() {
|
||||||
systemstate.delay_list_overflow = read_freertos_list(&mut systemstate, emulator, target);
|
Some(s) => {
|
||||||
|
systemstate.last_pc = Some(s.0 as u64);
|
||||||
|
},
|
||||||
|
None => (),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// println!("{:?}",std::str::from_utf8(¤t_tcb.pcTaskName));
|
||||||
|
|
||||||
// Extract priority lists
|
for i in 0..NUM_PRIOS {
|
||||||
for i in 0..NUM_PRIOS {
|
let target : u32 = listbytes*u32::try_from(i).unwrap()+h.ready_queues;
|
||||||
let target : GuestAddr = listbytes*GuestAddr::try_from(i).unwrap()+h.ready_queues;
|
systemstate.prio_ready_lists[i] = freertos::emu_lookup::lookup(emulator, target);
|
||||||
systemstate.prio_ready_lists[i] = read_freertos_list(&mut systemstate, emulator, target);
|
// println!("List at {}: {:?}",target, systemstate.prio_ready_lists[i]);
|
||||||
|
let mut next_index = systemstate.prio_ready_lists[i].pxIndex;
|
||||||
|
for _j in 0..systemstate.prio_ready_lists[i].uxNumberOfItems {
|
||||||
|
// always jump over the xListEnd marker
|
||||||
|
if (target..target+listbytes).contains(&next_index) {
|
||||||
|
let next_item : freertos::MiniListItem_t = freertos::emu_lookup::lookup(emulator, next_index);
|
||||||
|
let new_next_index=next_item.pxNext;
|
||||||
|
systemstate.dumping_ground.insert(next_index,List_MiniItem_struct(next_item));
|
||||||
|
next_index = new_next_index;
|
||||||
|
}
|
||||||
|
let next_item : freertos::ListItem_t = freertos::emu_lookup::lookup(emulator, next_index);
|
||||||
|
// println!("Item at {}: {:?}",next_index,next_item);
|
||||||
|
assert_eq!(next_item.pvContainer,target);
|
||||||
|
let new_next_index=next_item.pxNext;
|
||||||
|
let next_tcb : TCB_t= freertos::emu_lookup::lookup(emulator,next_item.pvOwner);
|
||||||
|
// println!("TCB at {}: {:?}",next_item.pvOwner,next_tcb);
|
||||||
|
systemstate.dumping_ground.insert(next_item.pvOwner,TCB_struct(next_tcb.clone()));
|
||||||
|
systemstate.dumping_ground.insert(next_index,List_Item_struct(next_item));
|
||||||
|
next_index=new_next_index;
|
||||||
|
}
|
||||||
|
// Handle edge case where the end marker was not included yet
|
||||||
|
if (target..target+listbytes).contains(&next_index) {
|
||||||
|
let next_item : freertos::MiniListItem_t = freertos::emu_lookup::lookup(emulator, next_index);
|
||||||
|
systemstate.dumping_ground.insert(next_index,List_MiniItem_struct(next_item));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
unsafe { CURRENT_SYSTEMSTATE_VEC.push(systemstate); }
|
unsafe { CURRENT_SYSTEMSTATE_VEC.push(systemstate); }
|
||||||
}
|
}
|
||||||
|
|
||||||
//============================= Trace interrupt service routines
|
pub fn exec_syscall_hook<QT, S>(
|
||||||
|
hooks: &mut QemuHooks<'_, QT, S>,
|
||||||
pub fn exec_isr_hook<QT, S>(
|
|
||||||
hooks: &mut QemuHooks<QT, S>,
|
|
||||||
_state: Option<&mut S>,
|
_state: Option<&mut S>,
|
||||||
pc: GuestAddr,
|
_pc: u32,
|
||||||
)
|
)
|
||||||
where
|
where
|
||||||
S: UsesInput,
|
S: UsesInput,
|
||||||
@ -274,15 +168,13 @@ where
|
|||||||
{
|
{
|
||||||
let emulator = hooks.emulator();
|
let emulator = hooks.emulator();
|
||||||
let h = hooks.helpers().match_first_type::<QemuSystemStateHelper>().expect("QemuSystemHelper not found in helper tupel");
|
let h = hooks.helpers().match_first_type::<QemuSystemStateHelper>().expect("QemuSystemHelper not found in helper tupel");
|
||||||
let src = read_rec_return_stackframe(emulator, 0xfffffffc);
|
trigger_collection(emulator, h);
|
||||||
trigger_collection(emulator, (src, pc), CaptureEvent::ISRStart, h);
|
|
||||||
// println!("Exec ISR Call {:#x} {:#x} {}", src, pc, get_icount(emulator));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//============================= Trace syscalls and returns
|
thread_local!(static LAST_API_CALL : UnsafeCell<Option<(GuestAddr,GuestAddr)>> = UnsafeCell::new(None));
|
||||||
|
|
||||||
pub fn gen_jmp_is_syscall<QT, S>(
|
pub fn gen_jmp_is_syscall<QT, S>(
|
||||||
hooks: &mut QemuHooks<QT, S>,
|
hooks: &mut QemuHooks<'_, QT, S>,
|
||||||
_state: Option<&mut S>,
|
_state: Option<&mut S>,
|
||||||
src: GuestAddr,
|
src: GuestAddr,
|
||||||
dest: GuestAddr,
|
dest: GuestAddr,
|
||||||
@ -292,102 +184,26 @@ where
|
|||||||
QT: QemuHelperTuple<S>,
|
QT: QemuHelperTuple<S>,
|
||||||
{
|
{
|
||||||
if let Some(h) = hooks.helpers().match_first_type::<QemuSystemStateHelper>() {
|
if let Some(h) = hooks.helpers().match_first_type::<QemuSystemStateHelper>() {
|
||||||
if h.app_range.contains(&src) && !h.app_range.contains(&dest) && in_any_range(&h.isr_ranges,src).is_none() {
|
if h.app_range.contains(&src) && !h.app_range.contains(&dest) {
|
||||||
if let Some(_) = in_any_range(&h.api_fn_ranges,dest) {
|
// println!("New jmp {:x} {:x}", src, dest);
|
||||||
// println!("New jmp {:x} {:x}", src, dest);
|
return Some(1);
|
||||||
// println!("API Call Edge {:x} {:x}", src, dest);
|
|
||||||
return Some(1);
|
|
||||||
// TODO: trigger collection right here
|
|
||||||
// otherwise there can be a race-condition, where LAST_API_CALL is set before the api starts, if the interrupt handler calls an api function, it will misidentify the callsite of that api call
|
|
||||||
}
|
|
||||||
} else if dest == 0 { // !h.app_range.contains(&src) &&
|
|
||||||
if let Some(_) = in_any_range(&h.api_fn_ranges, src) {
|
|
||||||
// println!("API Return Edge {:#x}", src);
|
|
||||||
return Some(2);
|
|
||||||
}
|
|
||||||
if let Some(_) = in_any_range(&h.isr_ranges, src) {
|
|
||||||
// println!("ISR Return Edge {:#x}", src);
|
|
||||||
return Some(3);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn trace_jmp<QT, S>(
|
pub fn trace_api_call<QT, S>(
|
||||||
hooks: &mut QemuHooks<QT, S>,
|
_hooks: &mut QemuHooks<'_, QT, S>,
|
||||||
_state: Option<&mut S>,
|
_state: Option<&mut S>,
|
||||||
src: GuestAddr, mut dest: GuestAddr, id: u64
|
src: GuestAddr, dest: GuestAddr, id: u64
|
||||||
)
|
)
|
||||||
where
|
where
|
||||||
S: UsesInput,
|
S: UsesInput,
|
||||||
QT: QemuHelperTuple<S>,
|
QT: QemuHelperTuple<S>,
|
||||||
{
|
{
|
||||||
let h = hooks.helpers().match_first_type::<QemuSystemStateHelper>().expect("QemuSystemHelper not found in helper tupel");
|
|
||||||
let emulator = hooks.emulator();
|
|
||||||
if id == 1 { // API call
|
|
||||||
trigger_collection(emulator, (src, dest), CaptureEvent::APIStart, h);
|
|
||||||
// println!("Exec API Call {:#x} {:#x} {}", src, dest, get_icount(emulator));
|
|
||||||
} else if id == 2 { // API return
|
|
||||||
// Ignore returns to other APIs or ISRs. We only account for the first call depth of API calls from user space.
|
|
||||||
if in_any_range(&h.api_fn_ranges, dest).is_none() && in_any_range(&h.isr_ranges, dest).is_none() {
|
|
||||||
|
|
||||||
let mut edge = (0, 0);
|
|
||||||
edge.0=in_any_range(&h.api_fn_ranges, src).unwrap().start;
|
|
||||||
edge.1=dest;
|
|
||||||
|
|
||||||
trigger_collection(emulator, edge, CaptureEvent::APIEnd, h);
|
|
||||||
// println!("Exec API Return Edge {:#x} {:#x} {}", src, dest, get_icount(emulator));
|
|
||||||
}
|
|
||||||
} else if id == 3 { // ISR return
|
|
||||||
dest = read_rec_return_stackframe(emulator, dest);
|
|
||||||
|
|
||||||
let mut edge = (0, 0);
|
|
||||||
edge.0=in_any_range(&h.isr_ranges, src).unwrap().start;
|
|
||||||
edge.1=dest;
|
|
||||||
|
|
||||||
trigger_collection(emulator, edge, CaptureEvent::ISREnd, h);
|
|
||||||
// println!("Exec ISR Return Edge {:#x} {:#x} {}", src, dest, get_icount(emulator));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//============================= Utility functions
|
|
||||||
|
|
||||||
fn get_icount(emulator : &Emulator) -> u64 {
|
|
||||||
unsafe {
|
unsafe {
|
||||||
// TODO: investigate why can_do_io is not set sometimes, as this is just a workaround
|
let p = LAST_API_CALL.with(|x| x.get());
|
||||||
let c = emulator.cpu_from_index(0);
|
*p = Some((src,dest));
|
||||||
let can_do_io = (*c.raw_ptr()).neg.can_do_io;
|
// print!("*");
|
||||||
(*c.raw_ptr()).neg.can_do_io = true;
|
|
||||||
let r = emu::icount_get_raw();
|
|
||||||
(*c.raw_ptr()).neg.can_do_io = can_do_io;
|
|
||||||
r
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_rec_return_stackframe(emu : &Emulator, lr : GuestAddr) -> GuestAddr {
|
|
||||||
let lr_ = lr & u32::MAX-1;
|
|
||||||
if lr_ == 0xfffffffc || lr_ == 0xFFFFFFF8 || lr_ == 0xFFFFFFF0 {
|
|
||||||
unsafe {
|
|
||||||
// if 0xFFFFFFF0/1 0xFFFFFFF8/9 -> "main stack" MSP
|
|
||||||
let mut buf = [0u8; 4];
|
|
||||||
let sp : GuestAddr = if lr_ == 0xfffffffc || lr_ == 0xFFFFFFF0 { // PSP
|
|
||||||
read_user_reg_unchecked(emu) as u32
|
|
||||||
} else {
|
|
||||||
emu.read_reg(13).unwrap()
|
|
||||||
};
|
|
||||||
let ret_pc = sp+0x18; // https://developer.arm.com/documentation/dui0552/a/the-cortex-m3-processor/exception-model/exception-entry-and-return
|
|
||||||
emu.read_mem(ret_pc, buf.as_mut_slice());
|
|
||||||
return u32::from_le_bytes(buf);
|
|
||||||
// elseif 0xfffffffc/d
|
|
||||||
}} else {
|
|
||||||
return lr;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn in_any_range<'a>(ranges: &'a Vec<(String, Range<u32>)>, addr : GuestAddr) -> Option<&'a std::ops::Range<GuestAddr>> {
|
|
||||||
for (_,r) in ranges {
|
|
||||||
if r.contains(&addr) {return Some(r);}
|
|
||||||
}
|
|
||||||
return None;
|
|
||||||
}
|
|
@ -1,15 +1,11 @@
|
|||||||
//! systemstate referes to the State of a FreeRTOS fuzzing target
|
//! systemstate referes to the State of a FreeRTOS fuzzing target
|
||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
use std::fmt;
|
use libafl::bolts::HasRefCnt;
|
||||||
use hashbrown::HashSet;
|
use libafl::bolts::AsSlice;
|
||||||
use libafl_bolts::HasRefCnt;
|
|
||||||
use libafl_bolts::AsSlice;
|
|
||||||
use libafl_qemu::GuestAddr;
|
|
||||||
use std::hash::Hasher;
|
use std::hash::Hasher;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use freertos::TCB_t;
|
use freertos::TCB_t;
|
||||||
|
|
||||||
@ -19,69 +15,47 @@ pub mod observers;
|
|||||||
pub mod feedbacks;
|
pub mod feedbacks;
|
||||||
pub mod graph;
|
pub mod graph;
|
||||||
pub mod schedulers;
|
pub mod schedulers;
|
||||||
pub mod stg;
|
|
||||||
|
// #[cfg(feature = "fuzz_interrupt")]
|
||||||
|
// pub const IRQ_INPUT_BYTES_NUMBER : u32 = 2; // Offset for interrupt bytes
|
||||||
|
// #[cfg(not(feature = "fuzz_interrupt"))]
|
||||||
|
// pub const IRQ_INPUT_BYTES_NUMBER : u32 = 0; // Offset for interrupt bytes
|
||||||
|
// pub const IRQ_INPUT_OFFSET : u32 = 347780; // Tick offset for app code start
|
||||||
|
|
||||||
// Constants
|
// Constants
|
||||||
const NUM_PRIOS: usize = 5;
|
const NUM_PRIOS: usize = 5;
|
||||||
|
|
||||||
//============================= Struct definitions
|
//============================= Struct definitions
|
||||||
|
|
||||||
#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)]
|
|
||||||
pub enum CaptureEvent {
|
|
||||||
APIStart, /// src,dst
|
|
||||||
APIEnd, /// src,dst
|
|
||||||
ISRStart, /// _,dst
|
|
||||||
ISREnd, /// src,_
|
|
||||||
End, /// src,_
|
|
||||||
#[default]
|
|
||||||
Undefined,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// Raw info Dump from Qemu
|
/// Raw info Dump from Qemu
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
pub struct RawFreeRTOSSystemState {
|
pub struct RawFreeRTOSSystemState {
|
||||||
qemu_tick: u64,
|
qemu_tick: u64,
|
||||||
current_tcb: TCB_t,
|
current_tcb: TCB_t,
|
||||||
prio_ready_lists: [freertos::List_t; NUM_PRIOS],
|
prio_ready_lists: [freertos::List_t; NUM_PRIOS],
|
||||||
delay_list: freertos::List_t,
|
|
||||||
delay_list_overflow: freertos::List_t,
|
|
||||||
dumping_ground: HashMap<u32,freertos::rtos_struct>,
|
dumping_ground: HashMap<u32,freertos::rtos_struct>,
|
||||||
input_counter: u32,
|
input_counter: u32,
|
||||||
edge: (GuestAddr,GuestAddr),
|
last_pc: Option<u64>,
|
||||||
capture_point: (CaptureEvent,String)
|
|
||||||
}
|
}
|
||||||
/// List of system state dumps from QemuHelpers
|
/// List of system state dumps from QemuHelpers
|
||||||
static mut CURRENT_SYSTEMSTATE_VEC: Vec<RawFreeRTOSSystemState> = vec![];
|
static mut CURRENT_SYSTEMSTATE_VEC: Vec<RawFreeRTOSSystemState> = vec![];
|
||||||
|
|
||||||
/// A reduced version of freertos::TCB_t
|
/// A reduced version of freertos::TCB_t
|
||||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
|
||||||
pub struct RefinedTCB {
|
pub struct RefinedTCB {
|
||||||
pub task_name: String,
|
pub task_name: String,
|
||||||
pub priority: u32,
|
pub priority: u32,
|
||||||
pub base_priority: u32,
|
pub base_priority: u32,
|
||||||
mutexes_held: u32,
|
mutexes_held: u32,
|
||||||
// notify_value: u32,
|
notify_value: u32,
|
||||||
notify_state: u8,
|
notify_state: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialEq for RefinedTCB {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
let ret = self.task_name == other.task_name &&
|
|
||||||
self.priority == other.priority &&
|
|
||||||
self.base_priority == other.base_priority;
|
|
||||||
#[cfg(feature = "do_hash_notify_state")]
|
|
||||||
let ret = ret && self.notify_state == other.notify_state;
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Hash for RefinedTCB {
|
impl Hash for RefinedTCB {
|
||||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
self.task_name.hash(state);
|
self.task_name.hash(state);
|
||||||
self.priority.hash(state);
|
self.priority.hash(state);
|
||||||
self.mutexes_held.hash(state);
|
self.mutexes_held.hash(state);
|
||||||
#[cfg(feature = "do_hash_notify_state")]
|
#[cfg(not(feature = "no_hash_state"))]
|
||||||
self.notify_state.hash(state);
|
self.notify_state.hash(state);
|
||||||
// self.notify_value.hash(state);
|
// self.notify_value.hash(state);
|
||||||
}
|
}
|
||||||
@ -97,7 +71,7 @@ impl RefinedTCB {
|
|||||||
priority: input.uxPriority,
|
priority: input.uxPriority,
|
||||||
base_priority: input.uxBasePriority,
|
base_priority: input.uxBasePriority,
|
||||||
mutexes_held: input.uxMutexesHeld,
|
mutexes_held: input.uxMutexesHeld,
|
||||||
// notify_value: input.ulNotifiedValue[0],
|
notify_value: input.ulNotifiedValue[0],
|
||||||
notify_state: input.ucNotifyState[0],
|
notify_state: input.ucNotifyState[0],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -111,124 +85,53 @@ impl RefinedTCB {
|
|||||||
priority: input.uxPriority,
|
priority: input.uxPriority,
|
||||||
base_priority: input.uxBasePriority,
|
base_priority: input.uxBasePriority,
|
||||||
mutexes_held: input.uxMutexesHeld,
|
mutexes_held: input.uxMutexesHeld,
|
||||||
// notify_value: input.ulNotifiedValue[0],
|
notify_value: input.ulNotifiedValue[0],
|
||||||
notify_state: input.ucNotifyState[0],
|
notify_state: input.ucNotifyState[0],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reduced information about a systems state, without any execution context
|
/// Refined information about the states an execution transitioned between
|
||||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||||
pub struct ReducedFreeRTOSSystemState {
|
pub struct RefinedFreeRTOSSystemState {
|
||||||
// pub tick: u64,
|
pub start_tick: u64,
|
||||||
|
pub end_tick: u64,
|
||||||
|
last_pc: Option<u64>,
|
||||||
|
input_counter: u32,
|
||||||
pub current_task: RefinedTCB,
|
pub current_task: RefinedTCB,
|
||||||
ready_list_after: Vec<RefinedTCB>,
|
ready_list_after: Vec<RefinedTCB>,
|
||||||
delay_list_after: Vec<RefinedTCB>,
|
|
||||||
// edge: (Option<GuestAddr>,Option<GuestAddr>),
|
|
||||||
// pub capture_point: (CaptureEvent,String),
|
|
||||||
// input_counter: u32
|
|
||||||
}
|
}
|
||||||
impl PartialEq for ReducedFreeRTOSSystemState {
|
impl PartialEq for RefinedFreeRTOSSystemState {
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
self.current_task == other.current_task && self.ready_list_after == other.ready_list_after &&
|
self.current_task == other.current_task && self.ready_list_after == other.ready_list_after &&
|
||||||
self.delay_list_after == other.delay_list_after
|
self.last_pc == other.last_pc
|
||||||
// && self.edge == other.edge
|
|
||||||
// && self.capture_point == other.capture_point
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Hash for ReducedFreeRTOSSystemState {
|
impl Hash for RefinedFreeRTOSSystemState {
|
||||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
self.current_task.hash(state);
|
self.current_task.hash(state);
|
||||||
self.ready_list_after.hash(state);
|
self.ready_list_after.hash(state);
|
||||||
self.delay_list_after.hash(state);
|
// self.last_pc.hash(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl ReducedFreeRTOSSystemState {
|
impl RefinedFreeRTOSSystemState {
|
||||||
// fn get_tick(&self) -> u64 {
|
fn get_time(&self) -> u64 {
|
||||||
// self.tick
|
self.end_tick-self.start_tick
|
||||||
// }
|
|
||||||
|
|
||||||
pub fn print_lists(&self) -> String {
|
|
||||||
let mut ret = String::from("+");
|
|
||||||
for j in self.ready_list_after.iter() {
|
|
||||||
ret.push_str(format!(" {}", j.task_name).as_str());
|
|
||||||
}
|
|
||||||
ret.push_str("\n-");
|
|
||||||
for j in self.delay_list_after.iter() {
|
|
||||||
ret.push_str(format!(" {}", j.task_name).as_str());
|
|
||||||
}
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
pub fn get_hash(&self) -> u64 {
|
|
||||||
let mut h = DefaultHasher::new();
|
|
||||||
self.hash(&mut h);
|
|
||||||
h.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
|
|
||||||
// pub enum ExecLevel {
|
|
||||||
// APP = 0,
|
|
||||||
// API = 1,
|
|
||||||
// ISR = 2,
|
|
||||||
// }
|
|
||||||
|
|
||||||
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub struct ExecInterval {
|
|
||||||
pub start_tick: u64,
|
|
||||||
pub end_tick: u64,
|
|
||||||
pub start_state: u64,
|
|
||||||
pub end_state: u64,
|
|
||||||
pub start_capture: (CaptureEvent, String),
|
|
||||||
pub end_capture: (CaptureEvent, String),
|
|
||||||
pub level: u8,
|
|
||||||
tick_spend_preempted: u64,
|
|
||||||
pub abb: Option<AtomicBasicBlock>
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ExecInterval {
|
|
||||||
pub fn get_exec_time(&self) -> u64 {
|
|
||||||
self.end_tick-self.start_tick-self.tick_spend_preempted
|
|
||||||
}
|
|
||||||
pub fn is_valid(&self) -> bool {
|
|
||||||
self.start_tick != 0 || self.end_tick != 0
|
|
||||||
}
|
|
||||||
pub fn invaildate(&mut self) {
|
|
||||||
self.start_tick = 0;
|
|
||||||
self.end_tick = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Attach this interval to the later one, keep a record of the time spend preempted
|
|
||||||
pub fn try_unite_with_later_interval(&mut self, later_interval : &mut Self) -> bool {
|
|
||||||
if self.end_state!=later_interval.start_state || self.abb!=later_interval.abb || !self.is_valid() || !later_interval.is_valid() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// assert_eq!(self.end_state, later_interval.start_state);
|
|
||||||
// assert_eq!(self.abb, later_interval.abb);
|
|
||||||
later_interval.tick_spend_preempted += self.tick_spend_preempted + (later_interval.start_tick-self.end_tick);
|
|
||||||
later_interval.start_tick = self.start_tick;
|
|
||||||
later_interval.start_state = self.start_state;
|
|
||||||
self.invaildate();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_hash_index(&self) -> (u64, u64) {
|
|
||||||
return (self.start_state, self.abb.as_ref().expect("ABB not set").get_hash())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wrapper around Vec<RefinedFreeRTOSSystemState> to attach as Metadata
|
// Wrapper around Vec<RefinedFreeRTOSSystemState> to attach as Metadata
|
||||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||||
pub struct FreeRTOSSystemStateMetadata {
|
pub struct FreeRTOSSystemStateMetadata {
|
||||||
pub inner: Vec<ReducedFreeRTOSSystemState>,
|
pub inner: Vec<RefinedFreeRTOSSystemState>,
|
||||||
trace_length: usize,
|
trace_length: usize,
|
||||||
indices: Vec<usize>, // Hashed enumeration of States
|
indices: Vec<usize>, // Hashed enumeration of States
|
||||||
tcref: isize,
|
tcref: isize,
|
||||||
}
|
}
|
||||||
impl FreeRTOSSystemStateMetadata {
|
impl FreeRTOSSystemStateMetadata {
|
||||||
pub fn new(inner: Vec<ReducedFreeRTOSSystemState>) -> Self{
|
pub fn new(inner: Vec<RefinedFreeRTOSSystemState>) -> Self{
|
||||||
let tmp = inner.iter().enumerate().map(|x| compute_hash(x) as usize).collect();
|
let tmp = inner.iter().enumerate().map(|x| compute_hash(x) as usize).collect();
|
||||||
Self {trace_length: inner.len(), inner: inner, indices: tmp, tcref: 0}
|
Self {trace_length: inner.len(), inner: inner, indices: tmp, tcref: 0}
|
||||||
}
|
}
|
||||||
@ -261,95 +164,4 @@ impl HasRefCnt for FreeRTOSSystemStateMetadata {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
libafl_bolts::impl_serdeany!(FreeRTOSSystemStateMetadata);
|
libafl::impl_serdeany!(FreeRTOSSystemStateMetadata);
|
||||||
|
|
||||||
#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
|
|
||||||
pub struct AtomicBasicBlock {
|
|
||||||
start: GuestAddr,
|
|
||||||
ends: HashSet<GuestAddr>,
|
|
||||||
level: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Hash for AtomicBasicBlock {
|
|
||||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
|
||||||
// Use a combination of the start address and the set of ending addresses to compute the hash value
|
|
||||||
self.start.hash(state);
|
|
||||||
let mut keys : Vec<_> = self.ends.iter().collect();
|
|
||||||
keys.sort();
|
|
||||||
self.level.hash(state);
|
|
||||||
keys.hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for AtomicBasicBlock {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
let mut ends_str = String::new();
|
|
||||||
for end in &self.ends {
|
|
||||||
ends_str.push_str(&format!("0x{:#x}, ", end));
|
|
||||||
}
|
|
||||||
write!(f, "ABB {{ level: {}, start: 0x{:#x}, ends: [{}]}}", self.level, self.start, ends_str.trim().trim_matches(','))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl fmt::Debug for AtomicBasicBlock {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
let mut ends_str = String::new();
|
|
||||||
for end in &self.ends {
|
|
||||||
ends_str.push_str(&format!("{:#x}, ", end));
|
|
||||||
}
|
|
||||||
write!(f, "ABB {{ level: {}, start: {:#x}, ends: [{}]}}", self.level, self.start, ends_str.trim().trim_matches(','))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialOrd for AtomicBasicBlock {
|
|
||||||
fn partial_cmp(&self, other: &AtomicBasicBlock) -> Option<std::cmp::Ordering> {
|
|
||||||
Some(self.cmp(other))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ord for AtomicBasicBlock {
|
|
||||||
fn cmp(&self, other: &AtomicBasicBlock) -> std::cmp::Ordering {
|
|
||||||
if self.start.cmp(&other.start) == std::cmp::Ordering::Equal {
|
|
||||||
if self.level.cmp(&other.level) != std::cmp::Ordering::Equal {
|
|
||||||
return self.level.cmp(&other.level);
|
|
||||||
}
|
|
||||||
// If the start addresses are equal, compare by 'ends'
|
|
||||||
let end1 = if self.ends.len() == 1 { *self.ends.iter().next().unwrap() as u64 } else {
|
|
||||||
let mut temp = self.ends.iter().collect::<Vec<_>>().into_iter().collect::<Vec<&GuestAddr>>();
|
|
||||||
temp.sort_unstable();
|
|
||||||
let mut h = DefaultHasher::new();
|
|
||||||
temp.hash(&mut h);
|
|
||||||
h.finish()
|
|
||||||
};
|
|
||||||
let end2 = if other.ends.len() == 1 { *self.ends.iter().next().unwrap() as u64 } else {
|
|
||||||
let mut temp = other.ends.iter().collect::<Vec<_>>().into_iter().collect::<Vec<&GuestAddr>>();
|
|
||||||
temp.sort_unstable();
|
|
||||||
let mut h = DefaultHasher::new();
|
|
||||||
temp.hash(&mut h);
|
|
||||||
h.finish()
|
|
||||||
};
|
|
||||||
end1.cmp(&end2)
|
|
||||||
} else {
|
|
||||||
// If the start addresses are not equal, compare by 'start'
|
|
||||||
self.start.cmp(&other.start)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AtomicBasicBlock {
|
|
||||||
pub fn get_hash(&self) -> u64 {
|
|
||||||
let mut s = DefaultHasher::new();
|
|
||||||
self.hash(&mut s);
|
|
||||||
s.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
fn get_task_names(trace: &Vec<ReducedFreeRTOSSystemState>) -> HashSet<String> {
|
|
||||||
let mut ret: HashSet<_, _> = HashSet::new();
|
|
||||||
for state in trace {
|
|
||||||
ret.insert(state.current_task.task_name.to_string());
|
|
||||||
}
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
|
|
||||||
libafl_bolts::impl_serdeany!(AtomicBasicBlock);
|
|
||||||
|
@ -1,24 +1,18 @@
|
|||||||
// use crate::systemstate::IRQ_INPUT_BYTES_NUMBER;
|
// use crate::systemstate::IRQ_INPUT_BYTES_NUMBER;
|
||||||
use libafl::prelude::ExitKind;
|
use libafl::prelude::{ExitKind, AsSlice};
|
||||||
use libafl::{inputs::HasTargetBytes, prelude::UsesInput};
|
use libafl::{inputs::HasTargetBytes, prelude::UsesInput};
|
||||||
use libafl_bolts::HasLen;
|
use libafl::bolts::HasLen;
|
||||||
use libafl_bolts::Named;
|
use libafl::bolts::tuples::Named;
|
||||||
use libafl_bolts::AsSlice;
|
|
||||||
use libafl::Error;
|
use libafl::Error;
|
||||||
use libafl::observers::Observer;
|
use libafl::observers::Observer;
|
||||||
|
use hashbrown::HashMap;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use hashbrown::{HashMap, HashSet};
|
|
||||||
use crate::systemstate::CaptureEvent;
|
|
||||||
use std::rc::Rc;
|
|
||||||
use std::cell::RefCell;
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
|
|
||||||
use super::{ AtomicBasicBlock, ExecInterval};
|
|
||||||
use super::{
|
use super::{
|
||||||
CURRENT_SYSTEMSTATE_VEC,
|
CURRENT_SYSTEMSTATE_VEC,
|
||||||
RawFreeRTOSSystemState,
|
RawFreeRTOSSystemState,
|
||||||
RefinedTCB,
|
RefinedTCB,
|
||||||
ReducedFreeRTOSSystemState,
|
RefinedFreeRTOSSystemState,
|
||||||
freertos::{List_t, TCB_t, rtos_struct, rtos_struct::*},
|
freertos::{List_t, TCB_t, rtos_struct, rtos_struct::*},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -30,11 +24,8 @@ use super::{
|
|||||||
#[allow(clippy::unsafe_derive_deserialize)]
|
#[allow(clippy::unsafe_derive_deserialize)]
|
||||||
pub struct QemuSystemStateObserver
|
pub struct QemuSystemStateObserver
|
||||||
{
|
{
|
||||||
pub last_run: Vec<ReducedFreeRTOSSystemState>,
|
pub last_run: Vec<RefinedFreeRTOSSystemState>,
|
||||||
pub last_states: HashMap<u64, ReducedFreeRTOSSystemState>,
|
|
||||||
pub last_trace: Vec<ExecInterval>,
|
|
||||||
pub last_input: Vec<u8>,
|
pub last_input: Vec<u8>,
|
||||||
pub success: bool,
|
|
||||||
name: String,
|
name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -51,22 +42,7 @@ where
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn post_exec(&mut self, _state: &mut S, _input: &S::Input, _exit_kind: &ExitKind) -> Result<(), Error> {
|
fn post_exec(&mut self, _state: &mut S, _input: &S::Input, _exit_kind: &ExitKind) -> Result<(), Error> {
|
||||||
// unsafe {self.last_run = invalidate_ineffective_isr(refine_system_states(&mut CURRENT_SYSTEMSTATE_VEC));}
|
unsafe {self.last_run = refine_system_states(&mut CURRENT_SYSTEMSTATE_VEC);}
|
||||||
unsafe {
|
|
||||||
let mut temp = refine_system_states(&mut CURRENT_SYSTEMSTATE_VEC);
|
|
||||||
// fix_broken_trace(&mut temp.1);
|
|
||||||
self.last_run = temp.0.clone();
|
|
||||||
// println!("{:?}",temp);
|
|
||||||
let mut temp = states2intervals(temp.0, temp.1);
|
|
||||||
self.last_trace = temp.0;
|
|
||||||
self.last_states = temp.1;
|
|
||||||
self.success = temp.2;
|
|
||||||
// println!("{:?}",temp);
|
|
||||||
}
|
|
||||||
// let abbs = extract_abbs_from_trace(&self.last_run);
|
|
||||||
// println!("{:?}",abbs);
|
|
||||||
// let abbs = trace_to_state_abb(&self.last_run);
|
|
||||||
// println!("{:?}",abbs);
|
|
||||||
self.last_input=_input.target_bytes().as_slice().to_owned();
|
self.last_input=_input.target_bytes().as_slice().to_owned();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@ -90,7 +66,7 @@ impl HasLen for QemuSystemStateObserver
|
|||||||
|
|
||||||
impl QemuSystemStateObserver {
|
impl QemuSystemStateObserver {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self{last_run: vec![], last_trace: vec![], last_input: vec![], name: "systemstate".to_string(), last_states: HashMap::new(), success: false }
|
Self{last_run: vec![], last_input: vec![], name: "systemstate".to_string()}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -134,255 +110,24 @@ fn tcb_list_to_vec_cached(list: List_t, dump: &mut HashMap<u32,rtos_struct>) ->
|
|||||||
ret
|
ret
|
||||||
}
|
}
|
||||||
/// Drains a List of raw SystemStates to produce a refined trace
|
/// Drains a List of raw SystemStates to produce a refined trace
|
||||||
fn refine_system_states(input: &mut Vec<RawFreeRTOSSystemState>) -> (Vec<ReducedFreeRTOSSystemState>, Vec<(u64, CaptureEvent, String, (u32, u32))>) {
|
fn refine_system_states(input: &mut Vec<RawFreeRTOSSystemState>) -> Vec<RefinedFreeRTOSSystemState> {
|
||||||
let mut ret = (Vec::<_>::new(), Vec::<_>::new());
|
let mut ret = Vec::<RefinedFreeRTOSSystemState>::new();
|
||||||
for mut i in input.drain(..) {
|
let mut start_tick : u64 = 0;
|
||||||
let cur = RefinedTCB::from_tcb_owned(i.current_tcb);
|
for mut i in input.drain(..) {
|
||||||
// println!("Refine: {} {:?} {:?} {:x}-{:x}", cur.task_name, i.capture_point.0, i.capture_point.1.to_string(), i.edge.0, i.edge.1);
|
let mut collector = Vec::<RefinedTCB>::new();
|
||||||
// collect ready list
|
for j in i.prio_ready_lists.into_iter().rev() {
|
||||||
let mut collector = Vec::<RefinedTCB>::new();
|
let mut tmp = tcb_list_to_vec_cached(j,&mut i.dumping_ground).iter().map(|x| RefinedTCB::from_tcb(x)).collect();
|
||||||
for j in i.prio_ready_lists.into_iter().rev() {
|
collector.append(&mut tmp);
|
||||||
let mut tmp = tcb_list_to_vec_cached(j,&mut i.dumping_ground).iter().map(|x| RefinedTCB::from_tcb(x)).collect();
|
|
||||||
collector.append(&mut tmp);
|
|
||||||
}
|
|
||||||
// collect delay list
|
|
||||||
let mut delay_list : Vec::<RefinedTCB> = tcb_list_to_vec_cached(i.delay_list, &mut i.dumping_ground).iter().map(|x| RefinedTCB::from_tcb(x)).collect();
|
|
||||||
let mut delay_list_overflow : Vec::<RefinedTCB> = tcb_list_to_vec_cached(i.delay_list_overflow, &mut i.dumping_ground).iter().map(|x| RefinedTCB::from_tcb(x)).collect();
|
|
||||||
delay_list.append(&mut delay_list_overflow);
|
|
||||||
delay_list.sort_by(|a,b| a.task_name.cmp(&b.task_name));
|
|
||||||
|
|
||||||
ret.0.push(ReducedFreeRTOSSystemState {
|
|
||||||
current_task: cur,
|
|
||||||
ready_list_after: collector,
|
|
||||||
delay_list_after: delay_list,
|
|
||||||
// input_counter: i.input_counter,//+IRQ_INPUT_BYTES_NUMBER,
|
|
||||||
});
|
|
||||||
ret.1.push((i.qemu_tick, i.capture_point.0, i.capture_point.1.to_string(), i.edge));
|
|
||||||
}
|
}
|
||||||
return ret;
|
ret.push(RefinedFreeRTOSSystemState {
|
||||||
|
current_task: RefinedTCB::from_tcb_owned(i.current_tcb),
|
||||||
|
start_tick: start_tick,
|
||||||
|
end_tick: i.qemu_tick,
|
||||||
|
ready_list_after: collector,
|
||||||
|
input_counter: i.input_counter,//+IRQ_INPUT_BYTES_NUMBER,
|
||||||
|
last_pc: i.last_pc,
|
||||||
|
});
|
||||||
|
start_tick=i.qemu_tick;
|
||||||
}
|
}
|
||||||
|
return ret;
|
||||||
/// Transform the states and metadata into a list of ExecIntervals
|
|
||||||
fn states2intervals(trace: Vec<ReducedFreeRTOSSystemState>, meta: Vec<(u64, CaptureEvent, String, (u32, u32))>) -> (Vec<ExecInterval>, HashMap<u64, ReducedFreeRTOSSystemState>, bool) {
|
|
||||||
if trace.len() == 0 {return (Vec::new(), HashMap::new(), true);}
|
|
||||||
let mut isr_stack : VecDeque<u8> = VecDeque::from([]); // 2+ = ISR, 1 = systemcall, 0 = APP. Trace starts with an ISREnd and executes the app
|
|
||||||
|
|
||||||
|
|
||||||
let mut level_of_task : HashMap<&str, u8> = HashMap::new();
|
|
||||||
|
|
||||||
let mut ret: Vec<ExecInterval> = vec![];
|
|
||||||
let mut edges: Vec<(u32, u32)> = vec![];
|
|
||||||
let mut last_hash : u64 = trace[0].get_hash();
|
|
||||||
let mut table : HashMap<u64, ReducedFreeRTOSSystemState> = HashMap::new();
|
|
||||||
table.insert(last_hash, trace[0].clone());
|
|
||||||
for i in 0..trace.len()-1 {
|
|
||||||
let curr_name = trace[i].current_task.task_name.as_str();
|
|
||||||
let level = match meta[i].1 {
|
|
||||||
CaptureEvent::APIEnd => { // API end always exits towards the app
|
|
||||||
if !level_of_task.contains_key(curr_name) {
|
|
||||||
level_of_task.insert(curr_name, 0);
|
|
||||||
}
|
|
||||||
*level_of_task.get_mut(curr_name).unwrap()=0;
|
|
||||||
0
|
|
||||||
},
|
|
||||||
CaptureEvent::APIStart => { // API start can only be called in the app
|
|
||||||
if !level_of_task.contains_key(curr_name) { // Should not happen, apps start from an ISR End. Some input exibited this behavior for unknown reasons
|
|
||||||
level_of_task.insert(curr_name, 0);
|
|
||||||
}
|
|
||||||
*level_of_task.get_mut(curr_name).unwrap()=1;
|
|
||||||
1
|
|
||||||
},
|
|
||||||
CaptureEvent::ISREnd => {
|
|
||||||
// special case where the next block is an app start
|
|
||||||
if !level_of_task.contains_key(curr_name) {
|
|
||||||
level_of_task.insert(curr_name, 0);
|
|
||||||
}
|
|
||||||
// nested isr, TODO: Test level > 2
|
|
||||||
if isr_stack.len() > 1 {
|
|
||||||
isr_stack.pop_back().unwrap();
|
|
||||||
*isr_stack.back().unwrap()
|
|
||||||
} else {
|
|
||||||
isr_stack.pop_back();
|
|
||||||
// possibly go back to an api call that is still running for this task
|
|
||||||
*level_of_task.get(curr_name).unwrap()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
CaptureEvent::ISRStart => {
|
|
||||||
// special case for isrs which do not capture their end
|
|
||||||
// if meta[i].2 == "isr_starter" {
|
|
||||||
// &2
|
|
||||||
// } else {
|
|
||||||
// regular case
|
|
||||||
if isr_stack.len() > 0 {
|
|
||||||
let l = *isr_stack.back().unwrap();
|
|
||||||
isr_stack.push_back(l+1);
|
|
||||||
l+1
|
|
||||||
} else {
|
|
||||||
isr_stack.push_back(2);
|
|
||||||
2
|
|
||||||
}
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
_ => 100
|
|
||||||
};
|
|
||||||
// if trace[i].2 == CaptureEvent::End {break;}
|
|
||||||
let next_hash=trace[i+1].get_hash();
|
|
||||||
if !table.contains_key(&next_hash) {
|
|
||||||
table.insert(next_hash, trace[i+1].clone());
|
|
||||||
}
|
|
||||||
ret.push(ExecInterval{
|
|
||||||
start_tick: meta[i].0,
|
|
||||||
end_tick: meta[i+1].0,
|
|
||||||
start_state: last_hash,
|
|
||||||
end_state: next_hash,
|
|
||||||
start_capture: (meta[i].1, meta[i].2.clone()),
|
|
||||||
end_capture: (meta[i+1].1, meta[i+1].2.clone()),
|
|
||||||
level: level,
|
|
||||||
tick_spend_preempted: 0,
|
|
||||||
abb: None
|
|
||||||
});
|
|
||||||
last_hash = next_hash;
|
|
||||||
edges.push((meta[i].3.1, meta[i+1].3.0));
|
|
||||||
}
|
|
||||||
let t = add_abb_info(&mut ret, &table, &edges);
|
|
||||||
(ret, table, t)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_abb_info(trace: &mut Vec<ExecInterval>, table: &HashMap<u64, ReducedFreeRTOSSystemState>, edges: &Vec<(u32, u32)>) -> bool {
|
|
||||||
let mut ret = true;
|
|
||||||
let mut task_has_started : HashSet<String> = HashSet::new();
|
|
||||||
let mut wip_abb_trace : Vec<Rc<RefCell<AtomicBasicBlock>>> = vec![];
|
|
||||||
// let mut open_abb_at_this_task_or_level : HashMap<(u8,&str),usize> = HashMap::new();
|
|
||||||
let mut open_abb_at_this_ret_addr_and_task : HashMap<(u32,&str),usize> = HashMap::new();
|
|
||||||
|
|
||||||
for i in 0..trace.len() {
|
|
||||||
let curr_name = &table[&trace[i].start_state].current_task.task_name;
|
|
||||||
// let last : Option<&usize> = last_abb_start_of_task.get(&curr_name);
|
|
||||||
|
|
||||||
// let open_abb = open_abb_at_this_task_or_level.get(&(trace[i].level, if trace[i].level<2 {&curr_name} else {""})).to_owned(); // apps/apis are differentiated by task name, isrs by nested level
|
|
||||||
let open_abb = open_abb_at_this_ret_addr_and_task.get(&(edges[i].0, if trace[i].level<2 {&curr_name} else {""})).to_owned(); // apps/apis are differentiated by task name, isrs by nested level
|
|
||||||
|
|
||||||
// println!("Edge {:x}-{:x}", edges[i].0.unwrap_or(0xffff), edges[i].1.unwrap_or(0xffff));
|
|
||||||
|
|
||||||
match trace[i].start_capture.0 {
|
|
||||||
// generic api abb start
|
|
||||||
CaptureEvent::APIStart => {
|
|
||||||
// assert_eq!(open_abb, None);
|
|
||||||
ret &= open_abb.is_none();
|
|
||||||
open_abb_at_this_ret_addr_and_task.insert((edges[i].1, if trace[i].level<2 {&curr_name} else {""}), i);
|
|
||||||
wip_abb_trace.push(Rc::new(RefCell::new(AtomicBasicBlock{start: edges[i].0, ends: HashSet::new(), level: if trace[i].level<2 {trace[i].level} else {2}})));
|
|
||||||
},
|
|
||||||
// generic isr abb start
|
|
||||||
CaptureEvent::ISRStart => {
|
|
||||||
// assert_eq!(open_abb, None);
|
|
||||||
ret &= open_abb.is_none();
|
|
||||||
open_abb_at_this_ret_addr_and_task.insert((edges[i].1, if trace[i].level<2 {&curr_name} else {""}), i);
|
|
||||||
wip_abb_trace.push(Rc::new(RefCell::new(AtomicBasicBlock{start: edges[i].0, ends: HashSet::new(), level: if trace[i].level<2 {trace[i].level} else {2}})));
|
|
||||||
},
|
|
||||||
// generic app abb start
|
|
||||||
CaptureEvent::APIEnd => {
|
|
||||||
// assert_eq!(open_abb, None);
|
|
||||||
ret &= open_abb.is_none();
|
|
||||||
open_abb_at_this_ret_addr_and_task.insert((edges[i].1, if trace[i].level<2 {&curr_name} else {""}), i);
|
|
||||||
wip_abb_trace.push(Rc::new(RefCell::new(AtomicBasicBlock{start: edges[i].0, ends: HashSet::new(), level: if trace[i].level<2 {trace[i].level} else {2}})));
|
|
||||||
},
|
|
||||||
// generic continued blocks
|
|
||||||
CaptureEvent::ISREnd => {
|
|
||||||
// special case app abb start
|
|
||||||
if trace[i].start_capture.1=="xPortPendSVHandler" && !task_has_started.contains(curr_name) {
|
|
||||||
// assert_eq!(open_abb, None);
|
|
||||||
ret &= open_abb.is_none();
|
|
||||||
wip_abb_trace.push(Rc::new(RefCell::new(AtomicBasicBlock{start: 0, ends: HashSet::new(), level: if trace[i].level<2 {trace[i].level} else {2}})));
|
|
||||||
open_abb_at_this_ret_addr_and_task.insert((edges[i].1, if trace[i].level<2 {&curr_name} else {""}), i);
|
|
||||||
task_has_started.insert(curr_name.clone());
|
|
||||||
} else {
|
|
||||||
if let Some(last) = open_abb_at_this_ret_addr_and_task.get(&(edges[i].0, if trace[i].level<2 {&curr_name} else {""})) {
|
|
||||||
let last = last.clone(); // required to drop immutable reference
|
|
||||||
wip_abb_trace.push(wip_abb_trace[last].clone());
|
|
||||||
// if the abb is interrupted again, it will need to continue at edge[i].1
|
|
||||||
open_abb_at_this_ret_addr_and_task.remove(&(edges[i].0, if trace[i].level<2 {&curr_name} else {""}));
|
|
||||||
open_abb_at_this_ret_addr_and_task.insert((edges[i].1, if trace[i].level<2 {&curr_name} else {""}), last); // order matters!
|
|
||||||
} else {
|
|
||||||
// panic!();
|
|
||||||
// println!("Continued block with no start {} {} {:?} {:?} {:x}-{:x} {} {}", curr_name, trace[i].start_tick, trace[i].start_capture, trace[i].end_capture, edges[i].0, edges[i].1, task_has_started.contains(curr_name),trace[i].level);
|
|
||||||
// println!("{:x?}", open_abb_at_this_ret_addr_and_task);
|
|
||||||
ret = false;
|
|
||||||
wip_abb_trace.push(Rc::new(RefCell::new(AtomicBasicBlock{start: edges[i].1, ends: HashSet::new(), level: if trace[i].level<2 {trace[i].level} else {2}})))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
_ => panic!("Undefined block start")
|
|
||||||
}
|
|
||||||
match trace[i].end_capture.0 {
|
|
||||||
// generic app abb end
|
|
||||||
CaptureEvent::APIStart => {
|
|
||||||
let _t = &wip_abb_trace[i];
|
|
||||||
RefCell::borrow_mut(&*wip_abb_trace[i]).ends.insert(edges[i].1);
|
|
||||||
open_abb_at_this_ret_addr_and_task.remove(&(edges[i].1, if trace[i].level<2 {&curr_name} else {""}));
|
|
||||||
},
|
|
||||||
// generic api abb end
|
|
||||||
CaptureEvent::APIEnd => {
|
|
||||||
RefCell::borrow_mut(&*wip_abb_trace[i]).ends.insert(edges[i].1);
|
|
||||||
open_abb_at_this_ret_addr_and_task.remove(&(edges[i].1, if trace[i].level<2 {&curr_name} else {""}));
|
|
||||||
},
|
|
||||||
// generic isr abb end
|
|
||||||
CaptureEvent::ISREnd => {
|
|
||||||
RefCell::borrow_mut(&*wip_abb_trace[i]).ends.insert(edges[i].1);
|
|
||||||
open_abb_at_this_ret_addr_and_task.remove(&(edges[i].1, if trace[i].level<2 {&curr_name} else {""}));
|
|
||||||
},
|
|
||||||
// end anything
|
|
||||||
CaptureEvent::End => {
|
|
||||||
RefCell::borrow_mut(&*wip_abb_trace[i]).ends.insert(edges[i].1);
|
|
||||||
open_abb_at_this_ret_addr_and_task.remove(&(edges[i].1, if trace[i].level<2 {&curr_name} else {""}));
|
|
||||||
},
|
|
||||||
CaptureEvent::ISRStart => (),
|
|
||||||
_ => panic!("Undefined block end")
|
|
||||||
}
|
|
||||||
// println!("{} {} {:x}-{:x} {:x}-{:x} {:?} {:?} {}",curr_name, trace[i].level, edges[i].0, edges[i].1, ((*wip_abb_trace[i])).borrow().start, ((*wip_abb_trace[i])).borrow().ends.iter().next().unwrap_or(&0xffff), trace[i].start_capture, trace[i].end_capture, trace[i].start_tick);
|
|
||||||
// println!("{:x?}", open_abb_at_this_ret_addr_and_task);
|
|
||||||
}
|
|
||||||
// drop(open_abb_at_this_task_or_level);
|
|
||||||
|
|
||||||
for i in 0..trace.len() {
|
|
||||||
trace[i].abb = Some((*wip_abb_trace[i]).borrow().clone());
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// restore the isr/api begin/end invariant
|
|
||||||
fn fix_broken_trace(meta: &mut Vec<(u64, CaptureEvent, String, (Option<u32>, Option<u32>))>) {
|
|
||||||
for i in meta.iter_mut() {
|
|
||||||
if i.1 == CaptureEvent::APIStart && i.2.ends_with("FromISR") {
|
|
||||||
i.1 = CaptureEvent::ISREnd;
|
|
||||||
i.2 = "isr_starter".to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// invalidate subsequent intervals of equal states where an ISREnd follows an ISRStart. If the interrupt had no effect on the system we, are not interested.
|
|
||||||
fn invalidate_ineffective_isr(trace: &mut Vec<ExecInterval>) {
|
|
||||||
let mut i = 0;
|
|
||||||
while i < trace.len() - 1 {
|
|
||||||
if trace[i].is_valid() &&
|
|
||||||
matches!(trace[i].start_capture.0, CaptureEvent::ISRStart) && matches!(trace[i].end_capture.0, CaptureEvent::ISREnd) &&
|
|
||||||
trace[i].start_capture.1 == trace[i].end_capture.1 && trace[i].start_state == trace[i].end_state
|
|
||||||
{
|
|
||||||
trace[i].invaildate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// merge a sequence of intervals of the same state+abb. jump over all invalid blocks.
|
|
||||||
fn merge_subsequent_abbs(trace: &mut Vec<ExecInterval>) {
|
|
||||||
let mut i = 1;
|
|
||||||
let mut lst_valid=0;
|
|
||||||
while i < trace.len() - 1 {
|
|
||||||
if trace[i].is_valid() {
|
|
||||||
let mut temp = trace[i].clone();
|
|
||||||
trace[lst_valid].try_unite_with_later_interval(&mut temp);
|
|
||||||
trace[i] = temp;
|
|
||||||
lst_valid = i;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
@ -6,19 +6,19 @@ use std::{cmp::{max, min}, mem::swap, borrow::BorrowMut};
|
|||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use libafl_bolts::{rands::Rand, serdeany::SerdeAny, AsSlice, HasRefCnt, HasLen};
|
|
||||||
use libafl::{
|
use libafl::{
|
||||||
|
bolts::{rands::Rand, serdeany::SerdeAny, AsSlice, HasRefCnt},
|
||||||
corpus::{Corpus, Testcase},
|
corpus::{Corpus, Testcase},
|
||||||
inputs::UsesInput,
|
inputs::UsesInput,
|
||||||
schedulers::{Scheduler, TestcaseScore, minimizer::DEFAULT_SKIP_NON_FAVORED_PROB },
|
schedulers::{Scheduler, TestcaseScore, minimizer::DEFAULT_SKIP_NON_FAVORED_PROB },
|
||||||
state::{HasCorpus, HasMetadata, HasRand, UsesState, State},
|
state::{HasCorpus, HasMetadata, HasRand, UsesState, State},
|
||||||
Error, SerdeAny, prelude::CorpusId,
|
Error, SerdeAny, prelude::HasLen,
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::worst::MaxTimeFavFactor;
|
use crate::worst::MaxTimeFavFactor;
|
||||||
|
|
||||||
use super::{stg::STGNodeMetadata, FreeRTOSSystemStateMetadata};
|
use super::FreeRTOSSystemStateMetadata;
|
||||||
|
|
||||||
/// A state metadata holding a map of favoreds testcases for each map entry
|
/// A state metadata holding a map of favoreds testcases for each map entry
|
||||||
#[derive(Debug, Serialize, Deserialize, SerdeAny, Default)]
|
#[derive(Debug, Serialize, Deserialize, SerdeAny, Default)]
|
||||||
@ -55,52 +55,52 @@ where
|
|||||||
CS::State: HasCorpus + HasMetadata + HasRand,
|
CS::State: HasCorpus + HasMetadata + HasRand,
|
||||||
{
|
{
|
||||||
/// Add an entry to the corpus and return its index
|
/// Add an entry to the corpus and return its index
|
||||||
fn on_add(&mut self, state: &mut CS::State, idx: CorpusId) -> Result<(), Error> {
|
fn on_add(&self, state: &mut CS::State, idx: usize) -> Result<(), Error> {
|
||||||
let l = state.corpus()
|
let l = state.corpus()
|
||||||
.get(idx)?
|
.get(idx)?
|
||||||
.borrow()
|
.borrow()
|
||||||
.metadata_map()
|
.metadata()
|
||||||
.get::<FreeRTOSSystemStateMetadata>().map_or(0, |x| x.trace_length);
|
.get::<FreeRTOSSystemStateMetadata>().map_or(0, |x| x.trace_length);
|
||||||
self.get_update_trace_length(state,l);
|
self.get_update_trace_length(state,l);
|
||||||
self.base.on_add(state, idx)
|
self.base.on_add(state, idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replaces the testcase at the given idx
|
/// Replaces the testcase at the given idx
|
||||||
// fn on_replace(
|
fn on_replace(
|
||||||
// &mut self,
|
&self,
|
||||||
// state: &mut CS::State,
|
state: &mut CS::State,
|
||||||
// idx: CorpusId,
|
idx: usize,
|
||||||
// testcase: &Testcase<<CS::State as UsesInput>::Input>,
|
testcase: &Testcase<<CS::State as UsesInput>::Input>,
|
||||||
// ) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
// let l = state.corpus()
|
let l = state.corpus()
|
||||||
// .get(idx)?
|
.get(idx)?
|
||||||
// .borrow()
|
.borrow()
|
||||||
// .metadata()
|
.metadata()
|
||||||
// .get::<FreeRTOSSystemStateMetadata>().map_or(0, |x| x.trace_length);
|
.get::<FreeRTOSSystemStateMetadata>().map_or(0, |x| x.trace_length);
|
||||||
// self.get_update_trace_length(state, l);
|
self.get_update_trace_length(state, l);
|
||||||
// self.base.on_replace(state, idx, testcase)
|
self.base.on_replace(state, idx, testcase)
|
||||||
// }
|
}
|
||||||
|
|
||||||
/// Removes an entry from the corpus, returning M if M was present.
|
/// Removes an entry from the corpus, returning M if M was present.
|
||||||
// fn on_remove(
|
fn on_remove(
|
||||||
// &self,
|
&self,
|
||||||
// state: &mut CS::State,
|
state: &mut CS::State,
|
||||||
// idx: usize,
|
idx: usize,
|
||||||
// testcase: &Option<Testcase<<CS::State as UsesInput>::Input>>,
|
testcase: &Option<Testcase<<CS::State as UsesInput>::Input>>,
|
||||||
// ) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
// self.base.on_remove(state, idx, testcase)?;
|
self.base.on_remove(state, idx, testcase)?;
|
||||||
// Ok(())
|
Ok(())
|
||||||
// }
|
}
|
||||||
|
|
||||||
/// Gets the next entry
|
/// Gets the next entry
|
||||||
fn next(&mut self, state: &mut CS::State) -> Result<CorpusId, Error> {
|
fn next(&self, state: &mut CS::State) -> Result<usize, Error> {
|
||||||
let mut idx = self.base.next(state)?;
|
let mut idx = self.base.next(state)?;
|
||||||
while {
|
while {
|
||||||
let l = state.corpus()
|
let l = state.corpus()
|
||||||
.get(idx)?
|
.get(idx)?
|
||||||
.borrow()
|
.borrow()
|
||||||
.metadata_map()
|
.metadata()
|
||||||
.get::<STGNodeMetadata>().map_or(0, |x| x.nodes.len());
|
.get::<FreeRTOSSystemStateMetadata>().map_or(0, |x| x.trace_length);
|
||||||
let m = self.get_update_trace_length(state,l);
|
let m = self.get_update_trace_length(state,l);
|
||||||
state.rand_mut().below(m) > l as u64
|
state.rand_mut().below(m) > l as u64
|
||||||
} && state.rand_mut().below(100) < self.skip_non_favored_prob
|
} && state.rand_mut().below(100) < self.skip_non_favored_prob
|
||||||
@ -118,7 +118,7 @@ where
|
|||||||
{
|
{
|
||||||
pub fn get_update_trace_length(&self, state: &mut CS::State, par: usize) -> u64 {
|
pub fn get_update_trace_length(&self, state: &mut CS::State, par: usize) -> u64 {
|
||||||
// Create a new top rated meta if not existing
|
// Create a new top rated meta if not existing
|
||||||
if let Some(td) = state.metadata_map_mut().get_mut::<LongestTracesMetadata>() {
|
if let Some(td) = state.metadata_mut().get_mut::<LongestTracesMetadata>() {
|
||||||
let m = max(td.max_trace_length, par);
|
let m = max(td.max_trace_length, par);
|
||||||
td.max_trace_length = m;
|
td.max_trace_length = m;
|
||||||
m as u64
|
m as u64
|
||||||
@ -160,32 +160,30 @@ pub struct GenerationScheduler<S> {
|
|||||||
|
|
||||||
impl<S> UsesState for GenerationScheduler<S>
|
impl<S> UsesState for GenerationScheduler<S>
|
||||||
where
|
where
|
||||||
S: State + UsesInput,
|
S: UsesInput,
|
||||||
{
|
{
|
||||||
type State = S;
|
type State = S;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> Scheduler for GenerationScheduler<S>
|
impl<S> Scheduler for GenerationScheduler<S>
|
||||||
where
|
where
|
||||||
S: State + HasCorpus + HasMetadata,
|
S: HasCorpus + HasMetadata,
|
||||||
S::Input: HasLen,
|
S::Input: HasLen,
|
||||||
{
|
{
|
||||||
/// get first element in current gen,
|
/// get first element in current gen,
|
||||||
/// if current_gen is empty, swap lists, sort by FavFactor, take top k and return first
|
/// if current_gen is empty, swap lists, sort by FavFactor, take top k and return first
|
||||||
fn next(&mut self, state: &mut Self::State) -> Result<CorpusId, Error> {
|
fn next(&self, state: &mut Self::State) -> Result<usize, Error> {
|
||||||
let mut to_remove : Vec<(usize, f64)> = vec![];
|
let mut to_remove : Vec<(usize, f64)> = vec![];
|
||||||
let mut to_return : usize = 0;
|
let mut to_return : usize = 0;
|
||||||
let corpus_len = state.corpus().count();
|
let c = state.corpus().count();
|
||||||
let mut current_len = 0;
|
let gm = state.metadata_mut().get_mut::<GeneticMetadata>().expect("Corpus Scheduler empty");
|
||||||
let gm = state.metadata_map_mut().get_mut::<GeneticMetadata>().expect("Corpus Scheduler empty");
|
|
||||||
// println!("index: {} curr: {:?} next: {:?} gen: {} corp: {}", gm.current_cursor, gm.current_gen.len(), gm.next_gen.len(), gm.gen,
|
// println!("index: {} curr: {:?} next: {:?} gen: {} corp: {}", gm.current_cursor, gm.current_gen.len(), gm.next_gen.len(), gm.gen,
|
||||||
// c);
|
// c);
|
||||||
match gm.current_gen.get(gm.current_cursor) {
|
match gm.current_gen.get(gm.current_cursor) {
|
||||||
Some(c) => {
|
Some(c) => {
|
||||||
current_len = gm.current_gen.len();
|
|
||||||
gm.current_cursor+=1;
|
gm.current_cursor+=1;
|
||||||
// println!("normal next: {}", (*c).0);
|
// println!("normal next: {}", (*c).0);
|
||||||
return Ok((*c).0.into())
|
return Ok((*c).0)
|
||||||
},
|
},
|
||||||
None => {
|
None => {
|
||||||
swap(&mut to_remove, &mut gm.current_gen);
|
swap(&mut to_remove, &mut gm.current_gen);
|
||||||
@ -197,71 +195,65 @@ where
|
|||||||
to_remove.extend(d);
|
to_remove.extend(d);
|
||||||
// move all indices to the left, since all other indices will be deleted
|
// move all indices to the left, since all other indices will be deleted
|
||||||
gm.current_gen.sort_by(|a,b| a.0.cmp(&(*b).0)); // in order of the corpus index
|
gm.current_gen.sort_by(|a,b| a.0.cmp(&(*b).0)); // in order of the corpus index
|
||||||
// for i in 0..gm.current_gen.len() {
|
for i in 0..gm.current_gen.len() {
|
||||||
// gm.current_gen[i] = (i, gm.current_gen[i].1);
|
gm.current_gen[i] = (i, gm.current_gen[i].1);
|
||||||
// }
|
}
|
||||||
to_return = gm.current_gen.get(0).unwrap().0;
|
to_return = gm.current_gen.get(0).unwrap().0;
|
||||||
// assert_eq!(to_return, 0);
|
|
||||||
gm.current_cursor=1;
|
gm.current_cursor=1;
|
||||||
gm.gen+=1;
|
gm.gen+=1;
|
||||||
current_len = gm.current_gen.len();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// removing these elements will move all indices left by to_remove.len()
|
// removing these elements will move all indices left by to_remove.len()
|
||||||
// to_remove.sort_by(|x,y| x.0.cmp(&(*y).0));
|
to_remove.sort_by(|x,y| x.0.cmp(&(*y).0));
|
||||||
// to_remove.reverse();
|
to_remove.reverse();
|
||||||
let cm = state.corpus_mut();
|
|
||||||
assert_eq!(corpus_len-to_remove.len(), current_len);
|
|
||||||
assert_ne!(current_len,0);
|
|
||||||
for i in to_remove {
|
for i in to_remove {
|
||||||
cm.remove(i.0.into()).unwrap();
|
state.corpus_mut().remove(i.0).unwrap();
|
||||||
}
|
}
|
||||||
assert_eq!(cm.get(to_return.into()).is_ok(),true);
|
|
||||||
// println!("switch next: {to_return}");
|
// println!("switch next: {to_return}");
|
||||||
return Ok(to_return.into());
|
return Ok(to_return);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add the new input to the next generation
|
/// Add the new input to the next generation
|
||||||
fn on_add(
|
fn on_add(
|
||||||
&mut self,
|
&self,
|
||||||
state: &mut Self::State,
|
state: &mut Self::State,
|
||||||
idx: CorpusId
|
idx: usize
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
// println!("On Add {idx}");
|
// println!("On Add {idx}");
|
||||||
let mut tc = state.corpus_mut().get(idx).expect("Newly added testcase not found by index").borrow_mut().clone();
|
let mut tc = state.corpus_mut().get(idx).unwrap().borrow_mut().clone();
|
||||||
let ff = MaxTimeFavFactor::compute(state, &mut tc).unwrap();
|
let ff = MaxTimeFavFactor::compute(&mut tc, state).unwrap();
|
||||||
if let Some(gm) = state.metadata_map_mut().get_mut::<GeneticMetadata>() {
|
if let Some(gm) = state.metadata_mut().get_mut::<GeneticMetadata>() {
|
||||||
gm.next_gen.push((idx.into(),ff));
|
gm.next_gen.push((idx,ff));
|
||||||
} else {
|
} else {
|
||||||
state.add_metadata(GeneticMetadata::new(vec![], vec![(idx.into(),ff)]));
|
state.add_metadata(GeneticMetadata::new(vec![], vec![(idx,ff)]));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
// fn on_replace(
|
fn on_replace(
|
||||||
// &self,
|
&self,
|
||||||
// _state: &mut Self::State,
|
_state: &mut Self::State,
|
||||||
// _idx: usize,
|
_idx: usize,
|
||||||
// _prev: &Testcase<<Self::State as UsesInput>::Input>
|
_prev: &Testcase<<Self::State as UsesInput>::Input>
|
||||||
// ) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
// // println!("On Replace {_idx}");
|
// println!("On Replace {_idx}");
|
||||||
// Ok(())
|
Ok(())
|
||||||
// }
|
}
|
||||||
|
|
||||||
// fn on_remove(
|
fn on_remove(
|
||||||
// &self,
|
&self,
|
||||||
// state: &mut Self::State,
|
state: &mut Self::State,
|
||||||
// idx: usize,
|
idx: usize,
|
||||||
// _testcase: &Option<Testcase<<Self::State as UsesInput>::Input>>
|
_testcase: &Option<Testcase<<Self::State as UsesInput>::Input>>
|
||||||
// ) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
// // println!("On Remove {idx}");
|
// println!("On Remove {idx}");
|
||||||
// if let Some(gm) = state.metadata_mut().get_mut::<GeneticMetadata>() {
|
if let Some(gm) = state.metadata_mut().get_mut::<GeneticMetadata>() {
|
||||||
// gm.next_gen = gm.next_gen.drain(..).into_iter().filter(|x| (*x).0 != idx).collect::<Vec<(usize, f64)>>();
|
gm.next_gen = gm.next_gen.drain(..).into_iter().filter(|x| (*x).0 != idx).collect::<Vec<(usize, f64)>>();
|
||||||
// gm.current_gen = gm.current_gen.drain(..).into_iter().filter(|x| (*x).0 != idx).collect::<Vec<(usize, f64)>>();
|
gm.current_gen = gm.current_gen.drain(..).into_iter().filter(|x| (*x).0 != idx).collect::<Vec<(usize, f64)>>();
|
||||||
// } else {
|
} else {
|
||||||
// state.add_metadata(GeneticMetadata::new(vec![], vec![]));
|
state.add_metadata(GeneticMetadata::new(vec![], vec![]));
|
||||||
// }
|
}
|
||||||
// Ok(())
|
Ok(())
|
||||||
// }
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> GenerationScheduler<S>
|
impl<S> GenerationScheduler<S>
|
||||||
|
@ -1,590 +0,0 @@
|
|||||||
|
|
||||||
use hashbrown::HashSet;
|
|
||||||
use libafl::SerdeAny;
|
|
||||||
/// Feedbacks organizing SystemStates as a graph
|
|
||||||
use libafl::inputs::HasBytesVec;
|
|
||||||
use libafl_bolts::ownedref::OwnedMutSlice;
|
|
||||||
use petgraph::graph::EdgeIndex;
|
|
||||||
use std::fs;
|
|
||||||
use libafl_bolts::rands::RandomSeed;
|
|
||||||
use libafl_bolts::rands::StdRand;
|
|
||||||
use libafl::mutators::Mutator;
|
|
||||||
use libafl::mutators::MutationResult;
|
|
||||||
use libafl::prelude::HasTargetBytes;
|
|
||||||
use libafl::prelude::UsesInput;
|
|
||||||
use libafl::state::HasNamedMetadata;
|
|
||||||
use libafl::state::UsesState;
|
|
||||||
use libafl::prelude::State;
|
|
||||||
use petgraph::dot::Config;
|
|
||||||
use petgraph::dot::Dot;
|
|
||||||
use core::marker::PhantomData;
|
|
||||||
use libafl::state::HasCorpus;
|
|
||||||
use libafl::state::HasSolutions;
|
|
||||||
use libafl::state::HasRand;
|
|
||||||
use crate::worst::MaxExecsLenFavFactor;
|
|
||||||
use crate::worst::MaxTimeFavFactor;
|
|
||||||
use libafl::schedulers::MinimizerScheduler;
|
|
||||||
use libafl_bolts::HasRefCnt;
|
|
||||||
use libafl_bolts::AsSlice;
|
|
||||||
use libafl_bolts::ownedref::OwnedSlice;
|
|
||||||
use libafl::inputs::BytesInput;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use crate::clock::QemuClockObserver;
|
|
||||||
use libafl::corpus::Testcase;
|
|
||||||
use libafl_bolts::tuples::MatchName;
|
|
||||||
use std::collections::hash_map::DefaultHasher;
|
|
||||||
use std::hash::Hasher;
|
|
||||||
use std::hash::Hash;
|
|
||||||
use libafl::events::EventFirer;
|
|
||||||
use libafl::state::MaybeHasClientPerfMonitor;
|
|
||||||
use libafl::feedbacks::Feedback;
|
|
||||||
use libafl_bolts::Named;
|
|
||||||
use libafl::Error;
|
|
||||||
use libafl_qemu::edges::EDGES_MAP_SIZE;
|
|
||||||
use hashbrown::HashMap;
|
|
||||||
use libafl::{executors::ExitKind, inputs::Input, observers::ObserversTuple, state::HasMetadata};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use super::feedbacks::SystemStateFeedbackState;
|
|
||||||
use super::AtomicBasicBlock;
|
|
||||||
use super::CaptureEvent;
|
|
||||||
use super::ExecInterval;
|
|
||||||
use super::ReducedFreeRTOSSystemState;
|
|
||||||
use super::FreeRTOSSystemStateMetadata;
|
|
||||||
use super::observers::QemuSystemStateObserver;
|
|
||||||
use petgraph::prelude::DiGraph;
|
|
||||||
use petgraph::graph::NodeIndex;
|
|
||||||
use petgraph::Direction;
|
|
||||||
use std::cmp::Ordering;
|
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use libafl_bolts::rands::Rand;
|
|
||||||
|
|
||||||
use crate::clock::FUZZ_START_TIMESTAMP;
|
|
||||||
use std::time::SystemTime;
|
|
||||||
use std::{fs::OpenOptions, io::Write};
|
|
||||||
|
|
||||||
//============================= Data Structures
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, Default, Hash)]
|
|
||||||
pub struct STGNode
|
|
||||||
{
|
|
||||||
base: ReducedFreeRTOSSystemState,
|
|
||||||
abb: AtomicBasicBlock,
|
|
||||||
}
|
|
||||||
impl STGNode {
|
|
||||||
pub fn pretty_print(&self) -> String {
|
|
||||||
format!("{}\nl{} {:x}-{:x}\n{}", self.base.current_task.task_name, self.abb.level, self.abb.start, self.abb.ends.iter().next().unwrap_or_else(||&0xFFFF), self.base.print_lists())
|
|
||||||
}
|
|
||||||
pub fn color_print(&self) -> String {
|
|
||||||
let color = match self.abb.level {
|
|
||||||
1 => "\", shape=box, style=filled, fillcolor=\"lightblue",
|
|
||||||
2 => "\", shape=box, style=filled, fillcolor=\"yellow",
|
|
||||||
0 => "\", shape=box, style=filled, fillcolor=\"white",
|
|
||||||
_ => "\", style=filled, fillcolor=\"lightgray",
|
|
||||||
};
|
|
||||||
let message = match self.abb.level {
|
|
||||||
1 => format!("API Call"),
|
|
||||||
2 => format!("ISR"),
|
|
||||||
0 => format!("Task: {}",self.base.current_task.task_name),
|
|
||||||
_ => format!(""),
|
|
||||||
};
|
|
||||||
let mut label = format!("{}\nABB: {:x}-{:x}\n{}", message, self.abb.start, self.abb.ends.iter().next().unwrap_or_else(||&0xFFFF), self.base.print_lists());
|
|
||||||
label.push_str(color);
|
|
||||||
label
|
|
||||||
}
|
|
||||||
fn get_hash(&self) -> u64 {
|
|
||||||
let mut s = DefaultHasher::new();
|
|
||||||
self.base.hash(&mut s);
|
|
||||||
self.abb.hash(&mut s);
|
|
||||||
s.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl PartialEq for STGNode {
|
|
||||||
fn eq(&self, other: &STGNode) -> bool {
|
|
||||||
self.base==other.base
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, Default, Hash, PartialEq, Eq)]
|
|
||||||
pub struct STGEdge
|
|
||||||
{
|
|
||||||
// is_interrupt: bool,
|
|
||||||
pub event: CaptureEvent,
|
|
||||||
pub name: String
|
|
||||||
}
|
|
||||||
|
|
||||||
impl STGEdge {
|
|
||||||
pub fn pretty_print(&self) -> String {
|
|
||||||
let mut short = match self.event {
|
|
||||||
CaptureEvent::APIStart => "Call: ",
|
|
||||||
CaptureEvent::APIEnd => "Ret: ",
|
|
||||||
CaptureEvent::ISRStart => "Int: ",
|
|
||||||
CaptureEvent::ISREnd => "IRet: ",
|
|
||||||
CaptureEvent::End => "End: ",
|
|
||||||
CaptureEvent::Undefined => "",
|
|
||||||
}.to_string();
|
|
||||||
short.push_str(&self.name);
|
|
||||||
short
|
|
||||||
}
|
|
||||||
pub fn color_print(&self) -> String {
|
|
||||||
let mut short = self.name.clone();
|
|
||||||
short.push_str(match self.event {
|
|
||||||
CaptureEvent::APIStart => "\", color=\"blue",
|
|
||||||
CaptureEvent::APIEnd => "\", color=\"black",
|
|
||||||
CaptureEvent::ISRStart => "\", color=red, style=\"dashed",
|
|
||||||
CaptureEvent::ISREnd => "\", color=red, style=\"solid",
|
|
||||||
CaptureEvent::End => "",
|
|
||||||
CaptureEvent::Undefined => "",
|
|
||||||
});
|
|
||||||
short
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Shared Metadata for a systemstateFeedback
|
|
||||||
#[derive(Debug, Serialize, Deserialize, SerdeAny, Clone)]
|
|
||||||
pub struct STGFeedbackState
|
|
||||||
{
|
|
||||||
// aggregated traces as a graph
|
|
||||||
pub graph: DiGraph<STGNode, STGEdge>,
|
|
||||||
systemstate_index: HashMap<u64, ReducedFreeRTOSSystemState>,
|
|
||||||
pub state_abb_hash_index: HashMap<(u64, u64), NodeIndex>,
|
|
||||||
stgnode_index: HashMap<u64, NodeIndex>,
|
|
||||||
entrypoint: NodeIndex,
|
|
||||||
exitpoint: NodeIndex,
|
|
||||||
// Metadata about aggregated traces. aggegated meaning, order has been removed
|
|
||||||
worst_observed_per_aggegated_path: HashMap<Vec<AtomicBasicBlock>,u64>,
|
|
||||||
worst_observed_per_abb_path: HashMap<u64,u64>,
|
|
||||||
worst_observed_per_stg_path: HashMap<u64,u64>,
|
|
||||||
worst_abb_exec_count: HashMap<AtomicBasicBlock, usize>
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for STGFeedbackState {
|
|
||||||
fn default() -> STGFeedbackState {
|
|
||||||
let mut graph = DiGraph::new();
|
|
||||||
let mut entry = STGNode::default();
|
|
||||||
entry.base.current_task.task_name="Start".to_string();
|
|
||||||
let mut exit = STGNode::default();
|
|
||||||
exit.base.current_task.task_name="End".to_string();
|
|
||||||
|
|
||||||
let systemstate_index = HashMap::from([(entry.base.get_hash(), entry.base.clone()), (exit.base.get_hash(), exit.base.clone())]);
|
|
||||||
|
|
||||||
let h_entry = entry.get_hash();
|
|
||||||
let h_exit = exit.get_hash();
|
|
||||||
|
|
||||||
let entrypoint = graph.add_node(entry.clone());
|
|
||||||
let exitpoint = graph.add_node(exit.clone());
|
|
||||||
|
|
||||||
let state_abb_hash_index = HashMap::from([((entry.base.get_hash(), entry.abb.get_hash()), entrypoint), ((exit.base.get_hash(), exit.abb.get_hash()), exitpoint)]);
|
|
||||||
|
|
||||||
let index = HashMap::from([(h_entry, entrypoint), (h_exit, exitpoint)]);
|
|
||||||
|
|
||||||
STGFeedbackState {
|
|
||||||
graph,
|
|
||||||
stgnode_index: index,
|
|
||||||
entrypoint,
|
|
||||||
exitpoint,
|
|
||||||
worst_observed_per_aggegated_path: HashMap::new(),
|
|
||||||
worst_observed_per_abb_path: HashMap::new(),
|
|
||||||
worst_observed_per_stg_path: HashMap::new(),
|
|
||||||
worst_abb_exec_count: HashMap::new(),
|
|
||||||
systemstate_index,
|
|
||||||
state_abb_hash_index
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Named for STGFeedbackState
|
|
||||||
{
|
|
||||||
#[inline]
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"stgfeedbackstate"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wrapper around Vec<RefinedFreeRTOSSystemState> to attach as Metadata
|
|
||||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
|
||||||
pub struct STGNodeMetadata {
|
|
||||||
pub nodes: Vec<NodeIndex>,
|
|
||||||
pub edges: Vec<EdgeIndex>,
|
|
||||||
pub abbs: u64,
|
|
||||||
pub aggregate: u64,
|
|
||||||
pub top_abb_counts: Vec<u64>,
|
|
||||||
pub intervals: Vec<ExecInterval>,
|
|
||||||
indices: Vec<usize>,
|
|
||||||
tcref: isize,
|
|
||||||
}
|
|
||||||
impl STGNodeMetadata {
|
|
||||||
pub fn new(nodes: Vec<NodeIndex>, edges: Vec<EdgeIndex>, abbs: u64, aggregate: u64, top_abb_counts: Vec<u64>, intervals: Vec<ExecInterval>) -> Self{
|
|
||||||
let mut indices : Vec<_> = vec![];
|
|
||||||
#[cfg(all(feature = "sched_stg",not(any(feature = "sched_stg_pathhash",feature = "sched_stg_abbhash",feature = "sched_stg_aggregatehash"))))]
|
|
||||||
{
|
|
||||||
indices = edges.iter().map(|x| x.index()).collect();
|
|
||||||
indices.sort_unstable();
|
|
||||||
indices.dedup();
|
|
||||||
}
|
|
||||||
#[cfg(feature = "sched_stg_pathhash")]
|
|
||||||
{
|
|
||||||
indices.push(get_generic_hash(&edges) as usize);
|
|
||||||
}
|
|
||||||
#[cfg(feature = "sched_stg_abbhash")]
|
|
||||||
{
|
|
||||||
indices.push(abbs as usize);
|
|
||||||
}
|
|
||||||
#[cfg(feature = "sched_stg_aggregatehash")]
|
|
||||||
{
|
|
||||||
// indices.push(aggregate as usize);
|
|
||||||
indices = top_abb_counts.iter().map(|x| (*x) as usize).collect();
|
|
||||||
}
|
|
||||||
Self {indices, intervals, nodes, abbs, aggregate, top_abb_counts, edges, tcref: 0}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl AsSlice for STGNodeMetadata {
|
|
||||||
/// Convert the slice of system-states to a slice of hashes over enumerated states
|
|
||||||
fn as_slice(&self) -> &[usize] {
|
|
||||||
self.indices.as_slice()
|
|
||||||
}
|
|
||||||
|
|
||||||
type Entry = usize;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HasRefCnt for STGNodeMetadata {
|
|
||||||
fn refcnt(&self) -> isize {
|
|
||||||
self.tcref
|
|
||||||
}
|
|
||||||
|
|
||||||
fn refcnt_mut(&mut self) -> &mut isize {
|
|
||||||
&mut self.tcref
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
libafl_bolts::impl_serdeany!(STGNodeMetadata);
|
|
||||||
|
|
||||||
pub type GraphMaximizerCorpusScheduler<CS> =
|
|
||||||
MinimizerScheduler<CS, MaxTimeFavFactor<<CS as UsesState>::State>,STGNodeMetadata>;
|
|
||||||
|
|
||||||
// AI generated, human verified
|
|
||||||
fn count_occurrences<T>(vec: &Vec<T>) -> HashMap<&T, usize>
|
|
||||||
where
|
|
||||||
T: PartialEq + Eq + Hash + Clone,
|
|
||||||
{
|
|
||||||
let mut counts = HashMap::new();
|
|
||||||
|
|
||||||
if vec.is_empty() {
|
|
||||||
return counts;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut current_obj = &vec[0];
|
|
||||||
let mut current_count = 1;
|
|
||||||
|
|
||||||
for obj in vec.iter().skip(1) {
|
|
||||||
if obj == current_obj {
|
|
||||||
current_count += 1;
|
|
||||||
} else {
|
|
||||||
counts.insert(current_obj, current_count);
|
|
||||||
current_obj = obj;
|
|
||||||
current_count = 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert the count of the last object
|
|
||||||
counts.insert(current_obj, current_count);
|
|
||||||
|
|
||||||
counts
|
|
||||||
}
|
|
||||||
|
|
||||||
//============================= Graph Feedback
|
|
||||||
|
|
||||||
pub static mut STG_MAP: [u16; EDGES_MAP_SIZE] = [0; EDGES_MAP_SIZE];
|
|
||||||
pub static mut MAX_STG_NUM: usize = 0;
|
|
||||||
pub unsafe fn stg_map_mut_slice<'a>() -> OwnedMutSlice<'a, u16> {
|
|
||||||
OwnedMutSlice::from_raw_parts_mut(STG_MAP.as_mut_ptr(), STG_MAP.len())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Feedback reporting novel System-State Transitions. Depends on [`QemuSystemStateObserver`]
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
|
||||||
pub struct StgFeedback
|
|
||||||
{
|
|
||||||
name: String,
|
|
||||||
last_node_trace: Option<Vec<NodeIndex>>,
|
|
||||||
last_edge_trace: Option<Vec<EdgeIndex>>,
|
|
||||||
last_intervals: Option<Vec<ExecInterval>>,
|
|
||||||
last_abbs_hash: Option<u64>, // only set, if it was interesting
|
|
||||||
last_aggregate_hash: Option<u64>, // only set, if it was interesting
|
|
||||||
last_top_abb_hashes: Option<Vec<u64>>, // only set, if it was interesting
|
|
||||||
dump_path: Option<PathBuf>
|
|
||||||
}
|
|
||||||
#[cfg(feature = "feed_stg")]
|
|
||||||
const INTEREST_EDGE : bool = true;
|
|
||||||
#[cfg(feature = "feed_stg")]
|
|
||||||
const INTEREST_NODE : bool = true;
|
|
||||||
#[cfg(feature = "feed_stg_pathhash")]
|
|
||||||
const INTEREST_PATH : bool = true;
|
|
||||||
#[cfg(feature = "feed_stg_abbhash")]
|
|
||||||
const INTEREST_ABBPATH : bool = true;
|
|
||||||
#[cfg(feature = "feed_stg_aggregatehash")]
|
|
||||||
const INTEREST_AGGREGATE : bool = true;
|
|
||||||
|
|
||||||
#[cfg(not(feature = "feed_stg"))]
|
|
||||||
const INTEREST_EDGE : bool = false;
|
|
||||||
#[cfg(not(feature = "feed_stg"))]
|
|
||||||
const INTEREST_NODE : bool = false;
|
|
||||||
#[cfg(not(feature = "feed_stg_pathhash"))]
|
|
||||||
const INTEREST_PATH : bool = false;
|
|
||||||
#[cfg(not(feature = "feed_stg_abbhash"))]
|
|
||||||
const INTEREST_ABBPATH : bool = false;
|
|
||||||
#[cfg(not(feature = "feed_stg_aggregatehash"))]
|
|
||||||
const INTEREST_AGGREGATE : bool = false;
|
|
||||||
fn set_observer_map(trace : &Vec<EdgeIndex>) {
|
|
||||||
unsafe {
|
|
||||||
for i in 0..MAX_STG_NUM {
|
|
||||||
STG_MAP[i] = 0;
|
|
||||||
}
|
|
||||||
for i in trace {
|
|
||||||
if MAX_STG_NUM < i.index() {
|
|
||||||
MAX_STG_NUM = i.index();
|
|
||||||
}
|
|
||||||
STG_MAP[i.index()]+=1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_generic_hash<H>(input: &H) -> u64
|
|
||||||
where
|
|
||||||
H: Hash,
|
|
||||||
{
|
|
||||||
let mut s = DefaultHasher::new();
|
|
||||||
input.hash(&mut s);
|
|
||||||
s.finish()
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StgFeedback {
|
|
||||||
pub fn new(dump_name: Option<PathBuf>) -> Self {
|
|
||||||
// Self {name: String::from("STGFeedback"), last_node_trace: None, last_edge_trace: None, last_intervals: None }
|
|
||||||
let mut s = Self::default();
|
|
||||||
s.dump_path = dump_name.map(|x| x.with_extension("stgsize"));
|
|
||||||
s
|
|
||||||
}
|
|
||||||
|
|
||||||
/// params:
|
|
||||||
/// tarce of intervals
|
|
||||||
/// hashtable of states
|
|
||||||
/// feedbackstate
|
|
||||||
/// produces:
|
|
||||||
/// tarce of node indexes representing the path trough the graph
|
|
||||||
/// newly discovered node?
|
|
||||||
/// side effect:
|
|
||||||
/// the graph gets new nodes and edge
|
|
||||||
fn update_stg_interval(trace: &Vec<ExecInterval>, table: &HashMap<u64, ReducedFreeRTOSSystemState>, fbs: &mut STGFeedbackState) -> (Vec<NodeIndex>, Vec<EdgeIndex>, bool, bool) {
|
|
||||||
let mut return_node_trace = vec![fbs.entrypoint];
|
|
||||||
let mut return_edge_trace = vec![];
|
|
||||||
let mut interesting = false;
|
|
||||||
let mut updated = false;
|
|
||||||
// add all missing state+abb combinations to the graph
|
|
||||||
for (i,interval) in trace.iter().enumerate() { // Iterate intervals
|
|
||||||
let node = STGNode {base: table[&interval.start_state].clone(), abb: interval.abb.as_ref().unwrap().clone()};
|
|
||||||
let h_node = node.get_hash();
|
|
||||||
let next_idx = if let Some(idx) = fbs.stgnode_index.get(&h_node) {
|
|
||||||
// alredy present
|
|
||||||
*idx
|
|
||||||
} else {
|
|
||||||
// not present
|
|
||||||
let h = (node.base.get_hash(), node.abb.get_hash());
|
|
||||||
let idx = fbs.graph.add_node(node);
|
|
||||||
fbs.stgnode_index.insert(h_node, idx);
|
|
||||||
fbs.state_abb_hash_index.insert(h, idx);
|
|
||||||
interesting |= INTEREST_NODE;
|
|
||||||
updated = true;
|
|
||||||
idx
|
|
||||||
};
|
|
||||||
// connect in graph if edge not present
|
|
||||||
let e = fbs.graph.edges_directed(return_node_trace[return_node_trace.len()-1],Direction::Outgoing).find(|x| petgraph::visit::EdgeRef::target(x) == next_idx);
|
|
||||||
if let Some(e_) = e {
|
|
||||||
return_edge_trace.push(petgraph::visit::EdgeRef::id(&e_));
|
|
||||||
} else {
|
|
||||||
let e_ = fbs.graph.add_edge(return_node_trace[return_node_trace.len()-1], next_idx, STGEdge{event: interval.start_capture.0, name: interval.start_capture.1.clone()});
|
|
||||||
return_edge_trace.push(e_);
|
|
||||||
interesting |= INTEREST_EDGE;
|
|
||||||
updated = true;
|
|
||||||
}
|
|
||||||
return_node_trace.push(next_idx);
|
|
||||||
/*
|
|
||||||
Ideas:
|
|
||||||
Mark edges triggered by interrupts
|
|
||||||
Specify path with edges instead of nodes?
|
|
||||||
Form a coverage map over edges?
|
|
||||||
Sum up execution time per ABB
|
|
||||||
*/
|
|
||||||
}
|
|
||||||
// every path terminates at the end
|
|
||||||
if !fbs.graph.neighbors_directed(return_node_trace[return_node_trace.len()-1],Direction::Outgoing).any(|x| x == fbs.exitpoint) {
|
|
||||||
let e_ = fbs.graph.add_edge(return_node_trace[return_node_trace.len()-1], fbs.exitpoint, STGEdge { event: CaptureEvent::End, name: String::from("End") });
|
|
||||||
return_edge_trace.push(e_);
|
|
||||||
interesting |= INTEREST_EDGE;
|
|
||||||
updated = true;
|
|
||||||
}
|
|
||||||
return_node_trace.push(fbs.exitpoint);
|
|
||||||
#[cfg(feature = "feed_stg")]
|
|
||||||
set_observer_map(&return_edge_trace);
|
|
||||||
(return_node_trace, return_edge_trace, interesting, updated)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn abbs_in_exec_order(trace: &Vec<ExecInterval>) -> Vec<AtomicBasicBlock> {
|
|
||||||
let mut ret = Vec::new();
|
|
||||||
for i in 0..trace.len() {
|
|
||||||
if trace[i].abb != None &&
|
|
||||||
(trace[i].end_capture.0 == CaptureEvent::APIStart || trace[i].end_capture.0 == CaptureEvent::APIEnd || trace[i].end_capture.0 == CaptureEvent::End || trace[i].end_capture.0 == CaptureEvent::ISREnd) {
|
|
||||||
ret.push(trace[i].abb.as_ref().unwrap().clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S> Feedback<S> for StgFeedback
|
|
||||||
where
|
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor + HasNamedMetadata,
|
|
||||||
S::Input: HasTargetBytes,
|
|
||||||
{
|
|
||||||
#[allow(clippy::wrong_self_convention)]
|
|
||||||
fn is_interesting<EM, OT>(
|
|
||||||
&mut self,
|
|
||||||
state: &mut S,
|
|
||||||
_manager: &mut EM,
|
|
||||||
_input: &S::Input,
|
|
||||||
observers: &OT,
|
|
||||||
_exit_kind: &ExitKind,
|
|
||||||
) -> Result<bool, Error>
|
|
||||||
where
|
|
||||||
EM: EventFirer<State = S>,
|
|
||||||
OT: ObserversTuple<S>,
|
|
||||||
{
|
|
||||||
let observer = observers.match_name::<QemuSystemStateObserver>("systemstate")
|
|
||||||
.expect("QemuSystemStateObserver not found");
|
|
||||||
let clock_observer = observers.match_name::<QemuClockObserver>("clocktime")
|
|
||||||
.expect("QemuClockObserver not found");
|
|
||||||
let feedbackstate = match state
|
|
||||||
.named_metadata_map_mut()
|
|
||||||
.get_mut::<STGFeedbackState>("stgfeedbackstate") {
|
|
||||||
Some(s) => s,
|
|
||||||
None => {
|
|
||||||
let n=STGFeedbackState::default();
|
|
||||||
state.named_metadata_map_mut().insert(n, "stgfeedbackstate");
|
|
||||||
state.named_metadata_map_mut().get_mut::<STGFeedbackState>("stgfeedbackstate").unwrap()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let (nodetrace, edgetrace, mut interesting, mut updated) = StgFeedback::update_stg_interval(&observer.last_trace, &observer.last_states, feedbackstate);
|
|
||||||
|
|
||||||
{
|
|
||||||
let h = get_generic_hash(&edgetrace);
|
|
||||||
if let Some(x) = feedbackstate.worst_observed_per_stg_path.get_mut(&h) {
|
|
||||||
let t = clock_observer.last_runtime();
|
|
||||||
if t > *x {
|
|
||||||
*x = t;
|
|
||||||
interesting |= INTEREST_PATH;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
feedbackstate.worst_observed_per_stg_path.insert(h, clock_observer.last_runtime());
|
|
||||||
updated = true;
|
|
||||||
interesting |= INTEREST_PATH;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut tmp = StgFeedback::abbs_in_exec_order(&observer.last_trace);
|
|
||||||
if INTEREST_AGGREGATE || INTEREST_ABBPATH {
|
|
||||||
if INTEREST_ABBPATH {
|
|
||||||
let h = get_generic_hash(&tmp);
|
|
||||||
self.last_abbs_hash = Some(h);
|
|
||||||
// order of execution is relevant
|
|
||||||
if let Some(x) = feedbackstate.worst_observed_per_abb_path.get_mut(&h) {
|
|
||||||
let t = clock_observer.last_runtime();
|
|
||||||
if t > *x {
|
|
||||||
*x = t;
|
|
||||||
interesting |= INTEREST_ABBPATH;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
feedbackstate.worst_observed_per_abb_path.insert(h, clock_observer.last_runtime());
|
|
||||||
interesting |= INTEREST_ABBPATH;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if INTEREST_AGGREGATE {
|
|
||||||
// aggegation by sorting, order of states is not relevant
|
|
||||||
let mut _tmp = tmp.clone();
|
|
||||||
_tmp.sort();
|
|
||||||
let counts = count_occurrences(&_tmp);
|
|
||||||
let mut top_indices = Vec::new();
|
|
||||||
for (k,c) in counts {
|
|
||||||
if let Some(reference) = feedbackstate.worst_abb_exec_count.get_mut(k) {
|
|
||||||
if *reference < c {
|
|
||||||
*reference = c;
|
|
||||||
top_indices.push(get_generic_hash(k));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
top_indices.push(get_generic_hash(k));
|
|
||||||
feedbackstate.worst_abb_exec_count.insert(k.clone(), c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.last_top_abb_hashes = Some(top_indices);
|
|
||||||
|
|
||||||
self.last_aggregate_hash = Some(get_generic_hash(&_tmp));
|
|
||||||
if let Some(x) = feedbackstate.worst_observed_per_aggegated_path.get_mut(&_tmp) {
|
|
||||||
let t = clock_observer.last_runtime();
|
|
||||||
if t > *x {
|
|
||||||
*x = t;
|
|
||||||
interesting |= INTEREST_AGGREGATE;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
feedbackstate.worst_observed_per_aggegated_path.insert(_tmp, clock_observer.last_runtime());
|
|
||||||
interesting |= INTEREST_AGGREGATE;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// let out = feedbackstate.graph.map(|i,x| x.pretty_print(), |_,_| "");
|
|
||||||
// let outs = Dot::with_config(&out, &[Config::EdgeNoLabel]).to_string();
|
|
||||||
// let outs = outs.replace(';',"\\n");
|
|
||||||
// fs::write("./mystg.dot",outs).expect("Failed to write graph");
|
|
||||||
self.last_node_trace = Some(nodetrace);
|
|
||||||
self.last_edge_trace = Some(edgetrace);
|
|
||||||
self.last_intervals = Some(observer.last_trace.clone());
|
|
||||||
|
|
||||||
if let Some(dp) = &self.dump_path {
|
|
||||||
if updated {
|
|
||||||
let timestamp = SystemTime::now().duration_since(unsafe {FUZZ_START_TIMESTAMP}).unwrap().as_millis();
|
|
||||||
let mut file = OpenOptions::new()
|
|
||||||
.read(true)
|
|
||||||
.write(true)
|
|
||||||
.create(true)
|
|
||||||
.append(true)
|
|
||||||
.open(dp).expect("Could not open stgsize");
|
|
||||||
writeln!(file, "{},{},{},{},{}", feedbackstate.graph.edge_count(), feedbackstate.graph.node_count(), feedbackstate.worst_observed_per_aggegated_path.len(),feedbackstate.worst_observed_per_stg_path.len(), timestamp).expect("Write to dump failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(interesting)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Append to the testcase the generated metadata in case of a new corpus item
|
|
||||||
#[inline]
|
|
||||||
fn append_metadata<OT>(&mut self, _state: &mut S, _observers: &OT, testcase: &mut Testcase<S::Input>) -> Result<(), Error> {
|
|
||||||
let nodes = self.last_node_trace.take();
|
|
||||||
let edges = self.last_edge_trace.take();
|
|
||||||
match nodes {
|
|
||||||
Some(s) => testcase.metadata_map_mut().insert(STGNodeMetadata::new(s, edges.unwrap(), self.last_abbs_hash.take().unwrap_or_default(), self.last_aggregate_hash.take().unwrap_or_default(), self.last_top_abb_hashes.take().unwrap_or_default(), self.last_intervals.take().unwrap())),
|
|
||||||
None => (),
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Discard the stored metadata in case that the testcase is not added to the corpus
|
|
||||||
#[inline]
|
|
||||||
fn discard_metadata(&mut self, _state: &mut S, _input: &S::Input) -> Result<(), Error> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Named for StgFeedback
|
|
||||||
{
|
|
||||||
#[inline]
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
&self.name
|
|
||||||
}
|
|
||||||
}
|
|
@ -4,7 +4,7 @@ use libafl::inputs::BytesInput;
|
|||||||
use libafl::inputs::HasTargetBytes;
|
use libafl::inputs::HasTargetBytes;
|
||||||
use libafl::feedbacks::MapIndexesMetadata;
|
use libafl::feedbacks::MapIndexesMetadata;
|
||||||
use libafl::corpus::Testcase;
|
use libafl::corpus::Testcase;
|
||||||
use libafl::prelude::{UsesInput};
|
use libafl::prelude::{UsesInput, AsSlice};
|
||||||
use core::marker::PhantomData;
|
use core::marker::PhantomData;
|
||||||
use libafl::schedulers::{MinimizerScheduler, TestcaseScore};
|
use libafl::schedulers::{MinimizerScheduler, TestcaseScore};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@ -13,8 +13,7 @@ use hashbrown::{HashMap};
|
|||||||
use libafl::observers::ObserversTuple;
|
use libafl::observers::ObserversTuple;
|
||||||
use libafl::executors::ExitKind;
|
use libafl::executors::ExitKind;
|
||||||
use libafl::events::EventFirer;
|
use libafl::events::EventFirer;
|
||||||
use libafl::state::{MaybeHasClientPerfMonitor, HasCorpus, UsesState};
|
use libafl::state::{HasClientPerfMonitor, HasCorpus, UsesState};
|
||||||
use libafl::prelude::State;
|
|
||||||
use libafl::inputs::Input;
|
use libafl::inputs::Input;
|
||||||
use libafl::feedbacks::Feedback;
|
use libafl::feedbacks::Feedback;
|
||||||
use libafl::state::HasMetadata;
|
use libafl::state::HasMetadata;
|
||||||
@ -23,12 +22,11 @@ use libafl::observers::MapObserver;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::cmp;
|
use std::cmp;
|
||||||
|
|
||||||
use libafl_bolts::{
|
|
||||||
Named,
|
|
||||||
HasLen,
|
|
||||||
AsSlice,
|
|
||||||
};
|
|
||||||
use libafl::{
|
use libafl::{
|
||||||
|
bolts::{
|
||||||
|
tuples::Named,
|
||||||
|
HasLen,
|
||||||
|
},
|
||||||
observers::Observer,
|
observers::Observer,
|
||||||
Error,
|
Error,
|
||||||
};
|
};
|
||||||
@ -56,7 +54,7 @@ where
|
|||||||
S: HasCorpus + HasMetadata,
|
S: HasCorpus + HasMetadata,
|
||||||
S::Input: HasLen,
|
S::Input: HasLen,
|
||||||
{
|
{
|
||||||
fn compute(state: &S, entry: &mut Testcase<<S as UsesInput>::Input>) -> Result<f64, Error> {
|
fn compute(entry: &mut Testcase<<S as UsesInput>::Input>, state: &S) -> Result<f64, Error> {
|
||||||
// TODO maybe enforce entry.exec_time().is_some()
|
// TODO maybe enforce entry.exec_time().is_some()
|
||||||
let et = entry.exec_time().expect("testcase.exec_time is needed for scheduler");
|
let et = entry.exec_time().expect("testcase.exec_time is needed for scheduler");
|
||||||
let tns : i64 = et.as_nanos().try_into().expect("failed to convert time");
|
let tns : i64 = et.as_nanos().try_into().expect("failed to convert time");
|
||||||
@ -86,9 +84,9 @@ where
|
|||||||
S: HasCorpus + HasMetadata,
|
S: HasCorpus + HasMetadata,
|
||||||
S::Input: HasLen,
|
S::Input: HasLen,
|
||||||
{
|
{
|
||||||
fn compute( state: &S, entry: &mut Testcase<S::Input>) -> Result<f64, Error> {
|
fn compute(entry: &mut Testcase<S::Input>, state: &S) -> Result<f64, Error> {
|
||||||
let execs_per_hour = (3600.0/entry.exec_time().expect("testcase.exec_time is needed for scheduler").as_secs_f64());
|
let execs_per_hour = (3600.0/entry.exec_time().expect("testcase.exec_time is needed for scheduler").as_secs_f64());
|
||||||
let execs_times_length_per_hour = execs_per_hour*entry.load_len(state.corpus()).unwrap() as f64;
|
let execs_times_length_per_hour = execs_per_hour*entry.cached_len()? as f64;
|
||||||
Ok(execs_times_length_per_hour)
|
Ok(execs_times_length_per_hour)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -102,7 +100,7 @@ pub struct SortedFeedback {
|
|||||||
|
|
||||||
impl<S> Feedback<S> for SortedFeedback
|
impl<S> Feedback<S> for SortedFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor,
|
S: UsesInput + HasClientPerfMonitor,
|
||||||
S::Input: HasTargetBytes,
|
S::Input: HasTargetBytes,
|
||||||
{
|
{
|
||||||
#[allow(clippy::wrong_self_convention)]
|
#[allow(clippy::wrong_self_convention)]
|
||||||
@ -123,24 +121,12 @@ where
|
|||||||
if tmp.len()<32 {return Ok(false);}
|
if tmp.len()<32 {return Ok(false);}
|
||||||
let tmp = Vec::<u8>::from(&tmp[0..32]);
|
let tmp = Vec::<u8>::from(&tmp[0..32]);
|
||||||
// tmp.reverse();
|
// tmp.reverse();
|
||||||
// if tmp.is_sorted_by(|a,b| match a.partial_cmp(b).unwrap_or(Less) {
|
if tmp.is_sorted_by(|a,b| match a.partial_cmp(b).unwrap_or(Less) {
|
||||||
// Less => Some(Greater),
|
Less => Some(Greater),
|
||||||
// Equal => Some(Greater),
|
Equal => Some(Greater),
|
||||||
// Greater => Some(Less),
|
Greater => Some(Less),
|
||||||
// }) {return Ok(true)};
|
}) {return Ok(true)};
|
||||||
let mut is_sorted = true;
|
return Ok(false);
|
||||||
if tmp[0]<tmp[1] {
|
|
||||||
for i in 1..tmp.len() {
|
|
||||||
is_sorted &= tmp[i-1]<=tmp[i];
|
|
||||||
if !is_sorted {break;}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for i in 1..tmp.len() {
|
|
||||||
is_sorted &= tmp[i-1]>=tmp[i];
|
|
||||||
if !is_sorted {break;}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Ok(is_sorted);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -175,7 +161,7 @@ pub struct ExecTimeReachedFeedback
|
|||||||
|
|
||||||
impl<S> Feedback<S> for ExecTimeReachedFeedback
|
impl<S> Feedback<S> for ExecTimeReachedFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor,
|
S: UsesInput + HasClientPerfMonitor,
|
||||||
{
|
{
|
||||||
#[allow(clippy::wrong_self_convention)]
|
#[allow(clippy::wrong_self_convention)]
|
||||||
fn is_interesting<EM, OT>(
|
fn is_interesting<EM, OT>(
|
||||||
@ -224,7 +210,7 @@ pub struct ExecTimeCollectorFeedback
|
|||||||
|
|
||||||
impl<S> Feedback<S> for ExecTimeCollectorFeedback
|
impl<S> Feedback<S> for ExecTimeCollectorFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor,
|
S: UsesInput + HasClientPerfMonitor,
|
||||||
{
|
{
|
||||||
#[allow(clippy::wrong_self_convention)]
|
#[allow(clippy::wrong_self_convention)]
|
||||||
fn is_interesting<EM, OT>(
|
fn is_interesting<EM, OT>(
|
||||||
@ -289,7 +275,7 @@ pub struct ExecTimeIncFeedback
|
|||||||
|
|
||||||
impl<S> Feedback<S> for ExecTimeIncFeedback
|
impl<S> Feedback<S> for ExecTimeIncFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor,
|
S: UsesInput + HasClientPerfMonitor,
|
||||||
{
|
{
|
||||||
#[allow(clippy::wrong_self_convention)]
|
#[allow(clippy::wrong_self_convention)]
|
||||||
fn is_interesting<EM, OT>(
|
fn is_interesting<EM, OT>(
|
||||||
@ -315,15 +301,14 @@ where
|
|||||||
Ok(false)
|
Ok(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn append_metadata<OT>(
|
fn append_metadata(
|
||||||
&mut self,
|
&mut self,
|
||||||
_state: &mut S,
|
_state: &mut S,
|
||||||
observers: &OT,
|
|
||||||
testcase: &mut Testcase<<S as UsesInput>::Input>,
|
testcase: &mut Testcase<<S as UsesInput>::Input>,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
#[cfg(feature = "feed_afl")]
|
#[cfg(feature = "feed_afl")]
|
||||||
if self.last_is_longest {
|
if self.last_is_longest {
|
||||||
let mim : Option<&mut MapIndexesMetadata>= testcase.metadata_map_mut().get_mut();
|
let mim : Option<&mut MapIndexesMetadata>= testcase.metadata_mut().get_mut();
|
||||||
// pretend that the longest input alone excercises some non-existing edge, to keep it relevant
|
// pretend that the longest input alone excercises some non-existing edge, to keep it relevant
|
||||||
mim.unwrap().list.push(usize::MAX);
|
mim.unwrap().list.push(usize::MAX);
|
||||||
};
|
};
|
||||||
@ -357,7 +342,7 @@ pub struct AlwaysTrueFeedback
|
|||||||
|
|
||||||
impl<S> Feedback<S> for AlwaysTrueFeedback
|
impl<S> Feedback<S> for AlwaysTrueFeedback
|
||||||
where
|
where
|
||||||
S: State + UsesInput + MaybeHasClientPerfMonitor,
|
S: UsesInput + HasClientPerfMonitor,
|
||||||
{
|
{
|
||||||
#[allow(clippy::wrong_self_convention)]
|
#[allow(clippy::wrong_self_convention)]
|
||||||
fn is_interesting<EM, OT>(
|
fn is_interesting<EM, OT>(
|
||||||
|
5
fuzzers/FRET/tests/.gitignore
vendored
5
fuzzers/FRET/tests/.gitignore
vendored
@ -1,5 +0,0 @@
|
|||||||
dump
|
|
||||||
demo*
|
|
||||||
*.dot
|
|
||||||
*.time
|
|
||||||
*.case
|
|
@ -1,27 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
# cargo build --no-default-features --features std,snapshot_restore,singlecore,feed_afl,observer_hitcounts
|
|
||||||
|
|
||||||
# Test basic fuzzing loop
|
|
||||||
../target/debug/fret -k ../benchmark/build/waters.elf -c ../benchmark/target_symbols.csv -n ./dump/waters -tar fuzz -t 10 -s 123
|
|
||||||
|
|
||||||
# Test reprodcibility
|
|
||||||
rm -f ./dump/demo.case.time
|
|
||||||
../target/debug/fret -k ../benchmark/build/waters.elf -c ../benchmark/target_symbols.csv -n ./dump/demo -tr showmap -i ./demo.case
|
|
||||||
if [[ $(cut -d, -f1 ./dump/demo.case.time) != $(cut -d, -f1 ./demo.example.time) ]]; then echo "Not reproducible!" && exit 1; else echo "Reproducible"; fi
|
|
||||||
|
|
||||||
# Test state dump
|
|
||||||
# cargo build --no-default-features --features std,snapshot_restore,singlecore,feed_afl,observer_hitcounts,systemstate
|
|
||||||
if [[ -n "$(diff -q demo.example.state.ron dump/demo.trace.ron)" ]]; then echo "State not reproducible!"; else echo "State Reproducible"; fi
|
|
||||||
|
|
||||||
# Test abb traces
|
|
||||||
# cargo build --no-default-features --features std,snapshot_restore,singlecore,feed_afl,observer_hitcounts,systemstate,trace_abbs
|
|
||||||
if [[ -n "$(diff -q demo.example.abb.ron dump/demo.trace.ron)" ]]; then echo "ABB not reproducible!"; else echo "ABB Reproducible"; fi
|
|
||||||
|
|
||||||
# ../target/debug/fret -k ../benchmark/build/minimal.elf -c ../benchmark/target_symbols.csv -n ./dump/minimal -tar fuzz -t 20 -s 123
|
|
||||||
# ../target/debug/fret -k ../benchmark/build/minimal.elf -c ../benchmark/target_symbols.csv -n ./dump/minimal_worst -tr showmap -i ./dump/minimal.case
|
|
||||||
|
|
||||||
# Test fuzzing using systemtraces
|
|
||||||
cargo build --no-default-features --features std,snapshot_restore,singlecore,feed_systemtrace
|
|
||||||
|
|
||||||
../target/debug/fret -k ../benchmark/build/waters.elf -c ../benchmark/target_symbols.csv -n ./dump/waters -tar fuzz -t 10 -s 123
|
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "baby_fuzzer"
|
name = "baby_fuzzer"
|
||||||
version = "0.10.0"
|
version = "0.7.1"
|
||||||
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
@ -21,4 +21,3 @@ debug = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
libafl = { path = "../../libafl/" }
|
libafl = { path = "../../libafl/" }
|
||||||
libafl_bolts = { path = "../../libafl_bolts/" }
|
|
||||||
|
@ -6,5 +6,3 @@ It runs on a single core until a crash occurs and then exits.
|
|||||||
|
|
||||||
The tested program is a simple Rust function without any instrumentation.
|
The tested program is a simple Rust function without any instrumentation.
|
||||||
For real fuzzing, you will want to add some sort to add coverage or other feedback.
|
For real fuzzing, you will want to add some sort to add coverage or other feedback.
|
||||||
|
|
||||||
You can run this example using `cargo run`, and you can enable the TUI feature by running `cargo run --features tui`.
|
|
@ -4,86 +4,67 @@ from pylibafl import libafl
|
|||||||
|
|
||||||
def map_observer_wrapper(map_observer):
|
def map_observer_wrapper(map_observer):
|
||||||
if type(map_observer).__name__ == "OwnedMapObserverI32":
|
if type(map_observer).__name__ == "OwnedMapObserverI32":
|
||||||
return libafl.MapObserverI32.new_owned(map_observer)
|
return libafl.MapObserverI32.new_from_owned(map_observer)
|
||||||
|
|
||||||
def executor_wrapper(executor):
|
def executor_wrapper(executor):
|
||||||
if type(executor).__name__ == "InProcessExecutor":
|
if type(executor).__name__ == "OwnedInProcessExecutorI32":
|
||||||
return libafl.Executor.new_inprocess(executor)
|
return libafl.ExecutorI32.new_from_inprocess(executor)
|
||||||
|
|
||||||
def generator_wrapper(generator):
|
|
||||||
if type(generator).__name__ == "RandPrintablesGenerator":
|
|
||||||
return libafl.Generator.new_rand_printables(generator)
|
|
||||||
|
|
||||||
def monitor_wrapper(monitor):
|
def monitor_wrapper(monitor):
|
||||||
return monitor.as_monitor()
|
if type(monitor).__name__ == "SimpleMonitor":
|
||||||
|
return libafl.Monitor.new_from_simple(monitor)
|
||||||
|
|
||||||
def event_manager_wrapper(event_manager):
|
def event_manager_wrapper(event_manager):
|
||||||
return event_manager.as_manager()
|
if type(event_manager).__name__ == "SimpleEventManager":
|
||||||
|
return libafl.EventManagerI32.new_from_simple(event_manager)
|
||||||
|
|
||||||
def corpus_wrapper(corpus):
|
def corpus_wrapper(corpus):
|
||||||
if type(corpus).__name__ == "InMemoryCorpus":
|
if type(corpus).__name__ == "InMemoryCorpus":
|
||||||
return libafl.Corpus.new_in_memory(corpus)
|
return libafl.Corpus.new_from_in_memory(corpus)
|
||||||
if type(corpus).__name__ == "OnDiskCorpus":
|
if type(corpus).__name__ == "OnDiskCorpus":
|
||||||
return libafl.Corpus.new_on_disk(corpus)
|
return libafl.Corpus.new_from_on_disk(corpus)
|
||||||
|
|
||||||
def rand_wrapper(rand):
|
def rand_wrapper(rand):
|
||||||
if type(rand).__name__ == "StdRand":
|
if type(rand).__name__ == "StdRand":
|
||||||
return libafl.Rand.new_std(rand)
|
return libafl.Rand.new_from_std(rand)
|
||||||
|
|
||||||
def mutator_wrapper(mutator):
|
|
||||||
if type(mutator).__name__ == "StdHavocMutator":
|
|
||||||
return libafl.Mutator.new_std_havoc(mutator)
|
|
||||||
|
|
||||||
def stage_wrapper(stage):
|
def stage_wrapper(stage):
|
||||||
if type(stage).__name__ == "StdMutationalStage":
|
if type(stage).__name__ == "StdScheduledHavocMutationsStageI32":
|
||||||
return libafl.Stage.new_std_mutational(stage)
|
return libafl.StageI32.new_from_std_scheduled(stage)
|
||||||
|
|
||||||
# CODE WRITTEN BY USER
|
# CODE WRITTEN BY USER
|
||||||
import logging
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
def harness(inp):
|
||||||
|
if len(inp.hex()) >= 2 and inp.hex()[:2] == '61':
|
||||||
|
raise Exception("NOOOOOO =)")
|
||||||
|
|
||||||
map_observer = libafl.OwnedMapObserverI32("signals", [0] * 16)
|
map_observer = libafl.OwnedMapObserverI32("signals", [0] * 16)
|
||||||
|
|
||||||
def harness(inp):
|
feedback_state = libafl.MapFeedbackStateI32.with_observer(map_observer_wrapper(map_observer))
|
||||||
#print(inp)
|
|
||||||
map_observer[0] = 1
|
|
||||||
if len(inp) > 0 and inp[0] == ord('a'):
|
|
||||||
map_observer[1] = 1
|
|
||||||
if len(inp) > 1 and inp[1] == ord('b'):
|
|
||||||
map_observer[2] = 1
|
|
||||||
if len(inp) > 2 and inp[2] == ord('c'):
|
|
||||||
map_observer[3] = 1
|
|
||||||
raise Exception("NOOOOOO =)")
|
|
||||||
|
|
||||||
feedback = libafl.MaxMapFeedbackI32(map_observer_wrapper(map_observer))
|
feedback = libafl.MaxMapFeedbackI32(feedback_state, map_observer_wrapper(map_observer))
|
||||||
objective = libafl.CrashFeedback()
|
|
||||||
|
|
||||||
state = libafl.StdState(
|
state = libafl.StdStateI32(
|
||||||
rand_wrapper(libafl.StdRand.with_current_nanos()),
|
rand_wrapper(libafl.StdRand.with_current_nanos()),
|
||||||
corpus_wrapper(libafl.InMemoryCorpus()),
|
corpus_wrapper(libafl.InMemoryCorpus()),
|
||||||
corpus_wrapper(libafl.OnDiskCorpus("./crashes")),
|
corpus_wrapper(libafl.OnDiskCorpus("./crashes")),
|
||||||
feedback.as_feedback(),
|
feedback_state
|
||||||
objective.as_feedback(),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
monitor = libafl.SimpleMonitor(lambda x: print(x))
|
monitor = libafl.SimpleMonitor()
|
||||||
|
|
||||||
mgr = libafl.SimpleEventManager(monitor_wrapper(monitor))
|
mgr = libafl.SimpleEventManager(monitor_wrapper(monitor))
|
||||||
|
|
||||||
fuzzer = libafl.StdFuzzer(feedback.as_feedback(), objective.as_feedback())
|
fuzzer = libafl.StdFuzzerI32(feedback)
|
||||||
|
|
||||||
observers = libafl.ObserversTuple([libafl.Observer.new_map_i32(map_observer_wrapper(map_observer))])
|
executor = libafl.OwnedInProcessExecutorI32(harness, map_observer_wrapper(map_observer), fuzzer, state, event_manager_wrapper(mgr))
|
||||||
|
|
||||||
executor = libafl.InProcessExecutor(harness, observers, fuzzer, state, event_manager_wrapper(mgr))
|
generator = libafl.RandPrintablesGeneratorI32(32)
|
||||||
|
|
||||||
generator = libafl.RandPrintablesGenerator(32)
|
state.generate_initial_inputs(fuzzer, executor_wrapper(executor), generator, event_manager_wrapper(mgr), 8)
|
||||||
|
|
||||||
state.generate_initial_inputs(fuzzer, executor_wrapper(executor), generator_wrapper(generator), event_manager_wrapper(mgr), 3)
|
stage = libafl.StdScheduledHavocMutationsStageI32.new_from_scheduled_havoc_mutations()
|
||||||
|
|
||||||
mutator = libafl.StdHavocMutator()
|
stage_tuple_list = libafl.StagesOwnedListI32(stage_wrapper(stage))
|
||||||
|
|
||||||
stage = libafl.StdMutationalStage(mutator_wrapper(mutator))
|
fuzzer.fuzz_loop(executor_wrapper(executor), state, event_manager_wrapper(mgr), stage_tuple_list)
|
||||||
|
|
||||||
stages = libafl.StagesTuple([stage_wrapper(stage)])
|
|
||||||
|
|
||||||
fuzzer.fuzz_loop(executor_wrapper(executor), state, event_manager_wrapper(mgr), stages)
|
|
@ -1,12 +1,13 @@
|
|||||||
|
use std::path::PathBuf;
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
use std::ptr::write_volatile;
|
use std::ptr::write_volatile;
|
||||||
use std::{path::PathBuf, ptr::write};
|
|
||||||
|
|
||||||
#[cfg(feature = "tui")]
|
#[cfg(feature = "tui")]
|
||||||
use libafl::monitors::tui::{ui::TuiUI, TuiMonitor};
|
use libafl::monitors::tui::TuiMonitor;
|
||||||
#[cfg(not(feature = "tui"))]
|
#[cfg(not(feature = "tui"))]
|
||||||
use libafl::monitors::SimpleMonitor;
|
use libafl::monitors::SimpleMonitor;
|
||||||
use libafl::{
|
use libafl::{
|
||||||
|
bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice},
|
||||||
corpus::{InMemoryCorpus, OnDiskCorpus},
|
corpus::{InMemoryCorpus, OnDiskCorpus},
|
||||||
events::SimpleEventManager,
|
events::SimpleEventManager,
|
||||||
executors::{inprocess::InProcessExecutor, ExitKind},
|
executors::{inprocess::InProcessExecutor, ExitKind},
|
||||||
@ -20,18 +21,16 @@ use libafl::{
|
|||||||
stages::mutational::StdMutationalStage,
|
stages::mutational::StdMutationalStage,
|
||||||
state::StdState,
|
state::StdState,
|
||||||
};
|
};
|
||||||
use libafl_bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice};
|
|
||||||
|
|
||||||
/// Coverage map with explicit assignments due to the lack of instrumentation
|
/// Coverage map with explicit assignments due to the lack of instrumentation
|
||||||
static mut SIGNALS: [u8; 16] = [0; 16];
|
static mut SIGNALS: [u8; 16] = [0; 16];
|
||||||
static mut SIGNALS_PTR: *mut u8 = unsafe { SIGNALS.as_mut_ptr() };
|
|
||||||
|
|
||||||
/// Assign a signal to the signals map
|
/// Assign a signal to the signals map
|
||||||
fn signals_set(idx: usize) {
|
fn signals_set(idx: usize) {
|
||||||
unsafe { write(SIGNALS_PTR.add(idx), 1) };
|
unsafe { SIGNALS[idx] = 1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::similar_names, clippy::manual_assert)]
|
#[allow(clippy::similar_names)]
|
||||||
pub fn main() {
|
pub fn main() {
|
||||||
// The closure that we want to fuzz
|
// The closure that we want to fuzz
|
||||||
let mut harness = |input: &BytesInput| {
|
let mut harness = |input: &BytesInput| {
|
||||||
@ -61,7 +60,8 @@ pub fn main() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Create an observation channel using the signals map
|
// Create an observation channel using the signals map
|
||||||
let observer = unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS_PTR, SIGNALS.len()) };
|
let observer =
|
||||||
|
unsafe { StdMapObserver::new_from_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) };
|
||||||
|
|
||||||
// Feedback to rate the interestingness of an input
|
// Feedback to rate the interestingness of an input
|
||||||
let mut feedback = MaxMapFeedback::new(&observer);
|
let mut feedback = MaxMapFeedback::new(&observer);
|
||||||
@ -88,11 +88,9 @@ pub fn main() {
|
|||||||
|
|
||||||
// The Monitor trait define how the fuzzer stats are displayed to the user
|
// The Monitor trait define how the fuzzer stats are displayed to the user
|
||||||
#[cfg(not(feature = "tui"))]
|
#[cfg(not(feature = "tui"))]
|
||||||
let mon = SimpleMonitor::new(|s| println!("{s}"));
|
let mon = SimpleMonitor::new(|s| println!("{}", s));
|
||||||
#[cfg(feature = "tui")]
|
#[cfg(feature = "tui")]
|
||||||
let ui = TuiUI::with_version(String::from("Baby Fuzzer"), String::from("0.0.1"), false);
|
let mon = TuiMonitor::new(String::from("Baby Fuzzer"), false);
|
||||||
#[cfg(feature = "tui")]
|
|
||||||
let mon = TuiMonitor::new(ui);
|
|
||||||
|
|
||||||
// The event manager handle the various events generated during the fuzzing loop
|
// The event manager handle the various events generated during the fuzzing loop
|
||||||
// such as the notification of the addition of a new item to the corpus
|
// such as the notification of the addition of a new item to the corpus
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "baby_fuzzer_gramatron"
|
name = "baby_fuzzer_gramatron"
|
||||||
version = "0.11.2"
|
version = "0.8.2"
|
||||||
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
@ -20,5 +20,4 @@ debug = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
libafl = { path = "../../libafl/" }
|
libafl = { path = "../../libafl/" }
|
||||||
libafl_bolts = { path = "../../libafl_bolts/" }
|
postcard = "0.7"
|
||||||
postcard = { version = "1.0", features = ["alloc"], default-features = false } # no_std compatible serde serialization format
|
|
||||||
|
@ -7,6 +7,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use libafl::{
|
use libafl::{
|
||||||
|
bolts::{current_nanos, rands::StdRand, tuples::tuple_list},
|
||||||
corpus::{InMemoryCorpus, OnDiskCorpus},
|
corpus::{InMemoryCorpus, OnDiskCorpus},
|
||||||
events::SimpleEventManager,
|
events::SimpleEventManager,
|
||||||
executors::{inprocess::InProcessExecutor, ExitKind},
|
executors::{inprocess::InProcessExecutor, ExitKind},
|
||||||
@ -24,15 +25,13 @@ use libafl::{
|
|||||||
stages::mutational::StdMutationalStage,
|
stages::mutational::StdMutationalStage,
|
||||||
state::StdState,
|
state::StdState,
|
||||||
};
|
};
|
||||||
use libafl_bolts::{current_nanos, rands::StdRand, tuples::tuple_list};
|
|
||||||
|
|
||||||
/// Coverage map with explicit assignments due to the lack of instrumentation
|
/// Coverage map with explicit assignments due to the lack of instrumentation
|
||||||
static mut SIGNALS: [u8; 16] = [0; 16];
|
static mut SIGNALS: [u8; 16] = [0; 16];
|
||||||
static mut SIGNALS_PTR: *mut u8 = unsafe { SIGNALS.as_mut_ptr() };
|
|
||||||
/*
|
/*
|
||||||
/// Assign a signal to the signals map
|
/// Assign a signal to the signals map
|
||||||
fn signals_set(idx: usize) {
|
fn signals_set(idx: usize) {
|
||||||
unsafe { std::ptr::write(SIGNALS_PTR.add(idx), 1) };
|
unsafe { SIGNALS[idx] = 1 };
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ -58,7 +57,7 @@ pub fn main() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Create an observation channel using the signals map
|
// Create an observation channel using the signals map
|
||||||
let observer = unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS_PTR, SIGNALS.len()) };
|
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS });
|
||||||
|
|
||||||
// Feedback to rate the interestingness of an input
|
// Feedback to rate the interestingness of an input
|
||||||
let mut feedback = MaxMapFeedback::new(&observer);
|
let mut feedback = MaxMapFeedback::new(&observer);
|
||||||
@ -84,7 +83,7 @@ pub fn main() {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
// The Monitor trait define how the fuzzer stats are reported to the user
|
// The Monitor trait define how the fuzzer stats are reported to the user
|
||||||
let monitor = SimpleMonitor::new(|s| println!("{s}"));
|
let monitor = SimpleMonitor::new(|s| println!("{}", s));
|
||||||
|
|
||||||
// The event manager handle the various events generated during the fuzzing loop
|
// The event manager handle the various events generated during the fuzzing loop
|
||||||
// such as the notification of the addition of a new item to the corpus
|
// such as the notification of the addition of a new item to the corpus
|
||||||
@ -123,7 +122,7 @@ pub fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut set = HashSet::new();
|
let mut set = HashSet::new();
|
||||||
let st = libafl_bolts::current_milliseconds();
|
let st = libafl::bolts::current_milliseconds();
|
||||||
let mut b = vec![];
|
let mut b = vec![];
|
||||||
let mut c = 0;
|
let mut c = 0;
|
||||||
for _ in 0..100000 {
|
for _ in 0..100000 {
|
||||||
@ -132,7 +131,7 @@ pub fn main() {
|
|||||||
set.insert(calculate_hash(&b));
|
set.insert(calculate_hash(&b));
|
||||||
c += b.len();
|
c += b.len();
|
||||||
}
|
}
|
||||||
println!("{} / {}", c, libafl_bolts::current_milliseconds() - st);
|
println!("{} / {}", c, libafl::bolts::current_milliseconds() - st);
|
||||||
println!("{} / 100000", set.len());
|
println!("{} / 100000", set.len());
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "baby_fuzzer_grimoire"
|
name = "baby_fuzzer_grimoire"
|
||||||
version = "0.11.2"
|
version = "0.8.2"
|
||||||
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
@ -20,4 +20,3 @@ debug = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
libafl = { path = "../../libafl/" }
|
libafl = { path = "../../libafl/" }
|
||||||
libafl_bolts = { path = "../../libafl_bolts/" }
|
|
||||||
|
@ -1,14 +1,15 @@
|
|||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
use std::ptr::write_volatile;
|
use std::ptr::write_volatile;
|
||||||
use std::{fs, io::Read, path::PathBuf, ptr::write};
|
use std::{fs, io::Read, path::PathBuf};
|
||||||
|
|
||||||
use libafl::{
|
use libafl::{
|
||||||
|
bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice},
|
||||||
corpus::{InMemoryCorpus, OnDiskCorpus},
|
corpus::{InMemoryCorpus, OnDiskCorpus},
|
||||||
events::SimpleEventManager,
|
events::SimpleEventManager,
|
||||||
executors::{inprocess::InProcessExecutor, ExitKind},
|
executors::{inprocess::InProcessExecutor, ExitKind},
|
||||||
feedbacks::{CrashFeedback, MaxMapFeedback},
|
feedbacks::{CrashFeedback, MaxMapFeedback},
|
||||||
fuzzer::{Evaluator, Fuzzer, StdFuzzer},
|
fuzzer::{Evaluator, Fuzzer, StdFuzzer},
|
||||||
inputs::{BytesInput, HasTargetBytes},
|
inputs::{GeneralizedInput, HasTargetBytes},
|
||||||
monitors::SimpleMonitor,
|
monitors::SimpleMonitor,
|
||||||
mutators::{
|
mutators::{
|
||||||
havoc_mutations, scheduled::StdScheduledMutator, GrimoireExtensionMutator,
|
havoc_mutations, scheduled::StdScheduledMutator, GrimoireExtensionMutator,
|
||||||
@ -20,14 +21,13 @@ use libafl::{
|
|||||||
stages::{mutational::StdMutationalStage, GeneralizationStage},
|
stages::{mutational::StdMutationalStage, GeneralizationStage},
|
||||||
state::{HasMetadata, StdState},
|
state::{HasMetadata, StdState},
|
||||||
};
|
};
|
||||||
use libafl_bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice};
|
|
||||||
|
|
||||||
/// Coverage map with explicit assignments due to the lack of instrumentation
|
/// Coverage map with explicit assignments due to the lack of instrumentation
|
||||||
static mut SIGNALS: [u8; 16] = [0; 16];
|
static mut SIGNALS: [u8; 16] = [0; 16];
|
||||||
static mut SIGNALS_PTR: *mut u8 = unsafe { SIGNALS.as_mut_ptr() };
|
|
||||||
/// Assign a signal to the signals map
|
/// Assign a signal to the signals map
|
||||||
fn signals_set(idx: usize) {
|
fn signals_set(idx: usize) {
|
||||||
unsafe { write(SIGNALS_PTR.add(idx), 1) };
|
unsafe { SIGNALS[idx] = 1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_sub<T: PartialEq>(mut haystack: &[T], needle: &[T]) -> bool {
|
fn is_sub<T: PartialEq>(mut haystack: &[T], needle: &[T]) -> bool {
|
||||||
@ -59,13 +59,13 @@ pub fn main() {
|
|||||||
let mut file = fs::File::open(path).expect("no file found");
|
let mut file = fs::File::open(path).expect("no file found");
|
||||||
let mut buffer = vec![];
|
let mut buffer = vec![];
|
||||||
file.read_to_end(&mut buffer).expect("buffer overflow");
|
file.read_to_end(&mut buffer).expect("buffer overflow");
|
||||||
let input = BytesInput::new(buffer);
|
let input = GeneralizedInput::new(buffer);
|
||||||
initial_inputs.push(input);
|
initial_inputs.push(input);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The closure that we want to fuzz
|
// The closure that we want to fuzz
|
||||||
let mut harness = |input: &BytesInput| {
|
let mut harness = |input: &GeneralizedInput| {
|
||||||
let target_bytes = input.target_bytes();
|
let target_bytes = input.target_bytes();
|
||||||
let bytes = target_bytes.as_slice();
|
let bytes = target_bytes.as_slice();
|
||||||
|
|
||||||
@ -77,14 +77,21 @@ pub fn main() {
|
|||||||
signals_set(3);
|
signals_set(3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
if input.grimoire_mutated {
|
||||||
|
// println!(">>> {:?}", input.generalized());
|
||||||
|
println!(">>> {:?}", std::str::from_utf8_unchecked(bytes));
|
||||||
|
}
|
||||||
|
}
|
||||||
signals_set(1);
|
signals_set(1);
|
||||||
ExitKind::Ok
|
ExitKind::Ok
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create an observation channel using the signals map
|
// Create an observation channel using the signals map
|
||||||
let observer = unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS_PTR, SIGNALS.len()) };
|
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS });
|
||||||
|
|
||||||
// Feedback to rate the interestingness of an input
|
// Feedback to rate the interestingness of an input
|
||||||
let mut feedback = MaxMapFeedback::tracking(&observer, false, true);
|
let mut feedback = MaxMapFeedback::new_tracking(&observer, false, true);
|
||||||
|
|
||||||
// A feedback to choose if an input is a solution or not
|
// A feedback to choose if an input is a solution or not
|
||||||
let mut objective = CrashFeedback::new();
|
let mut objective = CrashFeedback::new();
|
||||||
@ -106,12 +113,12 @@ pub fn main() {
|
|||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
if state.metadata_map().get::<Tokens>().is_none() {
|
if state.metadata().get::<Tokens>().is_none() {
|
||||||
state.add_metadata(Tokens::from([b"FOO".to_vec(), b"BAR".to_vec()]));
|
state.add_metadata(Tokens::from([b"FOO".to_vec(), b"BAR".to_vec()]));
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Monitor trait define how the fuzzer stats are reported to the user
|
// The Monitor trait define how the fuzzer stats are reported to the user
|
||||||
let monitor = SimpleMonitor::new(|s| println!("{s}"));
|
let monitor = SimpleMonitor::new(|s| println!("{}", s));
|
||||||
|
|
||||||
// The event manager handle the various events generated during the fuzzing loop
|
// The event manager handle the various events generated during the fuzzing loop
|
||||||
// such as the notification of the addition of a new item to the corpus
|
// such as the notification of the addition of a new item to the corpus
|
||||||
@ -151,7 +158,7 @@ pub fn main() {
|
|||||||
let mut stages = tuple_list!(
|
let mut stages = tuple_list!(
|
||||||
generalization,
|
generalization,
|
||||||
StdMutationalStage::new(mutator),
|
StdMutationalStage::new(mutator),
|
||||||
StdMutationalStage::transforming(grimoire_mutator)
|
StdMutationalStage::new(grimoire_mutator)
|
||||||
);
|
);
|
||||||
|
|
||||||
for input in initial_inputs {
|
for input in initial_inputs {
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "baby_fuzzer_minimizing"
|
name = "baby_fuzzer_minimizing"
|
||||||
version = "0.11.2"
|
version = "0.8.2"
|
||||||
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>", "Addison Crump <research@addisoncrump.info>"]
|
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>", "Addison Crump <research@addisoncrump.info>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
@ -21,4 +21,3 @@ debug = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
libafl = { path = "../../libafl/", features = ["prelude"] }
|
libafl = { path = "../../libafl/", features = ["prelude"] }
|
||||||
libafl_bolts = { path = "../../libafl_bolts/", features = ["prelude"] }
|
|
||||||
|
@ -1,17 +1,15 @@
|
|||||||
|
use std::path::PathBuf;
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
use std::ptr::write_volatile;
|
use std::ptr::write_volatile;
|
||||||
use std::{path::PathBuf, ptr::write};
|
|
||||||
|
|
||||||
use libafl::prelude::*;
|
use libafl::prelude::*;
|
||||||
use libafl_bolts::prelude::*;
|
|
||||||
|
|
||||||
/// Coverage map with explicit assignments due to the lack of instrumentation
|
/// Coverage map with explicit assignments due to the lack of instrumentation
|
||||||
static mut SIGNALS: [u8; 16] = [0; 16];
|
static mut SIGNALS: [u8; 16] = [0; 16];
|
||||||
static mut SIGNALS_PTR: *mut u8 = unsafe { SIGNALS.as_mut_ptr() };
|
|
||||||
|
|
||||||
/// Assign a signal to the signals map
|
/// Assign a signal to the signals map
|
||||||
fn signals_set(idx: usize) {
|
fn signals_set(idx: usize) {
|
||||||
unsafe { write(SIGNALS_PTR.add(idx), 1) };
|
unsafe { SIGNALS[idx] = 1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::similar_names)]
|
#[allow(clippy::similar_names)]
|
||||||
@ -34,9 +32,10 @@ pub fn main() -> Result<(), Error> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Create an observation channel using the signals map
|
// Create an observation channel using the signals map
|
||||||
let observer = unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS_PTR, SIGNALS.len()) };
|
let observer =
|
||||||
|
unsafe { StdMapObserver::new_from_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) };
|
||||||
|
|
||||||
let factory = MapEqualityFactory::with_observer(&observer);
|
let factory = MapEqualityFactory::new_from_observer(&observer);
|
||||||
|
|
||||||
// Feedback to rate the interestingness of an input
|
// Feedback to rate the interestingness of an input
|
||||||
let mut feedback = MaxMapFeedback::new(&observer);
|
let mut feedback = MaxMapFeedback::new(&observer);
|
||||||
@ -45,7 +44,7 @@ pub fn main() -> Result<(), Error> {
|
|||||||
let mut objective = CrashFeedback::new();
|
let mut objective = CrashFeedback::new();
|
||||||
|
|
||||||
// The Monitor trait define how the fuzzer stats are displayed to the user
|
// The Monitor trait define how the fuzzer stats are displayed to the user
|
||||||
let mon = SimpleMonitor::new(|s| println!("{s}"));
|
let mon = SimpleMonitor::new(|s| println!("{}", s));
|
||||||
|
|
||||||
let mut mgr = SimpleEventManager::new(mon);
|
let mut mgr = SimpleEventManager::new(mon);
|
||||||
|
|
||||||
@ -57,7 +56,7 @@ pub fn main() -> Result<(), Error> {
|
|||||||
// RNG
|
// RNG
|
||||||
StdRand::with_seed(current_nanos()),
|
StdRand::with_seed(current_nanos()),
|
||||||
// Corpus that will be evolved, we keep it in memory for performance
|
// Corpus that will be evolved, we keep it in memory for performance
|
||||||
InMemoryOnDiskCorpus::new(&corpus_dir).unwrap(),
|
OnDiskCorpus::new(&corpus_dir).unwrap(),
|
||||||
// Corpus in which we store solutions (crashes in this example),
|
// Corpus in which we store solutions (crashes in this example),
|
||||||
// on disk so the user can get them after stopping the fuzzer
|
// on disk so the user can get them after stopping the fuzzer
|
||||||
OnDiskCorpus::new(&solution_dir).unwrap(),
|
OnDiskCorpus::new(&solution_dir).unwrap(),
|
||||||
@ -109,7 +108,7 @@ pub fn main() -> Result<(), Error> {
|
|||||||
|
|
||||||
let mut state = StdState::new(
|
let mut state = StdState::new(
|
||||||
StdRand::with_seed(current_nanos()),
|
StdRand::with_seed(current_nanos()),
|
||||||
InMemoryOnDiskCorpus::new(minimized_dir).unwrap(),
|
OnDiskCorpus::new(&minimized_dir).unwrap(),
|
||||||
InMemoryCorpus::new(),
|
InMemoryCorpus::new(),
|
||||||
&mut (),
|
&mut (),
|
||||||
&mut (),
|
&mut (),
|
||||||
@ -117,7 +116,7 @@ pub fn main() -> Result<(), Error> {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
// The Monitor trait define how the fuzzer stats are displayed to the user
|
// The Monitor trait define how the fuzzer stats are displayed to the user
|
||||||
let mon = SimpleMonitor::new(|s| println!("{s}"));
|
let mon = SimpleMonitor::new(|s| println!("{}", s));
|
||||||
|
|
||||||
let mut mgr = SimpleEventManager::new(mon);
|
let mut mgr = SimpleEventManager::new(mon);
|
||||||
|
|
||||||
@ -137,13 +136,7 @@ pub fn main() -> Result<(), Error> {
|
|||||||
let mut executor = InProcessExecutor::new(&mut harness, (), &mut fuzzer, &mut state, &mut mgr)?;
|
let mut executor = InProcessExecutor::new(&mut harness, (), &mut fuzzer, &mut state, &mut mgr)?;
|
||||||
|
|
||||||
state.load_initial_inputs_forced(&mut fuzzer, &mut executor, &mut mgr, &[solution_dir])?;
|
state.load_initial_inputs_forced(&mut fuzzer, &mut executor, &mut mgr, &[solution_dir])?;
|
||||||
stages.perform_all(
|
stages.perform_all(&mut fuzzer, &mut executor, &mut state, &mut mgr, 0)?;
|
||||||
&mut fuzzer,
|
|
||||||
&mut executor,
|
|
||||||
&mut state,
|
|
||||||
&mut mgr,
|
|
||||||
CorpusId::from(0_usize),
|
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "baby_fuzzer_nautilus"
|
name = "baby_fuzzer_nautilus"
|
||||||
version = "0.11.2"
|
version = "0.8.2"
|
||||||
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
|
||||||
edition = "2021"
|
edition = "2018"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["std"]
|
default = ["std"]
|
||||||
@ -20,4 +20,3 @@ debug = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
libafl = { path = "../../libafl/", features = ["default", "nautilus"] }
|
libafl = { path = "../../libafl/", features = ["default", "nautilus"] }
|
||||||
libafl_bolts = { path = "../../libafl_bolts/" }
|
|
||||||
|
@ -3,6 +3,7 @@ use std::path::PathBuf;
|
|||||||
use std::ptr::write_volatile;
|
use std::ptr::write_volatile;
|
||||||
|
|
||||||
use libafl::{
|
use libafl::{
|
||||||
|
bolts::{current_nanos, rands::StdRand, tuples::tuple_list},
|
||||||
corpus::{InMemoryCorpus, OnDiskCorpus},
|
corpus::{InMemoryCorpus, OnDiskCorpus},
|
||||||
events::SimpleEventManager,
|
events::SimpleEventManager,
|
||||||
executors::{inprocess::InProcessExecutor, ExitKind},
|
executors::{inprocess::InProcessExecutor, ExitKind},
|
||||||
@ -20,15 +21,13 @@ use libafl::{
|
|||||||
stages::mutational::StdMutationalStage,
|
stages::mutational::StdMutationalStage,
|
||||||
state::{HasMetadata, StdState},
|
state::{HasMetadata, StdState},
|
||||||
};
|
};
|
||||||
use libafl_bolts::{current_nanos, rands::StdRand, tuples::tuple_list};
|
|
||||||
|
|
||||||
/// Coverage map with explicit assignments due to the lack of instrumentation
|
/// Coverage map with explicit assignments due to the lack of instrumentation
|
||||||
static mut SIGNALS: [u8; 16] = [0; 16];
|
static mut SIGNALS: [u8; 16] = [0; 16];
|
||||||
static mut SIGNALS_PTR: *mut u8 = unsafe { SIGNALS.as_mut_ptr() };
|
|
||||||
/*
|
/*
|
||||||
/// Assign a signal to the signals map
|
/// Assign a signal to the signals map
|
||||||
fn signals_set(idx: usize) {
|
fn signals_set(idx: usize) {
|
||||||
unsafe { str::ptr::write(SIGNALS_PTR.add(idx), 1) };
|
unsafe { SIGNALS[idx] = 1 };
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ -47,7 +46,7 @@ pub fn main() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Create an observation channel using the signals map
|
// Create an observation channel using the signals map
|
||||||
let observer = unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS_PTR, SIGNALS.len()) };
|
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS });
|
||||||
|
|
||||||
// Feedback to rate the interestingness of an input
|
// Feedback to rate the interestingness of an input
|
||||||
let mut feedback = feedback_or!(
|
let mut feedback = feedback_or!(
|
||||||
@ -75,16 +74,12 @@ pub fn main() {
|
|||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
if state
|
if state.metadata().get::<NautilusChunksMetadata>().is_none() {
|
||||||
.metadata_map()
|
|
||||||
.get::<NautilusChunksMetadata>()
|
|
||||||
.is_none()
|
|
||||||
{
|
|
||||||
state.add_metadata(NautilusChunksMetadata::new("/tmp/".into()));
|
state.add_metadata(NautilusChunksMetadata::new("/tmp/".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Monitor trait define how the fuzzer stats are reported to the user
|
// The Monitor trait define how the fuzzer stats are reported to the user
|
||||||
let monitor = SimpleMonitor::new(|s| println!("{s}"));
|
let monitor = SimpleMonitor::new(|s| println!("{}", s));
|
||||||
|
|
||||||
// The event manager handle the various events generated during the fuzzing loop
|
// The event manager handle the various events generated during the fuzzing loop
|
||||||
// such as the notification of the addition of a new item to the corpus
|
// such as the notification of the addition of a new item to the corpus
|
||||||
@ -122,7 +117,7 @@ pub fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut set = HashSet::new();
|
let mut set = HashSet::new();
|
||||||
let st = libafl_bolts::current_milliseconds();
|
let st = libafl::bolts::current_milliseconds();
|
||||||
let mut b = vec![];
|
let mut b = vec![];
|
||||||
let mut c = 0;
|
let mut c = 0;
|
||||||
for _ in 0..100000 {
|
for _ in 0..100000 {
|
||||||
@ -131,7 +126,7 @@ pub fn main() {
|
|||||||
set.insert(calculate_hash(&b));
|
set.insert(calculate_hash(&b));
|
||||||
c += b.len();
|
c += b.len();
|
||||||
}
|
}
|
||||||
println!("{} / {}", c, libafl_bolts::current_milliseconds() - st);
|
println!("{} / {}", c, libafl::bolts::current_milliseconds() - st);
|
||||||
println!("{} / 100000", set.len());
|
println!("{} / 100000", set.len());
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "baby_fuzzer_swap_differential"
|
name = "baby_fuzzer_swap_differential"
|
||||||
version = "0.11.2"
|
version = "0.7.1"
|
||||||
authors = ["Addison Crump <research@addisoncrump.info>"]
|
authors = ["Addison Crump <research@addisoncrump.info>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
default-run = "fuzzer_sd"
|
default-run = "fuzzer_sd"
|
||||||
@ -21,12 +21,11 @@ debug = true
|
|||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
bindgen = "0.63"
|
bindgen = "0.61"
|
||||||
cc = "1.0"
|
cc = "1.0"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
libafl = { path = "../../libafl" }
|
libafl = { path = "../../libafl" }
|
||||||
libafl_bolts = { path = "../../libafl_bolts" }
|
|
||||||
libafl_targets = { path = "../../libafl_targets", features = ["sancov_pcguard_hitcounts", "libfuzzer", "sancov_cmplog", "pointer_maps"] }
|
libafl_targets = { path = "../../libafl_targets", features = ["sancov_pcguard_hitcounts", "libfuzzer", "sancov_cmplog", "pointer_maps"] }
|
||||||
mimalloc = { version = "*", default-features = false }
|
mimalloc = { version = "*", default-features = false }
|
||||||
|
|
||||||
|
@ -1,27 +1,25 @@
|
|||||||
# Variables
|
# Variables
|
||||||
[env]
|
[env]
|
||||||
FUZZER_NAME='fuzzer_sd'
|
FUZZER_NAME='fuzzer_sd'
|
||||||
PROJECT_DIR = { script = ["pwd"] }
|
|
||||||
CARGO_TARGET_DIR = { value = "target", condition = { env_not_set = ["CARGO_TARGET_DIR"] } }
|
CARGO_TARGET_DIR = { value = "target", condition = { env_not_set = ["CARGO_TARGET_DIR"] } }
|
||||||
PROFILE = { value = "release" }
|
LIBAFL_CC = '${CARGO_TARGET_DIR}/release/libafl_cc'
|
||||||
PROFILE_DIR = {value = "release" }
|
FUZZER = '${CARGO_TARGET_DIR}/release/${FUZZER_NAME}'
|
||||||
LIBAFL_CC = '${CARGO_TARGET_DIR}/${PROFILE_DIR}/libafl_cc'
|
PROJECT_DIR = { script = ["pwd"] }
|
||||||
FUZZER = '${CARGO_TARGET_DIR}/${PROFILE_DIR}/${FUZZER_NAME}'
|
|
||||||
|
|
||||||
# Compilers
|
# Compilers
|
||||||
[tasks.cc]
|
[tasks.cc]
|
||||||
command = "cargo"
|
command = "cargo"
|
||||||
args = ["build" , "--profile", "${PROFILE}", "--bin", "libafl_cc"]
|
args = ["build" , "--release", "--bin", "libafl_cc"]
|
||||||
|
|
||||||
# Harness
|
# Harness
|
||||||
[tasks.fuzzer]
|
[tasks.fuzzer]
|
||||||
command = "cargo"
|
command = "cargo"
|
||||||
args = ["build" , "--profile", "${PROFILE}", "--bin", "${FUZZER_NAME}"]
|
args = ["build" , "--release", "--bin", "${FUZZER_NAME}"]
|
||||||
dependencies = [ "cc" ]
|
dependencies = [ "cc" ]
|
||||||
|
|
||||||
# Run the fuzzer
|
# Run the fuzzer
|
||||||
[tasks.run]
|
[tasks.run]
|
||||||
command = "${CARGO_TARGET_DIR}/${PROFILE_DIR}/${FUZZER_NAME}"
|
command = "${CARGO_TARGET_DIR}/release/${FUZZER_NAME}"
|
||||||
dependencies = [ "fuzzer" ]
|
dependencies = [ "fuzzer" ]
|
||||||
|
|
||||||
# Test
|
# Test
|
||||||
@ -33,13 +31,7 @@ windows_alias = "unsupported"
|
|||||||
[tasks.test_unix]
|
[tasks.test_unix]
|
||||||
script_runner = "@shell"
|
script_runner = "@shell"
|
||||||
script='''
|
script='''
|
||||||
timeout 30s ${CARGO_TARGET_DIR}/${PROFILE_DIR}/${FUZZER_NAME} >fuzz_stdout.log || true
|
timeout 10s ${CARGO_TARGET_DIR}/release/${FUZZER_NAME}
|
||||||
if [ -z "$(grep "objectives: 1" fuzz_stdout.log)" ]; then
|
|
||||||
echo "Fuzzer does not generate any testcases or any crashes"
|
|
||||||
exit 1
|
|
||||||
else
|
|
||||||
echo "Fuzzer is working"
|
|
||||||
fi
|
|
||||||
'''
|
'''
|
||||||
dependencies = [ "fuzzer" ]
|
dependencies = [ "fuzzer" ]
|
||||||
|
|
||||||
|
@ -27,7 +27,9 @@ fn main() -> anyhow::Result<()> {
|
|||||||
})
|
})
|
||||||
.join("release/libafl_cc");
|
.join("release/libafl_cc");
|
||||||
println!("cargo:rerun-if-changed={}", compiler.to_str().unwrap());
|
println!("cargo:rerun-if-changed={}", compiler.to_str().unwrap());
|
||||||
if compiler.try_exists().unwrap_or(false) {
|
if !compiler.try_exists().unwrap_or(false) {
|
||||||
|
println!("cargo:warning=Can't find libafl_cc; assuming that we're building it.");
|
||||||
|
} else {
|
||||||
cc::Build::new()
|
cc::Build::new()
|
||||||
.compiler(compiler)
|
.compiler(compiler)
|
||||||
.file("first.c")
|
.file("first.c")
|
||||||
@ -36,8 +38,6 @@ fn main() -> anyhow::Result<()> {
|
|||||||
.compile("diff-target");
|
.compile("diff-target");
|
||||||
|
|
||||||
println!("cargo:rustc-link-lib=diff-target");
|
println!("cargo:rustc-link-lib=diff-target");
|
||||||
} else {
|
|
||||||
println!("cargo:warning=Can't find libafl_cc; assuming that we're building it.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,7 +3,9 @@
|
|||||||
bool both_require(const uint8_t *bytes, size_t len) {
|
bool both_require(const uint8_t *bytes, size_t len) {
|
||||||
if (len >= 1 && bytes[0] == 'a') {
|
if (len >= 1 && bytes[0] == 'a') {
|
||||||
if (len >= 2 && bytes[1] == 'b') {
|
if (len >= 2 && bytes[1] == 'b') {
|
||||||
if (len >= 3 && bytes[2] == 'c') { return ACCEPT; }
|
if (len >= 3 && bytes[2] == 'c') {
|
||||||
|
return ACCEPT;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return REJECT;
|
return REJECT;
|
||||||
|
@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
bool inspect_first(const uint8_t *bytes, size_t len) {
|
bool inspect_first(const uint8_t *bytes, size_t len) {
|
||||||
if (both_require(bytes, len)) {
|
if (both_require(bytes, len)) {
|
||||||
if (len >= 4 && bytes[3] == 'd') { return ACCEPT; }
|
if (len >= 4 && bytes[3] == 'd') {
|
||||||
|
return ACCEPT;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return REJECT;
|
return REJECT;
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
bool inspect_second(const uint8_t *bytes, size_t len) {
|
bool inspect_second(const uint8_t *bytes, size_t len) {
|
||||||
if (both_require(bytes, len)) {
|
if (both_require(bytes, len)) {
|
||||||
if (len >= 5 && bytes[4] == 'e') { return ACCEPT; }
|
if (len >= 5 && bytes[4] == 'e') {
|
||||||
|
return ACCEPT;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return REJECT;
|
return REJECT;
|
||||||
}
|
}
|
@ -1,6 +1,6 @@
|
|||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
use libafl_cc::{ClangWrapper, CompilerWrapper, ToolWrapper};
|
use libafl_cc::{ClangWrapper, CompilerWrapper};
|
||||||
|
|
||||||
pub fn main() {
|
pub fn main() {
|
||||||
let args: Vec<String> = env::args().collect();
|
let args: Vec<String> = env::args().collect();
|
||||||
@ -11,7 +11,7 @@ pub fn main() {
|
|||||||
let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() {
|
let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() {
|
||||||
"cc" => false,
|
"cc" => false,
|
||||||
"++" | "pp" | "xx" => true,
|
"++" | "pp" | "xx" => true,
|
||||||
_ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"),
|
_ => panic!("Could not figure out if c or c++ wrapper was called. Expected {:?} to end with c or cxx", dir),
|
||||||
};
|
};
|
||||||
|
|
||||||
dir.pop();
|
dir.pop();
|
||||||
|
@ -6,11 +6,12 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(feature = "tui")]
|
#[cfg(feature = "tui")]
|
||||||
use libafl::monitors::tui::{ui::TuiUI, TuiMonitor};
|
use libafl::monitors::tui::TuiMonitor;
|
||||||
#[cfg(not(feature = "tui"))]
|
#[cfg(not(feature = "tui"))]
|
||||||
use libafl::monitors::SimpleMonitor;
|
use libafl::monitors::SimpleMonitor;
|
||||||
use libafl::{
|
use libafl::{
|
||||||
corpus::{Corpus, InMemoryCorpus, InMemoryOnDiskCorpus},
|
bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice},
|
||||||
|
corpus::{Corpus, InMemoryCorpus, OnDiskCorpus},
|
||||||
events::SimpleEventManager,
|
events::SimpleEventManager,
|
||||||
executors::{inprocess::InProcessExecutor, DiffExecutor, ExitKind},
|
executors::{inprocess::InProcessExecutor, DiffExecutor, ExitKind},
|
||||||
feedbacks::{CrashFeedback, MaxMapFeedback},
|
feedbacks::{CrashFeedback, MaxMapFeedback},
|
||||||
@ -23,22 +24,18 @@ use libafl::{
|
|||||||
stages::mutational::StdMutationalStage,
|
stages::mutational::StdMutationalStage,
|
||||||
state::{HasSolutions, StdState},
|
state::{HasSolutions, StdState},
|
||||||
};
|
};
|
||||||
use libafl_bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice};
|
use libafl_targets::{DifferentialAFLMapSwapObserver, MAX_EDGES_NUM};
|
||||||
use libafl_targets::{edges_max_num, DifferentialAFLMapSwapObserver};
|
|
||||||
#[cfg(not(miri))]
|
|
||||||
use mimalloc::MiMalloc;
|
use mimalloc::MiMalloc;
|
||||||
|
|
||||||
#[global_allocator]
|
#[global_allocator]
|
||||||
#[cfg(not(miri))]
|
|
||||||
static GLOBAL: MiMalloc = MiMalloc;
|
static GLOBAL: MiMalloc = MiMalloc;
|
||||||
|
|
||||||
// bindings to the functions defined in the target
|
// bindings to the functions defined in the target
|
||||||
mod bindings {
|
mod bindings {
|
||||||
#![allow(non_snake_case)]
|
|
||||||
#![allow(non_camel_case_types)]
|
#![allow(non_camel_case_types)]
|
||||||
#![allow(non_upper_case_globals)]
|
#![allow(non_upper_case_globals)]
|
||||||
#![allow(unused)]
|
#![allow(unused)]
|
||||||
#![allow(clippy::unreadable_literal)]
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
|
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,22 +44,24 @@ use bindings::{inspect_first, inspect_second};
|
|||||||
#[cfg(feature = "multimap")]
|
#[cfg(feature = "multimap")]
|
||||||
mod multimap {
|
mod multimap {
|
||||||
pub use libafl::observers::{HitcountsIterableMapObserver, MultiMapObserver};
|
pub use libafl::observers::{HitcountsIterableMapObserver, MultiMapObserver};
|
||||||
pub use libafl_bolts::ownedref::OwnedMutSlice;
|
|
||||||
|
pub static mut FIRST_EDGES: &'static mut [u8] = &mut [];
|
||||||
|
pub static mut SECOND_EDGES: &'static mut [u8] = &mut [];
|
||||||
|
pub static mut COMBINED_EDGES: [&'static mut [u8]; 2] = [&mut [], &mut []];
|
||||||
}
|
}
|
||||||
#[cfg(feature = "multimap")]
|
#[cfg(feature = "multimap")]
|
||||||
use multimap::{HitcountsIterableMapObserver, MultiMapObserver, OwnedMutSlice};
|
use multimap::*;
|
||||||
|
|
||||||
#[cfg(not(feature = "multimap"))]
|
#[cfg(not(feature = "multimap"))]
|
||||||
mod slicemap {
|
mod slicemap {
|
||||||
pub use libafl::observers::HitcountsMapObserver;
|
pub use libafl::observers::HitcountsMapObserver;
|
||||||
|
|
||||||
pub static mut EDGES: &mut [u8] = &mut [];
|
pub static mut EDGES: &'static mut [u8] = &mut [];
|
||||||
}
|
}
|
||||||
#[cfg(not(feature = "multimap"))]
|
#[cfg(not(feature = "multimap"))]
|
||||||
use slicemap::{HitcountsMapObserver, EDGES};
|
use slicemap::*;
|
||||||
|
|
||||||
#[allow(clippy::similar_names)]
|
#[allow(clippy::similar_names)]
|
||||||
#[allow(clippy::too_many_lines)]
|
|
||||||
pub fn main() {
|
pub fn main() {
|
||||||
// The closure that we want to fuzz
|
// The closure that we want to fuzz
|
||||||
let mut first_harness = |input: &BytesInput| {
|
let mut first_harness = |input: &BytesInput| {
|
||||||
@ -84,35 +83,19 @@ pub fn main() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let num_edges: usize = edges_max_num();
|
|
||||||
|
|
||||||
#[cfg(feature = "multimap")]
|
#[cfg(feature = "multimap")]
|
||||||
let (
|
let (first_map_observer, second_map_observer, map_swapper, map_observer) = {
|
||||||
first_map_observer,
|
|
||||||
second_map_observer,
|
|
||||||
map_swapper,
|
|
||||||
map_observer,
|
|
||||||
layout,
|
|
||||||
first_edges,
|
|
||||||
second_edges,
|
|
||||||
) = {
|
|
||||||
// initialize the maps
|
// initialize the maps
|
||||||
let layout = Layout::from_size_align(num_edges, 64).unwrap();
|
unsafe {
|
||||||
let first_edges = unsafe { (alloc_zeroed(layout), num_edges) };
|
let layout = Layout::from_size_align(MAX_EDGES_NUM, 64).unwrap();
|
||||||
let second_edges = unsafe { (alloc_zeroed(layout), num_edges) };
|
FIRST_EDGES = core::slice::from_raw_parts_mut(alloc_zeroed(layout), MAX_EDGES_NUM);
|
||||||
|
SECOND_EDGES = core::slice::from_raw_parts_mut(alloc_zeroed(layout), MAX_EDGES_NUM);
|
||||||
let combined_edges = unsafe {
|
COMBINED_EDGES = [&mut FIRST_EDGES, &mut SECOND_EDGES];
|
||||||
vec![
|
}
|
||||||
OwnedMutSlice::from_raw_parts_mut(first_edges.0, first_edges.1),
|
|
||||||
OwnedMutSlice::from_raw_parts_mut(second_edges.0, second_edges.1),
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
// create the base maps used to observe the different executors from two independent maps
|
// create the base maps used to observe the different executors from two independent maps
|
||||||
let mut first_map_observer =
|
let mut first_map_observer = StdMapObserver::new("first-edges", unsafe { FIRST_EDGES });
|
||||||
unsafe { StdMapObserver::from_mut_ptr("first-edges", first_edges.0, first_edges.1) };
|
let mut second_map_observer = StdMapObserver::new("second-edges", unsafe { SECOND_EDGES });
|
||||||
let mut second_map_observer =
|
|
||||||
unsafe { StdMapObserver::from_mut_ptr("second-edges", second_edges.0, second_edges.1) };
|
|
||||||
|
|
||||||
// create a map swapper so that we can replace the coverage map pointer (requires feature pointer_maps!)
|
// create a map swapper so that we can replace the coverage map pointer (requires feature pointer_maps!)
|
||||||
let map_swapper =
|
let map_swapper =
|
||||||
@ -123,35 +106,28 @@ pub fn main() {
|
|||||||
// differential mode
|
// differential mode
|
||||||
let map_observer = HitcountsIterableMapObserver::new(MultiMapObserver::differential(
|
let map_observer = HitcountsIterableMapObserver::new(MultiMapObserver::differential(
|
||||||
"combined-edges",
|
"combined-edges",
|
||||||
combined_edges,
|
unsafe { &mut COMBINED_EDGES },
|
||||||
));
|
));
|
||||||
|
|
||||||
(
|
(
|
||||||
first_map_observer,
|
first_map_observer,
|
||||||
second_map_observer,
|
second_map_observer,
|
||||||
map_swapper,
|
map_swapper,
|
||||||
map_observer,
|
map_observer,
|
||||||
layout,
|
|
||||||
first_edges,
|
|
||||||
second_edges,
|
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
#[cfg(not(feature = "multimap"))]
|
#[cfg(not(feature = "multimap"))]
|
||||||
let (first_map_observer, second_map_observer, map_swapper, map_observer) = {
|
let (first_map_observer, second_map_observer, map_swapper, map_observer) = {
|
||||||
// initialize the map
|
// initialize the map
|
||||||
unsafe {
|
unsafe {
|
||||||
let layout = Layout::from_size_align(num_edges * 2, 64).unwrap();
|
let layout = Layout::from_size_align(MAX_EDGES_NUM * 2, 64).unwrap();
|
||||||
EDGES = core::slice::from_raw_parts_mut(alloc_zeroed(layout), num_edges * 2);
|
EDGES = core::slice::from_raw_parts_mut(alloc_zeroed(layout), MAX_EDGES_NUM * 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
let edges_ptr = unsafe { EDGES.as_mut_ptr() };
|
|
||||||
|
|
||||||
// create the base maps used to observe the different executors by splitting a slice
|
// create the base maps used to observe the different executors by splitting a slice
|
||||||
let mut first_map_observer =
|
let mut first_map_observer =
|
||||||
unsafe { StdMapObserver::from_mut_ptr("first-edges", edges_ptr, num_edges) };
|
StdMapObserver::new("first-edges", unsafe { &mut EDGES[..MAX_EDGES_NUM] });
|
||||||
let mut second_map_observer = unsafe {
|
let mut second_map_observer =
|
||||||
StdMapObserver::from_mut_ptr("second-edges", edges_ptr.add(num_edges), num_edges)
|
StdMapObserver::new("second-edges", unsafe { &mut EDGES[MAX_EDGES_NUM..] });
|
||||||
};
|
|
||||||
|
|
||||||
// create a map swapper so that we can replace the coverage map pointer (requires feature pointer_maps!)
|
// create a map swapper so that we can replace the coverage map pointer (requires feature pointer_maps!)
|
||||||
let map_swapper =
|
let map_swapper =
|
||||||
@ -160,14 +136,10 @@ pub fn main() {
|
|||||||
// create a combined map observer, e.g. for calibration
|
// create a combined map observer, e.g. for calibration
|
||||||
// we use StdMapObserver::differential to indicate that we want to use the observer in
|
// we use StdMapObserver::differential to indicate that we want to use the observer in
|
||||||
// differential mode
|
// differential mode
|
||||||
let map_observer = unsafe {
|
let map_observer =
|
||||||
HitcountsMapObserver::new(StdMapObserver::differential_from_mut_ptr(
|
HitcountsMapObserver::new(StdMapObserver::differential("combined-edges", unsafe {
|
||||||
"combined-edges",
|
EDGES
|
||||||
edges_ptr,
|
}));
|
||||||
num_edges * 2,
|
|
||||||
))
|
|
||||||
};
|
|
||||||
|
|
||||||
(
|
(
|
||||||
first_map_observer,
|
first_map_observer,
|
||||||
second_map_observer,
|
second_map_observer,
|
||||||
@ -191,7 +163,7 @@ pub fn main() {
|
|||||||
InMemoryCorpus::new(),
|
InMemoryCorpus::new(),
|
||||||
// Corpus in which we store solutions (crashes in this example),
|
// Corpus in which we store solutions (crashes in this example),
|
||||||
// on disk so the user can get them after stopping the fuzzer
|
// on disk so the user can get them after stopping the fuzzer
|
||||||
InMemoryOnDiskCorpus::new(PathBuf::from("./crashes")).unwrap(),
|
OnDiskCorpus::new(PathBuf::from("./crashes")).unwrap(),
|
||||||
// States of the feedbacks.
|
// States of the feedbacks.
|
||||||
// The feedbacks can report the data that should persist in the State.
|
// The feedbacks can report the data that should persist in the State.
|
||||||
&mut feedback,
|
&mut feedback,
|
||||||
@ -202,11 +174,9 @@ pub fn main() {
|
|||||||
|
|
||||||
// The Monitor trait define how the fuzzer stats are displayed to the user
|
// The Monitor trait define how the fuzzer stats are displayed to the user
|
||||||
#[cfg(not(feature = "tui"))]
|
#[cfg(not(feature = "tui"))]
|
||||||
let mon = SimpleMonitor::new(|s| println!("{s}"));
|
let mon = SimpleMonitor::new(|s| println!("{}", s));
|
||||||
#[cfg(feature = "tui")]
|
#[cfg(feature = "tui")]
|
||||||
let ui = TuiUI::new(String::from("Baby Fuzzer"), false);
|
let mon = TuiMonitor::new(String::from("Baby Fuzzer"), false);
|
||||||
#[cfg(feature = "tui")]
|
|
||||||
let mon = TuiMonitor::new(ui);
|
|
||||||
|
|
||||||
// The event manager handle the various events generated during the fuzzing loop
|
// The event manager handle the various events generated during the fuzzing loop
|
||||||
// such as the notification of the addition of a new item to the corpus
|
// such as the notification of the addition of a new item to the corpus
|
||||||
@ -273,10 +243,4 @@ pub fn main() {
|
|||||||
)
|
)
|
||||||
.expect("Error in the fuzzing loop");
|
.expect("Error in the fuzzing loop");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "multimap")]
|
|
||||||
unsafe {
|
|
||||||
std::alloc::dealloc(first_edges.0, layout);
|
|
||||||
std::alloc::dealloc(second_edges.0, layout);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user