Algorithm Search⌘K

Algorithmadvanced

Vulnerability signature generation

Also called Brumley vulnerability signatures.

Builds a filter that matches every input that reaches a known vulnerability, as a regular expression, a symbolic constraint or a Turing machine.

Time
O(2^b n L^2 s^3) worst
Space
O(2^b n L) extra
Where
L = the largest input length; b = the number of branches; n = the number of instructions of the program; s = the size of the alphabet
Properties
deterministicofflinenot randomizedrecursive
Origin
David Brumley, James Newsome, Dawn Song, Hao Wang, Somesh Jha, 2006

A vulnerability signature is a filter that recognizes the inputs that exploit one known vulnerability of a program, whatever their form. An exploit-based signature, such as a byte pattern taken from captured attack traffic, matches the exploits that look like the sample and misses variants that reach the same flaw in another way. Brumley, Newsome, Song, Wang and Jha (IEEE S&P 2006) proposed to describe instead the language of all inputs that make the program reach the vulnerable point with the vulnerability condition true, and to compute it from the program and one sample exploit. They studied three representations: a Turing machine (the program itself, cut at the point), a symbolic constraint over the input bytes, and a regular expression. They trade matching cost against precision. The costs on this page are in the word-RAM model.

In plain words

Suppose a server has a bug: if a message says "copy 9 bytes" into a space of 4 bytes, it breaks. A patch takes time to ship, so in the meantime an administrator wants a filter in front of the server that drops bad messages.

A filter copied from one attack message catches only that message and close copies. Change one byte that the server does not care about, and the filter fails.

A vulnerability signature looks at the server, not at the attack. It asks "which messages make the server reach the copy with a length above 4?" The safest answer is to run the parser of the server up to the copy, but that can be slow. A shorter answer is a list of conditions on the bytes, or a pattern. Shorter answers are faster to check but can be too wide or too narrow.

The problem

The input is a program PP, a vulnerability given as a point in PP with a condition on the state there, and a sample input xx that exploits it. Let XX be the set of the inputs whose run reaches the point with the condition true. The output is a predicate that a filter can test on each input. It has a false positive on a harmless input that it matches, and a false negative on an exploit in XX that it misses. An exact signature matches XX exactly.

For programs with loops, an exact signature must in general decide whether a run reaches the point, which is undecidable by Rice's theorem and the halting problem; a Turing machine signature that just runs the program may not stop. The program of this page is a toy parser whose jumps go forward only, so every run ends and all four signatures can be computed and compared.

The algorithm

The toy program reads bytes, adds them, compares them with constants and jumps forward. A path condition is the conjunction of the atoms that a run along one path satisfies: "the input is longer than ii" for each load of byte ii, the outcome of each branch, and the vulnerability condition at the end.

  1. VULN-SIGNATURES(P, x, Σ, L) ▷ x: one sample exploit; inputs over Σ of length at most L
  2. 1TM ← the program P cut at the vulnerability point: run it on y and return the condition there
  3. 2φ ← the path condition of the run of P on x: the load guards, the branch outcomes and the condition at the point
  4. 3SINGLE ← the inputs that satisfy φ
  5. 4Φ ← the disjunction of the path conditions of all paths from the start to the point, by a depth-first search that forks at each branch
  6. 5MULTIPLE ← the inputs that satisfy Φ
  7. 6for each disjunct ψ of Φ and each length n ≤ L do
  8. 7fix the length to n in ψ; skip ψ for this n if an atom without bytes is false
  9. 8D_p ← Σ for each p < n; remove the values without support in an atom on one or two bytes, until nothing changes
  10. 9if no D_p is empty then add the alternative D_0 D_1 ... D_(n-1) to R
  11. 10return TM, SINGLE, MULTIPLE and the regular expression R, the alternation of its alternatives

Line L1 is exact but costs a run of the parser per input. Line L2 is a concolic run of the sample, as in symbolic execution; a real system first slices the program to the instructions that the point depends on, to keep the condition small. Line L4 enumerates paths, which can be exponential in the number of branches. Lines L6 to L9 turn each disjunct into a list of character classes, one per position, with arc consistency; an atom that relates two bytes, such as a sum of two length fields, cannot be expressed by classes, so the classes are wider than the solutions.

Example

The toy parser reads a message type in byte 0. Type 1 has one length field in byte 1 and a check that rejects lengths above 6, which is the wrong bound. Type 2 has two length fields in bytes 1 and 2 and no check. Both types then copy the total length into a buffer of 4 bytes: the vulnerability condition is "length > 4". The alphabet is {0,…,7}\{0, \ldots, 7\} and the inputs have length at most 3, which gives 585 inputs. The sample exploit is the input 1, 6.

