Mini Project: Audit a Seeded Toy Program
This project puts the whole course to work on one small program. labcfg is a toy configuration table: it parses up to eight name=value lines, stores the names in fixed buffers and the values on the heap, can log a value and clear the table. It was written for this lesson with seven seeded memory-safety bugs and has nothing to do with any real software. Your job is a professional audit: find the bugs with compiler warnings, sanitizers and review; classify each with its CWE and a severity; fix each one; prove the fixes with regression tests; and write the audit report. Everything runs in your own sandbox against your own toy, which is the only kind of target this course ever uses (Authorization and Scope).
The method
- Read the code once before running anything, and write down what looks suspicious. Review finds what tools can't prove.
- Compile with warnings (
-Wall -Wextra -Wformat=2 -Wconversion): cheap, and they point at lines. - Run each behaviour under ASan + UBSan, one scenario per run, because the first report stops the program. Treat "no report" as "not found yet", not "safe".
- Fix one bug at a time and run again: the first bug often hides the others.
- Write a regression test per finding, including the boundary values.
- Write the report with the template below.
Steps 1 to 4: finding the bugs
The program is in labcfg.c; scenarios.c is a small driver whose argument selects one behaviour: a normal entry, a long name, nine entries, a plain value, a value containing format directives, and clearing twice. The session runs the warnings, then every scenario under the sanitizers, then fixes the first finding and runs everything again. It runs in your sandbox:
cat > labcfg.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* labcfg: a toy configuration table of up to 8 "name=value" entries. Seeded bugs: lab use only. */
struct entry { char name[16]; char *value; };
struct table { struct entry e[8]; int count; };
int table_add(struct table *t, const char *line) {
const char *eq = strchr(line, '=');
if (!eq) return -1;
int n = eq - line;
if (t->count > 8) return -1; /* table full? */
memcpy(t->e[t->count].name, line, n);
t->e[t->count].name[n] = '\0';
t->e[t->count].value = malloc(strlen(eq + 1));
strcpy(t->e[t->count].value, eq + 1);
t->count++;
return 0;
}
void table_log(const struct table *t, int i) {
printf(t->e[i].value);
printf("\n");
}
void table_clear(struct table *t) {
for (int i = 0; i < t->count; i++)
free(t->e[i].value);
}
SRC
cat > scenarios.c <<'SRC'
#include <stdio.h>
#include <string.h>
struct entry { char name[16]; char *value; };
struct table { struct entry e[8]; int count; };
int table_add(struct table *t, const char *line);
void table_log(const struct table *t, int i);
void table_clear(struct table *t);
int main(int argc, char **argv) {
setvbuf(stdout, NULL, _IONBF, 0);
struct table t = {0};
const char *s = argc > 1 ? argv[1] : "normal";
if (!strcmp(s, "normal")) { table_add(&t, "host=lab.test"); table_log(&t, 0); table_clear(&t); }
if (!strcmp(s, "longname")) { table_add(&t, "a-very-long-setting-name=1"); }
if (!strcmp(s, "many")) { char l[16]; for (int i = 0; i < 9; i++) { snprintf(l, sizeof l, "k%d=v", i); table_add(&t, l); } }
if (!strcmp(s, "value")) { table_add(&t, "port=8080"); table_clear(&t); }
if (!strcmp(s, "format")) { table_add(&t, "motd=%p %p %p"); table_log(&t, 0); table_clear(&t); }
if (!strcmp(s, "clear2")) { table_add(&t, "x=1"); table_clear(&t); table_clear(&t); }
puts("done");
return 0;
}
SRC
run_all() {
gcc -g -O0 -fsanitize=address,undefined -fno-sanitize-recover=undefined labcfg.c scenarios.c -o audit 2>/dev/null
for s in normal longname many value format clear2; do
./audit $s > out.txt 2>&1
kind=$(grep -m1 -E 'ERROR: |runtime error: ' out.txt | sed -E 's/.*(ERROR: |runtime error: )//; s/ on (address )?0x.*//')
loc=$(grep -m1 -oE 'labcfg.c:[0-9]+' out.txt)
printf "%-9s %s\n" $s "${kind:-no report}${loc:+ at $loc}"
done
}
echo "== 1. compiler warnings"
gcc -Wall -Wextra -Wformat=2 -Wconversion -O2 -c labcfg.c -o /dev/null 2>&1 | grep ': warning' | sed 's/^labcfg.c://'
echo "== 2. sanitizers, one scenario per run"
run_all
echo "== 3. after fixing F1 (malloc without room for the NUL), run again"
sed -i 's|malloc(strlen(eq + 1));|malloc(strlen(eq + 1) + 1); /* F1 fixed */|' labcfg.c
run_all
echo "== 4. the format scenario has no sanitizer report; look at its output"
./audit format | head -1 | awk '{print NF " values printed for the message \"%p %p %p\": " ($1 ~ /^0x|nil/ ? "memory contents leaked" : "ok")}'== 1. compiler warnings
12:13: warning: conversion from ‘long int’ to ‘int’ may change value [-Wconversion]
14:39: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]
23:5: warning: format not a string literal and no format arguments [-Wformat-security]
== 2. sanitizers, one scenario per run
normal AddressSanitizer: heap-buffer-overflow at labcfg.c:17
longname index 24 out of bounds for type 'char [16]' at labcfg.c:15
many AddressSanitizer: heap-buffer-overflow at labcfg.c:17
value AddressSanitizer: heap-buffer-overflow at labcfg.c:17
format AddressSanitizer: heap-buffer-overflow at labcfg.c:17
clear2 AddressSanitizer: heap-buffer-overflow at labcfg.c:17
== 3. after fixing F1 (malloc without room for the NUL), run again
normal no report
longname index 24 out of bounds for type 'char [16]' at labcfg.c:15
many index 8 out of bounds for type 'entry [8]' at labcfg.c:14
value no report
format no report
clear2 AddressSanitizer: attempting double-free at labcfg.c:29
== 4. the format scenario has no sanitizer report; look at its output
3 values printed for the message "%p %p %p": memory contents leaked
What the tools found, and what they didn't
Work through the output before reading on, then compare with this list.
- Run 2: one bug hides five. Every scenario that stores a value stops at
labcfg.c:17, thestrcpyintomalloc(strlen(eq + 1)): F1, no room for the NUL (a heap off-by-one, CWE-193 / CWE-122). Onlylongnamegets past it, because a different bug stops it earlier. longname: UBSan, not ASan.index 24 out of bounds for type 'char [16]'at line 15: F2, the name length is never checked, somemcpyat line 14 writes 24 bytes into a 16-bytename. ASan stays quiet becausenameis inside a larger object (the whole table): an intra-object overflow into thevaluepointer and the next entry. UBSan's bounds check onname[n]caught it (CWE-787).- Run 3, after fixing F1:
manyreportsindex 8 out of bounds for type 'entry [8]'at line 14: F3,if (t->count > 8)lets a ninth entry in (off-by-one, CWE-193, writing past the array, CWE-787).clear2reportsattempting double-freeat line 29: F5,table_clearfrees but keepscountand the pointers, so a second clear frees again (CWE-415). - No sanitizer saw F4. The format scenario ran cleanly, yet printed three values for a message whose text was
%p %p %p:table_logcallsprintf(t->e[i].value), a format string bug (CWE-134). The compiler had warned at line 23 (-Wformat-security). - Warnings found two more.
-Wconversionat line 12: the pointer difference is stored in anint(F6, truncation, CWE-197; harmless for short lines, a bug for multi-gigabyte input). The-Wsign-conversionat line 14 is the same value used as asize_t. - Review finds the last one.
malloc's result is used without a check (F7, CWE-690). Under memory pressure,strcpywould write to address 0. Also noted in review:table_logdoesn't check its index.
Step 5: the fixed version and its regression tests
Each fix is marked with its finding number. The test file has one check per finding, plus the boundary cases (a 15-character name fits, a 16-character name doesn't; exactly 8 entries fit). The session compiles the fixed library with the same warning flags (counting the warnings) and runs the tests under ASan and UBSan:
cat > labcfg.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* labcfg 1.1: fixed version. Findings F1-F7 refer to the audit report. */
struct entry { char name[16]; char *value; };
struct table { struct entry e[8]; int count; };
#define TABLE_MAX (int)(sizeof ((struct table *)0)->e / sizeof ((struct table *)0)->e[0])
int table_add(struct table *t, const char *line) {
const char *eq = strchr(line, '=');
if (!eq) return -1;
size_t n = (size_t)(eq - line); /* F6: size_t, no narrowing */
if (t->count >= TABLE_MAX) return -1; /* F3: >=, not > */
if (n == 0 || n >= sizeof t->e[0].name) return -1; /* F2: name must fit with its NUL */
char *v = malloc(strlen(eq + 1) + 1); /* F1: room for the NUL */
if (!v) return -1; /* F7: check malloc */
memcpy(t->e[t->count].name, line, n);
t->e[t->count].name[n] = '\0';
strcpy(v, eq + 1); /* fits: allocated strlen + 1 */
t->e[t->count].value = v;
t->count++;
return 0;
}
int table_log(const struct table *t, int i) {
if (i < 0 || i >= t->count) return -1; /* bounds-check the index */
printf("%s\n", t->e[i].value); /* F4: constant format */
return 0;
}
void table_clear(struct table *t) {
for (int i = 0; i < t->count; i++) {
free(t->e[i].value);
t->e[i].value = NULL;
}
t->count = 0; /* F5: idempotent */
}
SRC
cat > test_labcfg.c <<'SRC'
#include <stdio.h>
#include <string.h>
struct entry { char name[16]; char *value; };
struct table { struct entry e[8]; int count; };
int table_add(struct table *t, const char *line);
int table_log(const struct table *t, int i);
void table_clear(struct table *t);
static int fails;
#define CHECK(cond, what) do { if (!(cond)) { printf("FAIL %s\n", what); fails++; } } while (0)
int main(void) {
struct table t = {0};
CHECK(table_add(&t, "host=lab.test") == 0 && !strcmp(t.e[0].value, "lab.test"), "normal pair");
CHECK(table_add(&t, "0123456789abcde=x") == 0, "F2: 15-char name fits");
CHECK(table_add(&t, "0123456789abcdef=x") == -1, "F2: 16-char name rejected");
CHECK(table_add(&t, "a-very-long-setting-name=1") == -1, "F2: long name rejected");
CHECK(table_add(&t, "=x") == -1, "empty name rejected");
table_clear(&t);
char l[16]; int added = 0;
for (int i = 0; i < 9; i++) { snprintf(l, sizeof l, "k%d=v", i); added += table_add(&t, l) == 0; }
CHECK(added == 8, "F3: exactly 8 entries accepted");
CHECK(table_log(&t, 8) == -1, "log index 8 rejected");
table_clear(&t);
table_add(&t, "motd=%p %p %p");
CHECK(table_log(&t, 0) == 0, "F4: format directives printed as text");
table_clear(&t);
table_clear(&t); /* F5: second clear is harmless */
CHECK(t.count == 0, "F5: clear resets count");
printf("%s (%d failures)\n", fails ? "TESTS FAILED" : "all tests passed", fails);
return fails != 0;
}
SRC
gcc -Wall -Wextra -Wformat=2 -Wconversion -O2 -c labcfg.c -o /dev/null 2>&1 | grep -c ': warning'
gcc -g -O0 -fsanitize=address,undefined -fno-sanitize-recover=undefined labcfg.c test_labcfg.c -o test && ./test 2>&1
echo "exit code: $?"0
%p %p %p
all tests passed (0 failures)
exit code: 0
Zero warnings, all tests passed under the sanitizers, and the format test printed %p %p %p literally. Note how the fixes follow the course's patterns rather than patching each crash site: sizes in size_t (Signedness), the table size derived from the array instead of a second literal 8 (Off-by-One), the value allocated and checked before anything is written (Safe C Patterns), a constant format (Format Strings), and an idempotent clear (Double Free).
Step 6: the audit report
Write the report for two readers: a manager who needs to know how bad it is and what to do, and an engineer who needs to reproduce and fix each finding. Use this template, and fill every field:
# Memory-safety audit: labcfg 1.0
**Scope:** labcfg.c (30 lines) at version 1.0, built with gcc 13.3 / clang 18 on x86-64 Linux.
**Method:** code review; -Wall -Wextra -Wformat=2 -Wconversion; ASan + UBSan on 6 scenarios; fixes verified with regression tests.
**Authorization:** own lab code, no third-party systems involved.
## Summary
7 findings: 5 high (three out-of-bounds writes, a double free, a format string),
2 low (truncation, unchecked malloc). All fixed in 1.1; regression tests added.
## Findings
| ID | Title | CWE | Severity | Location | Found by | Status |
|----|-------|-----|----------|----------|----------|--------|
| F1 | Heap overflow: value allocated without room for NUL | CWE-122, CWE-193 | High | labcfg.c:16-17 | ASan | Fixed |
| F2 | Name copied without length check | CWE-787 | High | labcfg.c:14-15 | UBSan | Fixed |
| ... | | | | | | |
## Finding F1 (one section per finding)
- **Description:** what is wrong, in one paragraph.
- **Impact:** what an attacker who controls the input could do (memory write of N bytes, leak, crash).
- **Reproduction:** the scenario or input, the command, the sanitizer line.
- **Root cause:** the line and the missing invariant.
- **Fix:** the change, and why it is complete (variant analysis done?).
- **Regression test:** the test name and the boundary values it covers.
## Recommendations
Build flags, CI sanitizer jobs, a fuzz target for table_add, banned-function header.Severity in this toy is a judgement: a configuration file is usually trusted input, which lowers the real risk. Say so in the report; an audit that rates everything "critical" is as useless as one that rates nothing.
Going further
- Write a libFuzzer target for
table_add+table_log(Sanitizers in CI and Fuzzing) and run it against the original version: how long until it finds F1, F2 and F3? - Build the original with
-O2and no sanitizers, then check which findings FORTIFY or the canary would have stopped in production (FORTIFY_SOURCE, Mitigations Compared). - Rewrite
labcfgin Rust with aVec<(String, String)>capped at 8 entries (Rust). Which findings become impossible, and which (the format string? the cap?) still need a deliberate decision?
Checklist
Did your audit cover everything?
- Seven findings, each with a CWE, a severity with a reason, a location and the tool (or review) that found it.
- The observation that F1 hid other findings, and the second run after fixing it.
- F2 explained as an intra-object overflow that ASan can't see.
- F4 found by a warning and by reading the output, not by a sanitizer.
- One regression test per finding, with the boundary cases 15/16 characters and 8/9 entries.
- The fixed version compiles with zero warnings and passes under ASan and UBSan.
- Recommendations that prevent the next bug, not only the seven you found.
Test yourself
Why did five of the six scenarios report the same bug in the first run?
- They all had the same input
- F1 (malloc without room for the NUL) runs in every scenario that stores a value and stops the program first
- ASan only reports one bug per file
- UBSan was off
Why did ASan not report the long name (F2)?
- It wasn't a bug
- The overflow stayed inside the larger table object (an intra-object overflow); UBSan's bounds check on name[n] caught it
- ASan was disabled
- memcpy is not intercepted
Which finding did no sanitizer detect?
- F1
- F3
- F4, the format string
- F5, the double free
Why does each regression test include boundary values such as 15 and 16 characters?
- For speed
- Off-by-one mistakes live exactly at the boundary; a test with only a long input would miss a > vs >= error
- The compiler needs them
- To fill the table