Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Writing your first fuzz harness

After this lesson: I can write a harness that lets libFuzzer test one C function.

60 min lesson10 commandsCompilers and computer architecture lab: gcc, flex, bison and RISC-V in one VM

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The bug that only shows on exact bytes

A settings file says motto="be kind and forgets the closing quote. Your reader copes in every test you wrote.

But it is reading one byte beyond its input, and only a tool that hands it exactly that many bytes will ever see it.

The one rule

Warning

Fuzz only code you wrote or are asked to test, on your own lab machine. Testing somebody else's system needs their written permission. In the UK the Computer Misuse Act 1990 applies.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can write a harness that lets libFuzzer test one C function.

Key words

WordWhat it meansExample
Harnessthe small function that passes fuzz input to your code
libFuzzerclang's built-in fuzzer that calls a harness-fsanitize=fuzzer
Entry pointthe function the fuzzer calls for every inputLLVMFuzzerTestOneInput
Crash filethe input libFuzzer saves when the code fails
Out-of-bounds readreading memory past the end of a buffer

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A harness turns bytes into one call

AFL++ in lesson 1 ran a whole program and fed it a file. libFuzzer works inside the program instead: it calls one function of yours thousands of times a second.

First write the function under test, read_value, and its three tests. It copies the value of a setting, with or without quotes.

Write the setting reader

Command
mkdir -p ~/fuzz/value && cd ~/fuzz/value && cat > value.c <<'END'
#include <stddef.h>
#include <string.h>
int read_value(const char *line, size_t len, char out[32]) {
  const char *eq = memchr(line, '=', len);
  if (eq == NULL) return -1;
  size_t start = (size_t)(eq - line) + 1;
  size_t n = 0;
  if (start < len && line[start] == '"') {
    start++;
    while (start + n <= len && line[start + n] != '"') n++;
  } else {
    n = len - start;
  }
  if (n > 31) return -1;
  memcpy(out, line + start, n);
  out[n] = 0;
  return (int)n;
}
END

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write three tests and run them

Command
cd ~/fuzz/value && cat > test_value.c <<'END'
#include <stdio.h>
#include <string.h>
int read_value(const char *line, size_t len, char out[32]);
int main(void) {
  const char *cases[] = {"name=ann", "motto=\"be kind\"", "no setting here"};
  char out[32];
  for (int i = 0; i < 3; i++) {
    int n = read_value(cases[i], strlen(cases[i]), out);
    printf("%s -> %d %s\n", cases[i], n, n < 0 ? "" : out);
  }
  return 0;
}
END
gcc -Wall -g -o test_value value.c test_value.c && ./test_value

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

One function, called for every input

A libFuzzer harness is a function named LLVMFuzzerTestOneInput. It receives a pointer and a size, calls the code under test and returns 0.

Keep it like this: no exit, no saved state between calls, no printing, and hand over the bytes exactly as given. Build it with -fsanitize=fuzzer,address.

Write the harness

Command
cd ~/fuzz/value && cat > fuzz_value.c <<'END'
#include <stddef.h>
#include <stdint.h>
int read_value(const char *line, size_t len, char out[32]);

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  char out[32];
  read_value((const char *)data, size, out);
  return 0;
}
END

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Build the fuzzer

Command
cd ~/fuzz/value && clang -g -fsanitize=fuzzer,address -o fuzz-value value.c fuzz_value.c && file fuzz-value | cut -d, -f1

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Try it: a harness sorts each result

Code: python
import random
def read_value(line):
    if "=" not in line:
        raise ValueError("no setting")
    value = line.split("=", 1)[1]
    if value[0] == '"':
        return value[1:].split('"')[0]
    return value

def harness(data):
    try:
        read_value(data)
        return "ok"
    except ValueError:
        return "refused"
    except Exception as error:
        return "crash: " + type(error).__name__

rng = random.Random(3)
seen = {}
for _ in range(300):
    data = "".join(rng.choice('ab="') for _ in range(rng.randrange(6)))
    verdict = harness(data)
    if verdict not in seen:
        seen[verdict] = data
        print(repr(data), "->", verdict)

# Change value[0] == '"' to value.startswith('"'). Which verdicts are left?

Make a free account to save your work and track your progress.

Fuzz it for up to a minute

Command
cd ~/fuzz/value && rm -f crash-* && DEBUGINFOD_URLS= ./fuzz-value -seed=1 -max_total_time=60 > fuzz.log 2>&1; grep -E 'of size|SUMMARY|Test unit' fuzz.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Look at the bytes it saved

Command
cd ~/fuzz/value && od -c crash-*

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Run the crash file again

Command
cd ~/fuzz/value && DEBUGINFOD_URLS= ./fuzz-value crash-* 2>&1 | grep -E 'Running|SUMMARY'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people copy the fuzz bytes into a string and add a zero at the end, to make the harness "safe". That hides this exact bug. Pass the bytes and the size as they come, unless the real caller always adds a zero.

Stop at the end, not one past it

The quoted loop tests start + n <= len, so it looks at the byte at index len, which is not part of the input. The test must be <.

Fix it and run the crash file again. Then fuzz for another 30 seconds to see whether anything else turns up.

Fix the loop and replay the crash

Command
cd ~/fuzz/value && sed -i 's/start + n <= len/start + n < len/' value.c && grep -n 'start + n' value.c && clang -g -fsanitize=fuzzer,address -o fuzz-value value.c fuzz_value.c && DEBUGINFOD_URLS= ./fuzz-value crash-* 2>&1 | grep -E 'Running|SUMMARY|Executed'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Fuzz the fixed code for 30 seconds

Command
cd ~/fuzz/value && DEBUGINFOD_URLS= ./fuzz-value -seed=2 -max_total_time=30 > fuzz2.log 2>&1; echo "exit $?"; grep -c SUMMARY fuzz2.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

The crash file becomes a regression input

Move the crash file into regress with a name that says what it is. Given files instead of a folder to fuzz, the fuzzer runs each once and stops.

That is how the team keeps this bug fixed: the same command runs in every build.

Keep the input and replay the folder

Command
cd ~/fuzz/value && mkdir -p regress && mv crash-* regress/unclosed-quote && DEBUGINFOD_URLS= ./fuzz-value regress/* 2>&1 | grep -E 'Running|NOTE'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Worked example: weak and good harnesses

Harness doesWhy it mattersBetter
Adds a zero to the bytesHides reads past the endPass data and size as given
Calls exit on bad inputThe fuzzer stopsReturn 0
Keeps a global counterA crash cannot be replayedNo state between calls
Prints every inputThousands of times slowerPrint nothing

The cells students fill in are left blank in this preview.

Assignment: sort what a harness sees

A harness must tell an input the code rightly refused from an input that broke it. Write two functions.

verdict(target, data) calls target(data). Return "ok" if it returns normally, "rejected" if it raises ValueError (a refusal the code meant), and "crash" if it raises any other exception.

tally(target, inputs) returns a dictionary with the keys "ok", "rejected" and "crash", each counting how many of the inputs got that verdict. All three keys are always present.

Code: python
def verdict(target, data):
    return "ok"


def tally(target, inputs):
    return {}

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.