signature what it is inputs matched false positives false negatives
exploits the set XX, by brute force 67
Turing machine run the parser up to the copy 67 0 0
single path length > 0, length > 1, y0=1y_0 = 1, y1≤6y_1 \le 6, y1>4y_1 > 4 18 0 49
multiple path the single path, or y0≠1y_0 \ne 1, y0=2y_0 = 2, length > 2, y1+y2>4y_1 + y_2 > 4 67 0 0
regular expression [1][5 6][1][5\,6], [1][5 6]Σ[1][5\,6]\Sigma, or [2]ΣΣ[2]\Sigma\Sigma 82 15 0

The single-path signature describes only type 1, since the sample is of type 1, and misses all 49 exploits of type 2. In the regular expression, every value of y1y_1 has some y2y_2 with y1+y2>4y_1 + y_2 > 4, so arc consistency removes nothing, and the 15 harmless messages of type 2 with y1+y2≤4y_1 + y_2 \le 4 match. The tests of the implementation check these numbers.

Correctness

Along a path, each register holds a linear form in the bytes, the length and a constant, and for an input that follows the path, its value is the form evaluated at the input, by induction on the instructions. So an input satisfies the path condition of a path exactly when its run follows that path and the condition at the end holds. Hence the single-path signature has no false positives and matches the sample, and the multiple-path signature, which covers every path to the point, is exact on programs whose paths it can enumerate. Arc consistency only removes a value when no value of the other byte satisfies an atom with it, so the bytes of an exploit are never removed, and the regular expression has no false negatives up to the length bound; when every atom mentions at most one byte, it is exact. The full proof is in the proof file, and the tests compare all four signatures with brute force over all 85 inputs of length at most 3 over four symbols, on 500 random programs.

Proof: Correctness of vulnerability signature generationfull

We prove the claims of the Correctness section for the four signatures of the page (lines L1 to L10). The program PP is a list of instructions in which every jump goes forward, so every run ends after at most ∣P∣|P| steps. An input yy is a finite list of symbols of an alphabet Σ\Sigma. The run of PP on yy exploits the vulnerability if it reaches a vuln instruction (r,op,k)(r, \mathit{op}, k) and ropkr \mathbin{op} k holds there; the run stops at the first vuln instruction. Let XX be the set of the inputs that exploit it.

A path is a sequence of instructions from the start that a run could follow: at a branch it goes to the target or to the next instruction, at a load of byte ii it requires i<∣y∣i < |y|, and it ends at a vuln instruction. Symbolic execution along a path keeps for each register a linear form in the bytes yiy_i, the length ∣y∣|y| and a constant, and collects atoms: ∣y∣>i|y| > i for each load, the condition or its negation for each branch, and the condition of the vuln instruction at the end.

Claim 1 (the Turing machine signature). RUN(P,y)(P, y) returns true if and only if y∈Xy \in X.

Proof. RUN executes the instructions of PP on yy as the semantics defines them, returns false at a halt, at a failed load or at the end of the program, and returns the condition at the first vuln instruction. □\square

Lemma 2 (symbolic evaluation). Let π\pi be a path, and let yy be an input whose run follows π\pi up to an instruction tt. Then before tt, every register form of the symbolic execution of π\pi, evaluated at yy, equals the value of the register in the run on yy.

Proof. By induction on the number of instructions before tt. All registers start at 0 in both. A len, load or const instruction sets the register to ∣y∣|y|, yiy_i or kk, and the form to the same quantity. For addi and add, the form is the sum of the forms of the operands, and the value is the sum of their values, which are equal by the hypothesis. Branches, jumps and vuln instructions change no register. □\square

Claim 3 (a run satisfies the atoms of its path). Let φπ\varphi_\pi be the conjunction of the atoms of a path π\pi that ends at a vuln instruction. Then yy satisfies φπ\varphi_\pi if and only if the run on yy follows π\pi and the condition at the end holds.

Proof. Let yy satisfy φπ\varphi_\pi. We show by induction on tt that the run on yy follows π\pi up to its tt-th instruction. At a load of byte ii, the atom ∣y∣>i|y| > i holds, so the load does not halt, and the run goes to the next instruction as π\pi does. At a branch, by Lemma 2 the atom of π\pi evaluated at yy is the branch condition evaluated in the run, so the run takes the same direction as π\pi. Other instructions have one successor. At the end, the last atom is the vuln condition, which holds in the run by Lemma 2. For the converse, if the run follows π\pi, every load atom holds because the loads did not halt, every branch atom holds by Lemma 2 because the run took the direction of π\pi, and the last atom holds because the condition holds. □\square

