Section 10.13

Fuzz harness

Definition

A fuzz harness is the code between a fuzzer, a tool that runs a program on very many automatically made inputs, and the code under test. The fuzzer hands the harness one input, a sequence of bytes. The harness turns the bytes into calls that the interface of the code under test allows, and lets every failure show as a crash or an error report. It thereby decides which code is tested, from which starting state, and what counts as a failure. The libFuzzer §10.26 documentation calls it a fuzz target.

The idea

A library’s decoding function expects a context, a structure that an initialization call creates, together with the message bytes and their length; afterwards the caller must free the context. A fuzzer produces only byte strings. The harness stands between the two: it creates the context, passes the bytes, checks the result and frees the context.

The fuzzer runs the harness millions of times, often inside one process, so a mistake in the harness repeats millions of times. A harness that leaves state behind makes each run depend on the runs before it. A failure found that way does not reproduce from the one input the fuzzer saves, and it may never occur in the real program.

A laboratory test fixture is a fair picture: it holds the specimen, applies the load, records the result and returns to its starting position before the next specimen. A fixture that is not reset, or that still presses on the last specimen, produces results that belong to no single specimen. The picture stops at one point: a harness may deliberately apply a sequence of operations, and then the whole sequence, encoded in one input, is the specimen.

How it works

libFuzzer and other in-process fuzzers call the harness as a function, many times in one process. libFuzzer’s harness has this form:

int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)

Data points to the input bytes, Size is their number, and the function returns 0. One call with one input is an invocation. Each invocation of a well-built harness runs these steps:

  1. Decode: read from the bytes what the code under test needs, such as which function to call, a length or a flag. Accept every input, the empty one included, and never read beyond Size bytes.

  2. Set up fresh per-input state, such as a new context. State that never changes once built, such as a lookup table, may be built once; libFuzzer calls the optional function LLVMFuzzerInitialize once for that work.

  3. Call the code under test, meeting every precondition its interface states, for example never passing a null pointer §4.26 where the interface forbids one.

  4. Check, optionally, a property the result must have, such as that decoding an encoded message gives back the original, and call abort() if the property fails, so that the fuzzer records a failure.

  5. Clean up: free what the invocation allocated, close what it opened, reset global variables it changed, and finish all asynchronous work it started. Join each thread, which means waiting until the thread has ended; cancel each timer and callback §14.22; and wait for or cancel each pending operation.

  6. Return 0.

The clean-up has a hard deadline. When the harness returns, the fuzzer may free or reuse the memory that held the input, and it starts the next invocation at once. Anything that still uses Data then uses memory whose ownership has gone back to the fuzzer.

The libFuzzer documentation adds its own rules: a harness must not call exit(); it may use threads, but ideally all threads should be joined at the end of the function; it must be as deterministic as possible and fast; ideally it should not modify global state; and a narrow harness, such as one per data format, is usually better than a broad one.

Deterministic means that the input alone fixes what the invocation does. If the code under test draws random numbers, the harness takes them from the input or starts the generator from a constant. To test behavior that depends on earlier calls, the harness splits one input into several messages and feeds them in order within one invocation, so that one saved input reproduces the whole sequence.

Worked example

State that is not reset. A library keeps a table of 64 records in a static variable, with a count nn that starts at 0. Its function add_record stores a record at position nn and adds 1 to nn, without comparing nn with 64. The library’s documentation requires the caller to call reset, which sets nn back to 0, after each message. A harness calls add_record once per input and never calls reset.

Invocations 1 to 64 fill positions 0 to 63. Invocation 65 writes at position 64, past the end of the table, and AddressSanitizer §10.22, a sanitizer §10.21 that checks every memory access, reports an out-of-bounds write §4.4. The fuzzer saves input 65. Run alone in a fresh process, input 65 writes at position 0, and nothing fails. As a report of a library bug, it is a false positive §1.22: the harness broke the library’s documented rule. The repair is to call reset at the end of every invocation.

If the real program may legitimately store 65 records before it calls reset, the overflow is a real bug, and the test must show it reproducibly. The harness then reads the first input byte as a count kk from 0 to 255, calls add_record kk times with records from the rest of the input, and calls reset before returning. An input whose first byte is 65 fails in every fresh process.

