TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Stack Buffer Overflow (CWE-121)

Stack Buffer Overflow (CWE-121)

A stack buffer overflow is a write past the end of an array that lives in a function's stack frame. It is the oldest bug class in this course. The 1988 Morris worm spread partly through an overflow of a 512-byte stack buffer in the fingerd service, which read its input with gets; "Smashing the Stack for Fun and Profit" (Aleph One, Phrack 49, 1996) made the technique widely known. Thirty years of mitigations later, stack overflows still appear in advisories for routers, printers, VPN appliances and industrial devices, typically in code that parses a header, a file name or a configuration line into a fixed-size local array.

The bug in a toy program

The toy parses an HTTP-style header line Key: value and copies the key into a 16-byte local array, character by character, until it sees the colon. It never compares the index with the size of the array. Real header names are short, so every normal test passes:

bash · try it yourself
cat > hdr.c <<'SRC'
#include <stdio.h>
#include <string.h>

/* Parses "Key: value" and prints the key. */
static void parse_header(const char *line) {
    char key[16];
    size_t i = 0;
    while (line[i] && line[i] != ':') {   /* BUG: no check against sizeof key */
        key[i] = line[i];
        i++;
    }
    key[i] = '\0';
    printf("key = %s\n", key);
}

int main(int argc, char **argv) {
    parse_header(argc > 1 ? argv[1] : "Host: lab.test");
    return 0;
}
SRC
gcc -g -O0 -fsanitize=address hdr.c -o hdr-asan
./hdr-asan 'Host: lab.test'
./hdr-asan 'X-A-Very-Long-Header-Name-From-The-Client: 1' 2>&1 | grep -E 'ERROR|WRITE|#0 |located in stack|\[32, 48\)|^=>'
echo "exit code: ${PIPESTATUS[0]}"
echo "== the default build, no ASan"
gcc -g -O0 hdr.c -o hdr
./hdr 'X-A-Very-Long-Header-Name-From-The-Client: 1' 2>&1 | cat; echo "exit code: ${PIPESTATUS[0]}"
key = Host
==17==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7f0403900030 at pc 0x5e34b813538f bp 0x7fff9738aa30 sp 0x7fff9738aa20
WRITE of size 1 at 0x7f0403900030 thread T0
    #0 0x5e34b813538e in parse_header /home/learner/hdr.c:9
Address 0x7f0403900030 is located in stack of thread T0 at offset 48 in frame
    #0 0x5e34b8135278 in parse_header /home/learner/hdr.c:5
    [32, 48) 'key' (line 6) <== Memory access at offset 48 overflows this variable
=>0x7f0403900000: f1 f1 f1 f1 00 00[f3]f3 00 00 00 00 00 00 00 00
exit code: 1
== the default build, no ASan
*** stack smashing detected ***: terminated
exit code: 134

The report, line by line

  • stack-buffer-overflow … WRITE of size 1: a one-byte store (key[i] = line[i]) outside a stack object. Unlike strcpy, which ASan sees as one big write, a loop is caught at its first bad byte.
  • #0 … parse_header hdr.c:9: the line key[i] = line[i];.
  • located in stack … at offset 48 in frame, then the frame's object list: [32, 48) 'key' (line 6) <== Memory access at offset 48 overflows this variable. ASan laid the frame out with key at offsets 32 to 47 and the write at 48 is the first byte after it, i.e. i == 16.
  • The shadow line f1 f1 f1 f1 00 00[f3]f3: left red zone (f1), the two addressable granules of key (00 00), and the right red zone (f3) that the write touched.

Without ASan the default Ubuntu build still has a stack canary (-fstack-protector-strong), so the program runs to the end of parse_header, the epilogue sees the changed canary, and glibc aborts with *** stack smashing detected *** (exit code 134, SIGABRT). That message proves the bug is real; it doesn't say where it is. The ASan build does.

What the overflow overwrote: the frame model

The header name has 41 characters before the colon, so the loop writes 41 bytes plus a NUL. On the stack-frame model of a 16-byte buffer (offsets measured with gdb in that lesson), the copy runs over everything above the buffer. The model then runs the three checks that could stop the function from returning to a corrupted address. Saved values are labelled placeholders, not real addresses. It runs in your browser:

