The bug that only shows on exact bytes
A settings file says motto="be kind and forgets the closing quote. Your reader copes in every test you wrote.
But it is reading one byte beyond its input, and only a tool that hands it exactly that many bytes will ever see it.
The one rule
Warning
Fuzz only code you wrote or are asked to test, on your own lab machine. Testing somebody else's system needs their written permission. In the UK the Computer Misuse Act 1990 applies.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsBy the end of this lesson
Note
I can write a harness that lets libFuzzer test one C function.
Key words
| Word | What it means | Example |
|---|---|---|
| Harness | the small function that passes fuzz input to your code | |
| libFuzzer | clang's built-in fuzzer that calls a harness | -fsanitize=fuzzer |
| Entry point | the function the fuzzer calls for every input | LLVMFuzzerTestOneInput |
| Crash file | the input libFuzzer saves when the code fails | |
| Out-of-bounds read | reading memory past the end of a buffer |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsA harness turns bytes into one call
AFL++ in lesson 1 ran a whole program and fed it a file. libFuzzer works inside the program instead: it calls one function of yours thousands of times a second.
First write the function under test, read_value, and its three tests. It copies the value of a setting, with or without quotes.
Write the setting reader
mkdir -p ~/fuzz/value && cd ~/fuzz/value && cat > value.c <<'END'
#include <stddef.h>
#include <string.h>
int read_value(const char *line, size_t len, char out[32]) {
const char *eq = memchr(line, '=', len);
if (eq == NULL) return -1;
size_t start = (size_t)(eq - line) + 1;
size_t n = 0;
if (start < len && line[start] == '"') {
start++;
while (start + n <= len && line[start + n] != '"') n++;
} else {
n = len - start;
}
if (n > 31) return -1;
memcpy(out, line + start, n);
out[n] = 0;
return (int)n;
}
ENDShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write three tests and run them
cd ~/fuzz/value && cat > test_value.c <<'END'
#include <stdio.h>
#include <string.h>
int read_value(const char *line, size_t len, char out[32]);
int main(void) {
const char *cases[] = {"name=ann", "motto=\"be kind\"", "no setting here"};
char out[32];
for (int i = 0; i < 3; i++) {
int n = read_value(cases[i], strlen(cases[i]), out);
printf("%s -> %d %s\n", cases[i], n, n < 0 ? "" : out);
}
return 0;
}
END
gcc -Wall -g -o test_value value.c test_value.c && ./test_valueShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsOne function, called for every input
A libFuzzer harness is a function named LLVMFuzzerTestOneInput. It receives a pointer and a size, calls the code under test and returns 0.
Keep it like this: no exit, no saved state between calls, no printing, and hand over the bytes exactly as given. Build it with -fsanitize=fuzzer,address.
Write the harness
cd ~/fuzz/value && cat > fuzz_value.c <<'END'
#include <stddef.h>
#include <stdint.h>
int read_value(const char *line, size_t len, char out[32]);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
char out[32];
read_value((const char *)data, size, out);
return 0;
}
ENDShown here, not run. Press Start lab to type it into your own lab’s terminal.
Build the fuzzer
cd ~/fuzz/value && clang -g -fsanitize=fuzzer,address -o fuzz-value value.c fuzz_value.c && file fuzz-value | cut -d, -f1Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Try it: a harness sorts each result
import random
def read_value(line):
if "=" not in line:
raise ValueError("no setting")
value = line.split("=", 1)[1]
if value[0] == '"':
return value[1:].split('"')[0]
return value
def harness(data):
try:
read_value(data)
return "ok"
except ValueError:
return "refused"
except Exception as error:
return "crash: " + type(error).__name__
rng = random.Random(3)
seen = {}
for _ in range(300):
data = "".join(rng.choice('ab="') for _ in range(rng.randrange(6)))
verdict = harness(data)
if verdict not in seen:
seen[verdict] = data
print(repr(data), "->", verdict)
# Change value[0] == '"' to value.startswith('"'). Which verdicts are left?
Make a free account to save your work and track your progress.
Fuzz it for up to a minute
cd ~/fuzz/value && rm -f crash-* && DEBUGINFOD_URLS= ./fuzz-value -seed=1 -max_total_time=60 > fuzz.log 2>&1; grep -E 'of size|SUMMARY|Test unit' fuzz.logShown here, not run. Press Start lab to type it into your own lab’s terminal.
Look at the bytes it saved
cd ~/fuzz/value && od -c crash-*Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Run the crash file again
cd ~/fuzz/value && DEBUGINFOD_URLS= ./fuzz-value crash-* 2>&1 | grep -E 'Running|SUMMARY'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsA common mistake
Warning
Many people copy the fuzz bytes into a string and add a zero at the end, to make the harness "safe". That hides this exact bug. Pass the bytes and the size as they come, unless the real caller always adds a zero.
Stop at the end, not one past it
The quoted loop tests start + n <= len, so it looks at the byte at index len, which is not part of the input. The test must be <.
Fix it and run the crash file again. Then fuzz for another 30 seconds to see whether anything else turns up.
Fix the loop and replay the crash
cd ~/fuzz/value && sed -i 's/start + n <= len/start + n < len/' value.c && grep -n 'start + n' value.c && clang -g -fsanitize=fuzzer,address -o fuzz-value value.c fuzz_value.c && DEBUGINFOD_URLS= ./fuzz-value crash-* 2>&1 | grep -E 'Running|SUMMARY|Executed'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Fuzz the fixed code for 30 seconds
cd ~/fuzz/value && DEBUGINFOD_URLS= ./fuzz-value -seed=2 -max_total_time=30 > fuzz2.log 2>&1; echo "exit $?"; grep -c SUMMARY fuzz2.logShown here, not run. Press Start lab to type it into your own lab’s terminal.
The crash file becomes a regression input
Move the crash file into regress with a name that says what it is. Given files instead of a folder to fuzz, the fuzzer runs each once and stops.
That is how the team keeps this bug fixed: the same command runs in every build.
Keep the input and replay the folder
cd ~/fuzz/value && mkdir -p regress && mv crash-* regress/unclosed-quote && DEBUGINFOD_URLS= ./fuzz-value regress/* 2>&1 | grep -E 'Running|NOTE'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Worked example: weak and good harnesses
| Harness does | Why it matters | Better |
|---|---|---|
| Adds a zero to the bytes | Hides reads past the end | Pass data and size as given |
| Calls exit on bad input | The fuzzer stops | Return 0 |
| Keeps a global counter | A crash cannot be replayed | No state between calls |
| Prints every input | Thousands of times slower | Print nothing |
The cells students fill in are left blank in this preview.
Assignment: sort what a harness sees
A harness must tell an input the code rightly refused from an input that broke it. Write two functions.
verdict(target, data) calls target(data). Return "ok" if it returns normally, "rejected" if it raises ValueError (a refusal the code meant), and "crash" if it raises any other exception.
tally(target, inputs) returns a dictionary with the keys "ok", "rejected" and "crash", each counting how many of the inputs got that verdict. All three keys are always present.
def verdict(target, data):
return "ok"
def tally(target, inputs):
return {}
Make a free account to save your work and track your progress.
Exit quiz
Have a go