Week 6 Buffer Overflows
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)
| Section | Format | Marks | Time | Emphasis |
|---|---|---|---|---|
| A — Multiple Choice | 10 questions, 2 marks each | 20 | 1.5 min/question (15 min) | Application, not recall |
| B — Short Answer | Choose 4 of 6, 10 marks each | 40 | 12 min/question (48 min) | Reasoning & structured thinking; labelled diagrams OK |
| C — Short Essays | Choose 2 of 3, 20 marks each | 40 | 20 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
| Reason | Why |
|---|---|
| C and C++ are everywhere | OSes, browsers, embedded/IoT firmware, network stacks |
| Consequences are severe | Crashes, silent corruption, privilege escalation, remote code execution |
| Attackers still target it | A memory bug in privileged code is a route to full compromise |
| Defenses are partial | Canaries, ASLR, DEP raise the bar — they do not remove the bug |
| New code, old mistakes | The same missing-length-check pattern is written fresh every year |
| Understanding is the defense | Recognise 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
ret55 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 width | 32 bits | 64 bits |
| Register prefix | E (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)
| Region | Contents |
|---|---|
| Text (code) | The program's instructions — read-only (can't modify its own code) |
| Data | Initialised global variables — placed at startup, available anywhere |
| Heap | Dynamic memory, allocated/freed on demand; typically grows toward higher addresses |
| Stack | Locals, 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.
- Fetch — control unit reads the next instruction from memory, at the address in EIP
- Decode — works out which operation and what data/registers it needs
- Execute — the ALU performs the operation
- 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
| Register | Name | Role |
|---|---|---|
| EAX | Accumulator | Arithmetic and logic; holds return values |
| EBX | Base | General storage; addressing |
| ECX | Counter | Loop and string counter |
| EDX | Data | General storage; extends EAX |
| ESI/EDI | Source/Dest index | Used by string and memory-copy operations |
| ESP | Stack Pointer | Points to the TOP of the stack; moves with every push/pop |
| EBP | Base Pointer | Fixed anchor for the current stack frame; locals referenced from it |
| EIP | Instruction Pointer | Address 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, plusenter/retfor 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 - 0x10Manage 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:
pushdecrements ESP first, then writes.popreads 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
| Step | Action | Result |
|---|---|---|
| 1 | push 5 | ESP decrements to 0x100, writes 0x00000005 there |
| 2 | push 4 | ESP decrements to 0xFC, writes 0x00000004 there |
| 3 | pop eax | Reads 0x00000004 (at ESP=0xFC) into EAX, ESP increments back to 0x100 |
| 4 | pop ecx | Reads 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
| Element | Detail |
|---|---|
| Local variables & buffers | Sit 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 address | Where execution resumes after the function — what an overflow aims to overwrite |
| The fatal geometry | The 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 overflowWhy it's dangerous:
nameholds 16 bytes — a fixed buffer sitting right below saved EBP and the return addressgets()never checks length — reads until Enter, however long, writes it all intoname- 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
- A function is called —
callpushes the return address onto the stack - The function runs — uses its frame, including buffers
- The function returns —
retpops the saved return address off the stack into EIP - 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:
| Prologue | Undone by |
|---|---|
push ebp | ret |
mov ebp, esp | pop ebp |
sub esp, N | mov esp, ebp |
Bottom-up order: mov esp, ebp → pop ebp → ret. The mov frees locals without needing to know N.
What ret actually does:
- It pops what ESP points at, not ESP itself
pop eipisn't encodable — which is the whole reasonretexists
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 pointermov ebp, esp— snapshots the current stack top into EBP, freezing it for the whole functionsub 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) — amovrather thanadd esp, Nbecause ESP can move by an amount unknown at compile timepop ebp— restores the caller's frame pointer; as a side effect leaves ESP pointing exactly at the return addressret— 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
retloads 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
| Escalation | Detail |
|---|---|
| Execute injected code | Jump to attacker-supplied instructions ("shellcode") placed in memory |
| Open a command shell | The classic goal: interactive control of the machine |
| Bypass security checks | Skip a password comparison or authorization gate entirely |
| Escalate privileges | If the vulnerable process is privileged, inherit that privilege |
| Crash the application | Even a failed hijack often takes the program down — denial of service |
| Take over the system | Chain 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
Three defenses — each breaks a different link (none fixes the missing bounds check)
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)
| Habit | Detail |
|---|---|
| Always bound the copy | Use fgets, strncpy, snprintf — never gets or unbounded strcpy |
| Validate input length | Check incoming data fits the buffer before you write it, every time |
| Use memory-safe languages | Rust, Go, Java, Python bounds-check for you — whole classes of this bug vanish (but still not immune to all bugs) |
| Keep mitigations on | Compile with stack protection, enable ASLR and DEP — cheap insurance |
| Fuzz and audit | Fuzzers and static analysers find these bugs before attackers do |
| Patch and update | Known 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
| Idea | Statement |
|---|---|
| The bug | Writing more into a buffer than it holds spills into adjacent memory |
| The stack | Local buffers sit just below the saved EBP and the return address |
| The geometry | Writes run upward, so an overflow reaches the return address above |
| The hinge | ret loads the return address into EIP, no questions asked |
| The hijack | Overwrite the return address and you choose what EIP runs next |
| The defenses | Canaries, 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 inCompile with protections disabled:
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vuln vuln.c| Flag | What it does |
|---|---|
-m32 | Builds a 32-bit executable instead of the default 64-bit |
-fno-stack-protector | Turns off the stack canary — the guard value normally placed before the return address to detect overwrites |
-z execstack | Marks the stack as executable, so code placed there (like injected shellcode) can run instead of faulting |
-no-pie | Disables 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=./vulnWant 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
checksecoutput 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 exit2. 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 whenhandle_usernamereturned, the CPU tried to jump to0x41414141— 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:
- Press Run (F9, possibly twice) — the program executes and hits the fault
- 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) - 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 theAfiller. If your offset is right, EIP will read exactly0x42424242— 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 step | Mitigation that stops it | Why |
|---|---|---|
| Overwriting the return address without detection | Stack canary | A 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 itself | DEP/NX | With 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)
| Concept | One-liner |
|---|---|
| Buffer overflow, one idea | Writing more into a buffer than it holds — the excess overwrites adjacent memory |
| Why it still matters | Manual memory management (C/C++) + everywhere in critical systems + defenses are only partial |
| Stack growth direction | Stack 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 functions | gets, strcpy, strcat, sprintf — no length limit. Safe cousins: fgets, strncpy, snprintf |
gets() fact | Removed from the C standard in 2011 for being this dangerous |
| The hinge instruction | ret: EIP ← [ESP], then ESP ← ESP + 4 — pops what ESP points at, not ESP itself |
Why ret exists | pop eip isn't encodable — EIP can't be a direct destination operand |
| EBP vs ESP role | EBP = stable anchor (bookmark) for the frame; ESP = the moving top-of-stack pointer (finger) |
| Offset | The exact byte count before the 4 bytes that land on the return address — found empirically with cyclic()/cyclic_find(), not assumed |
| Stack canary | Secret value before the return address — corrupted first by an overflow, checked before ret, aborts on mismatch |
| ASLR | Randomizes stack/heap/library/code load addresses each run — defeats hard-coded jump targets |
| DEP/NX | Marks stack/heap non-executable — defeats running injected shellcode directly |
| Why mitigations aren't bulletproof | Canaries 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 output | Stack 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 toggle | echo 0 | sudo tee /proc/sys/kernel/randomize_va_space (resets on reboot) |
| NOP sled | Padding of no-op instructions before shellcode so EIP doesn't need byte-precise landing |
| Return-to-libc / ROP | Redirect EIP to existing executable code instead of injected code — the answer when NX blocks shellcode injection |