Skip to main content
Be Bitwise

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:

c
// 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:

c
// 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

c
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

c
// Don't do this - too much irrelevant code
int 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

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:

c
// Pure parsing function - no state needed
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
parse_json(data, size);
return 0;
}

Targets with context objects — allocate and initialise the context:

c
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:

cpp
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:

c
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:

bash
# Gather seeds from multiple sources
mkdir corpus/
# 1. From the project's test suite
cp target/tests/testdata/*.png corpus/
# 2. Generate minimal valid files
python3 -c "
import struct
# Minimal valid PNG: 8-byte header + IHDR + IDAT + IEND
header = b'\x89PNG\r\n\x1a\n'
# ... construct minimal chunks
with 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 corpus
afl-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:

bash
# Build with coverage instrumentation
clang -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 report
llvm-profdata merge -sparse default.profraw -o default.profdata
llvm-cov show ./harness -instr-profile=default.profdata \
--format=html > coverage.html

Read 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:

bash
# 1. Minimise all crashes
for crash in output/crashes/id:*; do
afl-tmin -i "$crash" -o "minimised/$(basename $crash)" -- ./harness @@
done
# 2. Deduplicate by crash location
for 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"
fi
done | sort

Continuous 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:

bash
# 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 decoder

The 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
Fuzzing as Infrastructure

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.