Algorithm Search⌘K

Algorithmadvanced

Power schedule for fuzzing

Also called AFLFast schedule, Markov chain power schedule.

Gives more mutations to seeds that reach rare paths, by modeling greybox fuzzing as a Markov chain over paths.

Time
O(B (Q^2 + T)) worst
Space
O(Q) extra
Where
B = the number of generated inputs; Q = the number of seeds in the queue; T = the cost of one mutation and one run of the target
Properties
randomizedrandomized
Origin
Marcel Böhme, Van Thuan Pham, Abhik Roychoudhury, 2016

A power schedule decides how many mutants a greybox fuzzer makes from a seed each time it picks that seed from the queue; this number is the seed's energy. AFL gives each seed an energy that depends on its speed and size but not on how often its behavior has been seen. AFLFast (Böhme, Pham and Roychoudhury, 2016) models fuzzing as a Markov chain whose states are program paths: fuzzing a seed on path ii makes an input on path jj with some probability pijp_{ij}. Most inputs land on a few high-frequency paths, such as the path that rejects a bad header. The FAST schedule gives a seed an energy that grows exponentially with the number of times ss it was chosen and falls with the number ff of inputs that have exercised its path, so new and rare paths get most of the work. The schedules are heuristics. The Markov model explains why they help under its assumptions; it does not promise more bugs on a real program.

In plain words

A fuzzer has a list of saved inputs and must decide which ones to change and how much. Some saved inputs lead to code that the fuzzer has already run thousands of times; changing them again mostly gives the same old behavior. Other saved inputs reach code that the fuzzer has hardly seen; changes there are more likely to find something new. A power schedule counts, for each kind of behavior, how many inputs have shown it so far. It gives few changes to inputs with a common behavior and many to inputs with a rare one. It also raises the number each time the same input comes back, so that a rare input gets a fast, growing share of the time until its behavior stops being rare.

The problem

The input is a target PP with a path function (each input exercises one path, identified for example by its edge coverage bitmap), a nonempty list of seeds, a budget of BB generated inputs, a mutation operator and a schedule. The output is the queue of seeds and the count f(p)f(p) of inputs on each path pp. The goal is to discover many paths, or a given deep path, with few inputs. No schedule can be best for every target, so the measure is the number of inputs in experiments, compared with the statistics of Klees et al. (2018).

The algorithm

The main loop is the greybox loop of coverage-guided fuzzing with two changes, in line L3 (the search order) and in line L4 (the energy).

  1. POWER-SCHEDULE-FUZZ(P, seeds, B, schedule)
  2. 1queue <- the seeds, each with s = 0; f(p) <- the number of seeds on path p
  3. 2while fewer than B inputs are made do
  4. 3i <- the seed with the smallest (s(i), f(path(i)), index in queue)
  5. 4e <- ENERGY(s(i), f(path(i)), mu), where mu is the mean of f over the paths found
  6. 5repeat e times, while fewer than B inputs are made:
  7. 6x' <- MUTATE(x_i)
  8. 7p <- the path of P on x'; f(p) <- f(p) + 1
  9. 8if f(p) = 1 then append x' to queue
  10. 9s(i) <- s(i) + 1
  11. 10return queue and f
  12. ENERGY(s, f, mu), shown for the FAST and COE schedules
  13. 11FAST: e <- floor(alpha 2^s / (beta f))
  14. 12COE: if f > mu then return 0, otherwise e <- floor(alpha 2^s / beta)
  15. 13return min(M, max(1, e))

Here α\alpha is the base energy (in AFLFast, the energy AFL itself would give the seed), β≥1\beta \ge 1 is a constant, and MM is an upper bound. The six schedules of the paper are:

schedule energy before the bound
EXPLOIT α\alpha, the constant energy of AFL
EXPLORE α/β\alpha / \beta
COE (cut-off exponential) 0 if f>μf > \mu, otherwise α2s/β\alpha 2^s / \beta
FAST α2s/(βf)\alpha 2^s / (\beta f)
LINEAR αs/(βf)\alpha s / (\beta f)
QUAD αs2/(βf)\alpha s^2 / (\beta f)

