Conceptcore
Fuzz testing
Also called fuzzing, fuzz test, fuzzer, coverage-guided fuzzing.
Fuzz testing runs a program on a large number of generated or mutated inputs and watches for crashes, hangs and failed checks. Coverage-guided fuzzers keep the inputs that reach unseen code.
- Applies to
- core-languages
Idea
A fuzz test runs a program on a large number of inputs that no person chose and checks one thing: that the program does not crash or hang. The study of Miller, Fredriksen and So began with line noise. One of them used a dial-up line in a storm, and the spurious characters on the line crashed common UNIX utilities.1 They then fed random characters to about 90 utilities on seven versions of UNIX and crashed more than 24 percent of them.1
Miller lists three features of classic fuzz testing. The input is random. The test uses no model of the program, so it is a black box test. And the oracle is that the program must not crash or hang. It does not need to give a sensible answer, and it may exit quietly.2 The last feature is the key. A unit test needs an expected output for each input. A fuzz test needs none, so a machine can make the inputs.
The parser below reads records of the form [tag][length][value]. It does not check that the length byte exists. A blind fuzzer with a fixed seed finds the bug on its first input. A ValueError is the documented way to reject bad input, so the harness ignores it. Any other exception is a bug.
def xorshift32(state):
state ^= (state << 13) & 0xFFFFFFFF
state ^= state >> 17
state ^= (state << 5) & 0xFFFFFFFF
return state
def parse(data):
"""Reads records of the form [tag][length][value]."""
records = []
i = 0
while i < len(data):
tag = data[i]
length = data[i + 1] # bug: no check that the length byte exists
records.append((tag, data[i + 2 : i + 2 + length]))
i += 2 + length
return records
state = 2463534242
crashes = {}
for run in range(1, 1001):
state = xorshift32(state)
data = bytearray()
for _ in range(state % 9): # lengths 0 to 8
state = xorshift32(state)
data.append(state & 0xFF)
try:
parse(bytes(data))
except ValueError:
pass # a documented rejection is not a bug
except Exception as e:
name = type(e).__name__
if name not in crashes:
print(f"run {run}: {name}: {e} on {bytes(data)!r}")
crashes[name] = crashes.get(name, 0) + 1
print("crashes:", crashes)
run 1: IndexError: index out of range on b'z'
crashes: {'IndexError': 115}
The fuzzer knows nothing about the format. It found the bug because short inputs are common in its output, and every input of one byte crashes the parser.
How it works
A fuzzer has five parts: a target, a source of inputs, an oracle, a corpus and a minimizer.
The target. Miller's tools fed a random stream to the standard input of each utility, and a second tool, ptyjig, drove the utilities that need a terminal.1 In-process fuzzers call a function instead. libFuzzer calls LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) many times in one process. The target must accept any input, must not call exit, and must be deterministic and fast.4 A Go fuzz test is a function FuzzXxx(f *testing.F) that calls f.Fuzz with a function of *testing.T and the fuzzing arguments.5 In Rust, cargo fuzz generates a target whose body is a fuzz_target! closure over a byte slice.6
The inputs. Miller's fuzz program wrote random characters. Options chose printable characters, control characters or the NUL character, and a seed for the random generator made the tests repeatable.1 Blind random bytes rarely get past the first check of a structured format. A mutation fuzzer starts from a set of valid inputs, the seed corpus, and changes them. AFL first applies deterministic changes: bit flips, the addition and subtraction of small integers, and the insertion of interesting values such as 0, 1 and INT_MAX. Later it stacks random changes and splices test cases together.3
Coverage guidance. The compiler adds code at each branch. AFL's instrumentation counts each pair of branch source and branch destination in a 64 kB map shared with the fuzzer.3 When a mutated input makes a pair that no earlier input made, the fuzzer adds the input to its queue as a starting point for more mutation. An input with no unseen pair is discarded.3 libFuzzer gets the same information from LLVM's SanitizerCoverage and mutates its corpus to maximize the code coverage.4 The Go fuzzer also keeps an input only when it expands the coverage.5
The demonstration below shows why this matters. The bug needs the four bytes FUZZ in order. The target calls hit at each branch, as a compiler pass would. Both fuzzers change one to four bytes of an input from the corpus, with the same seed. The blind fuzzer always mutates the seed. The guided fuzzer also mutates each input that reached a branch not reached before.
class Rng:
def __init__(self, seed):
self.state = seed
def next(self):
y = self.state
y ^= (y << 13) & 0xFFFFFFFF
y ^= y >> 17
y ^= (y << 5) & 0xFFFFFFFF
self.state = y
return y
def target(data, hit):
"""The bug needs the bytes F, U, Z, Z in order. hit(n) marks branch n as reached."""
if len(data) > 0 and data[0] == ord("F"):
hit(1)
if len(data) > 1 and data[1] == ord("U"):
hit(2)
if len(data) > 2 and data[2] == ord("Z"):
hit(3)
if len(data) > 3 and data[3] == ord("Z"):
raise RuntimeError("reached the bug")
def mutate(rng, data):
"""Sets one to four random bytes of a 4-byte input to random values."""
data = bytearray(data)
for _ in range(1 + rng.next() % 4):
data[rng.next() % 4] = rng.next() & 0xFF
return bytes(data)
def fuzz(guided, runs=200_000):
rng = Rng(2463534242)
corpus = [b"AAAA"] # the seed corpus
seen = set()
for run in range(1, runs + 1):
data = mutate(rng, corpus[rng.next() % len(corpus)])
reached = set()
try:
target(data, reached.add)
except RuntimeError:
return f"crash on run {run} with {data!r}, corpus of {len(corpus)}"
if guided and not reached <= seen: # new coverage: keep the input
seen |= reached
corpus.append(data)
return f"no crash in {runs} runs, corpus of {len(corpus)}"
print("blind: ", fuzz(guided=False))
print("guided:", fuzz(guided=True))
blind: no crash in 200000 runs, corpus of 1
guided: crash on run 21646 with b'FUZZ', corpus of 4
The blind fuzzer must guess all four bytes at once. The guided fuzzer guesses one byte at a time, because the corpus keeps each step: F, then FU, then FUZ. AFL's documentation reports the same effect on GNU patch. Blind fuzzing reached 265 edges, guidance by edge coverage reached 2,070, and AFL's own model reached 2,597.3
The oracle. Miller counted a crash when the program dumped core and a hang when it ran with no output for a long time.1 A coverage-guided fuzzer runs the target in its own process, so it sees a crash as a signal, an uncaught exception or a panic. Go counts a panic, a call to t.Fail, an os.Exit and a run that takes more than one second as failures.5 Many memory errors in C and C++ do not crash at once. libFuzzer is usually combined with AddressSanitizer or UndefinedBehaviorSanitizer, which turn an out-of-bounds read or an overflow into an immediate report.4
The corpus. The fuzzer saves the inputs that reach code not reached before. AFL keeps its queue compact: each input in it shows a behaviour that the other inputs do not.3 The corpus is also a regression test. libFuzzer re-runs a list of files with no fuzzing when it gets files instead of directories, and the documentation suggests this mode for continuous integration.4 Plain go test runs each seed corpus entry of a fuzz test once, as a unit test. Only go test -fuzz=FuzzName generates inputs.5 Go writes each failing input to testdata/fuzz/FuzzName/, and from then on plain go test runs it.5
Minimization. A crashing input from a fuzzer is often long and full of noise. Go minimizes a failing input to the smallest and most readable value that still fails.5 AFL trims each input in its queue by removing blocks of data that do not change the coverage, but it keeps crashing inputs exactly as it found them. The tool afl-tmin shrinks them on request.3 This step is the shrinking of property-based testing, applied to bytes.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Library | |
| C++ | Library | |
| Java | Library | |
| C | Library | |
| C# | Library | |
| JavaScript | Library | |
| TypeScript | Library | |
| Go | Native | |
| Rust | Library | |
| Kotlin | Library | The Kotlin standard library has no fuzzer. Alternative: Jazzer, a coverage-guided fuzzer for the JVM, runs Kotlin code as it runs Java code. |
| SQL | Does not apply | A query is fuzzed through the database engine that runs it. |
| Bash | Idiom | Bash has no fuzzer. Alternative: A pipeline from a generator of random input to the program under test, as in Miller's study. |
| PowerShell | Idiom | PowerShell has no fuzzer in the language or its core modules. Alternative: A loop that generates input with Get-Random -SetSeed and passes it to the command under test. |
| HTML | Does not apply | Markup is fuzzed through the browser that renders it. |
| CSS | Does not apply | Style rules are fuzzed through the browser that renders them. |
| Regular expressions | Does not apply | A pattern is fuzzed through the engine that runs it. |
The examples run the seed corpus only, with a fixed list of inputs. They show the fixed parser, and they show how each language reacts to the original bug.
| Language | Verdict | Form |
|---|---|---|
| Python | library | Atheris, a coverage-guided fuzzer based on libFuzzer8 |
| JavaScript | library | Jazzer.js, a coverage-guided fuzzer for Node.js based on libFuzzer10 |
| TypeScript | library | Jazzer.js, as for JavaScript10 |
| Java | library | Jazzer, a coverage-guided fuzzer for the JVM, with a regression mode under JUnit9 |
| C | library | libFuzzer in Clang: -fsanitize=fuzzer, with AddressSanitizer; AFL and AFL++4312 |
| C++ | library | as for C; the target is extern "C"4 |
| C# | library | SharpFuzz, which runs .NET code under afl-fuzz11 |
| Go | native | func FuzzXxx(f *testing.F) in a test file, f.Add for seeds, go test -fuzz5 |
| Rust | library | cargo fuzz with fuzz_target!; it needs the nightly compiler67 |
| Kotlin | library | Jazzer, as for Java9 |
| PowerShell | idiom | a loop that pipes generated input to a command, as Miller did with UNIX utilities1 |
| Bash | idiom | a pipeline from a generator to the program under test, as fuzz 100000 -o outfile | deqn in Miller's report1 |
| SQL | n/a | a query is fuzzed through the database engine that runs it |
| Regex | n/a | a pattern is fuzzed through the engine that runs it |
| HTML/CSS | n/a | markup and style rules are fuzzed through the browser that renders them |
Go is the only tier 1 language with a fuzzer in its standard toolchain. A Go fuzz test lives in a _test.go file, takes only the argument types string, []byte, the integer and float types, rune and bool, and needs each seed to have the same types in the same order.5 In C and C++, the fuzz target does not depend on libFuzzer, so the same function can run under AFL.4 The original authors of libFuzzer have stopped active work on it, but it still receives fixes for important bugs.4 AFL is no longer updated, and its home page points to the fork AFL++.12
The languages also differ in what the bug does. Python, Java, C#, Go and Rust check each index, so the missing check is an exception or a panic, and the fuzzer sees it. C and C++ read past the end with no error, so the bug is found only with a sanitizer. JavaScript returns undefined for an index past the end of a typed array, so the bug gives a wrong result and no crash at all.
def parse(data: bytes) -> list[tuple[int, bytes]]:
"""Reads records of the form [tag][length][value]."""
records = []
i = 0
while i < len(data):
if i + 2 > len(data):
raise ValueError(f"truncated header at offset {i}")
tag, length = data[i], data[i + 1]
if i + 2 + length > len(data):
raise ValueError(f"truncated value at offset {i}")
records.append((tag, data[i + 2 : i + 2 + length]))
i += 2 + length
return records
def encode(records):
return b"".join(bytes([tag, len(value)]) + value for tag, value in records)
def fuzz_one(data: bytes) -> str:
"""The fuzz target: any exception other than ValueError is a bug."""
try:
records = parse(data)
except ValueError as e:
return f"rejected: {e}"
assert encode(records) == data, "accepted input does not encode back to itself"
return f"records={len(records)}"
# The seed corpus: valid inputs, plus the failing inputs that fuzzing found.
SEEDS = [b"", b"\x01\x02hi", b"\x01\x02hi\x02\x00", b"z", b"~\xe1"]
for seed in SEEDS:
print(f"{seed.hex(' ') or '(empty)'}: {fuzz_one(seed)}")
print(f"seed corpus: {len(SEEDS)} inputs passed")
(empty): records=0
01 02 68 69: records=1
01 02 68 69 02 00: records=2
7a: rejected: truncated header at offset 0
7e e1: rejected: truncated value at offset 0
seed corpus: 5 inputs passed
The original parser, run on the same corpus, stops at the input of one byte.
This code raises IndexError, on purpose.
def parse(data: bytes) -> list[tuple[int, bytes]]:
records = []
i = 0
while i < len(data):
tag = data[i]
length = data[i + 1] # no check that the length byte exists
records.append((tag, data[i + 2 : i + 2 + length]))
i += 2 + length
return records
SEEDS = [b"", b"\x01\x02hi", b"\x01\x02hi\x02\x00", b"z", b"~\xe1"]
for seed in SEEDS:
print(f"{seed.hex(' ') or '(empty)'}: records={len(parse(seed))}")
- Verdict: library. Atheris is a coverage-guided fuzzer for Python, based on libFuzzer. It also fuzzes native extensions of CPython.
- Python checks every index, so the missing check raises
IndexErrorand a fuzzer sees it. A slice never raises, sodata[i + 2 : i + 2 + length]returns a short value with no error. Only the round-trip assertion infuzz_onecatches that bug. fuzz_onelets every exception exceptValueErrorescape.ValueErroris the documented way to reject bad input.- The corpus holds the two inputs that fuzzing found,
7aand7e e1. They now run on each test run as regression tests.
#include <cstddef>
#include <cstdint>
#include <expected>
#include <format>
#include <print>
#include <span>
#include <string>
#include <string_view>
#include <vector>
struct Record {
std::uint8_t tag;
std::span<const std::uint8_t> value;
};
// Reads records of the form [tag][length][value]; a truncated input is an error value.
std::expected<std::vector<Record>, std::string> parse(std::span<const std::uint8_t> data) {
std::vector<Record> records;
std::size_t i = 0;
while (i < data.size()) {
if (data.size() - i < 2) {
return std::unexpected(std::format("truncated header at offset {}", i));
}
std::size_t length = data[i + 1];
if (data.size() - i - 2 < length) {
return std::unexpected(std::format("truncated value at offset {}", i));
}
records.push_back({data[i], data.subspan(i + 2, length)});
i += 2 + length;
}
return records;
}
extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) {
auto result = parse({data, size});
if (result) {
std::println("records={}", result->size());
} else {
std::println("rejected: {}", result.error());
}
return 0;
}
int main() {
using namespace std::string_view_literals;
const std::string_view seeds[] = {""sv, "\x01\x02hi"sv, "\x01\x02hi\x02\x00"sv, "z"sv, "~\xe1"sv};
for (std::string_view seed : seeds) {
std::vector<std::uint8_t> copy(seed.begin(), seed.end());
LLVMFuzzerTestOneInput(copy.data(), copy.size());
}
std::println("seed corpus: {} inputs passed", std::size(seeds));
}
records=0
records=1
records=2
rejected: truncated header at offset 0
rejected: truncated value at offset 0
seed corpus: 5 inputs passed
std::vector::at checks the index and throws std::out_of_range. With at, the original bug ends the program with an uncaught exception instead of a silent read.
This code fails on purpose. The output below is the error.
#include <cstddef>
#include <cstdint>
#include <print>
#include <string_view>
#include <vector>
// Counts the records of the form [tag][length][value].
std::size_t parse(const std::vector<std::uint8_t>& data) {
std::size_t count = 0;
std::size_t i = 0;
while (i < data.size()) {
std::size_t length = data.at(i + 1); // at() checks the index and throws
count++;
i += 2 + length;
}
return count;
}
int main() {
using namespace std::string_view_literals;
const std::string_view seeds[] = {""sv, "\x01\x02hi"sv, "\x01\x02hi\x02\x00"sv, "z"sv, "~\xe1"sv};
for (std::string_view seed : seeds) {
std::println("records={}", parse({seed.begin(), seed.end()}));
}
}
- Verdict: library. libFuzzer and AFL fuzz C++ code through the same
extern "C"entry point as in C. std::spanviews the bytes with their size.operator[]on a span or a vector does not check the index, so a fuzz build needs AddressSanitizer, as in C.std::expectedreturns either the records or an error message, so the parser needs no exceptions. The target prints both cases and never throws.subspangives a view of the value with no copy.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
public class Main {
record Rec(int tag, byte[] value) {}
/** Reads records of the form [tag][length][value]. */
static List<Rec> parse(byte[] data) {
List<Rec> records = new ArrayList<>();
int i = 0;
while (i < data.length) {
if (data.length - i < 2) {
throw new IllegalArgumentException("truncated header at offset " + i);
}
int tag = Byte.toUnsignedInt(data[i]);
int length = Byte.toUnsignedInt(data[i + 1]); // byte is signed in Java
if (data.length - i - 2 < length) {
throw new IllegalArgumentException("truncated value at offset " + i);
}
records.add(new Rec(tag, Arrays.copyOfRange(data, i + 2, i + 2 + length)));
i += 2 + length;
}
return records;
}
/** The fuzz target: any exception other than IllegalArgumentException is a bug. */
static String fuzzOne(byte[] data) {
try {
return "records=" + parse(data).size();
} catch (IllegalArgumentException e) {
return "rejected: " + e.getMessage();
}
}
public static void main(String[] args) {
byte[][] seeds = {
{}, {1, 2, 'h', 'i'}, {1, 2, 'h', 'i', 2, 0}, {'z'}, {'~', (byte) 0xe1},
};
HexFormat hex = HexFormat.ofDelimiter(" ");
for (byte[] seed : seeds) {
String shown = seed.length == 0 ? "(empty)" : hex.formatHex(seed);
System.out.println(shown + ": " + fuzzOne(seed));
}
System.out.println("seed corpus: " + seeds.length + " inputs passed");
}
}
(empty): records=0
01 02 68 69: records=1
01 02 68 69 02 00: records=2
7a: rejected: truncated header at offset 0
7e e1: rejected: truncated value at offset 0
seed corpus: 5 inputs passed
The original parser throws ArrayIndexOutOfBoundsException on the input of one byte.
This code raises ArrayIndexOutOfBoundsException, on purpose.
public class Main {
/** Counts the records of the form [tag][length][value]. */
static int parse(byte[] data) {
int count = 0;
int i = 0;
while (i < data.length) {
int length = Byte.toUnsignedInt(data[i + 1]); // no check that the length byte exists
count++;
i += 2 + length;
}
return count;
}
public static void main(String[] args) {
byte[][] seeds = {
{}, {1, 2, 'h', 'i'}, {1, 2, 'h', 'i', 2, 0}, {'z'}, {'~', (byte) 0xe1},
};
for (byte[] seed : seeds) {
System.out.println("records=" + parse(seed));
}
}
}
- Verdict: library. Jazzer is a coverage-guided fuzzer for the JVM, based on libFuzzer. Under JUnit, it runs saved inputs in a regression mode and generates inputs in a fuzzing mode.
- Java checks every array index, so the bug is an exception that a fuzzer sees.
byteis signed in Java, so a length byte of0xe1reads as -31.Byte.toUnsignedIntgives 225. Without it, the length -31 passes the checkdata.length - i - 2 < length, andcopyOfRangethrowsIllegalArgumentException. That is the type of the documented rejection, so the harness would hide the bug.IllegalArgumentExceptionis the documented rejection. Any other exception escapes fromfuzzOne.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Counts the records of the form [tag][length][value]; returns -1 for a truncated input. */
static int parse(const uint8_t *data, size_t size, size_t *bad_offset) {
int count = 0;
size_t i = 0;
while (i < size) {
if (size - i < 2) {
*bad_offset = i;
return -1;
}
size_t length = data[i + 1];
if (size - i - 2 < length) {
*bad_offset = i;
return -1;
}
count++;
i += 2 + length;
}
return count;
}
/* The fuzz target, with the signature that libFuzzer calls. */
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
size_t bad = 0;
int count = parse(data, size, &bad);
if (count < 0) {
printf("rejected at offset %zu\n", bad);
} else {
printf("records=%d\n", count);
}
return 0;
}
/* Our own main runs the seed corpus once; -fsanitize=fuzzer would supply a main that fuzzes. */
int main(void) {
static const struct { const char *bytes; size_t size; } seeds[] = {
{"", 0}, {"\x01\x02hi", 4}, {"\x01\x02hi\x02\x00", 6}, {"z", 1}, {"~\xe1", 2},
};
size_t n = sizeof seeds / sizeof seeds[0];
for (size_t k = 0; k < n; k++) {
/* A heap copy of the exact size lets AddressSanitizer see a read past the end. */
uint8_t *copy = malloc(seeds[k].size > 0 ? seeds[k].size : 1);
if (copy == NULL) {
return 1;
}
memcpy(copy, seeds[k].bytes, seeds[k].size);
printf("seed %zu: ", k);
LLVMFuzzerTestOneInput(copy, seeds[k].size);
free(copy);
}
printf("seed corpus: %zu inputs passed\n", n);
return 0;
}
seed 0: records=0
seed 1: records=1
seed 2: records=2
seed 3: rejected at offset 0
seed 4: rejected at offset 0
seed corpus: 5 inputs passed
The original parser reads the length byte with no check. For the input z, it reads one byte past the end of the heap copy. With AddressSanitizer, the run stops with a heap-buffer-overflow report.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Counts the records of the form [tag][length][value]. */
static int parse(const uint8_t *data, size_t size) {
int count = 0;
size_t i = 0;
while (i < size) {
size_t length = data[i + 1]; /* no check that the length byte exists */
count++;
i += 2 + length;
}
return count;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
printf("records=%d\n", parse(data, size));
return 0;
}
int main(void) {
static const struct { const char *bytes; size_t size; } seeds[] = {
{"", 0}, {"\x01\x02hi", 4}, {"\x01\x02hi\x02\x00", 6}, {"z", 1}, {"~\xe1", 2},
};
for (size_t k = 0; k < sizeof seeds / sizeof seeds[0]; k++) {
uint8_t *copy = malloc(seeds[k].size > 0 ? seeds[k].size : 1);
if (copy == NULL) {
return 1;
}
memcpy(copy, seeds[k].bytes, seeds[k].size);
LLVMFuzzerTestOneInput(copy, seeds[k].size);
free(copy);
}
return 0;
}
- Verdict: library. libFuzzer comes with Clang.
clang -fsanitize=fuzzer,address target.clinks amainthat fuzzesLLVMFuzzerTestOneInput. The same target also builds for AFL. - The example has its own
main, which calls the target once for each seed and does no fuzzing. libFuzzer does the same when it gets a list of files instead of a directory. - Without a sanitizer, the read past the end usually returns some byte, and the program goes on. The seed corpus passes and the bug stays. Build fuzz targets and their regression runs with AddressSanitizer.
size - i < 2is the overflow-safe form ofi + 2 > size:iis never more thansize, so the subtraction cannot wrap.
using System;
using System.Collections.Generic;
static class Program
{
// Reads records of the form [tag][length][value].
static List<(byte Tag, byte[] Value)> Parse(ReadOnlySpan<byte> data)
{
var records = new List<(byte, byte[])>();
int i = 0;
while (i < data.Length)
{
if (data.Length - i < 2)
{
throw new FormatException($"truncated header at offset {i}");
}
byte tag = data[i];
int length = data[i + 1];
if (data.Length - i - 2 < length)
{
throw new FormatException($"truncated value at offset {i}");
}
records.Add((tag, data.Slice(i + 2, length).ToArray()));
i += 2 + length;
}
return records;
}
// The fuzz target: any exception other than FormatException is a bug.
static string FuzzOne(byte[] data)
{
try
{
return $"records={Parse(data).Count}";
}
catch (FormatException e)
{
return $"rejected: {e.Message}";
}
}
static void Main()
{
byte[][] seeds = [[], [1, 2, (byte)'h', (byte)'i'], [1, 2, (byte)'h', (byte)'i', 2, 0], [(byte)'z'], [(byte)'~', 0xe1]];
foreach (byte[] seed in seeds)
{
string shown = seed.Length == 0 ? "(empty)" : BitConverter.ToString(seed).Replace("-", " ").ToLowerInvariant();
Console.WriteLine($"{shown}: {FuzzOne(seed)}");
}
Console.WriteLine($"seed corpus: {seeds.Length} inputs passed");
}
}
(empty): records=0
01 02 68 69: records=1
01 02 68 69 02 00: records=2
7a: rejected: truncated header at offset 0
7e e1: rejected: truncated value at offset 0
seed corpus: 5 inputs passed
The original parser throws IndexOutOfRangeException on the input of one byte.
This code raises IndexOutOfRangeException, on purpose.
using System;
static class Program
{
// Counts the records of the form [tag][length][value].
static int Parse(ReadOnlySpan<byte> data)
{
int count = 0;
int i = 0;
while (i < data.Length)
{
int length = data[i + 1]; // no check that the length byte exists
count++;
i += 2 + length;
}
return count;
}
static void Main()
{
byte[][] seeds = [[], [1, 2, (byte)'h', (byte)'i'], [1, 2, (byte)'h', (byte)'i', 2, 0], [(byte)'z'], [(byte)'~', 0xe1]];
foreach (byte[] seed in seeds)
{
Console.WriteLine($"records={Parse(seed)}");
}
}
}
- Verdict: library. SharpFuzz runs .NET code under afl-fuzz.
ReadOnlySpan<byte>checks each index, andSlicechecks its range, so an error in the bounds is an exception and not a silent read.byteis unsigned in C#, so the length byte needs no conversion.FormatExceptionis the documented rejection. Any other exception escapes fromFuzzOne.
// Reads records of the form [tag][length][value].
function parse(data) {
const records = [];
let i = 0;
while (i < data.length) {
if (data.length - i < 2) {
throw new RangeError(`truncated header at offset ${i}`);
}
const tag = data[i];
const length = data[i + 1];
if (data.length - i - 2 < length) {
throw new RangeError(`truncated value at offset ${i}`);
}
records.push({ tag, value: data.subarray(i + 2, i + 2 + length) });
i += 2 + length;
}
return records;
}
// The fuzz target: any exception other than RangeError is a bug.
function fuzzOne(data) {
try {
return `records=${parse(data).length}`;
} catch (e) {
if (!(e instanceof RangeError)) throw e;
return `rejected: ${e.message}`;
}
}
const hex = (data) => Array.from(data, (b) => b.toString(16).padStart(2, "0")).join(" ") || "(empty)";
const seeds = [[], [1, 2, 0x68, 0x69], [1, 2, 0x68, 0x69, 2, 0], [0x7a], [0x7e, 0xe1]].map((s) => Uint8Array.from(s));
for (const seed of seeds) {
console.log(`${hex(seed)}: ${fuzzOne(seed)}`);
}
console.log(`seed corpus: ${seeds.length} inputs passed`);
(empty): records=0
01 02 68 69: records=1
01 02 68 69 02 00: records=2
7a: rejected: truncated header at offset 0
7e e1: rejected: truncated value at offset 0
seed corpus: 5 inputs passed
The original parser does not crash in JavaScript. An index past the end of a typed array gives undefined, 2 + undefined is NaN, and the loop ends. The bad inputs are accepted as records with empty values.
This code runs but gives a wrong answer on purpose.
// Reads records of the form [tag][length][value], with no length checks.
function parse(data) {
const records = [];
let i = 0;
while (i < data.length) {
const tag = data[i];
const length = data[i + 1]; // undefined past the end: no exception
records.push({ tag, value: data.subarray(i + 2, i + 2 + length) });
i += 2 + length;
}
return records;
}
const seeds = [[0x7a], [0x7e, 0xe1]].map((s) => Uint8Array.from(s));
for (const seed of seeds) {
console.log(JSON.stringify(parse(seed), (key, v) => (v instanceof Uint8Array ? Array.from(v) : v)));
}
[{"tag":122,"value":[]}]
[{"tag":126,"value":[]}]
- Verdict: library. Jazzer.js is a coverage-guided fuzzer for Node.js, based on libFuzzer.
- A fuzzer that waits for a crash finds nothing here. Write the checks in the parser and add an oracle to the target, such as a round trip.
subarrayclamps its arguments to the length of the array and treatsNaNas 0, so a bad length gives a short or empty view with no error.RangeErroris the documented rejection.fuzzOnethrows again any other error.
type Entry = { tag: number; value: Uint8Array };
type ParseResult = { ok: true; records: Entry[] } | { ok: false; error: string };
// Reads records of the form [tag][length][value]; a truncated input is an error value.
function parse(data: Uint8Array): ParseResult {
const records: Entry[] = [];
let i = 0;
while (i < data.length) {
if (data.length - i < 2) {
return { ok: false, error: `truncated header at offset ${i}` };
}
const tag = data[i]!;
const length = data[i + 1]!;
if (data.length - i - 2 < length) {
return { ok: false, error: `truncated value at offset ${i}` };
}
records.push({ tag, value: data.subarray(i + 2, i + 2 + length) });
i += 2 + length;
}
return { ok: true, records };
}
// The fuzz target: it must not throw for any input.
function fuzzOne(data: Uint8Array): string {
const result = parse(data);
return result.ok ? `records=${result.records.length}` : `rejected: ${result.error}`;
}
const hex = (data: Uint8Array): string =>
Array.from(data, (b) => b.toString(16).padStart(2, "0")).join(" ") || "(empty)";
const seeds: Uint8Array[] = [[], [1, 2, 0x68, 0x69], [1, 2, 0x68, 0x69, 2, 0], [0x7a], [0x7e, 0xe1]].map((s) =>
Uint8Array.from(s),
);
for (const seed of seeds) {
console.log(`${hex(seed)}: ${fuzzOne(seed)}`);
}
console.log(`seed corpus: ${seeds.length} inputs passed`);
(empty): records=0
01 02 68 69: records=1
01 02 68 69 02 00: records=2
7a: rejected: truncated header at offset 0
7e e1: rejected: truncated value at offset 0
seed corpus: 5 inputs passed
- Verdict: library. Jazzer.js fuzzes TypeScript code as well as JavaScript.
- The parser returns a result union instead of throwing. The target then cannot throw for bad input, so any exception is a bug.
- An index into a
Uint8Arraypast the end givesundefinedat run time, as in JavaScript, but its static type isnumber. The!afterdata[i]states that the checks above make the index valid. The checks, not the types, prevent the bug. - The types are erased before the program runs, so they add no checks at run time.
package records
import "fmt"
// Record is one [tag][length][value] entry.
type Record struct {
Tag byte
Value []byte
}
// Parse reads records and returns an error for a truncated input.
func Parse(data []byte) ([]Record, error) {
var records []Record
for i := 0; i < len(data); {
if i+2 > len(data) {
return nil, fmt.Errorf("truncated header at offset %d", i)
}
tag, length := data[i], int(data[i+1])
if i+2+length > len(data) {
return nil, fmt.Errorf("truncated value at offset %d", i)
}
records = append(records, Record{tag, data[i+2 : i+2+length]})
i += 2 + length
}
return records, nil
}
// Encode writes records in the same format.
func Encode(records []Record) []byte {
var out []byte
for _, r := range records {
out = append(out, r.Tag, byte(len(r.Value)))
out = append(out, r.Value...)
}
return out
}
package records
import (
"bytes"
"testing"
)
// FuzzParse runs only the seed corpus under plain go test.
// go test -fuzz=FuzzParse would also generate new inputs.
func FuzzParse(f *testing.F) {
f.Add([]byte{})
f.Add([]byte("\x01\x02hi"))
f.Add([]byte("\x01\x02hi\x02\x00"))
f.Add([]byte("z")) // a failing input that fuzzing found
f.Add([]byte("~\xe1")) // another one
f.Fuzz(func(t *testing.T, data []byte) {
records, err := Parse(data)
if err != nil {
t.Logf("rejected: %v", err)
return
}
if got := Encode(records); !bytes.Equal(got, data) {
t.Fatalf("Encode(Parse(%x)) = %x", data, got)
}
t.Logf("records=%d", len(records))
})
}
=== RUN FuzzParse
=== RUN FuzzParse/seed#0
records_test.go:25: records=0
=== RUN FuzzParse/seed#1
records_test.go:25: records=1
=== RUN FuzzParse/seed#2
records_test.go:25: records=2
=== RUN FuzzParse/seed#3
records_test.go:19: rejected: truncated header at offset 0
=== RUN FuzzParse/seed#4
records_test.go:19: rejected: truncated value at offset 0
--- PASS: FuzzParse ($TIME)
--- PASS: FuzzParse/seed#0 ($TIME)
--- PASS: FuzzParse/seed#1 ($TIME)
--- PASS: FuzzParse/seed#2 ($TIME)
--- PASS: FuzzParse/seed#3 ($TIME)
--- PASS: FuzzParse/seed#4 ($TIME)
PASS
ok example $TIME
The original parser panics on the input of one byte. In a fuzz test, the panic is a failure, and Go writes the input to testdata/fuzz/FuzzParse/.
This code panics, on purpose.
package main
import "fmt"
// parse counts the records of the form [tag][length][value].
func parse(data []byte) int {
count := 0
for i := 0; i < len(data); {
length := int(data[i+1]) // no check that the length byte exists
count++
i += 2 + length
}
return count
}
func main() {
seeds := [][]byte{{}, []byte("\x01\x02hi"), []byte("\x01\x02hi\x02\x00"), []byte("z"), []byte("~\xe1")}
for _, seed := range seeds {
fmt.Printf("records=%d\n", parse(seed))
}
}
- Verdict: native. Fuzzing is part of
go test. A fuzz test is a functionFuzzXxx(f *testing.F)in a_test.gofile.f.Addadds seed corpus entries, andf.Fuzztakes the target. - Plain
go test, as here, runs only the seed corpus: one subtest for eachf.Add, namedseed#N, and one for each file intestdata/fuzz/FuzzParse/.go test -fuzz=FuzzParsegenerates more inputs with coverage guidance until it fails or is stopped. - The arguments of the target after
*testing.Tmust have the types of the seeds, in the same order. Here there is one[]byte. - Go checks every slice index, so the bug is a panic with the index and the length. A slice expression
data[i+2 : i+2+length]past the end also panics, unlike a Python slice.
/// Reads records of the form [tag][length][value]; a truncated input is an error.
fn parse(data: &[u8]) -> Result<Vec<(u8, &[u8])>, String> {
let mut records = Vec::new();
let mut rest = data;
while !rest.is_empty() {
let offset = data.len() - rest.len();
let [tag, length, tail @ ..] = rest else {
return Err(format!("truncated header at offset {offset}"));
};
let Some(value) = tail.get(..usize::from(*length)) else {
return Err(format!("truncated value at offset {offset}"));
};
records.push((*tag, value));
rest = &tail[value.len()..];
}
Ok(records)
}
/// The fuzz target, as the body of cargo fuzz's fuzz_target! would be.
fn fuzz_one(data: &[u8]) -> String {
match parse(data) {
Ok(records) => format!("records={}", records.len()),
Err(e) => format!("rejected: {e}"),
}
}
fn main() {
let seeds: [&[u8]; 5] = [b"", b"\x01\x02hi", b"\x01\x02hi\x02\x00", b"z", b"~\xe1"];
for seed in seeds {
let shown: Vec<String> = seed.iter().map(|b| format!("{b:02x}")).collect();
let shown = if shown.is_empty() { "(empty)".to_string() } else { shown.join(" ") };
println!("{shown}: {}", fuzz_one(seed));
}
println!("seed corpus: {} inputs passed", seeds.len());
}
(empty): records=0
01 02 68 69: records=1
01 02 68 69 02 00: records=2
7a: rejected: truncated header at offset 0
7e e1: rejected: truncated value at offset 0
seed corpus: 5 inputs passed
The original parser panics on the input of one byte. The panic message gives the index and the length.
This code panics, on purpose.
/// Counts the records of the form [tag][length][value].
fn parse(data: &[u8]) -> usize {
let mut count = 0;
let mut i = 0;
while i < data.len() {
let length = usize::from(data[i + 1]); // no check that the length byte exists
count += 1;
i += 2 + length;
}
count
}
fn main() {
let seeds: [&[u8]; 5] = [b"", b"\x01\x02hi", b"\x01\x02hi\x02\x00", b"z", b"~\xe1"];
for seed in seeds {
println!("records={}", parse(seed));
}
}
- Verdict: library.
cargo fuzz initcreates a fuzz target, andcargo fuzz runfuzzes it with libFuzzer. The tool needs the nightly compiler. The body of the target is a closure over&[u8], likefuzz_one. - The slice pattern
[tag, length, tail @ ..]matches only when two bytes exist, so the header check is part of the pattern. tail.get(..n)returnsNoneinstead of panicking when the range is past the end.- Safe Rust checks every index, so the bug is a panic and a fuzzer sees it. Under
cargo fuzz, a panic is a crash, and the input is saved in the artifacts directory.
Variations and related ideas
- Blind and coverage-guided fuzzing. Miller's fuzz used no model of the program.2 AFL and libFuzzer observe coverage and keep the inputs that reach code not reached before.34
- Structured inputs. Miller's later studies of X-Window, Windows NT and Mac OS X applications used valid keyboard and mouse events as well as random streams.2
- Dictionaries. AFL combines syntax tokens of a format from a dictionary, and the coverage feedback tells it which combinations reach code not reached before. It can also find tokens in an input by looking for runs of bytes that change the path in the same way when flipped, a sign of a comparison with a constant.3
- Differential and round-trip oracles. A harness can check more than "no crash": that two implementations agree, or that an accepted input encodes back to itself. The pitfall "Only crashes are bugs" shows a round-trip oracle.
- Property-based testing. A property-based test also runs a function on generated inputs, but it starts from typed generators and checks a stated rule. A fuzzer starts from bytes and checks for crashes. Go fuzz tests take typed arguments, so they sit between the two.5
Pitfalls
The harness hides the crash
A harness that catches every exception turns each bug into a rejection. The fuzzer then reports nothing.
This code runs but gives a wrong answer on purpose.
def xorshift32(state):
state ^= (state << 13) & 0xFFFFFFFF
state ^= state >> 17
state ^= (state << 5) & 0xFFFFFFFF
return state
def parse(data):
records = []
i = 0
while i < len(data):
tag = data[i]
length = data[i + 1] # the same bug as before
records.append((tag, data[i + 2 : i + 2 + length]))
i += 2 + length
return records
state = 2463534242
crashes = 0
for run in range(1000):
state = xorshift32(state)
data = bytearray()
for _ in range(state % 9):
state = xorshift32(state)
data.append(state & 0xFF)
try:
parse(bytes(data))
except Exception:
pass # hides every crash, not only the documented errors
print("crashes:", crashes)
crashes: 0
Catch only the error that the code documents for bad input, such as ValueError. Let every other exception reach the fuzzer. The same holds for a target that calls exit: libFuzzer requires that a target must not exit on any input.4
Only crashes are bugs
A fuzzer with no other oracle finds only crashes and hangs. Miller's report says so: a test succeeded when the program terminated normally, and the correctness of the output was not checked.1 The parser below checks the header but not the length of the value. A slice in Python never fails, so a short value is accepted and no crash occurs.
This code runs but gives a wrong answer on purpose.
def xorshift32(state):
state ^= (state << 13) & 0xFFFFFFFF
state ^= state >> 17
state ^= (state << 5) & 0xFFFFFFFF
return state
def parse(data):
records = []
i = 0
while i < len(data):
if i + 2 > len(data):
raise ValueError(f"truncated header at offset {i}")
tag, length = data[i], data[i + 1]
records.append((tag, data[i + 2 : i + 2 + length])) # a short value is not detected
i += 2 + length
return records
state = 2463534242
for run in range(1, 1001):
state = xorshift32(state)
data = bytearray()
for _ in range(state % 9):
state = xorshift32(state)
data.append(state & 0xFF)
try:
parse(bytes(data))
except ValueError:
pass
print("no crash in 1000 runs")
no crash in 1000 runs
Add a check to the harness. Here, an accepted input must encode back to the same bytes. The same inputs then show the bug on the second run.
def xorshift32(state):
state ^= (state << 13) & 0xFFFFFFFF
state ^= state >> 17
state ^= (state << 5) & 0xFFFFFFFF
return state
def parse(data):
records = []
i = 0
while i < len(data):
if i + 2 > len(data):
raise ValueError(f"truncated header at offset {i}")
tag, length = data[i], data[i + 1]
records.append((tag, data[i + 2 : i + 2 + length])) # a short value is not detected
i += 2 + length
return records
def encode(records):
return b"".join(bytes([tag, len(value)]) + value for tag, value in records)
state = 2463534242
for run in range(1, 1001):
state = xorshift32(state)
data = bytearray()
for _ in range(state % 9):
state = xorshift32(state)
data.append(state & 0xFF)
data = bytes(data)
try:
records = parse(data)
except ValueError:
continue
if encode(records) != data: # the oracle: accepted input must encode back to itself
print(f"run {run}: {data!r} parses to {records}")
print(f"which encodes to {encode(records)!r}")
break
run 2: b'~\xe1' parses to [(126, b'')]
which encodes to b'~\x00'
Memory errors that do not crash
In C and C++, a read one byte past the end of a buffer usually returns some byte and goes on. The fuzzer sees no crash. Build the target with AddressSanitizer, as the libFuzzer documentation suggests, so that the read is reported at once.4 The C example shows the report. Miller's first guideline, to check every array reference for valid bounds, is the same fix in the code.1
A target that is not deterministic
A target that uses its own random numbers, the clock or global state gives different coverage for the same input. The fuzzer then keeps inputs that add no coverage and cannot reproduce a failure. libFuzzer asks for a target that is as deterministic as possible.4 The Go documentation adds that the fuzz target runs in parallel in several workers, so its state must not persist past one call.5
The corpus is thrown away
A failure that a fuzzer found once can come back. Keep the failing inputs and run them on each build. Go does this by default with testdata/fuzz, and libFuzzer and Jazzer have a regression mode that runs saved inputs with no fuzzing.549 The examples on this page do this with the two failing inputs: one byte, z, and a header that claims more bytes than follow, ~\xe1.
Cost
- Open-ended run time. A fuzz run has no natural end. The Go documentation says that the user decides how long to fuzz, and that a run can go on forever if it finds no error.5 libFuzzer's option
-runssets the number of runs, and its default of -1 runs without end.4 - Speed per input. The value of a fuzzer grows with the number of inputs per second. AFL uses a fork server so that the target does
execve, linking and libc initialization only once. The documentation reports a gain of 1.5 to 2 times for fast targets.3 AFL sets the default timeout of a run at five times the calibrated speed, rounded up to 20 ms, and rejects slower paths.3 - Instrumentation. Coverage guidance needs a build with instrumentation, and a sanitizer adds more overhead. Go fuzzing needs a platform that supports coverage instrumentation for the corpus to grow.5
- Harness work. Someone must write a target for each entry point, decide which errors are documented, and keep the corpus. libFuzzer advises one target for each data format rather than one for all.4
History
- 1988. Barton Miller gave the fuzz project as an assignment in his graduate class CS736, Advanced Operating Systems, in the fall of 1988.2
- 1990. Miller, Fredriksen and So published the study of UNIX utilities in Communications of the ACM. They crashed or hung 24 to 33 percent of the utilities on each of seven versions of UNIX, and grouped the causes: pointer and array errors, unchecked return codes, input functions such as
gets, and others.12 - 1995 to 2020. Miller's group repeated the command-line study in 1995, 2006 and 2020, and studied X-Window applications in 1995, Windows NT in 2000 and Mac OS X in 2006.2
References
- Barton P. Miller, Lars Fredriksen and Bryan So, An Empirical Study of the Reliability of UNIX Utilities, Communications of the ACM 33(12), December 1990 (the report text), Summary; 1 Introduction; 2.1 Fuzz, Generating Random Input Strings; 3 The Tests; 4 The Results and Analysis; 5.1 Comments on the Results
- Barton P. Miller, Fuzz Testing of Application Reliability, the introduction (the three characteristics of classic fuzz testing); the list of papers (1988 project assignment, 1990 report, later studies)
- Technical whitepaper for afl-fuzz, 1 Coverage measurements; 2 Detecting new behaviors; 3 Evolving the input queue; 5 Trimming input files; 6 Fuzzing strategies; 7 Dictionaries; 9 Investigating crashes; 10 The fork server
- libFuzzer, a library for coverage-guided fuzz testing, LLVM documentation, Introduction; Status; Fuzz Target; Fuzzer Usage; Corpus; Options
- Go Fuzzing, the Go documentation, Requirements; Suggestions; Running fuzz tests; Failing input; Corpus file format; Glossary
- Rust Fuzz Book, cargo-fuzz, Tutorial, cargo fuzz init; fuzz_target!; cargo fuzz run
- Rust Fuzz Book, cargo-fuzz, Setup, Requirements (the nightly compiler)
- Atheris, a coverage-guided native Python fuzzer, README, the introduction
- Jazzer, fuzz testing for the JVM, README, the introduction; Running Jazzer, Regression mode and Fuzzing mode
- Jazzer.js, README, the introduction
- SharpFuzz, AFL-based fuzz testing for .NET, README, the introduction
- american fuzzy lop, home page, the note on AFL++
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag WENMVH Edit this page History Report an error Markdown