Algorithm Search⌘K

Algorithmadvanced

Buffer overrun detection by range analysis

Also called Wagner buffer overrun detector.

Models C strings by allocated size and used length, generates integer range constraints and flags uses where the length may exceed the size.

Time
O(m^2 b) worst
Space
O(m + b) extra
Where
b = the number of buffers; m = the number of statements
Properties
not context sensitivedeterministicnot flow sensitiveofflineiterative
Origin
David Wagner, Jeffrey S. Foster, Eric A. Brewer, Alexander Aiken, 2000

Buffer overrun detection by range analysis is the static detector of Wagner, Foster, Brewer and Aiken (NDSS 2000) for C programs that handle text with the standard string library. It models each string buffer ss by two integers: alloc(s)\mathrm{alloc}(s), the number of bytes allocated, and len(s)\mathrm{len}(s), the number of bytes in use, counting the terminating null byte. It turns each string operation into an integer range constraint, finds the least ranges that satisfy all the constraints, and flags every buffer whose length range can go past its allocated size. It is a flow-insensitive form of the interval domain, with an exact solver for the cycles that an abstract interpreter would handle with a widening. On sendmail it found real buffer overflows among many false alarms. It ignores most pointer aliasing, so it can also miss bugs. The costs on this page are in the word-RAM model.

In plain words

A C string lives in a buffer of fixed size. The program puts text into the buffer and a zero byte after the text. If the text and the zero byte need more bytes than the buffer has, the program writes past its end. This is a buffer overrun.

The detector never runs the program. For each buffer it keeps two ranges of numbers: how big the buffer can be, and how long its text can be. Each string call gives a rule. For example, a copy of a name of up to 16 bytes into a buffer means that the text of the buffer can also be up to 16 bytes long. The detector applies the rules until no range grows. Then it compares the two ranges of each buffer. If the text can be longer than the buffer, it gives a warning.

The problem

The input is a C program, or for this page a program of a small C-like language: declarations char s[n] and calls of the string functions on declared buffers. The safety property is that len(s)≤alloc(s)\mathrm{len}(s) \le \mathrm{alloc}(s) for every buffer at every point of every run. Whether a program has this property is undecidable by Rice's theorem, so a detector must give false alarms, miss bugs, or both. The output is one verdict per buffer: safe, possible overrun, or certain overrun.

Wagner et al. treat a string as an abstract type with the two attributes and read each library call as an operation on them. Each statement gives one constraint "e⊆ve \subseteq v": every value that the expression ee can take must be in the range of the variable vv. The table lists the constraints of the toy language, taken from Table 1 of the paper. A range is a set [a,b][a, b] of integers, where bb can be +∞+\infty.

statement constraint
char s[n] [n,n]⊆alloc(s)[n, n] \subseteq \mathrm{alloc}(s)
strcpy(s, "...") with kk characters [k+1,k+1]⊆len(s)[k+1, k+1] \subseteq \mathrm{len}(s)
fgets(s, n, f) [1,n]⊆len(s)[1, n] \subseteq \mathrm{len}(s)
gets(s) [1,+∞]⊆len(s)[1, +\infty] \subseteq \mathrm{len}(s)
strcpy(d, s) len(s)⊆len(d)\mathrm{len}(s) \subseteq \mathrm{len}(d)
strncpy(d, s, n) min⁡(len(s),n)⊆len(d)\min(\mathrm{len}(s), n) \subseteq \mathrm{len}(d)
strcat(d, s) len(d)+len(s)−1⊆len(d)\mathrm{len}(d) + \mathrm{len}(s) - 1 \subseteq \mathrm{len}(d)
strncat(d, s, n) len(d)+min⁡(len(s)−1,n)⊆len(d)\mathrm{len}(d) + \min(\mathrm{len}(s) - 1, n) \subseteq \mathrm{len}(d)

The analysis is flow-insensitive: it ignores the order of the statements, so the constraint of a statement holds for every point of the program. The paper also models malloc, sprintf, strlen, pointer assignment and a few other calls, and treats a function call by one shared set of variables for all its call sites.

The algorithm

A constraint of the form v+g(w)⊆vv + g(w) \subseteq v, with g(x)=min⁡(x−1,n)g(x) = \min(x - 1, n) and n≥0n \ge 0 (take n=+∞n = +\infty for strcat), is a cycle: the variable vv is on both sides. A plain round of updates on the constraints [5,5]⊆v[5, 5] \subseteq v and v+1⊆vv + 1 \subseteq v gives [5,5][5, 5], then [5,6][5, 6], then [5,7][5, 7], and never stops. The paper calls this counting to infinity. Its fix is exact, not a widening: if vv is not empty and the largest value of g(w)g(w) is positive, every solution has sup⁡v=+∞\sup v = +\infty (their Lemma 1). Line L6 applies this rule.

  1. DETECT-OVERRUNS(P) ▷ P: the declarations and string calls of a program
  2. 1C ← the constraints of the statements of P, one per statement
  3. 2for each buffer s: len(s) ← ∅, alloc(s) ← ∅
  4. 3repeat
  5. 4changed ← false
  6. 5for each constraint e ⊆ v in C do
  7. 6if e = v + g(w), v ≠ ∅, w ≠ ∅ and sup g(w) > 0 then r ← [inf v, +∞] ▷ the cycle rule
  8. 7else r ← the range of e under the current ranges
  9. 8if r ⊄ v then v ← hull(v, r), changed ← true
  10. 9until not changed
  11. 10for each buffer s with len(s) = [a, b] and alloc(s) = [c, d] do
  12. 11report safe if b ≤ c, certain overrun if a > d, and possible overrun otherwise

