Mini Project: A Full Research Cycle on a Toy Image Parser
This project puts the whole course together on one target: a small image decoder for a made-up format, LBMP, with two seeded bugs. You will write a harness, fuzz it, triage the crashes, find the root causes, fix them, add regression tests, prove the fix with another campaign, and write the advisory. Do each step yourself first; the sessions below are a reference solution you can compare with, recorded in the course sandbox.
Scope. The target is the toy decoder below, compiled and run in your own sandbox. Nothing else is tested. The "vendor" for the disclosure step is fictional (lab.test); the IDs are placeholders.
The target: LBMP
offset size field
0 4 magic "LBMP"
4 2 width (little-endian u16)
6 2 height (little-endian u16)
8 1 ncolors (at most 16)
9 3*ncolors palette: r, g, b per colour
... w*h one palette index per pixellbmp_decode() validates the magic, the colour count and the palette length, then converts the pixel indices to an RGB buffer. Read it before fuzzing and write down two hypotheses (The Research Workflow); the code is in the first session.
The method
| Step | Course lesson | Output |
|---|---|---|
| 1. hypotheses from review | Code Review | two written hypotheses |
| 2. harness and seed | libFuzzer Harnesses | fuzz_lbmp.c, one valid 2x2 image |
| 3. fuzz and triage | Crash Triage | crash files, buckets, classes |
| 4. root cause | Root-Cause Analysis, Variant Analysis | one root cause per real bug |
| 5. fix and regression tests | libFuzzer, Delta Debugging | patch, tests, clean campaign |
| 6. advisory | Writing an Advisory, Coordinated Disclosure | the advisory text |
Steps 2 and 3: fuzz and triage
The reference session builds the harness with ASan and UBSan (fatal), seeds the corpus with one valid 2x2 image and fuzzes until the first crash (c1). As in the libFuzzer lesson, it then patches that bug locally so the fuzzer can go deeper, and runs three more campaigns with different seeds (c2 to c4). A Python triage script extracts each report's kind and line and decodes the image's width and height from the crash file. It runs in your sandbox:
cat > lbmp.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
/* LBMP, the mini project's toy image format (little-endian):
"LBMP" | width u16 | height u16 | ncolors u8 | ncolors x (r,g,b) | width*height palette indices */
struct image { uint16_t w, h; uint8_t ncolors; uint8_t palette[16][3]; uint8_t *rgb; };
static uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
int lbmp_decode(const uint8_t *d, size_t n, struct image *img) {
if (n < 9 || memcmp(d, "LBMP", 4) != 0) return -1;
img->w = rd16(d + 4);
img->h = rd16(d + 6);
img->ncolors = d[8];
if (img->ncolors > 16) return -1;
size_t pos = 9;
if (n - pos < (size_t)img->ncolors * 3) return -1;
memcpy(img->palette, d + pos, (size_t)img->ncolors * 3);
pos += (size_t)img->ncolors * 3;
uint16_t npix = img->w * img->h; /* number of pixels */
if (n - pos < npix) return -1;
img->rgb = malloc((size_t)npix * 3);
if (!img->rgb) return -1;
for (size_t i = 0; i < (size_t)img->w * img->h; i++) {
uint8_t idx = d[pos + i];
memcpy(img->rgb + 3 * i, img->palette[idx], 3);
}
return 0;
}
SRC
cat > fuzz_lbmp.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
struct image { uint16_t w, h; uint8_t ncolors; uint8_t palette[16][3]; uint8_t *rgb; };
int lbmp_decode(const uint8_t *d, size_t n, struct image *img);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
struct image img = {0};
if (lbmp_decode(data, size, &img) == 0) free(img.rgb);
return 0;
}
SRC
build() { clang -g -O1 -fsanitize=fuzzer,address,undefined -fno-sanitize-recover=undefined lbmp.c fuzz_lbmp.c -o fuzz_lbmp; }
campaign() { # campaign <seed> <name>: fuzz until the first crash (60 s at most), keep input and report
./fuzz_lbmp -seed=$1 -max_total_time=60 corpus > "crashes/$2.log" 2>&1
mv crash-* "crashes/$2"
}
build
mkdir corpus crashes
python3 -c "
import struct, sys
sys.stdout.buffer.write(b'LBMP' + struct.pack('<HHB', 2, 2, 2) + bytes([0, 0, 0, 255, 255, 255]) + bytes([0, 1, 1, 0]))
" > corpus/2x2.lbmp
campaign 1 c1
echo "c1 found; patch it locally (reject palette indices >= ncolors) so the fuzzer can go deeper"
sed -i 's| uint8_t idx = d\[pos + i\];| uint8_t idx = d[pos + i];\n if (idx >= img->ncolors) { free(img->rgb); return -1; }|' lbmp.c
build
campaign 1 c2; campaign 2 c3; campaign 3 c4
python3 - <<'PY'
import re, struct
print(f"{'crash':<6}{'report':<50}{'w x h':>14}{'w*h':>12}{'as uint16':>10}")
buckets = {}
for name in ("c1", "c2", "c3", "c4"):
log = open(f"crashes/{name}.log").read()
m = re.search(r"lbmp\.c:(\d+):\d+: runtime error: (.+?)(?::| for type)", log)
if m:
kind = f"UBSan {re.sub(r'\d+', 'N', m.group(2))} (line {m.group(1)})"
else:
kind = re.search(r"AddressSanitizer: ([\w-]+)", log).group(1)
acc = re.search(r"^(READ|WRITE) of size \d+", log, re.M).group(1)
line = re.search(r"in lbmp_decode /home/learner/lbmp\.c:(\d+)", log).group(1)
kind = f"ASan {kind} {acc} (line {line})"
d = open(f"crashes/{name}", "rb").read()
w, h = struct.unpack("<HH", d[4:8])
buckets.setdefault(kind, []).append(name)
print(f"{name:<6}{kind:<50}{f'{w} x {h}':>14}{w * h:>12}{(w * h) & 0xFFFF:>10}")
print(f"{len(buckets)} buckets for 4 crashes")
PYc1 found; patch it locally (reject palette indices >= ncolors) so the fuzzer can go deeper
crash report w x h w*h as uint16
c1 UBSan index N out of bounds (line 28) 2 x 2 4 4
c2 UBSan signed integer overflow (line 22) 60674 x 60909 3695592666 17626
c3 UBSan signed integer overflow (line 22) 65535 x 65535 4294836225 1
c4 ASan heap-buffer-overflow WRITE (line 29) 2560 x 512 1310720 0
3 buckets for 4 crashes
Reading the results: four crashes, three buckets, two bugs
- c1 is UBSan's array-bounds check at line 28:
img->palette[idx]with an index of 16 or more, from a pixel byte. The decoder never compares a pixel's index withncolors(or with the 16-entry array). An out-of-bounds read: class "possible information leak", since palette bytes beyond the array come from neighbouring memory and end up in the output image. - c2 and c3 are UBSan's signed integer overflow at line 22:
img->w * img->hmultiplies twouint16_tvalues, which C promotes toint, and 60674 x 60909 does not fit in anint. - c4 is an ASan heap-buffer-overflow WRITE at line 29 (line 28 before the local patch): a 2560 x 512 image has 1,310,720 pixels, which wraps to 0 in the
uint16_t npix. The length checkn - pos < npixpasses,malloc(0)succeeds, and the loop, which uses the realw * h, writes into a zero-byte buffer. Class "likely exploitable".
Stack-hash bucketing gives three buckets, but c2, c3 and c4 are one root cause: the pixel count is computed in a type too narrow for it, and the truncated value is used for the check and the allocation while the full value drives the loop. Which symptom you see depends on the dimensions: overflow of int (caught by UBSan), or wrap-around of uint16_t (not undefined behaviour, but caught by ASan when the loop writes). Triage reduces crashes to buckets; only root-cause analysis reduces buckets to bugs.
The root causes, written as for a bug report:
- B1 (c2, c3, c4):
npixis computed asimg->w * img->hinintand stored inuint16_t, so the check (line 23) and the allocation (line 24) use a truncated count while the loop (line 26) uses the full product. CWE-190 integer overflow (and CWE-197 numeric truncation when the product is stored in 16 bits), leading to CWE-787/CWE-122 heap out-of-bounds write. - B2 (c1): pixel indices are never checked against
ncolorsbefore indexing the palette (line 28). CWE-129 improper validation of array index, leading to CWE-125 out-of-bounds read.
Variant check: are there other places where a product of header fields is computed in a narrow type, or an index from data is used without a check? In this small decoder, no; in a real one, search for every multiplication of header fields and every table lookup with a data-derived index (Variant Analysis).
Step 5: the fix, regression tests and a clean campaign
The fix computes the pixel count once, in size_t, rejects images above a documented maximum, and uses that single value for the check, the allocation and the loop; and it rejects pixel indices that are not in the palette. The regression tests are four tiny files written by hand from the buckets (a valid image, a bad palette index, maximum dimensions, and dimensions whose product wraps to 0), checked by a test program under ASan and UBSan. Then the fixed decoder is fuzzed for 300,000 runs with the regression files as seeds. It runs in your sandbox:
cat > lbmp.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
/* LBMP, the mini project's toy image format (little-endian):
"LBMP" | width u16 | height u16 | ncolors u8 | ncolors x (r,g,b) | width*height palette indices */
struct image { uint16_t w, h; uint8_t ncolors; uint8_t palette[16][3]; uint8_t *rgb; };
static uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
int lbmp_decode(const uint8_t *d, size_t n, struct image *img) {
if (n < 9 || memcmp(d, "LBMP", 4) != 0) return -1;
img->w = rd16(d + 4);
img->h = rd16(d + 6);
img->ncolors = d[8];
if (img->ncolors > 16) return -1;
size_t pos = 9;
if (n - pos < (size_t)img->ncolors * 3) return -1;
memcpy(img->palette, d + pos, (size_t)img->ncolors * 3);
pos += (size_t)img->ncolors * 3;
uint16_t npix = img->w * img->h; /* number of pixels */
if (n - pos < npix) return -1;
img->rgb = malloc((size_t)npix * 3);
if (!img->rgb) return -1;
for (size_t i = 0; i < (size_t)img->w * img->h; i++) {
uint8_t idx = d[pos + i];
memcpy(img->rgb + 3 * i, img->palette[idx], 3);
}
return 0;
}
SRC
cat > lbmp-fixed.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define LBMP_MAX_PIXELS (4096u * 4096u) /* documented limit */
/* LBMP, the mini project's toy image format (little-endian):
"LBMP" | width u16 | height u16 | ncolors u8 | ncolors x (r,g,b) | width*height palette indices */
struct image { uint16_t w, h; uint8_t ncolors; uint8_t palette[16][3]; uint8_t *rgb; };
static uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
int lbmp_decode(const uint8_t *d, size_t n, struct image *img) {
if (n < 9 || memcmp(d, "LBMP", 4) != 0) return -1;
img->w = rd16(d + 4);
img->h = rd16(d + 6);
img->ncolors = d[8];
if (img->ncolors > 16) return -1;
size_t pos = 9;
if (n - pos < (size_t)img->ncolors * 3) return -1;
memcpy(img->palette, d + pos, (size_t)img->ncolors * 3);
pos += (size_t)img->ncolors * 3;
size_t npix = (size_t)img->w * img->h; /* fix 1: count in size_t, one value used everywhere */
if (npix > LBMP_MAX_PIXELS || n - pos < npix) return -1;
img->rgb = malloc(npix * 3);
if (!img->rgb) return -1;
for (size_t i = 0; i < npix; i++) {
uint8_t idx = d[pos + i];
if (idx >= img->ncolors) { free(img->rgb); img->rgb = NULL; return -1; } /* fix 2 */
memcpy(img->rgb + 3 * i, img->palette[idx], 3);
}
return 0;
}
SRC
cat > test_lbmp.c <<'SRC'
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
struct image { uint16_t w, h; uint8_t ncolors; uint8_t palette[16][3]; uint8_t *rgb; };
int lbmp_decode(const uint8_t *d, size_t n, struct image *img);
static int check(const char *path, int expected) { /* regression test: decode one file */
FILE *f = fopen(path, "rb"); uint8_t buf[256]; size_t n = fread(buf, 1, sizeof buf, f); fclose(f);
uint8_t *d = malloc(n); for (size_t i = 0; i < n; i++) d[i] = buf[i];
struct image img = {0};
int r = lbmp_decode(d, n, &img);
free(img.rgb); free(d);
printf(" %-28s -> %2d (expected %2d) %s\n", path, r, expected, r == expected ? "ok" : "FAIL");
return r == expected;
}
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0); /* keep lines printed before a crash */
int ok = check("regress/valid-2x2.lbmp", 0) & check("regress/palette-index.lbmp", -1)
& check("regress/dims-overflow.lbmp", -1) & check("regress/npix-wraps-to-0.lbmp", -1);
puts(ok ? "all regression tests passed" : "regression tests FAILED");
return !ok;
}
SRC
mkdir regress && python3 - <<'PY'
import struct
def img(w, h, palette, pixels):
return b"LBMP" + struct.pack("<HHB", w, h, len(palette)) + b"".join(bytes(c) for c in palette) + bytes(pixels)
files = {
"valid-2x2.lbmp": img(2, 2, [(0, 0, 0), (255, 255, 255)], [0, 1, 1, 0]),
"palette-index.lbmp": img(2, 2, [(0, 0, 0), (255, 255, 255)], [0, 200, 1, 0]), # bucket of c1
"dims-overflow.lbmp": img(65535, 65535, [], []), # like c3
"npix-wraps-to-0.lbmp": img(2560, 512, [(9, 9, 9)], [0] * 8), # like c4
}
for name, data in files.items():
open(f"regress/{name}", "wb").write(data)
PY
echo "== the fix"
diff -u lbmp.c lbmp-fixed.c | tail -n +3 | grep -E '^[-+]'
echo "== regression tests, original code (first failure only: sanitizers stop the program)"
gcc -g -O0 -fsanitize=address,undefined -fno-sanitize-recover=undefined lbmp.c test_lbmp.c -o test_orig
./test_orig 2>&1 | grep -E 'ok$|FAIL$|runtime error' | sed -E 's/ [0-9]+ out of bounds/ N out of bounds/'
echo "== regression tests, fixed code"
gcc -g -O0 -fsanitize=address,undefined -fno-sanitize-recover=undefined lbmp-fixed.c test_lbmp.c -o test_fixed
./test_fixed 2>&1; echo "exit code: $?"
echo "== fuzz the fixed decoder"
cat > fuzz_lbmp.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
struct image { uint16_t w, h; uint8_t ncolors; uint8_t palette[16][3]; uint8_t *rgb; };
int lbmp_decode(const uint8_t *d, size_t n, struct image *img);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
struct image img = {0};
if (lbmp_decode(data, size, &img) == 0) free(img.rgb);
return 0;
}
SRC
clang -g -O1 -fsanitize=fuzzer,address,undefined -fno-sanitize-recover=undefined lbmp-fixed.c fuzz_lbmp.c -o fuzz_fixed
mkdir corpus && cp regress/* corpus/
./fuzz_fixed -seed=1 -runs=300000 corpus > f.log 2>&1; echo "300000 runs, exit code: $?, sanitizer reports: $(grep -cE 'ERROR|runtime error' f.log)"== the fix
+#define LBMP_MAX_PIXELS (4096u * 4096u) /* documented limit */
+
- uint16_t npix = img->w * img->h; /* number of pixels */
- if (n - pos < npix) return -1;
- img->rgb = malloc((size_t)npix * 3);
+ size_t npix = (size_t)img->w * img->h; /* fix 1: count in size_t, one value used everywhere */
+ if (npix > LBMP_MAX_PIXELS || n - pos < npix) return -1;
+ img->rgb = malloc(npix * 3);
- for (size_t i = 0; i < (size_t)img->w * img->h; i++) {
+ for (size_t i = 0; i < npix; i++) {
+ if (idx >= img->ncolors) { free(img->rgb); img->rgb = NULL; return -1; } /* fix 2 */
== regression tests, original code (first failure only: sanitizers stop the program)
regress/valid-2x2.lbmp -> 0 (expected 0) ok
lbmp.c:28:46: runtime error: index N out of bounds for type 'uint8_t [16][3]'
== regression tests, fixed code
regress/valid-2x2.lbmp -> 0 (expected 0) ok
regress/palette-index.lbmp -> -1 (expected -1) ok
regress/dims-overflow.lbmp -> -1 (expected -1) ok
regress/npix-wraps-to-0.lbmp -> -1 (expected -1) ok
all regression tests passed
exit code: 0
== fuzz the fixed decoder
300000 runs, exit code: 0, sanitizer reports: 0
- The diff is small and goes to the root causes: one
size_tcount used everywhere, a maximum, and an index check. Clamping the loop tonpixalone would have hidden c4 but kept the truncation; checking onlyidx < 16would have allowed reading uninitialised palette entries beyondncolors. - The original code fails the regression suite at the second file: UBSan stops the program at the palette index (exactly bucket c1), which is what a failing regression test looks like in CI.
- The fixed code passes all four tests, and 300,000 fuzzing runs from the regression seeds report nothing.
Hand-written regression inputs are often better than raw crash files: each one names the bug it guards against, is a few bytes long, and stays meaningful when the format changes. Keep the raw (minimised) crash files too, in the fuzzing corpus.
Step 6: the advisory
Write the advisory for the fictional vendor, following Writing an Advisory, and run it through that lesson's linter. One advisory can cover both bugs if they ship in one fix, with one CVE each.
# LAB-2026-0002: Heap buffer overflow and out-of-bounds read in lbmp_decode()
**CVEs:** CVE-2026-0001 (B1), CVE-2026-0002 (B2) (placeholders)
**Severity:** B1 High, B2 Medium (CVSS-B v4.0; give each vector, compute the scores with FIRST's calculator)
**Affected:** liblbmp 1.0.0 up to and including 1.2.3
**Fixed in:** liblbmp 1.2.4
## Summary
B1: lbmp_decode() computes the pixel count of an image in a 16-bit value. For images whose
width x height exceeds 65,535 the count wraps, the pixel buffer is allocated too small, and
decoding writes past it (CWE-190, CWE-787).
B2: pixel values are not checked against the palette size, so decoding reads past the
palette (CWE-129, CWE-125); the bytes read end up in the decoded image.
## Impact
Applications that decode untrusted LBMP files can crash (both bugs), and B1's heap overflow
may allow code execution. B2 may disclose memory contents through the decoded image.
No exploitation has been observed.
## Workaround
Reject LBMP files whose width x height exceeds 4096 x 4096 before calling lbmp_decode(), or
do not process LBMP files from untrusted sources until you have upgraded.
## Timeline
- (report date) reported privately to the maintainers
- (date) confirmed; fix and advisory prepared
- (date) coordinated publication with downstream packagers
## Credit
(your name, as you wish to be credited)
## References
- fix commit, release notes, CVE recordsFor orientation: with the vector of the advisory lesson (AV:L/AC:L/AT:N/PR:N/UI:P/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N) FIRST's v4.0 calculator gives B1 8.5 (High); a plausible vector for B2, AV:L/AC:L/AT:N/PR:N/UI:P/VC:L/VI:N/VA:L/SC:N/SI:N/SA:N (a small leak and a crash), gives 4.8 (Medium). Justify your own vectors in the text. Before sending a real advisory: check the version ranges against the repository history (which release introduced the 16-bit count?), get both CVE IDs from the right CNA, agree the date with downstream packagers, and keep exploit details out.
Going further
- Fuzz with a dictionary (
"LBMP"and a few boundary dimensions such as\xff\xff) and compare time to the first B1 crash with and without it. - Write a property-based test in Python for a Python port of the decoder:
decode(encode(img)) == imgfor random small images, and "never raises anything exceptValueError" for random bytes. - Add
-fsanitize=implicit-conversion(Clang) to the fuzzing build: it reports theinttouint16_ttruncation itself, so c4 is caught at line 22, where the count is truncated, like c2 and c3, instead of at the write in the loop. - Model the decoder's checks: write the validity conditions as a function and check, for all
wandhup to 65,535, that a passing header can never make the loop exceed the allocation.
Checklist
Did your research cycle cover everything?
- two written hypotheses before fuzzing, with the result of each
- a deterministic harness with ASan and fatal UBSan, a valid seed
- every crash file kept with its log; buckets by kind and location
- buckets reduced to root causes, with lines, CWEs and the reasoning
- a variant search for each root cause
- a minimal patch at the root cause, reviewed for side effects
- regression tests that fail before and pass after the fix
- a clean campaign after the fix, with the regression inputs as seeds
- an advisory that passes the linter: versions, severity vectors, workaround, timeline, credit, no exploit detail
- a disclosure plan: who is told, when, and which downstream projects need time
Test yourself
Why are c2, c3 and c4 one bug although they fall into two buckets?
- They have the same input size
- They share one root cause: the pixel count is computed and stored in too narrow a type, so the check and allocation use a truncated value
- They were found by the same seed
- The triage script is wrong
Why did c4 report a WRITE while c2 and c3 reported signed overflow?
- Different sanitizers were off
- 2560 x 512 fits in an int but wraps to 0 in uint16_t, so no UB occurs until the loop writes past the 0-byte buffer
- c4 is a different bug
- ASan was disabled for c2
Why was the first bug patched locally before the next campaigns?
- To hide it
- Fuzzers stop at the first crash; patching it lets them reach deeper bugs
- To make the fuzzer faster
- Because UBSan required it
Which part of the fix prevents B1 for good?
- Clamping the loop to npix
- Computing the count once in size_t, enforcing a maximum, and using that one value for check, allocation and loop
- Using calloc
- Checking idx < 16