Line L3 is the search strategy of AFLFast: seeds that were chosen less often come first, and among those, seeds on paths with a smaller ff. A new seed has s=0s = 0, so it is chosen in the next step after its discovery. Line L7 counts every generated input on its path, including inputs that are not kept, because ff estimates how dense the path is in the chain. Line L13 rounds and clamps the energy: at least 1 so that every chosen seed is fuzzed, at most MM so that one seed cannot take the whole budget.

Why the model favors rare paths. In the chain, a path with a high stationary probability is reached often whatever the fuzzer does, and a path with a low one is a low-density region. Fuzzing a seed of a dense path mostly gives dense paths again. The count f(p)f(p) is an estimate of the density of path pp under the current fuzzing, so dividing by ff moves energy to the low-density regions. The factor 2s2^s makes the energy of a seed grow fast while its path stays rare, and ff catches up once fuzzing the seed starts to produce inputs on the same path. This is an argument inside the model, which assumes fixed transition probabilities, while in a real fuzzer the queue and the chain change as paths are found.

Example

The target has four nested checks. The path of an input is the number of its leading bytes that equal the secret 3, 7, 1, 12, from 0 to 4. The mutation sets one uniform position of the 4-byte input to a uniform value from 0 to 15. The only seed is 0, 0, 0, 0, on path 0. From a seed of depth dd, a mutant has depth d+1d + 1 with probability q=14⋅116=164q = \frac14 \cdot \frac1{16} = \frac1{64} (the right position and the right value), depth jj with probability 14⋅1516\frac14 \cdot \frac{15}{16} for each j<dj < d (one of the correct bytes breaks), and depth dd otherwise. The test file checks this chain by listing all 64 choices.

The first ten choices of FAST with α=16\alpha = 16, β=1\beta = 1, M=1024M = 1024 and Python's random.Random(1) are these; each choice made ee inputs.

choice seed (its path) ss ff e=⌊16⋅2s/f⌋e = \lfloor 16 \cdot 2^s / f \rfloor
1 0 0 1 16
2 0 1 17 1
3 0 2 18 3
4 0 3 21 6
5 0 4 27 9
6 0 5 36 14
7 0 6 50 20
8 1 0 1 16
9 1 1 15 2
10 1 2 16 4

After choice 1, path 0 has been exercised 17 times, so its seed falls to energy 1, and then climbs as 2s2^s outgrows ff. During choice 7 a mutant reached path 1 and joined the queue; with s=0s = 0 it is chosen next and gets the full energy 16 because its path is new. Its count then jumps to 15 because most mutants of a depth-1 seed stay at depth 1, and its energy drops. The campaign reached path 4 after 217 inputs, with final counts 110, 76, 23, 8 and 1 for paths 0 to 4.

Over 400 campaigns with generator seeds 0 to 399, the mean number of inputs to reach path 4 was 396 with EXPLOIT (constant energy 16) and 333 with FAST. These are measurements on one toy target; the test file repeats them exactly. A reference point is the strategy that always fuzzes the deepest seed: it needs a sum of four geometric waits with mean 4/q=2564/q = 256 inputs. FAST gets closer to it because it stops spending on path 0 once path 0 is dense.

Correctness

A power schedule cannot be correct in the sense of finding more bugs; that is a measured property. What the algorithm guarantees is that its bookkeeping is right and that it ends. The proof file shows:

  • The counts are exact. At every line L2, f(p)f(p) equals the number of seeds plus generated inputs that exercised pp, and ∑pf(p)\sum_p f(p) is the number of seeds plus the number of inputs made.
  • The queue holds the first input of each new path. An input joins the queue exactly when its path had count 0 before it.
  • The energy is bounded. ENERGY returns a value from 1 to MM, except 0 for COE when f>μf > \mu.
  • The loop ends after exactly BB inputs. Even with COE, each pass over the seeds with equal ss makes an input: if a pass made none, no count changed during it, and the seed with the smallest ff in the queue has f≤μf \le \mu and gets energy at least 1.

The key invariant is the first one: ff counts runs by path, and every generated input is counted once.

Proof: Correctness of the power schedule loopfull

We prove the guarantees of the Correctness section for POWER-SCHEDULE-FUZZ (lines L1 to L10) and ENERGY (lines L11 to L13, with the other schedules of the table). The path function is deterministic, the list of seeds is not empty, B≥0B \ge 0, and α,β,M≥1\alpha, \beta, M \ge 1. Let nn be the number of seeds and let II be the number of inputs made so far.