Line L7 uses interval arithmetic: min⁡([a,b],n)=[min⁡(a,n),min⁡(b,n)]\min([a, b], n) = [\min(a, n), \min(b, n)] and [a,b]+[c,d]=[a+c,b+d][a, b] + [c, d] = [a + c, b + d], with the empty range if an argument is empty. Line L8 grows a range to the smallest range that holds both, so a range never shrinks. A buffer that is never written has an empty length range, and line L11 calls it safe.

Example

Take this program. The input line has at most 15 characters, so fgets stores at most 16 bytes with the null.

statement constraint
char buf[10], name[16], out[8], tag[4] [10,10]⊆alloc(buf)[10,10] \subseteq \mathrm{alloc}(buf), [16,16]⊆alloc(name)[16,16] \subseteq \mathrm{alloc}(name), [8,8]⊆alloc(out)[8,8] \subseteq \mathrm{alloc}(out), [4,4]⊆alloc(tag)[4,4] \subseteq \mathrm{alloc}(tag)
fgets(name, 16, f) [1,16]⊆len(name)[1, 16] \subseteq \mathrm{len}(name)
strcpy(buf, "hello") [6,6]⊆len(buf)[6, 6] \subseteq \mathrm{len}(buf)
strncpy(out, name, 8) min⁡(len(name),8)⊆len(out)\min(\mathrm{len}(name), 8) \subseteq \mathrm{len}(out)
strcat(buf, name) len(buf)+len(name)−1⊆len(buf)\mathrm{len}(buf) + \mathrm{len}(name) - 1 \subseteq \mathrm{len}(buf)
strcpy(tag, "error") [6,6]⊆len(tag)[6, 6] \subseteq \mathrm{len}(tag)

The first round of lines L3 to L9 sets the alloc ranges, then len(name)=[1,16]\mathrm{len}(name) = [1, 16] and len(buf)=[6,6]\mathrm{len}(buf) = [6, 6]. The strncpy constraint gives len(out)=[min⁡(1,8),min⁡(16,8)]=[1,8]\mathrm{len}(out) = [\min(1, 8), \min(16, 8)] = [1, 8]. The strcat constraint is a cycle with sup⁡g=16−1=15>0\sup g = 16 - 1 = 15 > 0, so line L6 sets len(buf)=[6,+∞]\mathrm{len}(buf) = [6, +\infty]. Then len(tag)=[6,6]\mathrm{len}(tag) = [6, 6]. A second round changes nothing. Lines L10 and L11 give:

buffer len alloc verdict
name [1,16][1, 16] [16,16][16, 16] safe, 16≤1616 \le 16
out [1,8][1, 8] [8,8][8, 8] safe, 8≤88 \le 8
buf [6,+∞][6, +\infty] [10,10][10, 10] possible overrun, 6≤10<+∞6 \le 10 < +\infty
tag [6,6][6, 6] [4,4][4, 4] certain overrun, 6>46 > 4

The warning on buf is a real bug: "hello" with 15 more characters needs 21 bytes. The analysis says +∞+\infty and not 21 because it does not know that the strcat runs once. The tests of the implementation check this example.

Correctness

There are two claims, both proved in full in the proof file. First, the solver is exact. Every update of lines L6 to L8 is forced by the constraints, so the ranges never pass the least solution; for line L6 this is Lemma 1 of the paper. When the loop stops, every constraint holds. So the result is the least solution, which exists by Theorem 1 of the paper. Second, the verdicts are sound for the toy language. In any run of the statements, in any order and any number of times, every length that a step writes to ss is in the range of len(s)\mathrm{len}(s), by induction over the steps. So a buffer that some run overruns is never called safe, and in a buffer called a certain overrun, every write overruns. This second claim does not hold for real C, where two pointers can name one buffer. The paper says that the tool ignores most aliasing and is unsound for that reason.

Proof: Correctness of buffer overrun detection by range analysisfull

