Algorithmcore
Coverage-guided greybox fuzzing
Also called greybox fuzzing, coverage-guided fuzzing.
Mutates inputs from a queue and keeps those that reach new code coverage, measured by lightweight instrumentation.
- Time
- O(N T + V (Q E + E log E)) worst
- Space
- O(Q (k + E)) extra
- Where
- E = the number of edges of the control flow graph; N = the number of executions; Q = the size of the queue; T = the largest number of steps of one run; V = the number of visits of queue entries; k = the number of parameters
- Model
- Word RAM
- Properties
- randomizedrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michał Zalewski, 2013
Coverage-guided greybox fuzzing tests a program by running it on a very large number of mutated inputs. Light instrumentation tells the fuzzer which edges of the control flow graph each run took and about how often. An input that makes the program do something new, by this measure, goes into a queue, and later inputs are mutations of the inputs in the queue. So the fuzzer climbs step by step into code that blind random inputs almost never reach, without the cost of a solver. This is the design of AFL and of most fuzzers after it. A fuzzer gives no completeness guarantee: when it finds no crash, nothing follows about the program.
In plain words
Start with a few example inputs. Take one of them, change it a little, and run the program. Each run leaves a trace of the jumps it took between blocks of code, with rough counts. If the trace has a jump, or a count range, that no earlier run had, keep the new input in a list; otherwise throw it away. If the run crashes, save the input for a person to look at. Go through the list again and again, changing each input in many small ways. A program check that needs three exact values in a row is too hard to guess at once, but the fuzzer can pass it one value at a time, because each correct value opens a new jump and so is kept. To save time, prefer the small set of fast inputs that together reach every jump seen so far.
The problem
The input is a program of the toy IR with integer parameters, a list of seed inputs, a budget of executions and a seed for the random number generator. The output is the queue of kept inputs, the crashing inputs found, and the coverage reached. A crash here is a trap, a division by zero or a shift out of range.
What a fuzzer can promise is limited by decidability. Whether some input reaches a given edge, or a given trap, is undecidable for programs with loops over unbounded integers, by a reduction from the halting problem. For loop-free programs with products over unbounded integers it contains Hilbert's tenth problem. Over a finite box of inputs it is decidable by trying every input, but real input spaces are far too large for that. A fuzzer does not try to decide it. It samples. Every crash it reports is real, because it ran, but a run with no crash proves nothing, and full edge coverage does not mean that every path, or every value on a path, was tested. The tests of this page check only coverage properties of one fixed-seed run, never that a bug or a path is found.
The algorithm
The instrumentation follows AFL. A run counts how often it takes each edge of the control flow graph and puts the count in one of the buckets 1, 2, 3, 4 to 7, 8 to 15, 16 to 31, 32 to 127 and 128 or more. The coverage of a run is the set of pairs (edge, bucket). The fuzzer keeps the union of the coverage of all queue entries, AFL's virgin map, and a second one for the crashes.
FUZZ(P, seeds, N, rng)- 1
queue <- the seeds, each with its coverage; virgin <- the union of their coverage - 2
while fewer than N runs were made do - 3
for each entry q of queue, in order, including entries added during the walk do - 4
favored <- CULL(queue) - 5
if q is not in favored then skip q with probability 0.9 - 6
the first time q is used, try each mutation of the deterministic stage; then try HAVOC(q) 32 times. To try an input x: - 7
(kind, cov) <- run P on x with edge counters - 8
if kind is a trap then save x as a crash if cov has a pair that no crash had - 9
else if kind is a return and cov has a pair not in virgin then - 10
virgin <- virgin union cov; append x to queue CULL(queue)- 11
for each edge e covered by the queue, best[e] <- the entry with the fewest steps that covers e (the earliest on ties) - 12
favored <- empty; covered <- empty - 13
for each edge e, in a fixed order: if e is not in covered then add best[e] to favored and its edges to covered - 14
return favored
The deterministic stage changes one thing at a time, in a fixed order: it flips each of the low 8 bits of each parameter, adds and subtracts 1 to 35, and sets each parameter to each value of the list , the 8-bit interesting values of AFL. HAVOC stacks 2 to 8 random changes of the same kinds, plus random values and copies of one parameter into another. In this implementation a run that uses up its fuel is neither kept nor reported.
CULL is AFL's queue culling. For each edge it chooses the cheapest entry that covers it, and a greedy pass picks entries until every edge is covered, a fast approximation of set cover. The fuzzer spends most of its time on this favored set, and the other entries are skipped with probability 0.9 on each visit.
Example
The parameters are , and . The trap needs three exact values, one after the other.
entry:
t = a == 17
br t l1 out
l1:
d = b - a
t = d == 4
br t l2 out
l2:
e = c - 100
z = a / e
ret z
out:
ret 0
The trap happens only for . A blind random tester that draws each parameter from to hits it with probability per run. With the seed , a budget of 20000 runs and the generator seed 0, the fuzzer of this page does this:
| run | input | event | coverage added |
|---|---|---|---|
| 1 | (0, 0, 0) | the seed, 3 steps | entry→out |
| 58 | (17, 0, 0) | kept, 6 steps | entry→l1, l1→out |
| 426 | (17, 21, 0) | kept, 8 steps | l1→l2 |
| 841 | (17, 21, 100) | crash |
All three steps come from the deterministic stage. Run 58 is the 17th addition to in the stage of the seed. Run 426 is the 21st addition to in the stage of , which became a queue entry because it took two new edges. Run 841 sets to the interesting value 100 in the stage of . The generator seeds 1 to 4 give the same four lines; the havoc runs in between add nothing to the queue. Blind random testing with the same budget over finds no crash for the seeds 0 to 4, and for the seeds 1 and 3 it does not even take the edge l1→l2.
The example also shows the limit. Change the constant 100 to 99 and the deterministic stage cannot make it from 0; the fuzzer then depends on havoc and luck. A check against a 32-bit constant or a checksum gives no partial reward at all, and the fuzzer has nothing to climb.
Correctness
The proof file shows the invariants that the implementation keeps. They are the whole of what the algorithm guarantees.
- Every kept input is real. Each queue entry and each crash was produced by a run of the program, and replaying it gives the same coverage and the same outcome, because the runs are deterministic. In particular every reported crash traps.
- The virgin map is exact. After each run, the virgin map equals the union of the coverage of the queue entries, and each entry after the seeds added at least one new pair when it was added.
- The favored set covers the queue. Every edge covered by some queue entry is covered by some favored entry, so skipping the other entries never hides an edge of the queue from the mutations.
- Covered edges are edges of the program. Each pair names an edge of the control flow graph, so the queue has at most entries beyond the seeds: each one adds a new pair, and there are at most 8 buckets per edge.
No completeness. None of this says that the fuzzer finds an edge, a path or a trap that some input reaches. The problem it would solve is undecidable in general, and even on a finite box the fuzzer makes random choices with no bound on the number of runs it needs.
Proof: The invariants of coverage-guided fuzzing, and why they give no completenessfull
Setting. is a program of the toy IR with integer parameters and only constants, copies, binary operations and the terminators jump, br and ret. is its control flow graph with the edge set , and . For an input , the run of on with fuel is a function of alone: the interpreter has no other state. EXEC returns its outcome kind (ret, trap or fuel), its step count and its coverage , the set of pairs for each edge that the run took times, where is the bucket function with 8 values.
The state of the fuzzer is the queue , the crash list , the virgin map and the crash map . Let be the number of seeds.
Lemma 1: coverage names real edges
Claim. For every input , every pair of is with and .
Proof. EXEC increments the counter of only when the terminator of moves the run to , which is a jump to or a br with as one target; both make an edge of . Each counter is at least 1 once it exists, and maps every to one of the 8 values.
Lemma 2: the state invariants
Claim. After line L1, and after every later run on lines L7 to L10, the following hold.
- (I1) Every entry of stores and the step count of its run, and every entry after the first comes from a run of kind ret.
- (I2) .
- (I3) For each , .
- (I4) Every traps, , and each crash after the first has a pair not in the union of the coverage of the crashes before it.
Proof. Induction over the runs. Line L1 runs each seed once, appends it with its own coverage and steps, and adds its coverage to ; and are empty. So (I1) to (I4) hold, with (I3) and (I4) empty.
A later run of on line L7 computes , since the run is a function of . There are three cases.
- Kind trap. If is empty or , then is appended to and is added to . By (I4) for the old state, was the union for the old crashes, so the new pair is new among all earlier crashes, and is again the union. and do not change.
- Kind ret, with . Then is appended as with its coverage and steps, and . By (I2), the old is , so (I3) holds for , and (I2) holds for the new state. (I1) holds because the kind is ret.
- Otherwise nothing changes.
Lemma 3: the favored set covers the queue
Claim. For every queue, the set returned by CULL satisfies , where is the set of edges of .
Proof. Line L11 defines exactly for the edges of the right side, and is an entry that covers . Line L13 visits each such . If is already in covered, some favored entry covers it. Otherwise is added to and its edges, among them, to covered. So at the end every edge of the right side is covered by a favored entry, and covered contains only edges of favored entries, which gives the other inclusion.
Theorem
Claim. At every point of a run of FUZZ:
- every queue entry and every crash replays to the stored coverage and outcome, and every crash traps;
- the virgin map is the union of the coverage of the queue, and each entry after the seeds added a new pair when it was added;
- the favored set covers every edge covered by the queue;
- every covered edge is an edge of , and ; and
- the number of runs is at most ; FUZZ stops surely when some queue entry covers an edge, and with probability 1 otherwise.
Proof. Items 1 and 2 are (I1) to (I4), with the determinism of the run. Item 3 is Lemma 3. For item 4, Lemma 1 bounds the pairs: there are at most possible pairs. By (I3), each entry after the seeds adds a pair that no earlier entry had, so the non-seed entries add distinct new pairs, at most of them. For item 5, line L1 runs the seeds, and every later run first tests the budget and returns when it is used, so there are at most runs. The queue is finite by item 4, so each walk on line L3 has finitely many visits. A visit that is not skipped makes at least one run or returns. If some entry covers an edge, the favored set is not empty by Lemma 3, and a favored entry is never skipped, so each walk makes a run, and after at most walks the budget is used. If no entry covers an edge, every entry is skipped with probability 0.9 on each visit, and a visit that is not skipped comes with probability 1.
What is not claimed
The theorem is about the state of the fuzzer, not about the program. It does not say that an edge, a path or a trap reachable by some input is found within the budget, or with any budget.
- Reachability of an edge or a trap is undecidable for programs with loops over unbounded integers, by Rice's theorem, so no procedure can promise to find every reachable one and stop.
- Even over a finite box of inputs, where the question is decidable by enumeration, the fuzzer samples. For the example of the page, an input reaches the trap only if it equals . Changing 100 to 99 leaves the deterministic stage unable to make the third value from 0, and every havoc run then reaches the trap with some probability below 1, so no fixed number of runs guarantees the trap.
- Coverage pairs abstract the run. Two runs with the same pairs can follow different paths, so "no new pair" does not mean "no new behavior", and a full set of pairs does not mean that every path was run.
The tests of the page check items 1 to 4 on fixed-seed runs, and nothing else.
Complexity
Let be the number of runs, the largest number of steps of a run, the size of the queue, the number of edges and the number of queue visits. Each run costs for the program and the counters, plus to compare its coverage with the virgin map. Each visit calls CULL, which reads the coverage of every entry, , sorts the edges, , and builds the favored set in . The total is . Since plus the seeds, the queue stays small. The space is for the queue.
AFL makes each run much cheaper than this: its map is a fixed array of 64 kB indexed by a hash of the edge, compared with the virgin map word by word, and it culls only after the queue changes. The cost of a fuzzer is dominated by the runs of the target, which is why AFL runs thousands of them per second and avoids anything as slow as a solver.
Properties
- Randomized. The havoc stage and the skipping of entries use random numbers. With a fixed seed the whole run can be repeated exactly.
- No false alarms. Every reported crash is a real run of the program.
- No completeness. A run of any length can miss an edge, a path or a crash; the fuzzer never says that none exists.
- Edge coverage, not path coverage. Two runs with the same edges and buckets look the same, though their paths can differ. The buckets also merge counts: a loop of 4 and a loop of 7 trips give the same coverage.
- Monotone queue. Entries are only added, and each one added a new pair.
Variants and improvements
- Power schedules. Böhme, Pham and Roychoudhury model the fuzzer as a Markov chain whose states are paths, and observe that AFL spends most runs on a few high-frequency paths. AFLFast assigns more mutations to entries that reach rarely seen paths. Seed scheduling is also studied as a multi-armed bandit problem.
- Hashed edge maps. AFL computes the index of an edge as the hash
cur_location ^ prev_location, withprev_locationshifted right by one after each block, into a 64 kB array. Collisions can hide new edges. This page uses exact edges, which a small toy program allows. - Trimming. AFL shortens each new queue entry by removing blocks of the input as long as the coverage stays the same, a cheap relative of delta debugging.
- Structure-aware mutation. Dictionaries of tokens and grammar-based fuzzing produce inputs that pass the parser of the program.
- Hybrid fuzzing. When coverage stops growing, a concolic or generational engine solves the path condition of a queue entry to pass a narrow check, such as a magic number, and gives the result back to the fuzzer.
- Oracles. A crash is the cheapest oracle. Sanitizers turn silent memory errors into crashes, and differential testing compares two implementations on each input.
When to use it
Use coverage-guided fuzzing on code that parses or transforms untrusted input, such as file formats, network protocols, compilers and libraries with a byte-buffer interface. It needs only a way to run the program many times quickly and to measure coverage, and it scales to large programs where symbolic methods time out. Start with small valid seeds. Add a solver-based tool when coverage stops at checks of exact values, and use a verifier when you need a proof: a fuzzer never gives one.
Pitfalls
- Reading "no crash" as "no bug". A fuzzing campaign gives evidence, never a proof. Report it as coverage reached in a given time.
- Magic values and checksums. A comparison of many bytes at once gives no partial coverage. Split the comparison, add a dictionary, or use a solver.
- Coverage is not behavior. Two inputs with the same edge coverage can compute different values, and a bug can hide in a value on a covered path.
- Nondeterministic targets. If the coverage of a run depends on time, threads or global state, the fuzzer keeps inputs that are not new and the queue grows with noise.
- Comparing fuzzers on one run. Results vary a lot with the seed. Compare many runs with a statistical test.
- Seeds that crash or hang. A seed that traps adds nothing to the queue and wastes the stage; check the seeds first.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coverage-guided-fuzzing/. The authors are listed in prov/6GRW00.jsonl.
"""Coverage-guided greybox fuzzing in the style of AFL, on the toy IR.
An input is a tuple of integers, one per parameter of the program. The
instrumentation counts how often each edge of the control flow graph is
taken in a run and puts each count in an AFL bucket (1, 2, 3, 4-7, 8-15,
16-31, 32-127, 128+). The coverage of a run is the set of pairs
(edge, bucket). An input that is not a crash is kept in the queue when its
coverage has a pair that no earlier input had. A crash is a trap; it is
kept when its coverage is new among the crashes.
Mutations: a deterministic stage the first time an entry is fuzzed (flip
each of the low 8 bits of each integer, add and subtract 1 to 35, set each
integer to an interesting value) and then a havoc stage of stacked random
mutations. Before each entry the queue is culled: for every edge, the
entry with the shortest run that covers the edge is a candidate, and a
greedy pass picks a favored set that covers every edge. Entries that are
not favored are skipped with probability 0.9.
fuzz(prog, seeds, max_execs, seed) returns a Result. Everything is driven
by random.Random(seed), so a run of the fuzzer can be repeated exactly.
Nothing here claims that the fuzzer finds every path or every crash.
"""
import random
import toyir
INTERESTING = (-128, -1, 0, 1, 16, 32, 64, 100, 127)
ARITH_MAX = 35
HAVOC_RUNS = 32
SKIP_NOT_FAVORED = 0.9
def bucket(n):
"""The AFL hit-count bucket of a count n >= 1."""
if n <= 3:
return n
if n <= 7:
return 4
if n <= 15:
return 8
if n <= 31:
return 16
if n <= 127:
return 32
return 128
def execute(prog, args, fuel=10000):
"""Run prog on args with edge counters. Returns (kind, coverage, steps),
where kind is "ret", "trap" or "fuel" and coverage is a frozenset of
pairs ((from, to), bucket)."""
env = dict(zip(prog.params, args))
counts = {}
steps = 0
label = prog.entry
def val(a):
if isinstance(a, int):
return a
if a not in env:
raise toyir.UndefinedName(a)
return env[a]
def cov():
return frozenset((e, bucket(n)) for e, n in counts.items())
while True:
block = prog.blocks[label]
for ins in block.instrs:
if steps >= fuel:
return "fuel", cov(), steps
steps += 1
if ins[0] == "const":
env[ins[1]] = ins[2]
elif ins[0] == "copy":
env[ins[1]] = val(ins[2])
elif ins[0] == "op":
try:
env[ins[1]] = toyir._binop(ins[2], val(ins[3]), val(ins[4]))
except toyir._Trap:
return "trap", cov(), steps
else:
raise ValueError("execute handles const, copy and op only")
if steps >= fuel:
return "fuel", cov(), steps
steps += 1
t = block.term
if t[0] == "ret":
return "ret", cov(), steps
nxt = t[1] if t[0] == "jump" else (t[2] if val(t[1]) != 0 else t[3])
e = (label, nxt)
counts[e] = counts.get(e, 0) + 1
label = nxt
class Entry:
__slots__ = ("args", "cov", "steps", "found_at", "det_done")
def __init__(self, args, cov, steps, found_at):
self.args = args
self.cov = cov
self.steps = steps
self.found_at = found_at
self.det_done = False
class Result:
def __init__(self):
self.queue = []
self.crashes = []
self.virgin = set()
self.crash_virgin = set()
self.execs = 0
self.first_crash = None
def deterministic(args):
"""The deterministic stage: one mutation at a time, in a fixed order."""
for i in range(len(args)):
for bit in range(8):
x = list(args)
x[i] ^= 1 << bit
yield tuple(x)
for i in range(len(args)):
for d in range(1, ARITH_MAX + 1):
for s in (d, -d):
x = list(args)
x[i] += s
yield tuple(x)
for i in range(len(args)):
for v in INTERESTING:
if args[i] != v:
x = list(args)
x[i] = v
yield tuple(x)
def havoc(rng, args):
"""A stack of 2 to 8 random mutations."""
x = list(args)
k = len(x)
for _ in range(1 << rng.randint(1, 3)):
i = rng.randrange(k)
r = rng.randrange(5)
if r == 0:
x[i] ^= 1 << rng.randrange(8)
elif r == 1:
x[i] += rng.choice((1, -1)) * rng.randint(1, ARITH_MAX)
elif r == 2:
x[i] = rng.choice(INTERESTING)
elif r == 3:
x[i] = rng.randint(-128, 127)
else:
x[i] = x[rng.randrange(k)]
return tuple(x)
def edges_of(cov):
return {e for e, _ in cov}
def cull(queue):
"""The favored entries: for each edge, the entry with the shortest run
that covers it (the earliest on ties); then a greedy pass over the edges
in sorted order adds the best entry of each edge not yet covered."""
best = {}
for idx, q in enumerate(queue): # @line L11
for e in edges_of(q.cov):
if e not in best or q.steps < queue[best[e]].steps:
best[e] = idx
favored = set() # @line L12
covered = set()
for e in sorted(best, key=repr): # @line L13
if e not in covered:
favored.add(best[e])
covered |= edges_of(queue[best[e]].cov)
return favored # @line L14
def fuzz(prog, seeds, max_execs=20000, seed=0, fuel=10000):
rng = random.Random(seed)
res = Result()
def try_input(x):
"""Run x and save it if it is interesting. False when the budget is used."""
if res.execs >= max_execs:
return False
res.execs += 1
kind, cov, steps = execute(prog, x, fuel) # @line L7
if kind == "trap": # @line L8
if cov - res.crash_virgin or not res.crashes:
res.crash_virgin |= cov
res.crashes.append(x)
if res.first_crash is None:
res.first_crash = res.execs
elif kind == "ret" and cov - res.virgin: # @line L9
res.virgin |= cov # @line L10
res.queue.append(Entry(x, cov, steps, res.execs))
return True
for s in seeds: # @line L1
s = tuple(s)
res.execs += 1
kind, cov, steps = execute(prog, s, fuel)
res.queue.append(Entry(s, cov, steps, res.execs))
res.virgin |= cov
if not res.queue:
raise ValueError("fuzz needs at least one seed")
while res.execs < max_execs: # @line L2
idx = 0
while idx < len(res.queue): # @line L3
q = res.queue[idx]
favored = cull(res.queue) # @line L4
if idx not in favored and rng.random() < SKIP_NOT_FAVORED: # @line L5
idx += 1
continue
if not q.det_done: # @line L6
q.det_done = True
for x in deterministic(q.args):
if not try_input(x):
return res
for _ in range(HAVOC_RUNS):
if not try_input(havoc(rng, q.args)):
return res
idx += 1
return res
def random_testing(prog, max_execs=20000, seed=0, lo=-128, hi=127, fuel=10000):
"""Blind random testing with the same budget, for comparison: returns
the set of edges covered and the number of the first crashing run."""
rng = random.Random(seed)
edges = set()
first_crash = None
for n in range(1, max_execs + 1):
x = tuple(rng.randint(lo, hi) for _ in prog.params)
kind, cov, _ = execute(prog, x, fuel)
edges |= edges_of(cov)
if kind == "trap" and first_crash is None:
first_crash = n
return edges, first_crash
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.
A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:
("const", x, k) x = k
("copy", x, a) x = y
("op", x, op, a, b) x = a op b
("phi", x, {pred: a}) x = phi [pred: a, ...]
("addr", p, x) p = &x
("load", x, p) x = *p
("store", p, a) *p = a
("alloc", p) p = alloc
("call", x, f, args) x = call f(a, b) (args is a list)
Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""
from dataclasses import dataclass, field
import re
OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")
@dataclass
class Block:
instrs: list = field(default_factory=list)
term: tuple = ("ret", 0)
@dataclass
class Program:
params: list
blocks: dict
@property
def entry(self):
return next(iter(self.blocks))
class UndefinedName(Exception):
"""A name was read before any definition."""
# ---------------------------------------------------------------- text form
_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"
def _operand(tok):
if re.fullmatch(_INT, tok):
return int(tok)
if re.fullmatch(_NAME, tok):
return tok
raise ValueError("bad operand: %r" % tok)
def _name(tok):
if not re.fullmatch(_NAME, tok):
raise ValueError("bad name: %r" % tok)
return tok
def _parse_instr(line):
toks = line.split()
if toks[0] == "jump" and len(toks) == 2:
return "term", ("jump", _name(toks[1]))
if toks[0] == "br" and len(toks) == 4:
return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
if toks[0] == "ret" and len(toks) == 2:
return "term", ("ret", _operand(toks[1]))
lhs, eq, rhs = line.partition("=")
if not eq:
raise ValueError("bad line: %r" % line)
lhs, rhs = lhs.strip(), rhs.strip()
if lhs.startswith("*"):
return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
x = _name(lhs)
if rhs.startswith("phi"):
body = rhs[3:].strip()
if not (body.startswith("[") and body.endswith("]")):
raise ValueError("bad phi: %r" % line)
args = {}
inner = body[1:-1].strip()
if inner:
for part in inner.split(","):
pred, colon, a = part.partition(":")
if not colon:
raise ValueError("bad phi: %r" % line)
args[_name(pred.strip())] = _operand(a.strip())
return "instr", ("phi", x, args)
if rhs.startswith("call "):
m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
if not m:
raise ValueError("bad call: %r" % line)
inner = m.group(2).strip()
args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
return "instr", ("call", x, m.group(1), args)
if rhs == "alloc":
return "instr", ("alloc", x)
if rhs.startswith("&"):
return "instr", ("addr", x, _name(rhs[1:].strip()))
if rhs.startswith("*"):
return "instr", ("load", x, _name(rhs[1:].strip()))
parts = rhs.split()
if len(parts) == 1:
a = _operand(parts[0])
if isinstance(a, int):
return "instr", ("const", x, a)
return "instr", ("copy", x, a)
if len(parts) == 3 and parts[1] in OPS:
return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
raise ValueError("bad instruction: %r" % line)
def parse(text):
"""Parse the text form. A line "# params: a, b" gives the parameters;
without it, the parameters are the names that are read and never
defined, in the order of their first use."""
params = None
blocks = {}
cur = None
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if line.startswith("#"):
m = re.fullmatch(r"#\s*params:(.*)", line)
if m:
inner = m.group(1).strip()
params = [_name(p.strip()) for p in inner.split(",")] if inner else []
continue
if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
label = line[:-1]
if label in blocks:
raise ValueError("duplicate label: %r" % label)
cur = label
blocks[label] = Block([], None)
continue
if cur is None:
raise ValueError("instruction outside a block: %r" % line)
if blocks[cur].term is not None:
raise ValueError("instruction after the terminator in %r" % cur)
kind, item = _parse_instr(line)
if kind == "term":
blocks[cur].term = item
else:
blocks[cur].instrs.append(item)
for label, b in blocks.items():
if b.term is None:
raise ValueError("block %r has no terminator" % label)
if not blocks:
raise ValueError("empty program")
prog = Program([], blocks)
if params is None:
params = _free_names(prog)
prog.params = params
return prog
def _free_names(prog):
defined = set()
for b in prog.blocks.values():
for ins in b.instrs:
d = defs(ins)
if d is not None:
defined.add(d)
out = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins):
if a not in defined and a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in defined and a not in out:
out.append(a)
return out
def _show_instr(ins):
k = ins[0]
if k == "const":
return "%s = %d" % (ins[1], ins[2])
if k == "copy":
return "%s = %s" % (ins[1], ins[2])
if k == "op":
return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
if k == "phi":
return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
if k == "addr":
return "%s = &%s" % (ins[1], ins[2])
if k == "load":
return "%s = *%s" % (ins[1], ins[2])
if k == "store":
return "*%s = %s" % (ins[1], ins[2])
if k == "alloc":
return "%s = alloc" % ins[1]
if k == "call":
return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
raise ValueError("bad instruction: %r" % (ins,))
def _show_term(t):
if t[0] == "jump":
return "jump %s" % t[1]
if t[0] == "br":
return "br %s %s %s" % (t[1], t[2], t[3])
if t[0] == "ret":
return "ret %s" % (t[1],)
raise ValueError("bad terminator: %r" % (t,))
def show(prog):
lines = ["# params: " + ", ".join(prog.params)]
for label, b in prog.blocks.items():
lines.append(label + ":")
for ins in b.instrs:
lines.append(" " + _show_instr(ins))
lines.append(" " + _show_term(b.term))
return "\n".join(lines) + "\n"
# ---------------------------------------------------------- names and graph
def defs(ins):
"""The name an instruction defines, or None for a store."""
return None if ins[0] == "store" else ins[1]
def uses(ins):
"""The names an instruction reads, in order (phi operands included)."""
k = ins[0]
if k == "const" or k == "alloc" or k == "addr":
ops = []
elif k == "copy":
ops = [ins[2]]
elif k == "op":
ops = [ins[3], ins[4]]
elif k == "phi":
ops = list(ins[2].values())
elif k == "load":
ops = [ins[2]]
elif k == "store":
ops = [ins[1], ins[2]]
elif k == "call":
ops = list(ins[3])
else:
raise ValueError("bad instruction: %r" % (ins,))
return [a for a in ops if isinstance(a, str)]
def term_uses(t):
if t[0] == "br" or t[0] == "ret":
return [t[1]] if isinstance(t[1], str) else []
return []
def succs(prog, label):
"""Successor labels of a block, without repeats, in terminator order."""
t = prog.blocks[label].term
if t[0] == "jump":
return [t[1]]
if t[0] == "br":
return [t[2]] if t[2] == t[3] else [t[2], t[3]]
return []
def edges(prog):
return [(a, b) for a in prog.blocks for b in succs(prog, a)]
def preds(prog):
"""Dict from label to the list of predecessor labels, in block order."""
out = {label: [] for label in prog.blocks}
for a, b in edges(prog):
out[b].append(a)
return out
def is_acyclic(prog):
color = {label: 0 for label in prog.blocks}
for root in prog.blocks:
if color[root]:
continue
color[root] = 1
stack = [(root, iter(succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
color[v] = 2
stack.pop()
elif color[w] == 1:
return False
elif color[w] == 0:
color[w] = 1
stack.append((w, iter(succs(prog, w))))
return True
def paths(prog):
"""Every path from the entry to a ret block, as a list of labels.
The CFG must be acyclic."""
if not is_acyclic(prog):
raise ValueError("paths needs an acyclic CFG")
out = []
def walk(path):
last = path[-1]
s = succs(prog, last)
if not s:
out.append(list(path))
for w in s:
path.append(w)
walk(path)
path.pop()
walk([prog.entry])
return out
# ------------------------------------------------------------------ running
class _Trap(Exception):
pass
class _Fuel(Exception):
pass
def _binop(op, a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("arithmetic on a pointer")
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" or op == "%":
if b == 0:
raise _Trap()
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
if op == "&":
return a & b
if op == "|":
return a | b
if op == "^":
return a ^ b
if op == "<<" or op == ">>":
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
if op == "<":
return int(a < b)
if op == "<=":
return int(a <= b)
if op == "==":
return int(a == b)
if op == "!=":
return int(a != b)
raise ValueError("bad operator: %r" % op)
class _Frame:
"""One activation: its program, its variables and its position."""
def __init__(self, prog, args, fid):
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
self.prog = prog
self.env = dict(zip(prog.params, args))
self.fid = fid
self.label = prog.entry
self.prev = None
self.pc = 0 # 0 means: the phis of the block have not run yet
self.dest = None # the name that receives the value of a pending call
def val(self, a):
if isinstance(a, int):
return a
if a not in self.env:
raise UndefinedName(a)
return self.env[a]
def _run(prog, args, fuel, funcs):
"""Run with an explicit stack of frames, so deep recursion in the toy
program does not use Python recursion."""
heap = {}
envs = {}
stack = []
fr = _Frame(prog, args, 0)
envs[0] = fr.env
nframes = 1
def tick():
nonlocal fuel
if fuel <= 0:
raise _Fuel()
fuel -= 1
while True:
block = fr.prog.blocks[fr.label]
instrs = block.instrs
if fr.pc == 0:
# Phis at the top of the block read all operands first, then assign.
incoming = []
i = 0
while i < len(instrs) and instrs[i][0] == "phi":
tick()
ins = instrs[i]
if fr.prev not in ins[2]:
raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
incoming.append((ins[1], fr.val(ins[2][fr.prev])))
i += 1
for x, v in incoming:
fr.env[x] = v
fr.pc = i if i > 0 else -1
start = fr.pc if fr.pc > 0 else 0
called = False
env = fr.env
for j in range(start, len(instrs)):
ins = instrs[j]
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = fr.val(ins[2])
elif k == "op":
env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
elif k == "addr":
env[ins[1]] = ("var", fr.fid, ins[2])
elif k == "alloc":
cell = ("heap", len(heap))
heap[cell] = None
env[ins[1]] = cell
elif k == "load":
p = fr.val(ins[2])
if p[0] == "var":
if p[2] not in envs[p[1]]:
raise UndefinedName(p[2])
env[ins[1]] = envs[p[1]][p[2]]
else:
if heap[p] is None:
raise UndefinedName(repr(p))
env[ins[1]] = heap[p]
elif k == "store":
p = fr.val(ins[1])
if p[0] == "var":
envs[p[1]][p[2]] = fr.val(ins[2])
else:
heap[p] = fr.val(ins[2])
elif k == "call":
if funcs is None or ins[2] not in funcs:
raise ValueError("unknown function %r" % ins[2])
vals = [fr.val(a) for a in ins[3]]
fr.pc = j + 1
fr.dest = ins[1]
stack.append(fr)
fr = _Frame(funcs[ins[2]], vals, nframes)
envs[nframes] = fr.env
nframes += 1
called = True
break
elif k == "phi":
raise ValueError("phi after a non-phi instruction")
else:
raise ValueError("bad instruction: %r" % (ins,))
if called:
continue
tick()
t = block.term
if t[0] == "jump" or t[0] == "br":
if t[0] == "jump":
nxt = t[1]
else:
nxt = t[2] if fr.val(t[1]) != 0 else t[3]
fr.prev, fr.label, fr.pc = fr.label, nxt, 0
continue
v = fr.val(t[1])
if not stack:
return ("ret", v), fuel
fr = stack.pop()
fr.env[fr.dest] = v
def run(prog, args, fuel=10000, funcs=None):
"""Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
Each instruction, phi and terminator uses one unit of fuel. funcs is an
optional dict from function name to Program, used by call; deep
recursion in the toy program is fine, because the frames are kept on an
explicit stack."""
try:
out, _ = _run(prog, list(args), fuel, funcs)
return out
except _Trap:
return ("trap",)
except _Fuel:
return ("fuel",)
# ------------------------------------------------------------ random programs
_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")
def random_program(rng, nvars, nblocks, acyclic):
"""A random program with blocks B0 .. B(nblocks-1) and variables
x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
others, so no run reads an undefined name. A division by a variable can
trap. Every block is reachable from
B0 and B0 has no predecessor. With acyclic=False, each loop has its own
counter c that is set to 0 in B0 and never reset, and the back edge is
taken only while c < m and c < 4, where m is the first parameter. So the
whole run takes each back edge at most 3 times."""
nvars = max(nvars, 1)
nblocks = max(nblocks, 1)
xs = ["x%d" % i for i in range(nvars)]
params = xs[:2]
labels = ["B%d" % i for i in range(nblocks)]
def operand():
if rng.random() < 0.25:
return rng.randint(-3, 9)
return rng.choice(xs)
def instr():
x = rng.choice(xs)
r = rng.random()
if r < 0.15:
return ("const", x, rng.randint(-5, 9))
if r < 0.25:
return ("copy", x, rng.choice(xs))
if r < 0.3:
# A division by a variable may trap.
return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
if r < 0.4:
op = rng.choice(_CONST_RIGHT)
k = rng.randint(1, 5)
return ("op", x, op, rng.choice(xs), k)
return ("op", x, rng.choice(_SAFE), operand(), operand())
blocks = {}
has_pred = [False] * nblocks
has_pred[0] = True
for i in range(nblocks):
instrs = [instr() for _ in range(rng.randint(1, 3))]
if i == 0:
instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
if i == nblocks - 1:
term = ("ret", rng.choice(xs))
elif has_pred[i + 1] and rng.random() < 0.2:
term = ("ret", rng.choice(xs))
else:
first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
if rng.random() < 0.5:
term = ("jump", labels[first])
has_pred[first] = True
else:
second = rng.randrange(i + 1, nblocks)
if second == first:
term = ("jump", labels[first])
else:
term = ("br", rng.choice(xs), labels[first], labels[second])
has_pred[second] = True
has_pred[first] = True
blocks[labels[i]] = Block(instrs, term)
if not acyclic and nblocks > 1:
nloops = rng.randint(1, max(1, nblocks // 3))
for k in range(nloops):
latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
if not latches:
break
t = rng.choice(latches)
h = labels[rng.randint(1, labels.index(t))]
c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
out = blocks[t].term[1]
blocks[t].instrs += [
("op", c, "+", c, 1),
("op", w1, "<", c, m),
("op", w2, "<", c, 4),
("op", w, "&", w1, w2),
]
blocks[t].term = ("br", w, h, out)
return Program(list(params), blocks)
test_coverage_guided_fuzzing.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coverage-guided-fuzzing/. The authors are listed in prov/6GRW00.jsonl.
import random
import toyir
from coverage_guided_fuzzing import bucket, cull, edges_of, execute, fuzz, random_testing
PAGE = """
# params: a, b, c
entry:
t = a == 17
br t l1 out
l1:
d = b - a
t = d == 4
br t l2 out
l2:
e = c - 100
z = a / e
ret z
out:
ret 0
"""
COUNT = """
# params: n
entry:
i = 0
jump head
head:
t = i < n
br t body exit
body:
i = i + 1
jump head
exit:
ret i
"""
def check_coverage_properties(prog, res, nseeds):
cfg = set(toyir.edges(prog))
# Every covered edge is an edge of the control flow graph.
assert edges_of(res.virgin) <= cfg
assert edges_of(res.crash_virgin) <= cfg
# Replaying the queue gives the same coverage, entry by entry and in total.
union = set()
for i, q in enumerate(res.queue):
kind, cov, steps = execute(prog, q.args)
assert cov == q.cov and steps == q.steps
if i >= nseeds:
# An entry was kept only because it added coverage.
assert kind == "ret"
assert cov - union
union |= cov
assert union == res.virgin
# Every saved crash is a real trap, and every crash after the first
# added coverage among the crashes.
seen = set()
for i, x in enumerate(res.crashes):
assert toyir.run(prog, x) == ("trap",)
kind, cov, _ = execute(prog, x)
assert kind == "trap"
assert i == 0 or cov - seen
seen |= cov
assert seen == res.crash_virgin
# The favored entries cover every edge that the queue covers.
fav = cull(res.queue)
covered = set()
for i in fav:
covered |= edges_of(res.queue[i].cov)
assert covered == edges_of(res.virgin)
def test_buckets():
expected = {1: 1, 2: 2, 3: 3, 4: 4, 7: 4, 8: 8, 15: 8, 16: 16, 31: 16, 32: 32, 127: 32, 128: 128, 1000: 128}
for n, b in expected.items():
assert bucket(n) == b
def test_hit_counts():
prog = toyir.parse(COUNT)
kind, cov, steps = execute(prog, (10,))
assert kind == "ret"
assert dict(cov) == {
("entry", "head"): 1,
("head", "body"): 8,
("body", "head"): 8,
("head", "exit"): 1,
}
# Runs of 4 and 7 trips fall in the same buckets, so they look the same.
assert execute(prog, (4,))[1] == execute(prog, (7,))[1]
assert execute(prog, (3,))[1] != execute(prog, (4,))[1]
def test_page_example():
prog = toyir.parse(PAGE)
res = fuzz(prog, [(0, 0, 0)], max_execs=20000, seed=0)
assert [(q.args, q.found_at) for q in res.queue] == [
((0, 0, 0), 1),
((17, 0, 0), 58),
((17, 21, 0), 426),
]
assert res.crashes == [(17, 21, 100)]
assert res.first_crash == 841
assert res.execs == 20000
check_coverage_properties(prog, res, 1)
edges, first_crash = random_testing(prog, max_execs=20000, seed=0)
assert first_crash is None
def test_hit_count_buckets_drive_the_queue():
prog = toyir.parse(COUNT)
res = fuzz(prog, [(0,)], max_execs=3000, seed=1)
check_coverage_properties(prog, res, 1)
seen = {b for q in res.queue for (e, b) in q.cov if e == ("head", "body")}
assert {1, 2, 3, 4, 8, 16, 32} <= seen
def test_same_seed_same_result():
prog = toyir.parse(PAGE)
a = fuzz(prog, [(5, 5, 5)], max_execs=3000, seed=42)
b = fuzz(prog, [(5, 5, 5)], max_execs=3000, seed=42)
assert [q.args for q in a.queue] == [q.args for q in b.queue]
assert a.crashes == b.crashes and a.virgin == b.virgin
def test_random_programs():
rng = random.Random(20261115)
for t in range(16):
acyclic = t % 2 == 0
prog = toyir.random_program(rng, rng.randint(2, 4), rng.randint(3, 8), acyclic=acyclic)
seeds = [(0, 0), (rng.randint(-5, 5), rng.randint(-5, 5))]
res = fuzz(prog, seeds, max_execs=1500, seed=t)
assert res.execs <= 1500
check_coverage_properties(prog, res, len(seeds))
History
Fuzz testing started with the study of Miller, Fredriksen and So in 1990, who fed random characters to UNIX utilities and crashed or hung between a quarter and a third of them. Random testing of that kind is blackbox. Michał Zalewski released American fuzzy lop (AFL) in 2013. Its contribution was a practical combination: compile-time edge instrumentation into a small shared map, hit-count buckets, a queue of inputs that add coverage, deterministic stages followed by havoc, and queue culling. AFL found many bugs in widely used libraries and made the design the default; libFuzzer, honggfuzz and AFL++ follow it. Böhme, Pham and Roychoudhury gave it a Markov chain model in 2016. The survey of Manès and others (2021) places greybox fuzzing between blackbox random testing and whitebox methods such as generational search.
References
- Michał Zalewski, Technical whitepaper for afl-fuzz, AFL documentation, sections 1 to 6 (coverage measurements, detecting new behaviors, evolving the input queue, culling the corpus, trimming input files, fuzzing strategies)
- Marcel Böhme, Van-Thuan Pham and Abhik Roychoudhury, Coverage-based greybox fuzzing as Markov chain, Proceedings of CCS 2016, pp. 1032 to 1043, the Markov chain model and the power schedules of AFLFast
- 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 general fuzzing loop and the sections on greybox fuzzing and seed scheduling
- 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, the first fuzz testing study with random inputs
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6GRW00 Edit this page History Report an error Markdown