Algorithmadvanced
Directed greybox fuzzing
Also called AFLGo, distance-guided fuzzing.
Steers greybox fuzzing toward chosen target sites by giving more energy to seeds whose paths are closer to the targets in the call and control graphs.
- Time
- O(n (n + e) + w (v + k) + B (Q + L)) worst
- Space
- O(n + v + Q) extra
- Where
- B = the number of inputs run; L = the length of one trace; Q = the number of seeds; e = the number of call edges; k = the number of control-flow edges; n = the number of functions; v = the number of basic blocks; w = the most blocks in one function
- Model
- Word RAM
- Properties
- randomizedrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Marcel Böhme, Van Thuan Pham, Manh Dung Nguyen, Abhik Roychoudhury, 2017
Directed greybox fuzzing sends a greybox fuzzer toward a few chosen places in a program, the targets, instead of spreading its effort over all of the code. The targets can be the lines changed by a patch, the frames of a crash report that must be reproduced, or a location flagged by a static analyzer. Before fuzzing, the compiler computes for each basic block a distance to the targets, from shortest paths in the call graph and in each function's control-flow graph. While fuzzing, the distance of a seed is the mean distance of the blocks it executes, and a power schedule based on simulated annealing multiplies the seed's energy by a factor from 1/32 to 32: at first all seeds are treated alike, and as time passes, closer seeds get more and more of the mutations. Böhme, Pham, Nguyen and Roychoudhury introduced the method in 2017 in their tool AFLGo. The distance and the schedule are heuristics; whether they reach a target faster is a measured property, which depends on the program and on the settings.
In plain words
You want the fuzzer to test one function, for example code that was just changed. Coverage-guided fuzzing would get there in the end, but it also spends time everywhere else. So first measure, on the map of the program, how many steps each piece of code is from the target: a step is a jump inside a function or a call into another function, and calls count ten times more. Then, for each saved input, look at the code it ran and take the average of those step counts. Inputs with a small average are close to the target. At the start, give all inputs the same share of changes, so the fuzzer still explores. As time passes, give the close inputs more changes and the far inputs fewer, until the fuzzer spends almost all of its time near the target.
The problem
The input is a program with its call graph and its control-flow graphs, a set of target basic blocks, seeds, and a time budget, with a time at which the search should turn from exploration to exploitation. The output is an input that executes a target block, if the fuzzer finds one in the budget. Reaching a given block is undecidable in general (Rice's theorem), so the method gives no guarantee of success; it changes where the fuzzer spends its time.
The algorithm
Lines L1 to L4 run once, at instrumentation time; lines L5 to L10 run for each choice of a seed. With and throughout:
DIRECTED-DISTANCES(call graph CG, control-flow graphs G_i, target blocks T_b)- 1
for each function n: d_f(n) <- [ sum over target functions t reachable from n in CG of 1 / d_CG(n, t) ]^-1, undefined if none is reachable - 2
for each function i: T <- the target blocks of i, each with d_b = 0 - 3
add to T every block m that calls a function n with d_f(n) defined; d_b(m) <- C * min over such n of d_f(n) - 4
for every other block m of i: d_b(m) <- [ sum over t in T reachable from m in G_i of 1 / (d_G(m, t) + d_b(t)) ]^-1, undefined if none is reachable DIRECTED-ENERGY(seed s, time t)- 5
d(s) <- the mean of d_b over the blocks that s executes and that have a distance - 6
d~(s) <- (d(s) - minD) / (maxD - minD), with minD and maxD over the seeds so far - 7
temperature <- 20^(-t / t_x) - 8
p <- (1 - d~(s)) (1 - temperature) + 0.5 temperature - 9
factor <- 2^(10 p - 5) - 10
energy <- max(1, floor(base energy * factor))
The target functions are the functions that contain a target block, and count edges on shortest paths (one breadth-first search per node), and is the constant of the paper that makes a call count more than a jump. The paper calls the combination in lines L1 and L4 a harmonic mean; the formula has no count factor, so it is the inverse of a sum of inverses. Its point is that a block close to one target is closer than a block at a middle distance from two, which an arithmetic mean would not show.
The paper defines as the blocks that call a function on the way to a target; this page also puts the target blocks themselves into with distance 0, so that blocks in the target's own function get a distance. With , a target function has , and a block that calls it directly gets distance 0 too. In line L5 the AFLGo trampoline adds the distance of a block each time the block runs, and blocks without a distance add nothing, so the mean is over the executed blocks that have one, counted with repetition. A seed with no such block gets , and when all seeds so far have one distance, ; these two cases are conventions of this page.
The schedule. The temperature of line L7 is exponential cooling, chosen so that it is 1 at and 0.05 at . Line L8 mixes the closeness with the neutral value ; at , and the factor is 1 for every seed, and as the temperature falls, tends to . So the factor tends to 32 for the closest seed and to 1/32 for the farthest. Line L10 multiplies the energy that the greybox fuzzer would give anyway.
Example
The model program has six functions. main calls parse or log by byte 0 of the input, parse calls body or header by byte 1, body calls check if byte 2 is 3, and check reaches the target block t2 if byte 3 is 4. The call graph gives = 0 for check, 1 for body, 2 for parse and 3 for main; log and header reach no target.
| block | function | role | |
|---|---|---|---|
| t2 | check | target | 0 |
| t1 | check | branches to t2 | 1 |
| b3 | body | calls check | |
| b2, b1 | body | one and two edges before b3 | 1, 2 |
| p3 | parse | calls body | |
| p1 | parse | one edge before p3 | 11 |
| m3 | main | calls parse | |
| m1 | main | one edge before m3 | 21 |
The other blocks, such as t3, b5 and the blocks of log, cannot reach the target and have no distance. The seed distance is the mean over the executed blocks that have one. With inputs, the four seeds of a campaign get these values (the factor is shown at three times):
| seed (bytes 0 to 3) | blocks with distance | factor at | at | at | ||
|---|---|---|---|---|---|---|
| 0 0 0 0 | m1 | 21 | 1 | 1 | 0.037 | 0.031 |
| 1 0 0 0 | m1, m3, p1 | 52/3 | 109/153 | 1 | 0.247 | 0.229 |
| 1 2 0 0 | m1, m3, p1, p3, b1 | 64/5 | 91/255 | 1 | 2.567 | 2.697 |
| 1 2 3 0 | m1, m3, p1, p3, b1, b2, b3, t1 | 33/4 | 0 | 1 | 26.909 | 31.986 |
Deeper seeds run more blocks near the target, so their mean falls. The test file computes these distances with breadth-first search and checks them, and the distances of 600 random small programs, against the same formulas computed from Floyd-Warshall all-pairs shortest paths.
Campaigns. The mutation sets one uniform byte of the 4-byte input to a uniform value from 0 to 7, the base energy is 16, seeds are chosen in turn, and an input is kept when it runs a new block. The mean number of inputs until t2 runs, over 100 campaigns with generator seeds 0 to 99, was:
| schedule | mean inputs |
|---|---|
| undirected (factor 1) | 343 |
| directed, | 245 |
| directed, | 916 |
These are measurements on one toy program. The slow schedule helps. The fast one hurts here, because the energy of a choice is fixed when the seed is chosen: once a seed is the closest so far, it gets up to 32 times 16 mutations in one go, and they continue after a deeper seed has been found. In a real campaign of hours, one choice is a small part of the time and is set in hours; the lesson of the toy is that the schedule has a setting that must fit the budget.
Correctness
Statement. Lines L1 to L4 compute, for every function and block, exactly the distances defined by the formulas above, and leave a block without a distance exactly when no target-relevant block is reachable from it in its function. Lines L5 to L10 give every seed a normalized distance in 0 to 1 and a factor in 1/32 to 32; the factor is 1 for all seeds at , and at any time it does not grow as grows.
Key invariant. Breadth-first search returns shortest path lengths in an unweighted graph, so each term of lines L1 and L4 is the true graph distance, and the values of in line L4 are already final when line L4 runs, because lines L2 and L3 do not depend on line L4. For the schedule, and make a mix of two numbers in 0 to 1, so and the factor is between and . The proof file has the details.
The method is not correct in the sense of reaching the target: a seed can be close in the graph and still far in input space, for example behind a checksum.
Proof: Correctness of the target distances and the bounds of the annealing schedulefull
We prove that lines L1 to L4 compute the distances defined on the page, that lines L5 to L9 give a factor in to that is 1 at time 0 and does not grow with the normalized distance, and that line L10 gives an energy of at least 1, so that the campaign ends. Throughout, and , and for a finite nonempty list of numbers we write . These claims are about the computation only; that a small distance leads to the target sooner is a heuristic, not a theorem.
Claim 1 (the combination). For with , if some , and otherwise .
Proof. If some , then , the sum is and its inverse is 0. Otherwise every term is positive and finite, so the sum is positive and finite and . The sum is at least , so its inverse is at most .
Claim 2 (function distances). After line L1, is defined exactly for the functions from which some target function is reachable in the call graph, and then . Moreover exactly when is a target function.
Proof. Breadth-first search from in an unweighted graph labels every node reachable from with the number of edges on a shortest path from , and labels no other node; this is the standard invariant that the queue holds nodes in order of their label and that the labels in the queue differ by at most 1. So the list in line L1 is the list of the true distances to the reachable target functions, and it is empty exactly when none is reachable. A distance is 0 exactly when , so by Claim 1 the value is 0 exactly when is itself a target function.
Claim 3 (the set T). For each function , lines L2 and L3 put into exactly the target blocks of , with value 0, and the blocks of that call at least one function with a defined , with value over those callees. These values do not depend on line L4.
Proof. Line L2 reads only the target set, and line L3 reads only the call lists and the values , which are final after line L1 by Claim 2. Neither reads of a block outside , so the values of are final before line L4 runs.
Claim 4 (block distances). After line L4, a block of function has a distance exactly when some block of is reachable from in ; a block of keeps its value from Claim 3, and any other block gets . Every distance is at least 0, every target block has distance 0, and for every reachable from , .
Proof. The search from in gives the true values by the argument of Claim 2, and the values for are final by Claim 3, so each term of line L4 is the term of the definition. The list is empty exactly when no block of is reachable, and then gets no distance. All terms are at least 0, so by Claim 1 the result is at least 0 and at most each term, which is the last inequality. For the inequality holds with , because . Target blocks are in with value 0 by Claim 3.
Claim 5 (normalized distance). Let be the list of seed distances defined so far, with and . For every seed , line L6 together with the two conventions of the page gives .
Proof. If executes a block with a distance, is the mean of a nonempty list of numbers that are at least 0 (Claim 4), so it is defined and belongs to , which gives . If , then lies in 0 to 1. If , the convention gives . If has no distance, the convention gives 1.
Claim 6 (the factor). For , and , the factor of line L9 lies in to ; it is 1 for every seed at ; at a fixed time it does not grow as grows; and the temperature is at .
Proof. Line L7 gives , and makes , with at and at . Line L8 gives , a weighted mean with weights and of two numbers in 0 to 1, so and . The map is increasing, so the factor lies in to . At , and , so the factor is whatever is. At a fixed time, is an affine function of with slope , so , and with it the factor, does not grow as grows.
Claim 7 (energy and termination). Line L10 gives an energy with for a base energy of at least 1, and a campaign with a budget of inputs makes at most choices of a seed and ends.
Proof. By Claim 6, , so its floor is at most , and the maximum with 1 makes . Each choice of a seed with fewer than inputs made so far runs at least one input before the next choice, because , so after at most choices the count of inputs reaches and the loop stops, unless it stopped before on a target block.
Claims 2 and 4 are the statement about lines L1 to L4, and Claims 5 to 7 are the statement about lines L5 to L10.
Complexity
Line L1 runs one breadth-first search per function on the call graph, . Lines L2 to L4 run one search per block inside its function; a function with blocks and edges costs , and the sum is at most with the most blocks in one function. This is the step the paper moves to compile time, and keeping it inside functions, instead of building an interprocedural control-flow graph, is what makes it scale. At run time, the instrumentation adds a block's distance and a counter at each executed block, which is for a trace of blocks, and the minimum and maximum over seeds can be kept as running values or scanned in . The extra space is one distance per function and block and one per seed.
Properties
- Randomized. The distances are fixed; the inputs are random.
- Static guidance. The distance comes from the graphs, not from the inputs, so it is cheap but blind to data: a branch on a hash or a checksum looks short in the graph.
- Time-dependent. The same seed gets a different factor at different times; before the fuzzer still explores.
- Relative. The normalized distance compares a seed with the seeds found so far, so the closest seed gets the largest factor even if it is far in absolute terms.
- A heuristic. The constant , the mean over the trace and the cooling rule are design choices that the paper chose by experiment.
Variants and improvements
- Other distances. Later directed fuzzers weight edges by branch probabilities, use the order in which a sequence of targets must be reached, as for a use after a free, or rank targets by a static analysis.
- Pruning. Inputs whose path cannot reach any target can be dropped early instead of only being given less energy.
- Mixing with symbolic execution. Directed symbolic execution solves the path constraints to a target; hybrid fuzzing runs a solver when the fuzzer stalls near the target.
- Patch testing and crash reproduction. These are the two uses of the paper: the targets are the changed lines, or the frames of a stack trace, which ties in with crash bucketing.
- Undirected schedules. With all factors 1, the method is the plain greybox loop with the schedule of the underlying fuzzer, which is the baseline of the example.
When to use it
Use it when the question is about a few places in the program: does this patch break something, can this crash report be reproduced, is this static analyzer warning real. It needs the source or a lifted binary to compute the graphs, and indirect calls make the call graph incomplete, so some targets look unreachable. When the target is behind a strong check on the data, distance alone does not help; add a solver or a dictionary. For broad testing, use the undirected fuzzer.
Pitfalls
- Arithmetic mean in line L1 or L4. Writing "the mean of the distances to the targets" gives the same value to a block at distance 1 from one target and 9 from another as to a block at distance 5 from both. The right line uses the inverse of the sum of inverses, which ranks the first block as closer.
- Dividing by zero for a target function. Computing for divides by zero. The right line L1 uses the convention , which gives for a target function, or treats that case first.
- Counting blocks without a distance as 0. Writing line L5 as the mean over all executed blocks, with 0 for blocks without a distance, makes seeds that run unrelated code look close to the target. The right line skips such blocks.
- A degenerate normalization. When all seeds have the same distance, line L6 divides by zero. The right line gives a fixed value, here 1/2, which leaves the energy neutral.
- Cooling too fast. A small turns the fuzzer greedy before it has found a seed near the target, and with large energies per choice it can be slower than no direction at all, as the example shows. The right setting of is a fraction of the budget, chosen by experiment.
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/directed-greybox-fuzzing/. The authors are listed in prov/FRYRBP.jsonl.
"""Directed greybox fuzzing: target distances and the annealing schedule.
At instrumentation time, every basic block gets a distance to the target
blocks, from shortest paths in the call graph and in the control-flow
graph of its function (Bohme, Pham, Nguyen and Roychoudhury, CCS 2017).
At run time, a seed's distance is the mean distance of the blocks that it
executes, normalized to 0 to 1 over the seeds seen so far, and an annealing
power schedule multiplies the energy of a seed by a factor from 1/32 to
32 that favors close seeds more and more as time passes.
Conventions of this file, which the page states: 1/0 is infinity and 1/inf
is 0, so a function that is a target function has function distance 0; the
target blocks of a function belong to its set T with distance 0; a block
from which no block of T is reachable has no distance (None) and is
skipped in the seed distance. The distance and the schedule are heuristics.
The program is a model: graphs given as dictionaries, and a trace given as
a list of block names. Nothing here reads or runs a real program.
"""
import random
from collections import deque
from dataclasses import dataclass, field
from fractions import Fraction
from typing import Callable, Hashable, Mapping, Sequence
C = 10 # the factor that magnifies function-level distance, as in the paper
def bfs_distances(graph: Mapping[Hashable, Sequence[Hashable]], source: Hashable) -> dict[Hashable, int]:
"""Return the number of edges on a shortest path from source to every
node reachable from it. Cost: O(V + E)."""
dist = {source: 0}
queue = deque([source])
while queue:
u = queue.popleft()
for v in graph.get(u, ()):
if v not in dist:
dist[v] = dist[u] + 1
queue.append(v)
return dist
def harmonic_combination(values: Sequence[Fraction]) -> Fraction | None:
"""Return (sum of 1/v)^-1 over the values, with 1/0 = infinity, or None
for no values. This is the "harmonic mean" of the paper without the
count factor. Cost: O(len(values))."""
if not values:
return None
if any(v == 0 for v in values):
return Fraction(0)
return 1 / sum(Fraction(1) / v for v in values)
def function_distances(call_graph: Mapping[str, Sequence[str]], target_functions: set[str]) -> dict[str, Fraction]:
"""Return d_f(n, T_f) for every function n that can reach a target
function in the call graph. Cost: O(F (F + E)) for F functions and E
call edges, one BFS per function."""
out: dict[str, Fraction] = {}
for n in call_graph:
dist = bfs_distances(call_graph, n)
reach = [Fraction(dist[t]) for t in target_functions if t in dist]
h = harmonic_combination(reach) # @line L1
if h is not None:
out[n] = h
return out
def block_distances(
cfgs: Mapping[str, Mapping[str, Sequence[str]]],
calls: Mapping[str, Sequence[str]],
call_graph: Mapping[str, Sequence[str]],
target_blocks: set[str],
) -> dict[str, Fraction]:
"""Return d_b(m, T_b) for every block m that has a distance.
cfgs maps each function to its control-flow graph (block -> successors),
calls maps a block to the functions it calls, and the target functions
are the functions that contain a target block. Cost: O(F (F + E) + the
sum over functions of B (B + K)) for B blocks and K edges per function.
"""
target_functions = {f for f, g in cfgs.items() if any(b in target_blocks for b in g)}
df = function_distances(call_graph, target_functions)
out: dict[str, Fraction] = {}
for f, g in cfgs.items():
t_set: dict[str, Fraction] = {}
for m in g:
if m in target_blocks:
t_set[m] = Fraction(0) # @line L2
else:
reach = [df[n] for n in calls.get(m, ()) if n in df]
if reach:
t_set[m] = C * min(reach) # @line L3
for m in g:
if m in t_set:
out[m] = t_set[m]
continue
dist = bfs_distances(g, m)
terms = [dist[t] + t_set[t] for t in t_set if t in dist]
h = harmonic_combination(terms) # @line L4
if h is not None:
out[m] = h
return out
def seed_distance(trace: Sequence[str], db: Mapping[str, Fraction]) -> Fraction | None:
"""Return the mean of d_b over the executed blocks that have a distance,
each counted every time it runs, or None if no block has one.
Cost: O(len(trace))."""
vals = [db[b] for b in trace if b in db]
if not vals:
return None
return sum(vals, Fraction(0)) / len(vals) # @line L5
def normalized_distance(d: Fraction | None, lo: Fraction | None, hi: Fraction | None) -> Fraction:
"""Return (d - lo) / (hi - lo), the normalized seed distance in 0 to 1.
A seed without a distance gets 1 (the farthest), and when all seeds so
far have the same distance the result is 1/2. Cost: O(1)."""
if d is None or lo is None or hi is None:
return Fraction(1)
if hi == lo:
return Fraction(1, 2)
return (d - lo) / (hi - lo) # @line L6
def annealing_factor(nd: float, t: float, tx: float) -> float:
"""Return the factor 2^(10 p - 5) with p = (1 - nd)(1 - T) + T / 2 and
the temperature T = 20^(-t / tx). Time t is in abstract units (here, the
number of inputs made); tx > 0 is the time to exploitation, at which
T = 0.05. The factor lies in 1/32 to 32. Cost: O(1)."""
temp = 20.0 ** (-t / tx) # @line L7
p = (1.0 - nd) * (1.0 - temp) + 0.5 * temp # @line L8
return 2.0 ** (10.0 * p - 5.0) # @line L9
@dataclass
class Result:
"""The outcome of a campaign: the inputs made, whether a target block
was reached, the queue, and one tuple (seed index, factor, energy) per
choice."""
inputs: int
reached: bool
queue: list[bytes]
log: list[tuple[int, float, int]] = field(default_factory=list)
def directed_fuzz(
run: Callable[[bytes], Sequence[str]],
seeds: Sequence[bytes],
db: Mapping[str, Fraction],
target_blocks: set[str],
mutate: Callable[[bytes, random.Random], bytes],
rng: random.Random,
budget: int,
tx: float,
base: int = 16,
directed: bool = True,
) -> Result:
"""Run a greybox loop whose energy is base times the annealing factor.
run returns the trace of an input (a list of block names). An input is
kept when it executes a block not seen before. Seeds are chosen in turn,
as in AFL's queue cycle. With directed False, the factor is 1, which is
the undirected baseline. The campaign ends when an input executes a
target block or after budget inputs.
Precondition: seeds is not empty, budget >= 0, tx > 0.
Cost: O(B (Q + T)) for B inputs, Q seeds and T the cost of run.
"""
if not seeds:
raise ValueError("at least one seed is needed")
queue = [bytes(s) for s in seeds]
dists: list[Fraction | None] = []
seen: set[str] = set()
for s in queue:
tr = run(s)
if any(b in target_blocks for b in tr):
return Result(0, True, queue)
seen |= set(tr)
dists.append(seed_distance(tr, db))
res = Result(0, False, queue)
turn = 0
while res.inputs < budget:
i = turn % len(queue)
turn += 1
known = [d for d in dists if d is not None]
lo, hi = (min(known), max(known)) if known else (None, None)
nd = float(normalized_distance(dists[i], lo, hi))
factor = annealing_factor(nd, res.inputs, tx) if directed else 1.0
energy = max(1, int(base * factor)) # @line L10
res.log.append((i, factor, energy))
for _ in range(energy):
if res.inputs == budget:
break
y = mutate(queue[i], rng)
tr = run(y)
res.inputs += 1
if any(b in target_blocks for b in tr):
res.reached = True
return res
new = set(tr) - seen
if new:
seen |= new
queue.append(y)
dists.append(seed_distance(tr, db))
return res
def set_one_byte(alphabet: int) -> Callable[[bytes, random.Random], bytes]:
"""Return a mutation that sets one uniform position to a uniform value
from 0 to alphabet - 1. Precondition: inputs are not empty."""
def mutate(x: bytes, rng: random.Random) -> bytes:
b = bytearray(x)
b[rng.randrange(len(b))] = rng.randrange(alphabet)
return bytes(b)
return mutate
test_directed_greybox_fuzzing.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/directed-greybox-fuzzing/. The authors are listed in prov/FRYRBP.jsonl.
import random
from fractions import Fraction
import pytest
from directed_greybox_fuzzing import (
C, annealing_factor, bfs_distances, block_distances, directed_fuzz, function_distances,
harmonic_combination, normalized_distance, seed_distance, set_one_byte,
)
# The model program of the page.
CFGS = {
"main": {"m1": ["m2", "m3"], "m2": ["m4"], "m3": ["m4"], "m4": []},
"log": {"l1": []},
"parse": {"p1": ["p2", "p3"], "p2": ["p4"], "p3": ["p4"], "p4": []},
"header": {"h1": []},
"body": {"b1": ["b2", "b5"], "b2": ["b3"], "b3": ["b4"], "b5": ["b4"], "b4": []},
"check": {"t1": ["t2", "t3"], "t2": [], "t3": []},
}
CALLS = {"m2": ["log"], "m3": ["parse"], "p2": ["header"], "p3": ["body"], "b3": ["check"]}
CALL_GRAPH = {"main": ["log", "parse"], "log": [], "parse": ["header", "body"], "header": [],
"body": ["check"], "check": []}
TARGETS = {"t2"}
def run(x: bytes) -> list[str]:
"""The trace of the model program: the blocks it executes, in order."""
tr = ["m1"]
if len(x) > 0 and x[0] == 1:
tr += ["m3", "p1"]
if len(x) > 1 and x[1] == 2:
tr += ["p3", "b1"]
if len(x) > 2 and x[2] == 3:
tr += ["b2", "b3", "t1"]
tr += ["t2"] if len(x) > 3 and x[3] == 4 else ["t3"]
else:
tr += ["b5"]
tr += ["b4"]
else:
tr += ["p2", "h1"]
tr += ["p4"]
else:
tr += ["m2", "l1"]
tr += ["m4"]
return tr
def test_page_example_distances():
df = function_distances(CALL_GRAPH, {"check"})
assert df == {"check": 0, "body": 1, "parse": 2, "main": 3}
db = block_distances(CFGS, CALLS, CALL_GRAPH, TARGETS)
assert db == {"t2": 0, "t1": 1, "b3": 0, "b2": 1, "b1": 2, "p3": 10, "p1": 11, "m3": 20, "m1": 21}
def test_page_example_seed_distances_and_factors():
db = block_distances(CFGS, CALLS, CALL_GRAPH, TARGETS)
inputs = [bytes([0, 0, 0, 0]), bytes([1, 0, 0, 0]), bytes([1, 2, 0, 0]), bytes([1, 2, 3, 0])]
ds = [seed_distance(run(x), db) for x in inputs]
assert ds == [Fraction(21), Fraction(52, 3), Fraction(64, 5), Fraction(33, 4)]
lo, hi = min(ds), max(ds)
nds = [normalized_distance(d, lo, hi) for d in ds]
assert nds == [1, Fraction(109, 153), Fraction(91, 255), 0]
rows = [[round(annealing_factor(float(nd), t, 100), 3) for t in (0, 100, 300)] for nd in nds]
assert rows == [
[1.0, 0.037, 0.031],
[1.0, 0.247, 0.229],
[1.0, 2.567, 2.697],
[1.0, 26.909, 31.986],
]
def test_page_example_measured_campaigns():
db = block_distances(CFGS, CALLS, CALL_GRAPH, TARGETS)
mutate = set_one_byte(8)
means = {}
for tx, directed in ((50.0, True), (1000.0, True), (1000.0, False)):
total = 0
for t in range(100):
r = directed_fuzz(run, [bytes(4)], db, TARGETS, mutate, random.Random(t), 10**6, tx,
directed=directed)
assert r.reached
total += r.inputs
means[(tx, directed)] = round(total / 100)
assert means == {(50.0, True): 916, (1000.0, True): 245, (1000.0, False): 343}
# The first choices of one directed campaign: (seed, factor, energy).
r = directed_fuzz(run, [bytes(4)], db, TARGETS, mutate, random.Random(0), 10**6, 1000.0)
assert r.inputs == 283
assert [(i, e) for i, _, e in r.log] == [
(0, 16), (0, 16), (0, 11), (1, 24), (0, 8), (1, 32), (0, 6), (1, 43), (2, 58), (1, 7), (2, 25), (3, 97),
]
def test_edge_cases():
assert harmonic_combination([]) is None
assert harmonic_combination([Fraction(0), Fraction(3)]) == 0
assert harmonic_combination([Fraction(2), Fraction(2)]) == 1
assert seed_distance(["l1", "m4"], {"m1": Fraction(3)}) is None
assert normalized_distance(None, Fraction(1), Fraction(2)) == 1
assert normalized_distance(Fraction(5), Fraction(5), Fraction(5)) == Fraction(1, 2)
assert annealing_factor(0.3, 0, 10) == 1.0
with pytest.raises(ValueError):
directed_fuzz(run, [], {}, TARGETS, set_one_byte(8), random.Random(0), 10, 1.0)
r = directed_fuzz(run, [bytes([1, 2, 3, 4])], {}, TARGETS, set_one_byte(8), random.Random(0), 10, 1.0)
assert r.reached and r.inputs == 0
def test_factor_range_and_monotonicity():
rng = random.Random(5)
for _ in range(2000):
nd = rng.random()
t = rng.uniform(0, 1000)
tx = rng.uniform(1, 200)
f = annealing_factor(nd, t, tx)
assert 1 / 32 - 1e-12 <= f <= 32 + 1e-12
# Closer seeds never get a smaller factor at the same time.
assert annealing_factor(nd / 2, t, tx) >= f - 1e-12
assert abs(annealing_factor(0.0, 100, 100) - 2 ** (10 * (0.95 + 0.025) - 5)) < 1e-12
def floyd_warshall(nodes, graph):
inf = float("inf")
d = {u: {v: (0 if u == v else inf) for v in nodes} for u in nodes}
for u in nodes:
for v in graph.get(u, ()):
d[u][v] = min(d[u][v], 1)
for k in nodes:
for i in nodes:
for j in nodes:
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]
return d
def oracle_block_distances(cfgs, calls, call_graph, targets):
"""The formulas of the page, from all-pairs shortest paths."""
funcs = list(cfgs)
fd = floyd_warshall(funcs, call_graph)
tf = [f for f in funcs if any(b in targets for b in cfgs[f])]
def inv_sum(vals):
if any(v == 0 for v in vals):
return Fraction(0)
return 1 / sum(Fraction(1) / v for v in vals)
df = {}
for n in funcs:
vals = [Fraction(int(fd[n][t])) for t in tf if fd[n][t] != float("inf")]
if vals:
df[n] = inv_sum(vals)
out = {}
for f in funcs:
blocks = list(cfgs[f])
bd = floyd_warshall(blocks, cfgs[f])
tset = {}
for m in blocks:
if m in targets:
tset[m] = Fraction(0)
elif any(n in df for n in calls.get(m, ())):
tset[m] = C * min(df[n] for n in calls.get(m, ()) if n in df)
for m in blocks:
if m in tset:
out[m] = tset[m]
else:
vals = [int(bd[m][t]) + tset[t] for t in tset if bd[m][t] != float("inf")]
if vals:
out[m] = inv_sum(vals)
return out
def random_program(rng):
nf = rng.randint(1, 4)
funcs = ["f" + str(i) for i in range(nf)]
cfgs, calls, cg = {}, {}, {f: [] for f in funcs}
for f in funcs:
nb = rng.randint(1, 4)
blocks = [f + "b" + str(j) for j in range(nb)]
cfgs[f] = {b: [c for c in blocks if rng.random() < 0.35] for b in blocks}
for b in blocks:
if rng.random() < 0.3:
callee = rng.choice(funcs)
calls[b] = [callee]
if callee not in cg[f]:
cg[f].append(callee)
all_blocks = [b for g in cfgs.values() for b in g]
targets = {b for b in all_blocks if rng.random() < 0.2}
return cfgs, calls, cg, targets
def test_random_programs_against_floyd_warshall():
rng = random.Random(17)
for _ in range(600):
cfgs, calls, cg, targets = random_program(rng)
got = block_distances(cfgs, calls, cg, targets)
assert got == oracle_block_distances(cfgs, calls, cg, targets)
for b in targets:
assert got[b] == 0
assert all(v >= 0 for v in got.values())
def test_bfs_small():
g = {"a": ["b"], "b": ["c", "a"], "c": []}
assert bfs_distances(g, "a") == {"a": 0, "b": 1, "c": 2}
assert bfs_distances(g, "c") == {"c": 0}
History
Directed symbolic execution tools tried to reach a given location by solving path constraints, which is precise but slow. Böhme, Pham, Nguyen and Roychoudhury (2017) moved the analysis to compile time and the guidance into the power schedule of greybox fuzzing, building on their Markov chain model of 2016, and released AFLGo. They reported, by measurement, that it reproduced known crashes faster than directed symbolic execution tools on their benchmarks, and that it found new bugs when used to test patches. Many directed fuzzers since then keep the same structure of a static distance and a dynamic energy.
References
- Marcel Böhme, Van-Thuan Pham, Manh-Dung Nguyen and Abhik Roychoudhury, Directed greybox fuzzing, Proceedings of CCS 2017, pp. 2329 to 2344, Section 3 (the function-level and basic-block-level target distances, the seed distance and its normalization, the annealing-based power schedule and its integration with AFL)
- Marcel Böhme, Van-Thuan Pham and Abhik Roychoudhury, Coverage-based greybox fuzzing as Markov chain, Proceedings of CCS 2016, pp. 1032 to 1043, power schedules
- 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 discussion of directed fuzzers and seed scheduling
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 FRYRBP Edit this page History Report an error Markdown