Claim 4 (the single-path signature). For a sample x∈Xx \in X, lines L2 and L3 return φπ\varphi_\pi for the path π\pi of the run on xx. Every input that satisfies it is in XX, and xx satisfies it.

Proof. Lines L2 and L3 follow the run on xx concretely, and at each branch record the atom of the direction that xx takes, so they compute exactly the atoms of the path of xx, which ends at a vuln instruction with a true condition because x∈Xx \in X. By Claim 3, an input satisfies φπ\varphi_\pi if and only if it follows π\pi and the condition holds, which implies that it is in XX, and xx follows π\pi. □\square

The converse fails: an exploit that takes another path to the same point does not satisfy φπ\varphi_\pi. So the single-path signature has no false positives and can have false negatives.

Claim 5 (the multiple-path signature). Lines L4 and L5 return the list of φπ\varphi_\pi over all paths π\pi that end at a vuln instruction, and y∈Xy \in X if and only if yy satisfies one of them.

Proof. EXPLORE follows the instructions with forms and atoms. At each branch it recurses into the target with the atom of the condition, and goes on to the next instruction with the negated atom; at each load it adds the atom ∣y∣>i|y| > i and goes on; it stops at a halt and at the end of the program, and it records the atoms at a vuln instruction. Since jumps go forward, the recursion ends, and by induction on the position it visits each path once. If y∈Xy \in X, its run follows some path π\pi to a vuln instruction with a true condition, so yy satisfies φπ\varphi_\pi by Claim 3. If yy satisfies some φπ\varphi_\pi, then y∈Xy \in X by Claim 3. □\square

Claim 6 (the regular expression signature). Let RR be the result of lines L6 to L10 for the list of Claim 5 and a bound LL. Every y∈Xy \in X with ∣y∣≤L|y| \le L matches RR. If every atom, after the length is fixed, mentions at most one byte, then the inputs of length at most LL that match RR are exactly those in XX.

Proof. Let y∈Xy \in X, ∣y∣=n≤L|y| = n \le L, and let φπ\varphi_\pi be a disjunct that yy satisfies. With the length fixed to nn, line L7 evaluates the atoms without bytes, which hold for yy, and no atom mentions a byte at a position ≥n\ge n, because the load atom before it would require n>in > i; so the alternative for (π,n)(\pi, n) is not skipped there. Line L8 starts with Dp=Σ∋ypD_p = \Sigma \ni y_p. We show that ypy_p stays in DpD_p. A value vv is removed from DpD_p only if no values of the other position of an atom, in their current domains, satisfy the atom together with vv. If yq∈Dqy_q \in D_q for all qq before the step, then ypy_p has the support yqy_q, because yy satisfies the atom; so ypy_p is not removed. Hence all domains are nonempty, line L9 adds the alternative D0⋯Dn−1D_0 \cdots D_{n-1}, and yy matches it.

For the second statement, let yy of length nn match the alternative of (π,n)(\pi, n), so yp∈Dpy_p \in D_p for all pp. Line L7 kept the alternative, so every atom without bytes holds. Every other atom mentions one byte pp, and line L8 removed from DpD_p every value that does not satisfy it, so ypy_p satisfies it. So yy satisfies φπ\varphi_\pi, and y∈Xy \in X by Claim 5. □\square

With atoms over two bytes, arc consistency keeps values that have support for each atom separately, and the product of the domains can contain inputs that satisfy no disjunct: the example of the page has such false positives. Atoms over three or more bytes are not used for pruning at all.

Claim 7 (cost). For a program of nn instructions with bb branches, an alphabet of ss symbols and the bound LL, line L1 costs O(n)O(n) per input; lines L2 and L3 cost O(nL)O(n L), as do the test of one conjunction; lines L4 and L5 cost O(2bnL)O(2^b n L); and lines L6 to L10 cost O(2bnL2s3)O(2^b n L^2 s^3).

Proof. A run executes each instruction at most once. A linear form has at most LL byte terms, so one symbolic step and one atom test cost O(L)O(L). EXPLORE has at most 2b2^b leaves and at most nn steps per path. For one disjunct and one length, line L7 costs O(nL)O(n L), and line L8 runs passes over at most nn atoms on domains of size ss. A pass revises each atom in O(s2)O(s^2), so it costs O(ns2)O(n s^2), and each pass but the last removes at least one of the at most LsL s values, so there are O(Ls)O(L s) passes. That is O(nLs3)O(n L s^3) per disjunct and length, and there are at most 2b2^b disjuncts and L+1L + 1 lengths. □\square

