Skip to content
systemcoding.dev
Security

Fuzz a Binary File Parser With AFL++

Build a file parser with afl-clang-fast and AddressSanitizer, seed and run afl-fuzz 4.x, read the crashes directory and shrink a crash with afl-tmin.

8 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the C, GNU and LLVM logos.

When the code you want to test is a command-line tool that takes a file path, AFL++ is the shortest route to fuzzing it. There is no harness function to write: the fuzzer runs the whole program once per input, watches coverage through instrumentation inserted by its compiler wrapper, and keeps the inputs that reach new code. This post builds a small archive reader with AFL++ 4.x and Clang 19, adds AddressSanitizer, creates seeds, runs afl-fuzz, reads the crash file names, and shrinks the finding with afl-tmin. It assumes you have built a C program with Clang and that the idea of coverage-guided fuzzing is familiar; the post on what fuzzing is covers the idea.

For library code with a clean entry point, libFuzzer needs less setup and runs faster in-process. AFL++ earns its place when the target is a program, when the source is awkward to wrap, or when you want its extra mutation strategies on the same corpus.

The target: an archive reader

The format is a header, a directory of entries and the data they point to.

OffsetSizeField
04magic ARC1
42entry count, little endian
616 eachentries: 8-byte name, 4-byte offset, 4-byte size

The reader loads the whole file, then prints the first byte of each entry. It checks the magic and the directory bounds but not the entry offsets.

arc.cc
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static uint32_t rd32(const uint8_t *p)
{
    return p[0] | (p[1] << 8) | (p[2] << 16) | ((uint32_t)p[3] << 24);
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "usage: %s file\n", argv[0]);
        return 2;
    }

    FILE *fp = fopen(argv[1], "rb");
    if (!fp)
        return 2;
    uint8_t *buf = malloc(1 << 16);
    size_t n = fread(buf, 1, 1 << 16, fp);
    fclose(fp);

    if (n < 6 || memcmp(buf, "ARC1", 4) != 0) {
        puts("bad header");
        return 1;
    }
    unsigned count = buf[4] | (buf[5] << 8);
    if (6 + (size_t)count * 16 > n) {
        puts("bad directory");
        return 1;
    }

    for (unsigned i = 0; i < count; i++) {
        const uint8_t *e = buf + 6 + i * 16;
        uint32_t off = rd32(e + 8);
        uint32_t size = rd32(e + 12);
        if (size > 0)
            printf("%.8s: first byte %02x\n", (const char *)e, buf[off]);   /* off is unchecked */
    }
    free(buf);
    return 0;
}

The 64 KiB heap buffer is deliberately larger than most inputs, which is realistic and makes the bug harder to see by hand: reading buf[off] for a small offset stays inside the allocation and returns stale bytes. Only a sanitizer, or an offset beyond 64 KiB, exposes it.

Build with the AFL++ compiler and AddressSanitizer

AFL++ ships compiler wrappers that add its coverage instrumentation. afl-clang-fast uses the LLVM plugin mode. Set AFL_USE_ASAN=1 to build with AddressSanitizer, so a memory error becomes an abort that AFL++ counts as a crash.

Shell
AFL_USE_ASAN=1 afl-clang-fast -g -O1 -fno-omit-frame-pointer arc.c -o arc_asan

If the compile succeeds, there is no output. Check the instrumentation is present before spending hours on a binary that is not instrumented. Running the program with afl-showmap prints how many coverage tuples a single input hits:

Shell
printf 'ARC1\x00\x00' > seed_empty.arc
afl-showmap -o /dev/null -m none -- ./arc_asan seed_empty.arc
Text
afl-showmap++4.21c by Michal Zalewski
[*] Executing './arc_asan'...

-- Program output begins --
-- Program output ends --

[+] Captured 4 tuples (map size 65536, highest value 1, total values 4) in '/dev/null'.

A non-zero tuple count confirms instrumentation. The version string, tuple count and map size depend on your build; zero tuples means the binary was compiled with the wrong compiler.

Create seeds

Give AFL++ at least one valid input, since a valid file starts it at the top of the format. Two small seeds are enough to begin: an empty archive and an archive with one entry.

Shell
mkdir -p in
printf 'ARC1\x00\x00' > in/empty.arc
printf 'ARC1\x01\x00name\x00\x00\x00\x00\x16\x00\x00\x00\x01\x00\x00\x00\x2a' > in/one.arc

The second seed holds one entry named name whose offset is 22, the first byte after the directory, and whose size is 1, followed by a single data byte * (0x2a). Keep seeds small: AFL++ mutates faster on short files, and the fuzzer will grow them as needed.

Run afl-fuzz

Shell
afl-fuzz -i in -o out -m none -- ./arc_asan @@

-i names the seed directory and -o the output directory. -m none removes the memory limit, which AddressSanitizer needs because it reserves a very large virtual address space. @@ is replaced with the path of each generated input file.

On a fresh Linux machine, afl-fuzz may stop with a message about the core dump pattern:

Text
[-] Hmm, your system is configured to send core dump notifications to an
    external utility. This will cause issues: there will be an extended delay
    between stumbling upon a crash and having this information relayed to the
    fuzzer via the standard waitpid() API.

The two fixes are to run echo core | sudo tee /proc/sys/kernel/core_pattern as root, or to set AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 in the environment, accepting that a crash can be missed. The first is the right choice on a dedicated fuzzing machine.

