Memory Safety Exercises
These exercises revisit every section of the course. Try each one before opening the answer; most answers link back to the lesson that explains them. Two of them run code: a sandbox session with two bug classes you haven't met in this exact form, and a small Python triage tool.
Reading reports
1. A report reads heap-buffer-overflow … READ of size 8 … 0 bytes after 24-byte region … allocated by … parse.c:40. What happened, and what do you check first at parse.c:40?
Answer
An 8-byte read (a pointer or long) right after the end of a 24-byte heap block. At line 40, check how the size was computed: a count * sizeof(T) that is one element short, or a size computed from a different length than the one used for the loop (Reading Sanitizer Reports, Off-by-One).
2. What does a shadow line fa fa 00 00 04 fa tell you about the block in the middle?
Answer
It is 8 + 8 + 4 = 20 bytes long: two full granules and one with 4 addressable bytes, surrounded by heap red zones (fa).
3. Run it. Predict, before reading the output, what ASan says for each scenario of this program: g copies a long string into a global buffer, r uses a pointer to a local array after its function returned. The session builds it with GCC, and the r case again with Clang:
cat > ex.c <<'SRC'
#include <stdio.h>
#include <string.h>
static char banner[8] = "lab"; /* a global buffer */
static const char *greeting(void) {
char msg[16];
snprintf(msg, sizeof msg, "hi %s", banner);
return msg; /* returns the address of a local */
}
int main(int argc, char **argv) {
setvbuf(stdout, NULL, _IONBF, 0);
if (argc > 1 && argv[1][0] == 'g')
strcpy(banner, "lab.test.example"); /* 16 characters + NUL into 8 bytes */
if (argc > 1 && argv[1][0] == 'r') {
const char *g = greeting();
printf("%c\n", g[0]);
}
return 0;
}
SRC
gcc -g -O0 -fsanitize=address ex.c -o ex 2>/dev/null
echo "== ./ex g"
./ex g 2>&1 | grep -E 'ERROR|WRITE|#[01] .*ex.c|located|global variable'
echo "== ./ex r (gcc build, then clang build)"
./ex r 2>&1 | grep -m1 -oE 'AddressSanitizer: SEGV on unknown address 0x0+'
clang -g -O0 -fsanitize=address ex.c -o ex-clang 2>/dev/null
ASAN_OPTIONS=detect_stack_use_after_return=1 ./ex-clang r 2>&1 | grep -E "ERROR|READ|#0 .*ex.c|located|<== Memory"== ./ex g
==16==ERROR: AddressSanitizer: global-buffer-overflow on address 0x5f866d8e8028 at pc 0x73df4d7ff303 bp 0x7ffe25d618b0 sp 0x7ffe25d61058
WRITE of size 17 at 0x5f866d8e8028 thread T0
#1 0x5f866d8e5494 in main /home/learner/ex.c:15
0x5f866d8e8028 is located 0 bytes after global variable 'banner' defined in 'ex.c:4:13' (0x5f866d8e8020) of size 8
== ./ex r (gcc build, then clang build)
AddressSanitizer: SEGV on unknown address 0x000000000000
==23==ERROR: AddressSanitizer: stack-use-after-return on address 0x76b71a700020 at pc 0x63da306c88d2 bp 0x7ffc8b6a63c0 sp 0x7ffc8b6a63b8
READ of size 1 at 0x76b71a700020 thread T0
#0 0x63da306c88d1 in main /home/learner/ex.c:18:24
Address 0x76b71a700020 is located in stack of thread T0 at offset 32 in frame
#0 0x63da306c88ff in greeting /home/learner/ex.c:6
[32, 48) 'msg' (line 7) <== Memory access at offset 32 is inside this variable
Answer
g: global-buffer-overflow, WRITE of size 17 (16 characters + NUL), 0 bytes after global variable 'banner' … of size 8: globals get red zones too. r with GCC: a SEGV on unknown address 0x000…: GCC knows greeting returns the address of a local (it warns with -Wreturn-local-addr) and deliberately returns NULL instead, so the bug becomes a NULL dereference. With Clang and detect_stack_use_after_return=1, ASan keeps the dead frame poisoned and reports stack-use-after-return: a read inside this variable 'msg' of the frame of greeting, which has already returned: a use-after-return (CWE-562), the stack version of use-after-free.
Memory layout
4. In the stack-frame model, how many bytes must an unbounded copy write (including the NUL) to change the first byte of the saved frame pointer?
Answer
33: the saved rbp starts at offset 32, so a 32-character string's NUL lands there. 32 characters + NUL = 33 bytes.
5. Why does malloc(24) followed by malloc(24) place the second block 32 bytes after the first on glibc?
Answer
Each chunk is 32 bytes: an 8-byte size field plus 24 usable bytes (the minimum chunk). See The Heap.
Bug classes
6. For each snippet name the bug class and the CWE:
(a) char *p = malloc(n); … free(p); … if (p->flag);
(b) uint16_t len = hdr + body_len; char *b = malloc(len); memcpy(b + hdr, body, body_len);;
(c) syslog(LOG_INFO, user_msg);;
(d) Image *im = static_cast<Image *>(node); with node from a file;
(e) int n = read_count(); if (n > MAX) return; memcpy(dst, src, n);.
Answer
(a) use-after-free, CWE-416. (b) truncation to 16 bits, then heap overflow: CWE-197 → CWE-122. (c) format string, CWE-134. (d) type confusion, CWE-843. (e) signedness: a negative n passes the check and becomes a huge size_t, CWE-195 → CWE-787 (Signedness).
7. Heartbleed was an out-of-bounds read. Why did the response include revoking certificates?
Answer
The over-read could have copied private keys out of server memory without leaving a trace, so every key that was in memory had to be treated as stolen (Out-of-Bounds Reads).
8. Which tool would you use for each: uninitialised read; data race; leak on an error path; unsigned wraparound in a size?
Answer
MSan (or Valgrind), TSan, LSan (with ASan), Clang's -fsanitize=unsigned-integer-overflow plus ASan for the resulting overflow.
Mitigations
9. Fill in: canaries stop ___; NX stops ___; ASLR is defeated by ___; full RELRO protects ___; CFI restricts ___; a shadow stack protects ___.
Answer
Linear stack overwrites of the return address; executing injected code; an information leak; the GOT; indirect calls and jumps (forward edges); returns (backward edges). See Mitigations Compared.
10. A build script adds -no-pie "for a profiler". Which two checksec columns change on Ubuntu?
Answer
PIE (No PIE) and RELRO (Partial RELRO), because Ubuntu's GCC passes -z now only with PIE.
11. Which FORTIFY level is the lowest that catches a strcpy overflow of malloc(n) with n known only at run time?
Answer
Level 3, which uses __builtin_dynamic_object_size (FORTIFY_SOURCE).
Triage in Python
12. Write a function that reads the first line of sanitizer reports and returns the CWE and a first severity guess (writes and frees above reads, reads above leaks). A starting point, run on headline lines taken from this course's sessions:
import re
RULES = [ # (pattern in the headline, CWE, base severity)
(r"stack-buffer-overflow", "CWE-121", 3), (r"heap-buffer-overflow", "CWE-122", 3),
(r"global-buffer-overflow", "CWE-787", 3), (r"heap-use-after-free", "CWE-416", 3),
(r"double-free", "CWE-415", 3), (r"negative-size-param", "CWE-195", 3),
(r"use-of-uninitialized-value", "CWE-457", 2), (r"detected memory leaks", "CWE-401", 1),
(r"data race", "CWE-362", 2),
]
LEVEL = {3: "high", 2: "medium", 1: "low"}
def triage(headline, access=None):
for pat, cwe, sev in RULES:
if re.search(pat, headline):
if access == "READ" and sev == 3:
sev = 2 # an over-read leaks; a write corrupts
return cwe, LEVEL[sev]
return "unknown", "needs a human"
reports = [
("ERROR: AddressSanitizer: heap-buffer-overflow on address 0x...", "WRITE"),
("ERROR: AddressSanitizer: heap-buffer-overflow on address 0x...", "READ"),
("ERROR: AddressSanitizer: attempting double-free on 0x...", None),
("ERROR: LeakSanitizer: detected memory leaks", None),
("WARNING: MemorySanitizer: use-of-uninitialized-value", None),
("ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000", "READ"),
]
for headline, access in reports:
cwe, sev = triage(headline, access)
print(f"{headline[:60]:60} {access or '':5} -> {cwe:8} {sev}")ERROR: AddressSanitizer: heap-buffer-overflow on address 0x. WRITE -> CWE-122 high
ERROR: AddressSanitizer: heap-buffer-overflow on address 0x. READ -> CWE-122 medium
ERROR: AddressSanitizer: attempting double-free on 0x... -> CWE-415 high
ERROR: LeakSanitizer: detected memory leaks -> CWE-401 low
WARNING: MemorySanitizer: use-of-uninitialized-value -> CWE-457 medium
ERROR: AddressSanitizer: SEGV on unknown address 0x000000000 READ -> unknown needs a human
Answer and extensions
The SEGV is "unknown" on purpose: a crash without a classification (a NULL dereference, or a wild pointer that might be attacker-controlled) needs a human. Extensions: parse the access line (READ of size N) yourself instead of passing it in; raise the severity when the size is large or input-controlled; group reports by the first frame in your own code to deduplicate (Why Memory Safety).
Safer code and fixing
13. Rewrite char *join(const char *a, const char *b) { char *r = malloc(strlen(a) + strlen(b)); strcpy(r, a); strcat(r, b); return r; } safely.
Answer
Compute size_t la = strlen(a), lb = strlen(b), n; and check ckd_add(&n, la, lb) || ckd_add(&n, n, 1); allocate n, check for NULL, memcpy(r, a, la); memcpy(r + la, b, lb + 1);. Or snprintf(NULL, 0, "%s%s", a, b) to size it, as in Off-by-One.
14. A fix adds a length check right before the memcpy that crashed. Name two things the reviewer should still ask.
Answer
Are there other uses of the same unchecked length (variant analysis)? Is there a regression test with the reproducer and the boundary values? Also: which versions are affected, and is an advisory needed (From Crash to Patch)?
Test yourself
Which ASan report kind did the global buffer in exercise 3 produce?
- heap-buffer-overflow
- global-buffer-overflow
- stack-buffer-overflow
- SEGV
Why did the GCC build of the use-after-return case crash at address 0?
- ASan bug
- GCC replaces a returned address of a local with NULL, turning the bug into a NULL dereference
- The stack was full
- ASLR
Which triage rule in exercise 12 reflects that over-reads are usually less severe than over-writes?
- SEGV is unknown
- A READ access lowers a high base severity to medium
- Leaks are low
- Races are medium
Which mitigation protects returns rather than indirect calls?
- Clang CFI
- Control Flow Guard
- Shadow stack
- IBT