Compare commits

...

59 Commits
fret ... 0.9.0

Author SHA1 Message Date
Dominik Maier
cc53da85fb
Remove {update,clear}_hash from ObserverWithHashField, add hasher (extending #1019) (#1028)
* libafl: Remove `{update,clear}_hash` from `ObserverWithHashField`

These methods aren't used by `NewHashFeedback`, so there's no compelling reason
to keep them in the interface. They preclude implementations of
`ObserverWithHashField` that calculcate a hash on-the-fly from a value. For
example, my use-case is to store the stdout of a process, and use
`NewHashFeedback` to only collect inputs that result in new messages on stdout.

Both of these methods are pretty suspicious to begin with - why should other
code be able to update the internal state of the observer? What are the
semantics of `update_hash`? If there are compelling reasons to keep these
methods, let's clarify their intent in the documentation.

* libafl: Return hash by value from `ObserverWithHashField`

This allows implementors of this trait to not store the hash, but rather to
compute it on-the-fly. Since `Option<u64>` is `Copy` (and quite small), and
this method is called once per execution of the target program, this is likely
to have negligible performance impact.

* libafl: Implement `ObserverWithHashField` for `ValueObserver`

This demonstrates the utility of the previous two commits. Now, `ValueObserver`
can be used with `NewHashFeedback`.

* Clippy, move to ahasher

* Oops :)

---------

