Algorithm Search⌘K

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
Properties
randomizedrandomized
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 TbT_b of target basic blocks, seeds, and a time budget, with a time txt_x 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 1/0=∞1/0 = \infty and 1/∞=01/\infty = 0 throughout:

  1. DIRECTED-DISTANCES(call graph CG, control-flow graphs G_i, target blocks T_b)
  2. 1for 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
  3. 2for each function i: T <- the target blocks of i, each with d_b = 0
  4. 3add 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)
  5. 4for 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
  6. DIRECTED-ENERGY(seed s, time t)
  7. 5d(s) <- the mean of d_b over the blocks that s executes and that have a distance
  8. 6d~(s) <- (d(s) - minD) / (maxD - minD), with minD and maxD over the seeds so far
  9. 7temperature <- 20^(-t / t_x)
  10. 8p <- (1 - d~(s)) (1 - temperature) + 0.5 temperature
  11. 9factor <- 2^(10 p - 5)
  12. 10energy <- max(1, floor(base energy * factor))

The target functions are the functions that contain a target block, dCGd_{CG} and dGd_G count edges on shortest paths (one breadth-first search per node), and C=10C = 10 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 TT as the blocks that call a function on the way to a target; this page also puts the target blocks themselves into TT with distance 0, so that blocks in the target's own function get a distance. With 1/0=∞1/0 = \infty, a target function has df=0d_f = 0, 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 d~=1\tilde d = 1, and when all seeds so far have one distance, d~=1/2\tilde d = 1/2; 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 t=0t = 0 and 0.05 at t=txt = t_x. Line L8 mixes the closeness 1−d~1 - \tilde d with the neutral value 1/21/2; at t=0t = 0, p=1/2p = 1/2 and the factor is 1 for every seed, and as the temperature falls, pp tends to 1−d~1 - \tilde d. 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 dfd_f = 0 for check, 1 for body, 2 for parse and 3 for main; log and header reach no target.

block function role dbd_b
t2 check target 0
t1 check branches to t2 1
b3 body calls check 10⋅0=010 \cdot 0 = 0
b2, b1 body one and two edges before b3 1, 2
p3 parse calls body 10⋅1=1010 \cdot 1 = 10
p1 parse one edge before p3 11
m3 main calls parse 10⋅2=2010 \cdot 2 = 20
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 tx=100t_x = 100 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 d(s)d(s) d~(s)\tilde d(s) factor at t=0t = 0 at t=100t = 100 at t=300t = 300
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, tx=1000t_x = 1000 245
directed, tx=50t_x = 50 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 txt_x 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 t=0t = 0, and at any time it does not grow as d~\tilde d 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 TT in line L4 are already final when line L4 runs, because lines L2 and L3 do not depend on line L4. For the schedule, 0≤d~≤10 \le \tilde d \le 1 and 0<temperature≤10 < \text{temperature} \le 1 make pp a mix of two numbers in 0 to 1, so 0≤p≤10 \le p \le 1 and the factor is between 2−52^{-5} and 252^5. 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 2−52^{-5} to 252^{5} 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, 1/0=∞1/0 = \infty and 1/∞=01/\infty = 0, and for a finite nonempty list of numbers x1,…,xr≥0x_1, \dots, x_r \ge 0 we write h(x1,…,xr)=(∑j1/xj)−1h(x_1, \dots, x_r) = \left(\sum_j 1/x_j\right)^{-1}. 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 x1,…,xr≥0x_1, \dots, x_r \ge 0 with r≥1r \ge 1, h(x1,…,xr)=0h(x_1, \dots, x_r) = 0 if some xj=0x_j = 0, and otherwise 0<h(x1,…,xr)≤min⁡jxj0 < h(x_1, \dots, x_r) \le \min_j x_j.

Proof. If some xj=0x_j = 0, then 1/xj=∞1/x_j = \infty, the sum is ∞\infty and its inverse is 0. Otherwise every term 1/xj1/x_j is positive and finite, so the sum is positive and finite and h>0h > 0. The sum is at least 1/min⁡jxj1/\min_j x_j, so its inverse is at most min⁡jxj\min_j x_j. □\square

Claim 2 (function distances). After line L1, df(n)d_f(n) is defined exactly for the functions nn from which some target function is reachable in the call graph, and then df(n)=h(dCG(n,t):t a reachable target function)d_f(n) = h(d_{CG}(n, t) : t \text{ a reachable target function}). Moreover df(n)=0d_f(n) = 0 exactly when nn is a target function.

Proof. Breadth-first search from nn in an unweighted graph labels every node reachable from nn with the number of edges on a shortest path from nn, 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 dCG(n,t)d_{CG}(n, t) to the reachable target functions, and it is empty exactly when none is reachable. A distance dCG(n,t)d_{CG}(n, t) is 0 exactly when t=nt = n, so by Claim 1 the value is 0 exactly when nn is itself a target function. □\square

Claim 3 (the set T). For each function ii, lines L2 and L3 put into TT exactly the target blocks of ii, with value 0, and the blocks of ii that call at least one function with a defined dfd_f, with value C⋅min⁡dfC \cdot \min d_f 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 dfd_f, which are final after line L1 by Claim 2. Neither reads dbd_b of a block outside TT, so the values of TT are final before line L4 runs. □\square

