Buffer Overflow

Difficulty: Advanced

Question

What is a buffer overflow, why is it dangerous, and what mitigations exist?

Answer

A buffer overflow happens when a program writes more data into a fixed-size memory buffer than it can hold, so the extra bytes overwrite adjacent memory. In languages without bounds checking, such as C and C++, an attacker who controls that input can corrupt variables, crash the program or overwrite a return address and redirect execution.

How a classic stack overflow works

When a C function runs, its stack frame holds local variables, the saved frame pointer and the return address that tells the CPU where to resume after the function returns. On x86-64 the stack grows towards lower addresses, but a buffer is filled towards higher addresses. So if char buf[64] receives 200 bytes through an unbounded copy, the write runs past buf, over the saved frame pointer and onto the return address. When the function returns, the CPU jumps wherever that value now points. Historically that meant code planted in the buffer; today it usually means chaining together snippets of existing code (return-oriented programming, ROP).

Types of overflows

  • Stack overflow: overruns a local buffer and targets return addresses or function pointers.
  • Heap overflow: overruns a malloced block, corrupting allocator metadata or neighbouring objects such as vtable pointers.
  • Off-by-one: writing one byte too many, often from forgetting the space for the \0 terminator.
  • Integer overflow leading to overflow: a size calculation wraps around, so a tiny buffer is allocated and a large copy follows.

Mitigations and what each one stops

MitigationHow it worksLimitation
Stack canaries (-fstack-protector-strong)Random value before the return address, checked on returnBypassed by info leaks or non-linear writes
NX / DEPStack and heap marked non-executableDefeated by ROP reusing existing code
ASLR and PIERandomise addresses of stack, heap, libraries and binaryWeakened by a memory-disclosure bug
_FORTIFY_SOURCECompiler swaps unsafe calls for checked versions when sizes are knownOnly covers calls it can analyse
CFI and shadow stacks (Intel CET)Hardware or compiler checks that returns and indirect calls hit valid targetsNeeds OS, compiler and CPU support
Memory-safe languagesRust, Go, Java and C# bounds-check every accessUnsafe blocks and FFI still need care

None of these replaces correct code; they raise the cost of exploitation. This is why agencies such as CISA and major vendors now push memory-safe languages for new systems code.

Why it still matters for web developers

Your Node.js or Python service is memory-safe, but it sits on native code: OpenSSL, image libraries like libwebp, video codecs, database drivers and the language runtime itself. Heartbleed (2014) was a buffer over-read in OpenSSL, and CVE-2023-4863 was a heap overflow in libwebp that affected browsers and almost any app decoding WebP images. Keeping native dependencies patched and processing untrusted files in sandboxes are your practical defences.

Common mistakes

  • Using unbounded copies with untrusted input. Prefer fgets, snprintf and explicit length checks.
  • Assuming strncpy always null-terminates. It does not when the source is too long.
  • Trusting a length field sent by the client without checking it against the real buffer size.
  • Turning off ASLR or stack protection to 'fix' a crash in a build.
Stack frame during an overflow. Bytes written past the buffer climb towards higher addresses and reach the return address.
  1. Caller's stack frame: Higher addresses, belongs to the calling function.
  2. Return address: Overwriting this value redirects execution on return.
  3. Saved frame pointer: Corrupted next as the overflow continues.
  4. Stack canary: A random guard value checked before returning.
  5. char buf[64]: Lower addresses, filled upward by the copy.

Code examples

Unbounded copy vs bounded copy in C

#include <stdio.h>
#include <string.h>

void unsafe_copy(const char *input) {
    char buf[64];
    strcpy(buf, input);          /* no length check: overflow if input > 63 */
    printf("Hello %s\n", buf);
}

void safe_copy(const char *input) {
    char buf[64];
    /* snprintf never writes more than sizeof buf and always terminates */
    int n = snprintf(buf, sizeof buf, "%s", input);
    if (n < 0 || (size_t)n >= sizeof buf) {
        fprintf(stderr, "input too long, rejected\n");
        return;
    }
    printf("Hello %s\n", buf);
}

The unbounded copy writes until it finds a null byte regardless of the destination size. snprintf bounds the write and reports truncation so you can reject oversized input.

Compile with modern hardening flags

# Stack canaries, fortified libc calls, PIE for ASLR, full RELRO, CET
gcc -O2 -fstack-protector-strong -D_FORTIFY_SOURCE=3 \
    -fPIE -pie -Wl,-z,relro,-z,now -fcf-protection=full \
    app.c -o app

# Inspect the protections on a binary (checksec from pwntools)
checksec --file=./app

_FORTIFY_SOURCE=3 needs GCC 12 or newer with optimisation enabled; older toolchains use level 2. These flags make exploitation harder but do not fix the underlying bug.

Key points

  • A buffer overflow writes past a buffer's bounds and corrupts adjacent memory.
  • Stack overflows classically overwrite the return address to redirect execution.
  • Canaries, NX/DEP, ASLR, FORTIFY_SOURCE and CFI are layered mitigations, not cures.
  • ROP bypasses NX by chaining existing instructions instead of injecting code.
  • Memory-safe languages remove the bug class; patch native dependencies in web stacks.

Common follow-up questions

  • How does return-oriented programming bypass a non-executable stack?
  • How can an information leak defeat ASLR and stack canaries?
  • What is the difference between a buffer overflow and a buffer over-read like Heartbleed?
  • Why does Rust prevent buffer overflows, and where can they still occur?

Interview tips

  • Draw the stack frame: buffer, canary, saved frame pointer, return address. It makes the explanation instantly clear.
  • List mitigations with what each defeats and how it is bypassed; that shows depth beyond the definition.
  • Connect it to web work by mentioning native libraries such as OpenSSL or libwebp.

Concepts covered

Memory Corruption, Stack Canaries, ASLR, NX/DEP, Memory Safety

More Web Security (OWASP, JWT, XSS, CSRF) questions