Co-authored-by: Langston Barrett <langston.barrett@gmail.com>
2023-01-31 10:45:42 +01:00
Andrea Fioraldi
fdf579bcd5
Bump to 0.9.0 (#946)
* bump to 0.9.0

* fix libafl_tinyinst

* fix

---------

Co-authored-by: Dominik Maier <domenukk@gmail.com>
2023-01-31 10:42:01 +01:00
Dominik Maier
d73fb92ddf
Python CI (#1024)
* Python CI

* fix testcase

* fix yml

* Fixing test

* format python

* cleanup
2023-01-31 05:04:19 +01:00
Dominik Maier
fc8c92514f
Update README.md (#1027) 2023-01-31 04:43:27 +01:00
Dominik Maier
7c4acb3b22
Update README.md (#1026) 2023-01-31 04:34:01 +01:00
Dominik Maier
2cd3fb8fea
New Logo (#1025) 2023-01-31 04:32:47 +01:00
Dominik Maier
ff9208f107
Fixing python example (#1016)
* Fixing python example

* Fix python baby fuzzer

---------

Co-authored-by: Andrea Fioraldi <andreafioraldi@gmail.com>
2023-01-30 20:03:07 +01:00
Fabian Freyer
afa506c0c8
libafl_frida: Allow compilation for iOS (#1023)
iOS does not have any TLS, so we don't need to keep track of it.
This allows compiling for the aarch64-apple-ios target.
2023-01-30 18:05:00 +01:00
Dominik Maier
33ddce2cea
Introduce MutatorId, Tuneable fixes (#1022)
* Add simpler APIs for TunableStage

* Make API usable

* Add TunableScheduledMutator APIs

* Introduce MutatorId

* More API

* Cleanup

* add sampling-based mutation scheduling

* reduce precision for sampling

* clippy
2023-01-30 18:04:42 +01:00
Dongjia "toka" Zhang
b927fc9b06
Add filename_path to MmapShMemProvider (#1014)
* change how it is named

* Add more comments

* more

* macOS 32bytes onlyu

* chg

* comment, fix
2023-01-26 00:53:37 +01:00
Dominik Maier
e5c220519e
LLMP Broker: timeouts for inactive clients (#1005)
* LLMP Timeouts

* Make broker timeouts optional

* fix warning

* fix warning
2023-01-25 12:03:23 +01:00
Andrea Fioraldi
92c0c5eeab
Fix second Forkserver Broken Pipe (#1013)
* Truncate at MAX_FILE

* AFL_MAP_SIZE

* todo
2023-01-24 20:50:56 +01:00
Addison Crump
00ec7e143c
fix for MapIndexesMetadata (#1008)
Co-authored-by: Andrea Fioraldi <andreafioraldi@gmail.com>
2023-01-23 15:08:33 +01:00
Dongjia "toka" Zhang
fe51286586
TinyInst Update (#968)
* tmp

* more

* save

* TODO

* fix

* update to tinyinst on crates

* dep

* fmt

* shmem done

* cpp fmt

* clp

* fmt

* why??

* ver

* more makefile.toml

* windows test

* Update build_and_test.yml

* fix

* a

* install

* fmt

* fix

* only macos and win

* more

* The order matters

* remove

* fmt

* chg

* typo

Co-authored-by: Andrea Fioraldi <andreafioraldi@gmail.com>
2023-01-23 11:11:53 +01:00
David CARLIER
3b68399cc9
libafl_cc fixes for clang 16 (#1010)
None constant being deprecated, it is recommended
to use the std::nullopt_t type instead.
2023-01-23 11:00:42 +01:00
Andrea Fioraldi
7fd9ac0952
SyncFromBrokerStage to sync from a broker with a different Input type (#997)
* ConverterLlmpEventManager

* docs

* SyncFromBrokerStage

* fix

* separate InputConverter

* nautilus

* nautilus_sync

* send testcases

* upd nautilus

* meta

* fix

* clippy

* fix

* Update build_and_test.yml

* fix

* fix

* Use find_libpython

* ci

* upd qemu
2023-01-20 17:16:29 +01:00
WorksButNotTested
5cdb7f7b05
Improve AARCH64 performance (#989) 2023-01-18 13:56:17 +01:00
Addison Crump
ebc886032f
Fixes for multiple subtle bugs with grimoire, mutators, and state (#1001)
* fix multiple subtle bugs with grimoire, mutators, and state

* obey the clippy overlord

* grimoire: skip over token after splice

* remove extraneous length check
2023-01-18 13:53:31 +01:00
Paul Walker
333a51aeaa
StacktraceObserver speedup using unresolved backtrace (#1002)
We don't use the symbols anyway, and it makes the call *way* faster.
2023-01-18 13:51:42 +01:00
Andrea Fioraldi
3c8a00bc42
Fix qemu user (#1003) 2023-01-18 13:38:49 +01:00
Dongjia "toka" Zhang
1446692f02
Fix stability UI (#1000)
* Update mod.rs

* fmt
2023-01-18 19:00:50 +09:00
van Hauser
15c1c0fb5e
Avoid no-op in ByteRandMutator (#999) 2023-01-17 11:07:50 +01:00
Andrea Fioraldi
7cf7d545a6
Update QEMU and fix snapshot restore mem leak (#998)
* Update qemu

* Fix leak

* upd

* fmt
2023-01-17 11:06:31 +01:00
Dominik Maier
97e88af0c5
OnDiskCorpus: Write metadata by default, metadata gzip compression (#995)
* Write metadata by default

* fix fuzzers

* Cleanup, gzip feature

* Fix casing for ondisk corpus

* fix fmt, clippy

* clippy

* clippy for gdiplus fuzzer

* fmt
2023-01-13 01:07:36 +01:00
Addison Crump
28786c943a
Grimoire fixes (#993)
* fixup grimoire/generalisation, remove GeneralizedInput in favour of metadata

* additional cleanup

* transformable inputs to solve the grimoire problem

* explicit use of 'transforming' to keep typing compatible with normal usage

* clippy fix

* fixes for nautilus, python

* explicit inlining for reflexive impl

* fix for tutorial

Co-authored-by: Andrea Fioraldi <andreafioraldi@gmail.com>
2023-01-13 01:07:21 +01:00
Andrea Fioraldi
ec84c71eae
Corpus maps (#947)
* hashmap corpus for inmemory

* corpus_btreemap feature

* CorpusId

* queue

* MinimizerScheduler::remove

* fixes

* continue

* keys

* working corpus

* ok

* weighted left

* wip

* port weighted scheduler

* it compiles

* doc

* fix mutators

* fix queue

* fix iter

* tests

* fix

* fix

* fix

* py

* clippy

* clippy

* clippy

* cmin

* fix

* fix

* fix

* clippy

* remove Corpus::random_id
2023-01-09 14:15:07 +01:00
biazo
3345727c94
fixing linking issue on qemu build (#990)
* fixing linking issue

* insteading of linking lib we dont use. just disable them

* fixing the keyutils problem

Co-authored-by: Andrea Fioraldi <andreafioraldi@gmail.com>
2023-01-09 10:10:14 +01:00
Dominik Maier
17cb317429
Fix early drop for frida transformer (#992)
* Fix early drop for frida transformer

* clippy
2023-01-08 18:19:30 +01:00
Dominik Maier
159e6ea480
Fix Launcher for M1, fix frida_libpng harness compilation, fix CI (#987)
* Fix harness compilation for frida_libpng

* M1: Always use fast cores

* always ignore result

* seeing if manualy installing libunistring fixes wget

* seeing if manualy installing wget fixes it, instead

* un-remove comment
2023-01-05 14:26:20 +01:00
WorksButNotTested
266677bb88
FRIDA: Fix previous_pc constant (#988)
Co-authored-by: Your Name <you@example.com>
2023-01-05 12:20:06 +01:00
WorksButNotTested
f27ca843e1
FRIDA x64 performance improvements (#985)
Co-authored-by: Your Name <you@example.com>
2023-01-05 11:51:58 +01:00
Dominik Maier
1bb37e4b98
Book: Explain SymCC constraint solving (follow up on #980) (#986)
* Make the kind of solving more clear (follow up on #980)

* Update docs/src/advanced_features/concolic.md

Co-authored-by: julihoh <julihoh@users.noreply.github.com>

Co-authored-by: julihoh <julihoh@users.noreply.github.com>
2023-01-05 11:51:31 +01:00
hexcoder
7d412693c8
Book review (#980)
* docs review

* docs review

* docs review wording

* docs review wording

* docs review wording

* wording

* nits

* wording

* wording

* nits

* docs_review wording

* wording

* wording

* wording

* Wording

* wording

* nits

* Wording

* fix main naming for afl++

* update symcc

Co-authored-by: Dominik Maier <dmnk@google.com>
2023-01-04 15:21:08 +01:00
Dongjia "toka" Zhang
d2985c5b2e
Clippy fix (#978)
* fix

* mac

* clp
2023-01-02 20:35:41 +09:00
Sparrrgh
43425cf103
Correct MIPS register naming in libafl_qemu (#977) 2022-12-31 09:23:50 +01:00
Dongjia "toka" Zhang
9458549fef
Remove declare -A (#976)
* fix

* fix

* debug

* debug

* older version

* newer version

* fix

* unix?

* fix
2022-12-30 02:02:38 +09:00
Erwan Grelet
3e38862837
Forkserver example with forkserver.c (#726) (#973)
* forkserver: Add an API to setup the shared memory region for edge coverage

This is inspired from and meant to be similar to afl-cc's instrumentation.
Remove ! return type from __afl_start_forkserver as it returns in several cases.

* Add example fuzzer using LibAFL's forkserver

The fuzzer is instrumented with libafl_cc as well.

Co-authored-by: ergrelet <ergrelet@users.noreply.github.com>
2022-12-28 22:16:27 +01:00
Dongjia "toka" Zhang
676a149497
Update CorpusWeightTestcaseScore (#975)
* fix

* clp

* fmt
2022-12-28 22:16:08 +01:00
Patrick Gersch
2b092f40fa
SimpleMonitor optionally displays user_monitor stats (#970)
* Adding with_user_monitor() to SimpleMonitor

* Satisfy clippy

* Satisfy fmt and pylibafl

* Fix leading whitespace
2022-12-26 11:20:30 +01:00
Dongjia "toka" Zhang
476cb7e7dc
Frida Makefile.toml fix (#969)
* frida build script fix

* fix

* Update build_and_test.yml

* Update build_and_test.yml

* Update build_and_test.yml

* Update build_and_test.yml

* Update build_and_test.yml

* Update build_and_test.yml

* Update build_and_test.yml

* Update build_and_test.yml

* Update build_and_test.yml
2022-12-26 14:19:37 +09:00
Dominik Maier
75f12bd0eb
Remodelling Observers/Examples that rely on UB, API cleanups (#950)
* Tackling UB

* PtrMut -> MutPtr, moved mapobservers to non-UB

* QEMU fixes

* test fixes

* qemu

* Change all interfaces, fix all fuzzers

* fixes

* fix more fixes

* fmt

* fix qemu sugar

* fix some qemus

* atheris

* fmt

* more fmt

* most fmt

* more fix

* nyx fyx

* fix qemu

* clippy, fixes

* more fixes

* no unfix, only fix

* fix

* fix

* more clippy

* fixes

* ListObserver

* fmt, clippy

* fix qemu on arm

* update zlib target

* fix?

* fix

* added migration guide

* ignore doc

* fix symcc

* fix new win fuzzer

* Fixes, rename PTR_SIZE to PTR_NUM

* Try fix linking on win

* Trying to fix win linking

* more cov

* trying to fix win some more

* trying to fix mac

* trying to fix mac

* Fix tests

* Fix tests

* trying to fix win

* more mac

* giving up for windows

* fmt

* python3

* mac?

* undo windows tests
2022-12-24 14:20:44 +01:00
Dominik Maier
3a1e499d9d
Documentation fixes (#967)
* a few stylistic/grammar changes

* expression

* some wording and a different git clone command

The original `git clone` command did not work for me (permission denied).

* small wording changes

* review

* typo

* neutral

Co-authored-by: hexcoder <hexcoder-@users.noreply.github.com>
2022-12-21 12:44:42 +01:00
humpty99
de6ee8b161
Fix Nyx build script (#965)
due to the call to pushd on line 23 not being directed at packer, the wrong commit was being used and so that resulted in the wrong init.cpio.gz being generated which hangs when trying to run the libxml2 examples however using the right commit (86b159bafc0b2ba8feeaa8761a45b6201d34084f) fixes this problem.
2022-12-21 20:29:42 +09:00
Dongjia "toka" Zhang
d77d9d5f31
Frida: Make stalker.exclude() configurable from command line arguments (#956)
* remove exclude on windows

* linux x86_64

* option
2022-12-21 11:23:57 +01:00
Max Ammann
4d8b566a87
[Windows] Add libfuzzer example for windows with ASAN (#934)
* Add libfuzzer example for window with ASAN

* Fix formatting

* Add link

* Fix cpp format

* Skip windows fuzzers

* Fix format

* Fix testing fuzzer

* Fix taks name

Co-authored-by: Dongjia "toka" Zhang <tokazerkje@outlook.com>
Co-authored-by: Andrea Fioraldi <andreafioraldi@gmail.com>
Co-authored-by: Dominik Maier <domenukk@gmail.com>
2022-12-21 10:41:58 +01:00
Dongjia "toka" Zhang
3c7dcac41d
Deduplicate crash handlers (#951)
* unix

* win

* std

* fmt

* more

* more

* win

* rename

* win

Co-authored-by: Dominik Maier <domenukk@gmail.com>
2022-12-21 10:41:18 +01:00
Dongjia "toka" Zhang
038732bd92
no mold (#964) 2022-12-21 13:27:14 +09:00
Dongjia "toka" Zhang
f1b25fed65
Fix CI (#955)
* fix

* fmt

* Update build_and_test.yml

* no nightly

* fix

* why

* Update build_and_test.yml

* a

* a

* ok

* linux only

* fmt

* Update build_and_test.yml

* fix
2022-12-21 11:12:54 +09:00
hexcoder
b0df0a26a1
Docs: grammar fix (#961) 2022-12-21 00:19:38 +01:00
Dominik Maier
7ed1ac9c9b
Additional SymCC Build Fixes (#954) 2022-12-20 00:37:19 +01:00
Dominik Maier
e56d5318e4
Fix SymCC build (#952) 2022-12-19 13:48:07 +01:00
Dominik Maier
ccf6cc708a
Windows clippy fixes (#948) 2022-12-18 12:35:30 +01:00
radl97
016a4c3778
Human readable execs & run/exec rounding fix (#936)
* Calculate run/exec statistics as float to solve rounding issues

* Fixup

* Clippy fixes

* Clippy fixes

* Change execs_per_sec() to return float per suggestions

* Monitors: Write 2 decimal floating-point for execs/sec

* Prettify exec/sec

* Formatting & fix copy pasta

* Pretty-print floats in monitor: use mega and kilo SI suffices

* prettify -> prettify_float, apply suggestion

* Clippy

* Fix prometheus client cannot handle float values yet

Co-authored-by: Andrea Fioraldi <andreafioraldi@gmail.com>
Co-authored-by: Dominik Maier <domenukk@gmail.com>
2022-12-16 23:46:33 +01:00
Sparrrgh
d04346c870
Add mips support for QemuTracerHelper (#941)
* Add mips support for QemuTracerHelper

* Formatting

Ran cargo +nightly fmt

* Removed unnecessary `any`

* Removed cfg guarding calls module

Co-authored-by: Andrea Fioraldi <andreafioraldi@gmail.com>
2022-12-14 17:45:54 +01:00
omergreen
664e87809e
libafl-frida: disable LibAFL's default features in Cargo.toml (#939)
* disable libafl's default features in libafl-frida

to allow users to disable default features while using stuff from libafl-frida

* Update Cargo.toml

Co-authored-by: Dominik Maier <domenukk@gmail.com>
2022-12-14 01:59:17 +01:00
Andrea Fioraldi
55e220f0e8
CI: diff with main and HEAD^ (#945) 2022-12-14 01:10:36 +01:00
Andrea Fioraldi
162de0ceaf
Fix CI diffing (#944)
* fix build_and_test_fuzzers to diff from origin/main

* fix fuzzbench_forkserver
2022-12-13 21:19:44 +01:00
Ao Li
9e4a0513c6
Gramatron: Fix a typo in gnf_converter.py (#942)
This patch addresses the issue in #879, which fixes a typo in the `remove_left_recursion` method.
2022-12-13 17:27:16 +01:00
Andrea Fioraldi
08be5f732e
CI: Only test fuzzers with diffing deps (#940)
* build and test fuzzer crate

* diffing fuzzers ci only

* clippy

* clippy merda

* clippy merde

* improve it

* comment

* split ubuntu CI workflow

* fix
2022-12-13 14:10:34 +01:00
292 changed files with 6483 additions and 2925 deletions

View File

@ -61,16 +61,12 @@ jobs:
with: with:
profile: minimal profile: minimal
toolchain: stable toolchain: stable
- name: set mold linker as default linker
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 llvm-dev clang ninja-build clang-format-13 shellcheck libgtk-3-dev gcc-arm-linux-gnueabi g++-arm-linux-gnueabi libslirp-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 && clang -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 --allow-downgrade run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade
- uses: actions/checkout@v3 - uses: actions/checkout@v3
@ -95,9 +91,35 @@ jobs:
- name: Test Docs - name: Test Docs
run: cargo +nightly test --doc --all-features run: cargo +nightly test --doc --all-features
# ---- build and feature check ---- # ---- build normal and examples ----
- name: Run a normal build - name: Run a normal build
run: cargo build --verbose run: cargo build --verbose
- name: Build examples
run: cargo build --examples --verbose
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
- name: Install and cache deps
uses: awalsh128/cache-apt-pkgs-action@v1.1.0
with:
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
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
run: rustup toolchain install nightly --allow-downgrade
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v2
# ---- build and feature check ----
# 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
@ -106,8 +128,6 @@ jobs:
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 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
@ -130,8 +150,6 @@ jobs:
with: with:
profile: minimal profile: minimal
toolchain: stable toolchain: stable
- name: set mold linker as default linker
uses: rui314/setup-mold@v1
- name: Install deps - name: Install deps
run: sudo apt-get install -y llvm llvm-dev clang ninja-build python3-dev python3-pip python3-venv run: sudo apt-get install -y llvm llvm-dev clang ninja-build python3-dev python3-pip python3-venv
- name: Install maturin - name: Install maturin
@ -139,7 +157,9 @@ jobs:
- 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: cd ./bindings/pylibafl && maturin build run: cd ./bindings/pylibafl && python3 -m venv .env && . .env/bin/activate && maturin develop && ./test.sh
- name: Run python test
run: . ./bindings/pylibafl/.env/bin/activate && cd ./fuzzers/baby_fuzzer && python3 baby_fuzzer.py | grep "Bye"
fuzzers: fuzzers:
strategy: strategy:
@ -151,24 +171,25 @@ jobs:
with: with:
profile: minimal profile: minimal
toolchain: stable toolchain: stable
- name: set mold linker as default linker
if: runner.os == 'Linux' # mold only support linux until now
uses: rui314/setup-mold@v1
- 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: Install python - name: Install cxxbridge
if: runner.os == 'macOS' if: runner.os == 'macOS'
run: brew install --force-bottle --overwrite python@3.11 run: cargo install cxxbridge-cmd
- name: Install python (macOS)
# Removing macOS things already installed in CI against failed linking
if: runner.os == 'macOS'
run: rm /usr/local/bin/2to3* /usr/local/bin/idle3* /usr/local/bin/pydoc3* /usr/local/bin/python3*; brew install --force-bottle --overwrite python
- uses: lyricwulf/abc@v1 - uses: lyricwulf/abc@v1
with: with:
# todo: remove afl++-clang when nyx support samcov_pcguard # todo: remove afl++-clang when nyx support samcov_pcguard
linux: llvm llvm-dev clang nasm ninja-build gcc-arm-linux-gnueabi g++-arm-linux-gnueabi libgtk-3-dev afl++-clang pax-utils linux: llvm llvm-dev clang nasm ninja-build gcc-arm-linux-gnueabi g++-arm-linux-gnueabi libgtk-3-dev afl++-clang pax-utils
# update bash for macos to support `declare -A` command` # update bash for macos to support `declare -A` command`
macos: llvm libpng nasm coreutils z3 bash macos: llvm libpng nasm coreutils z3 bash wget
- name: pip install - name: pip install
run: python3 -m pip install msgpack jinja2 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. # 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)"
@ -179,13 +200,14 @@ jobs:
- 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: Build and run example fuzzers (Linux) - name: Build and run example fuzzers (Linux)
if: runner.os == 'Linux' if: runner.os == 'Linux'
run: ./scripts/test_all_fuzzers.sh run: RUN_ON_CI=1 ./scripts/test_all_fuzzers.sh
- name: Build and run example fuzzers (macOS) - name: Build and run example fuzzers (macOS)
if: runner.os == 'macOS' # use bash v4 if: runner.os == 'macOS' # use bash v4
run: /usr/local/bin/bash ./scripts/test_all_fuzzers.sh run: /usr/local/bin/bash -c 'RUN_ON_CI=1 ./scripts/test_all_fuzzers.sh'
nostd-build: nostd-build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@ -238,10 +260,14 @@ 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/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
@ -254,6 +280,8 @@ jobs:
run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade run: rustup toolchain install nightly --component rustfmt --component clippy --allow-downgrade
- 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

View File

@ -16,6 +16,7 @@ members = [
"utils/deexit", "utils/deexit",
"utils/gramatron/construct_automata", "utils/gramatron/construct_automata",
"utils/libafl_benches", "utils/libafl_benches",
"utils/build_and_test_fuzzers",
] ]
default-members = [ default-members = [
"libafl", "libafl",
@ -32,7 +33,7 @@ exclude = [
] ]
[workspace.package] [workspace.package]
version = "0.8.2" version = "0.9.0"
[profile.release] [profile.release]
lto = true lto = true

View File

@ -1,6 +1,6 @@
# LibAFL, the fuzzer library. # LibAFL, the fuzzer library.
<img align="right" src="https://github.com/AFLplusplus/Website/raw/master/static/logo_256x256.png" alt="AFL++ Logo"> <img align="right" src="https://raw.githubusercontent.com/AFLplusplus/Website/main/static/libafl_logo.svg" alt="LibAFL logo" width="250" heigh="250">
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.

View File

@ -1,13 +1,13 @@
[package] [package]
name = "pylibafl" name = "pylibafl"
version = "0.8.2" version = "0.9.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
pyo3 = { version = "0.17", features = ["extension-module"] } pyo3 = { version = "0.17", features = ["extension-module"] }
libafl_qemu = { path = "../../libafl_qemu", version = "0.8.2", features = ["python"] } libafl_qemu = { path = "../../libafl_qemu", version = "0.9.0", features = ["python"] }
libafl_sugar = { path = "../../libafl_sugar", version = "0.8.2", features = ["python"] } libafl_sugar = { path = "../../libafl_sugar", version = "0.9.0", features = ["python"] }
libafl = { path = "../../libafl", version = "0.8.2", features = ["python"] } libafl = { path = "../../libafl", version = "0.9.0", features = ["python"] }
[build-dependencies] [build-dependencies]
pyo3-build-config = { version = "0.17" } pyo3-build-config = { version = "0.17" }

View File

@ -1,5 +1,8 @@
from pylibafl.libafl import * from pylibafl.libafl import *
import ctypes import ctypes
import platform
MAP_SIZE = 4096
class FooObserver(BaseObserver): class FooObserver(BaseObserver):
@ -33,11 +36,16 @@ class FooExecutor(BaseExecutor):
return (self.h)(input) return (self.h)(input)
libc = ctypes.cdll.LoadLibrary("libc.so.6") if platform.system() == "Darwin":
libc = ctypes.cdll.LoadLibrary("libc.dylib")
else:
libc = ctypes.cdll.LoadLibrary("libc.so.6")
area_ptr = libc.calloc(1, 4096) # Get a buffer to use for our map observer
libc.calloc.restype = ctypes.c_void_p
area_ptr = libc.calloc(1, MAP_SIZE)
observer = StdMapObserverI8("mymap", area_ptr, 4096) observer = StdMapObserverI8("mymap", area_ptr, MAP_SIZE)
m = observer.as_map_observer() m = observer.as_map_observer()
@ -69,7 +77,12 @@ 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
@ -91,4 +104,6 @@ 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)

11
bindings/pylibafl/test.sh Executable file
View File

@ -0,0 +1,11 @@
#!/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

View File

@ -1,7 +1,8 @@
# 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 attempts to describe concolic tracing from the ground up using an example. For those uninitiated, the following text 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.
@ -92,18 +93,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 similar to the previous example. These callbacks allow the runtime to construct a trace that is 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 solve any branches it comes across using [Z3](https://github.com/Z3Prover/z3/wiki) and * 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 [QSym](https://github.com/sslab-gatech/qsym)-based runtime, which does a bit more filtering on the expressions and also solves using Z3. * 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.
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.
Checkout out the `symcc_runtime` docs for more information on how to build your own runtime. Check out the `symcc_runtime` docs for more information on how to build your own runtime.
### SymQEMU ### SymQEMU
@ -123,7 +124,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 runtime ready before we can do instrumentation with SymCC. For example, we need to have a runtime ready before we can do instrumentation with SymCC.
### Building a Runtime ### Building a Runtime
@ -134,10 +135,12 @@ 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 a separate instrumented target with concolic tracing instrumentation and does not require source code. This avoids building a separate instrumented target with concolic tracing instrumentation and so 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.
@ -158,23 +161,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 let it know the path to your runtime by setting `--symcc-build` argument of the `configure` script to the path of your runtime. 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.
### 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 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 its 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 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 (set to 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 solved using an SMT-Solver. The `ConcolicMetadata` can be used to replay the concolic trace and to solve the conditions 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.

View File

@ -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.
For example in our `frida_libpng` example, we load the dynamic library and find the symbol to harness as follows: 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 @@ For example in our `frida_libpng` example, we load the dynamic library and find
## `FridaInstrumentationHelper` and Runtimes ## `FridaInstrumentationHelper` and Runtimes
To use functionalities that Frida offers, we'll first need to obtain `Gum` object by `Gum::obtain()`. To use functionalities that Frida offers, we'll first need to obtain a `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 instrumentation. 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.
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_ptr_mut()`. After setting up the `FridaInstrumentationHelper` you can obtain the pointer to the coverage map by calling `map_mut_ptr()`.
```rust,ignore ```rust,ignore
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
"edges", "edges",
frida_helper.map_ptr_mut().unwrap(), frida_helper.map_mut_ptr().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.

View File

@ -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. custom platforms like microcontrollers, kernels, hypervisors, and more. It is possible to use LibAFL in `no_std` environments e.g. on 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 input LibAFL needs for `no_std` is a monotonically increasing timestamp. The minimum amount of support LibAFL needs for a `no_std` environment 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

View File

@ -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. 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 type. 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 extension make all # this will not compile afl's additional extensions
``` ```
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 supported CPU 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 list of supported CPUs at <https://www.intel.com/content/www/us/en/support/articles/000056730/processors.html>.
## Preparing Nyx working directory ## Preparing the 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). 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. 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.
First, to create `Nyxhelper`: First, to create `Nyxhelper`:
@ -57,22 +57,21 @@ 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 the 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 need to 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 trace_bits = unsafe { std::slice::from_raw_parts_mut(helper.trace_bits, helper.map_size) }; let observer = unsafe { StdMapObserver::from_mut_ptr("trace", 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 as normal and pass them into `fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)` to start fuzzing. Finally, use them normally 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). First you 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) you first 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`:
@ -91,7 +90,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 master instance, there is only one master instance, other instances will be treated as slaved 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
) )
.unwrap(); .unwrap();
``` ```
@ -99,13 +98,11 @@ 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 trace_bits = let observer = unsafe { StdMapObserver::from_mut_ptr("trace", helper.trace_bits, helper.map_size) }
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 normal to start fuzzing: Finally, open a `Launcher` as usual to start fuzzing:
```rust,ignore ```rust,ignore
match Launcher::builder() match Launcher::builder()

View File

@ -105,8 +105,8 @@ fn main(){
## 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 is evolved during the fuzzing process. 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.
Includes all State, such as the Corpus of inputs, the current RNG state, and potential Metadata for the testcases and run. It 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,ignore
@ -129,8 +129,8 @@ let mut state = StdState::new(
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`.
- 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 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.
- last two parameters are feedback and objective, we will discuss them later. - The 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.
@ -225,7 +225,7 @@ 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 `singals_set` in our harness: As we don't rely on any instrumentation engine, we have to manually track the satisfied conditions by `signals_set` in our harness:
```rust ```rust
extern crate libafl; extern crate libafl;
@ -287,7 +287,7 @@ 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 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. **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.
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:
@ -356,7 +356,7 @@ fuzzer
`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.
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. 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.
```text ```text
$ cargo run $ cargo run

View File

@ -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 barew 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 bare metal|

View File

@ -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 tested program 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 program under test 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. 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.
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.

View File

@ -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 install 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 installs 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. 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. 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.
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.

View File

@ -11,16 +11,16 @@ 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) and the [`FeedbackState`](https://docs.rs/libafl/0/libafl/feedbacks/trait.FeedbackState.html) traits. 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.
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. 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 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.
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). 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).
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. 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.
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 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. 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.

View File

@ -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 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. 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.
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 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). 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).

View File

@ -1,9 +1,9 @@
# Mutator # Mutator
The Mutator is an entity that takes one or more Inputs and generates a new derived one. The Mutator is an entity that takes one or more Inputs and generates a new instance of Input derived by its inputs.
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 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. 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.
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.

View File

@ -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 be the time spent executing a run, the program output, or 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 collect the time spent executing a run, the program output, or a more advanced observation, like maximum stack depth at runtime.
This information is not preserved across runs, and it is an observation of a dynamic property of the program. This information 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.

View File

@ -1,8 +1,8 @@
# Stage # Stage
A Stage is an entity that operates on a single Input got from the Corpus. A Stage is an entity that operates on a single Input received 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 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. 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.
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.

View File

@ -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 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. 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.
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).

View File

@ -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)` that is a proc-macro in `libafl_derive` the user can use `libafl::impl_serdeany!(MyMetadata);`. As an alternative to `derive(SerdeAny)` which is a proc-macro in `libafl_derive` the user can use `libafl::impl_serdeany!(MyMetadata);`.
## Usage ## Usage

View File

@ -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 defined a generic for the input type, the state type, or the generic type, as these is no longer necessary to explicitly define 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, Observers, and State generics have been moved into traits with associated types (namely, In many scenarios, Input, Observer, 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` and `Corpus` no longer has a generic for After 0.9, all `Corpus` implementations are required to implement `UsesInput`. Also `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,3 +160,26 @@ 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`.

View File

@ -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 needed to add it to fuzzing at a decent speed. Note that the `--release` flag is optional for development, but you need to add it to do 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.

View File

@ -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 its project. For LibAFL, each crate has its self-contained purpose, and the user may not need to use all of them in their 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)
@ -52,13 +52,13 @@ 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 wrap compilers and create source-level fuzzers. This is a library that provides utils to 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.

View File

@ -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 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. 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.
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 git@github.com:AFLplusplus/LibAFL.git $ git clone https://github.com/AFLplusplus/LibAFL.git
``` ```
You can alternatively, on a UNIX-like machine, download a compressed archive and extract it with: Alternatively, on a UNIX-like machine, you can 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 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 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.
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,

View File

@ -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 design does not treat extensibility as a first-class citizen. Their designs do 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 can not just be combined for new projects. Their outstanding features cannot 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,7 +24,7 @@ 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-skool fuzzers, a `BytesInput` is just one of the potential forms of inputs: To give an example, as opposed to old-school 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.

View File

@ -5,7 +5,7 @@
*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 into the library. This book shall be a gentle introduction to 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.

View File

@ -1,6 +1,6 @@
# Message Passing # Message Passing
LibAFL offers a standard mechanism for message passing over processes and machines with a low overhead. LibAFL offers a standard mechanism for message passing between 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 an `OnDiskCorpus`. Depending on individual needs, LibAFL can also write testcase contents to disk, while still using events to notify other fuzzers, using an `OnDiskCorpus`.
@ -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 checks all incoming client maps periodically and then forwards new messages to its outgoing broadcast-`ShMem`, mapped by all connected clients. It periodically checks all incoming client maps 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, 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`. 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`.
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 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 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.
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 like this over the outgoing broadcast `Shmem`: So the outgoing messages flow is like this over the outgoing broadcast `Shmem`:
```text ```text
[broker] [broker]

View File

@ -8,14 +8,14 @@ The straightforward way to do Multi-Threading is to use the `LlmpRestartingEvent
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, itself binding to the port to await new clients. 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 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 operating systems as optimization and only actually restarts from scratch on Windows. While it's called "restarting" manager, it uses `fork` on Unix-like 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 operating systems
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 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 an 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,12 +42,12 @@ 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.
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 but one. 2. To use multiple launchers for individual configurations, you can set `spawn_broker` to `false` on all instances 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.
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).

View File

@ -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 in writing extensions to LibAFL like Feedbacks and Testcase's metadata. This tutorial will introduce you to writing extensions to LibAFL like Feedbacks and Testcase's metadata.

View File

@ -1,6 +1,6 @@
[package] [package]
name = "baby_fuzzer" name = "baby_fuzzer"
version = "0.7.1" version = "0.9.0"
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"

View File

@ -4,67 +4,84 @@ 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_from_owned(map_observer) return libafl.MapObserverI32.new_owned(map_observer)
def executor_wrapper(executor): def executor_wrapper(executor):
if type(executor).__name__ == "OwnedInProcessExecutorI32": if type(executor).__name__ == "InProcessExecutor":
return libafl.ExecutorI32.new_from_inprocess(executor) return libafl.Executor.new_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):
if type(monitor).__name__ == "SimpleMonitor": return monitor.as_monitor()
return libafl.Monitor.new_from_simple(monitor)
def event_manager_wrapper(event_manager): def event_manager_wrapper(event_manager):
if type(event_manager).__name__ == "SimpleEventManager": return event_manager.as_manager()
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_from_in_memory(corpus) return libafl.Corpus.new_in_memory(corpus)
if type(corpus).__name__ == "OnDiskCorpus": if type(corpus).__name__ == "OnDiskCorpus":
return libafl.Corpus.new_from_on_disk(corpus) return libafl.Corpus.new_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_from_std(rand) return libafl.Rand.new_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__ == "StdScheduledHavocMutationsStageI32": if type(stage).__name__ == "StdMutationalStage":
return libafl.StageI32.new_from_std_scheduled(stage) return libafl.Stage.new_std_mutational(stage)
# CODE WRITTEN BY USER # CODE WRITTEN BY USER
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)
feedback_state = libafl.MapFeedbackStateI32.with_observer(map_observer_wrapper(map_observer)) def harness(inp):
#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(feedback_state, map_observer_wrapper(map_observer)) feedback = libafl.MaxMapFeedbackI32(map_observer_wrapper(map_observer))
objective = libafl.CrashFeedback()
state = libafl.StdStateI32( state = libafl.StdState(
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_state feedback.as_feedback(),
objective.as_feedback(),
) )
monitor = libafl.SimpleMonitor() monitor = libafl.SimpleMonitor(lambda x: print(x))
mgr = libafl.SimpleEventManager(monitor_wrapper(monitor)) mgr = libafl.SimpleEventManager(monitor_wrapper(monitor))
fuzzer = libafl.StdFuzzerI32(feedback) fuzzer = libafl.StdFuzzer(feedback.as_feedback(), objective.as_feedback())
executor = libafl.OwnedInProcessExecutorI32(harness, map_observer_wrapper(map_observer), fuzzer, state, event_manager_wrapper(mgr)) observers = libafl.ObserversTuple([libafl.Observer.new_map_i32(map_observer_wrapper(map_observer))])
generator = libafl.RandPrintablesGeneratorI32(32) executor = libafl.InProcessExecutor(harness, observers, fuzzer, state, event_manager_wrapper(mgr))
state.generate_initial_inputs(fuzzer, executor_wrapper(executor), generator, event_manager_wrapper(mgr), 8) generator = libafl.RandPrintablesGenerator(32)
stage = libafl.StdScheduledHavocMutationsStageI32.new_from_scheduled_havoc_mutations() state.generate_initial_inputs(fuzzer, executor_wrapper(executor), generator_wrapper(generator), event_manager_wrapper(mgr), 3)
stage_tuple_list = libafl.StagesOwnedListI32(stage_wrapper(stage)) mutator = libafl.StdHavocMutator()
fuzzer.fuzz_loop(executor_wrapper(executor), state, event_manager_wrapper(mgr), stage_tuple_list) stage = libafl.StdMutationalStage(mutator_wrapper(mutator))
stages = libafl.StagesTuple([stage_wrapper(stage)])
fuzzer.fuzz_loop(executor_wrapper(executor), state, event_manager_wrapper(mgr), stages)

View File

@ -30,7 +30,7 @@ fn signals_set(idx: usize) {
unsafe { SIGNALS[idx] = 1 }; unsafe { SIGNALS[idx] = 1 };
} }
#[allow(clippy::similar_names)] #[allow(clippy::similar_names, clippy::manual_assert)]
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 +61,7 @@ pub fn main() {
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = let observer =
unsafe { StdMapObserver::new_from_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) }; unsafe { StdMapObserver::from_mut_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,7 +88,7 @@ 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 mon = TuiMonitor::new(String::from("Baby Fuzzer"), false); let mon = TuiMonitor::new(String::from("Baby Fuzzer"), false);

View File

@ -1,6 +1,6 @@
[package] [package]
name = "baby_fuzzer_gramatron" name = "baby_fuzzer_gramatron"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -57,7 +57,7 @@ pub fn main() {
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); let observer = unsafe { StdMapObserver::new("signals", &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);
@ -83,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

View File

@ -1,6 +1,6 @@
[package] [package]
name = "baby_fuzzer_grimoire" name = "baby_fuzzer_grimoire"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -9,7 +9,7 @@ use libafl::{
executors::{inprocess::InProcessExecutor, ExitKind}, executors::{inprocess::InProcessExecutor, ExitKind},
feedbacks::{CrashFeedback, MaxMapFeedback}, feedbacks::{CrashFeedback, MaxMapFeedback},
fuzzer::{Evaluator, Fuzzer, StdFuzzer}, fuzzer::{Evaluator, Fuzzer, StdFuzzer},
inputs::{GeneralizedInput, HasTargetBytes}, inputs::{BytesInput, HasTargetBytes},
monitors::SimpleMonitor, monitors::SimpleMonitor,
mutators::{ mutators::{
havoc_mutations, scheduled::StdScheduledMutator, GrimoireExtensionMutator, havoc_mutations, scheduled::StdScheduledMutator, GrimoireExtensionMutator,
@ -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 = GeneralizedInput::new(buffer); let input = BytesInput::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: &GeneralizedInput| { let mut harness = |input: &BytesInput| {
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,18 +77,12 @@ 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 = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) };
// Feedback to rate the interestingness of an input // Feedback to rate the interestingness of an input
let mut feedback = MaxMapFeedback::new_tracking(&observer, false, true); let mut feedback = MaxMapFeedback::new_tracking(&observer, false, true);
@ -118,7 +112,7 @@ pub fn main() {
} }
// 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
@ -158,7 +152,7 @@ pub fn main() {
let mut stages = tuple_list!( let mut stages = tuple_list!(
generalization, generalization,
StdMutationalStage::new(mutator), StdMutationalStage::new(mutator),
StdMutationalStage::new(grimoire_mutator) StdMutationalStage::transforming(grimoire_mutator)
); );
for input in initial_inputs { for input in initial_inputs {

View File

@ -1,6 +1,6 @@
[package] [package]
name = "baby_fuzzer_minimizing" name = "baby_fuzzer_minimizing"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -33,7 +33,7 @@ pub fn main() -> Result<(), Error> {
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = let observer =
unsafe { StdMapObserver::new_from_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) }; unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) };
let factory = MapEqualityFactory::new_from_observer(&observer); let factory = MapEqualityFactory::new_from_observer(&observer);
@ -44,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);
@ -116,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);
@ -136,7 +136,13 @@ 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(&mut fuzzer, &mut executor, &mut state, &mut mgr, 0)?; stages.perform_all(
&mut fuzzer,
&mut executor,
&mut state,
&mut mgr,
CorpusId::from(0_usize),
)?;
Ok(()) Ok(())
} }

View File

@ -1,8 +1,8 @@
[package] [package]
name = "baby_fuzzer_nautilus" name = "baby_fuzzer_nautilus"
version = "0.8.2" version = "0.9.0"
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"] authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
edition = "2018" edition = "2021"
[features] [features]
default = ["std"] default = ["std"]

View File

@ -46,7 +46,7 @@ pub fn main() {
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); let observer = unsafe { StdMapObserver::new("signals", &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!(
@ -79,7 +79,7 @@ pub fn main() {
} }
// 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

View File

@ -1,6 +1,6 @@
[package] [package]
name = "baby_fuzzer_swap_differential" name = "baby_fuzzer_swap_differential"
version = "0.7.1" version = "0.9.0"
authors = ["Addison Crump <research@addisoncrump.info>"] authors = ["Addison Crump <research@addisoncrump.info>"]
edition = "2021" edition = "2021"
default-run = "fuzzer_sd" default-run = "fuzzer_sd"

View File

@ -27,9 +27,7 @@ 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")
@ -38,6 +36,8 @@ 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.");
} }
} }

View File

@ -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 {:?} to end with c or cxx", dir), _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"),
}; };
dir.pop(); dir.pop();

View File

@ -32,10 +32,11 @@ 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"));
} }
@ -45,23 +46,26 @@ use bindings::{inspect_first, inspect_second};
mod multimap { mod multimap {
pub use libafl::observers::{HitcountsIterableMapObserver, MultiMapObserver}; pub use libafl::observers::{HitcountsIterableMapObserver, MultiMapObserver};
pub static mut FIRST_EDGES: &'static mut [u8] = &mut []; pub static mut FIRST_EDGES: &mut [u8] = &mut [];
pub static mut SECOND_EDGES: &'static mut [u8] = &mut []; pub static mut SECOND_EDGES: &mut [u8] = &mut [];
pub static mut COMBINED_EDGES: [&'static mut [u8]; 2] = [&mut [], &mut []]; pub static mut COMBINED_EDGES: [&mut [u8]; 2] = [&mut [], &mut []];
} }
#[cfg(feature = "multimap")] #[cfg(feature = "multimap")]
use multimap::*; use multimap::{
HitcountsIterableMapObserver, MultiMapObserver, COMBINED_EDGES, FIRST_EDGES, SECOND_EDGES,
};
#[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: &'static mut [u8] = &mut []; pub static mut EDGES: &mut [u8] = &mut [];
} }
#[cfg(not(feature = "multimap"))] #[cfg(not(feature = "multimap"))]
use slicemap::*; use slicemap::{HitcountsMapObserver, EDGES};
#[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| {
@ -94,8 +98,8 @@ pub fn main() {
} }
// 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 = StdMapObserver::new("first-edges", unsafe { FIRST_EDGES }); let mut first_map_observer = unsafe { StdMapObserver::new("first-edges", FIRST_EDGES) };
let mut second_map_observer = StdMapObserver::new("second-edges", unsafe { SECOND_EDGES }); let mut second_map_observer = unsafe { StdMapObserver::new("second-edges", SECOND_EDGES) };
// 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 =
@ -104,10 +108,13 @@ pub fn main() {
// create a combined map observer, e.g. for calibration // create a combined map observer, e.g. for calibration
// we use MultiMapObserver::differential to indicate that we want to use the observer in // we use MultiMapObserver::differential to indicate that we want to use the observer in
// differential mode // differential mode
let map_observer = HitcountsIterableMapObserver::new(MultiMapObserver::differential( let map_observer = unsafe {
HitcountsIterableMapObserver::new(MultiMapObserver::differential(
"combined-edges", "combined-edges",
unsafe { &mut COMBINED_EDGES }, &mut COMBINED_EDGES,
)); ))
};
( (
first_map_observer, first_map_observer,
second_map_observer, second_map_observer,
@ -124,10 +131,16 @@ pub fn main() {
} }
// 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::new("first-edges", unsafe { &mut EDGES[..MAX_EDGES_NUM] }); StdMapObserver::from_mut_ptr("first-edges", EDGES.as_mut_ptr(), MAX_EDGES_NUM)
let mut second_map_observer = };
StdMapObserver::new("second-edges", unsafe { &mut EDGES[MAX_EDGES_NUM..] }); let mut second_map_observer = unsafe {
StdMapObserver::from_mut_ptr(
"second-edges",
EDGES.as_mut_ptr().add(MAX_EDGES_NUM),
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 =
@ -136,10 +149,14 @@ 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 = let map_observer = unsafe {
HitcountsMapObserver::new(StdMapObserver::differential("combined-edges", unsafe { HitcountsMapObserver::new(StdMapObserver::differential_from_mut_ptr(
EDGES "combined-edges",
})); EDGES.as_mut_ptr(),
MAX_EDGES_NUM * 2,
))
};
( (
first_map_observer, first_map_observer,
second_map_observer, second_map_observer,
@ -174,7 +191,7 @@ 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 mon = TuiMonitor::new(String::from("Baby Fuzzer"), false); let mon = TuiMonitor::new(String::from("Baby Fuzzer"), false);

View File

@ -1,6 +1,6 @@
[package] [package]
name = "baby_fuzzer_tokens" name = "baby_fuzzer_tokens"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -65,7 +65,8 @@ pub fn main() {
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); let observer =
unsafe { StdMapObserver::from_mut_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);
@ -91,7 +92,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

View File

@ -1,6 +1,6 @@
[package] [package]
name = "baby_fuzzer_with_forkexecutor" name = "baby_fuzzer_with_forkexecutor"
version = "0.6.1" version = "0.9.0"
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"

View File

@ -64,7 +64,7 @@ pub fn main() {
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = StdMapObserver::new("signals", signals_clone.as_mut_slice()); let observer = unsafe { StdMapObserver::new("signals", signals_clone.as_mut_slice()) };
// Create a stacktrace observer to add the observers tuple // Create a stacktrace observer to add the observers tuple
// Feedback to rate the interestingness of an input, obtained by ANDing the interestingness of both feedbacks // Feedback to rate the interestingness of an input, obtained by ANDing the interestingness of both feedbacks
@ -91,7 +91,7 @@ pub fn main() {
.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}"));
// 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

View File

@ -1,6 +1,6 @@
[package] [package]
name = "baby_no_std" name = "baby_no_std"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -87,7 +87,7 @@ pub extern "C" fn main(_argc: isize, _argv: *const *const u8) -> isize {
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); let observer = unsafe { StdMapObserver::new("signals", &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);

View File

@ -45,7 +45,7 @@ pub fn main() {
libafl::executors::ExitKind::Ok libafl::executors::ExitKind::Ok
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = unsafe { ConstMapObserver::<u8, 3>::new_from_ptr("signals", map_ptr) }; let observer = unsafe { ConstMapObserver::<u8, 3>::from_mut_ptr("signals", map_ptr) };
// Create a stacktrace observer // Create a stacktrace observer
let mut bt = shmem_provider.new_shmem_object::<Option<u64>>().unwrap(); let mut bt = shmem_provider.new_shmem_object::<Option<u64>>().unwrap();
let bt_observer = BacktraceObserver::new( let bt_observer = BacktraceObserver::new(
@ -78,7 +78,7 @@ pub fn main() {
.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}"));
// 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

View File

@ -35,7 +35,7 @@ pub fn main() {
libafl::executors::ExitKind::Ok libafl::executors::ExitKind::Ok
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = unsafe { ConstMapObserver::<u8, 3>::new_from_ptr("signals", array_ptr) }; let observer = unsafe { ConstMapObserver::<u8, 3>::from_mut_ptr("signals", array_ptr) };
// Create a stacktrace observer // Create a stacktrace observer
let mut bt = None; let mut bt = None;
let bt_observer = BacktraceObserver::new( let bt_observer = BacktraceObserver::new(
@ -68,7 +68,7 @@ pub fn main() {
.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}"));
// 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

View File

@ -38,7 +38,7 @@ pub fn main() {
let shmem_id = signals.id(); let shmem_id = signals.id();
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = StdMapObserver::new("signals", signals.as_mut_slice()); let observer = unsafe { StdMapObserver::new("signals", signals.as_mut_slice()) };
// Create a stacktrace observer // Create a stacktrace observer
let bt_observer = AsanBacktraceObserver::new("AsanBacktraceObserver"); let bt_observer = AsanBacktraceObserver::new("AsanBacktraceObserver");
@ -67,7 +67,7 @@ pub fn main() {
.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}"));
// 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

View File

@ -78,7 +78,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

View File

@ -65,7 +65,7 @@ pub fn main() {
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = StdMapObserver::new("signals", signals_clone.as_mut_slice()); let observer = unsafe { StdMapObserver::new("signals", signals_clone.as_mut_slice()) };
// Create a stacktrace observer // Create a stacktrace observer
let bt_observer = BacktraceObserver::new( let bt_observer = BacktraceObserver::new(
"BacktraceObserver", "BacktraceObserver",
@ -97,7 +97,7 @@ pub fn main() {
.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}"));
// 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

View File

@ -58,7 +58,7 @@ pub fn main() {
}; };
// Create an observation channel using the signals map // Create an observation channel using the signals map
let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) };
// Create a stacktrace observer to add the observers tuple // Create a stacktrace observer to add the observers tuple
let mut bt = None; let mut bt = None;
let bt_observer = BacktraceObserver::new( let bt_observer = BacktraceObserver::new(
@ -91,7 +91,7 @@ pub fn main() {
.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}"));
// 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

View File

@ -0,0 +1,32 @@
[package]
name = "forkserver_libafl_cc"
version = "0.8.2"
authors = ["ergrelet <ergrelet@users.noreply.github.com>"]
edition = "2021"
[features]
default = ["std"]
std = []
# Forces a crash
crash = []
[profile.release]
lto = true
codegen-units = 1
opt-level = 3
debug = true
[build-dependencies]
cc = { version = "1.0", features = ["parallel"] }
which = { version = "4.0.2" }
[dependencies]
libafl = { path = "../../libafl/", features = ["default"] }
clap = { version = "4.0", features = ["derive"] }
nix = "0.25"
libafl_targets = { path = "../../libafl_targets/" }
libafl_cc = { path = "../../libafl_cc/" }
[lib]
name = "libforkserver_libafl_cc"
crate-type = ["staticlib"]

View File

@ -0,0 +1,115 @@
# Variables
[env]
FUZZER_NAME='fuzzer_libafl_cc'
CARGO_TARGET_DIR = { value = "${PROJECT_DIR}/target", condition = { env_not_set = ["CARGO_TARGET_DIR"] } }
LIBAFL_CC = '${CARGO_TARGET_DIR}/release/libafl_cc'
LIBAFL_CXX = '${CARGO_TARGET_DIR}/release/libafl_cxx'
FUZZER = '${CARGO_TARGET_DIR}/release/${FUZZER_NAME}'
PROJECT_DIR = { script = ["pwd"] }
[tasks.unsupported]
script_runner="@shell"
script='''
echo "Cargo-make not integrated yet on this"
'''
# Compilers
[tasks.cxx]
linux_alias = "cxx_unix"
mac_alias = "cxx_unix"
windows_alias = "unsupported"
[tasks.cxx_unix]
command = "cargo"
args = ["build" , "--release"]
[tasks.cc]
linux_alias = "cc_unix"
mac_alias = "cc_unix"
windows_alias = "unsupported"
[tasks.cc_unix]
command = "cargo"
args = ["build" , "--release"]
[tasks.crash_cxx]
linux_alias = "crash_cxx_unix"
mac_alias = "crash_cxx_unix"
windows_alias = "unsupported"
[tasks.crash_cxx_unix]
command = "cargo"
args = ["build" , "--release", "--features=crash"]
[tasks.crash_cc]
linux_alias = "crash_cc_unix"
mac_alias = "crash_cc_unix"
windows_alias = "unsupported"
[tasks.crash_cc_unix]
command = "cargo"
args = ["build" , "--release", "--features=crash"]
# Harness
[tasks.fuzzer]
linux_alias = "fuzzer_unix"
mac_alias = "fuzzer_unix"
windows_alias = "unsupported"
[tasks.fuzzer_unix]
command = "${CARGO_TARGET_DIR}/release/libafl_cc"
args = ["${PROJECT_DIR}/src/program.c", "-o", "${FUZZER_NAME}", "-lm"]
dependencies = [ "cxx", "cc" ]
# Crashing Harness
[tasks.fuzzer_crash]
linux_alias = "fuzzer_crash_unix"
mac_alias = "fuzzer_crash_unix"
windows_alias = "unsupported"
[tasks.fuzzer_crash_unix]
command = "${CARGO_TARGET_DIR}/release/libafl_cc"
args = ["${PROJECT_DIR}/src/program.c", "-o", "${FUZZER_NAME}_crash", "-lm"]
dependencies = [ "crash_cxx", "crash_cc" ]
# Run the fuzzer
[tasks.run]
linux_alias = "run_unix"
mac_alias = "run_unix"
windows_alias = "unsupported"
[tasks.run_unix]
script_runner = "@shell"
script='''
taskset -c 1 ${CARGO_TARGET_DIR}/release/${CARGO_MAKE_PROJECT_NAME} ./${FUZZER_NAME} ./corpus/ -t 1000
'''
dependencies = [ "fuzzer" ]
# Run the fuzzer with a crash
[tasks.crash]
linux_alias = "crash_unix"
mac_alias = "crash_unix"
windows_alias = "unsupported"
[tasks.crash_unix]
script_runner = "@shell"
script='''
taskset -c 1 ${CARGO_TARGET_DIR}/release/${CARGO_MAKE_PROJECT_NAME} ./${FUZZER_NAME}_crash ./corpus/ -t 1000
'''
dependencies = [ "fuzzer_crash" ]
# Clean up
[tasks.clean]
linux_alias = "clean_unix"
mac_alias = "clean_unix"
windows_alias = "unsupported"
[tasks.clean_unix]
# Disable default `clean` definition
clear = true
script_runner="@shell"
script='''
rm -f ./${FUZZER_NAME}
cargo clean
'''

View File

@ -0,0 +1,13 @@
# Simple Forkserver Fuzzer
This is a simple example fuzzer to fuzz an executable instrumented by libafl_cc.
## Usage
You can build this example by running `cargo make fuzzer`.
This compiles, libafl_cc, the fuzzer and the example harness program in
`src/program.c` with libafl_cc.
## Run
You can run this example by running `cargo make run`.

View File

@ -0,0 +1 @@
aaa

View File

@ -0,0 +1,45 @@
use std::env;
use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses};
pub fn main() {
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
let mut dir = env::current_exe().unwrap();
let wrapper_name = dir.file_name().unwrap().to_str().unwrap();
let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() {
"cc" => false,
"++" | "pp" | "xx" => true,
_ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"),
};
dir.pop();
let mut cc = ClangWrapper::new();
if let Some(code) = cc
.cpp(is_cpp)
// silence the compiler wrapper output, needed for some configure scripts.
.silence(true)
.parse_args(&args)
.expect("Failed to parse the command line")
// Enable libafl's coverage instrumentation
.add_pass(LLVMPasses::AFLCoverage)
.add_arg("-mllvm")
.add_arg("-ctx") // Context sensitive coverage
// Imitate afl-cc's compile definitions
.add_arg("-D__AFL_FUZZ_INIT()=int __afl_sharedmem_fuzzing = 1;extern unsigned int *__afl_fuzz_len;extern unsigned char *__afl_fuzz_ptr;unsigned char __afl_fuzz_alt[1048576];unsigned char *__afl_fuzz_alt_ptr = __afl_fuzz_alt;void libafl_start_forkserver(void)")
.add_arg("-D__AFL_FUZZ_TESTCASE_BUF=(__afl_fuzz_ptr ? __afl_fuzz_ptr : __afl_fuzz_alt_ptr)")
.add_arg("-D__AFL_FUZZ_TESTCASE_LEN=(__afl_fuzz_ptr ? *__afl_fuzz_len : (*__afl_fuzz_len = read(0, __afl_fuzz_alt_ptr, 1048576)) == 0xffffffff ? 0 : *__afl_fuzz_len)")
.add_arg("-D__AFL_INIT()=libafl_start_forkserver()")
// Link with libafl's forkserver implementation
.link_staticlib(&dir, "libforkserver_libafl_cc")
.run()
.expect("Failed to run the wrapped compiler")
{
std::process::exit(code);
}
} else {
panic!("LibAFL CC: No Arguments given");
}
}

View File

@ -0,0 +1,5 @@
pub mod libafl_cc;
fn main() {
libafl_cc::main();
}

View File

@ -0,0 +1,9 @@
use libafl_targets::{map_shared_memory, start_forkserver};
#[no_mangle]
pub fn libafl_start_forkserver() {
// Map shared memory region for the edge coverage map
map_shared_memory();
// Start the forkserver
start_forkserver();
}

View File

@ -0,0 +1,215 @@
use core::time::Duration;
use std::path::PathBuf;
use clap::{self, Parser};
use libafl::{
bolts::{
current_nanos,
rands::StdRand,
shmem::{ShMem, ShMemProvider, UnixShMemProvider},
tuples::{tuple_list, MatchName, Merge},
AsMutSlice,
},
corpus::{Corpus, InMemoryCorpus, OnDiskCorpus},
events::SimpleEventManager,
executors::{
forkserver::{ForkserverExecutor, TimeoutForkserverExecutor},
HasObservers,
},
feedback_and_fast, feedback_or,
feedbacks::{CrashFeedback, MaxMapFeedback, TimeFeedback},
fuzzer::{Fuzzer, StdFuzzer},
inputs::BytesInput,
monitors::SimpleMonitor,
mutators::{scheduled::havoc_mutations, tokens_mutations, StdScheduledMutator, Tokens},
observers::{HitcountsMapObserver, MapObserver, StdMapObserver, TimeObserver},
schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler},
stages::mutational::StdMutationalStage,
state::{HasCorpus, HasMetadata, StdState},
};
use nix::sys::signal::Signal;
/// The commandline args this fuzzer accepts
#[derive(Debug, Parser)]
#[command(
name = "forkserver_libafl_cc",
about = "This is a simple example fuzzer to fuzz a executable instrumented by libafl_cc.",
author = "ergrelet <ergrelet@users.noreply.github.com>"
)]
struct Opt {
#[arg(
help = "The instrumented binary we want to fuzz",
name = "EXEC",
required = true
)]
executable: String,
#[arg(
help = "The directory to read initial inputs from ('seeds')",
name = "INPUT_DIR",
required = true
)]
in_dir: PathBuf,
#[arg(
help = "Timeout for each individual execution, in milliseconds",
short = 't',
long = "timeout",
default_value = "1200"
)]
timeout: u64,
#[arg(
help = "If not set, the child's stdout and stderror will be redirected to /dev/null",
short = 'd',
long = "debug-child",
default_value = "false"
)]
debug_child: bool,
#[arg(
help = "Arguments passed to the target",
name = "arguments",
num_args(1..),
allow_hyphen_values = true,
)]
arguments: Vec<String>,
#[arg(
help = "Signal used to stop child",
short = 's',
long = "signal",
value_parser = str::parse::<Signal>,
default_value = "SIGKILL"
)]
signal: Signal,
}
#[allow(clippy::similar_names)]
pub fn main() {
const MAP_SIZE: usize = 65536;
let opt = Opt::parse();
let corpus_dirs: Vec<PathBuf> = [opt.in_dir].to_vec();
// The unix shmem provider supported by LibAFL for shared memory
let mut shmem_provider = UnixShMemProvider::new().unwrap();
// The coverage map shared between observer and executor
let mut shmem = shmem_provider.new_shmem(MAP_SIZE).unwrap();
// let the forkserver know the shmid
shmem.write_to_env("__AFL_SHM_ID").unwrap();
let shmem_buf = shmem.as_mut_slice();
// Create an observation channel using the signals map
let edges_observer =
unsafe { HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)) };
// Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time");
// Feedback to rate the interestingness of an input
// This one is composed by two Feedbacks in OR
let mut feedback = feedback_or!(
// New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state
TimeFeedback::with_observer(&time_observer)
);
// A feedback to choose if an input is a solution or not
// We want to do the same crash deduplication that AFL does
let mut objective = feedback_and_fast!(
// Must be a crash
CrashFeedback::new(),
// Take it onlt if trigger new coverage over crashes
MaxMapFeedback::new(&edges_observer)
);
// 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::<BytesInput>::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(),
// States of the feedbacks.
// The feedbacks can report the data that should persist in the State.
&mut feedback,
// Same for objective feedbacks
&mut objective,
)
.unwrap();
// The Monitor trait define how the fuzzer stats are reported to the user
let monitor = 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(monitor);
// A minimization+queue policy to get testcasess from the corpus
let scheduler = IndexesLenTimeMinimizerScheduler::new(QueueScheduler::new());
// A fuzzer with feedbacks and a corpus scheduler
let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);
// If we should debug the child
let debug_child = opt.debug_child;
// Create the executor for the forkserver
let args = opt.arguments;
let mut tokens = Tokens::new();
let mut forkserver = ForkserverExecutor::builder()
.program(opt.executable)
.debug_child(debug_child)
.shmem_provider(&mut shmem_provider)
.autotokens(&mut tokens)
.parse_afl_cmdline(args)
.coverage_map_size(MAP_SIZE)
.build(tuple_list!(time_observer, edges_observer))
.unwrap();
if let Some(dynamic_map_size) = forkserver.coverage_map_size() {
forkserver
.observers_mut()
.match_name_mut::<HitcountsMapObserver<StdMapObserver<'_, u8, false>>>("shared_mem")
.unwrap()
.downsize_map(dynamic_map_size);
}
let mut executor = TimeoutForkserverExecutor::with_signal(
forkserver,
Duration::from_millis(opt.timeout),
opt.signal,
)
.expect("Failed to create the executor.");
// In case the corpus is empty (on first run), reset
if state.corpus().count() < 1 {
state
.load_initial_inputs(&mut fuzzer, &mut executor, &mut mgr, &corpus_dirs)
.unwrap_or_else(|err| {
panic!(
"Failed to load initial corpus at {:?}: {:?}",
&corpus_dirs, err
)
});
println!("We imported {} inputs from disk.", state.corpus().count());
}
state.add_metadata(tokens);
// Setup a mutational stage with a basic bytes mutator
let mutator =
StdScheduledMutator::with_max_stack_pow(havoc_mutations().merge(tokens_mutations()), 6);
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");
}

View File

@ -0,0 +1,37 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// The following line is needed for shared memory testcase fuzzing
__AFL_FUZZ_INIT();
void vuln(char *buf) {
if (strcmp(buf, "vuln") == 0) { abort(); }
}
int main(int argc, char **argv) {
// Start the forkserver at this point (i.e., forks will happen here)
__AFL_INIT();
// The following five lines are for normal fuzzing.
/*
FILE *file = stdin;
if (argc > 1) { file = fopen(argv[1], "rb"); }
char buf[16];
char *p = fgets(buf, 16, file);
buf[15] = 0;
*/
// The following line is also needed for shared memory testcase fuzzing
unsigned char *buf = __AFL_FUZZ_TESTCASE_BUF; // must be after __AFL_INIT
// printf("input: %s\n", buf);
if (buf[0] == 'b') {
if (buf[1] == 'a') {
if (buf[2] == 'd') { abort(); }
}
}
vuln((char *)buf);
return 0;
}

View File

@ -1,6 +1,6 @@
[package] [package]
name = "forkserver_simple" name = "forkserver_simple"
version = "0.8.2" version = "0.9.0"
authors = ["tokatoka <tokazerkje@outlook.com>"] authors = ["tokatoka <tokazerkje@outlook.com>"]
edition = "2021" edition = "2021"

View File

@ -103,7 +103,8 @@ pub fn main() {
let shmem_buf = shmem.as_mut_slice(); let shmem_buf = shmem.as_mut_slice();
// Create an observation channel using the signals map // Create an observation channel using the signals map
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)); let edges_observer =
unsafe { HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)) };
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
@ -114,7 +115,7 @@ pub fn main() {
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false), MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// A feedback to choose if an input is a solution or not // A feedback to choose if an input is a solution or not
@ -144,7 +145,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

View File

@ -1,6 +1,6 @@
[package] [package]
name = "frida_gdiplus" name = "frida_gdiplus"
version = "0.7.0" version = "0.9.0"
authors = ["Richard Johnson <richinseattle@gmail.com>"] authors = ["Richard Johnson <richinseattle@gmail.com>"]
edition = "2021" edition = "2021"

View File

@ -1,10 +1,10 @@
//! A libfuzzer-like fuzzer with llmp-multithreading support and restarts //! A `libfuzzer`-like fuzzer with `llmp`-multithreading support and restarts
//! The example harness is built for gdiplus. //! The example harness is built for `gdiplus`.
//! NOTE: This file is 1-to-1 copy of the ../../frida_libpng/fuzzer.rs, which //! NOTE: This file is 1-to-1 copy of `../../frida_libpng/fuzzer.rs`, which
//! is platform independent. Hence, this file contains code for other platforms //! is platform independent. Hence, this file contains code for other platforms
//! but it's only meaningful for Windows because of the gdiplus target. If you //! but it's only meaningful for Windows because of the `gdiplus` target. If you
//! going to make it compilable only for windows, don't foret to modify the //! going to make it compilable only for Windows, don't forget to modify the
//! scripts/test_all_fuzzers.sh to opt-out this fuzzer from that test. //! `scripts/test_all_fuzzers.sh` to opt-out this fuzzer from that test.
use mimalloc::MiMalloc; use mimalloc::MiMalloc;
#[global_allocator] #[global_allocator]
@ -23,7 +23,7 @@ use libafl::{
tuples::{tuple_list, Merge}, tuples::{tuple_list, Merge},
AsSlice, AsSlice,
}, },
corpus::{ondisk::OnDiskMetadataFormat, CachedOnDiskCorpus, Corpus, OnDiskCorpus}, corpus::{CachedOnDiskCorpus, Corpus, OnDiskCorpus},
events::{llmp::LlmpRestartingEventManager, EventConfig}, events::{llmp::LlmpRestartingEventManager, EventConfig},
executors::{inprocess::InProcessExecutor, ExitKind, ShadowExecutor}, executors::{inprocess::InProcessExecutor, ExitKind, ShadowExecutor},
feedback_and_fast, feedback_or, feedback_or_fast, feedback_and_fast, feedback_or, feedback_or_fast,
@ -51,7 +51,7 @@ use libafl_frida::{
executor::FridaInProcessExecutor, executor::FridaInProcessExecutor,
helper::FridaInstrumentationHelper, helper::FridaInstrumentationHelper,
}; };
use libafl_targets::cmplog::{CmpLogObserver, CMPLOG_MAP}; use libafl_targets::cmplog::CmpLogObserver;
/// The main fn, usually parsing parameters, and starting the fuzzer /// The main fn, usually parsing parameters, and starting the fuzzer
pub fn main() { pub fn main() {
@ -60,18 +60,18 @@ pub fn main() {
let options = parse_args(); let options = parse_args();
unsafe { unsafe {
match fuzz(options) { match fuzz(&options) {
Ok(()) | Err(Error::ShuttingDown) => println!("\nFinished fuzzing. Good bye."), Ok(()) | Err(Error::ShuttingDown) => println!("\nFinished fuzzing. Good bye."),
Err(e) => panic!("Error during fuzzing: {:?}", e), Err(e) => panic!("Error during fuzzing: {e:?}"),
} }
} }
} }
/// The actual fuzzer /// The actual fuzzer
#[allow(clippy::too_many_lines, clippy::too_many_arguments)] #[allow(clippy::too_many_lines, clippy::too_many_arguments)]
unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { unsafe fn fuzz(options: &FuzzerOptions) -> Result<(), Error> {
// 'While the stats are state, they are usually used in the broker - which is likely never restarted // 'While the stats are state, they are usually used in the broker - which is likely never restarted
let monitor = MultiMonitor::new(|s| println!("{}", s)); let monitor = MultiMonitor::new(|s| println!("{s}"));
let shmem_provider = StdShMemProvider::new()?; let shmem_provider = StdShMemProvider::new()?;
@ -102,15 +102,15 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
#[cfg(unix)] #[cfg(unix)]
let mut frida_helper = let mut frida_helper =
FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage, asan)); FridaInstrumentationHelper::new(&gum, options, tuple_list!(coverage, asan));
#[cfg(windows)] #[cfg(windows)]
let mut frida_helper = let mut frida_helper =
FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage)); FridaInstrumentationHelper::new(&gum, options, tuple_list!(coverage));
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
"edges", "edges",
frida_helper.map_ptr_mut().unwrap(), frida_helper.map_mut_ptr().unwrap(),
MAP_SIZE, MAP_SIZE,
)); ));
@ -123,7 +123,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false), MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// Feedbacks to recognize an input as solution // Feedbacks to recognize an input as solution
@ -146,11 +146,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
CachedOnDiskCorpus::new(PathBuf::from("./corpus_discovered"), 64).unwrap(), CachedOnDiskCorpus::new(PathBuf::from("./corpus_discovered"), 64).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_save_meta( OnDiskCorpus::new(&options.output).unwrap(),
options.output.to_path_buf(),
Some(OnDiskMetadataFormat::JsonPretty),
)
.unwrap(),
&mut feedback, &mut feedback,
&mut objective, &mut objective,
) )
@ -225,12 +221,12 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
let cmplog = CmpLogRuntime::new(); let cmplog = CmpLogRuntime::new();
let mut frida_helper = let mut frida_helper =
FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage, cmplog)); FridaInstrumentationHelper::new(&gum, options, tuple_list!(coverage, cmplog));
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
"edges", "edges",
frida_helper.map_ptr_mut().unwrap(), frida_helper.map_mut_ptr().unwrap(),
MAP_SIZE, MAP_SIZE,
)); ));
@ -243,7 +239,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false), MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
#[cfg(unix)] #[cfg(unix)]
@ -261,14 +257,11 @@ unsafe fn fuzz(options: FuzzerOptions) -> 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
CachedOnDiskCorpus::new(PathBuf::from("./corpus_discovered"), 64).unwrap(), CachedOnDiskCorpus::no_meta(PathBuf::from("./corpus_discovered"), 64)
.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_save_meta( OnDiskCorpus::new(&options.output).unwrap(),
options.output.to_path_buf(),
Some(OnDiskMetadataFormat::JsonPretty),
)
.unwrap(),
&mut feedback, &mut feedback,
&mut objective, &mut objective,
) )
@ -330,7 +323,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
} }
// Create an observation channel using cmplog map // Create an observation channel using cmplog map
let cmplog_observer = CmpLogObserver::new("cmplog", &mut CMPLOG_MAP, true); let cmplog_observer = CmpLogObserver::new("cmplog", true);
let mut executor = ShadowExecutor::new(executor, tuple_list!(cmplog_observer)); let mut executor = ShadowExecutor::new(executor, tuple_list!(cmplog_observer));
@ -358,12 +351,12 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
let coverage = CoverageRuntime::new(); let coverage = CoverageRuntime::new();
let mut frida_helper = let mut frida_helper =
FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage)); FridaInstrumentationHelper::new(&gum, options, tuple_list!(coverage));
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
"edges", "edges",
frida_helper.map_ptr_mut().unwrap(), frida_helper.map_mut_ptr().unwrap(),
MAP_SIZE, MAP_SIZE,
)); ));
@ -376,7 +369,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false), MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
#[cfg(unix)] #[cfg(unix)]
@ -394,14 +387,11 @@ unsafe fn fuzz(options: FuzzerOptions) -> 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
CachedOnDiskCorpus::new(PathBuf::from("./corpus_discovered"), 64).unwrap(), CachedOnDiskCorpus::no_meta(PathBuf::from("./corpus_discovered"), 64)
.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_save_meta( OnDiskCorpus::new(&options.output).unwrap(),
options.output.to_path_buf(),
Some(OnDiskMetadataFormat::JsonPretty),
)
.unwrap(),
&mut feedback, &mut feedback,
&mut objective, &mut objective,
) )

View File

@ -1,6 +1,6 @@
[package] [package]
name = "frida_fuzzer" name = "frida_fuzzer"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -1,10 +1,7 @@
# Variables # Variables
[env] [env]
CARGO_TARGET_DIR = { value = "${CARGO_MAKE_WORKING_DIRECTORY}${SEP}target", condition = { env_not_set = ["CARGO_TARGET_DIR"] } } CARGO_TARGET_DIR = { value = "target", condition = { env_not_set = ["CARGO_TARGET_DIR"] } }
SEP={ source = "${CARGO_MAKE_RUST_TARGET_OS}", default_value = "/", mapping = {"linux" = "/", "macos" = "/", "windows" = "\\"} }
FUZZER_NAME={ source = "${CARGO_MAKE_RUST_TARGET_OS}", default_value = "frida_fuzzer", mapping = {"linux" = "frida_fuzzer", "macos" = "frida_fuzzer", "windows" = "frida_fuzzer.exe"} } FUZZER_NAME={ source = "${CARGO_MAKE_RUST_TARGET_OS}", default_value = "frida_fuzzer", mapping = {"linux" = "frida_fuzzer", "macos" = "frida_fuzzer", "windows" = "frida_fuzzer.exe"} }
FUZZER = '${CARGO_TARGET_DIR}${SEP}release${SEP}${FUZZER_NAME}'
[tasks.unsupported] [tasks.unsupported]
@ -72,7 +69,7 @@ windows_alias = "fuzzer_windows"
script_runner="@shell" script_runner="@shell"
script=''' script='''
cargo build --release cargo build --release
cp ${CARGO_TARGET_DIR}${SEP}release${SEP}${FUZZER_NAME} . cp ${CARGO_TARGET_DIR}/release/${FUZZER_NAME} .
''' '''
[tasks.fuzzer_windows] [tasks.fuzzer_windows]

View File

@ -22,7 +22,7 @@
#include <vector> #include <vector>
#define PNG_INTERNAL #define PNG_INTERNAL
#include "png.h" #include "libpng-1.6.37/png.h"
#define PNG_CLEANUP \ #define PNG_CLEANUP \
if (png_handler.png_ptr) { \ if (png_handler.png_ptr) { \

View File

@ -45,7 +45,7 @@ use libafl_frida::{
executor::FridaInProcessExecutor, executor::FridaInProcessExecutor,
helper::FridaInstrumentationHelper, helper::FridaInstrumentationHelper,
}; };
use libafl_targets::cmplog::{CmpLogObserver, CMPLOG_MAP}; use libafl_targets::cmplog::CmpLogObserver;
/// The main fn, usually parsing parameters, and starting the fuzzer /// The main fn, usually parsing parameters, and starting the fuzzer
pub fn main() { pub fn main() {
@ -54,18 +54,18 @@ pub fn main() {
let options = parse_args(); let options = parse_args();
unsafe { unsafe {
match fuzz(options) { match fuzz(&options) {
Ok(()) | Err(Error::ShuttingDown) => println!("\nFinished fuzzing. Good bye."), Ok(()) | Err(Error::ShuttingDown) => println!("\nFinished fuzzing. Good bye."),
Err(e) => panic!("Error during fuzzing: {:?}", e), Err(e) => panic!("Error during fuzzing: {e:?}"),
} }
} }
} }
/// The actual fuzzer /// The actual fuzzer
#[allow(clippy::too_many_lines, clippy::too_many_arguments)] #[allow(clippy::too_many_lines, clippy::too_many_arguments)]
unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { unsafe fn fuzz(options: &FuzzerOptions) -> Result<(), Error> {
// 'While the stats are state, they are usually used in the broker - which is likely never restarted // 'While the stats are state, they are usually used in the broker - which is likely never restarted
let monitor = MultiMonitor::new(|s| println!("{}", s)); let monitor = MultiMonitor::new(|s| println!("{s}"));
let shmem_provider = StdShMemProvider::new()?; let shmem_provider = StdShMemProvider::new()?;
@ -96,15 +96,15 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
#[cfg(unix)] #[cfg(unix)]
let mut frida_helper = let mut frida_helper =
FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage, asan)); FridaInstrumentationHelper::new(&gum, options, tuple_list!(coverage, asan));
#[cfg(windows)] #[cfg(windows)]
let mut frida_helper = let mut frida_helper =
FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage)); FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage));
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
"edges", "edges",
frida_helper.map_ptr_mut().unwrap(), frida_helper.map_mut_ptr().unwrap(),
MAP_SIZE, MAP_SIZE,
)); ));
@ -117,7 +117,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false), MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// Feedbacks to recognize an input as solution // Feedbacks to recognize an input as solution
@ -137,14 +137,11 @@ unsafe fn fuzz(options: FuzzerOptions) -> 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
CachedOnDiskCorpus::new(PathBuf::from("./corpus_discovered"), 64).unwrap(), CachedOnDiskCorpus::no_meta(PathBuf::from("./corpus_discovered"), 64)
.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_save_meta( OnDiskCorpus::new(options.output.clone()).unwrap(),
options.output.to_path_buf(),
Some(OnDiskMetadataFormat::JsonPretty),
)
.unwrap(),
&mut feedback, &mut feedback,
&mut objective, &mut objective,
) )
@ -219,12 +216,12 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
let cmplog = CmpLogRuntime::new(); let cmplog = CmpLogRuntime::new();
let mut frida_helper = let mut frida_helper =
FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage, cmplog)); FridaInstrumentationHelper::new(&gum, options, tuple_list!(coverage, cmplog));
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
"edges", "edges",
frida_helper.map_ptr_mut().unwrap(), frida_helper.map_mut_ptr().unwrap(),
MAP_SIZE, MAP_SIZE,
)); ));
@ -237,7 +234,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false), MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
#[cfg(unix)] #[cfg(unix)]
@ -255,14 +252,11 @@ unsafe fn fuzz(options: FuzzerOptions) -> 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
CachedOnDiskCorpus::new(PathBuf::from("./corpus_discovered"), 64).unwrap(), CachedOnDiskCorpus::no_meta(PathBuf::from("./corpus_discovered"), 64)
.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_save_meta( OnDiskCorpus::new(options.output.clone()).unwrap(),
options.output.to_path_buf(),
Some(OnDiskMetadataFormat::JsonPretty),
)
.unwrap(),
&mut feedback, &mut feedback,
&mut objective, &mut objective,
) )
@ -324,7 +318,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
} }
// Create an observation channel using cmplog map // Create an observation channel using cmplog map
let cmplog_observer = CmpLogObserver::new("cmplog", &mut CMPLOG_MAP, true); let cmplog_observer = CmpLogObserver::new("cmplog", true);
let mut executor = ShadowExecutor::new(executor, tuple_list!(cmplog_observer)); let mut executor = ShadowExecutor::new(executor, tuple_list!(cmplog_observer));
@ -352,12 +346,12 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
let coverage = CoverageRuntime::new(); let coverage = CoverageRuntime::new();
let mut frida_helper = let mut frida_helper =
FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage)); FridaInstrumentationHelper::new(&gum, options, tuple_list!(coverage));
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
"edges", "edges",
frida_helper.map_ptr_mut().unwrap(), frida_helper.map_mut_ptr().unwrap(),
MAP_SIZE, MAP_SIZE,
)); ));
@ -370,7 +364,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> {
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false), MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
#[cfg(unix)] #[cfg(unix)]
@ -388,14 +382,11 @@ unsafe fn fuzz(options: FuzzerOptions) -> 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
CachedOnDiskCorpus::new(PathBuf::from("./corpus_discovered"), 64).unwrap(), CachedOnDiskCorpus::no_meta(PathBuf::from("./corpus_discovered"), 64)
.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_save_meta( OnDiskCorpus::new(options.output.clone()).unwrap(),
options.output.to_path_buf(),
Some(OnDiskMetadataFormat::JsonPretty),
)
.unwrap(),
&mut feedback, &mut feedback,
&mut objective, &mut objective,
) )

