Lecture 6 - Buffer Overflows

Updated 14 Oct 2026

CSS484 · Ethical Hacking · Lecture 06 — Buffer Overflows

From a missing bounds check to a hijacked instruction pointer, one overwritten return address at a time Dr. Matthew Gaber For defence, testing, and understanding risk.


Mid Term Exam Info

  • Section A – Multiple Choice (10 questions)
    • 2 marks each = 20 marks
    • 1.5 minutes per question = 15 minutes
    • Emphasis: application, not recall
  • Section B – Short Answer (4 questions)
    • Choose 4 out of 6
    • 10 marks each = 40 marks
    • 12 minutes per question = 48 minutes
    • Emphasis: reasoning and structured thinking
    • May use clearly labelled diagrams to support answers where appropriate
  • Section C – Short Essays (2 questions)
    • Choose 2 out of 3
    • 20 marks each = 40 marks
    • 20 minutes per essay = 40 minutes
    • Emphasis: reasoning and structured thinking
    • Questions 2 and 3 require clearly labelled diagrams
  • Exam rules
    • One A4 piece of paper, notes allowed on both sides
    • No dictionary, no calculator, no phone, no browser, no AI
    • Bring student ID

Section 1 · The Big Picture

What a buffer overflow is

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

[Image]

A buffer overflow, in one 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

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

  • Decades of mitigations have made exploitation harder, not impossible
  • The bug class is alive because the conditions that create it are still everywhere
  • C and C++ are everywhere — operating systems, browsers, embedded and 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, and 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 is to understand the mechanism so well that you can spot the vulnerable pattern in code and design it out.


Section 2 · Machine Foundations

How the machine runs code

  • Assembly, registers, and memory: just enough to see the overflow clearly

[Image]

Source becomes assembly becomes 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 this at godbolt.org

C source (what the developer wrote):

int square(int num)
{
    return num * num;
}

Assembly (Intel) — human-readable CPU steps:

push rbp
mov  rbp, rsp
mov  [rbp-4], edi
mov  eax, [rbp-4]
imul eax, eax
pop  rbp
ret

Machine code — the bytes the CPU executes:

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. It is the lowest representation a human can read comfortably, and it is where we watch the stack, registers, and return address change.

Two worlds: x86 and x64

  • The same ideas, at two register widths
  • We will normally use 32-bit x86 names, because it keeps the addresses short and readable, and most classic overflow material is written this way
  • x86 — 32-bit. Registers and memory addresses are 32 bits long. Registers use the E prefix: EAX, ESP, EIP
  • x64 — 64-bit. Registers and addresses are 64 bits long. Registers use the R prefix: RAX, RSP, RIP, plus R8 to R15
  • Largely the same — same instructions and logic; the main difference is register size
  • 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

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

How memory is laid out

  • When a program runs, it is laid out in memory (think RAM) in four regions
  • Two of them, the stack and the heap, grow toward each other. The stack is our whole story today

Low address → High address:

  • Text (code) — the program's instructions, read-only. Read-only, so the program cannot modify its own code
  • Data — initialised global variables. Global values placed at startup and available to any part of the program
  • Heap — dynamic memory, grows down ▼. Allocated and freed on demand as the program runs; typically grows toward higher addresses
  • Stack — locals, frames, return addresses, grows up ▲. Local variables, function parameters, and control data. 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 the orientation freely, but that direction never changes, and it is why overflows reach the return address.

How the CPU runs each instruction

  • The CPU repeats one simple loop billions of times a second
  • The instruction pointer (EIP) tracks which instruction is next, and it advances automatically after each fetch
  1. Fetch — the control unit reads the next instruction from memory, at the address in EIP
  2. Decode — it works out which operation this is and what data or registers it needs
  3. Execute — the ALU performs the operation: add, subtract, compare, move, and so on
  4. Store — the result is written back to a register or to memory. Then repeat
  • ↻ the instruction pointer (EIP) advances after each fetch, so the loop marches through the program automatically

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.

[Image] — fetch/decode/execute cycle diagram (Control Unit / ALU / Registers / Main Memory)

The x86 registers that matter

  • Registers are the CPU's small, fast, on-chip storage
  • A few are general-purpose; three are special, and two of those three run our entire story
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 and pop
EBPBase Pointerfixed anchor for the current stack frame; locals are referenced from it
EIPInstruction Pointeraddress of the NEXT instruction to execute; the attacker's target

Section 3 · The Stack in Motion

Watching the stack work

  • Push, pop, and the stack pointer: the mechanics an overflow will abuse