Complexity

The Turing machine signature costs O(n)O(n) per input, a run of the loop-free parser; in general it costs a run of the program up to the point, which may not end. The single-path signature has O(n)O(n) atoms with forms of at most LL terms, so building it and testing an input cost O(nL)O(nL). The multiple-path signature has up to 2b2^b disjuncts, so building and testing it cost O(2bnL)O(2^b n L). For the regular expression, each disjunct and length needs arc consistency, with O(Ls)O(L s) passes of O(ns2)O(n s^2) each, which gives O(2bnL2s3)O(2^b n L^2 s^3) in total, and the expression can have 2b(L+1)2^b (L + 1) alternatives. Matching it with a deterministic automaton is linear in the input, which is why filters prefer this form. The space is O(2bnL)O(2^b n L) for the disjuncts.

Properties

  • Vulnerability-based. The signature depends on the program and the flaw, not on the bytes of one attack, so polymorphic variants that reach the flaw are caught by the exact forms.
  • Ordered by precision. Turing machine and multiple path: exact on loop-free programs. Single path: no false positives. Regular expression from character classes: no false negatives.
  • Ordered by cost. The regular expression is the cheapest to match and the Turing machine the most expensive.
  • Needs the program. The method needs the binary or the source of the vulnerable program and a way to execute it symbolically.

Variants and improvements

  • Slicing first. Cut the program to the instructions that the vulnerability point depends on, with program slicing, so that the Turing machine signature runs only the relevant parser code and the path conditions are shorter.
  • Solvers for matching. Test a symbolic signature with an SMT solver or by direct evaluation, as here; direct evaluation suffices because the input is concrete.
  • Exploration beyond one sample. Explore other paths to the point with symbolic execution or fuzzing, and add them to the disjunction until a time budget ends; the signature then has fewer false negatives without the full cost of all paths.
  • Protocol-level filters. Shield (Wang et al., SIGCOMM 2004) wrote vulnerability-driven filters by hand against a protocol specification. Vigilante and Bouncer (Costa et al., 2005 and 2007) generated filters from the program automatically and checked them on the exploit.
  • Exploit-based signatures. Polygraph (Newsome, Karp and Song, 2005) learns token signatures from many samples of a worm. It needs no program but can be evaded by a worm that changes its invariant bytes, which motivated vulnerability-based signatures.

When to use it

Use vulnerability signatures to protect a known flaw between the discovery and the deployment of a patch, at a network filter or inside the program as an input check. They suit flaws whose trigger is a property of the input that a parser computes, such as a length field or a nesting depth, and programs whose relevant code can be executed symbolically. When the patch can be deployed quickly, patch. When no program is available, only exploit-based signatures apply, as in misuse detection.

Pitfalls

  • Signatures that are too wide. A regular expression can drop valid traffic, as the 15 false positives of the example show. Measure the false positive rate on real, harmless traffic before blocking.
  • Signatures that are too narrow. A single-path signature misses exploits that take another path. Use it as a first response, and extend it.
  • The filter parses differently. A filter that parses messages differently from the program, for example in how it splits packets or decodes fields, can be bypassed. Base the signature on the program's own parser.
  • Cost on the critical path. A Turing machine signature runs part of the parser for every message. Check that the filter keeps up with the traffic.
  • Generated filters leak the flaw. A published signature describes the trigger of the vulnerability, which helps attackers as much as an unprotected patch. Distribute it with the same care as the patch; see patch-based exploit generation.

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.