We prove the claims of the Correctness section for DETECT-OVERRUNS (lines L1 to L11) on the toy language of the page. A range is either empty or an interval [l,h][l, h] with ll an integer and hh an integer or +∞+\infty. Ranges are ordered by inclusion, and ⊔\sqcup is the hull. A constraint e⊆ve \subseteq v holds for an assignment RR of ranges to variables if the range of ee under RR, computed with interval arithmetic, is a subset of R(v)R(v). The three forms are a constant [p,q]⊆v[p, q] \subseteq v, a copy min⁡(u,k)⊆v\min(u, k) \subseteq v with k≥1k \ge 1 or k=+∞k = +\infty, and a concatenation v+g(w)⊆vv + g(w) \subseteq v with g(x)=min⁡(x−1,k)g(x) = \min(x - 1, k), k≥0k \ge 0 or k=+∞k = +\infty. The interval operations are min⁡([l,h],k)=[min⁡(l,k),min⁡(h,k)]\min([l, h], k) = [\min(l, k), \min(h, k)] and [l1,h1]+[l2,h2]=[l1+l2,h1+h2][l_1, h_1] + [l_2, h_2] = [l_1 + l_2, h_1 + h_2], and both give the empty range if an argument is empty. Both are monotone in each argument.

Let FF be the set of the integer constants that occur in the constraints, and let S∗S^* be the least assignment that satisfies every constraint. Wagner et al. prove that S∗S^* exists (their Theorem 1); it also follows from the Knaster-Tarski theorem, because the ranges form a complete lattice and each constraint is a monotone condition.

Claim 1 (bounds). At every point of the run of the algorithm, every nonempty range has its lower bound in FF, every finite upper bound is in FF, and the lower bound of every nonempty len range is at least 1.

Proof. By induction over the updates of line L8. The constant constraints of len variables have p≥1p \ge 1 (a literal of kk characters gives k+1k + 1, fgets and gets give 1). A copy gives the bounds min⁡(l,k)\min(l, k) and min⁡(h,k)\min(h, k), which are an old bound or the constant k≥1k \ge 1. Line L6 keeps the lower bound and sets the upper bound to +∞+\infty. Line L7 on a concatenation that does not fire the cycle rule returns the current range. The alloc variables get only constant ranges. The hull of two ranges with bounds in F∪{+∞}F \cup \{+\infty\} has its bounds in the same set, and the hull of two len ranges with lower bounds at least 1 has a lower bound at least 1. □\square

Claim 2 (termination and cost). The loop of lines L3 to L9 stops after at most 2v(∣F∣+1)+12 v (|F| + 1) + 1 rounds, where vv is the number of variables. Each round costs O(c)O(c) for cc constraints, so the cost is O(c2v)O(c^2 v), since ∣F∣≤c|F| \le c.

Proof. A variable only grows, because line L8 replaces R(v)R(v) by R(v)⊔rR(v) \sqcup r. By Claim 1 its lower bound moves down inside FF and its upper bound moves up inside F∪{+∞}F \cup \{+\infty\}, so each of the 2v2v bounds changes at most ∣F∣+1|F| + 1 times (counting the first change from empty). A round that sets changed to true moves at least one bound, so at most 2v(∣F∣+1)2v(|F| + 1) rounds change something, and the next round stops the loop. □\square

Claim 3 (no update overshoots). At every point, R⊑S∗R \sqsubseteq S^*.

Proof. At line L2 every range is empty. Suppose R⊑S∗R \sqsubseteq S^* before an update of line L8 by a constraint with left side ee and target vv. If line L7 computed rr, then rr is the range of ee under RR, and by monotonicity rr is a subset of the range of ee under S∗S^*, which is a subset of S∗(v)S^*(v), since S∗S^* satisfies the constraint. If line L6 computed r=[l,+∞]r = [l, +\infty], then R(v)=[l,h]R(v) = [l, h] is nonempty, and sup⁡g(R(w))>0\sup g(R(w)) > 0. By monotonicity S∗(v)⊇R(v)S^*(v) \supseteq R(v) is nonempty and sup⁡g(S∗(w))≥sup⁡g(R(w))>0\sup g(S^*(w)) \ge \sup g(R(w)) > 0. Let H=sup⁡S∗(v)H = \sup S^*(v). The constraint gives H+sup⁡g(S∗(w))≤HH + \sup g(S^*(w)) \le H, which is false for finite HH. So H=+∞H = +\infty, and S∗(v)⊇[l,+∞]S^*(v) \supseteq [l, +\infty], since inf⁡S∗(v)≤l\inf S^*(v) \le l. In both cases R(v)⊔r⊑S∗(v)R(v) \sqcup r \sqsubseteq S^*(v). This is Lemma 1 of Wagner et al. for the affine function x↦x+cx \mapsto x + c with c>0c > 0. □\square

Claim 4 (the result is a solution). When the loop stops, RR satisfies every constraint.

Proof. In the last round no update changed RR, so for each constraint the rr of lines L6 or L7 was a subset of R(v)R(v). For a constant or a copy, rr is the range of ee under RR, so the constraint holds. For a concatenation with R(v)R(v) or R(w)R(w) empty, the range of ee is empty. Otherwise R(w)=[lw,hw]R(w) = [l_w, h_w] with lw≥1l_w \ge 1 by Claim 1, so g(R(w))=[min⁡(lw−1,k),min⁡(hw−1,k)]g(R(w)) = [\min(l_w - 1, k), \min(h_w - 1, k)] with both ends at least 0. If the cycle rule fired, R(v)⊇[l,+∞]R(v) \supseteq [l, +\infty] with l=inf⁡R(v)l = \inf R(v), and the range of ee is [l+inf⁡g,+∞]⊆R(v)[l + \inf g, +\infty] \subseteq R(v), since inf⁡g≥0\inf g \ge 0. If it did not fire, sup⁡g≤0\sup g \le 0, so g(R(w))=[0,0]g(R(w)) = [0, 0], and the range of ee is R(v)R(v) itself. □\square

