Build a Coverage-Guided Fuzzer in Python
libFuzzer and AFL++ are large programs, but the idea at their core fits on one screen: run the target, record which code it reached, mutate inputs, and keep the ones that reach something new. Writing that loop yourself is the best way to understand what the real tools do, why their statistics look the way they do, and where they get stuck. In this lesson you build one in about a hundred lines of Python and point it at a toy parser with a seeded bug.
The target: a toy parser with a seeded bug
The parser reads the course's toy TLV1 format: the magic TLV1, then records of a type byte, a length byte and a value. Type 1 is a name. If a name starts with the UTF-16LE byte-order mark FF FE, the next byte says how many two-byte code units follow, and the parser reads the last one. The seeded bug: that count is never compared with the record's length, so a large count reads past the value.
Python itself is memory-safe: an index past the end of bytes raises an IndexError or, for slices, silently returns less. To model a C parser, every risky read goes through load(), a bounds-checked accessor that raises Crash with a report, exactly the role AddressSanitizer plays for C. That is the oracle.
The three parts of a fuzzer
- Coverage.
sys.settracecalls a function on every line Python executes. The tracer records arcs, pairs (previous line, current line) insideparse, the Python equivalent of the branch edges that compiler instrumentation records in C (-fsanitize=fuzzerin Clang,afl-clang-fastin AFL++). - Mutation.
mutate()stacks one to three small changes: overwrite a byte with a random value, overwrite it with a boundary value (0x00,0x7F,0xFF…), flip a bit, insert or delete a byte. Real fuzzers call this stacked mode "havoc". - The loop. Pick a parent from the corpus, mutate it, run it. A crash ends the campaign. New arcs put the child in the corpus.
To see what the feedback is worth, the same loop runs blind: it mutates only the seed and never keeps anything. Both fuzzers start from one valid file, use a fixed random seed so the output is reproducible (a real campaign uses fresh randomness), and stop after 20,000 runs. It runs in your browser and takes a few seconds:
import random, sys
class Crash(Exception):
pass
def load(buf, i):
"""A bounds-checked read: our stand-in for AddressSanitizer."""
if not 0 <= i < len(buf):
raise Crash(f"out-of-bounds read at index {i} of a {len(buf)}-byte buffer")
return buf[i]
def parse(data):
"""Toy TLV1 parser with one seeded bug."""
if len(data) < 4 or data[:4] != b"TLV1":
return None
pos, names = 4, []
while pos + 2 <= len(data):
typ, ln = data[pos], data[pos + 1]
val = data[pos + 2:pos + 2 + ln]
if len(val) < ln:
return None # truncated record: rejected correctly
if typ == 1 and ln >= 3:
if val[0] == 0xFF: # UTF-16LE byte-order mark FF FE, first byte
if val[1] == 0xFE: # ... second byte
units = val[2] # number of UTF-16 code units that follow
last = load(val, 2 + 2 * units) # BUG: units never checked against ln
names.append(("utf16", units, last))
else:
names.append(("bytes", ln))
else:
names.append(("ascii", ln))
elif typ == 2:
names.append(("sum", sum(val) & 0xFF))
pos += 2 + ln
return names
def coverage(data):
"""Run parse() once; return (arcs, crash). An arc = (previous line, line) inside parse."""
arcs, prev = set(), [0]
code = parse.__code__
def tracer(frame, event, arg):
if frame.f_code is not code:
return None
if event == "line":
arcs.add((prev[0], frame.f_lineno))
prev[0] = frame.f_lineno
return tracer
sys.settrace(tracer)
try:
parse(data)
crash = None
except Crash as e:
crash = str(e)
finally:
sys.settrace(None)
return arcs, crash
INTERESTING = [0x00, 0x01, 0x10, 0x20, 0x40, 0x7F, 0x80, 0xFE, 0xFF]
def mutate(rng, data):
b = bytearray(data)
for _ in range(rng.randint(1, 3)): # stack 1-3 small changes ("havoc")
op = rng.random()
if op < 0.35 and b:
b[rng.randrange(len(b))] = rng.randrange(256) # overwrite a byte
elif op < 0.55 and b:
b[rng.randrange(len(b))] = rng.choice(INTERESTING) # a boundary value
elif op < 0.7 and b:
b[rng.randrange(len(b))] ^= 1 << rng.randrange(8) # flip a bit
elif op < 0.85 and len(b) < 64:
b.insert(rng.randrange(len(b) + 1), rng.randrange(256))
elif len(b) > 1:
del b[rng.randrange(len(b))]
return bytes(b)
def fuzz(seed_input, runs, guided, seed=1, log=False):
rng = random.Random(seed)
corpus = [seed_input]
seen, _ = coverage(seed_input)
for i in range(1, runs + 1):
parent = rng.choice(corpus) if guided else seed_input
child = mutate(rng, parent)
arcs, crash = coverage(child)
if crash:
return i, len(seen), child, crash
if not arcs <= seen: # new coverage
seen |= arcs
if guided:
corpus.append(child) # keep it as a stepping stone
if log:
print(f" run {i:5d}: new arcs, corpus {len(corpus)}: {child!r}")
return None, len(seen), None, None
SEED = b"TLV1\x01\x03bob\x02\x02\x01\x02" # one valid file: a name record and a sum record
print("seed parses to:", parse(SEED))
print("coverage-guided, seed 1:")
found, arcs, child, crash = fuzz(SEED, 20000, guided=True, seed=1, log=True)
print(f" run {found:5d}: CRASH {crash}\n input {child!r}")
print("20,000 runs each:")
for guided in (False, True):
for s in (1, 2, 3):
found, arcs, child, crash = fuzz(SEED, 20000, guided, seed=s)
label = "coverage-guided" if guided else "blind (seed only)"
print(f" {label:<18} seed {s}: arcs {arcs}, first crash at run {found}")seed parses to: [('ascii', 3), ('sum', 3)]
coverage-guided, seed 1:
run 3: new arcs, corpus 2: b'TLV1\x01bob \x02\r\x02'
run 5: new arcs, corpus 3: b'@LV1\x01\x03bob\x02\x02\x01p'
run 22: new arcs, corpus 4: b'TLV1\x01\x03\x9f\xf2\x96b\x02\x02\x01\x02'
run 628: new arcs, corpus 5: b'TLV1\x01\x03\xffob\x02\x02\x01\x02'
run 7123: CRASH out-of-bounds read at index 198 of a 3-byte buffer
input b'TLV1\x01\x03\xff\xfeb\x02\x02\x01\x02'
20,000 runs each:
blind (seed only) seed 1: arcs 21, first crash at run None
blind (seed only) seed 2: arcs 21, first crash at run None
blind (seed only) seed 3: arcs 21, first crash at run None
coverage-guided seed 1: arcs 21, first crash at run 7123
coverage-guided seed 2: arcs 21, first crash at run 4119
coverage-guided seed 3: arcs 21, first crash at run 3435
Reading the run
The log of the guided campaign is the whole story of coverage guidance:
- Runs 3, 5 and 22 add easy stepping stones: a truncated record, a broken magic, and a record of an unknown type (an inserted byte shifted the framing).
- Run 628 is the important one: a mutation wrote
0xFFas the first byte of the name. That made theval[0] == 0xFFcomparison true, a new arc, so the input joined the corpus. - Run 7123 mutated that input, wrote
0xFEnext to it, and the parser took the UTF-16 path with a count of0x62(98 code units, the letterb):load(val, 2 + 2 * 98)tried index 198 of a 3-byte value, and the oracle fired.
The blind fuzzer reaches the same arcs: it, too, sometimes writes 0xFF into the name. But it throws that input away, so it needs both bytes right in a single mutation, roughly a one-in-150,000 chance per run (a simulation of mutate on the seed gives about that), and finds nothing in 20,000 runs. The guided fuzzer found the bug with three different seeds in 3,435 to 7,123 runs. The final arc counts are the same; what differs is that the guided fuzzer built on its discoveries.
What the real tools add
This loop is the skeleton of every coverage-guided fuzzer. Production tools add:
| Feature | Why |
|---|---|
| compiled-in edge counters (a shared bitmap, hit counts in buckets) | microseconds per run instead of milliseconds; "loop ran 1, 2, 3, 4-7, 8-15, … 128+ times" counts as different coverage |
| corpus scheduling (favour small, fast, rarely-hit inputs) | spends time where progress is likely |
comparison tracing (CmpLog, -use_cmp) |
sees val[0] == 0xFF and tries 0xFF directly |
| crossover (splice two corpus inputs) | combines discoveries from different branches |
| crash files and deduplication | each unique bug saved once, as a reproducer |
| fork and parallel modes | many cores share one corpus |
The next lessons use the real thing: libFuzzer on the C version of this parser, and AFL++.
How fuzz findings are detected and confirmed
A fuzzer's crash is a claim, not a finding. Confirm it outside the fuzzer: replay the saved input against a normal build with the sanitizer (parse(crash_input) here, ./run_tlv crash-file in C), check that it fails the same way twice, and minimise it (Delta Debugging). Then triage it like any other bug.
How the bug is fixed
The fix checks the count against what the record really holds, before reading:
units = val[2]
if 3 + 2 * units > ln: # the code units must fit inside this record
return None # reject the fileand the crashing input becomes a regression test, assert parse(b"TLV1\x01\x03\xff\xfeb...") is None, so the bug cannot quietly return. Re-run the fuzzer after the fix: a campaign that now runs clean, with the same coverage, is the evidence that the fix is complete for the inputs the fuzzer can reach.
Pitfalls
- An oracle that never fires. Without
load(), the Python slice would return a short result and nothing would be reported. In C, the same over-read without ASan usually does not crash either. - Non-determinism in the target. If the target reads the clock or a global counter, the same input takes different paths and coverage becomes noise.
- Tracing the wrong code. This tracer only watches
parse; coverage in helper functions is invisible to it. Real instrumentation covers the whole program (or the parts you choose). - Comparing fuzzers on one seed. Waiting times are random; compare several seeds, as the table does.
Practice
1. Remove the "boundary value" mutation (the INTERESTING list). What do you expect, and why?
Both 0xFF and 0xFE must now come from a random overwrite (per change, 0.35/256 instead of 0.35/256 + 0.20/9 for the chosen value), so each step needs roughly 17 times as many runs; the guided fuzzer will probably not find the bug in 20,000 runs. Try it with runs=200000.
2. Make the fuzzer report the arc that each new corpus entry added. Which arc did run 628 add?
Store arcs - seen before updating seen and print it. Run 628 adds the arcs into and out of the line if val[1] == 0xFE:, reached only when val[0] == 0xFF is true.
3. Apply the fix to parse and re-run the guided campaign. What should change?
No crash in 20,000 runs (first crash at run None for all seeds), and the arc count grows by the new rejection path once an input reaches it.
Test yourself
In this fuzzer, what plays the role of AddressSanitizer?
- sys.settrace
- The bounds-checked load() that raises Crash on an out-of-bounds index
- random.Random
- The corpus
Why did run 628 matter even though it did not crash?
- It was the fastest run
- Writing 0xFF made a comparison true, a new arc, so the input became a stepping stone for the crash at run 7123
- It reset the corpus
- It changed the seed
The blind fuzzer reached the same arcs but found no crash. Why?
- It used different mutations
- It never kept interesting inputs, so it needed both BOM bytes in one mutation
- It had a bug
- It ran fewer times
What do arcs (previous line, current line) approximate?
- Memory usage
- The branch edges that compiler instrumentation records in C fuzzers
- Execution time
- The call stack