Variant Analysis: Finding a Bug's Siblings
You have just fixed the stack overflow in rec_name. The obvious question that too many fixes skip: where else does this code base make the same mistake? Developers copy patterns, and a missing check in one handler is usually missing in its siblings too. Attackers know it as well: when a security fix is published, the first thing a careful reader does is look for the variants the fix missed. Google Project Zero's yearly reviews of zero-days exploited in the wild have repeatedly found that a large share were variants of bugs fixed before; for 2022 the review counted 17 of 41 in-the-wild zero-days, over 40%, as variants of previously reported bugs. Variant analysis is the disciplined search for those siblings, done by the defender first.
From one bug to a pattern
Variant analysis starts from a root cause you fully understand and generalises it, step by step:
- State the root cause precisely. Not "overflow in rec_name", but "a length read from input is used as a
memcpysize into a fixed-size local array without being compared with that array's size". - Turn it into a pattern. Source (length from input), sink (
memcpyinto a fixed array), missing guard (comparison withsizeof). - Search with the cheapest tool that expresses the pattern:
grep, a script, a Semgrep rule, a CodeQL query (previous lesson). - Triage each hit by reading it: real variant, safe, or a different mistake the search revealed.
- Widen the pattern carefully (other copy functions, other buffers, other projects that share the code) and repeat until the hits stop being interesting.
A pattern search in Python
The toy code base has the fixed rec_name and four relatives in two other files. The script finds each function, collects its fixed-size char arrays, and for every memcpy into one of them checks what the copy length was compared with before the copy. It runs in your browser:
import re
# A toy code base: the fixed function and its relatives. (Strings, not real files.)
FILES = {
"tlv.c": """
static int rec_name(const uint8_t *v, size_t len) {
char name[16];
if (len > sizeof name) return -1; /* the fix for the reported bug */
memcpy(name, v, len);
return name[0];
}
""",
"tags.c": """
static int rec_tag(const uint8_t *v, size_t len) {
char tag[8];
memcpy(tag, v, len);
return tag[0] == '#';
}
static int rec_lang(const uint8_t *v, size_t len) {
char lang[4];
size_t n = len < sizeof lang ? len : sizeof lang;
memcpy(lang, v, n);
return lang[0];
}
""",
"meta.c": """
static int rec_author(const uint8_t *v, size_t len, char *out) {
char author[32];
if (len >= sizeof author) return -1;
memcpy(author, v, len);
author[len] = 0;
return copy_out(out, author);
}
static int rec_title(const uint8_t *v, size_t len) {
char title[24];
if (len > 64) return -1; /* a check, but against the wrong limit */
memcpy(title, v, len);
return title[0];
}
""",
}
FUNC = re.compile(r"^static int (\w+)\(.*?^}", re.S | re.M)
ARRAY = re.compile(r"char (\w+)\[(\d+)\];")
COPY = re.compile(r"memcpy\((\w+), \w+, (\w+)\);")
def verdict(body, buf, size, length):
"""Is `length` bounded by `buf`'s size before the copy?"""
before = body[:body.index("memcpy(" + buf)]
if re.search(rf"{length}\s*[<>]=?\s*sizeof {buf}", before) or re.search(rf"{length} = .*sizeof {buf}", before):
return "checked against sizeof"
m = re.search(rf"{length}\s*>=?\s*(\d+)", before)
if m:
return f"checked against {m.group(1)}, buffer holds {size}" + (" <-- WRONG LIMIT" if int(m.group(1)) > int(size) else "")
return "NOT CHECKED <-- variant"
for fname, src in FILES.items():
for f in FUNC.finditer(src):
body, arrays = f.group(0), dict(ARRAY.findall(f.group(0)))
for buf, length in COPY.findall(body):
if buf in arrays:
print(f"{fname:<7} {f.group(1):<11} memcpy({buf}[{arrays[buf]}], ..., {length}): {verdict(body, buf, arrays[buf], length)}")tlv.c rec_name memcpy(name[16], ..., len): checked against sizeof
tags.c rec_tag memcpy(tag[8], ..., len): NOT CHECKED <-- variant
tags.c rec_lang memcpy(lang[4], ..., n): checked against sizeof
meta.c rec_author memcpy(author[32], ..., len): checked against sizeof
meta.c rec_title memcpy(title[24], ..., len): checked against 64, buffer holds 24 <-- WRONG LIMIT
Five copies, three kinds of result:
rec_name(the fixed bug),rec_lang(clamps the length tosizeof lang) andrec_author(checkslen >= sizeof author, leaving room for the terminator) are safe.rec_tagis the exact variant: an 8-byte array and an unchecked length. It needs the same fix and its own report or advisory entry.rec_titleis the interesting one: it has a check, so a reviewer skimming for "is there an if?" would pass it. But it compares with 64 while the buffer holds 24. Lengths 25 to 64 overflow. A check against the wrong constant is a classic variant that pure "missing check" searches miss; the script found it only because it compares the limit with the array size.
Where variant analysis goes next
| Widening step | Example |
|---|---|
| other sinks with the same meaning | memmove, strncpy, read(fd, buf, len), loops that copy byte by byte |
| other buffer kinds | struct fields, heap buffers with a size stored elsewhere |
| other sources | lengths from network headers, environment variables, IPC |
| other code bases | forks, vendored copies, other parsers of the same format, the same developer's other projects |
| other languages | copy_from_slice panics in Rust, System.arraycopy exceptions in Java: the same logic error, a different failure |
For large code bases this is where CodeQL shines: the data-flow query follows the length from any input source to any copy. For patch analysis, the same thinking applies in reverse: read a security fix, state what it assumes, and check whether every path that reaches the bug goes through the fix. Incomplete fixes are a common source of second CVEs for the same bug.
How variants are detected in practice, and prevented
- Make the search a rule. Once the pattern is right, add it to CI (Semgrep or CodeQL), so a new sibling is flagged in review before it merges.
- Fix the class, not just the instances. Replace raw
memcpywith a helper that takes both sizes (copy_bounded(dst, sizeof dst, src, len)) and returns an error, and ban the raw call in parsers with a rule. The variants then disappear structurally. - Report variants together. A vendor prefers one advisory for "five handlers trusted the record length" over five surprises spread over a year. If the variants are found after the first fix shipped, say so in the new report.
Pitfalls
- Searching for the crash site instead of the root cause.
grep memcpyreturns everything; the root cause tells you which ones matter. - Trusting the presence of a check.
rec_titlechecks the wrong limit. Read every condition. - Stopping at one repository. Code is copied into forks, firmware SDKs and vendored dependencies; the advisory should say which.
- Regex limits. The script handles this toy's formatting, not C in general (macros, multi-line calls, aliases). Use a parser-based tool for real code.
Practice
1. Extend the script to report strncpy(buf, src, n) with the same verdicts.
Add a second sink regex, strncpy\((\w+), \w+, (\w+)\);, and run the same verdict for its matches. (Remember that strncpy with n == sizeof buf does not terminate the string: a different bug, worth its own check.)
2. Fix rec_title and explain why the fix should use sizeof rather than 24.
if (len > sizeof title) return -1; stays correct if someone later changes the array size; a literal 24 (or 64) can drift from the declaration, which is exactly how the bug happened.
3. The vendor fixed rec_tag after your report but not rec_title. What do you do?
Report rec_title privately as an incomplete fix or new variant, reference the earlier report, and give the same disclosure timeline. Do not publish details of the unfixed variant with the first advisory.
Test yourself
What is the starting point of variant analysis?
- A random file
- A precisely stated root cause of a known bug
- A fuzzer corpus
- A CVSS score
Why is rec_title a variant even though it has an if statement?
- It uses memcpy
- It compares the length with 64 while the buffer holds 24
- It is in another file
- It returns title[0]
Which step removes a whole class of variants for good?
- Fixing each instance
- A bounded-copy helper that takes both sizes, enforced by a CI rule
- Longer fuzzing
- Renaming functions