Claim 1 (energy bounds). ENERGY returns an integer from 1 to MM, except that COE returns 0 when f>μf > \mu.

Proof. Every schedule other than the 0 case of COE computes a value ee and then returns min⁡(M,max⁡(1,e))\min(M, \max(1, e)) in line L13. Since M≥1M \ge 1, this value is at least 1 and at most MM. □\square

Claim 2 (counts). At every test of line L2 and at line L10, for every path pp, f(p)f(p) is the number of seeds on pp plus the number of generated inputs on pp, and ∑pf(p)=n+I\sum_p f(p) = n + I.

Proof. By induction over the steps. After line L1, f(p)f(p) is the number of seeds on pp and I=0I = 0. Line L7 is the only line that changes ff, and it runs exactly once for each generated input, adding 1 to the count of that input's path, at the same time as II grows by 1. So both statements are kept. □\square

Claim 3 (queue). After line L1 the queue is the list of seeds. A generated input joins the queue if and only if its path had no seed and no earlier generated input. In particular, the generated entries of the queue have pairwise different paths, and none of them is the path of a seed.

Proof. Line L8 appends x′x' exactly when f(p)=1f(p) = 1 after the increment of line L7, that is, when f(p)=0f(p) = 0 before it. By Claim 2, f(p)=0f(p) = 0 means that no seed and no earlier input exercised pp. Two appended inputs with the same path would both need count 0 before their increment, but the first increment makes the count positive for good, because counts never decrease. □\square

Claim 4 (search). Line L3 is well defined: the queue is never empty, and f(path(i))≥1f(\text{path}(i)) \ge 1 for every seed ii in it.

Proof. The queue starts with n≥1n \ge 1 entries and only grows. Each entry is a seed or a generated input, and by Claim 2 its own run is counted in the count of its path. □\square

So the divisions of ENERGY are by βf≥1\beta f \ge 1, and μ=(n+I)/(number of paths with f>0)\mu = (n + I) / (\text{number of paths with } f > 0) is defined.

Claim 5 (termination). The loop ends, and at line L10, I=BI = B.

Proof. Each pass through lines L3 to L9 makes at most B−IB - I inputs, because line L5 stops when I=BI = B. So I≤BI \le B always, and the loop ends as soon as I=BI = B. It remains to show that II keeps growing while I<BI < B.

For every schedule other than COE, Claim 1 gives e≥1e \ge 1, so each choice makes an input. For COE, consider the choices made while the smallest value of ss in the queue is some fixed σ\sigma. Line L3 picks only seeds with s=σs = \sigma, and line L9 raises each picked seed to σ+1\sigma + 1, so after at most QQ choices (with QQ the current queue size) every seed has s>σs > \sigma, unless an input was made, which may also add a new seed. Suppose these choices make no input. Then ff, μ\mu and the queue stay the same during them, and every seed is picked once. The seed jj with the smallest count has f(path(j))≤μf(\text{path}(j)) \le \mu, because μ\mu is the mean of the counts over the paths found and the path of jj is one of them, and the minimum over all seeds is at most the minimum over paths, which is at most the mean. When jj is picked, COE does not return 0, and by Claim 1 its energy is at least 1, so an input is made, a contradiction. Hence every QQ consecutive choices with a fixed queue make at least one input, and II reaches BB. The implementation also accepts a stop test on new paths, used by the example to end at path DD; it only ends the loop earlier, and Claims 1 to 4 still hold. □\square

Claim 6 (the chain of the example). Let the path of xx be the number of leading bytes of xx that equal a secret c0,…,cD−1c_0, \dots, c_{D - 1} with no zero byte, let a mutation set a uniform position to a uniform value from 0 to A−1A - 1, and let xx be c0,…,cd−1c_0, \dots, c_{d - 1} followed by D−dD - d zeros, with d<Dd < D. Then a mutant of xx has path d+1d + 1 with probability 1/(DA)1/(DA), path jj with probability (A−1)/(DA)(A - 1)/(DA) for each j<dj < d, and path dd otherwise.