[Image]

The stack, summarised

  • A region of memory for short-term, per-function storage, run as a strict Last-In-First-Out structure and tracked by the stack pointer
  • A memory data structure — a dedicated region of memory, not a separate chip
  • Last-In, First-Out — 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 and pop — plus enter and ret for entering and leaving functions
  • Tracked by ESP and EBP — ESP marks the top; EBP anchors the current frame
  • Short-term storage only — locals and call state, discarded when the function returns

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

The handful of instructions we need

  • You do not need the full instruction set to follow an overflow
  • These few move data, do arithmetic, and manage the stack
  • Reminder: opcode first, then destination, then source

Move data & do arithmetic:

  • mov eax, ebx → copy the contents of EBX into EAX
  • mov eax, 0x42 → put the value 0x42 into EAX
  • add eax, ebx → EAX=EAX+EBXEAX = EAX + EBX
  • sub eax, 0x10 → EAX=EAX−0x10EAX = 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 for push and pop: push decrements ESP first, then writes. pop reads first, then increments ESP. This precision matters when we trace the stack.

Trace it: four instructions, step by step

  • The program runs: push 5, push 4, pop eax, pop ecx
  • Watch the stack memory (left) and ESP (right) after each step
  • Higher addresses are at the bottom, matching how the stack grows upward on the page

Initial state:

Memory AddressValue
0xE8
0xEC
0xF0
0xF4
0xF8
0xFC
0x100
RegisterValue
EAX
EBX
ECX
EDX
ESP

Step 1 — push 5

  • ESP decrements to 0x00000100, writes 0x00000005 at that address
Memory AddressValue
0x1000x00000005

ESP = 0x00000100

Step 2 — push 4

  • ESP decrements further to 0x000000FC, writes 0x00000004
Memory AddressValue
0xFC0x00000004
0x1000x00000005

ESP = 0x000000FC

Step 3 — pop eax

  • Reads value at ESP (0x00000004) into EAX, then ESP increments back to 0x00000100
RegisterValue
EAX0x00000004

ESP = 0x00000100

Step 4 — pop ecx

  • Reads value at ESP (0x00000005) into ECX, then ESP increments
RegisterValue
EAX0x00000004
ECX0x00000005

ESP = ???? (back to original top of stack before the pushes)

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


Section 4 · Anatomy of the Overflow

Inside a stack buffer overflow

  • A frame, a buffer, a missing check, and the return address sitting right above

[Image]

What a function call puts on the stack

  • Every function call builds a stack frame: a slice of the stack holding its arguments, the return address, the saved base pointer, and its 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

  • Local variables & buffers — sit at the low-address end, nearest the top of the stack. Written into as the function runs

  • Saved base pointer (EBP) — the caller's frame anchor, saved so it can be restored when this function returns

  • The return address — where execution resumes after the function. This is 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 the 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
  • The word "fixed" is where the danger lives
  • Small and fixed-size — its capacity is decided when the code is written
  • Holds temporary data — often exactly the text a user or a network sends in
  • Has a hard maximum — for example, 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 — and 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

  • Write past the buffer's capacity and the extra bytes overwrite adjacent stack data
  • Here, 24 bytes of excess march up through the saved EBP and into the return address

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=ASCII ’A’\boxed{0x41 = \text{ASCII 'A'}}

  • 0x41 is the hex for the letter "A". So 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, do not 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

  • Enough diagrams, here is an actual vulnerable function
  • gets() and strcpy() copy input with no length limit, so a long input runs straight off the end of the buffer

vulnerable.c

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

The fix: bound the read to the buffer size — fixed.c

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

Why it is dangerous:

  • name holds 16 bytes — a fixed buffer sitting on the stack, right below the saved EBP and return address
  • gets() never checks length — it reads input until the user presses Enter, however long that is, and writes it all into name
  • Type 40 characters, and 24 of them overwrite whatever follows the buffer: 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() is so dangerous it was removed from the C standard in 2011, yet vulnerable copies like these still ship in real software today.

The return address and EIP

  • The link that turns a memory write into code execution
  • The return address is just data on the stack, until ret loads it into EIP and makes it the next instruction
  1. A function is called — call pushes the return address (where to resume) onto the stack
  2. The function runs — it uses its stack frame, including any buffers, doing its work
  3. The function returns — ret pops the saved return address off the stack and loads it into EIP
  4. The CPU jumps there — EIP now points at that address, so 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. Control the return address, and you control the instruction pointer

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.

The return address and EIP — going deeper

  • Why the epilogue restores ESP, and why a buffer overflow never has to touch it

