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
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 by two integers: , the number of bytes allocated, and , 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 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 "": every value that the expression can take must be in the range of the variable . The table lists the constraints of the toy language, taken from Table 1 of the paper. A range is a set of integers, where can be .
| statement | constraint |
|---|---|
char s[n] |
|
strcpy(s, "...") with characters |
|
fgets(s, n, f) |
|
gets(s) |
|
strcpy(d, s) |
|
strncpy(d, s, n) |
|
strcat(d, s) |
|
strncat(d, s, n) |
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 , with and (take for strcat), is a cycle: the variable is on both sides. A plain round of updates on the constraints and gives , then , then , and never stops. The paper calls this counting to infinity. Its fix is exact, not a widening: if is not empty and the largest value of is positive, every solution has (their Lemma 1). Line L6 applies this rule.
DETECT-OVERRUNS(P) ▷ P: the declarations and string calls of a program- 1
C ← the constraints of the statements of P, one per statement - 2
for each buffer s: len(s) ← ∅, alloc(s) ← ∅ - 3
repeat - 4
changed ← false - 5
for each constraint e ⊆ v in C do - 6
if e = v + g(w), v ≠ ∅, w ≠ ∅ and sup g(w) > 0 then r ← [inf v, +∞] ▷ the cycle rule - 7
else r ← the range of e under the current ranges - 8
if r ⊄ v then v ← hull(v, r), changed ← true - 9
until not changed - 10
for each buffer s with len(s) = [a, b] and alloc(s) = [c, d] do - 11
report safe if b ≤ c, certain overrun if a > d, and possible overrun otherwise
Line L7 uses interval arithmetic: and , 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] |
, , , |
fgets(name, 16, f) |
|
strcpy(buf, "hello") |
|
strncpy(out, name, 8) |
|
strcat(buf, name) |
|
strcpy(tag, "error") |
The first round of lines L3 to L9 sets the alloc ranges, then and . The strncpy constraint gives . The strcat constraint is a cycle with , so line L6 sets . Then . A second round changes nothing. Lines L10 and L11 give:
| buffer | len | alloc | verdict |
|---|---|---|---|
| name | safe, | ||
| out | safe, | ||
| buf | possible overrun, | ||
| tag | certain overrun, |
The warning on buf is a real bug: "hello" with 15 more characters needs 21 bytes. The analysis says 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 is in the range of , 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 with an integer and an integer or . Ranges are ordered by inclusion, and is the hull. A constraint holds for an assignment of ranges to variables if the range of under , computed with interval arithmetic, is a subset of . The three forms are a constant , a copy with or , and a concatenation with , or . The interval operations are and , and both give the empty range if an argument is empty. Both are monotone in each argument.
Let be the set of the integer constants that occur in the constraints, and let be the least assignment that satisfies every constraint. Wagner et al. prove that 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 , every finite upper bound is in , 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 (a literal of characters gives , fgets and gets give 1). A copy gives the bounds and , which are an old bound or the constant . Line L6 keeps the lower bound and sets the upper bound to . 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 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.
Claim 2 (termination and cost). The loop of lines L3 to L9 stops after at most rounds, where is the number of variables. Each round costs for constraints, so the cost is , since .
Proof. A variable only grows, because line L8 replaces by . By Claim 1 its lower bound moves down inside and its upper bound moves up inside , so each of the bounds changes at most times (counting the first change from empty). A round that sets changed to true moves at least one bound, so at most rounds change something, and the next round stops the loop.
Claim 3 (no update overshoots). At every point, .
Proof. At line L2 every range is empty. Suppose before an update of line L8 by a constraint with left side and target . If line L7 computed , then is the range of under , and by monotonicity is a subset of the range of under , which is a subset of , since satisfies the constraint. If line L6 computed , then is nonempty, and . By monotonicity is nonempty and . Let . The constraint gives , which is false for finite . So , and , since . In both cases . This is Lemma 1 of Wagner et al. for the affine function with .
Claim 4 (the result is a solution). When the loop stops, satisfies every constraint.
Proof. In the last round no update changed , so for each constraint the of lines L6 or L7 was a subset of . For a constant or a copy, is the range of under , so the constraint holds. For a concatenation with or empty, the range of is empty. Otherwise with by Claim 1, so with both ends at least 0. If the cycle rule fired, with , and the range of is , since . If it did not fire, , so , and the range of is itself.
Claim 5 (exactness). The ranges returned are .
Proof. By Claim 4 the result satisfies all constraints, so by the minimality of . By Claim 3, .
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 lies in .
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 with the current length of the source, which by induction is in , so the value is in the interval . A concatenation step writes with and in the ranges of the target and the source, so the value is in .
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 and . If some run of Claim 6 writes a length greater than to , the verdict of line L11 is not "safe". If the verdict is "certain overrun", every write to in every such run overruns.
Proof. A written length satisfies by Claim 6, so , and line L11 does not say "safe". If the verdict is "certain", then , and every written length satisfies by Claim 6.
Complexity
In the round-robin form above, a round costs for statements. Every finite bound that a range takes is one of the at most constants of the program, and each of the bounds of the buffers only moves in one direction, so there are at most rounds. The time is and the extra space is .
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")withchar 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 , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JPTZRY Edit this page History Report an error Markdown