Proof. If the position is j<dj < d, the path becomes jj unless the value is cjc_j, which leaves xx unchanged; this gives (A−1)/(DA)(A - 1)/(DA) for each jj. If the position is dd and the value is cdc_d, the first d+1d + 1 bytes match and byte d+1d + 1 (if any) is 0, which is not cd+1c_{d + 1}, so the path is d+1d + 1. Every other choice leaves the first dd bytes correct and byte dd different from cdc_d, so the path stays dd. □\square

Every seed in the queue of the example has this form, by Claim 6 applied to the step that discovered it and by induction, so the chain of the page describes every step. A fuzzer that always mutates the deepest seed waits for DD independent events of probability q=1/(DA)q = 1/(DA) each, so its expected number of inputs is D/qD/q by the mean of the geometric distribution; for D=4D = 4 and A=16A = 16 this is 256.

Claims 1 to 5 are the guarantees of the page: bounded energy, exact counts, a queue with the first input of each new path, and exactly BB inputs. ■\blacksquare

Complexity

Each choice scans the queue in line L3 and computes μ\mu, which costs O(Q)O(Q), and each input costs TT for the mutation and the run. With schedules that never return 0, every choice makes at least one input, so the time is O(B(Q+T))O(B(Q + T)). With COE, a pass can contain up to Q−1Q - 1 choices of energy 0 for one input, which gives the worst case O(B(Q2+T))O(B(Q^2 + T)) of the front matter. A priority queue keyed by (s,f,index)(s, f, \text{index}) and a running sum of ff bring the search to O(log⁡Q)O(\log Q), but a key changes whenever a count changes. The space is O(Q)O(Q) for the queue and the counts, plus the inputs.

Properties

  • Randomized. The schedule is deterministic given the counts, but the counts depend on random mutations.
  • Adaptive. Unlike plain mutation-based fuzzing, the energy of a seed depends on everything found so far.
  • Exponential search. FAST, COE, LINEAR and QUAD give a seed little energy the first time and more each time it returns while its path stays rare, which finds the energy a seed needs without knowing it in advance.
  • A heuristic. The model assumes fixed transition probabilities and one path per input. The schedules were chosen by the argument above and by experiment, not derived as optimal.

Variants and improvements

  • The other schedules. EXPLORE and EXPLOIT are constant; COE refuses seeds on paths above the mean count; LINEAR and QUAD grow slower than FAST in ss.
  • Bandit schedules. Woo et al. (2013) treat the choice of what to fuzz next as a multi-armed bandit problem for blackbox fuzzing; later greybox fuzzers apply bandit rules to seeds and to mutation operators.
  • Directed schedules. Directed greybox fuzzing multiplies the energy by a factor that grows as a seed gets closer to a target, with an annealing temperature that moves from exploration to exploitation.
  • Rare edges. Some fuzzers count hits per edge or per branch instead of per path, which is cheaper and less sensitive to the noise of path hashes.
  • Estimating what is left. The counts ff are the same data that STADS uses to estimate the chance that the next input finds a new path.

When to use it

Use a schedule of the FAST family when most inputs of a target take a few common paths, as with parsers that reject most mutants early. It costs almost nothing over plain greybox fuzzing: one counter per path and one division per choice. When the question is how to reach a known location, a directed schedule is a better fit. When the comparison between schedules matters, run repeated trials and use a statistical test, because single runs vary a lot (Klees et al. 2018).

Pitfalls

  • Overflow of 2s2^s. In a fixed-width integer, e <- alpha << s in line L11 wraps for large ss and can give a tiny or zero energy to the seed that should get the most. The right line bounds the factor first: compute the energy only while 2s≤Mβf/α2^s \le M \beta f / \alpha, and use MM beyond that.
  • Dividing by a zero count. If line L1 sets f(p)←0f(p) \leftarrow 0 for the seeds, line L11 divides by zero for a seed that was never run. The right line L1 counts the run of each seed, so f≥1f \ge 1.
  • Counting only kept inputs. Writing line L7 as "if pp is new then f(p)←1f(p) \leftarrow 1" leaves every count at 1, and FAST becomes α2s\alpha 2^s for all seeds. The right line counts every generated input.
  • Dropping the lower bound. Without max(1, e) in line L13, FAST gives energy 0 to seeds on dense paths until 2s2^s catches up, and the choices of line L3 are spent without making inputs.
  • Reading the model as a promise. The Markov argument is about the model; a speedup on one benchmark is a measurement, not a law for other programs.

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.

