Week 6 Buffer Overflows

Updated 4 Oct 2026

CSS484 — Week 6 Cheat Sheet: Buffer Overflows

"From a missing bounds check to a hijacked instruction pointer, one overwritten return address at a time."The one sentence to carry away: a buffer overflow turns a missing bounds check into control of the instruction pointer, and the fix is as simple as never writing past the end of the buffer.


📋 Midterm Exam Format (from the lecture — know this cold)

SectionFormatMarksTimeEmphasis
A — Multiple Choice10 questions, 2 marks each201.5 min/question (15 min)Application, not recall
B — Short AnswerChoose 4 of 6, 10 marks each4012 min/question (48 min)Reasoning & structured thinking; labelled diagrams OK
C — Short EssaysChoose 2 of 3, 20 marks each4020 min/essay (40 min)Reasoning & structured thinking; Q2 & Q3 require labelled diagrams

Exam rules: One A4 page of notes, both sides allowed. No dictionary, calculator, phone, browser, or AI. Bring student ID.


1. The Big Picture — What a Buffer Overflow Is

Write past the end of a buffer, and you overwrite whatever sits next to it.

The core idea:

  • A program writes more data into a buffer than it was allocated to hold
  • Because memory is contiguous, the extra bytes overwrite adjacent memory the program never meant to touch
  • Too much data, too small a box — more bytes written than the buffer can hold
  • The excess spills sideways — adjacent memory gets overwritten, not the intended target
  • It can corrupt control data — variables, saved registers, and return addresses all live nearby
  • One of the oldest bug classes — documented since the 1980s, exploited to this day
  • C and C++ are prime territory — manual memory management, no automatic bounds checks
  • The prize is control flow — reach the return address, and you steer the program

Analogy: Like coffee spilling from an overfilled cup — the extra data has to go somewhere, and it lands on the memory next door.

Why a 1980s bug still matters

ReasonWhy
C and C++ are everywhereOSes, browsers, embedded/IoT firmware, network stacks
Consequences are severeCrashes, silent corruption, privilege escalation, remote code execution
Attackers still target itA memory bug in privileged code is a route to full compromise
Defenses are partialCanaries, ASLR, DEP raise the bar — they do not remove the bug
New code, old mistakesThe same missing-length-check pattern is written fresh every year
Understanding is the defenseRecognise the pattern and you can prevent an entire bug class

The goal is not to memorise one exploit: it's to understand the mechanism so well you can spot the vulnerable pattern in code and design it out.


2. Machine Foundations

Source → assembly → machine code

The CPU never runs your C. A compiler turns source into assembly (human-readable CPU instructions), then into the raw bytes the processor executes. (Explore at godbolt.org.)

int square(int num) { return num * num; }
push rbp
mov  rbp, rsp
mov  [rbp-4], edi
mov  eax, [rbp-4]
imul eax, eax
pop  rbp
ret
55          push rbp
48 89 E5
89 7D FC
8B 45 FC
0F AF C0
5D
C3          ret

Assembly is the level we work at — the lowest representation a human can read comfortably, and where we watch the stack, registers, and return address change.

x86 vs. x64

This course normally uses 32-bit x86 names, because it keeps addresses short/readable, and most classic overflow material is written this way.

x86 (32-bit)x64 (64-bit)
Register width32 bits64 bits
Register prefixE (EAX, ESP, EIP)R (RAX, RSP, RIP, + R8–R15)
Compatibility—Backward compatible — a 64-bit OS can still run 32-bit software directly

Malware is often 32-bit — broader compatibility, and 64-bit systems run it anyway.

Opcode/operand split: in push rbp, push is the opcode (the instruction), rbp is the operand (what it acts on). Opcodes are mostly the same across x86/x64; the registers differ.

Memory layout — four regions (low → high address)