Claim 5 (exactness). The ranges returned are S∗S^*.

Proof. By Claim 4 the result satisfies all constraints, so S∗⊑RS^* \sqsubseteq R by the minimality of S∗S^*. By Claim 3, R⊑S∗R \sqsubseteq S^*. □\square

Claim 6 (soundness for the toy language). Take any run of the program that executes its statements in any order, each any number of times, where a statement reads only buffers that some earlier step wrote. Then every length that a step writes to buffer ss lies in S∗(len(s))S^*(\mathrm{len}(s)).

Proof. By induction over the steps. Suppose every length written before the step lies in the range of its buffer. A literal, fgets or gets step writes a value in its constant range. A copy step writes min⁡(x,k)\min(x, k) with xx the current length of the source, which by induction is in S∗(len(src))S^*(\mathrm{len}(src)), so the value is in the interval min⁡(S∗(len(src)),k)⊆S∗(len(dst))\min(S^*(\mathrm{len}(src)), k) \subseteq S^*(\mathrm{len}(dst)). A concatenation step writes y+g(x)y + g(x) with yy and xx in the ranges of the target and the source, so the value is in S∗(len(d))+g(S∗(len(s)))⊆S∗(len(d))S^*(\mathrm{len}(d)) + g(S^*(\mathrm{len}(s))) \subseteq S^*(\mathrm{len}(d)). □\square

The analysis does not depend on the order of the statements, so Claim 6 covers every order in which the statements of a real program could run, including loops and branches. It does not cover aliasing: in C, two pointers can name the same buffer, and the toy language has no pointers. Wagner et al. say that the real tool ignores most aliasing and is unsound for that reason.

Claim 7 (verdicts). Let alloc(s)=[n,n](s) = [n, n] and S∗(len(s))=[a,b]S^*(\mathrm{len}(s)) = [a, b]. If some run of Claim 6 writes a length greater than nn to ss, the verdict of line L11 is not "safe". If the verdict is "certain overrun", every write to ss in every such run overruns.

Proof. A written length x>nx > n satisfies x≤bx \le b by Claim 6, so b>nb > n, and line L11 does not say "safe". If the verdict is "certain", then a>na > n, and every written length xx satisfies x≥a>nx \ge a > n by Claim 6. □\square

Complexity

In the round-robin form above, a round costs O(m)O(m) for mm statements. Every finite bound that a range takes is one of the at most mm constants of the program, and each of the 2b2b bounds of the bb buffers only moves in one direction, so there are at most 2b(m+1)+12b(m + 1) + 1 rounds. The time is O(m2b)O(m^2 b) and the extra space is O(m+b)O(m + b).

The solver of the paper is faster. It follows the constraint graph by depth-first search, finds the cycles, and solves each cycle in linear time (their Theorem 2), with a separate treatment of min and max (their Appendix B). The authors report that it takes a few seconds on sendmail 8.9.3 (about 32,000 lines, which give about 9,000 variables and 29,000 constraints), while the whole tool, with parsing and constraint generation, took about 15 minutes on a Pentium III. These are measurements on one machine in 1999 and 2000.

Properties

  • Flow-insensitive and context-insensitive. One range per buffer for the whole program, and one set of variables for each function over all call sites.
  • Exact for its constraints. The solver returns the least solution, not a widened upper bound.
  • Not sound for real C. Pointer aliasing is mostly ignored, and all structures of one type share one variable per field.
  • Not complete. Every flagged buffer is a possible bug, but many are false alarms. Every nontrivial strcat is flagged, because its cycle makes the length range unbounded.
  • Deterministic. The same program gives the same warnings.

Variants and improvements

  • More precision. Table 2 of the paper estimates what fraction of the false alarms on sendmail flow sensitivity and other improvements would remove. These are the authors' estimates, not measurements of a built tool.
  • Linear programming. Ganapathy, Jha, Chandler, Melski and Vitek (CCS 2003) generate similar range constraints with points-to analysis and solve them with linear programming.
  • Sound string analysis. CSSV (Dor, Rodeh and Sagiv, PLDI 2003) uses procedure contracts, pointer analysis and an integer analysis, and aims to report every string overrun with few false alarms.
  • Annotations. Splint (Larochelle and Evans, USENIX Security 2001) checks programmer annotations on the bounds of buffers and uses heuristics for loops.
  • Widening. A flow-sensitive abstract interpretation over the interval domain handles loops by widening instead of the exact cycle rule.
  • Run-time checks. A dynamic tool such as AddressSanitizer finds the overruns that a test actually triggers, with no false alarms; a fuzzer supplies the tests. The two methods complement each other.