fuzzing_power_schedule.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fuzzing-power-schedule/. The authors are listed in prov/NACEVP.jsonl.
"""Power schedules for greybox fuzzing, in the form of AFLFast.

A greybox loop keeps a queue of seeds. Each time it picks a seed, the
power schedule decides the energy: how many mutants of that seed to make.
AFLFast models fuzzing as a Markov chain whose states are program paths,
and gives more energy to seeds whose path has been exercised rarely, so
that the fuzzer spends its time in the low-density parts of the chain.

The schedules are heuristics. The Markov model explains why the FAST
schedule helps under the model's assumptions; it does not promise more
bugs on a real program.

Here a path is any hashable value returned by path_of, and the mutation
is a function passed in. The tests use small Python functions on bytes
as targets; nothing here runs a real program.
"""

import random
from dataclasses import dataclass, field
from fractions import Fraction
from typing import Callable, Hashable, Sequence

EXPLOIT, EXPLORE, COE, FAST, LINEAR, QUAD = "exploit", "explore", "coe", "fast", "linear", "quad"
SCHEDULES = (EXPLOIT, EXPLORE, COE, FAST, LINEAR, QUAD)


def energy(schedule: str, s: int, f: int, alpha: int, beta: int, m: int, mu: Fraction) -> int:
    """Return the number of mutants for a seed, as an integer.

    s is the number of earlier choices of the seed, f >= 1 is the number of
    generated inputs (and seeds) that exercised its path, mu is the mean of
    f over the discovered paths, alpha >= 1 is the base energy, beta >= 1
    is the divisor of the schedule, and m >= 1 is the upper bound.

    EXPLOIT gives alpha; EXPLORE gives alpha / beta; COE gives 0 when
    f > mu and alpha 2^s / beta otherwise; FAST gives alpha 2^s / (beta f);
    LINEAR gives alpha s / (beta f); QUAD gives alpha s^2 / (beta f).
    Every value except the 0 of COE is rounded down and then clamped to
    1 to m. All arithmetic is on integers. Cost: O(s) bit operations.
    """
    if f < 1 or alpha < 1 or beta < 1 or m < 1 or s < 0:
        raise ValueError("need f, alpha, beta, m >= 1 and s >= 0")
    if schedule == EXPLOIT:
        e = alpha
    elif schedule == EXPLORE:
        e = alpha // beta
    elif schedule == COE:
        if f > mu:
            return 0  # @line L12
        e = (alpha << s) // beta
    elif schedule == FAST:
        e = (alpha << s) // (beta * f)  # @line L11
    elif schedule == LINEAR:
        e = (alpha * s) // (beta * f)
    elif schedule == QUAD:
        e = (alpha * s * s) // (beta * f)
    else:
        raise ValueError("unknown schedule " + repr(schedule))
    return min(m, max(1, e))  # @line L13


@dataclass
class Seed:
    """A queue entry: its input, its path and how often it was chosen."""

    data: bytes
    path: Hashable
    chosen: int = 0


@dataclass
class Campaign:
    """The state after a campaign.

    queue holds the seeds in order of discovery, freq maps each path to the
    number of inputs that exercised it, inputs is the number of generated
    inputs, and log holds one tuple (seed index, s, f, energy, inputs made)
    per choice."""

    queue: list[Seed]
    freq: dict[Hashable, int]
    inputs: int = 0
    log: list[tuple[int, int, int, int, int]] = field(default_factory=list)