The status screen refreshes continuously. These fields tell you how the run is going:

  • run time and last new find show how long the fuzzer has run and how long since coverage grew.

  • cycles done counts full passes through the queue; the colour turns from magenta to cyan to green as it finds nothing new across more cycles.

  • map density shows what fraction of the coverage map your target touches, and the count of total paths (queue entries).

  • total crashes and total tmouts count findings; afl-fuzz stores each unique crash.

Within seconds the fuzzer finds an entry whose offset points far outside the 64 KiB buffer.

Read the crashes directory

Findings land under out/default/:

Text
out/default/
  crashes/
  hangs/
  queue/
  fuzzer_stats
  plot_data

Each crash file name encodes how it was found:

Shell
ls out/default/crashes
Text
id:000000,sig:06,src:000003,time:2384,execs:41239,op:havoc,rep:4
README.txt

id numbers the crash, and sig:06 is the signal that killed the process: signal 6, SIGABRT, which is what AddressSanitizer raises after printing its report. src is the queue entry that was mutated, time is milliseconds since the start, execs is the executions so far, op:havoc names the mutation stage and rep:4 the number of stacked mutations. The values here are examples and will differ.

Replay the file directly with the sanitized binary to get the report:

Shell
./arc_asan 'out/default/crashes/id:000000,sig:06,src:000003,time:2384,execs:41239,op:havoc,rep:4'
Text
=================================================================
==83210==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x631000014210 at pc 0x55a4e0f2a1d3 bp 0x7ffc4f8a5b50 sp 0x7ffc4f8a5b48
READ of size 1 at 0x631000014210 thread T0
    #0 0x55a4e0f2a1d2 in main arc.c:39:63
    #1 0x7f6b8d62a1c9 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16
...
0x631000014210 is located 1 bytes after 65536-byte region [0x631000004210,0x631000014210)
allocated by thread T0 here:
    #0 0x55a4e0ecc9ee in malloc (arc_asan+0x9e9ee)
    #1 0x55a4e0f29f8e in main arc.c:20:19
...
SUMMARY: AddressSanitizer: heap-buffer-overflow arc.c:39:63 in main

The access is one byte past the 65,536-byte block, the offset the fuzzer found. The fix is a range check before the read.

arc.cc
        if (size > 0) {
            if (off >= n)
                continue;                      /* entry points outside the file */
            printf("%.8s: first byte %02x\n", (const char *)e, buf[off]);
        }

Minimize the crash and the corpus

Crash inputs from havoc mutation are noisy, with many irrelevant bytes. afl-tmin shrinks one while it keeps the same behavior:

Shell
afl-tmin -i 'out/default/crashes/id:000000,sig:06,src:000003,time:2384,execs:41239,op:havoc,rep:4' -o crash_min.arc -m none -- ./arc_asan @@
Text
afl-tmin++4.21c by Michal Zalewski

[+] Read 89 bytes from 'out/default/crashes/id:000000,...'.
[*] Performing dry run (mem limit = 0 MB, timeout = 1000 ms)...
[+] Program terminates normally, minimizing in crash mode.
[*] Stage #0: One-time block normalization...
[+] Block normalization complete, 29 bytes replaced.
[*] --- Pass #1 ---
[*] Stage #1: Removing blocks of data...
[*] Stage #2: Minimizing symbols (22 code points)...
[*] Stage #3: Character minimization...
[+] Left with 24 bytes of 89 (26.97% of original).
[+] We're done here. Have a nice day!

That is the exact byte count of a one-entry archive: 6 header bytes plus 16 entry bytes plus a little data. The minimized file goes into your test suite. To shrink the whole queue, afl-cmin keeps the smallest subset with the same coverage:

Shell
afl-cmin -i out/default/queue -o in_min -m none -- ./arc_asan @@

Use in_min as the seed directory for the next run, so the campaign continues from what it learned.

Make the run faster and wider

Three settings change throughput the most. Build the target with -O1 or -O2 and without heavy debug options. Put the output directory on a RAM-backed filesystem such as /dev/shm to avoid writing queue files to disk. And avoid fork overhead with persistent mode, where a loop inside the process runs thousands of inputs per fork; the persistent mode post in this series shows the macros.

For more cores, run one main instance and several secondary ones that sync through the shared output directory:

Shell
afl-fuzz -i in -o out -M main -m none -- ./arc_asan @@
afl-fuzz -i in -o out -S s1 -m none -- ./arc_asan @@
afl-fuzz -i in -o out -S s2 -m none -- ./arc_asan @@

Run each command in its own terminal, or under tmux. The instances exchange queue entries every few minutes, so all of them benefit from one another's discoveries.

For input comparisons that block progress, such as a checked magic string or a checksum compare, AFL++ offers CMPLOG, which logs comparison operands so the fuzzer can copy the expected values into the input. Build a second binary with AFL_LLVM_CMPLOG=1 and pass it with -c:

Shell
AFL_LLVM_CMPLOG=1 afl-clang-fast -g -O1 arc.c -o arc_cmplog
afl-fuzz -i in -o out -m none -c ./arc_cmplog -- ./arc_asan @@

When AFL++ is the wrong choice

For a library function that takes a buffer, a libFuzzer harness is faster to write and runs in-process without fork or file I/O. For targets that need structure the byte-level mutators cannot produce, a custom mutator or a structure-aware tool is better. And for programs that spawn threads, open sockets or call fork themselves, the forkserver model gets awkward; wrap the parser or use a persistent harness instead.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.