TExcelTAD

Mutation, Generation and Grammar-Based Fuzzing

A mutation fuzzer is excellent at binary formats where any byte can be anything, and poor at formats with syntax: a JavaScript engine rejects almost every randomly mutated script on the first parse error, so the interesting code behind the parser is never reached. Fuzzers therefore differ in where inputs come from. This lesson compares the three main families on one toy target and shows when each one wins.

Three ways to make inputs

Family Inputs come from Needs Good for
Random (dumb) fresh random bytes or characters nothing very shallow code, robustness smoke tests
Mutation-based small changes to existing samples (the corpus), with or without coverage feedback a few valid samples binary formats, decoders, anything with a corpus
Generation-based built from a model of the format: a grammar, a protocol description, a schema someone writes the model languages and nested formats: interpreters, compilers, SQL, PDF, protocol messages

Grammar-based fuzzing is the most common generation approach: the format's grammar is turned into a random generator, so every input is syntactically valid and the target's parser always lets it through. Structure-aware fuzzing combines the two worlds: inputs are kept as structured objects (a tree, a protocol buffer), the fuzzer mutates the structure instead of the bytes, and coverage feedback still decides what to keep. libprotobuf-mutator with libFuzzer and JavaScript-engine fuzzers that mutate an intermediate language are examples of that design.

The target: a toy calculator with a seeded bug