def power_schedule_fuzz(
    path_of: Callable[[bytes], Hashable],
    seeds: Sequence[bytes],
    budget: int,
    rng: random.Random,
    schedule: str,
    mutate: Callable[[bytes, random.Random], bytes],
    alpha: int = 16,
    beta: int = 1,
    m: int = 1024,
    stop: Callable[[Hashable], bool] | None = None,
) -> Campaign:
    """Run a greybox loop with a power schedule until budget inputs are made.

    The search order picks the seed with the smallest (s, f, index): seeds
    chosen less often first, then seeds on rarer paths. An input whose path
    is new joins the queue. If stop is given, the campaign ends as soon as
    an input reaches a path p with stop(p).

    Precondition: seeds is not empty and budget >= 0. The loop terminates:
    in each pass over the seeds with the same s, either an input is made or
    no f changes, and then the seed with the smallest f has f <= mu and gets
    energy at least 1. Cost: O(B (Q + T)) for B inputs, Q seeds in the queue
    and T the cost of one call of mutate and path_of.
    """
    if not seeds:
        raise ValueError("at least one seed is needed")
    queue = [Seed(bytes(x), path_of(x)) for x in seeds]
    freq: dict[Hashable, int] = {}
    for sd in queue:
        freq[sd.path] = freq.get(sd.path, 0) + 1  # @line L1
    camp = Campaign(queue, freq)
    if stop is not None and any(stop(sd.path) for sd in queue):
        return camp
    while camp.inputs < budget:  # @line L2
        i = min(range(len(queue)), key=lambda j: (queue[j].chosen, freq[queue[j].path], j))  # @line L3
        sd = queue[i]
        mu = Fraction(sum(freq.values()), len(freq))
        f = freq[sd.path]
        e = energy(schedule, sd.chosen, f, alpha, beta, m, mu)  # @line L4
        made = 0
        done = False
        for _ in range(e):  # @line L5
            if camp.inputs == budget:
                break
            y = mutate(sd.data, rng)  # @line L6
            p = path_of(y)
            camp.inputs += 1
            made += 1
            freq[p] = freq.get(p, 0) + 1  # @line L7
            if freq[p] == 1:
                queue.append(Seed(y, p))  # @line L8
                if stop is not None and stop(p):
                    done = True
                    break
        camp.log.append((i, sd.chosen, f, e, made))
        sd.chosen += 1  # @line L9
        if done:
            break
    return camp  # @line L10


def depth_of(secret: bytes) -> Callable[[bytes], int]:
    """Return the path function of the chain model: the number of leading
    bytes of the input that equal the secret. It models nested checks, one
    byte per level. Cost of a call: O(len(secret))."""

    def path_of(x: bytes) -> int:
        d = 0
        while d < len(secret) and d < len(x) and x[d] == secret[d]:
            d += 1
        return d

    return path_of


def set_one_byte(alphabet: int) -> Callable[[bytes, random.Random], bytes]:
    """Return the mutation of the chain model: set one uniform position to a
    uniform value from 0 to alphabet - 1. Precondition: the input is not
    empty. Cost of a call: O(L) for an input of length L."""

    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_fuzzing_power_schedule.py 198 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fuzzing-power-schedule/. The authors are listed in prov/NACEVP.jsonl.
import itertools
import math
import random
from collections import Counter
from fractions import Fraction

import pytest

from fuzzing_power_schedule import (
    COE, EXPLOIT, EXPLORE, FAST, LINEAR, QUAD, SCHEDULES,
    depth_of, energy, power_schedule_fuzz, set_one_byte,
)

SECRET = bytes([3, 7, 1, 12])
PATH = depth_of(SECRET)
MUT = set_one_byte(16)


def run_example(schedule, t):
    return power_schedule_fuzz(PATH, [bytes(4)], 10**6, random.Random(t), schedule, MUT,
                               16, 1, 1024, stop=lambda p: p == 4)


def oracle_energy(schedule, s, f, alpha, beta, m, mu):
    """The schedules of the page, with exact rationals."""
    if schedule == EXPLOIT:
        v = Fraction(alpha)
    elif schedule == EXPLORE:
        v = Fraction(alpha, beta)
    elif schedule == COE:
        if f > mu:
            return 0
        v = Fraction(alpha * 2**s, beta)
    elif schedule == FAST:
        v = Fraction(alpha * 2**s, beta * f)
    elif schedule == LINEAR:
        v = Fraction(alpha * s, beta * f)
    else:
        v = Fraction(alpha * s * s, beta * f)
    return min(m, max(1, math.floor(v)))