When to use it

Use a flow-insensitive range detector to rank the call sites of a large C program for manual review: on sendmail it gave 44 warnings for about 695 call sites of unsafe string functions. Use it when a quick, scalable pass is worth a high false alarm rate. Do not use it as a proof of safety, because of aliasing, and do not use it when the program uses pointer arithmetic more than library calls. For a proof, use a sound analysis; for confirmation of a warning, use a test under a run-time checker.

Pitfalls

  • The order of statements is lost. The program strcpy(s, "a"); strcpy(t, s); strcpy(s, "a longer text") with char t[5] gets a warning on t, because the analysis also lets the later, longer content of s flow into t. The tests check this false alarm.
  • Aliasing. A write through a pointer to the same buffer under another name is not seen. A clean report is not a proof.
  • Counting the null byte. len includes the null byte. An analysis or a programmer that forgets it misses the off-by-one overruns that the paper found in sendmail.
  • strncpy. The paper models strncpy by min⁡(len(src),n)\min(\mathrm{len}(src), n), but the real function writes no null byte when the source is long. The next string operation on the target can then read past the end.
  • Integer arithmetic on sizes. A size computed with integer overflow wraps around, and a range model with unbounded integers does not see it.

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.

buffer_overrun_detection_by_range_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/buffer-overrun-detection-by-range-analysis/. The authors are listed in prov/JPTZRY.jsonl.
"""Buffer overrun detection by range analysis, after Wagner, Foster, Brewer and Aiken (NDSS 2000).

Each buffer s has two integer variables: alloc(s), the number of bytes
allocated for it, and len(s), the number of bytes in use, counting the
terminating null. The program is safe when len(s) <= alloc(s) for every
buffer. The analysis is flow-insensitive: it turns every statement into one
range constraint "e is a subset of v", finds the least ranges that satisfy
all the constraints, and compares the two ranges of each buffer.

The program is a list of statements of a small C-like language, one tuple
per statement. Names are strings and the numbers are ints:

    ("decl", s, n)        char s[n];                 n >= 1
    ("lit", s, k)         strcpy(s, a literal of k characters)   k >= 0
    ("fgets", s, n)       fgets(s, n, input)         n >= 1
    ("gets", s)           gets(s)
    ("strcpy", d, s)      strcpy(d, s)
    ("strncpy", d, s, n)  strncpy(d, s, n)           n >= 1
    ("strcat", d, s)      strcat(d, s)
    ("strncat", d, s, n)  strncat(d, s, n)           n >= 0

Each buffer is declared once, before or after its uses (the order of the
statements does not matter to a flow-insensitive analysis), and every buffer
that a statement names is declared. The constraints follow Table 1 of the
paper; strncpy is modelled as in the paper, by min(len(src), n).

This is a static detector on a toy language. It reads no real program and
no real memory.
"""

import math
from dataclasses import dataclass, field
from typing import Optional, Sequence

INF = math.inf

Range = Optional[tuple[float, float]]  # (lo, hi) with lo <= hi, hi may be INF; None is the empty range
Var = tuple[str, str]  # ("len", s) or ("alloc", s)
Constraint = tuple  # see generate_constraints

SAFE = "safe"
POSSIBLE = "possible overrun"
CERTAIN = "certain overrun"


def generate_constraints(program: Sequence[tuple]) -> list[Constraint]:
    """Return the range constraints of the program, one per statement.

    The constraint forms are:
      ("const", v, lo, hi)  the range [lo, hi] is a subset of v
      ("copy", v, u, cap)   min(u, cap) is a subset of v (cap may be INF)
      ("cat", v, w, cap)    v + min(w - 1, cap) is a subset of v (cap may be INF)
    Raises ValueError on a malformed program. Cost O(m) for m statements.
    """
    declared: dict[str, int] = {}
    for st in program:
        if st[0] == "decl":
            _, s, n = st
            if s in declared:
                raise ValueError(f"buffer {s!r} is declared twice")
            if n < 1:
                raise ValueError("a buffer has at least one byte")
            declared[s] = n
    out: list[Constraint] = []
    for st in program:
        op = st[0]
        names = [x for x in st[1:] if isinstance(x, str)]
        for name in names:
            if name not in declared:
                raise ValueError(f"buffer {name!r} is not declared")
        if op == "decl":
            out.append(("const", ("alloc", st[1]), st[2], st[2]))
        elif op == "lit":
            if st[2] < 0:
                raise ValueError("a literal has length >= 0")
            out.append(("const", ("len", st[1]), st[2] + 1, st[2] + 1))
        elif op == "fgets":
            if st[2] < 1:
                raise ValueError("fgets needs n >= 1")
            out.append(("const", ("len", st[1]), 1, st[2]))
        elif op == "gets":
            out.append(("const", ("len", st[1]), 1, INF))
        elif op == "strcpy":
            out.append(("copy", ("len", st[1]), ("len", st[2]), INF))
        elif op == "strncpy":
            if st[3] < 1:
                raise ValueError("strncpy needs n >= 1")
            out.append(("copy", ("len", st[1]), ("len", st[2]), st[3]))
        elif op == "strcat":
            out.append(("cat", ("len", st[1]), ("len", st[2]), INF))
        elif op == "strncat":
            if st[3] < 0:
                raise ValueError("strncat needs n >= 0")
            out.append(("cat", ("len", st[1]), ("len", st[2]), st[3]))
        else:
            raise ValueError(f"unknown statement {op!r}")
    return out


