TExcelTAD

Root-Cause Analysis with gdb and the Bug Report

A sanitizer report says where memory went wrong: memcpy in rec_name, line 8, 24 bytes into a 16-byte buffer. The root cause is the first place where the program made a wrong decision that led there, and it is often somewhere else: the function that passed a length it never validated, the protocol layer that trusted a header, the refactoring that removed a check. Fixing the crash site (memcpy only 16 bytes) without the root cause leaves the next caller with the same bug. This lesson finds a root cause with gdb on the minimised crash from triage, then writes it up as a bug report.

Questions that lead to the root cause

  1. What exactly was wrong at the crash? Which value was out of range (the length 24), and what was the limit (16)?
  2. Where did that value come from? Walk up the stack: who computed or passed it? Here: tlv_parse read it from the input.
  3. Which check should have stopped it, and why didn't it? There is a check (len > size - pos), but it compares with the input, not with the buffer.
  4. Is the wrong assumption anywhere else? That is variant analysis, two lessons ahead.

gdb answers the first three with a few commands. Debugging with gdb in the reverse-engineering course covers the tool; here it is used as an instrument for one question at a time.

A gdb session on the minimised crash

The input is the minimised file from bucket 1 of the triage lesson: a sum record ab followed by a name record of length 24. The session builds the parser without a sanitizer (so gdb sees the program as it really runs), stops in rec_name only when the length exceeds the buffer (a conditional breakpoint), and then asks the questions in order. It runs in your sandbox:

bash · try it yourself
cat > tlv.c <<'SRC'
#include <stddef.h>
#include <stdint.h>
#include <string.h>

/* Toy format "TLV1": magic, then records of type (1 byte), length (1 byte), value. */
static int rec_name(const uint8_t *v, size_t len) {
    char name[16];
    memcpy(name, v, len);                 /* seeded bug 1: len is never checked against 16 */
    return name[0];
}

static int rec_sum(const uint8_t *v, size_t len) {
    unsigned sum = 0;
    for (size_t i = 0; i <= len; i++)     /* seeded bug 2: <= reads one byte too many */
        sum += v[i];
    return (int)(sum & 0xff);
}

int tlv_parse(const uint8_t *data, size_t size) {
    if (size < 4 || memcmp(data, "TLV1", 4) != 0) return -1;
    size_t pos = 4;
    int acc = 0;
    while (pos + 2 <= size) {
        uint8_t type = data[pos], len = data[pos + 1];
        pos += 2;
        if (len > size - pos) return -1;  /* the input-length check is correct */
        if (type == 1) acc += rec_name(data + pos, len);
        else if (type == 2) acc += rec_sum(data + pos, len);
        pos += len;
    }
    return acc;
}
SRC
cat > run_tlv.c <<'SRC'
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int tlv_parse(const uint8_t *data, size_t size);
int main(int argc, char **argv) {
    FILE *f = fopen(argv[1], "rb");
    if (!f) return 2;
    uint8_t *buf = malloc(4096);
    size_t n = fread(buf, 1, 4096, f);
    fclose(f);
    uint8_t *data = malloc(n);                  /* exact-size copy, so over-reads hit a redzone */
    for (size_t i = 0; i < n; i++) data[i] = buf[i];
    free(buf);
    printf("%s: tlv_parse = %d\n", argv[1], tlv_parse(data, n));
    free(data);
    return 0;
}
SRC
gcc -g -O0 tlv.c run_tlv.c -o run_tlv_dbg                  # a plain debug build for gdb
printf 'TLV1\x02\x02ab\x01\x18NNNNNNNNNNNNNNNNNNNNNNNN' > c3-min.tlv  # minimised crash from bucket 1
gdb -q -batch \
  -ex 'break rec_name if len > sizeof(name)' \
  -ex 'run c3-min.tlv' \
  -ex 'bt' \
  -ex 'print len' \
  -ex 'print sizeof(name)' \
  -ex 'up' \
  -ex 'print pos' \
  -ex 'print size - pos' \
  -ex 'print/x data[pos - 2]@2' \
  -ex 'info locals' \
  -ex 'kill' \
  ./run_tlv_dbg 2>&1 | grep -v '^\[Inferior'