def test_page_example_trace():
    c = run_example(FAST, 1)
    # (seed index, s, f, energy, inputs made) for the first ten choices.
    assert c.log[:10] == [
        (0, 0, 1, 16, 16), (0, 1, 17, 1, 1), (0, 2, 18, 3, 3), (0, 3, 21, 6, 6),
        (0, 4, 27, 9, 9), (0, 5, 36, 14, 14), (0, 6, 50, 20, 20), (1, 0, 1, 16, 16),
        (1, 1, 15, 2, 2), (1, 2, 16, 4, 4),
    ]
    assert c.inputs == 217
    assert [(sd.data, sd.path) for sd in c.queue] == [
        (bytes([0, 0, 0, 0]), 0), (bytes([3, 0, 0, 0]), 1), (bytes([3, 7, 0, 0]), 2),
        (bytes([3, 7, 1, 0]), 3), (bytes([3, 7, 1, 12]), 4),
    ]
    assert c.freq == {0: 110, 1: 76, 2: 23, 3: 8, 4: 1}


def test_page_example_measured_means():
    means = {}
    for sch in (EXPLOIT, FAST):
        runs = [run_example(sch, t).inputs for t in range(400)]
        means[sch] = round(sum(runs) / len(runs))
    assert means == {EXPLOIT: 396, FAST: 333}


def test_chain_transitions_of_the_model():
    # From a seed of depth d (the secret up to d, then zeros), list all 4 * 16
    # choices of the mutation and compare with the chain of the page.
    q = Fraction(1, 64)
    for d in range(4):
        x = SECRET[:d] + bytes(4 - d)
        assert PATH(x) == d
        counts = Counter()
        for pos in range(4):
            for v in range(16):
                b = bytearray(x)
                b[pos] = v
                counts[PATH(bytes(b))] += 1
        prob = {j: Fraction(n, 64) for j, n in counts.items()}
        assert prob.get(d + 1, 0) == q
        for j in range(d):
            assert prob[j] == Fraction(1, 4) * Fraction(15, 16)
        assert sum(prob.values()) == 1
        assert max(prob) == d + 1


def test_frontier_only_expectation():
    # Fuzzing only the deepest seed needs D / q = 256 inputs on average.
    rng = random.Random(7)
    total = 0
    trials = 400
    for _ in range(trials):
        x = bytes(4)
        d = 0
        n = 0
        while d < 4:
            y = MUT(x, rng)
            n += 1
            e = PATH(y)
            if e > d:
                x, d = y, e
        total += n
    mean = total / trials
    # The count is a sum of 4 geometric variables with p = 1/64: sd about 127.
    assert abs(mean - 256) <= 6 * 127 / math.sqrt(trials)


def test_energy_matches_rational_oracle():
    rng = random.Random(3)
    for _ in range(3000):
        sch = rng.choice(SCHEDULES)
        s = rng.randint(0, 12)
        f = rng.randint(1, 60)
        alpha = rng.randint(1, 40)
        beta = rng.randint(1, 5)
        m = rng.randint(1, 3000)
        mu = Fraction(rng.randint(1, 400), rng.randint(1, 9))
        assert energy(sch, s, f, alpha, beta, m, mu) == oracle_energy(sch, s, f, alpha, beta, m, mu)


def test_energy_edge_cases():
    assert energy(FAST, 0, 1, 16, 1, 1024, Fraction(1)) == 16
    assert energy(FAST, 100, 1, 16, 1, 1024, Fraction(1)) == 1024
    assert energy(FAST, 0, 1000, 16, 1, 1024, Fraction(1)) == 1
    assert energy(COE, 0, 5, 16, 1, 1024, Fraction(4)) == 0
    assert energy(COE, 0, 4, 16, 1, 1024, Fraction(4)) == 16
    assert energy(LINEAR, 0, 1, 16, 1, 1024, Fraction(1)) == 1
    with pytest.raises(ValueError):
        energy(FAST, 0, 0, 16, 1, 1024, Fraction(1))
    with pytest.raises(ValueError):
        energy("slow", 0, 1, 16, 1, 1024, Fraction(1))
    with pytest.raises(ValueError):
        power_schedule_fuzz(PATH, [], 10, random.Random(0), FAST, MUT)
    c = power_schedule_fuzz(PATH, [bytes(4)], 0, random.Random(0), FAST, MUT)
    assert c.inputs == 0 and c.log == [] and c.freq == {0: 1}
    c = power_schedule_fuzz(PATH, [SECRET], 50, random.Random(0), FAST, MUT, stop=lambda p: p == 4)
    assert c.inputs == 0