View File

@ -1,6 +1,6 @@
[package] [package]
name = "fuzzbench" name = "fuzzbench"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -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++ warpper was called. Expected {:?} to end with c or cxx", dir), _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"),
}; };
dir.pop(); dir.pop();

View File

@ -1,5 +1,5 @@
pub mod libafl_cc; pub mod libafl_cc;
fn main() { fn main() {
libafl_cc::main() libafl_cc::main();
} }

View File

@ -36,7 +36,7 @@ use libafl::{
scheduled::havoc_mutations, token_mutations::I2SRandReplace, tokens_mutations, scheduled::havoc_mutations, token_mutations::I2SRandReplace, tokens_mutations,
StdMOptMutator, StdScheduledMutator, Tokens, StdMOptMutator, StdScheduledMutator, Tokens,
}, },
observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, observers::{HitcountsMapObserver, TimeObserver},
schedulers::{ schedulers::{
powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler, powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler,
}, },
@ -50,8 +50,7 @@ use libafl::{
#[cfg(any(target_os = "linux", target_vendor = "apple"))] #[cfg(any(target_os = "linux", target_vendor = "apple"))]
use libafl_targets::autotokens; use libafl_targets::autotokens;
use libafl_targets::{ use libafl_targets::{
libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer, CmpLogObserver,
MAX_EDGES_NUM,
}; };
#[cfg(unix)] #[cfg(unix)]
use nix::{self, unistd::dup}; use nix::{self, unistd::dup};
@ -121,7 +120,7 @@ pub fn libafl_main() {
); );
if let Some(filenames) = res.get_many::<String>("remaining") { if let Some(filenames) = res.get_many::<String>("remaining") {
let filenames: Vec<&str> = filenames.map(|v| v.as_str()).collect(); let filenames: Vec<&str> = filenames.map(String::as_str).collect();
if !filenames.is_empty() { if !filenames.is_empty() {
run_testcases(&filenames); run_testcases(&filenames);
return; return;
@ -167,7 +166,7 @@ pub fn libafl_main() {
.expect("Could not parse timeout in milliseconds"), .expect("Could not parse timeout in milliseconds"),
); );
fuzz(out_dir, crashes, in_dir, tokens, logfile, timeout) fuzz(out_dir, crashes, &in_dir, tokens, &logfile, timeout)
.expect("An error occurred while fuzzing"); .expect("An error occurred while fuzzing");
} }
@ -176,7 +175,7 @@ fn run_testcases(filenames: &[&str]) {
// Call LLVMFUzzerInitialize() if present. // Call LLVMFUzzerInitialize() if present.
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if libfuzzer_initialize(&args) == -1 { if libfuzzer_initialize(&args) == -1 {
println!("Warning: LLVMFuzzerInitialize failed with -1") println!("Warning: LLVMFuzzerInitialize failed with -1");
} }
println!( println!(
@ -184,7 +183,7 @@ fn run_testcases(filenames: &[&str]) {
filenames.len() filenames.len()
); );
for fname in filenames { for fname in filenames {
println!("Executing {}", fname); println!("Executing {fname}");
let mut file = File::open(fname).expect("No file found"); let mut file = File::open(fname).expect("No file found");
let mut buffer = vec![]; let mut buffer = vec![];
@ -195,20 +194,16 @@ fn run_testcases(filenames: &[&str]) {
} }
/// The actual fuzzer /// The actual fuzzer
#[allow(clippy::too_many_lines)]
fn fuzz( fn fuzz(
corpus_dir: PathBuf, corpus_dir: PathBuf,
objective_dir: PathBuf, objective_dir: PathBuf,
seed_dir: PathBuf, seed_dir: &PathBuf,
tokenfile: Option<PathBuf>, tokenfile: Option<PathBuf>,
logfile: PathBuf, logfile: &PathBuf,
timeout: Duration, timeout: Duration,
) -> Result<(), Error> { ) -> Result<(), Error> {
let log = RefCell::new( let log = RefCell::new(OpenOptions::new().append(true).create(true).open(logfile)?);
OpenOptions::new()
.append(true)
.create(true)
.open(&logfile)?,
);
#[cfg(unix)] #[cfg(unix)]
let mut stdout_cpy = unsafe { let mut stdout_cpy = unsafe {
@ -221,10 +216,10 @@ fn fuzz(
// 'While the monitor are state, they are usually used in the broker - which is likely never restarted // 'While the monitor are state, they are usually used in the broker - which is likely never restarted
let monitor = SimpleMonitor::new(|s| { let monitor = SimpleMonitor::new(|s| {
#[cfg(unix)] #[cfg(unix)]
writeln!(&mut stdout_cpy, "{}", s).unwrap(); writeln!(&mut stdout_cpy, "{s}").unwrap();
#[cfg(windows)] #[cfg(windows)]
println!("{}", s); println!("{s}");
writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); writeln!(log.borrow_mut(), "{:?} {s}", current_time()).unwrap();
}); });
// We need a shared map to store our state before a crash. // We need a shared map to store our state before a crash.
@ -240,21 +235,19 @@ fn fuzz(
return Ok(()); return Ok(());
} }
_ => { _ => {
panic!("Failed to setup the restarter: {}", err); panic!("Failed to setup the restarter: {err}");
} }
}, },
}; };
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
// We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges) // We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges)
let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") });
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges));
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
let cmplog = unsafe { &mut CMPLOG_MAP }; let cmplog_observer = CmpLogObserver::new("cmplog", true);
let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true);
let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false); let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false);
@ -266,7 +259,7 @@ fn fuzz(
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
map_feedback, map_feedback,
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// A feedback to choose if an input is a solution or not // A feedback to choose if an input is a solution or not
@ -297,7 +290,7 @@ fn fuzz(
// Call LLVMFUzzerInitialize() if present. // Call LLVMFUzzerInitialize() if present.
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if libfuzzer_initialize(&args) == -1 { if libfuzzer_initialize(&args) == -1 {
println!("Warning: LLVMFuzzerInitialize failed with -1") println!("Warning: LLVMFuzzerInitialize failed with -1");
} }
// Setup a randomic Input2State stage // Setup a randomic Input2State stage
@ -394,12 +387,7 @@ fn fuzz(
dup2(null_fd, io::stderr().as_raw_fd())?; dup2(null_fd, io::stderr().as_raw_fd())?;
} }
// reopen file to make sure we're at the end // reopen file to make sure we're at the end
log.replace( log.replace(OpenOptions::new().append(true).create(true).open(logfile)?);
OpenOptions::new()
.append(true)
.create(true)
.open(&logfile)?,
);
fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)?; fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)?;