Text (code)  →  Data  →  Heap (grows ▼ toward higher addr)  →  Stack (grows ▲ toward lower addr)
RegionContents
Text (code)The program's instructions — read-only (can't modify its own code)
DataInitialised global variables — placed at startup, available anywhere
HeapDynamic memory, allocated/freed on demand; typically grows toward higher addresses
StackLocals, frames, return addresses; grows toward lower addresses — this is where overflows bite

⭐ The one rule to remember: the stack grows from high addresses toward low addresses. Diagrams flip orientation freely, but that direction never changes — it is why overflows reach the return address.

How the CPU runs each instruction — fetch/decode/execute

The CPU repeats one loop billions of times a second; EIP tracks the next instruction and advances automatically after each fetch.

  1. Fetch — control unit reads the next instruction from memory, at the address in EIP
  2. Decode — works out which operation and what data/registers it needs
  3. Execute — the ALU performs the operation
  4. Store — result written back to a register or memory — then repeat

Why this is the whole game: the CPU blindly executes whatever EIP points to. It has no idea whether that address is legitimate code or somewhere an attacker redirected it. If you control EIP, the fetch-decode-execute loop will faithfully run your instructions instead.

The x86 registers that matter

RegisterNameRole
EAXAccumulatorArithmetic and logic; holds return values
EBXBaseGeneral storage; addressing
ECXCounterLoop and string counter
EDXDataGeneral storage; extends EAX
ESI/EDISource/Dest indexUsed by string and memory-copy operations
ESPStack PointerPoints to the TOP of the stack; moves with every push/pop
EBPBase PointerFixed anchor for the current stack frame; locals referenced from it
EIPInstruction PointerAddress of the NEXT instruction to execute — the attacker's target

3. The Stack in Motion

The stack, summarised

A region of memory for short-term, per-function storage, run as a strict Last-In-First-Out (LIFO) structure, tracked by the stack pointer.

  • A memory data structure — a dedicated region of memory, not a separate chip
  • LIFO — the most recent thing pushed is the first thing popped
  • Grows high to low — each push moves the top toward lower addresses
  • Driven by push/pop, plus enter/ret for entering/leaving functions
  • Tracked by ESP (marks the top) and EBP (anchors the current frame)
  • Short-term storage only — locals and call state, discarded when the function returns

Analogy: the program's scratchpad for "right now" — each function call borrows a slice, uses it, hands it straight back. That discipline is exactly what makes nested function calls work.

The handful of instructions you need

Move data & arithmetic:

mov eax, ebx   ; copy EBX into EAX
mov eax, 0x42  ; put 0x42 into EAX
add eax, ebx   ; EAX = EAX + EBX
sub eax, 0x10  ; EAX = EAX - 0x10

Manage the stack:

push 5   ; decrement ESP by 4, then write 5 at the new top
pop eax  ; read the top into EAX, then increment ESP by 4
call f   ; push the return address, then jump to f
ret      ; pop the return address into EIP, and jump there

⚠️ Note the exact order: push decrements ESP first, then writes. pop reads first, then increments ESP. This precision matters when tracing the stack.

Worked trace — four instructions, step by step

Program: push 5, push 4, pop eax, pop ecx

StepActionResult
1push 5ESP decrements to 0x100, writes 0x00000005 there
2push 4ESP decrements to 0xFC, writes 0x00000004 there
3pop eaxReads 0x00000004 (at ESP=0xFC) into EAX, ESP increments back to 0x100
4pop ecxReads 0x00000005 (at ESP=0x100) into ECX, ESP increments back to original top

Notice: after two pushes and two pops, ESP returns to where it started — the LIFO discipline in action.


4. Anatomy of the Overflow

What a function call puts on the stack

Every function call builds a stack frame: a slice of the stack holding arguments, the return address, the saved base pointer, and local variables (including buffers).

