Harness Development
Advanced Fuzzing Techniques · VR Analysis & Discovery track
11 min read
In this module
Writing Code That Finds Bugs
A fuzz harness is the glue between a fuzzer and the code you want to test. It's a small program that takes the fuzzer's bytes, sets up whatever context the target needs, and calls in. Harness quality decides everything. A sharp harness rakes in dozens of bugs; a sloppy one can grind for weeks and surface nothing.
Anatomy of a Fuzz Harness
Every harness has the same basic structure:
// libFuzzer harness template#include <stdint.h>#include <stddef.h>
// Include target headers#include "target_library.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { // 1. Validate minimum input size if needed if (size < MINIMUM_USEFUL_SIZE) return 0;
// 2. Set up any required state target_context *ctx = target_init();
// 3. Call the target function with fuzz data target_process(ctx, data, size);
// 4. Clean up target_destroy(ctx);
return 0;}For AFL++, the harness reads from stdin or a file:
// AFL++ harness template#include <stdio.h>#include <stdlib.h>#include "target_library.h"
int main(int argc, char *argv[]) { // Read input from file (AFL++ passes filename as @@) FILE *f = fopen(argv[1], "rb"); if (!f) return 1;
fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET);
uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f);
// Call target target_context *ctx = target_init(); target_process(ctx, data, size); target_destroy(ctx);
free(data); return 0;}Isolating Target Code
The biggest decision when writing a harness is what to call. You want to point the fuzzer at the code that touches untrusted input, not at the whole application:
Good: fuzzing the image decoder function directly
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { // Directly call the PNG decode function png_image image; memset(&image, 0, sizeof(image)); image.version = PNG_IMAGE_VERSION; png_image_begin_read_from_memory(&image, data, size);
if (PNG_IMAGE_FAILED(image)) { png_image_free(&image); return 0; }
size_t buf_size = PNG_IMAGE_SIZE(image); if (buf_size > MAX_ALLOC) { png_image_free(&image); return 0; }
void *buffer = malloc(buf_size); png_image_finish_read(&image, NULL, buffer, 0, NULL);
free(buffer); png_image_free(&image); return 0;}Bad: fuzzing the entire application which includes UI, file dialogue, and other irrelevant code
// Don't do this - too much irrelevant codeint LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { write_temp_file(data, size); system("./image_viewer /tmp/fuzz_input.png"); return 0;}The good harness pours fuzzer cycles straight into the parser. The bad one burns most of them on file I/O, process spawning, and UI init before anything interesting runs.
Harness granularity is a tradeoff. A single-function harness (fine-grained) is fast and tightly focused, but it misses bugs that only show up across a sequence of calls. A higher-level API harness (coarse-grained) catches interactions but runs slower and earns coverage more grudgingly. The usual play is fine-grained first, on the parser hotspots, then build coarser harnesses on top for integration shaking.
Handling State
Plenty of targets need state in place before the function under test will do anything. The harness has to put it there:
Stateless targets (easiest) — functions that swallow input without external dependencies:
// Pure parsing function - no state neededint LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { parse_json(data, size); return 0;}Targets with context objects — allocate and initialise the context:
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { SSL_CTX *ctx = SSL_CTX_new(TLS_method()); SSL *ssl = SSL_new(ctx); BIO *rbio = BIO_new_mem_buf(data, size); SSL_set_bio(ssl, rbio, BIO_new(BIO_s_null())); SSL_set_accept_state(ssl); // act as a server, or the handshake fails at once SSL_do_handshake(ssl); SSL_free(ssl); SSL_CTX_free(ctx); return 0;}Forget SSL_set_accept_state() (or SSL_set_connect_state() for the client side) and OpenSSL bails out of SSL_do_handshake() before reading a byte, so the fuzzer sees one flat path no matter what it feeds in. A harness like this would show perfect stability and zero progress, which is exactly the failure that's hard to spot.
Targets that need several values — when a function wants an integer, a flag and a buffer, don't hand-carve offsets out of data. LLVM ships FuzzedDataProvider (#include <fuzzer/FuzzedDataProvider.h>, C++), which peels typed values off the input for you:
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { FuzzedDataProvider fdp(data, size); int level = fdp.ConsumeIntegralInRange<int>(0, 9); bool strict = fdp.ConsumeBool(); std::vector<uint8_t> rest = fdp.ConsumeRemainingBytes<uint8_t>(); compress(rest.data(), rest.size(), level, strict); return 0;}Targets with global state — may need a reset between iterations:
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { // Reset global state reset_parser_state(); clear_error_flags();
// Now fuzz process_input(data, size); return 0;}If global state won't reset cleanly, you're stuck with fork-based fuzzing (AFL++'s default) rather than persistent mode. Throughput takes a hit. There's no way around it.
Seed Corpus Creation
A good seed corpus hands the fuzzer a head start. The aim is a set of seeds that, between them, walk diverse code paths:
# Gather seeds from multiple sourcesmkdir corpus/
# 1. From the project's test suitecp target/tests/testdata/*.png corpus/
# 2. Generate minimal valid filespython3 -c "import struct# Minimal valid PNG: 8-byte header + IHDR + IDAT + IENDheader = b'\x89PNG\r\n\x1a\n'# ... construct minimal chunkswith open('corpus/minimal.png', 'wb') as f: f.write(header + ihdr + idat + iend)"
# 3. Edge case files# - 1x1 pixel image# - Maximum dimension image (small file, large dimensions)# - Each supported colour type# - Interlaced vs. non-interlaced
# 4. Minimise the corpusafl-cmin -i corpus/ -o corpus_min/ -- ./harness @@Quality over quantity: 50 well-chosen seeds beat 10,000 near-duplicates every time. Run afl-cmin to drop the seeds that don't add coverage.
Measuring and Improving Coverage
Monitor coverage during fuzzing to identify blind spots:
# Build with coverage instrumentationclang -fprofile-instr-generate -fcoverage-mapping \ -fsanitize=fuzzer,address harness.c target.c -o harness
# Fuzz for a while./harness corpus/ -max_total_time=3600
# Generate coverage reportllvm-profdata merge -sparse default.profraw -o default.profdatallvm-cov show ./harness -instr-profile=default.profdata \ --format=html > coverage.htmlRead the coverage report and look for the gaps:
- Uncovered error handlers — bug-rich territory that nothing's testing
- Uncovered format variations — add seeds that exercise those formats
- Uncovered conditional branches — the fuzzer can't satisfy the predicate; a dictionary token or custom mutator might unstick it
Triaging Fuzzer Crashes at Scale
A productive fuzzer drowns you in crashes. Triage has to keep up:
# 1. Minimise all crashesfor crash in output/crashes/id:*; do afl-tmin -i "$crash" -o "minimised/$(basename $crash)" -- ./harness @@done
# 2. Deduplicate by crash locationfor crash in minimised/*; do # Get crash address from ASan addr=$(./harness_asan "$crash" 2>&1 | grep "^ #0" | head -1) echo "$addr :: $crash"done | sort | uniq -w40
# 3. Triage by exploitability (using ASan output)for crash in minimised/*; do output=$(./harness_asan "$crash" 2>&1) if echo "$output" | grep -q "heap-buffer-overflow.*WRITE"; then echo "HIGH: $crash - heap overflow (write)" elif echo "$output" | grep -q "use-after-free"; then echo "HIGH: $crash - use-after-free" elif echo "$output" | grep -q "heap-buffer-overflow.*READ"; then echo "MEDIUM: $crash - heap overflow (read)" else echo "LOW: $crash" fidone | sortContinuous Fuzzing with OSS-Fuzz
OSS-Fuzz is Google's free continuous-fuzzing service for open-source projects. Once you're integrated, your harnesses run continuously on Google's infrastructure, with crashes filed straight to the issue tracker:
# OSS-Fuzz project structure (projects/my_project/ in the oss-fuzz repo)my_project/ project.yaml # Metadata: homepage, language, main_repo, contacts Dockerfile # Build environment build.sh # Compile harnesses harness_parse.c # Fuzz harness for parser (often kept upstream instead) harness_decode.c # Fuzz harness for decoderThe backend is ClusterFuzz (also Google), which gives you:
- Parallel fuzzing across thousands of CPU cores
- Automatic crash minimisation and deduplication
- Bisection to pinpoint the commit that introduced the bug
- Automatic verification when a fix lands
- Public disclosure after 90 days or once fixed
The teams that find the most bugs treat fuzzing as infrastructure, not a one-off. Harnesses live alongside the project code, corpora are version-controlled and curated, and the fuzzer runs around the clock. Every commit gets fuzzed automatically. Regressions show up the same day, and new code is being chewed on the moment it lands. If you maintain an open-source project, an OSS-Fuzz integration is one of the best security investments you can make.