View File

@ -1,6 +1,6 @@
[package] [package]
name = "fuzzbench_fork_qemu" name = "fuzzbench_fork_qemu"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -45,7 +45,7 @@ use libafl::{
Error, Error,
}; };
use libafl_qemu::{ use libafl_qemu::{
cmplog::{CmpLogMap, CmpLogObserver, QemuCmpLogChildHelper, CMPLOG_MAP_PTR}, cmplog::{CmpLogMap, CmpLogObserver, QemuCmpLogChildHelper},
edges::{QemuEdgeCoverageChildHelper, EDGES_MAP_PTR, EDGES_MAP_SIZE}, edges::{QemuEdgeCoverageChildHelper, EDGES_MAP_PTR, EDGES_MAP_SIZE},
elf::EasyElf, elf::EasyElf,
emu::Emulator, emu::Emulator,
@ -195,13 +195,16 @@ fn fuzz(
let file_null = File::open("/dev/null")?; let file_null = File::open("/dev/null")?;
// 'While the stats are state, they are usually used in the broker - which is likely never restarted // 'While the stats are state, they are usually used in the broker - which is likely never restarted
let monitor = SimpleMonitor::new(|s| { let monitor = SimpleMonitor::with_user_monitor(
|s| {
#[cfg(unix)] #[cfg(unix)]
writeln!(&mut stdout_cpy, "{}", s).unwrap(); writeln!(&mut stdout_cpy, "{s}").unwrap();
#[cfg(windows)] #[cfg(windows)]
println!("{}", s); println!("{s}");
writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); writeln!(log.borrow_mut(), "{:?} {s}", current_time()).unwrap();
}); },
true,
);
let mut shmem_provider = StdShMemProvider::new()?; let mut shmem_provider = StdShMemProvider::new()?;
@ -213,7 +216,10 @@ fn fuzz(
.new_shmem(core::mem::size_of::<CmpLogMap>()) .new_shmem(core::mem::size_of::<CmpLogMap>())
.unwrap(); .unwrap();
let cmplog = cmp_shmem.as_mut_slice(); let cmplog = cmp_shmem.as_mut_slice();
unsafe { CMPLOG_MAP_PTR = cmplog.as_mut_ptr() as *mut CmpLogMap };
// Beginning of a page should be properly aligned.
#[allow(clippy::cast_ptr_alignment)]
let cmplog_map_ptr = cmplog.as_mut_ptr().cast::<libafl_qemu::cmplog::CmpLogMap>();
let (state, mut mgr) = match SimpleRestartingEventManager::launch(monitor, &mut shmem_provider) let (state, mut mgr) = match SimpleRestartingEventManager::launch(monitor, &mut shmem_provider)
{ {
@ -224,21 +230,24 @@ fn fuzz(
return Ok(()); return Ok(());
} }
_ => { _ => {
panic!("Failed to setup the restarter: {}", err); panic!("Failed to setup the restarter: {err}");
} }
}, },
}; };
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges_observer = let edges_observer = unsafe {
HitcountsMapObserver::new(ConstMapObserver::<_, EDGES_MAP_SIZE>::new("edges", edges)); HitcountsMapObserver::new(ConstMapObserver::<_, EDGES_MAP_SIZE>::from_mut_ptr(
"edges",
edges.as_mut_ptr(),
))
};
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
// Create an observation channel using cmplog map // Create an observation channel using cmplog map
let cmplog_observer = let cmplog_observer = unsafe { CmpLogObserver::with_map_ptr("cmplog", cmplog_map_ptr, true) };
CmpLogObserver::new("cmplog", unsafe { CMPLOG_MAP_PTR.as_mut().unwrap() }, true);
let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false); let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false);
@ -250,7 +259,7 @@ fn fuzz(
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
map_feedback, map_feedback,
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// A feedback to choose if an input is a solution or not // A feedback to choose if an input is a solution or not

View File

@ -3,5 +3,5 @@ pub mod fuzzer;
fn main() { fn main() {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fuzzer::main() fuzzer::main();
} }

View File

@ -1,6 +1,6 @@
[package] [package]
name = "fuzzbench_forkserver" name = "fuzzbench_forkserver"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -19,7 +19,7 @@ use libafl::{
corpus::{Corpus, OnDiskCorpus}, corpus::{Corpus, OnDiskCorpus},
events::SimpleEventManager, events::SimpleEventManager,
executors::forkserver::{ForkserverExecutor, TimeoutForkserverExecutor}, executors::forkserver::{ForkserverExecutor, TimeoutForkserverExecutor},
feedback_and_fast, feedback_or, feedback_or,
feedbacks::{CrashFeedback, MaxMapFeedback, TimeFeedback}, feedbacks::{CrashFeedback, MaxMapFeedback, TimeFeedback},
fuzzer::{Fuzzer, StdFuzzer}, fuzzer::{Fuzzer, StdFuzzer},
inputs::BytesInput, inputs::BytesInput,
@ -225,7 +225,7 @@ fn fuzz(
// 'While the monitor are state, they are usually used in the broker - which is likely never restarted // 'While the monitor are state, they are usually used in the broker - which is likely never restarted
let monitor = SimpleMonitor::new(|s| { let monitor = SimpleMonitor::new(|s| {
println!("{}", s); println!("{s}");
writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap();
}); });
@ -241,9 +241,12 @@ fn fuzz(
// let the forkserver know the shmid // let the forkserver know the shmid
shmem.write_to_env("__AFL_SHM_ID").unwrap(); shmem.write_to_env("__AFL_SHM_ID").unwrap();
let shmem_buf = shmem.as_mut_slice(); let shmem_buf = shmem.as_mut_slice();
// To let know the AFL++ binary that we have a big map
std::env::set_var("AFL_MAP_SIZE", format!("{}", MAP_SIZE));
// Create an observation channel using the hitcounts map of AFL++ // Create an observation channel using the hitcounts map of AFL++
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)); let edges_observer =
unsafe { HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)) };
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
@ -258,17 +261,11 @@ fn fuzz(
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
map_feedback, map_feedback,
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// A feedback to choose if an input is a solution or not // A feedback to choose if an input is a solution or not
// We want to do the same crash deduplication that AFL does let mut objective = CrashFeedback::new();
let mut objective = feedback_and_fast!(
// Must be a crash
CrashFeedback::new(),
// Take it onlt if trigger new coverage over crashes
MaxMapFeedback::new(&edges_observer)
);
// create a State from scratch // create a State from scratch
let mut state = StdState::new( let mut state = StdState::new(

View File

@ -1,6 +1,6 @@
[package] [package]
name = "fuzzbench_qemu" name = "fuzzbench_qemu"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -1,6 +1,6 @@
//! A singlethreaded QEMU fuzzer that can auto-restart. //! A singlethreaded QEMU fuzzer that can auto-restart.
use core::{cell::RefCell, time::Duration}; use core::{cell::RefCell, ptr::addr_of_mut, time::Duration};
#[cfg(unix)] #[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::io::{AsRawFd, FromRawFd};
use std::{ use std::{
@ -45,11 +45,11 @@ use libafl::{
Error, Error,
}; };
use libafl_qemu::{ use libafl_qemu::{
//asan::{init_with_asan, QemuAsanHelper},
cmplog,
cmplog::{CmpLogObserver, QemuCmpLogHelper}, cmplog::{CmpLogObserver, QemuCmpLogHelper},
edges, //asan::{init_with_asan, QemuAsanHelper},
edges::edges_map_mut_slice,
edges::QemuEdgeCoverageHelper, edges::QemuEdgeCoverageHelper,
edges::MAX_EDGES_NUM,
elf::EasyElf, elf::EasyElf,
emu::Emulator, emu::Emulator,
filter_qemu_args, filter_qemu_args,
@ -226,7 +226,7 @@ fn fuzz(
#[cfg(unix)] #[cfg(unix)]
writeln!(&mut stdout_cpy, "{}", s).unwrap(); writeln!(&mut stdout_cpy, "{}", s).unwrap();
#[cfg(windows)] #[cfg(windows)]
println!("{}", s); println!("{s}");
writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap();
}); });
@ -241,22 +241,25 @@ fn fuzz(
return Ok(()); return Ok(());
} }
_ => { _ => {
panic!("Failed to setup the restarter: {}", err); panic!("Failed to setup the restarter: {err}");
} }
}, },
}; };
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges = unsafe { &mut edges::EDGES_MAP }; let edges_observer = unsafe {
let edges_counter = unsafe { &mut edges::MAX_EDGES_NUM }; HitcountsMapObserver::new(VariableMapObserver::from_mut_slice(
let edges_observer = "edges",
HitcountsMapObserver::new(VariableMapObserver::new("edges", edges, edges_counter)); edges_map_mut_slice(),
addr_of_mut!(MAX_EDGES_NUM),
))
};
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
// Create an observation channel using cmplog map // Create an observation channel using cmplog map
let cmplog_observer = CmpLogObserver::new("cmplog", unsafe { &mut cmplog::CMPLOG_MAP }, true); let cmplog_observer = CmpLogObserver::new("cmplog", true);
let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false); let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false);
@ -268,7 +271,7 @@ fn fuzz(
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
map_feedback, map_feedback,
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// A feedback to choose if an input is a solution or not // A feedback to choose if an input is a solution or not

View File

@ -1,6 +1,6 @@
[package] [package]
name = "fuzzbench_text" name = "fuzzbench_text"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -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++ warpper was called. Expected {:?} to end with c or cxx", dir), _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"),
}; };
dir.pop(); dir.pop();

