Algorithm Search⌘K

Algorithmintro

Mutation-based fuzzing

Also called blackbox mutational fuzzing, dumb fuzzing.

Makes new inputs by random bit flips, byte changes, insertions and splices of seed inputs, with no feedback from the program.

Time
O(N (K L + T)) worst
Space
O(L) extra
Where
K = the largest number of stacked mutations; L = the length bound of an input; N = the number of runs; T = the cost of one run of the target
Properties
randomizedrandomized
Origin
Barton P. Miller, Lars Fredriksen, Bryan So, 1990

Mutation-based fuzzing makes test inputs by changing valid example inputs, the seeds, at random: it flips a bit, sets a byte, inserts or deletes a byte, or splices two seeds together, and runs the program on the result. A run that crashes is saved. The program gives no feedback: whatever a run does, the next run starts again from a seed, so the inputs are independent draws from one fixed distribution. That makes the method easy to build and to analyse, and it is the base that coverage-guided fuzzing extends with a queue of interesting inputs. Its weakness follows from the same fact: a check that needs two bytes to be right at once must be passed by two lucky mutations in the same run.

In plain words

Take a file that the program reads correctly, for example a small picture. Make a copy and damage it a little: change one bit, replace one byte with a random byte, add a byte, remove a byte, or glue the start of this file to the end of another one. Do this a few times on the copy. Give the damaged copy to the program and watch it. If the program crashes, keep the copy for a person to look at. Then start again from a clean seed. The seeds keep the input close to the expected format, so the program does not reject it at the first byte, and the damage reaches code that handles odd cases. The program never tells the fuzzer which changes were useful, so a change that got halfway through a check is thrown away like the others.

The problem

The input is a target PP that maps a byte string to an outcome (it returns, or it fails), a nonempty list of seeds, a number of runs NN, a largest stack size KK, a length bound LL and a random number generator. The output is the list of runs whose input made PP fail, with the inputs. A failure here is an exception of the target; for a real program it is a crash, a failed assertion or a sanitizer report, and a fuzzer also needs a time limit for hangs.

