Lab 02 — Write a bug, harness it, fuzz it, triage it¶
Objective: run the entire research loop once, on the host, against a parser you write and break yourself — so that when your triage verdict disagrees with the ground truth, you can find out which of you is wrong. Real targets never offer that feedback, which is why the first time you do this it must be against a bug whose answer you already know.
Difficulty: intermediate Time: 3–4 hours Prerequisites: 70 §3.4 to §3.9 and §7. Helpful: 19-Memory §3.9 (the defect taxonomy you will classify against), 01-Computer-Science-Basics (the stack, the heap).
What you need
| A host C compiler with AddressSanitizer | clang is ideal; gcc is sufficient and is what every measured number in this lab came from |
python3 |
For generating seeds and inputs |
| No device | Deliberately. Nothing in this lab touches a phone |
| The chapter's examples | ../examples/ — as a worked reference, not as the thing you fuzz |
Warning — do not fuzz on a phone you depend on. Everything here runs on your workstation. A campaign is millions of executions of code designed to misbehave; on a device it fills storage with artefacts, wedges services and thermally throttles. §7.6. Every number in this lab was produced on a host — under WSL2 with gcc 11.4.0, as it happens, and none of it went near either phone attached to the machine.
0. Why you must plant the bug yourself¶
You cannot practise triage against a bug whose ground truth you do not know.
When you triage a crash in real code, your verdict is a hypothesis and nothing tells you whether it is right. If you conclude "the write length is attacker-controlled" and you are wrong, you find out weeks later when a vendor's engineer says so — or never. That is a terrible feedback loop, and it is why people who have fuzzed for years still triage badly.
Here, you will know the answer. Every time your verdict and the plant disagree, one of them is wrong, and finding out which is the entire lesson.
Second reason, equally important: the target is yours, so the authorisation question in §1.6 does not arise at all. The first thing anyone fuzzes should be something nobody else has a claim on.
Part 1 — Write the parser¶
Step 1.1 Choose a format¶
Design a small binary container. Keep it small enough to write in an hour and complex enough to have somewhere for a bug to live. A workable minimum:
- A magic value, so most random input is rejected immediately.
- A version field.
- A count of items.
- Per item: a type, one or more length fields, and variable-length data.
The chapter's own ../examples/acfg.h documents exactly such a format and
explains why each field is there. Read it, then design a different one. Copying it defeats the
purpose, because you would already know where the bug is.
Structurally this family covers a surprising amount of real ground: the chunk stream in
resources.arsc, the box tree in an MP4, the tag stream in an ID3 header, the extra-field stream in
a ZIP local file header. TLV is where parser bugs live.
Write the format down before you write any code:
# MYFMT v1
offset 0 4 magic "MYFM"
offset 4 2 version, LE uint16, must be 1
offset 6 2 count, LE uint16
then `count` items:
0 1 type (1..4)
1 1 klen key length
2 2 vlen value length, LE uint16
4 klen bytes of key
vlen bytes of value
Step 1.2 Write the parser correctly first¶
Write it with every check present and correct:
- Input at least as long as the header.
- Magic matches.
- Version supported.
- Each item's header is present before you read it.
- Each item's key and value bytes are present in the input.
- Each item's key fits its destination.
- Every allocation is checked.
- Every error path frees what has been allocated so far, and nothing else.
Get it correct first, because you cannot plant one bug in code that already has three by accident.
Step 1.3 Write the accessor and the free function¶
Two things people forget, both of which the harness needs:
/* A free that is safe on a zeroed object, and frees only what was built.
Track `built` and increment it AFTER the last allocation in each iteration,
never before. Getting that order wrong is its own bug class. */
void myfmt_free(myfmt_doc *d);
Step 1.4 Sanity-test it by hand¶
# host -- python3 -B make_seed.py
import struct
def blob(items, version=1):
b = b'MYFM' + struct.pack('<HH', version, len(items))
for t, k, v in items:
b += struct.pack('<BBH', t, len(k), len(v)) + k + v
return b
open('seed-one.bin','wb').write(blob([(1, b'hello', b'abc')]))
open('seed-two.bin','wb').write(blob([(1, b'a', b'x'), (2, b'b', b'yy')]))
open('seed-zero.bin','wb').write(blob([]))
open('seed-empty.bin','wb').write(b'')
Parse each one, print what came out, and confirm it is right. A parser you have not verified on valid input will produce crashes that are your bug, not the planted one, and you will spend an hour triaging your own mistake.
Success criterion for Part 1: the parser accepts all three valid blobs, rejects an empty file, a wrong magic, a wrong version, and a truncated item — and you have run each case.
Part 2 — Plant exactly one bug¶
Step 2.1 Choose the class¶
Pick one. Each has a characteristic signature you will later have to recognise from the report alone.
| Class | How to plant it | What you should see |
|---|---|---|
| Missing destination check | Delete the klen >= KEY_MAX check before the copy |
heap-buffer-overflow WRITE, size equal to klen |
| Off-by-one | Change >= to > in that check |
A one-byte overflow — the terminator. Possibly UBSan only |
| Integer overflow into allocation | malloc(klen + vlen + 1) in a 16-bit variable |
An undersized allocation, then a large overflow |
| Use-after-free | Free the item on an error path and then read it in the loop's tail | heap-use-after-free |
| Double free | Free on the error path and in myfmt_free without clearing the pointer |
attempting double-free |
| Wrong bound | Check klen against vlen's destination size |
Overflow whose size looks unrelated to the check |
The first is the recommended choice for a first run, because it is the shape that survives real code review — the parser still contains a correct check, three lines above the bug, that validates the source.
Step 2.2 Plant it, and write down the ground truth¶
Create GROUND-TRUTH.md outside the directory you will be triaging from, and record:
Class : missing destination-size check on the key copy
Location : myfmt.c, the memcpy in the item loop
Trigger : klen > KEY_MAX
Expected report: heap-buffer-overflow, WRITE, size == klen
Expected control: length fully controlled (0..255), contents fully controlled
Reachability : none -- nothing on any device parses MYFMT
Then do not look at it again until Part 6 is finished.
Mental Model — the point of the sealed envelope. You are running an experiment with a known answer. The value is not in finding the bug; you know where it is. The value is in discovering which parts of your triage were guesses.
Step 2.3 Predict the second and third faces¶
Before you build anything, predict — in writing — what happens when the bug fires under different header values. Specifically:
- What if
countis 1 versus 4? - What if
klenis exactlyKEY_MAX? - What is
sizeofyour item struct, and where does the overflow land in each case?
This prediction is the most valuable thing you will write today, and Part 6 will check it. Chapter §3.7's measured result for the ACFG parser was that one defect produced a loud ASan abort, a UBSan-only line, and a completely silent outcome — depending only on those two fields.
Part 3 — Build the harness¶
Step 3.1 Generate the skeleton¶
# host
../scripts/make-fuzz-harness.sh \
--name myfmt --func myfmt_parse \
--sig 'int(const uint8_t *buf, size_t len, myfmt_doc *out)' \
--header myfmt.h --source myfmt.c \
--out /tmp/myfmt-harness
Because your signature has three parameters, the generator will emit a #error rather than guess at
the call. That is deliberate: a generator that guessed would produce a harness that compiles and
tests nothing. Read NOTES.md, then complete TODO 1.
Step 3.2 Write the body¶
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
myfmt_doc doc;
int rc = myfmt_parse(data, size, &doc);
if (rc == MYFMT_OK) {
/* Rule 5: READ the output. A missing NUL terminator produces no
symptom at all without this, and the bug ships. */
size_t acc = 0;
for (uint16_t i = 0; i < doc.built; i++) {
acc += strlen(doc.items[i].key);
acc += doc.items[i].type;
}
g_sink = acc;
}
/* Rule 2: free on EVERY path. Calling it unconditionally also tests the
promise that freeing a failed parse is safe. */
myfmt_free(&doc);
return 0;
}
Step 3.3 Check yourself against the five rules¶
| Rule | Your harness |
|---|---|
| 1. No state across calls | Is doc a local? Any statics? Any caches inside the parser? |
| 2. Free on every path | Is myfmt_free called unconditionally? |
| 3. No output per iteration | Any printf left in from debugging? |
| 4. No artificial crashes | Do you abort() on any return code? You must not |
| 5. Read the output | Does anything call strlen on the key? |
Rule 5 has a portability trap the chapter measured: the sink must be volatile or the optimiser
deletes the reads, but a function-local static volatile that is only written triggers clang's
-Wunused-but-set-variable and fails a -Werror build. gcc 11.4 accepts it; clang 14 does not. Use
a file-scope volatile assigned once, as the generator does.
Success criterion for Part 3: the harness compiles with -Wall -Wextra -Werror and no warnings.
Part 4 — Build with the detectors¶
Step 4.1 The build¶
# host
gcc -std=c11 -Wall -Wextra -Werror -g -O1 \
-fsanitize=address,undefined -fno-omit-frame-pointer \
-DMYFMT_STANDALONE \
harness.c myfmt.c -o fuzz_myfmt
Or with clang and libFuzzer, if you have it:
# host
clang -std=c11 -Wall -Wextra -Werror -g -O1 \
-fsanitize=fuzzer,address,undefined -fno-omit-frame-pointer \
-fsanitize-address-use-after-scope \
harness.c myfmt.c -o fuzz_myfmt
Every flag earns its place:
| Flag | Why |
|---|---|
-g |
Without symbols, every triage report is hex addresses |
-O1 |
-O0 is too slow to fuzz; -O2 makes line numbers lie |
-fno-omit-frame-pointer |
Readable stack traces, for one register |
-fsanitize=address |
Turns silent corruption into a diagnosable abort |
-fsanitize=undefined |
Catches what ASan structurally cannot — see Part 6 |
-Werror |
The compiler finds bugs for free; do not ignore it |
Step 4.2 Set the runtime options¶
# host
export ASAN_OPTIONS=abort_on_error=1:detect_leaks=1:allocator_may_return_null=0
export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1
UBSAN_OPTIONS=halt_on_error=1 is not the default, and this is the single most consequential
line in the lab. Without it, UBSan prints one line and the process carries on: your campaign exits
with status 0 and the finding sits in the log where a script grading on exit codes will never see it.
Step 4.3 Prove the harness reaches the target¶
Do not skip this. It takes ninety seconds and it is the only thing that distinguishes a campaign that found nothing from a campaign that tested nothing.
# host
# 1. add abort(); as the FIRST statement of myfmt_parse
# 2. rebuild
# 3. run one input
./fuzz_myfmt seed-one.bin
# expect: Aborted
# 4. remove the abort() and rebuild
If it does not abort, your harness is not calling your parser, and every result after this point would have been meaningless.
Success criterion for Part 4: the planted abort() fires, and after removing it the three valid
seeds replay with no fault.
Part 5 — Run the campaign¶
Step 5.1 With libFuzzer¶
# host
mkdir -p corpus findings
cp seed-*.bin corpus/
./fuzz_myfmt corpus/ -artifact_prefix=findings/ -max_len=512 \
-seed=1234 -print_final_stats=1
Step 5.2 Without libFuzzer¶
Use the standalone driver pattern from ../examples/fuzz-acfg.c. Copy its
mutation loop; the two things you must copy exactly are:
- Write the candidate input to disk before executing it. When the sanitizer fires it calls
_Exitand runs no cleanup, so an input held only in memory is gone and you are left with a stack trace and no reproducer. Every hand-written driver gets this wrong exactly once. - Write the execution index too. "It crashed somewhere between the 140,000th and 160,000th execution" is not a reproduction step.
# host
./fuzz_myfmt -m 200000 1234 seed-one.bin findings/ 2>&1 | tee campaign.log
Step 5.3 Watch the right things¶
| Signal | Healthy | Wrong |
|---|---|---|
exec/s |
thousands | under a few hundred — I/O or a slow harness |
cov: (libFuzzer) |
grows, then plateaus | flat from execution one — instrumentation did not apply |
rss: |
steady | growing — your harness leaks |
| Crashes | eventually | immediately on every input — your harness is broken |
Reference numbers. Against the chapter's ACFG parser, with gcc, ASan+UBSan, PRNG seed 1234 and a 20-byte valid seed, the standalone driver produced a UBSan line before execution 20,000 and an ASan abort at execution 143,121. Throughput was about 4,700 executions per second — 50,000 executions in 10.6 s wall clock, of which 0.6 s was user time and 3.5 s was system time. The system time dominates because of those two small file writes per execution. That is a deliberate trade of throughput for reproducibility, and it is why real fuzzers serialise the reproducer from inside their crash handler instead.
Success criterion for Part 5: a crash, a saved reproducer, and the execution index it occurred at.
Part 6 — Triage¶
This is the part of the lab that matters. Answer each question before running the tool, and
before opening GROUND-TRUTH.md.
Step 6.1 Question 1 — target or harness?¶
Read the stack from the bottom up.
#2 0x... in myfmt_parse myfmt.c:258
#3 0x... in LLVMFuzzerTestOneInput harness.c:104
#4 0x... in main harness.c:334
Frames 3 and 4 are the harness doing nothing but calling the target. Frame 2 is in the target. If
every meaningful frame were in harness.c, the bug would be yours — fix it and requeue every
artefact, because a harness bug can mask target bugs behind it.
Step 6.2 Question 2 — does it reproduce?¶
# host -- a FRESH process
./fuzz_myfmt findings/current.bin
If it does not reproduce, you have one of three things and they need different fixes:
| Symptom | Cause | Fix |
|---|---|---|
| Replays clean every time | State carried across calls in the harness | Rule 1 |
| Reproduces sometimes | Non-determinism: ASLR, a hash seed, uninitialised memory | Disable randomisation and re-check; suspect uninitialised memory |
| Reproduces on the old binary only | Wrong build | Record provenance: flags, commit, compiler version |
A crash you cannot reproduce is not a finding, and telling a vendor about one is how you lose credibility.
Step 6.3 Question 3 — read the report, field by field¶
Take this real report and answer the questions from it alone:
==911==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x5060000178d8
WRITE of size 58 at 0x5060000178d8 thread T0
#0 in __interceptor_memcpy
#1 in memcpy /usr/include/x86_64-linux-gnu/bits/string_fortified.h:29
#2 in acfg_parse /home/harsh/vr70/acfg-vulnerable.c:258
#3 in LLVMFuzzerTestOneInput /home/harsh/vr70/fuzz-acfg.c:104
#4 in main /home/harsh/vr70/fuzz-acfg.c:334
0x5060000178d8 is located 0 bytes to the right of 56-byte region
[0x5060000178a0,0x5060000178d8)
allocated by thread T0 here:
#0 in __interceptor_calloc
#1 in acfg_parse /home/harsh/vr70/acfg-vulnerable.c:148
| Question | Answer, and where it came from |
|---|---|
| Read or write? | Write. The WRITE of size 58 line |
| How big? | 58 bytes |
| How far out of bounds? | Zero. "0 bytes to the right" — the write begins exactly at the end of the allocation, which is the most useful case for an attacker because what follows is predictable |
| How big was the allocation? | 56 bytes |
| Where was it allocated? | Line 148 — a different line from the bug, and it matters: the allocation size and the overflow length are chosen independently |
| Is the length controlled? | The report cannot say. Go and read line 236. |
| Is the content controlled? | Same — the source, not the report |
Note the last two rows. Every real triage ends with a question the crash cannot answer, and knowing which question it is is the skill.
Step 6.4 Question 4 — do it mechanically, and disagree with the tool¶
# host
./fuzz_myfmt findings/current.bin 2> report.txt
python3 -B ../scripts/triage-asan.py report.txt
Compare with your own answers. Where you disagree, work out which of you is wrong; the tool is a heuristic and it says so in its own header.
Step 6.5 Question 5 — check your Part 2.3 predictions¶
Now build the three inputs you predicted about, by hand:
# host -- python3 -B make_crashers.py
def blob(items, version=1):
import struct
b = b'MYFM' + struct.pack('<HH', version, len(items))
for t, k, v in items:
b += struct.pack('<BBH', t, len(k), len(v)) + k + v
return b
open('c1-count1-big.bin','wb').write(blob([(1, b'A'*58, b'')]))
open('c2-count1-exact.bin','wb').write(blob([(1, b'A'*32, b'')])) # klen == KEY_MAX
open('c3-count4-mid.bin','wb').write(blob([(1, b'C'*40, b''), (1,b'a',b''),
(1,b'b',b''), (1,b'c',b'')]))
Run each and record the exit code and whether anything appeared in the log.
Against the chapter's ACFG parser, the answers were:
| Input | ASan | UBSan | Exit code |
|---|---|---|---|
count=1, klen=58 |
heap-buffer-overflow WRITE of size 58 |
— | 1 |
count=1, klen=32 |
silent | index 32 out of bounds for type 'char [32]' |
0 |
count=4, klen=40 |
silent | index 40 out of bounds for type 'char [32]' |
0 |
If your parser behaves the same way, you have reproduced the chapter's central measurement. If it does not, work out why — the layout of your item struct is probably different, and computing where your overflow lands is exactly the reasoning §3.8 question 4 asks for.
The mechanism. sizeof(acfg_record) is 56 bytes: 1 byte of type, 32 of name, 7 of padding, an
8-byte pointer, a 2-byte length, 6 of tail padding. At count = 1 the whole allocation is 56 bytes
and the overflow runs off the end of it, into ASan's redzone. At count = 4 it is 224 bytes and the
overflow lands on the next struct inside the same allocation — and ASan places no redzone between
two structs in one allocation, so it sees nothing. UBSan catches it because its array-bounds
check knows the static type is char[32], which the shadow map does not.
Warning — this is the reason "we fuzzed it and it was clean" means so little. If your corpus had happened to carry
count = 4rather thancount = 1, and your campaign were graded on exit codes, it would have reported no findings against a parser with a live out-of-bounds write in it. Grade on log content:grep -c "runtime error" campaign.log.
Success criterion for Part 6: a written triage — class, operation, size, distance, allocation size and site, what is controlled and what you could not determine from the report — plus the results of your three predicted inputs, and an explicit note of every place your prediction was wrong.
Part 7 — The reachability verdict¶
Step 7.1 Answer the sentence¶
Fill this in with specifics, from §3.9:
A [who] with [what starting position] can [do what], which causes [which process] to execute [which code] on data they control, giving them [what].
For MYFMT you cannot fill it in, and that is the answer: nothing on any device parses your format.
Step 7.2 Write the verdict block¶
Reachability : NONE. No software anywhere parses MYFMT; the parser exists only
in this lab.
Evidence : Level 0 -- the code exists. That is not evidence of anything.
Impact : Out-of-bounds heap write, length and contents attacker-controlled,
allocation size attacker-influenced through the count field.
Not shown : No control-flow hijack demonstrated. No exploit developed. No
hosting process exists in which to assess heap state.
Severity : None. This is a bug in a teaching artefact.
Confidence : Certain.
Step 7.3 Sit with that for a moment¶
You have a fully-controlled heap out-of-bounds write, with attacker control of both the length and the contents, adjacent to an allocation whose size class the attacker also chooses. That is, on paper, one of the strongest primitive classes there is.
Its severity is none. Nothing reaches it.
This is the chapter's thesis in a form you cannot argue with, because you built both halves of it yourself. Reachability, not mechanism, is what makes a bug a vulnerability. §1.3, §3.9, §5.7.
Step 7.4 Now make it hypothetical, carefully¶
Write one paragraph: if this parser were the native backend of a ContentProvider on a shipping
device, what would you need to establish before claiming a severity? Your list should include at
minimum:
- Which process hosts it, and what privilege that process has.
- Whether an app with no permissions can reach the provider.
- What the shipped build's mitigations are — CFI,
_FORTIFY_SOURCE, RELRO, PAC — verified from the binary, not assumed from AOSP. - What the SELinux domain permits, because a corruption primitive inside a domain that can do nothing is worth much less.
- What the allocator would place after your chunk. 19-Memory §3.8 is the reference, including its measured finding that Scudo on Android has no quarantine and a freed block comes straight back at the same address.
Notice that none of those requires writing an exploit, and that all of them are things a vendor's response team would ask.
Success criterion for Part 7: a verdict block, and the hypothetical paragraph with at least five things you would need to establish.
Part 8 — Fix it, and prove the fix¶
Step 8.1 Write the fix¶
Add the check you deleted. Two details that are not pedantry:
/* >= and not >, because one byte of the destination is reserved for the
terminator. Fixing this with > stops the 223-byte overflow and leaves a
one-byte NUL overflow behind -- which is not a lesser bug, it is a famous
one. */
if (klen >= KEY_MAX) {
myfmt_free(out);
return MYFMT_E_KEY;
}
And reject, do not clamp. if (klen > 31) klen = 31; also stops the overflow and is the wrong
fix: it silently accepts a malformed blob and produces a truncated key that the rest of the system
treats as legitimate. That converts a memory-safety bug into a parser differential — a real pattern
in shipped "fixes", and 10-APK-Internals §18 owns what that class
costs.
Step 8.2 Verify properly¶
Three tests, in increasing strength. Most people stop after the first, and the first proves almost nothing.
# host -- 1. the crashing input. Proves you patched THAT INPUT.
./fuzz_myfmt_fixed findings/current.bin
# host -- 2. every crasher you built by hand, including the UBSan-only ones.
for f in c1-*.bin c2-*.bin c3-*.bin; do
./fuzz_myfmt_fixed "$f" > /dev/null 2> "$f.log"
echo "$f: exit=$? sanitizer-lines=$(grep -cE 'runtime error|Sanitizer' "$f.log")"
done
# host -- 3. the WHOLE campaign again, same PRNG seed, same seed file.
# Proves the CLASS is gone.
./fuzz_myfmt_fixed -m 200000 1234 seed-one.bin findings-fixed/ 2>&1 | tee fixed.log
grep -cE 'runtime error|Sanitizer' fixed.log # expect 0
Test 3 is the one that matters. A fix that special-cased klen == 58 would pass test 1 and fail test
3.
For reference, the chapter's fixed ACFG parser produced: no fault on the campaign reproducer, zero sanitizer lines on all four hand-built crashers including the two UBSan-only ones, and a complete 200,000-execution campaign from the identical PRNG seed with zero sanitizer lines in the log.
Step 8.3 What the clean run does not prove¶
Write this down, because it is the habit that matters:
The fixed parser survived 200,000 executions from one seed with one PRNG seed under ASan and UBSan. That is a statement about this corpus, this mutator, this detector set and this clock. It is not evidence that the parser is correct, and it is not evidence that no other defect exists. Fuzzing produces evidence of presence only.
Success criterion for Part 8: all three tests pass, and you have written the paragraph above in your own words.
Success criteria¶
- A parser you wrote, verified correct on valid input first.
- Exactly one planted bug, with
GROUND-TRUTH.mdwritten before you started triaging. - Written predictions, made before building, about what the bug does at different header values.
- A harness that passes all five rules and compiles with
-Werror. - The planted-
abort()check performed, and passed. - A campaign that produced a crash, with a saved reproducer and the execution index.
- A hand-written triage produced before you ran
triage-asan.py, and a note of every place the two disagreed. - Your three predicted inputs run, with exit codes and log contents recorded — including at least one that exits 0 while still being a bug.
- A reachability verdict block, correctly reading none.
- A fix verified by all three tests, including the full re-run.
- The written statement of what the clean run does not prove.
Extension exercises¶
- Swap parsers with someone else. They plant a bug in theirs, you plant one in yours, neither sees the other's ground truth. Triage each other's crashes and compare verdicts. This is the closest thing to real conditions you can arrange, and it is where you find out how much of your confidence was borrowed from knowing the answer.
- Plant a use-after-free instead, and notice how much harder the reachability reasoning is: the window's width becomes part of the assessment, and the report tells you nothing about it.
- Add a CRC over the item area. Run the campaign again without touching the harness, and watch the coverage flatline. Then solve it in the harness and watch it recover. That contrast is §3.4's checksum problem, felt rather than read.
- Build a coverage report with
-fprofile-instr-generate -fcoverage-mappingand runllvm-cov show. Find a line with zero executions and work out whether it is unreachable through this entry point or just unexercised by your corpus. That distinction is the whole of §7.3. - Compare gcc and clang on the same code. Does the same input produce the same report? The same line numbers? The same classification? Toolchain differences in triage output are real and worth having seen once.
Where to go next¶
Lab 03 — Triage at scale, and the report takes a pile of artefacts rather than one, and ends with the disclosure document.