Stack frame layout (low address/top of stack → high address/caller's frame):

char buf[8]         ← ESP
more locals
saved EBP            ← EBP
return address        (the prize)
arguments
ElementDetail
Local variables & buffersSit at the low-address end, nearest the top of the stack — written as the function runs
Saved base pointer (EBP)The caller's frame anchor, saved to restore when this function returns
Return addressWhere execution resumes after the function — what an overflow aims to overwrite
The fatal geometryThe buffer is BELOW the return address, and writes run upward, from low toward high addresses

Everything hinges on the layout: the buffer sits below saved EBP and the return address. Overfill the buffer, keep writing upward, and you reach both.

What exactly is a buffer?

A small, fixed-size block of memory that temporarily holds data — very often user input. "Fixed" is where the danger lives.

  • Small and fixed-size — capacity decided when code is written
  • Holds temporary data — often exactly what a user/network sends
  • Has a hard maximum — e.g. room for 16 characters, no more
  • Excess must go somewhere — the CPU will not stop the write on its own
  • Needs a size check — safe code compares input length to capacity first
  • The check is often missing — that single omission is the whole vulnerability

Example — a 16-byte buffer holding "HELLO":

H E L L O [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
capacity: 16 bytes · used: 5 · free: 11

If the program writes "HELLO", all is well. If it writes 40 characters without checking, the last 24 land outside this box, on whatever memory follows.

The overflow, byte by byte

Normal:

buf: "HELLO"
saved EBP
return addr: 0x08...

Overflowed (40 bytes of "A"):

AAAAAAAAAAAA      (buffer overwritten)
AAAAAAAA          (saved EBP overwritten)
return addr: 0x41414141   (hijacked!)

0x41 is the hex for the letter "A". Writing 40 A's overwrites the return address with 0x41414141 — an address the attacker now controls. When the function returns, the CPU jumps there.

⚠️ Two directions, don't confuse them: new stack frames grow DOWN (toward low addresses), but writes inside a buffer go UP (toward high addresses). The upward write is what reaches the return address.

The bug in real code

vulnerable.c:

void greet(void) {
    char name[16];       // 16 bytes on the stack
    gets(name);          // BAD: no length limit
    printf("Hi %s\n", name);
}

fixed.c:

fgets(name, sizeof(name), stdin);
// fgets stops at 15 chars + null: it cannot overflow

Why it's dangerous:

  • name holds 16 bytes — a fixed buffer sitting right below saved EBP and the return address
  • gets() never checks length — reads until Enter, however long, writes it all into name
  • Type 40 characters, and 24 overwrite whatever follows: saved EBP, then the return address
  • The infamous functions: gets, strcpy, strcat, sprintf — all copy without a length limit. Their safe cousins take a size.

This is not a contrived example. gets() was so dangerous it was removed from the C standard in 2011, yet vulnerable copies still ship in real software today.

The return address and EIP — the hinge

  1. A function is called — call pushes the return address onto the stack
  2. The function runs — uses its frame, including buffers
  3. The function returns — ret pops the saved return address off the stack into EIP
  4. The CPU jumps there — EIP now points at that address; the CPU fetches and runs whatever is there

The hinge: the return address is just bytes sitting on the stack. The stack is writable memory. A buffer overflow can write those bytes. So ret will happily load an attacker-chosen value into EIP.

⭐ This is the sentence the whole lecture builds to: if you can overwrite the return address, you can put any value into EIP, and EIP decides what the CPU does next.

Going deeper — offsets from EBP

[EBP+8]  → arg 1
[EBP+4]  → return address
[EBP+0]  → saved EBP
[EBP-4]  → local var
[EBP-12] → buf[8]

The epilogue is the prologue undone:

PrologueUndone by
push ebpret
mov ebp, esppop ebp
sub esp, Nmov esp, ebp

Bottom-up order: mov esp, ebp → pop ebp → ret. The mov frees locals without needing to know N.

What ret actually does: EIP←[ESP],ESP←ESP+4EIP \leftarrow [ESP], \quad ESP \leftarrow ESP + 4

  • It pops what ESP points at, not ESP itself
  • pop eip isn't encodable — which is the whole reason ret exists

Why this is exploitable: buf[8] sits at a lower address than the return address, so an overrun writes upward into [EBP+4]. ESP is never touched — it still points exactly where it should, and the CPU has no way to tell anything is wrong.

Going deeper, in words (the mechanism, full walkthrough)

The call: caller pushes arguments, executes call. call pushes the address of the next instruction (the return address) onto the stack, then jumps. Stack grows downward, so each push lands at a lower address.

Prologue (callee sets up its frame):

  • push ebp — saves the caller's frame pointer
  • mov ebp, esp — snapshots the current stack top into EBP, freezing it for the whole function
  • sub esp, N — carves out space for locals
  • From here everything has a fixed offset from EBP

During the body: ESP sits at the bottom of the locals and keeps moving as the function pushes args for further calls. ESP does not track the return address — EBP does. That's the entire purpose of a frame pointer: a stable anchor while ESP wanders.

Epilogue (prologue undone in reverse):

  • mov esp, ebp — discards the locals in one instruction (deallocation, not repositioning) — a mov rather than add esp, N because ESP can move by an amount unknown at compile time
  • pop ebp — restores the caller's frame pointer; as a side effect leaves ESP pointing exactly at the return address
  • ret — transfers control back

Analogy: Think of EBP as a bookmark that never moves during a chapter (the function), while ESP is a finger sliding up and down the page as things get pushed and popped. When the chapter ends, the bookmark tells you exactly where to put the finger back.


5. Hijacking Control Flow

The moment of the hijack

; the stack slot for the return address now holds attacker bytes
[esp] = 0xDEADBEEF
 
ret
; 1. pop [esp] into EIP
; 2. EIP = 0xDEADBEEF
; 3. CPU jumps to 0xDEADBEEF
; the program is no longer running its own code
  • The buffer sat near the return address — so the overflow reached it
  • The extra input overwrote it — the original return address is gone
  • ret loads it into EIP — the CPU does not validate the address; it simply jumps
  • The program jumps to the new location

The original return address is lost. The program no longer returns where it should — it jumps wherever the attacker's bytes point, and the hijack is complete.

What an attacker does with control

EscalationDetail
Execute injected codeJump to attacker-supplied instructions ("shellcode") placed in memory
Open a command shellThe classic goal: interactive control of the machine
Bypass security checksSkip a password comparison or authorization gate entirely
Escalate privilegesIf the vulnerable process is privileged, inherit that privilege
Crash the applicationEven a failed hijack often takes the program down — denial of service
Take over the systemChain the above into full, persistent control of the host

Impact scales with the privilege of the vulnerable code. A single missing length check, in the wrong place, can hand an attacker the entire machine.

The whole attack, end to end (six steps — know this sequence)

1. A small buffer        → program declares a fixed-size buffer on the stack
2. Unchecked input        → reads user input with no length check
3. Input exceeds size     → attacker supplies far more data than the buffer holds
4. The stack is overwritten → excess bytes run up through saved EBP into return address
5. Return address replaced → the saved return address becomes an attacker-chosen value
6. CPU jumps to attacker code → on ret, EIP loads that value and execution is hijacked

6. Defenses & Prevention

Stack Canary

  • A secret random value placed between local buffers and the saved return address
  • How it helps: any overflow reaching the return address must overwrite the canary first — a pre-return check catches it and aborts
  • Breaks: silently overwriting the return address

ASLR (Address Space Layout Randomization)

  • Shuffles where stack, heap, libraries, and code load on every run
  • How it helps: the attacker cannot know which address to jump to — a hard-coded target fails because it moves every run
  • Breaks: choosing a reliable value to put in EIP

DEP / NX (Data Execution Prevention)

  • Marks the stack and heap as non-executable memory
  • How it helps: even if EIP lands on injected shellcode, the CPU refuses to run instructions from a data region
  • Breaks: running injected code off the stack

Layered, not bulletproof: canaries can be leaked, ASLR can be defeated with an address leak, and DEP is bypassed by reusing existing code (ROP). They make attacks harder, not impossible, and none fixes the bug itself.

How to actually prevent the bug (defense mindset)

HabitDetail
Always bound the copyUse fgets, strncpy, snprintf — never gets or unbounded strcpy
Validate input lengthCheck incoming data fits the buffer before you write it, every time
Use memory-safe languagesRust, Go, Java, Python bounds-check for you — whole classes of this bug vanish (but still not immune to all bugs)
Keep mitigations onCompile with stack protection, enable ASLR and DEP — cheap insurance
Fuzz and auditFuzzers and static analysers find these bugs before attackers do
Patch and updateKnown overflow bugs get fixed upstream — keep dependencies current

The defender's mindset: treat every byte of external input as hostile, and never let it write past a boundary. Get that one habit right and the overflow never happens.

Summary — the whole lecture in seven ideas

IdeaStatement
The bugWriting more into a buffer than it holds spills into adjacent memory
The stackLocal buffers sit just below the saved EBP and the return address
The geometryWrites run upward, so an overflow reaches the return address above
The hingeret loads the return address into EIP, no questions asked
The hijackOverwrite the return address and you choose what EIP runs next
The defensesCanaries, ASLR, DEP raise the bar; bounds-checking removes the bug

7. 🖥️ LAB SECTION — Week 6 Workshop: Smashing the Stack

The point of the workshop: to make the theory physical — you see, with your own eyes in a debugger, your input bytes overwrite the return address and land in EIP. That moment makes the whole mechanism click.

Setup needed: Kali lab VM, a C compiler, a debugger, and the lecture's core concepts (stack frame layout, saved return address, EIP, the three mitigations). You will be switching those mitigations off deliberately.

Exercise 1 — Build a vulnerable program with its guards down

Goal: write & compile a deliberately vulnerable 32-bit C program with stack canary, executable-stack protection, and position-independence all disabled — then confirm those protections are really off.

The vulnerable program (vuln.c):

#include <stdio.h>
#include <string.h>
 
void handle_username(const char *input) {
    char username[64];
    strcpy(username, input); // VULNERABLE: no bounds check
    printf("Hello, %s!\n", username);
}
 
int main(int argc, char **argv) {
    if (argc > 1)
        handle_username(argv[1]);
    return 0;
}

Install 32-bit build tooling first:

sudo apt update && sudo apt install gcc-multilib
# accept restart defaults, log out and back in

Compile with protections disabled:

gcc -m32 -fno-stack-protector -z execstack -no-pie -o vuln vuln.c
FlagWhat it does
-m32Builds a 32-bit executable instead of the default 64-bit
-fno-stack-protectorTurns off the stack canary — the guard value normally placed before the return address to detect overwrites
-z execstackMarks the stack as executable, so code placed there (like injected shellcode) can run instead of faulting
-no-pieDisables position-independent executable generation — binary loads at a fixed, predictable address rather than randomized

Disable ASLR for your session:

echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
cat /proc/sys/kernel/randomize_va_space   # confirm it prints 0

0 = off, 2 = normal default. This resets on VM reboot — must be re-run after restarting.

Verify protections are off with checksec:

sudo apt install checksec
checksec --file=./vuln

Want to see:

Stack Canary: No canary found
NX: NX disabled
PIE: No PIE

Worked discussion (why this matters): with these off, the binary matches the conditions assumed in the lecture — a fixed, predictable load address (no PIE, no ASLR), no compiler-inserted guard value, and a stack region the CPU is willing to execute instructions from. With any one of these left on, the overflow in Exercises 2/3 would either be silently caught (canary), land at an unpredictable address (ASLR/PIE), or be unable to run injected code directly (NX) — exactly the point: these protections exist specifically to interrupt the chain of events this workshop demonstrates.

Report checklist:

  • Your C source, vulnerable line clearly identifiable
  • The exact compile command + one-line explanation of each flag
  • Screenshot of checksec output showing canary/NX/PIE all disabled

Exercise 2 — Trigger the crash and find the offset

Goal: overflow the buffer to crash the program, then determine the precise offset from the start of input to the saved return address.

1. Confirm normal behaviour (baseline):

./vuln Matthew
# → "Hello, Matthew!" and a clean exit

2. Overflow it:

./vuln $(python3 -c 'print("A"*200)')

Buffer is 64 bytes, so 200 A's is comfortably past the return address → Segmentation fault. The A's (0x41) overwrote the saved return address, so when handle_username returned, the CPU tried to jump to 0x41414141 — not a valid instruction address.

Worked example (actual run): running the 200-byte overflow first in a plain shell (no debugger attached) confirms the crash isn't an artifact of the debugging environment — the shell's own segmentation fault message shows the same fault happens with or without edb watching. The debugger is only needed to see why it crashes.

3. Find the exact offset (empirically, not by guessing):

sudo apt install python3-pwntools
python3 -c 'from pwn import *; print(cyclic(200).decode())'
# or directly:
edb --run ./vuln $(python3 -c 'from pwn import *;print(cyclic(200).decode())')

In EDB:

  1. Press Run (F9, possibly twice) — the program executes and hits the fault
  2. When it crashes, EDB freezes at the faulting state — look at the EIP register (top right) or the popup error. It holds a 4-byte value from your pattern (e.g. 0x61616174)
  3. Read that value back to its offset:
python3 -c 'from pwn import *; print(cyclic_find(0x61616174))'

That number is your offset — the count of bytes before the four that land on EIP. For a 64-byte buffer on a typical 32-bit frame it usually comes out to 76 (64 buffer + 8 alignment/locals + 4 saved EBP) — but read it off the tool rather than assuming, since frame layout varies with compiler version and flags.

Worked example (actual run detail): EDB's status bar reported SIGSEGV: SEGV_MAPERR: Accessed address 0x61616174 not mapped, and EIP held that same value — a 4-byte fragment of the cyclic pattern (also visible in ASCII in ESP as "uaavaaawaaaxaaa..."). Running cyclic_find(0x61616174) returned an offset of 76.

4. Prove your offset is correct:

edb --run ./vuln $(python3 -c 'print("A"*76 + "B"*4)')

Use Bs (0x42) as markers so they're unmistakable against the A filler. If your offset is right, EIP will read exactly 0x42424242 — your four Bs and nothing else. That's the proof: you've placed a value of your choosing precisely onto the return address.

⚠️ What an incorrect offset would look like (and why it matters): if the offset were wrong, EIP would instead hold a mixture of A and B bytes (e.g. 0x42414141 or 0x41414242), or an address made up entirely of A's if the marker bytes hadn't yet reached the return-address slot. The offset matters because it's the precondition for control: without knowing exactly how many bytes precede the return address, an attacker cannot place a specific 4-byte value (like the address of injected shellcode) onto EIP — they could only crash the program, not direct it.

Why the cyclic-pattern method beats reasoning from buffer size alone: because every 4-byte window in cyclic(200)is unique, the specific 4 bytes landing in EIP at the crash can be mapped back, via cyclic_find, to their exact position in the original input. This is more reliable than reasoning purely from the declared buffer size, since the compiler may insert additional padding, alignment bytes, or saved registers between the buffer and the return address that aren't visible from source alone.

Report checklist:

  • Screenshots (baseline run, crash, EDB EIP=cyclic value, EDB EIP=0x42424242 proof)
  • The offset found + how you determined it
  • 1–2 sentences: what an incorrect offset would look like, and why the offset matters for precise control

Exercise 3 — Reason about what comes next (no lab commands — conceptual)

Now that EIP holds an attacker-controlled value, the return address no longer points back into main — it points wherever the attacker chooses.

The classic approach — inject shellcode:

  • A short sequence of machine instructions (typically spawning a shell — execve("/bin/sh")) is injected into the buffer itself, as part of the overflowing input
  • EIP is set to the address where that buffer sits in memory
  • When the function returns, execution jumps into the attacker's bytes and runs them
  • NOP sled refinement: pad the front of the shellcode with no-op instructions so EIP only has to land somewhere in that range rather than the exact first byte

When injected code can't run — return-to-libc / ROP:

  • Instead of injecting new code, point EIP at code already present in a library function or existing instruction sequences
  • This is what attackers turn to when NX/DEP blocks injected code execution

🎯 Mapping each attack step to the mitigation that would have stopped it (the workshop's actual final question — high-yield for the exam)

Attack stepMitigation that stops itWhy
Overwriting the return address without detectionStack canaryA canary sits between the buffer and the saved return address; the epilogue checks it against a known value immediately before ret executes, so an overflow reaching the return address must first overwrite (and corrupt) the canary — causing the program to abort deliberately rather than letting ret load an attacker-chosen EIP at all
Knowing where to point EIP(predicting the injected buffer's address)ASLR (and PIE)With ASLR on, the stack's base address is randomised every run, so a hard-coded target almost never lands inside the buffer; PIE similarly randomises where the executable itself loads. Disabling both is what made the fixed, guessable address in Exercise 2 possible
Executing the injected shellcode itselfDEP/NXWith NX enabled, the stack region is marked non-executable — even if EIP is successfully redirected into the buffer, the CPU refuses to fetch instructions from that page and the process faults instead of running attacker code. This is exactly why attackers facing NX turn to return-to-libc/ROP: those redirect execution to existing, already-executable code, sidestepping NX entirely

Layered defence, not a single gate: the canary would have stopped corruption from reaching EIP at all; ASLR/PIE would have stopped the attacker from knowing where to aim even if EIP were reached; NX would have stopped the payload from running even if EIP were aimed correctly. Defeating all three simultaneously (info leak + ROP) is significantly harder than defeating any one alone — the practical justification for enabling all three by default.


8. Rapid-Fire Recall Table (Last-Minute Review)

ConceptOne-liner
Buffer overflow, one ideaWriting more into a buffer than it holds — the excess overwrites adjacent memory
Why it still mattersManual memory management (C/C++) + everywhere in critical systems + defenses are only partial
Stack growth directionStack frames grow DOWN (toward low addresses); writes inside a buffer go UP (toward high addresses) — that's what reaches the return address
Stack frame order (low→high)buffer → other locals → saved EBP → return address (the prize) → arguments
The infamous unsafe functionsgets, strcpy, strcat, sprintf — no length limit. Safe cousins: fgets, strncpy, snprintf
gets() factRemoved from the C standard in 2011 for being this dangerous
The hinge instructionret: EIP ← [ESP], then ESP ← ESP + 4 — pops what ESP points at, not ESP itself
Why ret existspop eip isn't encodable — EIP can't be a direct destination operand
EBP vs ESP roleEBP = stable anchor (bookmark) for the frame; ESP = the moving top-of-stack pointer (finger)
OffsetThe exact byte count before the 4 bytes that land on the return address — found empirically with cyclic()/cyclic_find(), not assumed
Stack canarySecret value before the return address — corrupted first by an overflow, checked before ret, aborts on mismatch
ASLRRandomizes stack/heap/library/code load addresses each run — defeats hard-coded jump targets
DEP/NXMarks stack/heap non-executable — defeats running injected shellcode directly
Why mitigations aren't bulletproofCanaries can leak, ASLR can be defeated by an address leak, NX bypassed via ROP/ret-to-libc
Real fix (not mitigation)Bound every copy, validate length, use memory-safe languages, keep mitigations on, fuzz/audit, patch
checksec good outputStack Canary: No canary found / NX: NX disabled / PIE: No PIE (deliberately weakened for the lab)
Compile flags for the lab-m32 (32-bit) · -fno-stack-protector (no canary) · -z execstack (executable stack) · -no-pie(fixed load address)
ASLR toggleecho 0 | sudo tee /proc/sys/kernel/randomize_va_space (resets on reboot)
NOP sledPadding of no-op instructions before shellcode so EIP doesn't need byte-precise landing
Return-to-libc / ROPRedirect EIP to existing executable code instead of injected code — the answer when NX blocks shellcode injection