Section 10.26

libFuzzer

Full name: libFuzzer, the fuzzing library of the LLVM compiler project; lib is the usual prefix of a library’s name. LLVM began as Low Level Virtual Machine; the project now treats the letters as a plain name.

Definition

libFuzzer is a coverage-guided fuzzing §10.12 engine for C and C++, distributed with the Clang §12.17 compiler. Fuzzing §10.9 means running code on very many generated inputs to find inputs that make it fail. libFuzzer is linked into the program under test and calls one function written by the tester, LLVMFuzzerTestOneInput, again and again in the same process, each time with a new byte string. It keeps inputs that reach new code, mutates them into new inputs, and stops at the first crash or sanitizer §10.21 report, saving the input that caused it.

The idea

A parser library needs 10 microseconds to parse one message. Starting a fresh process for each input costs, in this example, another 1 ms for loading and initialization. That allows at most 1/(1.01ms)≈9901 / (1.01\ \text{ms}) \approx 990 inputs per second. Calling the parse function directly inside one running process removes the start-up cost: 1/(0.01ms)=100,0001 / (0.01\ \text{ms}) = 100{,}000 inputs per second, about 100 times as many.

The price of that speed is that all inputs share one process. Whatever one call leaves behind, such as a changed global variable, unfreed memory, an open file or a running thread, is the starting state of the next call. libFuzzer therefore needs the code it calls to behave like a function of the input bytes alone: accept any bytes, finish every call, and leave nothing behind that changes the next call.

How it works

  1. Write the fuzz target, libFuzzer’s form of a fuzz harness §10.13, the code that hands each generated input to the code under test. It is one function with a fixed signature:

    int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)

    Data points to Size input bytes, which the target must not modify. The target passes them to the code under test and returns 0. Returning −1-1 keeps the input out of the corpus, the set of kept inputs; other return values are reserved. An optional function, LLVMFuzzerInitialize, runs once at start-up.

  2. Build with clang -g -O1 -fsanitize=fuzzer,address. The part fuzzer adds coverage instrumentation §14.24, counters on the edges between blocks of straight-line code plus tracing of comparisons, and links libFuzzer’s own main function. The part address adds AddressSanitizer §10.22, which turns silent memory errors into reports.

  3. Run ./target CORPUS, where the directory CORPUS holds a seed corpus §10.14 of example inputs. libFuzzer then loops: pick a corpus input; mutate it by flipping bits, inserting or erasing bytes, splicing two inputs, or inserting tokens and values seen in comparisons; copy the result into a fresh heap buffer of exactly Size bytes, so that AddressSanitizer catches a read even one byte past the end; call the target; and add the input to the corpus if it reached a new edge, or reached an edge a number of times that falls in a range of counts not seen before.

  4. Stop and save. On a crash, a sanitizer report, a timeout §9.34, a memory leak §4.8 or memory exhaustion, libFuzzer writes the input to a file named crash-, timeout-, leak- or oom- followed by a hash of the input, and exits. Running the program with that file name as its argument reruns the target on that input.

Options set the limits: -max_len on the input length, -timeout on the seconds one input may take (1200 by default), and -rss_limit_mb on the memory of the process (2048 megabytes by default); -dict names an input dictionary §10.16 of tokens. When LeakSanitizer, the leak detector among the sanitizers, is built in, libFuzzer checks each input for leaks. The option -fork=N runs the fuzzing in N child processes, so that timeouts and memory exhaustion no longer end the campaign.

libFuzzer’s documentation lists what a fuzz target must do: tolerate any input, whether empty, huge or malformed; never call exit; join any threads it starts before it returns; be as deterministic as possible, because random decisions not derived from the input bytes make fuzzing inefficient; be fast; and ideally leave global state unchanged.

Worked example

A message parser keeps a global flag have_header, set when the parser accepts a message that starts with the bytes HDR and never cleared. A defect sits in the body path: when have_header is set and a BODY message has a length field of 0, the code computes len - 1 in 32-bit unsigned arithmetic, gets 0−1+232=4,294,967,2950 - 1 + 2^{32} = 4{,}294{,}967{,}295, and tries to copy that many bytes.

During a campaign, input number 10,421 starts with HDR and sets the flag. Input 10,422 is a BODY message with length 0. It crashes, AddressSanitizer reports the overflowing copy, and libFuzzer saves input 10,422 alone. The developer runs the target on the saved file. In the fresh process have_header is clear, the parser rejects a body without a header, and nothing crashes. The defect is real, but the saved evidence does not reproduce it.

Two repairs make the saved file carry the whole cause. Either the target resets the parser at the start of every call, so that input 10,422 behaves the same at any position in the campaign. Or one input encodes a whole sequence of messages, for example a count byte followed by messages that each start with their length, and the target builds a fresh parser for each input; the crashing file then contains both messages and crashes in a fresh process. Had the parser called exit on its first malformed message, the campaign would have ended almost at once: libFuzzer treats a call to exit inside the target as an error and saves that input as a crash.

Stated precisely

Let TT be the fuzz target, xx an input byte string no longer than the -max_len limit, and σ\sigma the part of the process state that can influence TT: global variables, heap contents, open files, running threads and the state of random number generators. The results of a campaign mean what they appear to mean under three conditions.

  1. Totality. Apart from defects in the code under test, T(x)T(x) returns for every xx within the time and memory limits. In particular, TT never calls exit, and it rejects any input that breaks a documented precondition of the code it calls.

  2. Reset. Before every call, σ\sigma is the same as in a fresh process after initialization.

  3. Determinism. The path that T(x)T(x) takes, and therefore its coverage and its outcome, depends only on xx and σ\sigma.

Under conditions 2 and 3, every saved crash reproduces when its file is run alone, and every corpus input reproduces the coverage for which it was kept. Under condition 1, every report points at a defect in the code under test, not at the harness.

Limits and common mistakes

libFuzzer finds only what something reports: crashes, sanitizer reports, timeouts, leaks, memory exhaustion, and checks that the target makes itself, such as comparing a decoded value with the original. A wrong output that nothing checks passes silently.

An in-process engine shares the fate of its process. A crash ends the campaign unless -fork is used, an endless loop is caught only by the timeout, and the default timeout of 1200 seconds is far longer than most targets need.

Tolerating arbitrary bytes does not mean accepting them. The target should reject malformed input with an error return, exactly as production code must; what is wrong is ending the process on ordinary invalid input. If the code under test has a documented precondition, the target must enforce it before the call, or every violation of the precondition is reported as a crash.

A campaign on the host checks the host build. Code written for a microcontroller §6.1 must first be built for the host with its hardware replaced, and timing, interrupts §6.11 and real peripherals then lie outside the result.

The original authors of libFuzzer have moved to another fuzzing engine, Centipede; libFuzzer still receives bug fixes but no major new features. Its fuzz target interface is also accepted by other engines, among them AFL++ §10.27, a fuzzer descended from AFL (American Fuzzy Lop).

Questions answered

Why must the target tolerate arbitrary bytes and reset relevant state between inputs?

The target must tolerate arbitrary bytes and reset its state because libFuzzer calls it millions of times inside one process, with byte strings made by blind mutation: every byte string can arrive, and every call starts from whatever the earlier calls left behind.

The cure is to reset the state at the start of every call or, when behavior over a sequence of messages is the object of the test, to encode the whole sequence in one input and start each input from a fresh state.

Related entries: Fuzzing (§10.9), Coverage-guided fuzzing (§10.12), Fuzz harness (§10.13), Seed corpus (§10.14), Deterministic replay (§10.37). Further reading: [24].