View File

@ -31,7 +31,7 @@ use libafl::{
feedback_or, feedback_or,
feedbacks::{CrashFeedback, MaxMapFeedback, TimeFeedback}, feedbacks::{CrashFeedback, MaxMapFeedback, TimeFeedback},
fuzzer::{Fuzzer, StdFuzzer}, fuzzer::{Fuzzer, StdFuzzer},
inputs::{BytesInput, GeneralizedInput, HasTargetBytes}, inputs::{BytesInput, HasTargetBytes},
monitors::SimpleMonitor, monitors::SimpleMonitor,
mutators::{ mutators::{
grimoire::{ grimoire::{
@ -42,13 +42,13 @@ use libafl::{
token_mutations::I2SRandReplace, token_mutations::I2SRandReplace,
tokens_mutations, StdMOptMutator, StdScheduledMutator, Tokens, tokens_mutations, StdMOptMutator, StdScheduledMutator, Tokens,
}, },
observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, observers::{HitcountsMapObserver, TimeObserver},
schedulers::{ schedulers::{
powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler, powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler,
}, },
stages::{ stages::{
calibrate::CalibrationStage, dump::DumpToDiskStage, power::StdPowerMutationalStage, calibrate::CalibrationStage, power::StdPowerMutationalStage, GeneralizationStage,
GeneralizationStage, StdMutationalStage, TracingStage, StdMutationalStage, TracingStage,
}, },
state::{HasCorpus, HasMetadata, StdState}, state::{HasCorpus, HasMetadata, StdState},
Error, Error,
@ -56,8 +56,7 @@ use libafl::{
#[cfg(any(target_os = "linux", target_vendor = "apple"))] #[cfg(any(target_os = "linux", target_vendor = "apple"))]
use libafl_targets::autotokens; use libafl_targets::autotokens;
use libafl_targets::{ use libafl_targets::{
libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer, CmpLogObserver,
MAX_EDGES_NUM,
}; };
#[cfg(unix)] #[cfg(unix)]
use nix::{self, unistd::dup}; use nix::{self, unistd::dup};
@ -149,11 +148,8 @@ pub fn libafl_main() {
} }
} }
let mut crashes = out_dir.clone(); let mut crashes = out_dir.clone();
let mut report = out_dir.clone();
crashes.push("crashes"); crashes.push("crashes");
report.push("report");
out_dir.push("queue"); out_dir.push("queue");
drop(fs::create_dir(&report));
let in_dir = PathBuf::from( let in_dir = PathBuf::from(
res.get_one::<String>("in") res.get_one::<String>("in")
@ -178,9 +174,7 @@ pub fn libafl_main() {
); );
if check_if_textual(&in_dir, &tokens) { if check_if_textual(&in_dir, &tokens) {
fuzz_text( fuzz_text(out_dir, crashes, &in_dir, tokens, &logfile, timeout)
out_dir, crashes, &report, &in_dir, tokens, &logfile, timeout,
)
.expect("An error occurred while fuzzing"); .expect("An error occurred while fuzzing");
} else { } else {
fuzz_binary(out_dir, crashes, &in_dir, tokens, &logfile, timeout) fuzz_binary(out_dir, crashes, &in_dir, tokens, &logfile, timeout)
@ -286,7 +280,7 @@ fn fuzz_binary(
#[cfg(unix)] #[cfg(unix)]
writeln!(&mut stdout_cpy, "{}", s).unwrap(); writeln!(&mut stdout_cpy, "{}", s).unwrap();
#[cfg(windows)] #[cfg(windows)]
println!("{}", s); println!("{s}");
writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap();
}); });
@ -303,21 +297,19 @@ fn fuzz_binary(
return Ok(()); return Ok(());
} }
_ => { _ => {
panic!("Failed to setup the restarter: {}", err); panic!("Failed to setup the restarter: {err}");
} }
}, },
}; };
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
// We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges) // We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges)
let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") });
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges));
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
let cmplog = unsafe { &mut CMPLOG_MAP }; let cmplog_observer = CmpLogObserver::new("cmplog", true);
let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true);
let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false); let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false);
@ -329,7 +321,7 @@ fn fuzz_binary(
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
map_feedback, map_feedback,
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// 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();
@ -469,7 +461,6 @@ fn fuzz_binary(
fn fuzz_text( fn fuzz_text(
corpus_dir: PathBuf, corpus_dir: PathBuf,
objective_dir: PathBuf, objective_dir: PathBuf,
report_dir: &Path,
seed_dir: &PathBuf, seed_dir: &PathBuf,
tokenfile: Option<PathBuf>, tokenfile: Option<PathBuf>,
logfile: &PathBuf, logfile: &PathBuf,
@ -490,7 +481,7 @@ fn fuzz_text(
#[cfg(unix)] #[cfg(unix)]
writeln!(&mut stdout_cpy, "{}", s).unwrap(); writeln!(&mut stdout_cpy, "{}", s).unwrap();
#[cfg(windows)] #[cfg(windows)]
println!("{}", s); println!("{s}");
writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap();
}); });
@ -507,21 +498,19 @@ fn fuzz_text(
return Ok(()); return Ok(());
} }
_ => { _ => {
panic!("Failed to setup the restarter: {}", err); panic!("Failed to setup the restarter: {err}");
} }
}, },
}; };
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
// We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges) // We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges)
let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") });
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges));
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
let cmplog = unsafe { &mut CMPLOG_MAP }; let cmplog_observer = CmpLogObserver::new("cmplog", true);
let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true);
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, true); let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, true);
@ -533,7 +522,7 @@ fn fuzz_text(
let mut feedback = feedback_or!( let mut feedback = feedback_or!(
map_feedback, map_feedback,
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// A feedback to choose if an input is a solution or not // A feedback to choose if an input is a solution or not
@ -591,7 +580,7 @@ fn fuzz_text(
), ),
3, 3,
); );
let grimoire = StdMutationalStage::new(grimoire_mutator); let grimoire = StdMutationalStage::transforming(grimoire_mutator);
// A minimization+queue policy to get testcasess from the corpus // A minimization+queue policy to get testcasess from the corpus
let scheduler = IndexesLenTimeMinimizerScheduler::new(StdWeightedScheduler::with_schedule( let scheduler = IndexesLenTimeMinimizerScheduler::new(StdWeightedScheduler::with_schedule(
@ -602,7 +591,7 @@ fn fuzz_text(
let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective); let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);
// The wrapped harness function, calling out to the LLVM-style harness // The wrapped harness function, calling out to the LLVM-style harness
let mut harness = |input: &GeneralizedInput| { let mut harness = |input: &BytesInput| {
let target = input.target_bytes(); let target = input.target_bytes();
let buf = target.as_slice(); let buf = target.as_slice();
libfuzzer_test_one_input(buf); libfuzzer_test_one_input(buf);
@ -638,23 +627,8 @@ fn fuzz_text(
timeout * 10, timeout * 10,
)); ));
let fuzzbench = DumpToDiskStage::new(
|input: &GeneralizedInput| input.target_bytes().into(),
&report_dir.join("queue"),
&report_dir.join("crashes"),
)
.unwrap();
// The order of the stages matter! // The order of the stages matter!
let mut stages = tuple_list!( let mut stages = tuple_list!(generalization, calibration, tracing, i2s, power, grimoire);
fuzzbench,
generalization,
calibration,
tracing,
i2s,
power,
grimoire
);
// Read tokens // Read tokens
if state.metadata().get::<Tokens>().is_none() { if state.metadata().get::<Tokens>().is_none() {

View File

@ -1,8 +1,8 @@
[package] [package]
name = "libafl_atheris" name = "libafl_atheris"
version = "0.8.2" version = "0.9.0"
authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"] authors = ["Andrea Fioraldi <andreafioraldi@gmail.com>", "Dominik Maier <domenukk@gmail.com>"]
edition = "2018" edition = "2021"
[features] [features]
default = ["std"] default = ["std"]

View File

@ -34,7 +34,7 @@ use libafl::{
scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator},
token_mutations::{I2SRandReplace, Tokens}, token_mutations::{I2SRandReplace, Tokens},
}, },
observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, observers::{HitcountsMapObserver, TimeObserver},
schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler},
stages::{StdMutationalStage, TracingStage}, stages::{StdMutationalStage, TracingStage},
state::{HasCorpus, HasMetadata, StdState}, state::{HasCorpus, HasMetadata, StdState},
@ -42,7 +42,7 @@ use libafl::{
}; };
use libafl_targets::{ use libafl_targets::{
CmpLogObserver, __sanitizer_cov_trace_cmp1, __sanitizer_cov_trace_cmp2, CmpLogObserver, __sanitizer_cov_trace_cmp1, __sanitizer_cov_trace_cmp2,
__sanitizer_cov_trace_cmp4, __sanitizer_cov_trace_cmp8, CMPLOG_MAP, EDGES_MAP_PTR, __sanitizer_cov_trace_cmp4, __sanitizer_cov_trace_cmp8, std_edges_map_observer, EDGES_MAP_PTR,
MAX_EDGES_NUM, MAX_EDGES_NUM,
}; };
@ -211,26 +211,19 @@ pub fn LLVMFuzzerRunDriver(
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
let monitor = MultiMonitor::new(|s| println!("{}", s)); let monitor = MultiMonitor::new(|s| println!("{s}"));
// TODO: we need to handle Atheris calls to `exit` on errors somhow. // TODO: we need to handle Atheris calls to `exit` on errors somhow.
let mut run_client = |state: Option<_>, mut mgr, _core_id| { let mut run_client = |state: Option<_>, mut mgr, _core_id| {
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges_observer = unsafe { let edges_observer = unsafe { HitcountsMapObserver::new(std_edges_map_observer("edges")) };
HitcountsMapObserver::new(StdMapObserver::new_from_ptr(
"edges",
EDGES_MAP_PTR,
MAX_EDGES_NUM,
))
};
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
// Create the Cmp observer // Create the Cmp observer
let cmplog = unsafe { &mut CMPLOG_MAP }; let cmplog_observer = CmpLogObserver::new("cmplog", true);
let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true);
// Feedback to rate the interestingness of an input // Feedback to rate the interestingness of an input
// This one is composed by two Feedbacks in OR // This one is composed by two Feedbacks in OR
@ -238,7 +231,7 @@ pub fn LLVMFuzzerRunDriver(
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
MaxMapFeedback::new_tracking(&edges_observer, true, false), MaxMapFeedback::new_tracking(&edges_observer, true, false),
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// A feedback to choose if an input is a solution or not // A feedback to choose if an input is a solution or not

View File

@ -1,6 +1,6 @@
[package] [package]
name = "libfuzzer_libmozjpeg" name = "libfuzzer_libmozjpeg"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -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++ warpper was called. Expected {:?} to end with c or cxx", dir), _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"),
}; };
dir.pop(); dir.pop();