Asynchronous work that is not joined. Another harness starts a worker thread that parses Data and returns 0 without joining the thread. The fuzzer frees the input buffer and begins the next invocation while the worker still reads memory that is freed or now holds the next input. AddressSanitizer may report a use-after-free §4.6 during a later invocation, and the fuzzer then saves that later, unrelated input. Resetting a global variable does not help, because the fault concerns object lifetime §4.1: the worker uses the input after the harness’s right to it has ended. The repair is to join the worker before returning.

Stated precisely

Let HH be the harness, TT the code under test, xx any byte string of any length including 0, and H(x)H(x) one invocation of HH on xx. The harness is correct when five conditions hold.

  1. Preconditions: every call from HH to TT meets the preconditions that the interface of TT states.

  2. Attribution: whenever H(x)H(x) does not return normally, the cause is a violation of the contract of TT by TT, never a fault of HH.

  3. Isolation: H(x)H(x) gives the same result whether xx runs first in a fresh process or after any sequence of other inputs. All state that an invocation can change is reset before the next invocation or deliberately encoded in xx.

  4. Completion: when H(x)H(x) returns, every thread, timer, callback and asynchronous operation it started has finished or has been canceled, and nothing will use the bytes of xx or memory that HH freed.

  5. Determinism: every choice made during H(x)H(x) is fixed by xx or by a constant.

If all five conditions hold and the rerun uses the same build, every reported failure is a failure of TT on an input that TT can receive through that interface, and the saved input reproduces the failure. State built once at start-up and never changed afterwards does not break isolation.

Limits and common mistakes

A harness tests only the code it reaches. A harness that skips framing, authentication §1.6 or a checksum §4.32 to reach a parser supports claims about the parser only, and any claim must say so.

A harness can hide bugs and so produce false negatives: by catching every error and carrying on, turning crashes into return values, filtering inputs more strictly than the real program does, or checking results too weakly. A positive control §10.30, a known bug planted in a test build that the fuzzer must find, shows that the harness can report a failure at all.

In-process fuzzing §10.9 lets damage accumulate: memory corruption that does not crash at once can make a later, unrelated input crash. Sanitizers catch each fault in the invocation that caused it.

Memory that an invocation never frees is a memory leak §4.8 that grows with every invocation. When the program is built with AddressSanitizer or LeakSanitizer, a leak detector, libFuzzer by default compares the numbers of allocations and frees in each invocation. When they differ, it reruns the input under LeakSanitizer and reports a confirmed leak together with its input.

Joining threads does not determine the order of their steps, which the operating system decides. A data race §9.3, two threads accessing the same memory without synchronization while at least one of them writes, may occur in some runs only. ThreadSanitizer §10.25, a sanitizer that detects data races, reports a race only in a run in which both racing accesses occur, so the saved input may not reproduce the report.

Logging, sleeping or rebuilding fixed data in every invocation cuts the number of inputs tried per second.

Questions answered

Is every invocation reset, and are asynchronous tasks joined?

Both must be true before the results of a fuzzing campaign can be trusted, except that a test may deliberately carry state forward inside one input. An invocation is one call of the fuzz harness, the code between the fuzzer and the code under test, with one input. Reset means that all state an invocation can change is restored before the next invocation: static and global variables, caches, open sessions, allocated memory, files, and simulated or real hardware registers. Joined means that every thread has ended, every timer and callback has been canceled, and every pending operation has completed or been canceled before the harness returns, because the fuzzer may then free the input bytes and starts the next input at once. State that a test must carry from call to call is encoded in the input as a sequence of calls within one invocation.

To check both conditions: run each saved input alone in a fresh process and confirm the same result; run the corpus in two different orders and compare the results; run under AddressSanitizer, which catches use of the input after the harness returned, and under ThreadSanitizer, which catches leftover work racing with the next invocation; and confirm that libFuzzer’s leak detection reports nothing.

Related entries: Asynchronous completion (§9.28), Cancellation (§9.29), Object lifetime (§4.1), libFuzzer (§10.26), Coverage-guided fuzzing (§10.12), Sanitizer (§10.21), Deterministic replay (§10.37), Positive control (§10.30). Further reading: [24].