vulnerability_signature_generation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vulnerability-signature-generation/. The authors are listed in prov/6GQ6TV.jsonl.
"""Vulnerability signatures for a toy loop-free input parser, in four representations.

The program is a list of instructions over integer registers and the input
bytes. Jumps go forward only, so every run ends. The vulnerability is the
instruction ("vuln", r, op, k): an input exploits it when a run reaches the
instruction and r op k holds there, for example a copy length larger than a
buffer. The run stops at the first vuln instruction it reaches.

Instructions:
  ("len", r)               r <- the length of the input
  ("load", r, i)           r <- byte i; the run halts safely if i >= length
  ("const", r, k)          r <- k
  ("addi", r, s, k)        r <- s + k
  ("add", r, s, t)         r <- s + t
  ("br", r, op, k, j)      if r op k then jump to instruction j > the current one
  ("jmp", j)               jump to instruction j > the current one
  ("vuln", r, op, k)       the vulnerability point and its condition
  ("halt",)

The signatures, after Brumley, Newsome, Song, Wang and Jha (2006):
  * the Turing machine signature runs the program up to the vulnerability; it is exact;
  * the single-path symbolic signature is the path condition of one sample
    exploit; it has no false positives and can have false negatives;
  * the multiple-path symbolic signature is the disjunction over all paths
    that reach the point; on loop-free programs it is exact;
  * the regular expression signature over-approximates each disjunct by
    character classes; it has no false negatives and can have false positives.

The inputs here are small integer lists over a given alphabet, not network
traffic. The code only evaluates programs that the tests build.
"""

import operator
import re
from typing import Callable, Optional, Sequence

OPS = ("==", "!=", "<", "<=", ">", ">=")
NEG = {"==": "!=", "!=": "==", "<": ">=", "<=": ">", ">": "<=", ">=": "<"}

# A linear form: (((position, coefficient), ...), coefficient of the length, constant).
Lin = tuple
# An atom: (linear form, op, k), true when the form op k holds.
Atom = tuple


_CMP = {"==": operator.eq, "!=": operator.ne, "<": operator.lt, "<=": operator.le, ">": operator.gt, ">=": operator.ge}


def holds(v: int, op: str, k: int) -> bool:
    return _CMP[op](v, k)


def lin_const(k: int) -> Lin:
    return ((), 0, k)


def lin_add(a: Lin, b: Lin) -> Lin:
    terms = dict(a[0])
    for p, c in b[0]:
        terms[p] = terms.get(p, 0) + c
    return (tuple(sorted((p, c) for p, c in terms.items() if c)), a[1] + b[1], a[2] + b[2])


def lin_eval(f: Lin, x: Sequence[int]) -> int:
    return sum(c * x[p] for p, c in f[0]) + f[1] * len(x) + f[2]


def satisfies(atoms: Sequence[Atom], x: Sequence[int]) -> bool:
    """True if x satisfies every atom; positions beyond the input make it false."""
    for f, op, k in atoms:
        if any(p >= len(x) for p, _ in f[0]) or not holds(lin_eval(f, x), op, k):
            return False
    return True


def run(program: Sequence[tuple], x: Sequence[int]) -> bool:
    """The Turing machine signature: True if the run on x reaches the vuln point with its condition true.

    Cost O(|program|), since jumps go forward.
    """
    regs: dict[int, int] = {}
    pc = 0
    while pc < len(program):  # @line L1
        ins = program[pc]
        op = ins[0]
        if op == "len":
            regs[ins[1]] = len(x)
        elif op == "load":
            if ins[2] >= len(x):
                return False
            regs[ins[1]] = x[ins[2]]
        elif op == "const":
            regs[ins[1]] = ins[2]
        elif op == "addi":
            regs[ins[1]] = regs.get(ins[2], 0) + ins[3]
        elif op == "add":
            regs[ins[1]] = regs.get(ins[2], 0) + regs.get(ins[3], 0)
        elif op == "br":
            if holds(regs.get(ins[1], 0), ins[2], ins[3]):
                pc = ins[4]
                continue
        elif op == "jmp":
            pc = ins[1]
            continue
        elif op == "vuln":
            return holds(regs.get(ins[1], 0), ins[2], ins[3])
        elif op == "halt":
            return False
        pc += 1
    return False


def _step_symbolic(ins: tuple, regs: dict[int, Lin]) -> None:
    op = ins[0]
    if op == "len":
        regs[ins[1]] = ((), 1, 0)
    elif op == "load":
        regs[ins[1]] = (((ins[2], 1),), 0, 0)
    elif op == "const":
        regs[ins[1]] = lin_const(ins[2])
    elif op == "addi":
        regs[ins[1]] = lin_add(regs.get(ins[2], lin_const(0)), lin_const(ins[3]))
    elif op == "add":
        regs[ins[1]] = lin_add(regs.get(ins[2], lin_const(0)), regs.get(ins[3], lin_const(0)))


