Algorithm Search⌘K

Algorithmresearch

Input-to-state correspondence

Also called Redqueen.

Solves magic byte and checksum comparisons by finding operands of comparisons that appear in the input and patching them directly.

Time
O((c + 1) n (n + T)) worst
Space
O(c n^2) extra
Where
T = the cost of one run of the target; c = the number of comparisons in one run; n = the length of the input
Properties
randomizedofflinerandomizediterative
Origin
Cornelius Aschermann, Sergej Schumilo, Tim Blazytko, Robert Gawlik, Thorsten Holz, 2019

Input-to-state correspondence is a method that helps a coverage-guided fuzzer pass the comparisons that random mutation almost never satisfies, such as a check of a 4-byte magic value or of a stored checksum. The observation of Aschermann, Schumilo, Blazytko, Gawlik and Holz (NDSS 2019) is that in such a comparison one operand is often a direct copy of some input bytes, perhaps in another byte order or width. So the fuzzer logs the two operands of each comparison, searches the input for an encoding of one operand, and writes the matching encoding of the other operand in its place. The method needs no taint tracking and no symbolic execution: only a run that records comparisons. A step called colorization first fills the input with random bytes wherever this keeps the path, so that an operand occurs only where it came from. The costs on this page are in the word-RAM model.

In plain words

Some programs check that the input starts with a fixed word, such as "TOY1". A fuzzer that changes bytes at random has about one chance in four billion to get four bytes right. So the check stops it.

Input-to-state correspondence watches the program instead. When the program compares the first four input bytes with "TOY1", the fuzzer sees both values. It looks for the first value in the input, finds it at the start, and writes "TOY1" there. One run is enough.

To make the search clear, the fuzzer first puts random bytes into every part of the input that does not change what the program does. Then the value that the program read is rare, and it shows up only in the place it came from.

The problem

The input is a deterministic program PP that logs the two operands of each comparison it executes, and an input xx that reaches some comparisons but fails them. The goal is a small set of new inputs that pass those comparisons, so that the fuzzer covers new branches. A comparison of an integer read from the input with a constant of kk bytes is true for a fraction 256−k256^{-k} of the values of the field, so random mutation needs about 256k256^k tries on average. Exact methods exist: concolic testing builds a path condition and calls a solver, and taint tracking finds the input bytes that flow into the comparison. Both cost much more per run than a plain run.

The algorithm