Stack frame with offsets from EBP (high → low addresses):

  • [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: mov esp, ebp → pop ebp → ret. The mov frees locals without knowing N

What ret actually does:

EIP←[ESP],ESP←ESP+4\boxed{EIP \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.

The return address and EIP — going deeper, in words

The call:

  • Caller pushes arguments, then 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: return address at [EBP+4], saved EBP at [EBP+0], locals at negative offsets

During the body:

  • ESP sits at the bottom of the locals and keeps moving as the function pushes arguments 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 (the prologue undone in reverse):

  • mov esp, ebp — discards the locals in one instruction. Its job is deallocation, not repositioning
  • A mov rather than add esp, N because ESP can move by an amount unknown at compile time; EBP was snapshotted before any of that
  • pop ebp — restores the caller's frame pointer, and as a side effect leaves ESP pointing exactly at the return address
  • ret — transfers control back

What ret does:

  • EIP←[ESP]EIP \leftarrow [ESP] then ESP←ESP+4ESP \leftarrow ESP + 4 (RIP and +8 in 64-bit)
  • It pops what ESP points at, not ESP itself — ESP is the pointer, the dword at that address is the value
  • Architecturally identical to pop eip, which doesn't exist because EIP isn't encodable as a destination operand
  • ret imm16 pops the address first, then adds the immediate — that's stdcall, callee cleans the args

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.


Section 5 · Hijacking Control Flow

Pulling the trigger

  • From an overwritten return address to a program running the attacker's will

[Image]

The moment of the hijack

  • The overflow has already overwritten the return address
  • Now the function reaches its final instruction, ret, and the trap springs

What ret does with the poisoned value:

; 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 two are only a few bytes apart in the frame
  • The extra input overwrote it — the original return address is gone, replaced by the attacker's value
  • ret loads it into EIP — the CPU does not validate the address; it simply jumps
  • The program jumps to the new location — execution continues from wherever the attacker pointed it

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

  • Once you control EIP, you control execution, and control of execution is control of the program
  • The possibilities escalate quickly from nuisance to catastrophe
  • Execute injected code — jump to attacker-supplied instructions ("shellcode") placed in memory
  • Open a command shell — the classic goal: a shell gives interactive control of the machine
  • Bypass security checks — skip a password comparison or an 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

This is why the bug class is so feared: a single missing length check, in the wrong place, can hand an attacker the entire machine. Impact scales with the privilege of the vulnerable code.

The whole attack, end to end

  • Six steps, every one of which we have now studied
  • This is the complete arc, from a small buffer and careless input to the CPU running attacker code
  1. A small buffer — the program declares a fixed-size buffer on the stack
  2. Unchecked input — it reads user input into that buffer with no length check
  3. Input exceeds size — the attacker supplies far more data than the buffer holds
  4. The stack is overwritten — excess bytes run up through saved EBP into the 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

Section 6 · Defenses & Practice

Fighting back

  • The mitigations that make exploitation hard, and why the bug still matters

[Image]

Three defenses, and how they break the chain

  • Each mitigation targets a different link in the attack chain
  • None of them fixes the missing bounds check itself

Stack Canary

  • A secret random value placed between the 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 the 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.

How to actually prevent the bug (Defense hat)

  • The mitigations are your safety net. The real fix is upstream: write code that cannot overflow in the first place
  • These habits close the bug class at the source
  • Always bound the copy — use the length-aware functions: fgets, strncpy, snprintf. Never gets or unbounded strcpy
  • Validate input length — check that incoming data fits the buffer before you write it, every time
  • Use memory-safe languages — Rust, Go, Java, and Python bounds-check for you. Whole classes of this bug vanish, but still not immune
  • Keep mitigations on — compile with stack protection, enable ASLR and DEP. They are 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, tracing the single thread from a missing check to a hijacked CPU
  • 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

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.

This week's exercise

  • A guided walkthrough where you make an overflow happen, and watch the return address and instruction pointer change as you do

What you will do:

  • Work in Kali
  • Compile a vulnerable program — a small C program with a classic unbounded input bug, like today's example
  • Trigger the overflow — feed it oversized input and observe the crash as the return address is corrupted
  • Watch it in a debugger — inspect the stack, ESP, and EIP, and see your input land on the return address

The point: to make today's theory physical — you will 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.

  • Full instructions are on Google Classroom. Work through the walkthrough at your own pace

[Image] — Thank you slide

CSS484 · Week 6 · Buffer Overflows: from a missing bounds check to a hijacked instruction pointer