def single_path_signature(program: Sequence[tuple], sample: Sequence[int]) -> list[Atom]:
    """The path condition of one exploit, with the vulnerability condition. Cost O(|program| |sample|)."""
    regs: dict[int, Lin] = {}
    atoms: list[Atom] = []
    pc = 0
    if not run(program, sample):
        raise ValueError("the sample does not exploit the program")
    while True:  # @line L2
        ins = program[pc]
        if ins[0] == "load":
            atoms.append((((), 1, 0), ">", ins[2]))
        if ins[0] in ("len", "load", "const", "addi", "add"):
            _step_symbolic(ins, regs)
        elif ins[0] == "br":
            f = regs.get(ins[1], lin_const(0))
            taken = holds(lin_eval(f, sample), ins[2], ins[3])
            atoms.append((f, ins[2] if taken else NEG[ins[2]], ins[3]))
            if taken:
                pc = ins[4]
                continue
        elif ins[0] == "jmp":
            pc = ins[1]
            continue
        elif ins[0] == "vuln":
            atoms.append((regs.get(ins[1], lin_const(0)), ins[2], ins[3]))
            return atoms  # @line L3
        pc += 1


def multiple_path_signature(program: Sequence[tuple]) -> list[list[Atom]]:
    """The disjunction, over all paths from the start to the vuln point, of path condition and vuln condition.

    Depth-first search that forks at each branch. Cost O(2^b |program|) for b branches.
    """
    out: list[list[Atom]] = []

    def explore(pc: int, regs: dict[int, Lin], atoms: list[Atom]) -> None:
        while pc < len(program):  # @line L4
            ins = program[pc]
            if ins[0] == "load":
                atoms = atoms + [(((), 1, 0), ">", ins[2])]
            if ins[0] in ("len", "load", "const", "addi", "add"):
                _step_symbolic(ins, regs)
            elif ins[0] == "br":
                f = regs.get(ins[1], lin_const(0))
                explore(ins[4], dict(regs), atoms + [(f, ins[2], ins[3])])
                atoms = atoms + [(f, NEG[ins[2]], ins[3])]
            elif ins[0] == "jmp":
                pc = ins[1]
                continue
            elif ins[0] == "vuln":
                out.append(atoms + [(regs.get(ins[1], lin_const(0)), ins[2], ins[3])])
                return
            elif ins[0] == "halt":
                return
            pc += 1

    explore(0, {}, [])
    return out  # @line L5


def _byte_class(values: Sequence[int]) -> str:
    return "[" + "".join(re.escape(chr(v)) for v in sorted(values)) + "]"


def regex_signature(disjuncts: Sequence[Sequence[Atom]], alphabet: Sequence[int], max_len: int) -> Optional[re.Pattern]:
    """A regular expression over inputs of length at most max_len that matches every solution of the disjuncts.

    For each disjunct and length n, fix the length, then remove values
    without support from the per-position domains (arc consistency on atoms
    over one or two positions). Atoms over more positions are not used, which
    can only add matches. Returns None if no alternative is left.
    Cost O(2^b n L^2 s^3) for 2^b disjuncts of at most n atoms, lengths up to L and s symbols.
    """
    alts = []
    for atoms in disjuncts:
        for n in range(max_len + 1):  # @line L6
            rest = []
            ok = True
            for (terms, lc, c), op, k in atoms:  # @line L7
                if any(p >= n for p, _ in terms):
                    ok = False
                    break
                f = (terms, 0, c + lc * n)
                if not terms:
                    ok = ok and holds(f[2], op, k)
                elif len(terms) <= 2:
                    rest.append((f, op, k))
            if not ok:
                continue
            dom = [set(alphabet) for _ in range(n)]
            changed = True
            while changed:  # @line L8
                changed = False
                for (terms, _, c), op, k in rest:
                    if len(terms) == 1:
                        (p, a), = terms
                        keep = {v for v in dom[p] if holds(a * v + c, op, k)}
                        if keep != dom[p]:
                            dom[p], changed = keep, True
                    else:
                        (p, a), (q, b) = terms
                        keep_p = {v for v in dom[p] if any(holds(a * v + b * w + c, op, k) for w in dom[q])}
                        keep_q = {w for w in dom[q] if any(holds(a * v + b * w + c, op, k) for v in keep_p)}
                        if keep_p != dom[p] or keep_q != dom[q]:
                            dom[p], dom[q], changed = keep_p, keep_q, True
            if all(dom):
                alts.append("".join(_byte_class(d) for d in dom))  # @line L9
    if not alts:
        return None
    return re.compile("|".join("(?:" + a + ")" for a in alts), re.DOTALL)  # @line L10


def regex_matches(pattern: Optional[re.Pattern], x: Sequence[int]) -> bool:
    return pattern is not None and pattern.fullmatch("".join(map(chr, x))) is not None