def hull(a: Range, b: Range) -> Range:
    """The smallest range that holds both a and b."""
    if a is None:
        return b
    if b is None:
        return a
    return (min(a[0], b[0]), max(a[1], b[1]))


def contains(a: Range, b: Range) -> bool:
    """True if the range b is a subset of the range a."""
    if b is None:
        return True
    if a is None:
        return False
    return a[0] <= b[0] and b[1] <= a[1]


def solve(cons: Sequence[Constraint], variables: Sequence[Var]) -> dict[Var, Range]:
    """The least ranges that satisfy every constraint.

    Precondition: the constraints come from generate_constraints, so every
    lower bound of a len variable is at least 1. Cost O(c^2 v) in the word-RAM
    model for c constraints and v variables: a round costs O(c), and every
    round but the last moves one of the 2v bounds to another of at most c + 1
    values.
    """
    R: dict[Var, Range] = {x: None for x in variables}  # @line L2
    changed = True
    while changed:  # @line L3
        changed = False  # @line L4
        for c in cons:  # @line L5
            kind, v = c[0], c[1]
            if kind == "const":
                r: Range = (c[2], c[3])  # @line L7
            elif kind == "copy":
                u = R[c[2]]
                r = None if u is None else (min(u[0], c[3]), min(u[1], c[3]))  # @line L7
            else:  # "cat": v + g(w) with g(x) = min(x - 1, cap) >= 0
                cur, w = R[v], R[c[2]]
                if cur is None or w is None:
                    r = None  # @line L7
                elif min(w[1] - 1, c[3]) > 0:
                    r = (cur[0], INF)  # @line L6
                else:
                    r = cur  # @line L7
            if not contains(R[v], r):  # @line L8
                R[v] = hull(R[v], r)
                changed = True
    return R  # @line L9


def classify(length: Range, alloc: Range) -> str:
    """Compare len(s) = [a, b] with alloc(s) = [c, d].

    Safe if b <= c (or the buffer is never written), a certain overrun if
    a > d, and a possible overrun otherwise.
    """
    if length is None:
        return SAFE
    if alloc is None:
        raise ValueError("a written buffer must be declared")
    a, b = length
    c, d = alloc
    if b <= c:
        return SAFE
    if a > d:
        return CERTAIN
    return POSSIBLE


@dataclass
class Report:
    ranges: dict[Var, Range] = field(default_factory=dict)
    verdicts: dict[str, str] = field(default_factory=dict)


def detect_overruns(program: Sequence[tuple]) -> Report:
    """Run DETECT-OVERRUNS on a program of the toy language.

    Returns the least ranges of len(s) and alloc(s) and a verdict per
    declared buffer. Precondition: the program is well formed (see the module
    comment). Cost O(m^2 b) for m statements and b buffers.
    """
    cons = generate_constraints(program)  # @line L1
    buffers = sorted({st[1] for st in program if st[0] == "decl"})
    variables = [(k, s) for s in buffers for k in ("len", "alloc")]
    R = solve(cons, variables)
    report = Report(ranges=R)
    for s in buffers:  # @line L10
        report.verdicts[s] = classify(R[("len", s)], R[("alloc", s)])  # @line L11
    return report
test_buffer_overrun_detection_by_range_analysis.py 277 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/buffer-overrun-detection-by-range-analysis/. The authors are listed in prov/JPTZRY.jsonl.
import random

import pytest

from buffer_overrun_detection_by_range_analysis import (
    CERTAIN,
    INF,
    POSSIBLE,
    SAFE,
    detect_overruns,
    generate_constraints,
)

NAMES = ["a", "b", "c"]
GETS_MAX = 3  # the concrete runs read at most GETS_MAX - 1 characters with gets
LOOP_MAX = 2  # a loop body runs 0, 1 or 2 times


def page_example():
    return [
        ("decl", "buf", 10),
        ("decl", "name", 16),
        ("decl", "out", 8),
        ("decl", "tag", 4),
        ("fgets", "name", 16),
        ("lit", "buf", 5),
        ("strncpy", "out", "name", 8),
        ("strcat", "buf", "name"),
        ("lit", "tag", 5),
    ]


def test_page_example():
    rep = detect_overruns(page_example())
    R = rep.ranges
    assert R[("len", "name")] == (1, 16)
    assert R[("len", "out")] == (1, 8)
    assert R[("len", "buf")] == (6, INF)
    assert R[("len", "tag")] == (6, 6)
    assert R[("alloc", "buf")] == (10, 10)
    assert rep.verdicts == {"buf": POSSIBLE, "name": SAFE, "out": SAFE, "tag": CERTAIN}