Claim 4 (block distances). After line L4, a block mm of function ii has a distance exactly when some block of TT is reachable from mm in GiG_i; a block of TT keeps its value from Claim 3, and any other block gets h(dG(m,t)+db(t):t∈T reachable from m)h(d_G(m, t) + d_b(t) : t \in T \text{ reachable from } m). Every distance is at least 0, every target block has distance 0, and for every t∈Tt \in T reachable from mm, db(m)≤dG(m,t)+db(t)d_b(m) \le d_G(m, t) + d_b(t).

Proof. The search from mm in GiG_i gives the true values dG(m,t)d_G(m, t) by the argument of Claim 2, and the values db(t)d_b(t) for t∈Tt \in T 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 TT is reachable, and then mm 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 m∈Tm \in T the inequality holds with t=mt = m, because dG(m,m)=0d_G(m, m) = 0. Target blocks are in TT with value 0 by Claim 3. □\square

Claim 5 (normalized distance). Let DD be the list of seed distances defined so far, with min⁡D\min D and max⁡D\max D. For every seed ss, line L6 together with the two conventions of the page gives 0≤d~(s)≤10 \le \tilde d(s) \le 1.

Proof. If ss executes a block with a distance, d(s)d(s) is the mean of a nonempty list of numbers that are at least 0 (Claim 4), so it is defined and belongs to DD, which gives min⁡D≤d(s)≤max⁡D\min D \le d(s) \le \max D. If max⁡D>min⁡D\max D > \min D, then d~(s)=(d(s)−min⁡D)/(max⁡D−min⁡D)\tilde d(s) = (d(s) - \min D)/(\max D - \min D) lies in 0 to 1. If max⁡D=min⁡D\max D = \min D, the convention gives 1/21/2. If ss has no distance, the convention gives 1. □\square

Claim 6 (the factor). For 0≤d~≤10 \le \tilde d \le 1, t≥0t \ge 0 and tx>0t_x > 0, the factor of line L9 lies in 2−52^{-5} to 252^5; it is 1 for every seed at t=0t = 0; at a fixed time it does not grow as d~\tilde d grows; and the temperature is 1/20=0.051/20 = 0.05 at t=txt = t_x.

Proof. Line L7 gives τ=20−t/tx\tau = 20^{-t/t_x}, and t/tx≥0t/t_x \ge 0 makes 0<τ≤10 < \tau \le 1, with τ=1\tau = 1 at t=0t = 0 and τ=20−1\tau = 20^{-1} at t=txt = t_x. Line L8 gives p=(1−τ)(1−d~)+τ⋅12p = (1 - \tau)(1 - \tilde d) + \tau \cdot \tfrac12, a weighted mean with weights 1−τ≥01 - \tau \ge 0 and τ>0\tau > 0 of two numbers in 0 to 1, so 0≤p≤10 \le p \le 1 and −5≤10p−5≤5-5 \le 10p - 5 \le 5. The map x↦2xx \mapsto 2^x is increasing, so the factor lies in 2−52^{-5} to 252^5. At t=0t = 0, τ=1\tau = 1 and p=1/2p = 1/2, so the factor is 20=12^0 = 1 whatever d~\tilde d is. At a fixed time, pp is an affine function of d~\tilde d with slope −(1−τ)≤0-(1 - \tau) \le 0, so pp, and with it the factor, does not grow as d~\tilde d grows. □\square

Claim 7 (energy and termination). Line L10 gives an energy ee with 1≤e≤32⋅base1 \le e \le 32 \cdot \text{base} for a base energy of at least 1, and a campaign with a budget of BB inputs makes at most BB choices of a seed and ends.

Proof. By Claim 6, base⋅factor≤32⋅base\text{base} \cdot \text{factor} \le 32 \cdot \text{base}, so its floor is at most 32⋅base32 \cdot \text{base}, and the maximum with 1 makes e≥1e \ge 1. Each choice of a seed with fewer than BB inputs made so far runs at least one input before the next choice, because e≥1e \ge 1, so after at most BB choices the count of inputs reaches BB and the loop stops, unless it stopped before on a target block. □\square

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. ■\blacksquare

Complexity

Line L1 runs one breadth-first search per function on the call graph, O(n(n+e))O(n(n + e)). Lines L2 to L4 run one search per block inside its function; a function with viv_i blocks and kik_i edges costs O(vi(vi+ki))O(v_i(v_i + k_i)), and the sum is at most O(w(v+k))O(w(v + k)) with ww 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 O(L)O(L) for a trace of LL blocks, and the minimum and maximum over QQ seeds can be kept as running values or scanned in O(Q)O(Q). 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 txt_x 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 C=10C = 10, 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 1/dCG(n,t)1/d_{CG}(n, t) for n=tn = t divides by zero. The right line L1 uses the convention 1/0=∞1/0 = \infty, which gives df=0d_f = 0 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 txt_x 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 txt_x 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.

directed_greybox_fuzzing.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

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