TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Sanitizers in CI and a First Look at Fuzzing

Sanitizers in CI and a First Look at Fuzzing

Every lesson of the bug-class section ended with the same sentence: "ASan finds it, if a test runs that code with that input". Two practices turn that "if" into a routine. Sanitizer builds in CI run the whole test suite under ASan, UBSan, TSan and (with Clang) MSan on every change, so a test that touches a bug fails at once. Fuzzing generates the inputs no one wrote a test for: millions of mutated inputs per hour, steered by code coverage, each run under a sanitizer. Google's OSS-Fuzz has run this combination continuously for open-source projects since 2016 and reported tens of thousands of bugs. This lesson sets both up for a toy parser; fuzzing in depth (writing a coverage-guided fuzzer, AFL++, corpus management, triage at scale) is part of the planned course Security Research.

A sanitizer matrix for CI

Sanitizers can't all go in one build (Your Toolkit), so CI runs a small matrix. A sketch of a GitHub Actions job (illustrative; adapt names and commands to your build system):

yaml
jobs:
  sanitizers:
    strategy:
      matrix:
        include:
          - name: asan-ubsan
            cflags: "-fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer"
          - name: tsan
            cflags: "-fsanitize=thread"
          - name: msan            # clang only; every dependency must be built with it
            cflags: "-fsanitize=memory -fsanitize-memory-track-origins"
    runs-on: ubuntu-24.04
    env:
      CC: clang
      CFLAGS: ${{ matrix.cflags }} -g -O1
      ASAN_OPTIONS: detect_leaks=1:abort_on_error=1:strict_string_checks=1
      UBSAN_OPTIONS: print_stacktrace=1
    steps:
      - uses: actions/checkout@v4
      - run: make clean all && make test

The details that matter: -fno-sanitize-recover so UBSan fails the job instead of printing and continuing; -O1 and -fno-omit-frame-pointer for readable stacks at bearable speed; leak detection on; and a failing job blocks the merge. A sanitizer report in CI is a bug, not a flaky test.

Fuzzing in one paragraph

A fuzz target (or harness) is a function that takes a byte array and feeds it to the code under test. A coverage-guided fuzzer (libFuzzer, AFL++, honggfuzz) starts from a corpus of sample inputs, mutates them (flip bits, insert bytes, splice inputs, try "interesting" values such as 0, 255, 0x7fffffff), runs the target, and keeps every mutant that reaches new code, measured by instrumentation the compiler inserted. Over time the corpus explores deeper and deeper into the parser. A sanitizer turns each memory error into a crash, and the fuzzer saves the crashing input as a file: a ready-made reproducer.

The fuzzing lab shows why the coverage feedback matters, on a toy parser that crashes only when the input starts with TAD!. In 50,000 executions with seed 1, pure random inputs reach 7 of its 12 branch edges and never crash (about one run in 6.9 × 10⁹ would). The coverage-guided fuzzer with havoc mutations keeps 8 inputs in its corpus, covers all 12 edges and finds the crash at execution 14,416; with a dictionary of the target's comparison bytes (what libFuzzer's -use_cmp and AFL++'s CmpLog provide) it needs only 828. Bit flips alone get stuck at 3 edges, because one flip can't turn the seed's a into T. Why Fuzzing Works takes the lab further.

target: parse(b, len)if (len < 4) return;if (b[0] == 'T') { if (b[1] == 'A') { if (b[2] == 'D') { if (b[3] == '!') crash();}}}if (b[len-1] == '\n') …dots: branch taken, random | guidedbranch edges covered (of 12)036912110^110^210^310^4executions (log scale)✕crash at 14,416randomguided: havocexecutions: 50,000random: 7 edges, crash not foundguided: 12 edges, crash at 14,416corpus: 8 inputs keptrandom: 1 crash in ≈ 6.9e9 runsa deterministic simulation with a fixed seed; toy target, no real program is fuzzed

Fuzzing the toy parser

The parser reads a record "LAB" + a one-byte length + a name. It correctly checks that the length fits in the input, but not that it fits in the 16-byte name buffer, the same "two lengths" mistake as the heap overflow lesson, here on the stack. The seed corpus is one valid record, LAB\x03bob. The session builds the harness with Clang's libFuzzer and ASan, fuzzes for at most 60 seconds with a fixed seed, checks the crash, fixes the bug, replays the crash file and fuzzes again. It runs in your sandbox, on one CPU core:

bash · try it yourself
cat > parse.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
#include <string.h>

/* Parses a record "LAB" + 1-byte length + name; copies the name into a fixed buffer. */
int parse_record(const uint8_t *data, size_t size) {
    char name[16];
    if (size < 4 || memcmp(data, "LAB", 3) != 0) return -1;
    size_t len = data[3];
    if (len > size - 4) return -1;               /* the input check is right ... */
    memcpy(name, data + 4, len);                 /* BUG: ... but len is never compared with sizeof name */
    return len ? name[0] : 0;
}
SRC
cat > fuzz.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
int parse_record(const uint8_t *data, size_t size);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    parse_record(data, size);
    return 0;
}
SRC
clang -g -O1 -fsanitize=fuzzer,address parse.c fuzz.c -o fuzz
mkdir corpus && printf 'LAB\x03bob' > corpus/seed
./fuzz -seed=1 -max_total_time=60 corpus > fuzz.log 2>&1; echo "fuzzer exit code: $?"
grep -m1 -oE 'AddressSanitizer: [a-z-]+' fuzz.log
grep -m1 -E '#1 .*parse_record' fuzz.log | sed 's/.* in /in /'
crash=$(ls crash-* | head -1)
python3 -c "import sys; d = open(sys.argv[1], 'rb').read(); print('crash input starts with', d[:3], '| length field > 16:', d[3] > 16, '| enough bytes follow:', len(d) - 4 >= d[3])" "$crash"
echo "== after the fix: replay the crash, then fuzz again"
sed -i 's|if (len > size - 4) return -1;               /\* the input check is right ... \*/|if (len > size - 4 \|\| len > sizeof name) return -1;|' parse.c
clang -g -O1 -fsanitize=fuzzer,address parse.c fuzz.c -o fuzz-fixed
./fuzz-fixed "$crash" > replay.log 2>&1; echo "replay exit code: $?"
./fuzz-fixed -seed=1 -runs=200000 corpus > fuzz2.log 2>&1; echo "200000 runs, exit code: $?, errors: $(grep -c ERROR fuzz2.log)"
fuzzer exit code: 1
AddressSanitizer: stack-buffer-overflow
in parse_record /home/learner/parse.c:11:5
crash input starts with b'LAB' | length field > 16: True | enough bytes follow: True
== after the fix: replay the crash, then fuzz again
replay exit code: 0
200000 runs, exit code: 0, errors: 0