python · try it yourself
FIELDS = [("buf[16]", 0, 16), ("padding", 16, 8), ("canary", 24, 8),
          ("saved rbp", 32, 8), ("return address", 40, 8)]
CANARY = bytes.fromhex("005a3c91e27f4b18")          # fixed here; real canaries are secret, set per process

def new_frame():
    return bytearray(bytes(24) + CANARY + b"FRAMEPTR" + b"RET>main")

def copy_until_colon(frame, line):                  # the toy's loop, no bound
    i = 0
    while i < len(line) and line[i] != ord(":") and i < len(frame):
        frame[i] = line[i]
        i += 1
    if i < len(frame):
        frame[i] = 0

def epilogue(frame, canary_on=True, shadow_stack_on=True):
    if canary_on and frame[24:32] != CANARY:
        return "abort: *** stack smashing detected *** (canary changed)"
    if shadow_stack_on and frame[40:48] != b"RET>main":
        return "abort: control-protection fault (return address != shadow copy)"
    ret = bytes(frame[40:48])
    return "returns to main" if ret == b"RET>main" else f"returns to garbage {ret!r}: crash or worse"

line = b"X-A-Very-Long-Header-Name-From-The-Client: 1"
f = new_frame()
copy_until_colon(f, line)
for name, off, size in FIELDS:
    print(f"{name:15} {bytes(f[off:off + size])!r}")
print()
print("canary + shadow stack:", epilogue(f))
print("shadow stack only:    ", epilogue(f, canary_on=False))
print("no mitigation:        ", epilogue(f, canary_on=False, shadow_stack_on=False))
ok = new_frame(); copy_until_colon(ok, b"Host: lab.test")
print("short header:         ", epilogue(ok))
buf[16]         b'X-A-Very-Long-He'
padding         b'ader-Nam'
canary          b'e-From-T'
saved rbp       b'he-Clien'
return address  b't\x00T>main'

canary + shadow stack: abort: *** stack smashing detected *** (canary changed)
shadow stack only:     abort: control-protection fault (return address != shadow copy)
no mitigation:         returns to garbage b't\x00T>main': crash or worse
short header:          returns to main

The name overwrote the padding, the canary, the saved frame pointer and the return address. With the canary on, the function aborts before ret; a CPU shadow stack would catch the mismatch even without a canary; with neither, the function "returns" into the bytes of the header name, which here is just a crash. In a real attack those bytes would be chosen, which is why this one missing bounds check used to mean remote code execution. Mitigations are compared in Stack Canaries, NX and Why ROP Exists; this lesson's job is the fix.

The stack-frame lab runs the same comparison as an animation, with the toy's numbers: a 16-byte buffer and 42 bytes written (41 name bytes plus the NUL). Its frame has no padding, so the canary sits directly above the buffer, but the order of the checks is the same. With the canary on, the canary, saved rbp and return address are all overwritten (plus 2 bytes of the caller's frame) and the canary check aborts. Turn on ASan redzones and the program stops at the write of byte 17 (buf[16]) before anything outside the buffer changes, which is what the ASan report above says; with only the shadow stack on, the abort comes at ret.

offsetbytes, address →contents (rows grow ↑)rbp+0x58rbp+0x50rbp+0x48rbp+0x40rbp+0x38rbp+0x30rbp+0x28rbp+0x20rbp+0x18rbp+0x10AAcaller's frame (+2 B)rbp+0x08AAAAAAAAret → 0x4141414141414141rbp+0x00AAAAAAAAsaved rbp: 8 bytes = 0x41rbp−0x08AAAAAAAAcanary: 8 bytes changedrbp−0x10AAAAAAAArbp−0x18AAAAAAAAchar buf[16]void greet(int fd) {char buf[16];read(fd, buf, 42);}✓ copy input✕ check canary– leave (pop rbp)– retcaught: canarycanary check failsbefore leave: "stacksmashing detected",abortabstract model: placeholder values, only 'A' (0x41) bytes are written

Root cause

The loop has two exit conditions (end of string, colon) but the destination has a third limit, its size, which the code never checks. The size of key is known in the function (sizeof key), so this is a missing check, not a missing piece of information.

The fix

Stop at the size, leave room for the NUL, and tell the caller when the input didn't fit. Rejecting is better than truncating: a truncated header name may match a different header.

bash · try it yourself
cat > hdr.c <<'SRC'
#include <stdio.h>
#include <string.h>