def test_flow_insensitive_false_alarm():
    # t only ever gets the 1-character string, but s later holds 11
    # characters, and the analysis does not know the order of the statements.
    prog = [
        ("decl", "s", 16),
        ("decl", "t", 5),
        ("lit", "s", 1),
        ("strcpy", "t", "s"),
        ("lit", "s", 11),
    ]
    rep = detect_overruns(prog)
    assert rep.ranges[("len", "t")] == (2, 12)
    assert rep.verdicts["t"] == POSSIBLE
    assert concrete_values(prog)["t"] == {2}


def test_edge_cases():
    # A buffer that is never written is safe.
    assert detect_overruns([("decl", "a", 1)]).verdicts == {"a": SAFE}
    # strcat of an empty string and strncat with n = 0 add nothing.
    prog = [("decl", "a", 4), ("decl", "b", 4), ("lit", "a", 3), ("lit", "b", 0),
            ("strcat", "a", "b"), ("strncat", "a", "a", 0)]
    rep = detect_overruns(prog)
    assert rep.ranges[("len", "a")] == (4, 4)
    assert rep.verdicts["a"] == SAFE
    # gets is unbounded, so it is a possible overrun for every size.
    rep = detect_overruns([("decl", "a", 100), ("gets", "a")])
    assert rep.ranges[("len", "a")] == (1, INF)
    assert rep.verdicts["a"] == POSSIBLE
    # Exact fit: 3 characters and the null in 4 bytes is safe; in 3 bytes it is certain.
    assert detect_overruns([("decl", "a", 4), ("lit", "a", 3)]).verdicts["a"] == SAFE
    assert detect_overruns([("decl", "a", 3), ("lit", "a", 3)]).verdicts["a"] == CERTAIN
    # A copy cycle does not count to infinity.
    prog = [("decl", "a", 8), ("decl", "b", 8), ("lit", "a", 2),
            ("strcpy", "b", "a"), ("strcpy", "a", "b")]
    rep = detect_overruns(prog)
    assert rep.ranges[("len", "a")] == (3, 3) and rep.ranges[("len", "b")] == (3, 3)
    # Malformed programs.
    with pytest.raises(ValueError):
        detect_overruns([("lit", "a", 1)])
    with pytest.raises(ValueError):
        detect_overruns([("decl", "a", 2), ("decl", "a", 3)])
    with pytest.raises(ValueError):
        detect_overruns([("decl", "a", 0)])
    with pytest.raises(ValueError):
        detect_overruns([("decl", "a", 2), ("strncpy", "a", "a", 0)])
    with pytest.raises(ValueError):
        generate_constraints([("memcpy", "a", "b", 3)])


# ----- an independent oracle for the least solution -----

def oracle_least_ranges(program):
    """Plain round-robin iteration with interval arithmetic and a cut-off.

    In the least solution every finite bound is one of the constants of the
    program (the proof is in proofs/correctness.md), so a bound that grows
    past the largest constant must be infinite. This oracle has no cycle rule.
    """
    cons = generate_constraints(program)
    big = 1
    for c in cons:
        for x in c[2:]:
            if isinstance(x, (int, float)) and x != INF:
                big = max(big, int(x))
    buffers = sorted({st[1] for st in program if st[0] == "decl"})
    R = {(k, s): None for s in buffers for k in ("len", "alloc")}
    changed = True
    while changed:
        changed = False
        for c in cons:
            kind, v = c[0], c[1]
            if kind == "const":
                r = (c[2], c[3])
            elif kind == "copy":
                u = R[c[2]]
                r = None if u is None else (min(u[0], c[3]), min(u[1], c[3]))
            else:
                cur, w = R[v], R[c[2]]
                if cur is None or w is None:
                    r = None
                else:
                    r = (cur[0] + min(w[0] - 1, c[3]), cur[1] + min(w[1] - 1, c[3]))
            if r is None:
                continue
            old = R[v]
            new = r if old is None else (min(old[0], r[0]), max(old[1], r[1]))
            if new[1] != INF and new[1] > big:
                new = (new[0], INF)
            if new != old:
                R[v] = new
                changed = True
    return R


# ----- concrete runs of the toy language -----

def random_statement(rng, names):
    op = rng.choice(["lit", "fgets", "gets", "strcpy", "strncpy", "strcat", "strncat"])
    d = rng.choice(names)
    s = rng.choice(names)
    if op == "lit":
        return ("lit", d, rng.randint(0, 5))
    if op == "fgets":
        return ("fgets", d, rng.randint(1, 4))
    if op == "gets":
        return ("gets", d)
    if op == "strcpy":
        return ("strcpy", d, s)
    if op == "strncpy":
        return ("strncpy", d, s, rng.randint(1, 4))
    if op == "strcat":
        return ("strcat", d, s)
    return ("strncat", d, s, rng.randint(0, 3))