View File

@ -1,5 +1,5 @@
pub mod libafl_cc; pub mod libafl_cc;
fn main() { fn main() {
libafl_cc::main() libafl_cc::main();
} }

View File

@ -32,7 +32,7 @@ use libafl::{
Error, Error,
}; };
use libafl_targets::{ use libafl_targets::{
libfuzzer_initialize, libfuzzer_test_one_input, CMP_MAP, EDGES_MAP, MAX_EDGES_NUM, libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer, CMP_MAP,
}; };
const ALLOC_MAP_SIZE: usize = 16 * 1024; const ALLOC_MAP_SIZE: usize = 16 * 1024;
@ -62,7 +62,7 @@ pub fn libafl_main() {
/// The actual fuzzer /// The actual fuzzer
fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Result<(), Error> { fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Result<(), Error> {
// 'While the stats are state, they are usually used in the broker - which is likely never restarted // 'While the stats are state, they are usually used in the broker - which is likely never restarted
let monitor = SimpleMonitor::new(|s| println!("{}", s)); let monitor = SimpleMonitor::new(|s| println!("{s}"));
// The restarting state will spawn the same process again as child, then restarted it each time it crashes. // The restarting state will spawn the same process again as child, then restarted it each time it crashes.
let (state, mut restarting_mgr) = let (state, mut restarting_mgr) =
@ -78,14 +78,13 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re
}; };
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; let edges_observer = unsafe { std_edges_map_observer("edges") };
let edges_observer = StdMapObserver::new("edges", edges);
// Create an observation channel using the cmp map // Create an observation channel using the cmp map
let cmps_observer = StdMapObserver::new("cmps", unsafe { &mut CMP_MAP }); let cmps_observer = unsafe { StdMapObserver::new("cmps", &mut CMP_MAP) };
// Create an observation channel using the allocations map // Create an observation channel using the allocations map
let allocs_observer = StdMapObserver::new("allocs", unsafe { &mut libafl_alloc_map }); let allocs_observer = unsafe { StdMapObserver::new("allocs", &mut libafl_alloc_map) };
// 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!(

View File

@ -1,6 +1,6 @@
[package] [package]
name = "libfuzzer_libpng" name = "libfuzzer_libpng"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -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++ warpper was called. Expected {:?} to end with c or cxx", dir), _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"),
}; };
dir.pop(); dir.pop();