The main block takes one input of the fuzzing queue. Line L7 belongs to the fuzzing loop around it, which keeps the candidates that cover a new (site, outcome) pair and puts them in the queue.

  1. INPUT-TO-STATE(P, x) ▷ P logs the operands (a, b, w) of each comparison
  2. 1x' ← COLORIZE(P, x)
  3. 2T ← the comparisons (a, b, w) that the run of P on x' executes
  4. 3Y ← ∅
  5. 4for each (a, b, w) in T, each pair (u, v) in {(a, b), (b, a)} and each encoding E for w do
  6. 5for each position i where E(u) occurs in x' do
  7. 6Y ← Y ∪ {x' with E(v) written at position i}
  8. 7keep the inputs y in Y whose run covers a (site, outcome) pair not seen before
  9. 8return those inputs
  10. COLORIZE(P, x)
  11. 9h ← the path of P on x, ranges ← {[0, |x|)}
  12. 10while ranges ≠ ∅ and the budget is not used up do
  13. 11take the longest range [i, j) out of ranges, y ← x with random bytes at i to j - 1
  14. 12if the path of P on y is h then x ← y
  15. 13else if j - i > 1 then put the two halves of [i, j) into ranges
  16. 14return x

The encodings of line L4 are little endian and big endian at the width ww of the comparison and at each smaller width of 1, 2, 4 or 8 bytes that holds both values, because a field of one byte may be widened to four before the comparison. A comparison of byte strings, such as a call of memcmp, is used as it is. The paper uses a larger set of encodings and more kinds of comparison; the list here is a small design choice for the toy targets.

Line L12 compares the whole path, so a random byte stays only where the program does not look at it, or looks at it without a change of branch. The bytes that the program compares with a constant are usually of this second kind: the comparison fails before and after the change. So colorization fills them too, and their value becomes rare.

Example

The target is a made-up format. It reads the first four bytes as a little-endian integer and compares it with 0x31594F54\mathtt{0x31594F54} (the bytes "TOY1"); if that holds, it compares bytes 4 and 5 as a big-endian integer with 0x0102\mathtt{0x0102}; if that holds, it compares bytes 6 and 7 with "OK" and then fails. The seed is "AAAAAAAA", eight bytes 0x41\mathtt{0x41}.

Without colorization. The run logs one comparison, a=0x41414141a = \mathtt{0x41414141} against b=0x31594F54b = \mathtt{0x31594F54} at width 4. The pattern of aa is "AAAA" in both byte orders, and it occurs at positions 0 to 4. So lines L4 to L6 build 10 inputs, five with "TOY1" and five with "1YOT", and only "TOY1AAAA" passes the check.

With colorization. The implementation, with seed 1 of its generator, replaces all eight bytes at once, and the path stays the same (the first check still fails). The new input is 44 20 82 3c fd e6 f1 c2\mathtt{44\,20\,82\,3c\,fd\,e6\,f1\,c2} in hexadecimal, after 2 runs. The logged operand is now a=0x3c822044a = \mathtt{0x3c822044}, whose little-endian pattern occurs only at position 0, and whose big-endian pattern does not occur. Line L6 builds one input, "TOY1" followed by fd e6 f1 c2\mathtt{fd\,e6\,f1\,c2}, and it passes the first check.

round queue input comparison that fails candidate that passes
1 "AAAAAAAA" site 1, little-endian width 4 "TOY1" + 4 random bytes
2 "TOY1" + 4 random bytes site 2, big-endian width 2 "TOY1", 01 02\mathtt{01\,02}, 2 random bytes
3 "TOY1", 01 02\mathtt{01\,02}, 2 random bytes site 3, bytes "OK" "TOY1", 01 02\mathtt{01\,02}, "OK"

The loop finds the failing input "TOY1", 01 02\mathtt{01\,02}, "OK" after 33 runs in total, with a corpus of 3 inputs. A blind fuzzer would need on the order of 2568256^8 tries for the same eight bytes. The tests of the implementation check these numbers.

Correctness

The method is a heuristic, and its guarantee holds under a condition. Suppose a comparison on the colorized input compares uu with vv, uu was read from the bytes at position ii with one of the encodings, and neither the path up to the comparison nor vv depends on those bytes. Then line L6 builds the input with the encoding of vv at position ii, and on that input the comparison is reached and is true. This is input-to-state correspondence. Colorization keeps the path by construction, and after it a pattern of ℓ\ell bytes occurs by chance at a given random position with probability 256−ℓ256^{-\ell}, so most candidates are useful. For a program that checks kk disjoint fields against constants, one after the other, the loop reaches the end with enough runs. If the program transforms the bytes before the comparison, by a hash or an exclusive or with a key, the condition fails and the method gives nothing; the tests show this case. The full proof is in the proof file.

Proof: Correctness of input-to-state correspondencefull

We prove the claims of the Correctness section for INPUT-TO-STATE (lines L1 to L8) and COLORIZE (lines L9 to L14). The program PP is deterministic: the same input gives the same path, the same logged comparisons and the same outcome. A path is the sequence of (site, outcome) pairs of the comparisons that a run executes. An encoding EE maps a value to a byte string: little or big endian at a width w′w' of 1, 2, 4 or 8 bytes, or the identity for byte strings.

Claim 1 (colorization keeps the path). COLORIZE returns an input x′x' with ∣x′∣=∣x∣|x'| = |x| and PATH(P,x′)=PATH(P,x)\mathrm{PATH}(P, x') = \mathrm{PATH}(P, x). If the budget is at least 2∣x∣2|x|, it uses at most 2∣x∣2|x| runs.

Proof. Line L11 changes bytes only inside [0,∣x∣)[0, |x|), so the length stays the same. Line L12 replaces xx by yy only when the path of yy equals hh, the path of the original input from line L9, so the current input always has path hh. The ranges form a binary tree: the root is [0,∣x∣)[0, |x|), and line L13 gives a range of length ℓ>1\ell > 1 two children of lengths ⌊ℓ/2⌋\lfloor \ell/2 \rfloor and ⌈ℓ/2⌉\lceil \ell/2 \rceil. Every range that line L11 takes is a node of the full halving tree of [0,∣x∣)[0, |x|), whose leaves are the ∣x∣|x| single bytes, so at most 2∣x∣−12|x| - 1 ranges are tried. Each costs one run, and line L9 costs one more. □\square

Claim 2 (the main property). Let x′x' be the input of line L2, and let one comparison of its run compare uu with vv. Suppose that, for some position ii and some encoding EE in the list, (a) E(u)=x′[i…i+∣E(u)∣−1]E(u) = x'[i \ldots i + |E(u)| - 1], and uu was read from exactly these bytes with this encoding; (b) vv has an encoding E(v)E(v) of the same length; and (c) neither the path up to this comparison nor the value vv depends on these bytes. Then line L6 puts into YY the input yy equal to x′x' with E(v)E(v) written at ii, and in the run of PP on yy this comparison is reached and is true.

Proof. Line L4 tries the ordered pair (u,v)(u, v) with the encoding EE. Line L5 finds every position where E(u)E(u) occurs, and by (a) ii is one of them, so line L6 builds yy. The two inputs differ only in the bytes [i,i+∣E(u)∣)[i, i + |E(u)|). By (c) and determinism, the run on yy follows the same path up to the comparison and computes the same vv. By (a) it reads the first operand from the changed bytes with the encoding EE, so it reads the value whose encoding is E(v)E(v), which is vv. So the comparison is v=vv = v, which is true. □\square

Conditions (a) to (c) are the input-to-state correspondence: an operand is a direct copy of input bytes. Redqueen observes that this is common in parsers (magic values, length fields, stored checksums) and does not claim it in general. If the program transforms the bytes before the comparison, for example by a hash or an exclusive or with a key, condition (a) fails, the pattern need not occur in the input, and the step gives nothing useful. The tests check this case.

Claim 3 (colorization removes spurious positions). After colorization, a byte that does not affect the path holds a byte drawn uniformly at random. A pattern of ℓ\ell bytes occurs at a fixed position made only of such bytes with probability 256−ℓ256^{-\ell}.

Proof. When line L12 accepts a range, every byte in it is a fresh uniform byte from line L11, independent of the pattern, which comes from a run on the input before the change. The bytes of a fixed window are then independent and uniform, so they equal a given pattern with probability 256−ℓ256^{-\ell}. □\square

Claim 3 is the reason for colorization. With a seed of equal bytes, the operand read from the input occurs at many positions, and the step builds a candidate for each. With random bytes, the operand occurs where it was read and, with high probability, nowhere else.

Claim 4 (no false reports). Every input that the fuzzing loop reports as a crash makes PP fail, and every input it adds to the corpus covers a (site, outcome) pair that no earlier input covered.

Proof. The loop reports yy only after a run of PP on yy failed, and PP is deterministic. Line L7 adds yy only if its path has a pair outside the covered set, and then adds those pairs to the set. □\square

Claim 5 (nested checks). Let PP compare kk disjoint fields of the input, one after the other, each against a constant, read with an encoding from the list, and stop at the first false comparison; let it fail if all kk are true. With an unlimited number of runs, the loop finds an input on which PP fails.

Proof. We show by induction on jj that some input in the corpus passes the first jj checks. For j=0j = 0 the seed does. Suppose an input zz in the corpus passes the first j<kj < k checks. The loop takes zz from the queue at some point, because the queue is first in, first out and every input in the corpus was put in it. By Claim 1 the colorized z′z' still passes the first jj checks and reaches check j+1j + 1. Conditions (a) to (c) of Claim 2 hold for check j+1j + 1: its operand is read from its own field with the encoding of the check, the other operand is a constant, and the earlier checks read other fields. So a candidate yy passes check j+1j + 1. Writing at the field of check j+1j + 1 does not change the other fields, so yy also passes the first jj checks. Either j+1=kj + 1 = k and PP fails on yy, or yy covers the pair (check j+1j + 1, true). If no earlier input covered that pair, yy goes into the corpus. If an earlier input covered it, that input passed check j+1j + 1 and, since the checks are nested, also the first jj checks, and it is in the corpus by Claim 4. □\square

Complexity

Let nn be the length of the input, cc the number of comparisons in one run, and TT the cost of one run. Colorization tries at most 2n−12n - 1 ranges, each a copy of O(n)O(n) bytes and a run, so it costs O(n(n+T))O(n (n + T)). There are at most 16 pattern pairs per comparison (two orders of the operands, two byte orders, four widths), and each pattern occurs at most nn times, so there are O(cn)O(c n) candidates. Building and running them costs O(cn(n+T))O(c n (n + T)). The total is O((c+1)n(n+T))O((c + 1) n (n + T)). The implementation keeps all candidates, O(cn2)O(c n^2) bytes; running each candidate as it is built needs only O(n+c)O(n + c) extra space. A run with logging costs more than a plain run, so the logging run is done once per input and the candidates run without it.

Properties

  • Cheap. It needs a run with comparison logging and plain runs, not a solver or a taint engine.
  • Incomplete. It solves a comparison only when an operand is a copy of input bytes in one of the encodings.
  • Randomized. Colorization draws random bytes; the candidates themselves are a deterministic function of the colorized input.
  • Works on stored checksums. A comparison of a stored checksum field with a computed value has the stored field in the input, so the step writes the computed value there.

Variants and improvements

  • Nested checksums. A magic value behind a checksum is harder: writing the magic value changes the checksum, and the run fails before the new comparison. The paper detects comparisons that look like checksums, patches them out of the program during fuzzing, and repairs the checksums in the inputs it finds afterwards, again by input-to-state replacement.
  • Comparison logging in common fuzzers. Later fuzzers adopted the idea. AFL++ calls its version CmpLog. libFuzzer keeps a table of recent comparison operands and uses them as dictionary entries for mutation.
  • Splitting comparisons. Another approach compiles a comparison of 4 bytes into four comparisons of 1 byte, so that coverage rewards each correct byte. This needs no logging, but costs about 4⋅2564 \cdot 256 tries for 4 bytes instead of one run.
  • Solvers. Hybrid fuzzing calls concolic testing when the fuzzer is stuck. It handles transformed values that input-to-state correspondence cannot, at a much higher cost per input.

When to use it

Use it in a greybox fuzzer for parsers of binary formats and protocols, where magic values, version fields, lengths and stored checksums guard the interesting code. Use it when the target is a binary without source code, since it needs only the operands of comparisons. Use a solver-based method for comparisons with values that the program computes from the input in a nontrivial way.

Pitfalls

  • Spurious matches. Without colorization, an operand such as 0 or "AAAA" occurs at many positions of a seed, and most candidates are wrong.
  • Paths that read every byte. If every byte changes the path, colorization replaces nothing. The method still works, but with more candidates.
  • Bug counts on synthetic suites. The paper reports that it finds more bugs on LAVA-M than the suite lists, and 65 new bugs with 16 CVEs in real programs. These are measurements on the targets and the time budgets of the paper. Klees et al. (CCS 2018) explain why synthetic suites and short runs make comparisons of fuzzers weak.
  • Nondeterministic targets. A target whose path changes from run to run makes colorization reject every change.

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.

input_to_state_correspondence.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/input-to-state-correspondence/. The authors are listed in prov/RZ5788.jsonl.
"""Input-to-state correspondence, after Redqueen (Aschermann et al., NDSS 2019).

Many hard branches of a parser compare a value that was copied from the
input, perhaps with another byte order or width, against a constant or a
value that the program computed. If the run logs the two operands of every
comparison, the fuzzer can look for one operand in the input and write the
other operand in its place. This solves magic bytes and stored checksums
without symbolic execution.

The target is a Python callable target(x, t) on bytes that reports each
comparison to the tracer t, by t.cmp(site, a, b, width) for integers of
width bytes or t.cmp_bytes(site, a, b) for byte strings. Both return a == b.
The target may raise an exception, which counts as a crash. The tests use
small functions written for the purpose; nothing here runs a real program.

The colorization schedule, the list of encodings and the budget are design
choices, as in the paper, not theorems.
"""

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

ENDIANS = ("little", "big")
WIDTHS = (1, 2, 4, 8)


class Tracer:
    """Records the comparisons of one run and the path as (site, outcome) pairs."""

    def __init__(self) -> None:
        self.comparisons: list[tuple] = []
        self.path: list[tuple[int, bool]] = []

    def cmp(self, site: int, a: int, b: int, width: int) -> bool:
        self.comparisons.append(("int", a, b, width))
        self.path.append((site, a == b))
        return a == b

    def cmp_bytes(self, site: int, a: bytes, b: bytes) -> bool:
        self.comparisons.append(("bytes", bytes(a), bytes(b), len(a)))
        self.path.append((site, a == b))
        return a == b


Target = Callable[[bytes, Tracer], None]


@dataclass
class Run:
    path: tuple
    comparisons: list
    crashed: bool


def run(target: Target, x: bytes) -> Run:
    """Run the target once on x and return its path, comparisons and crash flag."""
    t = Tracer()
    crashed = False
    try:
        target(x, t)
    except Exception:
        crashed = True
    return Run(tuple(t.path), t.comparisons, crashed)


def colorize(target: Target, x: bytes, rng: random.Random, budget: int) -> tuple[bytes, int]:
    """Replace as many bytes of x as possible by random bytes without changing the path.

    Returns the new input and the number of runs used, at most budget. Each
    range is first tried whole; a range that changes the path is split in two.
    Cost O(n) runs for an input of n bytes when budget >= 2n.
    """
    h = run(target, x).path  # @line L9
    used = 1
    x = bytearray(x)
    ranges = [(0, len(x))] if x else []
    while ranges and used < budget:  # @line L10
        ranges.sort(key=lambda r: r[1] - r[0])
        i, j = ranges.pop()  # @line L11
        y = bytearray(x)
        for k in range(i, j):
            y[k] = rng.randrange(256)
        used += 1
        if run(target, bytes(y)).path == h:  # @line L12
            x = y
        elif j - i > 1:  # @line L13
            mid = (i + j) // 2
            ranges.append((i, mid))
            ranges.append((mid, j))
    return bytes(x), used  # @line L14


def encodings(a, b, kind: str, width: int) -> list[tuple[bytes, bytes]]:
    """The (pattern, replacement) pairs for the comparison of a with b.

    Integers are tried as little and big endian at their own width and at
    every smaller width that holds both values (the input field may be
    narrower than the comparison). Byte strings are tried as they are.
    """
    if kind == "bytes":
        return [(a, b)] if a != b and len(a) > 0 else []
    out = []
    for w in WIDTHS:
        if w > width or a >= 256 ** w or b >= 256 ** w or a < 0 or b < 0:
            continue
        for e in ENDIANS:
            pair = (a.to_bytes(w, e), b.to_bytes(w, e))
            if pair[0] != pair[1] and pair not in out:
                out.append(pair)
    return out


def occurrences(x: bytes, pattern: bytes) -> list[int]:
    """Every position i with x[i : i + len(pattern)] == pattern, overlaps included."""
    out = []
    i = x.find(pattern)
    while i >= 0:
        out.append(i)
        i = x.find(pattern, i + 1)
    return out


def candidates(x: bytes, comparisons: list) -> list[bytes]:
    """The inputs made by writing one operand where the other occurs in x.

    Cost O(c e n^2) for c comparisons, e encodings each and n bytes, since
    each of up to n positions per pattern gives a copy of x.
    """
    out: list[bytes] = []
    seen = {x}
    for kind, a, b, width in comparisons:  # @line L4
        for u, v in ((a, b), (b, a)):
            for pat, rep in encodings(u, v, kind, width):
                for i in occurrences(x, pat):  # @line L5
                    y = x[:i] + rep + x[i + len(pat):]  # @line L6
                    if y not in seen:
                        seen.add(y)
                        out.append(y)
    return out


def input_to_state(target: Target, x: bytes, rng: random.Random, budget: int = 64) -> tuple[list[bytes], int]:
    """One step of INPUT-TO-STATE on input x.

    Returns the candidate inputs and the number of runs used. Precondition:
    the target is deterministic. Cost O(n) runs for colorization and O(c e n)
    candidates for c comparisons on the trace.
    """
    xc, used = colorize(target, x, rng, budget)  # @line L1
    trace = run(target, xc).comparisons  # @line L2
    used += 1
    ys = candidates(xc, trace)  # @line L3
    return ys, used


@dataclass
class FuzzResult:
    corpus: list[bytes] = field(default_factory=list)
    crashes: list[bytes] = field(default_factory=list)
    runs: int = 0


def fuzz(target: Target, seed: bytes, rng: random.Random, max_runs: int = 10000, colorize_budget: int = 64) -> FuzzResult:
    """A small fuzzing loop that uses only input-to-state candidates.

    Every candidate that covers a (site, outcome) pair not seen before goes
    to the queue; a candidate that crashes the target is reported. The loop
    stops at the first crash, when the queue is empty, or after max_runs runs.
    """
    res = FuzzResult(corpus=[seed])
    first = run(target, seed)
    res.runs = 1
    if first.crashed:
        res.crashes.append(seed)
        return res
    covered = set(first.path)
    queue = [seed]
    while queue and res.runs < max_runs:
        x = queue.pop(0)
        ys, used = input_to_state(target, x, rng, colorize_budget)
        res.runs += used
        for y in ys:
            if res.runs >= max_runs:
                break
            r = run(target, y)
            res.runs += 1
            if r.crashed:
                res.crashes.append(y)
                return res
            new = set(r.path) - covered
            if new:  # @line L7
                covered |= new
                queue.append(y)
                res.corpus.append(y)
    return res  # @line L8
test_input_to_state_correspondence.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/input-to-state-correspondence/. The authors are listed in prov/RZ5788.jsonl.
import random

from input_to_state_correspondence import (
    candidates,
    colorize,
    encodings,
    fuzz,
    input_to_state,
    occurrences,
    run,
)


class Found(Exception):
    pass


def page_target(x, t):
    """The target of the page: a made-up header, a version field and a tag."""
    if len(x) < 8:
        return
    if t.cmp(1, int.from_bytes(x[0:4], "little"), 0x31594F54, 4):  # the bytes "TOY1"
        if t.cmp(2, int.from_bytes(x[4:6], "big"), 0x0102, 2):
            if t.cmp_bytes(3, x[6:8], b"OK"):
                raise Found()


def test_page_example():
    seed = b"AAAAAAAA"
    # Without colorization, "AAAA" occurs at 5 positions and reads the same
    # in both byte orders, so there are 10 candidates and only one is right.
    trace = run(page_target, seed).comparisons
    assert trace == [("int", 0x41414141, 0x31594F54, 4)]
    ys = candidates(seed, trace)
    assert len(ys) == 10
    assert b"TOY1AAAA" in ys and b"1YOTAAAA" in ys
    assert sum(run(page_target, y).path != run(page_target, seed).path for y in ys) == 1
    # With colorization, the random bytes occur only where they came from.
    xc, used = colorize(page_target, seed, random.Random(1), 64)
    assert xc == bytes.fromhex("4420823cfde6f1c2") and used == 2
    rng = random.Random(1)
    ys, used = input_to_state(page_target, seed, rng)
    assert ys == [b"TOY1" + bytes.fromhex("fde6f1c2")]
    assert used == 3  # two runs of colorization and one logging run
    res = fuzz(page_target, seed, random.Random(1))
    assert len(res.crashes) == 1
    crash = res.crashes[0]
    assert crash[:4] == b"TOY1" and crash[4:6] == b"\x01\x02" and crash[6:8] == b"OK"
    assert len(res.corpus) == 3  # the seed and two inputs with new coverage
    assert res.runs == 33


def test_occurrences_against_slicing():
    rng = random.Random(7)
    for _ in range(600):
        n = rng.randint(0, 12)
        x = bytes(rng.randrange(3) for _ in range(n))
        pat = bytes(rng.randrange(3) for _ in range(rng.randint(1, 3)))
        naive = [i for i in range(n - len(pat) + 1) if x[i:i + len(pat)] == pat]
        assert occurrences(x, pat) == naive


def test_encodings():
    assert encodings(0x0102, 0x0304, "int", 2) == [
        (b"\x02\x01", b"\x04\x03"),
        (b"\x01\x02", b"\x03\x04"),
    ]
    # A one-byte field compared at width 4 is found at width 1.
    assert (b"\x41", b"\x42") in encodings(0x41, 0x42, "int", 4)
    assert encodings(5, 5, "int", 4) == []
    assert encodings(b"ab", b"cd", "bytes", 2) == [(b"ab", b"cd")]


def random_checks(rng, n, k):
    """k nested equality checks on disjoint fields of an input of n bytes."""
    checks = []
    free = list(range(n))
    for _ in range(k):
        w = rng.choice([1, 2, 4])
        starts = [i for i in free if all(j in free for j in range(i, i + w)) and i + w <= n]
        if not starts:
            break
        i = rng.choice(starts)
        for j in range(i, i + w):
            free.remove(j)
        kind = rng.choice(["little", "big", "bytes"])
        const = bytes(rng.randrange(256) for _ in range(w))
        checks.append((i, w, kind, const))
    return checks


def make_target(checks):
    def target(x, t):
        for site, (i, w, kind, const) in enumerate(checks):
            if len(x) < i + w:
                return
            field_ = x[i:i + w]
            if kind == "bytes":
                ok = t.cmp_bytes(site, field_, const)
            else:
                ok = t.cmp(site, int.from_bytes(field_, kind), int.from_bytes(const, kind), w)
            if not ok:
                return
        raise Found()
    return target


def satisfies(checks, x):
    """The independent oracle: does x pass every check, read directly from the spec?"""
    return all(x[i:i + w] == const for i, w, _, const in checks)


def test_random_colorize_keeps_path():
    rng = random.Random(11)
    for _ in range(500):
        n = rng.randint(1, 10)
        checks = random_checks(rng, n, rng.randint(0, 3))
        target = make_target(checks)
        x = bytes(rng.randrange(256) for _ in range(n))
        xc, used = colorize(target, x, rng, 64)
        assert len(xc) == n and used <= 64
        assert run(target, xc).path == run(target, x).path


def test_random_one_candidate_passes_the_next_check():
    """For an input that reaches check j, some candidate passes check j."""
    rng = random.Random(12)
    solved = 0
    for _ in range(600):
        n = rng.randint(2, 10)
        checks = random_checks(rng, n, rng.randint(1, 3))
        target = make_target(checks)
        x = bytearray(rng.randrange(256) for _ in range(n))
        if not checks:
            continue
        j = rng.randrange(len(checks))
        for i, w, _, const in checks[:j]:
            x[i:i + w] = const
        x = bytes(x)
        if satisfies(checks[: j + 1], x):
            continue
        ys, _ = input_to_state(target, x, rng)
        assert any(satisfies(checks[: j + 1], y) for y in ys)
        solved += 1
    assert solved > 500


def test_random_full_loop_reaches_the_planted_crash():
    rng = random.Random(13)
    for _ in range(500):
        n = rng.randint(4, 10)
        checks = random_checks(rng, n, rng.randint(1, 3))
        target = make_target(checks)
        seed = bytes(rng.randrange(256) for _ in range(n))
        res = fuzz(target, seed, rng, max_runs=3000)
        assert len(res.crashes) == 1
        assert satisfies(checks, res.crashes[0])


def test_no_correspondence_no_solution():
    """If the program transforms the field before the comparison, nothing in the input matches."""
    def target(x, t):
        if len(x) >= 2 and t.cmp(1, int.from_bytes(x[0:2], "little") ^ 0x5A5A, 0x1234, 2):
            raise Found()

    rng = random.Random(3)
    res = fuzz(target, bytes([1, 2, 3, 4]), rng, max_runs=500)
    assert res.crashes == []


def test_stored_checksum_is_repaired():
    """A stored checksum field is an operand that occurs in the input."""
    def target(x, t):
        if len(x) < 6:
            return
        stored = int.from_bytes(x[0:2], "big")
        computed = sum(x[2:]) % 65536
        if t.cmp(1, stored, computed, 2):
            raise Found()

    res = fuzz(target, bytes([0, 0, 9, 8, 7, 6]), random.Random(5), max_runs=200)
    assert res.crashes and int.from_bytes(res.crashes[0][:2], "big") == sum(res.crashes[0][2:])

History

Hard comparisons were a main weakness of greybox fuzzers such as AFL in the mid-2010s. Driller (Stephens et al., NDSS 2016) called concolic execution when the fuzzer got stuck. VUzzer (NDSS 2017) and Angora (IEEE S&P 2018) used taint tracking to find the bytes that reach a comparison. Aschermann, Schumilo, Blazytko, Gawlik and Holz (NDSS 2019) showed with their fuzzer Redqueen that in many programs the operand is a direct copy of input bytes, so a search of the input replaces the taint engine. Their abstract reports that it handled magic bytes and nested checksums and found 65 new bugs, with 16 CVEs. The idea is now a standard feature of greybox fuzzers.

References

  1. Cornelius Aschermann, Sergej Schumilo, Tim Blazytko, Robert Gawlik and Thorsten Holz, REDQUEEN, fuzzing with input-to-state correspondence, NDSS 2019, the abstract and the description of the method (comparison logging, colorization, input patching and the handling of checksums)
  2. George Klees, Andrew Ruef, Benji Cooper, Shiyi Wei and Michael Hicks, Evaluating fuzz testing, CCS 2018, the discussion of synthetic bug suites such as LAVA-M and of what a fair comparison of fuzzers needs

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
  • at least three sources
  • a scene preset for the example