The target evaluates expressions with digits, +, * and parentheses. Like many hand-written C parsers, it saves its partial result on a fixed-size stack at every (, here with 8 entries, and never checks the depth. The ninth nested parenthesis writes past the end. As in the previous lesson, store() is a bounds-checked write that plays the role of AddressSanitizer.

The three generators each make 5,000 inputs with the same seed (fixed for reproducible output):

  • random: 1 to 30 characters drawn from the calculator's own alphabet 0123456789+*(), which is already generous;
  • mutation: one of three valid seed expressions with one to four characters inserted or deleted;
  • grammar: generated from expr := term (op term)* and term := digit | "(" expr ")", with nesting chosen at random up to 12 levels.

It runs in your browser:

python · try it yourself
import random

class Crash(Exception):
    pass

def store(buf, i, v):
    """Bounds-checked write, the stand-in for AddressSanitizer."""
    if not 0 <= i < len(buf):
        raise Crash(f"out-of-bounds write at index {i} of an {len(buf)}-entry stack")
    buf[i] = v

def calc(text):
    """Toy calculator: digits, + and *, parentheses. Seeded bug: a fixed 8-entry stack."""
    saved = [None] * 8                 # partial results saved at each '('
    depth, acc, term, op = 0, 0, 1, "+"
    for ch in text:
        if ch.isdigit():
            term = term * int(ch) if op == "*" else int(ch)
            if op == "*":
                op = "+"
        elif ch == "+":
            acc, term = acc + term, 1
        elif ch == "*":
            op = "*"
        elif ch == "(":
            store(saved, depth, (acc, term, op))      # BUG: depth never checked against 8
            depth, acc, term, op = depth + 1, 0, 1, "+"
        elif ch == ")":
            if depth == 0:
                raise ValueError("unbalanced")
            depth -= 1
            inner = acc + term
            acc, term, op = saved[depth]
            term = term * inner if op == "*" else inner
            op = "+"
        else:
            raise ValueError("bad character")
    if depth:
        raise ValueError("unbalanced")
    return acc + term

def run(text):
    try:
        calc(text)
        return "valid"
    except ValueError:
        return "rejected"
    except Crash:
        return "CRASH"

# 1. Random strings over the calculator's alphabet.
def random_input(rng):
    return "".join(rng.choice("0123456789+*()") for _ in range(rng.randint(1, 30)))

# 2. Mutation of a seed corpus of valid expressions.
SEEDS = ["1+2", "(3*4)+5", "2*(1+(2+3))"]
def mutated_input(rng):
    s = list(rng.choice(SEEDS))
    for _ in range(rng.randint(1, 4)):
        i = rng.randrange(len(s) + 1)
        if rng.random() < 0.5:
            s.insert(i, rng.choice("0123456789+*()"))
        elif s:
            del s[min(i, len(s) - 1)]
    return "".join(s)

# 3. Generation from the grammar  expr := term (op term)* ; term := digit | "(" expr ")"
def gen_expr(rng, depth=0):
    parts = [gen_term(rng, depth)]
    while rng.random() < 0.3:
        parts += [rng.choice("+*"), gen_term(rng, depth)]
    return "".join(parts)

def gen_term(rng, depth):
    if depth < 12 and rng.random() < 0.55:
        return "(" + gen_expr(rng, depth + 1) + ")"
    return rng.choice("0123456789")

assert calc("2*(1+(2+3))") == 12 and calc("(3*4)+5") == 17
for name, make in [("random", random_input), ("mutation", mutated_input), ("grammar", gen_expr)]:
    rng = random.Random(7)
    counts, first = {"valid": 0, "rejected": 0, "CRASH": 0}, None
    for i in range(1, 5001):
        x = make(rng)
        r = run(x)
        counts[r] += 1
        if r == "CRASH" and first is None:
            first = (i, x)
    print(f"{name:<9} valid {counts['valid']:4d}  rejected {counts['rejected']:4d}  crashes {counts['CRASH']:4d}")
    if first:
        print(f"          first crash at input {first[0]}: {first[1]}")
random    valid 1344  rejected 3656  crashes    0
mutation  valid 3403  rejected 1597  crashes    0
grammar   valid 4711  rejected    0  crashes  289
          first crash at input 24: (((((((3))*((1))+((2*((6)))))))*(4)))*((4)*6+((8*7))+((((0)))))

Reading the numbers

  • Random strings are valid about a quarter of the time (short ones like 7 or 3+4), but balanced nesting nine levels deep almost never appears by chance: no crash.
  • Mutation keeps most inputs valid (3,403), because small edits to a valid expression often stay valid. But the seeds have at most two levels of nesting, and adding one parenthesis per edit almost always unbalances the expression. Without coverage feedback to keep the partial progress, it never gets deep. (A coverage-guided fuzzer would do better here, but depth is not a new branch: the same ( line runs at depth 3 and depth 9, so even coverage gives little guidance. This is a classic blind spot.)
  • Grammar inputs are all valid by construction (zero rejected), and deep nesting is just a probability in the generator: 289 crashes, the first on input 24.

The lesson generalises: when the bug sits behind syntax, generate; when it sits behind values in a binary layout, mutate with coverage; when you have both, use a structure-aware fuzzer.

Grammars in practice

Real grammar fuzzers derive the generator from a grammar file (ANTLR or a JSON/BNF description), weight the rules so that rare constructs still appear, and bound the depth and size so inputs stay fast. Browser and JavaScript-engine fuzzing has relied on generators for years, because the inputs (HTML, CSS, scripts) are languages. Protocol fuzzers describe messages field by field, with lengths and checksums computed automatically, so every message gets past the framing (Protocol Fuzzing).

Writing the grammar is work, and the grammar is also a bias: the fuzzer only produces what the grammar describes. Bugs in error handling (unbalanced input, invalid characters) need invalid inputs too, so good setups mix generated and mutated inputs.

How such bugs are detected and prevented

Detection is the oracle again: the bounds-checked store() here, ASan in C. Prevention for this bug class is to bound recursion and nesting explicitly, with a limit that the parser enforces and documents (if depth >= 8: reject), or to use a growable stack. Recursion-depth limits matter in memory-safe languages too: an unbounded recursive-descent parser in Python, Java or Rust turns deep nesting into a stack overflow, a denial of service (CWE-674, uncontrolled recursion). Every parser of nested data (JSON, XML, YAML, expressions) needs a depth limit.

Pitfalls

  • A grammar that is too polite. If it never generates edge cases (empty input, maximum lengths, deep nesting), it will not find edge-case bugs. Add weights and limits deliberately.
  • Measuring validity instead of bugs. 100% valid inputs is the point of a grammar fuzzer, not a success metric; crashes and new coverage are.
  • Forgetting invalid inputs. Error paths are attack surface too.
  • Unbounded generation. A recursive grammar without a depth bound can produce enormous inputs and slow the campaign to a crawl.

Practice

1. Fix the calculator and re-run. What should the three lines print?

Add if depth >= len(saved): raise ValueError("nesting too deep") before store. Random and mutation stay the same; grammar now shows 0 crashes and the former crashes become "rejected" (289 of them).

2. Change the grammar's nesting probability from 0.55 to 0.3. Predict the effect.

Deep nesting becomes much rarer (the chance of nine nested levels drops sharply), so crashes become rare or disappear in 5,000 inputs. Weights decide which bugs a grammar fuzzer can reach.

3. Why does coverage feedback help little for this particular bug?

Nesting deeper executes the same lines and branches as nesting shallower; no new edge appears at depth 5 or 8. Coverage-guided fuzzers use hit-count buckets and, in some tools, value profiles or custom feedback (for example depth as a metric) to reward such progress.

Test yourself

When does a grammar-based fuzzer beat a mutation fuzzer?

  1. For compressed binary files
  2. When the bug sits behind syntax that random edits almost always break, such as deep but balanced nesting
  3. Always
  4. Never

Why did the mutation fuzzer find nothing here?

  1. It was too slow
  2. Single-character edits of shallow seeds rarely produce nine balanced nested levels, and nothing kept partial progress
  3. It had no oracle
  4. Its seeds were invalid

What is structure-aware fuzzing?

  1. Fuzzing source code
  2. Mutating a structured representation (tree, protobuf) with coverage feedback, then serialising it
  3. Fuzzing without a corpus
  4. Manual testing

Which defence prevents the calculator's bug class in any language?

  1. A larger fixed stack
  2. An explicit, enforced nesting-depth limit (or a growable stack)
  3. Rewriting in Python
  4. Turning off optimisation