def generate(program: Sequence[tuple], sample: Sequence[int], kind: str, alphabet: Sequence[int] = range(256), max_len: int = 16) -> Callable[[Sequence[int]], bool]:
    """Return a filter of the given kind: "turing", "single", "multiple" or "regex"."""
    if kind == "turing":
        return lambda y: run(program, y)
    if kind == "single":
        atoms = single_path_signature(program, sample)
        return lambda y: satisfies(atoms, y)
    disjuncts = multiple_path_signature(program)
    if kind == "multiple":
        return lambda y: any(satisfies(a, y) for a in disjuncts)
    pattern = regex_signature(disjuncts, alphabet, max_len)
    return lambda y: len(y) <= max_len and regex_matches(pattern, y)
test_vulnerability_signature_generation.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vulnerability-signature-generation/. The authors are listed in prov/6GQ6TV.jsonl.
import itertools
import operator
import random

import pytest

from vulnerability_signature_generation import (
    OPS,
    generate,
    multiple_path_signature,
    regex_signature,
    single_path_signature,
)

# The page example: byte 0 is a message type, then one or two length fields.
# The parser copies the total length into a buffer of 4 bytes.
PAGE = [
    ("load", 1, 0),
    ("load", 2, 1),
    ("br", 1, "==", 1, 5),
    ("br", 1, "==", 2, 8),
    ("halt",),
    ("br", 2, ">", 6, 11),  # a check with the wrong bound
    ("addi", 3, 2, 0),
    ("jmp", 10),
    ("load", 4, 2),
    ("add", 3, 2, 4),
    ("vuln", 3, ">", 4),
    ("halt",),
]


COMPARE = {"==": operator.eq, "!=": operator.ne, "<": operator.lt, "<=": operator.le, ">": operator.gt, ">=": operator.ge}


def all_inputs(alphabet, max_len):
    for n in range(max_len + 1):
        yield from (list(t) for t in itertools.product(alphabet, repeat=n))


def oracle(program, x):
    """An independent interpreter: follow the instructions with a register file per step."""
    def go(pc, regs):
        if pc >= len(program):
            return False
        ins = program[pc]
        kind, args = ins[0], ins[1:]
        val = lambda r: regs.get(r, 0)
        test = lambda v, op, k: COMPARE[op](v, k)
        if kind == "halt":
            return False
        if kind == "vuln":
            return test(val(args[0]), args[1], args[2])
        if kind == "jmp":
            return go(args[0], regs)
        if kind == "br":
            return go(args[3] if test(val(args[0]), args[1], args[2]) else pc + 1, regs)
        if kind == "load" and args[1] >= len(x):
            return False
        new = dict(regs)
        new[args[0]] = {"len": lambda: len(x), "load": lambda: x[args[1]], "const": lambda: args[1],
                        "addi": lambda: val(args[1]) + args[2], "add": lambda: val(args[1]) + val(args[2])}[kind]()
        return go(pc + 1, new)
    return go(0, {})


def test_page_example():
    alphabet, max_len = range(8), 3
    inputs = list(all_inputs(alphabet, max_len))
    exploits = [x for x in inputs if oracle(PAGE, x)]
    assert len(inputs) == 585 and len(exploits) == 67
    sigs = {kind: generate(PAGE, [1, 6], kind, alphabet, max_len) for kind in ("turing", "single", "multiple", "regex")}
    matched = {kind: [x for x in inputs if f(x)] for kind, f in sigs.items()}
    assert matched["turing"] == exploits and matched["multiple"] == exploits
    assert len(matched["single"]) == 18 and all(oracle(PAGE, x) for x in matched["single"])
    assert len(matched["regex"]) == 82 and set(map(tuple, exploits)) <= set(map(tuple, matched["regex"]))
    false_pos = [x for x in matched["regex"] if not oracle(PAGE, x)]
    assert len(false_pos) == 15 and all(x[0] == 2 and x[1] + x[2] <= 4 for x in false_pos)
    single = single_path_signature(PAGE, [1, 6])
    assert single == [(((), 1, 0), ">", 0), (((), 1, 0), ">", 1), ((((0, 1),), 0, 0), "==", 1),
                      ((((1, 1),), 0, 0), "<=", 6), ((((1, 1),), 0, 0), ">", 4)]
    assert len(multiple_path_signature(PAGE)) == 2