What happened, step by step:

  1. Starting from one valid record, the fuzzer learned (through coverage feedback on the memcmp and the length check) to produce inputs that start with LAB, carry a length above 16 and enough bytes to pass the input check, and ASan stopped the memcpy at parse.c:11 with a stack-buffer-overflow. It usually takes only seconds. The exact crashing input differs between runs, so the session prints its properties instead of its bytes.
  2. libFuzzer wrote the input to crash-<sha1>, which reproduces the bug with ./fuzz crash-…. That file becomes a regression test: check it into the repository's corpus or test data so the bug can never silently return.
  3. After the fix (len > sizeof name rejected), replaying the crash exits 0 and 200,000 further runs find nothing.

The fuzzer's statistics lines (executions per second, coverage counters, memory) are left out because they differ from run to run.

Writing good fuzz targets

  • Small and fast: one parser entry point, no network, no disk, no global state that survives between inputs. Thousands of executions per second per core is the goal.
  • Deterministic: the same input must take the same path (fixed seeds inside, no time-dependence), or crashes won't reproduce.
  • Feed structure: for formats with checksums or compression, fix them up in the harness or use a structure-aware fuzzer; otherwise the fuzzer never gets past the first check.
  • A seed corpus of real samples (valid files from tests) and a dictionary of the format's keywords ("LAB", magic numbers) speed up exploration enormously.
  • Run it continuously: in CI for a few minutes per change (regressions), and in a long-running service such as OSS-Fuzz or ClusterFuzzLite for depth.

How findings are handled

Deduplicate crashes by sanitizer kind and top stack frames; minimise the input (./fuzz -minimize_crash=1 crash-…); classify severity (a WRITE is worse than a READ, a heap overflow with a controllable length is worse than a one-byte over-read); fix the root cause; add the input to the regression corpus. The next lesson section covers the fixing side, and From Crash to Patch shows the whole path for a vulnerability.

Pitfalls

  • Fuzzing without sanitizers finds only crashes; most memory bugs (over-reads, small overflows) don't crash.
  • Harnesses that catch everything: a try { … } catch (...) {} or a signal handler in the target hides the very crashes the fuzzer looks for.
  • Never fuzz what you aren't allowed to: fuzzing your own code locally is fine; sending fuzzed inputs to someone else's service is an attack (Authorization and Scope).

Practice

1. Why did the fuzzer need coverage feedback to find this bug quickly?

Random bytes almost never start with LAB, and also need a length above 16 with enough bytes behind it. Coverage feedback keeps the inputs that pass each check, so the fuzzer climbs through them one at a time instead of guessing all of them at once.

2. Write the one-line regression test that keeps this bug fixed.

Run the target on the saved crash file and assert a clean exit, e.g. ./fuzz-fixed tests/crash-parse-record-overflow in the test suite, under ASan. Or, in a unit test, call parse_record with a 4-byte header claiming length 17 followed by 17 bytes and check that it returns -1.

3. Why is -fno-sanitize-recover=undefined important in CI but not for libFuzzer?

In CI, recovering mode prints UBSan errors and exits 0, so the job passes. libFuzzer treats any sanitizer report as a crash only if it aborts; with UBSan you also need -fno-sanitize-recover (or UBSAN_OPTIONS=halt_on_error=1) there. In both cases: make the first report fatal.

Test yourself

What did the fuzzer save when it found the bug?

  1. A core dump
  2. The crashing input as a file crash-<sha1>, a ready-made reproducer
  3. A patch
  4. The coverage map

What makes a fuzzer 'coverage-guided'?

  1. It reads the source code
  2. It keeps mutated inputs that reach new code, measured by compiler instrumentation
  3. It tries every possible input
  4. It uses a GPU

Why does a CI sanitizer matrix have separate ASan, TSan and MSan jobs?

  1. For speed only
  2. They use incompatible shadow memory and can't be combined in one build
  3. TSan needs Windows
  4. MSan is GCC-only

Why did the session print properties of the crashing input instead of its bytes?

  1. The bytes are secret
  2. The exact input found differs between fuzzing runs; its properties (LAB prefix, length > 16) do not
  3. Python can't print bytes
  4. The file was deleted

In the fuzzing lab (seed 1, 50,000 executions), why does the coverage-guided fuzzer find the TAD! crash while random inputs don't?

  1. It runs more executions
  2. It keeps every input that reaches a new branch, so it can solve the four byte comparisons one at a time instead of all at once
  3. It reads the source code
  4. Random inputs are too short