def reference_campaign(path_of, seeds, budget, rng, schedule, mutate, alpha, beta, m):
    """A second, plain version of the loop: it sorts the queue at each step."""
    queue = [[bytes(x), path_of(x), 0, k] for k, x in enumerate(seeds)]
    freq = Counter(e[1] for e in queue)
    inputs = 0
    log = []
    while inputs < budget:
        order = sorted(queue, key=lambda e: (e[2], freq[e[1]], e[3]))
        entry = order[0]
        mu = Fraction(sum(freq.values()), len(freq))
        e = oracle_energy(schedule, entry[2], freq[entry[1]], alpha, beta, m, mu)
        made = min(e, budget - inputs)
        f0 = freq[entry[1]]
        for _ in range(made):
            y = mutate(entry[0], rng)
            p = path_of(y)
            inputs += 1
            freq[p] += 1
            if freq[p] == 1:
                queue.append([y, p, 0, len(queue)])
        log.append((entry[3], entry[2], f0, e, made))
        entry[2] += 1
    return [(e[0], e[1]) for e in queue], dict(freq), inputs, log


def test_random_campaigns_match_reference_and_replay():
    rng = random.Random(11)
    for trial in range(500):
        n = rng.randint(1, 3)
        secret = bytes(rng.randrange(1, 4) for _ in range(n))
        path_of = depth_of(secret)
        mutate = set_one_byte(4)
        seeds = [bytes(rng.randrange(4) for _ in range(n)) for _ in range(rng.randint(1, 3))]
        sch = rng.choice(SCHEDULES)
        alpha, beta, m = rng.randint(1, 8), rng.randint(1, 3), rng.randint(1, 20)
        budget = rng.randint(0, 60)
        c = power_schedule_fuzz(path_of, seeds, budget, random.Random(trial), sch, mutate, alpha, beta, m)
        ref = reference_campaign(path_of, seeds, budget, random.Random(trial), sch, mutate, alpha, beta, m)
        assert ([(sd.data, sd.path) for sd in c.queue], c.freq, c.inputs, c.log) == ref
        # Replay the bookkeeping from the log alone.
        assert c.inputs == sum(row[4] for row in c.log) == budget
        assert sum(c.freq.values()) == len(seeds) + c.inputs
        chosen = Counter(row[0] for row in c.log)
        assert all(sd.chosen == chosen.get(k, 0) for k, sd in enumerate(c.queue))
        assert all(0 <= row[3] <= m for row in c.log)
        assert len({sd.path for sd in c.queue[len(seeds):]}) == len(c.queue) - len(seeds)


def test_path_function_against_brute_force():
    secret = bytes([1, 2])
    path_of = depth_of(secret)
    for n in range(4):
        for t in itertools.product(range(3), repeat=n):
            x = bytes(t)
            expect = max(d for d in range(3) if x[:d] == secret[:d])
            assert path_of(x) == expect

History

AFL (2013) assigned energy by a performance score of speed, coverage size and queue depth. Böhme, Pham and Roychoudhury (2016) modeled coverage-based greybox fuzzing as a Markov chain over paths, explained AFL's waste on high-frequency paths, and proposed the schedules above and the search order by ss and ff in AFLFast; they measured their tool on GNU binutils against AFL. The same group used the annealing schedule for directed fuzzing in 2017, and the counts per path became the input to statistical estimates of fuzzing progress such as STADS (2018).

References

  1. 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, the power schedules EXPLOIT, EXPLORE, COE, FAST, LINEAR and QUAD, and the search strategy
  2. Andreas Zeller, Rahul Gopinath, Marcel Böhme, Gordon Fraser and Christian Holler, The Fuzzing Book, chapter Greybox Fuzzing, the sections on power schedules and boosted greybox fuzzing
  3. Maverick Woo, Sang Kil Cha, Samantha Gottlieb and David Brumley, Scheduling black-box mutational fuzzing, Proceedings of CCS 2013, pp. 511 to 522, scheduling as a multi-armed bandit problem
  4. George Klees, Andrew Ruef, Benji Cooper, Shiyi Wei and Michael Hicks, Evaluating fuzz testing, Proceedings of CCS 2018, pp. 2123 to 2138, how to compare fuzzers with repeated trials and statistical tests

Where this leads

About this page

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

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