/* Returns 0 on success, -1 if the key does not fit. */
static int parse_header(const char *line, char *key, size_t keysz) {
    size_t n = strcspn(line, ":");          /* length of the key */
    if (line[n] != ':' || n >= keysz)
        return -1;                          /* no colon, or too long: reject */
    memcpy(key, line, n);
    key[n] = '\0';
    return 0;
}

int main(void) {
    const char *tests[] = {"Host: lab.test", "X-A-Very-Long-Header-Name-From-The-Client: 1",
                           "0123456789abcde: fits", "0123456789abcdef: one too many", "no colon"};
    char key[16];
    for (int t = 0; t < 5; t++) {
        if (parse_header(tests[t], key, sizeof key) == 0) printf("ok       %s\n", key);
        else printf("rejected %.20s...\n", tests[t]);
    }
    return 0;
}
SRC
gcc -g -O0 -fsanitize=address,undefined hdr.c -o hdr-fixed && ./hdr-fixed 2>&1
echo "exit code: $?"
ok       Host
rejected X-A-Very-Long-Header...
ok       0123456789abcde
rejected 0123456789abcdef: on...
rejected no colon...
exit code: 0

Clean under ASan and UBSan. The boundary cases are the regression tests: a 15-character key (0123456789abcde, fits with its NUL) is accepted and a 16-character one is rejected.

How it is detected

  • Compilers: GCC warns (-Wstringop-overflow, -Warray-bounds) when the size and the length are both known at compile time; this loop is invisible to it.
  • Sanitizers and fuzzing: an ASan build plus a fuzzer that generates long header names finds this in seconds.
  • Review: every write into a local array in a loop or through strcpy, strcat, sprintf, gets, scanf("%s"), memcpy with an input-derived length. CodeQL and Semgrep have rules for these patterns.
  • In production: stack smashing detected in logs, or crashes with a corrupted backtrace.

The CWE

CWE-121: Stack-based Buffer Overflow, a child of CWE-787 (Out-of-bounds Write) and CWE-788 (Access of Memory Location After End of Buffer), both under CWE-119. Advisories often use CWE-787 for any out-of-bounds write; in a code review, name the specific one.

Pitfalls

  • Fixing with a bigger buffer (char key[256]) only moves the threshold.
  • strncpy(key, line, sizeof key) stops the overflow but leaves key unterminated when the input is long. See C Buffers.
  • Variable-length arrays (char key[n] with n from input) turn a huge n into a jump past the stack's guard page; compile with -Wvla and avoid them.

Practice

1. Which input length is the first that ASan reports for the original loop?

A key of 16 characters: the loop writes key[0]..key[15] (in bounds) and then the NUL at key[16], offset 48, out of bounds. With 15 characters the NUL lands in key[15].

2. Why does the canary-protected build print nothing from printf("key = …")?

It does reach the printf (the canary is checked at the end of the function), but stdout is a pipe, so the output sits in a buffer; abort() kills the process without flushing it. Run it on a terminal and you would see the line before the abort message.

3. Rewrite the original loop with the smallest possible change that makes it safe.

while (line[i] && line[i] != ':' && i < sizeof key - 1), then reject if line[i] != ':' after the loop. The strcspn version is clearer.

Test yourself

What did the ASan report say about the variable?

  1. [0, 16) 'key' underflows
  2. [32, 48) 'key' <== Memory access at offset 48 overflows this variable
  3. key was freed
  4. key is a global

Without ASan, what stopped the default build?

  1. NX
  2. The stack canary check in the epilogue: stack smashing detected
  3. ASLR
  4. Nothing

In the model, which check catches the overwrite when the canary is turned off?

  1. None
  2. The shadow stack comparing the return address with its protected copy
  3. ASLR
  4. FORTIFY_SOURCE

Which fix is correct?

  1. char key[256]
  2. Check the key length against the buffer size (leaving room for the NUL) and reject inputs that don't fit
  3. strncpy(key, line, sizeof key)
  4. Compile with -O2

In the stack-frame lab (16-byte buffer, 42 bytes written), you turn on ASan redzones. How many bytes outside the buffer get written?

  1. 0: ASan checks each store and aborts on byte 17, before it is written
  2. 8: the canary
  3. 26: everything past the buffer
  4. 2: only the caller's frame