View File

@ -1,5 +1,5 @@
pub mod libafl_cc; pub mod libafl_cc;
fn main() { fn main() {
libafl_cc::main() libafl_cc::main();
} }

View File

@ -62,7 +62,7 @@ pub fn libafl_main() {
#[cfg(not(test))] #[cfg(not(test))]
fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Result<(), Error> { fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Result<(), Error> {
// 'While the stats are state, they are usually used in the broker - which is likely never restarted // 'While the stats are state, they are usually used in the broker - which is likely never restarted
let monitor = MultiMonitor::new(|s| println!("{}", s)); let monitor = MultiMonitor::new(|s| println!("{s}"));
// The restarting state will spawn the same process again as child, then restarted it each time it crashes. // The restarting state will spawn the same process again as child, then restarted it each time it crashes.
let (state, mut restarting_mgr) = let (state, mut restarting_mgr) =
@ -73,14 +73,19 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re
return Ok(()); return Ok(());
} }
_ => { _ => {
panic!("Failed to setup the restarter: {}", err); panic!("Failed to setup the restarter: {err}");
} }
}, },
}; };
// Create an observation channel using the coverage map // Create an observation channel using the coverage map
let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; let edges_observer = unsafe {
let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); HitcountsMapObserver::new(StdMapObserver::from_mut_ptr(
"edges",
EDGES_MAP.as_mut_ptr(),
MAX_EDGES_NUM,
))
};
// Create an observation channel to keep track of the execution time // Create an observation channel to keep track of the execution time
let time_observer = TimeObserver::new("time"); let time_observer = TimeObserver::new("time");
@ -95,7 +100,7 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re
// New maximization map feedback linked to the edges observer and the feedback state // New maximization map feedback linked to the edges observer and the feedback state
map_feedback, map_feedback,
// Time feedback, this one does not need a feedback state // Time feedback, this one does not need a feedback state
TimeFeedback::new_with_observer(&time_observer) TimeFeedback::with_observer(&time_observer)
); );
// A feedback to choose if an input is a solution or not // A feedback to choose if an input is a solution or not
@ -182,7 +187,7 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re
// Call LLVMFUzzerInitialize() if present. // Call LLVMFUzzerInitialize() if present.
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if libfuzzer_initialize(&args) == -1 { if libfuzzer_initialize(&args) == -1 {
println!("Warning: LLVMFuzzerInitialize failed with -1") println!("Warning: LLVMFuzzerInitialize failed with -1");
} }
// In case the corpus is empty (on first run), reset // In case the corpus is empty (on first run), reset

View File

@ -1,6 +1,6 @@
[package] [package]
name = "libfuzzer_libpng_accounting" name = "libfuzzer_libpng_accounting"
version = "0.8.2" version = "0.9.0"
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"

View File

@ -13,7 +13,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++ warpper was called. Expected {:?} to end with c or cxx", dir), _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"),
}; };
dir.pop(); dir.pop();

Some files were not shown because too many files have changed in this diff Show More