AFL++, OSS-Fuzz and ClusterFuzz
libFuzzer runs inside the target process. The other big family of fuzzers runs the target as a separate program, feeds it a file or standard input, and reads the coverage from shared memory. That is the design of American Fuzzy Lop (AFL), released by Michał Zalewski in 2013, and of its community successor AFL++, which is what most people mean by "AFL" today. Above both sit the services that run fuzzers continuously for whole ecosystems: Google's ClusterFuzz and OSS-Fuzz. AFL++ is not installed in this course's sandbox, so its part of the lesson is a labelled lab transcript; the coverage map it relies on is built in Python so you can see how it behaves.
How AFL-style coverage works
The compiler wrapper (afl-clang-fast, afl-clang-lto, or afl-gcc-fast) gives every basic block an ID and inserts a few instructions that update a 64 KiB shared bitmap. In the classic scheme from the original AFL documentation:
map[cur_id ^ prev_id]++; /* the slot of the edge prev -> cur */
prev_id = cur_id >> 1; /* shifted, so A->B and B->A get different slots */After each run the fuzzer reads the bitmap, turns each counter into a hit-count class (1, 2, 3, 4-7, 8-15, 16-31, 32-127, 128+) and compares with everything seen before. A new slot, or a known slot in a new class, is new coverage. The example reproduces that scheme on five paths through four blocks, then counts how many edges collide when the map is too small. It runs in your browser:
import random
def bucket(n):
"""AFL-style hit-count classes: 1, 2, 3, 4-7, 8-15, 16-31, 32-127, 128+."""
for limit, cls in ((1, 1), (2, 2), (3, 3), (7, 4), (15, 5), (31, 6), (127, 7)):
if n <= limit:
return cls
return 8
def trace_map(blocks, ids, map_size):
"""Classic AFL edge coverage: map[cur ^ prev]++, prev = cur >> 1."""
m, prev = {}, 0
for b in blocks:
cur = ids[b]
idx = (cur ^ prev) % map_size
m[idx] = m.get(idx, 0) + 1
prev = cur >> 1
return {i: bucket(c) for i, c in m.items()}
rng = random.Random(3)
ids = {b: rng.randrange(65536) for b in "ABCDEFGH"} # random IDs chosen at compile time
paths = {
"A B C D": list("ABCD"),
"A C B D": list("ACBD"), # same blocks, other order
"A B (C x3) D": list("AB") + ["C"] * 3 + ["D"],
"A B (C x5) D": list("AB") + ["C"] * 5 + ["D"],
"A B (C x6) D": list("AB") + ["C"] * 6 + ["D"],
}
seen = set()
for name, p in paths.items():
m = frozenset(trace_map(p, ids, 65536).items())
new = not m <= seen
seen |= m
print(f"{name:<14} blocks {sorted(set(p))} map entries {len(m)} new coverage: {new}")
# Collisions: how many distinct edges of a 2,000-edge program share a slot?
edges = {(rng.randrange(65536), rng.randrange(65536) >> 1) for _ in range(2000)}
for size in (65536, 4096, 256):
slots = {(a ^ b) % size for a, b in edges}
print(f"map {size:>6} slots: {len(edges)} edges -> {len(slots)} distinct slots ({len(edges) - len(slots)} lost)")A B C D blocks ['A', 'B', 'C', 'D'] map entries 4 new coverage: True
A C B D blocks ['A', 'B', 'C', 'D'] map entries 4 new coverage: True
A B (C x3) D blocks ['A', 'B', 'C', 'D'] map entries 5 new coverage: True
A B (C x5) D blocks ['A', 'B', 'C', 'D'] map entries 5 new coverage: True
A B (C x6) D blocks ['A', 'B', 'C', 'D'] map entries 5 new coverage: False
map 65536 slots: 2000 edges -> 1976 distinct slots (24 lost)
map 4096 slots: 2000 edges -> 1584 distinct slots (416 lost)
map 256 slots: 2000 edges -> 256 distinct slots (1744 lost)
A B C DandA C B Dvisit the same blocks but different edges, so the second path is new coverage. Block coverage would miss that.- Running the loop block
Cthree times adds the self-edge C to C (taken twice); five visits take it four times, a new class (4-7), so that is new too; six visits take it five times, the same 4-7 class, so it is not new. Buckets let the fuzzer notice "the loop ran more" without keeping every count. - With 2,000 edges in a 64 KiB map, 24 edges share a slot with another; a 256-slot map loses almost everything. Collisions hide coverage. That is why AFL++ offers an LTO mode that assigns collision-free IDs at link time, and why its default LLVM instrumentation uses a guard per edge instead of the XOR hash.
AFL++ in a lab session
The transcript below was made in a lab VM on the course's toy parser (scope: a local build of tlv.c with its seeded bugs; nothing else). It is abridged, and the counters are from one run: yours will differ.
lab@fuzz-vm:~/tlv$ export AFL_USE_ASAN=1 # build with AddressSanitizer
lab@fuzz-vm:~/tlv$ afl-clang-fast -g -O1 tlv.c run_tlv.c -o tlv_afl
lab@fuzz-vm:~/tlv$ mkdir seeds && printf 'TLV1\x01\x03bob\x02\x02\x01\x02' > seeds/ok.tlv
lab@fuzz-vm:~/tlv$ afl-fuzz -i seeds -o findings -- ./tlv_afl @@ # @@ = path of the input file
american fuzzy lop ++4.x (default) [explore]
┌─ process timing ────────────────────────────────────┬─ overall results ────┐
│ run time : 0 days, 0 hrs, 2 min, 10 sec │ cycles done : 14 │
│ last new find : 0 days, 0 hrs, 0 min, 41 sec │ corpus count : 23 │
│last saved crash : 0 days, 0 hrs, 1 min, 52 sec │saved crashes : 2 │
│ last saved hang : none seen yet │ saved hangs : 0 │
├─ map coverage ──────────────────────────────────────┴──────────────────────┤
│ map density : 0.04% / 0.05% count coverage : 2.31 bits/tuple │
├─ item geometry (abridged) ─────────────────────────────────────────────────┤
│ stability : 100.00% │
└────────────────────────────────────────────────────────────────────────────┘
^C
lab@fuzz-vm:~/tlv$ ls findings/default/crashes/
README.txt id:000000,sig:06,src:000004,time:7114,execs:20311,op:havoc,rep:4
id:000001,sig:06,src:000017,time:109962,execs:306120,op:havoc,rep:2
lab@fuzz-vm:~/tlv$ afl-tmin -i findings/default/crashes/id:000000* -o min1.tlv -- ./tlv_afl @@
lab@fuzz-vm:~/tlv$ ./tlv_afl min1.tlv 2>&1 | grep -E 'ERROR|READ|WRITE'
==4711==ERROR: AddressSanitizer: heap-buffer-overflow on address ...
READ of size 1 at ... thread T0What to read on that screen and in those names:
- saved crashes counts unique crashes by AFL's own measure (a new coverage pattern in a crashing run), not unique bugs: two crash files can be the same bug. Deduplicate by stack (Crash Triage).
- sig:06 is SIGABRT, which is how ASan ends the process;
srcis the corpus entry it was mutated from,op:havocthe mutation stage. - stability below 100% means the same input takes different paths: non-determinism in the target, which makes coverage unreliable.
- cycles done counts passes through the whole queue; when it keeps rising with no new finds, the campaign has plateaued and needs new seeds, a dictionary or a better harness.
The other tools you will use: afl-cmin (shrink a corpus to the inputs that matter), afl-tmin (shrink one input), afl-showmap (print the coverage of one input), parallel instances (-M main, -S worker1), CmpLog (-c ./tlv_cmplog, a second build that records comparison operands so the fuzzer can copy magic values into inputs, the dictionary effect of the lab), and persistent mode (a loop inside the target with __AFL_LOOP, which removes the cost of starting a process for every input). AFL++ also accepts libFuzzer-style harnesses unchanged.
OSS-Fuzz and ClusterFuzz
A fuzzer on a laptop runs for hours; serious bugs often need weeks of CPU time. ClusterFuzz is Google's infrastructure for running fuzzers at scale, and OSS-Fuzz (launched in 2016) offers it free to important open-source projects. A project joins with three small files in the OSS-Fuzz repository: a project.yaml (contacts, languages, sanitizers), a Dockerfile (fetch the source and build dependencies) and a build.sh (compile the harnesses with the flags the service supplies). From then on, ClusterFuzz:
- builds the project and its harnesses with each sanitizer, for each engine (libFuzzer, AFL++, honggfuzz and others);
- fuzzes continuously, sharing and minimising corpora;
- deduplicates crashes by sanitizer type and top stack frames, minimises the input, and bisects the commit range that introduced the bug;
- files a bug with the reproducer, restricted to the project's maintainers;
- checks the bug again on every new build, marks it fixed automatically, and opens it to the public after a disclosure deadline (OSS-Fuzz's policy: 90 days after the report or when the fix is released, whichever is earlier, with a 14-day grace period if a fix is imminent).
That last step makes OSS-Fuzz a disclosure process as well as a test service: fuzzing found the bug, but the reports go privately to the people who fix it. For your own projects, ClusterFuzzLite runs the same harnesses for a few minutes on every pull request in CI, which catches regressions before they merge.
How continuous fuzzing detects and prevents bugs
The value of a service is time and regression: a harness that runs every day finds the bug the week it is introduced, while the code is fresh, and a bug that comes back is reported again within a day. Projects that take part typically see a burst of findings in the first weeks (old bugs), then a steady trickle tied to new code. The fix side is the project's own: root cause, patch, a regression test, and an advisory where the bug was security-relevant.
Pitfalls
- Counting crash files as bugs. "saved crashes: 2" can be one bug, or two bugs behind one deduplication key.
- Ignoring stability. A target at 70% stability makes the fuzzer chase noise; fix the non-determinism first.
- Fuzzing only in CI. A few minutes per pull request finds regressions, not deep bugs. Run long campaigns too.
- Running someone else's harness against someone else's service. OSS-Fuzz runs on code a project chose to submit; using fuzzers against systems you do not own is still unauthorised testing.
Practice
1. In the Python example, why is A B (C x6) D not new coverage?
Six visits of C take the self-edge C to C five times; the previous path, with five visits, took it four times. Both counts fall in the 4-7 class, and every other edge (start to A, A to B, B to C, C to D) ran once in both. After classing, the bitmap is identical to one already seen, so nothing is new.
2. A campaign shows 87% stability. Name two likely causes in a parser harness.
Uninitialised memory or global state that changes between runs (a cache, a counter), and time- or randomness-dependent code (timestamps, rand() without a fixed seed). Threads are a third.
3. What does bisection give the maintainer of an OSS-Fuzz bug?
The range of commits (often a single commit) that introduced the crash, which points straight at the root cause and tells which releases are affected, both of which the advisory needs.
Test yourself
Why does classic AFL shift prev_id right by one bit?
- To save memory
- So that the edges A->B and B->A, and a block's self-loop, map to different slots
- To speed up hashing
- For alignment
What does AFL++'s 'saved crashes' count?
- Unique bugs
- Crashing inputs with a new coverage pattern, which still need stack-based deduplication
- Total crashes
- Hangs
What do hit-count classes (1, 2, 3, 4-7, ...) let a fuzzer notice?
- Memory leaks
- That a loop ran a different number of times, without storing every count
- Crashes
- Timeouts
What does ClusterFuzz do after it finds a crash?
- Publishes it immediately
- Deduplicates, minimises, bisects, files a restricted bug, verifies the fix, then discloses after a deadline
- Deletes it
- Sends it to a CVE database