Articles

Writing fuzzing harnesses with an AI agent: libFuzzer and AFL++

Using an AI agent to write real fuzzing harnesses: choosing the target function, a libFuzzer harness with LLVMFuzzerTestOneInput and -fsanitize=fuzzer,address, AFL++ with afl-clang-fast, corpus seeding, dictionaries, coverage checks, crash triage, and where models write bad harnesses.

· 9 min read

An old-master oil painting of old bone dice tumbling across a dark wooden table, one die smouldering with a thin curl of smoke.

Fuzzing is one of the best-value things you can do in vulnerability research, and writing the harness is the part people put off. It's fiddly, repetitive glue code: take a byte buffer, turn it into whatever your target function wants, call it, and make sure a crash is attributable. That shape — repetitive glue around a well-understood API — is exactly what an AI agent is good at. The judgement calls around it are what you keep for yourself.

This guide walks the whole loop with an agent: pick the right function, write a libFuzzer harness, run it under AFL++ as well, seed a corpus and a dictionary, check coverage, and triage and minimize the crashes. It ends with where models reliably write bad harnesses, because recognising those failures is most of the skill.

Fuzz code you own, maintain, or have permission to test, and build it yourself locally. Everything here is local: a target you compiled, a corpus on your disk, crashes in your own directory.

The fuzzing loop with an agentChoose a target function that parses untrusted input. Write a harness that maps fuzzer bytes to that function's arguments. Build it with sanitizers under libFuzzer or AFL++. Seed a corpus and a dictionary, then run and watch coverage. When it finds a crash, minimize it and triage the root cause; feed fixes and new seeds back into the loop.NoYesChoose a targetfunctionWrite the harnessbytes → argumentsBuild with sanitizerslibFuzzer or AFL++Seed corpus+ dictionaryRun, watch coverageCrash?Minimize + triage
The fuzzing loop with an agent

Step 1: choose the target function (the decision models get wrong)

A fuzz target should be a function that parses or processes untrusted input, is deterministic, and is cheap to call in a tight loop — no network, no global setup, no files if you can avoid them. The best targets are parsers: a file-format loader, a protocol decoder, a deserializer, a decompressor, a regex compiler.

This is a judgement call, and it's the one models most want to shortcut. A model asked to "write a fuzzer for this library" will often harness the first public function it sees, or the top-level API that does I/O and setup, and produce something that technically runs but barely exercises the parser underneath. So make the choice yourself, or make the model justify it:

List the functions in this library that parse externally-supplied bytes, are deterministic, and have no I/O or global state. For each, say what input format it expects. Recommend the best fuzz target and explain why.

Then you pick. A good prompt at this point sets up the next step: "We'll fuzz parse_header(const uint8_t *data, size_t len). Write a libFuzzer harness that maps the fuzzer's input directly to those two arguments."

Step 2: a libFuzzer harness

libFuzzer is built into LLVM. The entire contract is one function, LLVMFuzzerTestOneInput, which receives a buffer and length:

// harness.c — fuzz a parser that takes (bytes, length)
#include <stdint.h>
#include <stddef.h>
#include "project.h"

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    parse_header(data, size);   // the function under test
    return 0;                   // non-zero returns are reserved; always return 0
}

Build it with the fuzzer and AddressSanitizer instrumentation. The combination -fsanitize=fuzzer,address links libFuzzer's main and turns memory errors into loud, attributable crashes:

clang -g -O1 -fsanitize=fuzzer,address harness.c project.c -o fuzz_header
./fuzz_header corpus/        # runs until a crash, writing crash-<hash> on a find

Add -fsanitize=fuzzer,address,undefined to catch undefined behaviour too. For C++, use clang++. When the target needs a structured argument rather than raw bytes, FuzzedDataProvider (a header shipped with LLVM) is the clean way to carve typed values out of the buffer, and models use it well once you point them at it — ask for it by name.

Step 3: AFL++ as well

AFL++ is the maintained successor to AFL, and running the same target under both fuzzers finds different bugs — they explore differently. AFL++ instruments at compile time with afl-clang-fast (or afl-clang-lto for better coverage) and drives the target with afl-fuzz.

The easiest path is a target that reads from stdin or a file argument. AFL++ can also run a libFuzzer-style harness directly, because afl-clang-fast understands LLVMFuzzerTestOneInput:

afl-clang-fast -g -O1 -fsanitize=address harness.c project.c -o fuzz_header_afl
mkdir -p in out && cp corpus/* in/        # seed inputs
afl-fuzz -i in -o out -- ./fuzz_header_afl

-i is the seed directory, -o is where AFL++ writes its state, queue and crashes, and everything after -- is the target. AFL++ shows a live status screen; the numbers that matter are the execution speed, the map coverage, and whether it's finding new paths. For serious runs, AFL++'s docs cover parallel fuzzing (-M/-S for a main and secondary instances) and the different instrumentation modes — have the model read the AFL++ docs rather than invent flags.

Step 4: seed the corpus and write a dictionary

A fuzzer starting from nothing wastes enormous time rediscovering your input format. Two cheap fixes multiply its effectiveness:

A seed corpus — a handful of small, valid inputs that already exercise the parser. For a PNG parser, a few tiny PNGs; for a config parser, a few valid configs. The model can generate plausible seeds, but real sample files from the project's own test suite are better. Keep them small: libFuzzer and AFL++ both mutate faster on short inputs.

A dictionary — the magic constants, keywords and tokens of the format, so the fuzzer can insert them whole instead of discovering them byte by byte. This is a task models do well, because extracting format tokens from a spec or a header file is a reading job:

# http.dict — tokens the fuzzer can splice in
content_length="Content-Length:"
get="GET "
crlf="\r\n"
./fuzz_header -dict=http.dict corpus/           # libFuzzer
afl-fuzz -i in -o out -x http.dict -- ./fuzz_header_afl   # AFL++

Ask the model: "Extract a fuzzing dictionary of the magic bytes, keywords and delimiters for this format from its spec / these headers, in AFL/libFuzzer dictionary syntax."

Step 5: check coverage

Coverage is how you know the fuzzer is actually reaching the code you care about, not spinning on the input validation at the front door. Build a coverage-instrumented version and render a report after a run:

clang -g -O1 -fsanitize=fuzzer -fprofile-instr-generate -fcoverage-mapping \
      harness.c project.c -o fuzz_cov
./fuzz_cov -runs=0 corpus/                       # replay the corpus, no new fuzzing
llvm-profdata merge -sparse default.profraw -o cov.profdata
llvm-cov show ./fuzz_cov -instr-profile=cov.profdata project.c

Read the report with the model: "Here's the coverage over project.c. Which functions in the parser are the corpus not reaching, and why might the harness not get there?" A common answer is that the harness feeds the wrong layer — see the failures below — and the fix is a better harness or better seeds.

Coverage tells you whether the harness reaches the parserYou run the corpus under a coverage build and merge the profile. The coverage report shows which parser functions were reached. If the deep parser is cold, the harness is probably feeding the wrong layer or the seeds are too shallow, so you fix the harness or add seeds and measure again.YesNoReplay corpus,coverage buildProfile dataWhich parserfuncs reachedDeep parsercold?Harness feedswrong layer —fix itGood coverage,keep fuzzing
Coverage tells you whether the harness reaches the parser

Step 6: triage and minimize crashes

A crash file is a starting point, not a bug report. Two jobs turn it into something actionable, and the model helps with both.

Minimize it to the smallest input that still crashes — easier to understand and faster to re-run:

./fuzz_header -minimize_crash=1 -runs=10000 crash-<hash>    # libFuzzer
afl-tmin -i crash-<hash> -o crash-min -- ./fuzz_header_afl  # AFL++

Triage the root cause. Re-run the minimized input under the sanitizer build and read the report with the agent:

./fuzz_header crash-min     # ASan prints the type, the stack, and the faulting address

ASan tells you the bug class (heap-buffer-overflow, use-after-free, stack overflow) and the stack. Hand that to the model: "Here's the ASan report and the minimized input. What's the root cause in the source, and is it a read or a write past the buffer?" A write past a buffer is more serious than a read; the model is good at reading the stack back to the offending line, and you confirm it against the source. Deduplicate by the crashing stack — many crash files are the same bug. For turning a confirmed crash into an understanding of exploitability, the exploit-development guide covers the next step, and responsible disclosure applies if the code isn't yours — see the vulnerability-research guide.

Where models write bad harnesses

This is the part to internalise, because a harness that runs but tests nothing is worse than none — it gives false confidence. The recurring failures:

  • Fuzzing the wrong layer. The model harnesses a high-level API that validates and dispatches, when the bugs live in the parser three calls down. Coverage over the parser stays near zero. Fix: target the parser directly, confirm with coverage.
  • Leaking state between runs. LLVMFuzzerTestOneInput is called millions of times in one process. If the harness allocates and never frees, or mutates a global and never resets it, you get spurious "crashes" (OOM, or state-dependent behaviour) that aren't real bugs. Each call must be independent: free what you allocate, reset what you touch.
  • Non-determinism. A harness that reads the clock, the network, a file, or uninitialised memory makes crashes unreproducible and poisons minimization. Keep it a pure function of the input bytes.
  • Rejecting all input at the door. If the target needs a checksum or a magic header, a naive harness makes every fuzz input fail validation immediately and nothing downstream runs. Either seed a valid corpus and dictionary, or (carefully) patch out the checksum in the harness so the fuzzer reaches the interesting code.
  • Swallowing the crash. A harness wrapped in a catch-all that ignores errors hides the very thing you're fuzzing for. Let it crash.
  • Inventing flags. Models will confidently produce afl-fuzz or libFuzzer options that don't exist. If you can't find a flag in the tool's own docs, it's probably hallucinated — check before you build a run around it.

Make the model state, for any harness it writes, what layer it targets, why each run is independent, and why it's deterministic. If it can't, the harness isn't ready.

Prior art: OSS-Fuzz

Before writing a harness from scratch, check whether your target is in OSS-Fuzz, Google's continuous-fuzzing service for open-source projects. Hundreds of projects already have harnesses there, and they're an excellent template: real, maintained, and written by people who know the target. If your project is covered, read its existing harnesses with the model and extend them; if it isn't, OSS-Fuzz's structure is a good model for how to organise your own. OSS-Fuzz has also been integrating AI-written harnesses, which is worth reading about as a sign of where this is going.

Where caveira fits

Any shell-capable agent can write harnesses and drive clang, libFuzzer and AFL++: Claude Code, Codex, OpenCode and caveira among them. Two things matter here. Refusals — writing a fuzzer to find memory-corruption bugs is legitimate security work that mainstream assistants sometimes treat as suspicious. And a local toolchain, because you build and run everything yourself.

caveira suits this work: its backend serves uncensored, abliterated open-weight models, so it works through harness-writing and crash triage without hedging, and its optional Docker box ships a C/C++ toolchain, gdb with GEF, radare2 and binutils — enough to build an instrumented target and triage a crash without installing anything on the host. It's one capable option; the fuzzers are standard, and the discipline above applies whatever agent drives them.