Breakpoint 1 at 0x125d: file tlv.c, line 6.
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, rec_name (v=0x5b066727649a 'N' <repeats 24 times>, len=24) at tlv.c:6
6	static int rec_name(const uint8_t *v, size_t len) {
#0  rec_name (v=0x5b066727649a 'N' <repeats 24 times>, len=24) at tlv.c:6
#1  0x00005b062b2073a7 in tlv_parse (data=0x5b0667276490 "TLV1\002\002ab\001\030", 'N' <repeats 24 times>, size=34) at tlv.c:27
#2  0x00005b062b2074d1 in main (argc=2, argv=0x7ffcc8bbad28) at run_tlv.c:14
$1 = 24
$2 = 16
#1  0x00005b062b2073a7 in tlv_parse (data=0x5b0667276490 "TLV1\002\002ab\001\030", 'N' <repeats 24 times>, size=34) at tlv.c:27
27	        if (type == 1) acc += rec_name(data + pos, len);
$3 = 10
$4 = 24
$5 = {0x1, 0x18}
type = 1 '\001'
len = 24 '\030'
pos = 10
acc = 196

Reading the answers:

  • What was wrong: len = 24, sizeof(name) = 16. The breakpoint fired before the copy, which is the point of a conditional breakpoint: you see the state that will cause the overflow, not the wreckage after it.
  • Where it came from: frame #1 is tlv_parse at line 27, and data[pos - 2]@2 shows the record header {0x1, 0x18}: type 1, length 0x18 = 24, straight from the file.
  • Which check failed to stop it: size - pos is also 24. The input-length check at line 26 (len > size - pos) passed correctly, because 24 bytes really follow. No check compares len with the 16-byte destination: that missing comparison is the root cause. In CWE terms: CWE-121 (stack-based buffer overflow) caused by CWE-1284 (improper validation of a specified quantity in input).
  • A bonus finding: acc = 196. The sum record ab should give 97 + 98 = 195; the extra 1 is the type byte of the next record, read by the off-by-one in rec_sum (bug 2). It did not crash because the next byte belonged to the input. Debuggers show silent bugs that sanitizers would only catch at the end of a buffer.

Detection and the fix

The root cause dictates the fix: the decision "does this value fit where it is going" belongs where the value is used against a buffer, so rec_name checks len > sizeof name and rejects the record. Better still, the parser could give each handler a typed view of the value with its length (a struct span { const uint8_t *p; size_t n; }) so that every copy is written against both sizes. The regression test is the 34-byte file; the variant check is "every handler that copies len bytes into a fixed buffer".

The bug report

A report is the product of research. Maintainers have little time and no context; a report that answers their questions in the first screen gets fixed first. A template that works for private reports to a project:

text
Title:      Stack buffer overflow in rec_name() via TLV1 name record longer than 16 bytes
Component:  tlv.c (all versions with rec_name, checked at commit <hash>)
Type:       CWE-121 stack-based buffer overflow (missing size check, CWE-1284)
Found by:   fuzzing (libFuzzer + ASan), confirmed by hand
Reproduce:  gcc -g -fsanitize=address tlv.c run_tlv.c -o run_tlv && ./run_tlv c3-min.tlv
            (attached: c3-min.tlv, 34 bytes; full ASan report attached)
Root cause: tlv_parse() checks that a record's length fits the input (line 26), but
            rec_name() copies that length into char name[16] without comparing (line 8).
Impact:     an attacker-supplied file can write up to 239 bytes past name[] on the stack.
            Any program that parses untrusted TLV1 files is affected. Assessed as
            likely exploitable for code execution in builds without stack protection;
            not demonstrated (no exploit was written).
Suggested fix:  if (len > sizeof name) return -1;  before the memcpy (patch attached),
                plus the attached regression test.
Also noticed:   rec_sum() reads one byte past each value (<= instead of <, line 14),
                reported separately as it is a different bug.
Disclosure: reported privately; happy to coordinate a date for the advisory.

Note what is not in it: no exploit, no speculation beyond what was checked, and no bundling of two bugs into one report. Separate bugs get separate reports so each can be tracked, fixed and credited on its own. The public version of this text is the advisory (Writing an Advisory).

Pitfalls

  • Fixing the crash site. Clamping the memcpy to 16 bytes silently truncates names and leaves the wrong assumption in the parser; the next handler repeats it.
  • Debugging the sanitizer build only. ASan changes the stack layout; for questions about real layout, use a plain debug build, as here.
  • Breakpoints after the fact. Break where the bad value is about to be used, with a condition, rather than at the crash.
  • Reports without a reproducer. A maintainer who cannot reproduce in five minutes moves on.

Practice

1. Write the gdb command that stops in rec_sum only on the last record of the input.

break rec_sum if v + len == data + size does not work, because data and size are not visible in rec_sum's frame. Use the frame of the caller: break tlv.c:28 if type == 2 && pos + len == size, which stops on line 28 just before rec_sum is called for a value that ends the input.

2. Why is "up to 239 bytes past name[]" the right bound for the impact sentence?

The length is one byte, at most 255, and the buffer holds 16, so the write can extend 255 - 16 = 239 bytes beyond it. The input-length check guarantees those bytes exist in the file, so the attacker controls all of them.

3. The maintainer replies: "it is only a crash, the parser is used in a desktop tool." How do you answer?

Explain the reachability (desktop tools open files from email and downloads), that a stack write with attacker-controlled bytes is classed as likely exploitable, and that the fix is one line. Offer the regression test. Stay factual; do not threaten publication, but agree on a timeline (Coordinated Disclosure).

Test yourself

What is the root cause of bug 1?

  1. memcpy is unsafe
  2. rec_name copies a length taken from the input without comparing it with the 16-byte buffer
  3. The input-length check at line 26 is wrong
  4. The file is too long

Why use a conditional breakpoint break rec_name if len > sizeof(name)?

  1. It is faster to type
  2. It stops just before the overflow, only for the dangerous calls, so you see the cause and not the wreckage
  3. gdb requires it
  4. To disable ASan

What did acc = 196 reveal?

  1. A gdb bug
  2. The off-by-one in rec_sum silently read the next record's type byte (195 + 1)
  3. The name was summed
  4. Nothing

Why report the rec_sum bug separately?

  1. Rules of grammar
  2. Separate bugs need separate tracking, fixes, tests and credit
  3. To get two bounties
  4. It is not a bug