Nothing in the output says that the target has no bug. The question "does some input make PP fail" is undecidable for general programs (Rice's theorem), and the fuzzer does not try to decide it. It samples.

The algorithm

  1. MUTATION-FUZZ(P, seeds, N, K, L, rng)
  2. 1crashes <- empty list
  3. 2for r <- 1 to N do
  4. 3x <- a copy of a seed chosen uniformly at random
  5. 4k <- a number chosen uniformly from 1 to K
  6. 5repeat k times: x <- MUTATE(x, seeds, L, rng)
  7. 6outcome <- run P on x
  8. 7if outcome is a failure then append (r, x) to crashes
  9. 8return crashes
  10. MUTATE(x, seeds, L, rng)
  11. 9ops <- the operators that apply to x: flip, set and delete need |x| > 0; insert needs |x| < L; splice always applies
  12. 10op <- an operator chosen uniformly from ops
  13. 11flip: choose a position i and a bit b uniformly; flip bit b of x[i]
  14. 12set: choose a position i and a value v from 0 to 255 uniformly; x[i] <- v
  15. 13insert: choose a position i from 0 to |x| and a value v uniformly; insert v before position i
  16. 14delete: choose a position i uniformly; remove x[i]
  17. 15splice: choose a seed y, a cut i from 0 to |x| and a cut j from 0 to |y| uniformly; x <- the first L bytes of x[0 .. i) followed by y[j ..)
  18. 16return x

Each run is independent of the others: line L3 starts from a clean seed, and nothing that line L6 sees goes back into the choices. Lines L4 and L5 stack several mutations, as the havoc stage of AFL does, because some changes need more than one edit. The five operators are the usual ones of the survey of Manès et al. and of the Fuzzing Book; the list and the uniform choices are design choices, and real fuzzers add more, such as adding small numbers to a byte or a word, setting "interesting" values like 0, 255 or the largest signed integer, and copying blocks of bytes.

Example

The target fails on inputs that start with bad. It checks one byte at a time, in three nested branches. There is one seed, bat.

One mutation from bat. With K=1K = 1, all five operators apply, each with probability 1/51/5. Three choices give bad...: flip bit 4 of byte 2 (t is 0x74 and d is 0x64, so they differ in one bit), probability 15⋅13⋅18\frac15 \cdot \frac13 \cdot \frac18; set byte 2 to d, probability 15⋅13⋅1256\frac15 \cdot \frac13 \cdot \frac1{256}; insert d before position 2, which gives badt, probability 15⋅14⋅1256\frac15 \cdot \frac14 \cdot \frac1{256}. Delete and splice with the seed itself cannot make a d. So one run fails with probability

q=15(124+1768+11024)=0.0087891,q = \frac15 \left(\frac1{24} + \frac1{768} + \frac1{1024}\right) = 0.0087891,

and the number of runs until the first failure is geometric with mean 1/q=113.81/q = 113.8. The test file computes qq exactly by listing all 1835 choices of one mutation (24 flips, 768 sets, 1024 inserts, 3 deletes and 16 splices), and checks a campaign of 20000 runs against it with a Hoeffding margin. The bit flip gives 95 percent of qq: a one-bit change of a letter is far more likely to be hit by a flip than by a random byte.

A trace. With K=2K = 2 and generator seed 1 (Python's random.Random(1)), the first eight runs are these. A byte that is not printable is written as \x and two hex digits.

run k input outcome
1 1 \xfdbat returns
2 2 au returns
3 2 \xa2att returns
4 1 bau returns
5 1 ba returns
6 1 bt returns
7 2 bp returns
8 2 b4 returns

Run 4 flipped a bit of byte 2, but bit 0 and not bit 4. Runs 4 and 5 passed the first two checks, as the seed does. Nothing is kept: each run starts again from bat.

Two bytes away. Start from the seed bxt instead. Now byte 1 and byte 2 are both wrong, and one mutation can fix at most one of them, so with K=1K = 1 the probability is exactly 0. With K=2K = 2, a run fails with probability 2.36×10−62.36 \times 10^{-6} (computed by listing every pair of mutations), so the mean number of runs is about 424000, against 114 when one byte was wrong. A greybox fuzzer splits the problem in two. One mutation of bxt fixes byte 1 with probability 15(1768+11024)\frac15(\frac1{768} + \frac1{1024}), about once in 2194 runs; that input reaches a new branch and is kept as a seed, and if it is bat, the last byte takes about 114 more runs. The sum of the two steps is near 2300 runs, not 424000. This gap, multiplied over every multi-byte check of a real parser, is the reason for coverage feedback.

Correctness

The full proof is in the proof file. The algorithm promises little, and it keeps all of it:

  1. Every reported failure is real. Each pair (r,x)(r, x) in the result was run in line L6 and failed, and the target is deterministic, so running xx again fails again.
  2. Inputs stay in bounds. Each MUTATE result has length at most LL, by induction over the operators of lines L11 to L15.
  3. No feedback. The inputs of the runs are a function of the random stream alone; they do not depend on the outcomes. So the inputs of different runs are independent and identically distributed, the number of failures in NN runs is binomial with parameters NN and qq, and the first failure comes after a geometric number of runs with mean 1/q1/q, where qq is the failure probability of one run.
  4. The seeds do not change, because line L3 copies.

The key invariant is item 3: line L3 resets the state of the run to a fresh seed. It is what makes the analysis simple, and what the greybox loop gives up.

Proof: Correctness of mutation-based fuzzingfull

We prove the claims of the Correctness section for MUTATION-FUZZ (lines L1 to L8) and MUTATE (lines L9 to L16). The target PP is deterministic: the same input always gives the same outcome. Every seed has length at most LL, the list of seeds is not empty, and K≥1K \ge 1.

Claim 1 (bounds). If ∣x∣≤L|x| \le L, then MUTATE returns a string of length at most LL, and the operator chosen in line L10 can be applied.

Proof. Line L9 puts flip, set and delete in the list only if ∣x∣>0|x| > 0, so a position exists for lines L11, L12 and L14. Flip and set keep the length, and delete makes it shorter. Insert is in the list only if ∣x∣<L|x| < L, so line L13 gives length ∣x∣+1≤L|x| + 1 \le L. Splice is always in the list; its cut ii is in 0 to ∣x∣|x| and its cut jj is in 0 to ∣y∣|y|, so both slices exist, and line L15 keeps only the first LL bytes. The list is never empty, because splice is always in it. □\square

By induction over the kk calls of line L5, starting from a seed of length at most LL in line L3, every input that line L6 runs has length at most LL.

Claim 2 (no false reports). Every pair (r,x)(r, x) in the result is an input on which PP fails.

Proof. Line L7 appends (r,x)(r, x) only when the outcome of line L6 on xx was a failure, and nothing changes xx between lines L6 and L7. Since PP is deterministic, PP fails on xx again. □\square

Claim 3 (seeds are kept). The seeds after the call are the same as before.

Proof. Line L3 makes a copy, and MUTATE works on a new byte array and returns a new string, so no line writes into a seed. □\square

Claim 4 (independence). Let XrX_r be the input of run rr. The variables X1,…,XNX_1, \dots, X_N are independent and have the same distribution DD, which depends only on the seeds, KK and LL.

Proof. Model the generator as a source of independent uniform choices. Run rr reads fresh choices in line L3 (the seed), line L4 (kk) and lines L10 to L15 (the operators and their arguments). By Claim 3 the seeds are the same at the start of every run, and no line reads the outcome of line L6 except line L7, which only writes to the result. So XrX_r is the same function of the fresh choices of run rr in every run, and the choices of different runs are disjoint. Functions of disjoint sets of independent choices are independent and, being the same function, have the same distribution. □\square

Claim 5 (rates). Let qq be the probability that PP fails on an input drawn from DD. The number of failures in NN runs has the binomial distribution with parameters NN and qq, and if q>0q > 0, the number of the first failing run has the geometric distribution with mean 1/q1/q.

Proof. Let FrF_r be 1 if run rr fails. FrF_r is a function of XrX_r, because PP is deterministic, so by Claim 4 the FrF_r are independent Bernoulli variables with parameter qq. Their sum is binomial with parameters NN and qq. The first rr with Fr=1F_r = 1 is rr with probability (1−q)r−1q(1 - q)^{r - 1} q, which is the geometric distribution, and its mean is ∑r≥1r(1−q)r−1q=1/q\sum_{r \ge 1} r (1 - q)^{r - 1} q = 1/q. □\square

Claim 6 (the example). For the seed bat, K=1K = 1 and the target that fails on inputs that start with bad, q=15(124+1768+11024)q = \frac15(\frac1{24} + \frac1{768} + \frac1{1024}).

Proof. All five operators apply, each with probability 1/51/5. A result starts with bad only if its first two bytes stay ba and its third byte becomes d. Flip: of the 24 choices, only bit 4 of byte 2 changes t (0x74) to d (0x64), probability 1/241/24. Set: only the value d at byte 2, probability 13⋅1256\frac13 \cdot \frac1{256}. Insert: only d before position 2, probability 14⋅1256\frac14 \cdot \frac1{256}; inserting at positions 0 or 1 changes byte 0 or byte 1, and at position 3 leaves bat in front. Delete gives a string of length 2. Splice of bat with itself gives a prefix of bat followed by a suffix of bat; its third byte, if it has one, is a byte of bat, never d. Add the three cases and multiply by 1/51/5. □\square

Claims 1 to 5 together are the Correctness section of the page: every report is a real failure, every input is in bounds, the seeds are kept, and the runs are independent draws, so the number of failures is binomial and the wait for the first is geometric. Claim 6 is the number of the worked example, which the tests also check by listing every choice. ■\blacksquare

Complexity

Line L3 copies a seed, O(L)O(L). Each MUTATE copies the input into a byte array and changes it; insert, delete and splice shift up to LL bytes, so each mutation costs O(L)O(L) and a run costs O(KL)O(KL) before the target. With TT the cost of one run of the target, the total time is O(N(KL+T))O(N(KL + T)) in the word RAM model. In practice TT dominates by orders of magnitude: a real fuzzer spends almost all of its time in the target, which is why it runs the target in a fork server or in the same process. The extra space is O(L)O(L) for the input, plus the saved failures.

Properties

  • Randomized, and repeatable with a fixed seed. The same generator seed gives the same inputs.
  • No false alarms. Every reported input fails when run again (for a deterministic target).
  • No completeness. A campaign of any length can miss every bug.
  • Memoryless. No run uses what an earlier run found. This makes rates easy to estimate and multi-byte checks very hard to pass.
  • Seed-dependent. The distribution of inputs is fixed by the seeds and the operators; a bug far from every seed is out of reach in practice.

Variants and improvements

  • Generation instead of mutation. Miller's 1990 study fed random characters with no seeds; grammar-based fuzzing generates inputs from a model of the format, so that the parser accepts them.
  • Coverage feedback. Coverage-guided fuzzing keeps every mutated input that reaches new code, measured by an edge coverage bitmap, and mutates those inputs later. This removes the memoryless property and with it the product of small probabilities of the example.
  • Scheduling seeds. Woo et al. (2013) model a campaign over many (program, seed) pairs and treat the choice of the next pair as a multi-armed bandit problem, and compare 26 scheduling algorithms by measurement in the CERT Basic Fuzzing Framework. The choice of schedule is a heuristic; its value is a measured bug count on their benchmark. The greybox form of this idea is the power schedule.
  • Choosing seeds. Rebert et al. (2014) showed by experiment that the seed files change the number of bugs found, and choose them by corpus minimization.
  • Dictionaries and magic values. Insert tokens of the format (keywords, magic numbers) as one mutation, which turns a many-byte check into one choice.
  • Deterministic stages. AFL first walks each seed through all single bit flips, byte flips and small arithmetic changes in order, and only then uses random stacked mutations.

When to use it

Use it when the program cannot be instrumented, for example a closed binary or a remote device that only accepts inputs, and when good seed files exist. It needs nothing but a way to run the program and to see a failure. When instrumentation is possible, coverage-guided fuzzing finds deeper bugs in the same time, and when the input has a strict grammar, a generator of valid inputs wastes fewer runs on the parser's error paths.

Pitfalls

  • Mutating the seed itself. Writing line L3 as x <- a seed with an in-place byte array changes the seed, and later runs start from damaged seeds that drift away from the format. The right line copies the seed.
  • Off by one in insert. Choosing ii from 0 to ∣x∣−1|x| - 1 in line L13 can never append a byte at the end. The right range is 0 to ∣x∣|x|, which has ∣x∣+1|x| + 1 positions.
  • Zero mutations. Choosing kk from 0 in line L4 runs the unchanged seed again and again. The right range is 1 to KK.
  • Ignoring hangs. Line L6 needs a time limit; a target that loops forever stops a fuzzer that waits for it, and a hang is a finding too.
  • Counting crashes as bugs. Many failing inputs come from one bug. Group them with crash bucketing, and compare fuzzers by bugs, not crashes.
  • One generator seed for parallel instances. Two instances with the same generator seed make the same inputs.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

mutation_based_fuzzing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mutation-based-fuzzing/. The authors are listed in prov/GG8WSX.jsonl.
"""Mutation-based fuzzing with no feedback from the program.

Each run copies a seed chosen uniformly at random, applies k random
mutations with k uniform from 1 to K, and runs the target on the result.
A run whose target raises an exception is a crash. Nothing that the run
does changes later runs: the seeds stay as they are, and no input is kept
for its behavior. This is the blackbox loop that greybox fuzzing extends
with a queue.

The five mutation operators (flip one bit, set one byte, insert one byte,
delete one byte, splice with a seed) and the uniform choices between them
are design choices, the usual ones in the literature, not a theorem.

The target is any Python callable on bytes. The tests use small functions
with nested branches on bytes; nothing here runs a real program.
"""

import random
from dataclasses import dataclass, field
from typing import Callable, Sequence

FLIP, SET, INSERT, DELETE, SPLICE = "flip", "set", "insert", "delete", "splice"


def applicable_operators(x: bytes, max_len: int) -> list[str]:
    """Return the operators that can change x, in a fixed order.

    Flip, set and delete need a byte; insert needs room below max_len.
    Splice always applies. Cost: O(1).
    """
    ops = []
    if len(x) > 0:
        ops += [FLIP, SET]
    if len(x) < max_len:
        ops.append(INSERT)
    if len(x) > 0:
        ops.append(DELETE)
    ops.append(SPLICE)
    return ops


def mutate(x: bytes, seeds: Sequence[bytes], rng: random.Random, max_len: int) -> bytes:
    """Apply one random mutation to x and return the new input.

    Precondition: seeds is not empty, len(x) <= max_len, max_len >= 1.
    The result has length at most max_len. Cost: O(L) to copy, with L the
    larger of max_len and the longest seed.
    """
    ops = applicable_operators(x, max_len)  # @line L9
    op = ops[rng.randrange(len(ops))]  # @line L10
    b = bytearray(x)
    if op == FLIP:
        i = rng.randrange(len(b))
        bit = rng.randrange(8)
        b[i] ^= 1 << bit  # @line L11
    elif op == SET:
        i = rng.randrange(len(b))
        b[i] = rng.randrange(256)  # @line L12
    elif op == INSERT:
        i = rng.randrange(len(b) + 1)
        b.insert(i, rng.randrange(256))  # @line L13
    elif op == DELETE:
        i = rng.randrange(len(b))
        del b[i]  # @line L14
    else:
        y = seeds[rng.randrange(len(seeds))]
        i = rng.randrange(len(b) + 1)
        j = rng.randrange(len(y) + 1)
        b = (b[:i] + y[j:])[:max_len]  # @line L15
    return bytes(b)  # @line L16


@dataclass
class FuzzResult:
    """The outcome of a campaign: the crashing runs as (run number, input,
    exception name), and the number of runs made."""

    crashes: list[tuple[int, bytes, str]] = field(default_factory=list)
    runs: int = 0


def mutation_fuzz(
    target: Callable[[bytes], object],
    seeds: Sequence[bytes],
    runs: int,
    rng: random.Random,
    max_stack: int = 4,
    max_len: int = 64,
    trace: list[tuple[int, bytes, int, bytes, bool]] | None = None,
) -> FuzzResult:
    """Run the blackbox mutation loop for a fixed number of runs.

    A crash is a run in which target raises an Exception. If trace is a
    list, one tuple (run, seed, k, input, crashed) is appended per run.

    Precondition: seeds is not empty and every seed has length at most
    max_len; runs >= 0; max_stack >= 1. Cost: O(N (K L + T)) for N runs,
    K = max_stack, L the length bound and T the cost of one target call.
    """
    if not seeds:
        raise ValueError("at least one seed is needed")
    if any(len(s) > max_len for s in seeds):
        raise ValueError("a seed is longer than max_len")
    result = FuzzResult()  # @line L1
    for r in range(1, runs + 1):  # @line L2
        seed = seeds[rng.randrange(len(seeds))]
        x = bytes(seed)  # @line L3
        k = rng.randint(1, max_stack)  # @line L4
        for _ in range(k):
            x = mutate(x, seeds, rng, max_len)  # @line L5
        crashed = False
        name = ""
        try:
            target(x)  # @line L6
        except Exception as e:  # noqa: BLE001, a crash of the toy target
            crashed = True
            name = type(e).__name__
        if crashed:
            result.crashes.append((r, x, name))  # @line L7
        if trace is not None:
            trace.append((r, seed, k, x, crashed))
        result.runs = r
    return result  # @line L8
test_mutation_based_fuzzing.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mutation-based-fuzzing/. The authors are listed in prov/GG8WSX.jsonl.
import itertools
import math
import random
from fractions import Fraction

import pytest

from mutation_based_fuzzing import applicable_operators, mutate, mutation_fuzz


class Crash(Exception):
    pass


def bad_target(x: bytes) -> None:
    """The target of the page: it fails on inputs that start with b"bad"."""
    if len(x) >= 1 and x[0] == ord("b"):
        if len(x) >= 2 and x[1] == ord("a"):
            if len(x) >= 3 and x[2] == ord("d"):
                raise Crash("bad")


def one_step_distribution(x, seeds, max_len):
    """Exact distribution of one mutation, by listing every choice."""
    out = {}
    ops = []
    if x:
        ops.append(("flip", [(i, bit) for i in range(len(x)) for bit in range(8)]))
        ops.append(("set", [(i, v) for i in range(len(x)) for v in range(256)]))
    if len(x) < max_len:
        ops.append(("insert", [(i, v) for i in range(len(x) + 1) for v in range(256)]))
    if x:
        ops.append(("delete", list(range(len(x)))))
    ops.append(("splice", [(s, i, j) for s in range(len(seeds))
                           for i in range(len(x) + 1) for j in range(len(seeds[s]) + 1)]))
    for name, choices in ops:
        for c in choices:
            if name == "splice":
                # seed, then cut i in x, then cut j in that seed, each uniform
                w = Fraction(1, len(ops) * len(seeds) * (len(x) + 1) * (len(seeds[c[0]]) + 1))
            else:
                w = Fraction(1, len(ops) * len(choices))
            if name == "flip":
                i, bit = c
                y = x[:i] + bytes([x[i] ^ (1 << bit)]) + x[i + 1:]
            elif name == "set":
                i, v = c
                y = x[:i] + bytes([v]) + x[i + 1:]
            elif name == "insert":
                i, v = c
                y = x[:i] + bytes([v]) + x[i:]
            elif name == "delete":
                y = x[:c] + x[c + 1:]
            else:
                s, i, j = c
                y = (x[:i] + seeds[s][j:])[:max_len]
            out[y] = out.get(y, 0) + w
    return out


def crash_probability_one_mutation(seed):
    dist = one_step_distribution(seed, [seed], 64)
    total = Fraction(0)
    for y, p in dist.items():
        try:
            bad_target(y)
        except Crash:
            total += p
    return total


def test_page_example_exact_probability():
    q = crash_probability_one_mutation(b"bat")
    assert q == Fraction(1, 5) * (Fraction(1, 24) + Fraction(1, 768) + Fraction(1, 1024))
    assert round(float(q), 7) == 0.0087891
    assert round(1 / float(q), 1) == 113.8


def test_page_example_trace():
    trace = []
    res = mutation_fuzz(bad_target, [b"bat"], 8, random.Random(1), max_stack=2, trace=trace)
    assert res.runs == 8 and len(trace) == 8
    for r, seed, k, x, crashed in trace:
        assert seed == b"bat" and 1 <= k <= 2 and len(x) <= 64
        assert crashed == x.startswith(b"bad")
    assert [c[0] for c in res.crashes] == [t[0] for t in trace if t[4]]
    # The exact table of the page.
    assert [(t[2], t[3]) for t in trace] == [
        (1, b"\xfdbat"), (2, b"au"), (2, b"\xa2att"), (1, b"bau"),
        (1, b"ba"), (1, b"bt"), (2, b"bp"), (2, b"b4"),
    ]
    assert res.crashes == []


def test_page_example_choice_count_and_greybox_first_step():
    # 24 flips, 768 sets, 1024 inserts, 3 deletes and 16 splices from b"bat".
    assert 3 * 8 + 3 * 256 + 4 * 256 + 3 + 4 * 4 == 1835
    dist = one_step_distribution(b"bxt", [b"bxt"], 64)
    p = sum(w for y, w in dist.items() if y[:2] == b"ba")
    assert p == Fraction(1, 5) * (Fraction(1, 768) + Fraction(1, 1024))
    assert round(1 / float(p)) == 2194


def test_monte_carlo_matches_exact_rate():
    q = float(crash_probability_one_mutation(b"bat"))
    n = 20000
    res = mutation_fuzz(bad_target, [b"bat"], n, random.Random(5), max_stack=1)
    rate = len(res.crashes) / n
    margin = math.sqrt(math.log(2 / 1e-6) / (2 * n))  # Hoeffding, failure chance 1e-6
    assert abs(rate - q) <= margin
    assert all(x.startswith(b"bad") and name == "Crash" for _, x, name in res.crashes)


def test_two_bytes_away_needs_two_mutations():
    # From b"bxt" one mutation can fix at most one wrong byte of b"bad".
    assert crash_probability_one_mutation(b"bxt") == 0


def test_seeds_are_not_changed_and_no_feedback():
    seeds = [b"abc", b"xyz"]
    copy = [bytes(s) for s in seeds]
    t1 = []
    t2 = []
    mutation_fuzz(lambda x: None, seeds, 300, random.Random(9), trace=t1)
    # A target that crashes on everything gives the same inputs: the loop has no feedback.
    def always(x):
        raise Crash()
    mutation_fuzz(always, seeds, 300, random.Random(9), trace=t2)
    assert seeds == copy
    assert [t[3] for t in t1] == [t[3] for t in t2]


def test_edge_cases():
    with pytest.raises(ValueError):
        mutation_fuzz(bad_target, [], 1, random.Random(0))
    with pytest.raises(ValueError):
        mutation_fuzz(bad_target, [b"aaaa"], 1, random.Random(0), max_len=3)
    assert mutation_fuzz(bad_target, [b"bat"], 0, random.Random(0)).runs == 0
    rng = random.Random(3)
    for _ in range(200):
        y = mutate(b"", [b""], rng, 1)
        assert len(y) <= 1  # from the empty input only insert and splice apply
    assert applicable_operators(b"", 4) == ["insert", "splice"]
    assert applicable_operators(b"abcd", 4) == ["flip", "set", "delete", "splice"]


def test_random_mutations_are_in_the_exact_support():
    rng = random.Random(11)
    for _ in range(600):
        max_len = rng.randint(1, 4)
        seeds = [bytes(rng.randrange(4) for _ in range(rng.randint(0, max_len)))
                 for _ in range(rng.randint(1, 3))]
        x = bytes(rng.randrange(256) for _ in range(rng.randint(0, max_len)))
        support = one_step_support(x, seeds, max_len)
        y = mutate(x, seeds, rng, max_len)
        assert y in support
        assert len(y) <= max_len
    # The exact distribution sums to 1 on a few cases.
    for x, seeds in [(b"", [b""]), (b"ab", [b"ab", b"c"]), (b"xyz", [b"q"])]:
        dist = one_step_distribution(x, seeds, 4)
        assert sum(dist.values()) == 1 and set(dist) == one_step_support(x, seeds, 4)


def one_step_support(x, seeds, max_len):
    """Every input that one mutation of x can give, by listing the choices."""
    out = set()
    if x:
        out |= {x[:i] + bytes([x[i] ^ (1 << bit)]) + x[i + 1:] for i in range(len(x)) for bit in range(8)}
        out |= {x[:i] + bytes([v]) + x[i + 1:] for i in range(len(x)) for v in range(256)}
        out |= {x[:i] + x[i + 1:] for i in range(len(x))}
    if len(x) < max_len:
        out |= {x[:i] + bytes([v]) + x[i:] for i in range(len(x) + 1) for v in range(256)}
    out |= {(x[:i] + s[j:])[:max_len] for s in seeds for i in range(len(x) + 1) for j in range(len(s) + 1)}
    return out


def test_crashes_are_exactly_the_failing_inputs_of_brute_force():
    # All inputs of length up to 3 over a small alphabet that make the target fail.
    alphabet = b"abdt"
    failing = set()
    for n in range(4):
        for t in itertools.product(alphabet, repeat=n):
            x = bytes(t)
            try:
                bad_target(x)
            except Crash:
                failing.add(x)
    assert failing == {b"bad"}
    rng = random.Random(4)
    for _ in range(50):
        trace = []
        res = mutation_fuzz(bad_target, [b"bat", b"ba"], 40, rng, max_stack=3, max_len=3, trace=trace)
        crashed_inputs = {x for _, x, _ in res.crashes}
        assert crashed_inputs <= {b"bad"}
        assert crashed_inputs == {x for _, _, _, x, c in trace if c}

History

Miller, Fredriksen and So ran random character streams against UNIX utilities in 1990 and made between a quarter and a third of them crash or hang; this started fuzz testing. File format and protocol fuzzers of the following years mutated valid samples instead, because random bytes rarely pass the first check of a parser. Woo, Cha, Gottlieb and Brumley (2013) gave a mathematical model of a campaign of this kind and studied how to schedule it, and Rebert et al. (2014) studied how to choose its seeds. AFL (2013) added coverage feedback to the same mutation operators, and most new fuzzers since then are greybox, with blackbox mutation kept for targets that cannot be instrumented.

References

  1. Andreas Zeller, Rahul Gopinath, Marcel Böhme, Gordon Fraser and Christian Holler, The Fuzzing Book, chapter Mutation-Based Fuzzing (mutating inputs, multiple mutations, guiding by coverage)
  2. Barton P. Miller, Lars Fredriksen and Bryan So, An empirical study of the reliability of UNIX utilities, Communications of the ACM 33(12), 1990, pp. 32 to 44, random input streams and the failures of the utilities
  3. Maverick Woo, Sang Kil Cha, Samantha Gottlieb and David Brumley, Scheduling black-box mutational fuzzing, Proceedings of CCS 2013, pp. 511 to 522, the model of a campaign over program and seed pairs and the scheduling algorithms
  4. Valentin J. M. Manès, HyungSeok Han, Choongwoo Han, Sang Kil Cha, Manuel Egele, Edward J. Schwartz and Maverick Woo, The art, science, and engineering of fuzzing, a survey, IEEE Transactions on Software Engineering 47(11), 2021, pp. 2312 to 2331, the sections on input generation by mutation (bit flipping, arithmetic mutation, block-based mutation)
  5. Alexandre Rebert, Sang Kil Cha, Thanassis Avgerinos, Jonathan Foote, David Warren, Gustavo Grieco and David Brumley, Optimizing seed selection for fuzzing, USENIX Security 2014, pp. 861 to 875, the effect of the seed files on a mutational fuzzer

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example