def test_edge_cases():
    with pytest.raises(ValueError):
        single_path_signature(PAGE, [3, 3])
    safe = [("load", 0, 0), ("halt",)]
    assert multiple_path_signature(safe) == []
    assert regex_signature([], range(4), 3) is None
    assert not generate(safe, [], "regex", range(4), 3)([0])
    # A vulnerability that needs no input: the empty input matches.
    always = [("const", 0, 9), ("vuln", 0, ">", 4)]
    assert generate(always, [], "regex", range(4), 2)([]) and generate(always, [], "single")([1, 2])
    # Inputs longer than the bound are outside the regular expression.
    assert not generate(always, [], "regex", range(4), 2)([0, 0, 0])


def random_program(rng):
    n = rng.randint(3, 9)
    prog = []
    for pc in range(n):
        r = rng.random()
        if r < 0.3:
            prog.append(("load", rng.randrange(4), rng.randrange(3)))
        elif r < 0.5:
            prog.append(("br", rng.randrange(4), rng.choice(OPS), rng.randrange(7), rng.randint(pc + 1, n)))
        elif r < 0.6:
            prog.append(("add", rng.randrange(4), rng.randrange(4), rng.randrange(4)))
        elif r < 0.68:
            prog.append(("addi", rng.randrange(4), rng.randrange(4), rng.randint(-2, 2)))
        elif r < 0.73:
            prog.append(("len", rng.randrange(4)))
        elif r < 0.78:
            prog.append(("const", rng.randrange(4), rng.randrange(4)))
        elif r < 0.83:
            prog.append(("jmp", rng.randint(pc + 1, n)))
        elif r < 0.86:
            prog.append(("halt",))
        else:
            prog.append(("vuln", rng.randrange(4), rng.choice(OPS), rng.randrange(7)))
    if rng.random() < 0.7:
        prog.append(("vuln", rng.randrange(4), rng.choice(OPS), rng.randrange(7)))
    if rng.random() < 0.4:
        # A sum of two bytes, as in a pair of length fields; jump targets shift by 3.
        shifted = [ins[:-1] + (ins[-1] + 3,) if ins[0] in ("br", "jmp") else ins for ins in prog]
        prog = [("load", 0, 0), ("load", 1, 1), ("add", 2, 0, 1)] + shifted
    return prog


def test_random_programs_against_brute_force():
    rng = random.Random(61)
    alphabet, max_len = range(4), 3
    inputs = list(all_inputs(alphabet, max_len))
    nontrivial = binary = 0
    for _ in range(500):
        prog = random_program(rng)
        exploits = {tuple(x) for x in inputs if oracle(prog, x)}
        disjuncts = multiple_path_signature(prog)
        assert {tuple(x) for x in inputs if generate(prog, [], "turing")(x)} == exploits
        if not exploits:
            assert not any(generate(prog, [], "multiple")(x) for x in inputs)
            continue
        assert {tuple(x) for x in inputs if generate(prog, [], "multiple")(x)} == exploits
        regex = generate(prog, [], "regex", alphabet, max_len)
        over = {tuple(x) for x in inputs if regex(x)}
        assert exploits <= over
        if all(len(f[0]) <= 1 for atoms in disjuncts for f, _, _ in atoms):
            assert over == exploits
        else:
            binary += 1
        if exploits and len(exploits) < len(inputs):
            nontrivial += 1
        for sample in rng.sample(sorted(exploits), min(3, len(exploits))):
            single = generate(prog, list(sample), "single")
            matched = {tuple(x) for x in inputs if single(x)}
            assert sample in matched and matched <= exploits
    assert nontrivial > 100 and binary > 30

History

Network intrusion detection systems used exploit-based signatures, byte patterns from captured attacks, from the 1990s. Worms of the early 2000s, and polymorphic worms that change their bytes, led to automatic generators such as Autograph, EarlyBird and Polygraph, which learn patterns from many samples. Shield (2004) instead wrote filters by hand from the vulnerability. Brumley, Newsome, Song, Wang and Jha (IEEE S&P 2006) defined a vulnerability signature as a representation of the language of all exploits of a flaw, compared the Turing machine, symbolic constraint and regular expression forms in cost and precision, and generated signatures from the program and a single exploit with data-flow analysis and constraint solving. Bouncer (2007) combined this approach with the search for other paths to the same flaw.

References

  1. David Brumley, James Newsome, Dawn Song, Hao Wang and Somesh Jha, Towards automatic generation of vulnerability-based signatures, IEEE Symposium on Security and Privacy 2006, the abstract (a signature as a representation of the language of the inputs that exploit a vulnerability, the analysis of the complexity of making and matching signatures, generation from a single exploit)

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