From Crash to Patch: Fixing a Memory-Safety CVE
A memory-safety vulnerability usually arrives as a crash: a fuzzer's reproducer, a sanitizer report from CI, a stack trace in a bug report, or an email from a researcher. Between that and a shipped fix lie several decisions that matter as much as the code: what the root cause is (not where the crash is), what the smallest correct change is, how to prove it with a test, how severe it is, who must be told and when. This lesson walks that path once, end to end, on a toy library, and reads the patch the way a reviewer, a distribution maintainer or an attacker reading a security update would. The disclosure side is covered in depth in Security Foundations' Responsible Disclosure and Penetration Testing's CVE, CWE and CPE lesson.
The report
The toy library labkv parses key=value pairs. A fuzzer produced a reproducer and this ASan summary:
==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x… (abridged; the same report appears in the session below)
WRITE of size 20 at 0x… thread T0
#1 in kv_parse labkv.c:9
[32, 48) 'key' (line 5) <== Memory access at offset 48 overflows this variable
reproducer: crash-7e1d… (contents: "AAAAAAAAAAAAAAAAAAAA=1")Triage questions, in order: Is it reproducible? (run the reproducer on the current code under ASan.) What is the root cause? (the frame in kv_parse and the variable list point at key, written by the memcpy at line 9 with a length taken from the input.) What can an attacker control? (the length and content of the key: a write of attacker-chosen length and bytes on the stack, so assume the worst until shown otherwise.) Which versions are affected? (find the commit that introduced the code, e.g. with git log -S or git bisect.)
The fix, as a reviewer sees it
The session writes the vulnerable version, reproduces the bug, writes the fixed version, prints the patch as a unified diff, and runs the regression test against both versions. It runs in your sandbox:
mkdir -p old new
cat > old/labkv.c <<'SRC'
#include <string.h>
/* Copies the key of "key=value" into out (16 bytes). Returns the value, or NULL. */
const char *kv_parse(const char *line, char out[16]) {
char key[16];
const char *eq = strchr(line, '=');
if (!eq) return NULL;
size_t n = (size_t)(eq - line);
memcpy(key, line, n);
key[n] = '\0';
memcpy(out, key, n + 1);
return eq + 1;
}
SRC
sed -e 's| size_t n = (size_t)(eq - line);| size_t n = (size_t)(eq - line);\n if (n >= sizeof key) return NULL; /* reject keys that do not fit (fixes LAB-2026-0001) */|' old/labkv.c > new/labkv.c
cat > test_kv.c <<'SRC'
#include <stdio.h>
#include <string.h>
const char *kv_parse(const char *line, char out[16]);
int main(void) {
char key[16]; int failures = 0;
const char *v = kv_parse("user=alice", key);
if (!v || strcmp(key, "user") || strcmp(v, "alice")) { puts("FAIL normal pair"); failures++; }
if (kv_parse("0123456789abcde=x", key) == NULL) { puts("FAIL 15-char key must fit"); failures++; }
if (kv_parse("AAAAAAAAAAAAAAAAAAAA=1", key) != NULL) { puts("FAIL long key must be rejected"); failures++; } /* the reproducer */
if (kv_parse("0123456789abcdef=x", key) != NULL) { puts("FAIL 16-char key must be rejected"); failures++; } /* the boundary */
printf("%s (%d failures)\n", failures ? "TESTS FAILED" : "all tests passed", failures);
return failures != 0;
}
SRC
echo "== the patch"
diff -u old/labkv.c new/labkv.c | sed '1,2s/\t.*//'
for v in old new; do
gcc -g -O0 -fsanitize=address,undefined test_kv.c $v/labkv.c -o test-$v 2>/dev/null
echo "== regression test against the $v version"
./test-$v 2>&1 | grep -E 'tests passed|TESTS FAILED|FAIL|ERROR' | head -3
done== the patch
--- old/labkv.c
+++ new/labkv.c
@@ -6,6 +6,7 @@
const char *eq = strchr(line, '=');
if (!eq) return NULL;
size_t n = (size_t)(eq - line);
+ if (n >= sizeof key) return NULL; /* reject keys that do not fit (fixes LAB-2026-0001) */
memcpy(key, line, n);
key[n] = '\0';
memcpy(out, key, n + 1);
== regression test against the old version
==22==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7bf7319000f0 at pc 0x7bf73473b303 bp 0x7ffc1ee7bc90 sp 0x7ffc1ee7b438
== regression test against the new version
all tests passed (0 failures)
The old version fails the test with the same ASan report the fuzzer produced; the new one passes all four cases. The test file encodes what was learned: a normal pair, the largest key that fits (15 characters), the reproducer, and the exact boundary (16 characters). The boundary case is what stops a future "fix" from changing >= to >.
Reading a patch like an attacker (and why that matters)
A security fix in an open-source project is public the moment it is committed, often before every user has updated. A two-line patch that adds if (n >= sizeof key) return NULL; before a memcpy tells anyone reading it exactly where the bug was and what input triggers it. Attackers routinely diff releases ("patch diffing", for binaries with tools such as BinDiff) to find fixed bugs and target users who haven't updated. Three consequences for defenders:
- Ship the fix and the advisory together, and coordinate with distributions in advance (for example through the linux-distros list) so packages are ready on disclosure day.
- Don't hide security fixes in unrelated commits: it delays downstream backports and fools nobody who diffs.
- Update quickly when you consume software: the time between a public fix and exploitation can be days.
The advisory
The fix ships with a description that downstream users can act on: which versions are affected, which are fixed, how severe it is, and what to do. Machine-readable formats (OSV, CSAF, CVE JSON 5) let scanners match it against dependency lists automatically. The model builds a minimal OSV-style record for the toy bug (LAB-2026-0001 is a placeholder, not a real identifier: real ones come from a CVE Numbering Authority, such as the project's own CNA or MITRE). It runs in your browser:
import json
advisory = {
"id": "LAB-2026-0001", # placeholder; a real advisory gets a CVE ID from a CNA
"summary": "Stack buffer overflow in kv_parse() with keys of 16 or more bytes",
"details": ("kv_parse() copied the key of a key=value line into a 16-byte stack buffer "
"without checking its length. A line with a key of 16 bytes or more overwrites "
"the stack. Fixed by rejecting keys that do not fit."),
"affected": [{"package": {"name": "labkv", "ecosystem": "Lab"},
"ranges": [{"type": "SEMVER", "events": [{"introduced": "1.0.0"}, {"fixed": "1.4.2"}]}]}],
"database_specific": {"cwe_ids": ["CWE-121", "CWE-787"],
"cvss_v4_vector": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N"},
"references": [{"type": "FIX", "url": "https://git.lab.test/labkv/commit/abc1234"}],
}
def affected(version, adv):
v = tuple(map(int, version.split(".")))
for a in adv["affected"]:
for r in a["ranges"]:
ev = {k: tuple(map(int, val.split("."))) for e in r["events"] for k, val in e.items()}
if ev["introduced"] <= v < ev["fixed"]:
return True
return False
print(json.dumps({k: advisory[k] for k in ("id", "summary")}, indent=2))
for ver in ("0.9.0", "1.0.0", "1.4.1", "1.4.2", "2.0.0"):
print(f"labkv {ver}: {'AFFECTED - upgrade to 1.4.2' if affected(ver, advisory) else 'not affected'}"){
"id": "LAB-2026-0001",
"summary": "Stack buffer overflow in kv_parse() with keys of 16 or more bytes"
}
labkv 0.9.0: not affected
labkv 1.0.0: AFFECTED - upgrade to 1.4.2
labkv 1.4.1: AFFECTED - upgrade to 1.4.2
labkv 1.4.2: not affected
labkv 2.0.0: not affected
The CVSS v4.0 vector says: network-reachable (if kv_parse parses network input), low complexity, no privileges or user interaction, high impact on the vulnerable system's confidentiality, integrity and availability, the usual rating for an attacker-controlled stack write until shown otherwise. Scoring is taught in CVSS v4.0; in a real advisory, score for the realistic deployment and explain the assumptions in the text.
Coordinated disclosure, briefly
When the bug is found by an outside researcher, the usual sequence is: private report to the vendor's security contact (security.txt, a bug-bounty platform, or a security mailing address), acknowledgement, fix and advisory prepared under embargo, coordination with downstream distributors, public release of fix and advisory together, and credit to the reporter. Deadlines keep it moving: Google Project Zero's policy, for example, publishes the details 90 days after the report whether or not a fix has shipped (7 days for bugs exploited in the wild), and its policy page announces shorter windows from 2027. If a bug is being exploited in the wild, timelines shrink to days, and the vulnerability may be added to CISA's Known Exploited Vulnerabilities catalogue.
Pitfalls
- Fixing the symptom. Adding a check at the crash site (here, before the second
memcpy) instead of where the length enters leaves other uses ofnvulnerable. Fix where the invariant is first violated. - No regression test. Without the reproducer in the test suite, refactoring reintroduces the bug; this happens to real projects.
- Incomplete variant analysis. The same mistake is usually made more than once. After a fix, search for the pattern (
memcpyof a length computed from a delimiter into a fixed buffer) across the code base, and fuzz the neighbouring functions. - Silent fixes. Fixing without an advisory leaves downstream users on vulnerable versions without knowing it.
Practice
1. Why does the regression test include both the 15-character and the 16-character key?
They are the two sides of the boundary. 15 characters plus the NUL fill the 16-byte buffer exactly and must work; 16 must be rejected. A test with only the long reproducer would still pass if someone wrote n > sizeof key (an off-by-one that writes the NUL one byte past the end).
2. Which versions does the advisory mark as affected, and why is 2.0.0 not affected?
1.0.0 up to, but not including, 1.4.2 (introduced ≤ v < fixed). 2.0.0 is after the fix in the same range description; if 2.x were a separate branch with the bug, it would need its own range.
3. Do a variant analysis: which other line of the old kv_parse depends on the same unchecked n?
memcpy(out, key, n + 1); writes n + 1 bytes into the caller's 16-byte out. The fix at the source (rejecting n >= 16) covers both writes; a fix only at the first memcpy would not have.
Test yourself
Where should a memory-safety fix go?
- At the line that crashed
- Where the invariant is first violated, e.g. where an untrusted length enters, so every later use is covered
- In the allocator
- In the test suite only
What did the regression test do against the old version?
- Passed
- Failed with the same ASan stack-buffer-overflow the fuzzer found
- Did not compile
- Hung
Why do attackers diff security patches?
- To review code style
- A fix reveals where the bug was and how to trigger it, which can be used against users who haven't updated
- To find licences
- To speed up builds
Who assigns real CVE IDs?
- Anyone
- CVE Numbering Authorities (CNAs), such as vendors' own CNAs or MITRE
- The NVD only
- GitHub only