def random_program(rng):
    """A structured program: declarations, one first write per buffer, then items.

    An item is a statement, ("loop", body) or ("maybe", body).
    """
    names = NAMES[: rng.randint(1, 3)]
    items = [("decl", s, rng.randint(1, 8)) for s in names]
    for s in names:
        first = rng.choice([("lit", s, rng.randint(0, 5)), ("fgets", s, rng.randint(1, 4)), ("gets", s)])
        items.append(first)
    for _ in range(rng.randint(0, 4)):
        kind = rng.random()
        if kind < 0.6:
            items.append(random_statement(rng, names))
        elif kind < 0.8:
            items.append(("loop", [random_statement(rng, names) for _ in range(rng.randint(1, 2))]))
        else:
            items.append(("maybe", [random_statement(rng, names)]))
    return items


def flatten(items):
    out = []
    for it in items:
        if it[0] in ("loop", "maybe"):
            out.extend(it[1])
        else:
            out.append(it)
    return out


def step(states, st, names, seen):
    """All states after statement st, and record the lengths that st writes."""
    op = st[0]
    if op == "decl":
        return states
    i = names.index(st[1])
    out = set()
    for state in states:
        if op == "lit":
            vals = [st[2] + 1]
        elif op == "fgets":
            vals = range(1, st[2] + 1)
        elif op == "gets":
            vals = range(1, GETS_MAX + 1)
        else:
            src = state[names.index(st[2])]
            if op == "strcpy":
                vals = [src]
            elif op == "strncpy":
                vals = [min(src, st[3])]
            elif op == "strcat":
                vals = [state[i] + src - 1]
            else:
                vals = [state[i] + min(src - 1, st[3])]
        for v in vals:
            seen[st[1]].add(v)
            new = list(state)
            new[i] = v
            out.add(tuple(new))
    return out


def concrete_values(items):
    """The set of lengths written to each buffer over all runs (exhaustive)."""
    names = sorted({it[1] for it in items if it[0] == "decl"})
    seen = {s: set() for s in names}
    states = {tuple(0 for _ in names)}
    for it in items:
        if it[0] == "loop":
            total = set(states)
            cur = states
            for _ in range(LOOP_MAX):
                for st in it[1]:
                    cur = step(cur, st, names, seen)
                total |= cur
            states = total
        elif it[0] == "maybe":
            cur = states
            for st in it[1]:
                cur = step(cur, st, names, seen)
            states = states | cur
        else:
            states = step(states, it, names, seen)
    return seen


def test_random_least_solution_matches_oracle():
    rng = random.Random(20000)
    for _ in range(600):
        prog = flatten(random_program(rng))
        rng.shuffle(prog)  # order does not matter to the analysis
        assert detect_overruns(prog).ranges == oracle_least_ranges(prog)


def test_random_soundness_against_concrete_runs():
    rng = random.Random(4242)
    flagged = certain = 0
    for _ in range(600):
        items = random_program(rng)
        prog = flatten(items)
        rep = detect_overruns(prog)
        values = concrete_values(items)
        sizes = {st[1]: st[2] for st in prog if st[0] == "decl"}
        for s, vals in values.items():
            r = rep.ranges[("len", s)]
            assert vals and r is not None
            assert all(r[0] <= v <= r[1] for v in vals)
            overrun = any(v > sizes[s] for v in vals)
            if overrun:
                assert rep.verdicts[s] != SAFE
                flagged += 1
            if rep.verdicts[s] == CERTAIN:
                assert all(v > sizes[s] for v in vals)
                certain += 1
    assert flagged > 100 and certain > 20

History

Buffer overruns were known as a source of attacks long before 2000: the Morris worm of 1988 spread in part through an unchecked gets in a network service. By the late 1990s they were among the most common classes of reported vulnerability, and the usual automated check was a lexical scan that flagged every call of an unsafe function. Wagner, Foster, Brewer and Aiken (NDSS 2000) called their tool a first step towards automated detection. They gave the two-integer string model, the range constraints, and a cycle solver that is exact where a widening would only approximate. On sendmail 8.9.3 the tool gave 44 probable warnings; 4 were real off-by-one bugs and the rest were false alarms. It also found new overruns in the Linux net tools and several overruns in the older sendmail 8.7.5. Later work added flow sensitivity, pointer analysis, linear programming and contracts.

References

  1. David Wagner, Jeffrey S. Foster, Eric A. Brewer and Alexander Aiken, A first step towards automated detection of buffer overrun vulnerabilities, NDSS 2000, Section 3 (the string model and Table 1 of constraints), Section 4 (the constraint solver, Theorems 1 and 2, Figure 4), Section 5 (the experience with sendmail and the false alarm estimates of Table 2) and Appendix A
  2. Patrick Cousot and Radhia Cousot, Abstract interpretation: a unified lattice model for static analysis of programs by construction or approximation of fixpoints, POPL 1977, the interval example and the widening that makes an analysis with infinite ascending chains stop
  3. Laszlo Szekeres, Mathias Payer, Tao Wei and Dawn Song, SoK, eternal war in memory, 2013 IEEE Symposium on Security and Privacy, pages 48-62, the attack model of memory corruption and the place of spatial memory errors in it

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