Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Exploitation Concepts

How Memory Corruption Works (and How It Is Stopped)

Understand stack buffer overflows with a safe simulation, then see how bounds checks, stack canaries, ASLR and DEP/NX make memory-corruption flaws harder to exploit.

Memory corruption bugs happen in languages like C and C++ where the program manages memory by hand. If code writes more data into a buffer than it can hold, the extra bytes spill into neighbouring memory. Depending on what lives there, the result may be a crash, silently wrong data, or, in the worst case, an attacker steering the program.

As a penetration tester you rarely write these exploits from scratch. You need to understand them so you can recognize risky software, read advisories, judge whether an exploit module is safe to run, and explain to developers why the fix matters. This lesson uses a harmless toy memory model in Python. It has no real addresses, no machine code and no target: it only shows the idea.

The stack in one picture

When a function is called, the CPU reserves a block of memory called a stack frame. A simplified frame holds local variables (such as a 16-byte name buffer) and, just above them, the saved return address: the place the program jumps back to when the function ends.

flowchart TB
    A["Higher addresses"] --> B["Saved return address<br/>(where to go next)"]
    B --> C["Saved frame pointer"]
    C --> D["Local buffer: 16 bytes<br/>(grows toward higher addresses when filled)"]
    D --> E["Lower addresses"]

A simplified stack frame. Writing past the end of the buffer walks toward the return address.

A stack buffer overflow happens when input longer than 16 bytes is copied without checking its length. The surplus overwrites the saved values above the buffer. If the saved return address is replaced, the function returns somewhere the attacker chose. Old tutorials describe putting machine code in the buffer and jumping to it; modern systems make that much harder, as you will see below.

Python A toy stack frame (safe simulation)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The long input replaced the return address with 0x41414141, the bytes of the letter A. A real program would then jump to an invalid address and crash, which is why a crash with such a value in a debugger is the classic sign of an overflow. The fix is simply to check the length before copying.

Other memory bug families

  • Heap overflow: the same idea on dynamically allocated memory, corrupting allocator metadata or neighbouring objects.
  • Use-after-free: a program keeps using memory after releasing it; someone else may now own that memory.
  • Integer overflow: arithmetic wraps around (size + 1 becomes 0), leading to undersized buffers.
  • Format string bugs: user input is used as a printf format, letting it read or write memory.
  • Out-of-bounds read: reading past a buffer leaks secrets without crashing, as in the Heartbleed bug.

Memory-safe languages (Rust, Go, Java, C#, Python) prevent most of these by checking bounds and managing lifetimes. That is the strongest long-term defense and a good recommendation in a report.

Mitigations you will meet

Operating systems and compilers add layers so that a single bug is not enough:

Mitigation What it does What a tester notices
Stack canary A random value is placed before the return address and checked before returning Overflow is detected and the program aborts with "stack smashing detected"
ASLR Address Space Layout Randomization moves the stack, heap and libraries each run Fixed addresses from tutorials no longer work; an info leak is needed
DEP / NX Data pages are marked non-executable Code placed in a buffer will not run
PIE and RELRO Randomize the program image itself; protect relocation tables Fewer fixed targets inside the binary
CFI and shadow stacks Validate that jumps and returns go where the program intended Hijacked control flow is blocked

These do not remove the bug. They raise the cost of exploiting it, and skilled attackers chain several bugs to get around them. So the right fix is always to repair the code, with the mitigations as a safety net.

Python Canaries and ASLR in the toy model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A canary turns silent hijacking into a loud crash, and ASLR makes blind guessing both unreliable and noisy. In a real test, repeated crashes of a service are a reason to stop and tell the client, not to keep trying.

Safe practice for testers

  • Never fuzz or exploit production memory bugs without explicit approval. They can corrupt data or take services down.
  • Test against your own lab copies of vulnerable software (intentionally vulnerable VMs, old releases you install yourself).
  • Prefer a version check or a vendor-published safe check over a full exploit when proving that a patch is missing.
  • Report the exact component, version, CVE and a recommendation (patch, upgrade, compile with hardening flags, or replace with a memory-safe component).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What typically sits just above a local buffer in a stack frame and makes overflows dangerous?

    If input overflows the buffer, it can overwrite saved control data such as the return address.
  2. 2. What is the best fix for a stack buffer overflow in application code?

    Mitigations make exploitation harder, but only fixing the bounds check removes the bug.
  3. 3. What does a stack canary do?

    A random value sits between the buffer and the return address. If an overflow changes it, the check fails and the program stops.
  4. 4. You find a legacy service with a known memory-corruption CVE in production, and the rules of engagement do not mention exploitation. What do you do?

    A version-based finding is evidence enough, and unapproved exploitation could cause an outage or breach the rules.

Summary

  • Memory corruption comes from unchecked writes or lifetimes in languages like C and C++.
  • A stack overflow can overwrite the saved return address; the cure is bounds checking or a memory-safe language.
  • Canaries, ASLR, DEP/NX, PIE and CFI raise the cost of exploitation but do not remove bugs.
  • Testers validate carefully, use lab copies, and report versions and remediation rather than risking production.

Next: Exploit frameworks and safe validation