Week 5 Exploit Development
CSS484 — Week 5 Cheat Sheet: Exploit Development
"Turning unintended behaviour into controlled behaviour: input, memory, architecture, representation." The whole arc in one sentence: a wrong assumption in code → becomes a memory bug → becomes control over the instruction pointer → becomes arbitrary code execution.
1. Foundations — What Makes a Bug Exploitable
A computer does what it is told, not what the developer meant.
Exploit development, defined
Turning unintended behaviour into controlled behaviour. Key question: "Can an attacker steer this behaviour reliably and repeatably?"
Four overlapping skill sets:
| Skill | Why it's needed |
|---|---|
| Programming | Understand what the code intended to do |
| Operating systems | Understand privilege and isolation |
| Debugging | Observe real runtime behaviour |
| Reverse engineering | Reason about binaries with no source |
Vulnerability vs. Exploit — NOT the same thing (guaranteed exam question)
| Term | Meaning |
|---|---|
| Vulnerability | A weakness — bug, design flaw, or incorrect assumption — that could lead to unintended behaviour |
| Exploit | Crafted input/code that reliably triggers the weakness to achieve a specific outcome |
One vulnerability, many exploits — e.g. a buffer overflow in a file parser can lead to:
- Denial of service — crash the program
- Information disclosure — leak adjacent memory
- Control-flow hijack — change what executes
Analogy: The vulnerability is the unlocked door; the exploit is the specific way someone chooses to walk through it (steal something, hide inside, prop it open for later).
Fix the vulnerability, not just one exploit. Unless the underlying weakness is removed, attackers develop new exploit variants. CVEs track vulnerabilities but rarely capture exploitability context.
From computation to vulnerabilities
The CPU has no idea what a "string" or a "safe input" is. It knows registers, addresses, and instructions. Vulnerabilities live in what the CPU does not enforce.
| Developer assumes | The CPU enforces |
|---|---|
| "strings are null-terminated" | Nothing — just writes bytes |
| "this length is reasonable" | No bound on any value |
| "this pointer is valid" | No notion of a valid pointer |
A program is a state machine: input drives transitions between states. Vulnerabilities occur when attacker-controlled input forces a transition into a state the developer never intended or tested. Exploit dev = finding those unintended states and reaching them reliably.
Most memory bugs are correct code under incorrect assumptions — the code works perfectly under normal conditions, which is exactly why the bugs are so hard to see.
2. Finding Bugs — Where Vulnerabilities Hide
Follow untrusted input across trust boundaries into risky operations.
The code review mindset
You are not looking for "bad code" in general — you're looking for mismatches between trust and behaviour. Start at the attack surface, follow the data.
Track the dataflow: input (untrusted enters) → size (used to compute a size) → allocation (buffer allocated) → copy(data copied in)
Key checks:
- Attack surface first — where does untrusted input enter the program?
- Trust boundaries — user→service, network→parser, app→kernel
- Risky operations — copies, parsing, indexing, casts, allocations
- Check the invariants — length fields, null-termination, encoding assumptions
- "Almost validated" — validated once, then transformed later and re-trusted (dangerous!)
Ask of every edge case: what happens at 0, at max, at negative, on overflow, on truncation? Critical bugs love the edges.
Privilege & impact — the same bug, different blast radius
| Context | Impact |
|---|---|
| Same bug in a user-level app | One user can crash their own program — limited blast radius |
| Same bug in a privileged service | Full system compromise — the bug now runs above the attacker |
High-value privilege targets: root/admin · SYSTEM · NT AUTHORITY · kernel drivers · auth components · sandbox boundary
The exploit chain:
- Low-priv bug — code exec in a sandbox (e.g. browser renderer)
- Privilege escalation — a second bug escapes the sandbox / escalates = full compromise
The real question is not "can this code crash?" It is "what can this code access if it misbehaves?" That is why least privilege and sandboxing matter.
Input validation, done right
Not about filtering "bad characters" — about enforcing a strict contract between input and internal representation, and validating again after every transformation.
- Validate every field — type, range, length, encoding, on all attacker-controlled input
- Prefer allow-lists — known-good formats beat trying to block bad characters
- Re-validate after transforms — decode, decompress, normalize can all invalidate earlier checks
- Normalize carefully — avoid double-decoding and inconsistent parsing across components
- Use safe APIs — bounded copies, checked conversions, hardened parsing libraries
- Fail closed — reject invalid input, never guess intent or auto-correct
Treat integer math as hostile. Overflow, underflow, signedness, and truncation break "validated" values.
3. Memory — Buffer Overflows
Writing past the end of a fixed-size region, and what lies next to it.
The core idea
Writing more data into a buffer than it can hold. Because memory is contiguous, the excess overwrites adjacent memory the program never meant to touch.
| Term | Definition |
|---|---|
| Buffer | A generic block of memory |
| Stack | A limited region handling function calls and local variables |
| Stack overflow | A buffer overflow that happens on the stack |
| Heap | A separate region that persists data across calls |
What overflowing a stack buffer hits (top→bottom order, overflow writes toward higher addresses):
buffer[ ] → other locals → saved EBP (frame pointer) → return address (where CPU returns)
Analogy: Imagine a hallway of labelled boxes stacked one after another. If you pour too much water into the first box, it overflows into the next, then the next — eventually flooding the box that says "where to go next" (the return address).
The CPU does not enforce buffer boundaries. Mitigations (NX/DEP, ASLR, stack canaries, CFG) reduce exploit reliability, but do not remove the underlying bug.
A buffer overflow in the wild
vulnerable.c:
void handle_username(const char *input) {
char username[16]; // 16 bytes only
strcpy(username, input); // BAD: no bounds check
printf("Hello, %s!\n", username);
}What goes wrong:
usernameholds 15 chars + a null terminator = 16 bytes- If
inputis longer,strcpycopies until it finds a null, writing past the buffer - It overwrites other locals, the saved frame pointer, then the return address
Seen historically in network services parsing headers, CLI tools copying args, and file parsers reading name fields.
The fix — check length before copying:
if (strlen(input) >= sizeof(username)) {
puts("Username too long.");
return;
}Outcomes: a crash, corrupted variables and weird behaviour, or a real security risk once the corruption reaches control-flow data.
🧠 Quiz — Buffer Overflow Check Yourself (exam-style, verbatim reasoning)
void handle_input(char *input, size_t len) {
char buf[32];
memcpy(buf, input, len); // buf holds 32 bytes; len is attacker-controlled
process(buf);
}| Option | Correct? |
|---|---|
| A. If len > 32, memcpy writes beyond buf, causing an overflow | ✅ |
| B. If len is exactly 32, the program auto-stops at the buffer end | ❌ |
C. The program should check len <= 32 before calling memcpy | ✅ |
| D. memcpy automatically checks the destination is large enough | ❌ |
| E. A buffer overflow can only happen if the program crashes | ❌ |
Why B, D, E are wrong:
memcpydoes exactly what it is told with no safety checks, and many overflows never crash — they silently corrupt memory, which is what makes them dangerous.
4. Arithmetic — Integer Overflows
When arithmetic wraps around and quietly invalidates a correct-looking check.
The core idea
Integers have fixed sizes. When arithmetic exceeds the limit, the value wraps around instead of raising an error — and that can bypass otherwise-correct checks.
- Wraps, does not error — exceed the max and the value silently rolls over to a small number
- Dangerous in size math —
size = count * element_sizecan wrap to a tiny value - Signed/unsigned mixing — a negative value becomes a huge one when cast to unsigned
- Cast truncation — storing a wide value in a narrow type drops the high bits
- Under-allocate, then overflow — a too-small buffer gets filled with the real, larger amount of data
- Bypasses validation —
if (len < MAX)passes becauselenwas computed unsafely
Analogy: Imagine a car odometer that only has 5 digits. Once it hits 99,999 and you drive one more mile, it silently rolls back to 00,000 — it doesn't stop or warn you, it just wraps.
Hard to spot in review — the logic looks correct unless you explicitly consider arithmetic limits. Fix with checked arithmetic, wider types, explicit bounds on intermediate results.
A size calculation that overflows
// each pixel is 4 bytes (RGBA)
uint32_t bytes = width * height * 4; // BAD: can overflow 32-bit int
uint8_t *buf = malloc(bytes); // allocates the wrapped, small size
// decoder later writes width*height pixels: far beyond buf → corruptionA realistic scenario:
- Header declares
width = 100000,height = 100000 - True size = 40 GB. After 32-bit wraparound,
bytesbecomes a few MB (or near zero):mallocsucceeds small, decoder writes 40 GB worth.
Why it wraps: width × height × 4 (the true byte count) exceeds 2^32 - 1 (the max a 32-bit int holds) → high bits discarded → value wraps to a small number → malloc too small → under-allocation → decode writes real size → out-of-bounds write
Common in file parsers, media codecs, and protocol code. The validation checked width and height were reasonable — but not the product.
How 32 bits wrap around
all 32 bits on = 0xFFFFFFFF = 4,294,967,295
one more: 2^32 = 4,294,967,296
in binary: 1 00000000 00000000 00000000 00000000
↑ the 33rd bit does not fit in 32 bits — discarded, value wraps to 0
🧠 Quiz — Integer Overflow Check Yourself
bytes = width * height * 4, computed with 32-bit arithmetic, width/height from user input.
| Option | Correct? |
|---|---|
| A. If the result is too large, the program automatically refuses to calculate it | ❌ |
| B. If the result exceeds the 32-bit maximum, it wraps around to a smaller number | ✅ |
| C. Integer overflows only affect calculations, not memory allocation | ❌ |
| D. Integer overflow only happens with negative numbers | ❌ |
Why: A 32-bit number can only count up to ~4.29 billion. Past that limit, extra bits are discarded and the value wraps to a smaller number — that can make the program allocate too little memory, leading to a buffer overflow later. Overflow is not about negatives, and it is not "only maths" — it directly drives real memory-safety bugs by corrupting a size before it is ever used to allocate.
5. Discovery — Fuzzing
Throw malformed input at a program and watch how it fails, at scale.
Fuzzing & AFL++
Instead of valid input, send random and malformed data, and watch how the program fails. No source code required — black-box testing.
- Malformed input — unexpected/invalid data, on purpose
- Broad targets — programs, file formats, protocols, APIs
- Watch the failures — crashes, hangs, memory corruption
- Black-box — no source code required to run it
- Automated & scalable — millions of test cases, continuously
- Used early & often — throughout modern dev pipelines
AFL++ — coverage-guided fuzzer:
- Monitors which code paths execute, then mutates inputs to reach new ones
- Give it a program plus a few valid sample inputs; it generates thousands to millions of test cases
- On a crash, it saves the exact input for later analysis
https://aflplus.plus/
Feedback-driven and relentless. AFL++ has found thousands of real-world vulnerabilities in widely used software — the de-facto standard for security fuzzing.
6. Architecture — How the CPU Runs Code
Registers, the instruction pointer, and why controlling it means controlling everything.
CPU architecture basics
The CPU runs a fetch, decode, execute cycle on machine instructions, looping continuously.
- Fetch — read the next instruction from memory
- Decode — work out what the instruction means
- Execute — perform the operation, then repeat
| Detail | Why it changes bug behaviour |
|---|---|
| ISA differs | x86/x64 vs ARM64 — different registers, encoding, calling convention |
| Word size | 32 vs 64-bit changes pointer size, address space, overflow behaviour |
| Endianness | Byte order of multi-byte values in memory |
| Memory model | Stack, heap, code segments, and R/W/X permissions |
| Syscalls & ABI | How user-mode asks the OS to do privileged work |
ABI vs API: ABI (Application Binary Interface) = rules for how two compiled binaries interact at the machine level. API = how source code interacts.
The x86 register set — three generations (backward compatibility preserved throughout)
| 8086 · 16-bit | x86 · 32-bit (E) | x64 · 64-bit (R) |
|---|---|---|
| AX | EAX | RAX |
| BX | EBX | RBX |
| CX | ECX | RCX |
| DX | EDX | RDX |
| SP | ESP | RSP |
| BP | EBP | RBP |
| SI | ESI | RSI |
| DI | EDI | RDI |
| IP | EIP | RIP |
- "E" = Extended (addresses up to 4 GB); "R" = Register (64-bit + new R8–R15)
- The lower 16 bits of EAX are still AX; the lower 8 are still AL/AH — old software keeps running on new CPUs
Layered registers — one register, four views (RAX example)
RAX · 64-bit
└─ EAX · 32-bit
└─ AX · 16-bit
└─ AH / AL · 8-bit each
Analogy: Think of RAX like a full glass of water (64-bit). EAX is just the bottom half of that same glass (32-bit). AX is the bottom quarter, AH/AL are the very bottom eighths. It's all the same water — just different amounts being looked at.
| Register | Purpose |
|---|---|
| RAX | Accumulator — results, return values |
| RCX | Counter — loops; also passes args (x64) |
| RSI/RDI | Source/destination index (copies) |
| RBP/RSP | Base/stack pointer (stack frames) |
⭐ EIP/RIP — The Instruction Pointer (the single most important concept this week)
Holds the address of the next instruction. It controls what the CPU executes next. If an attacker overwrites RIP/EIP with a new address, the CPU jumps there and starts executing. Executable code at that address = arbitrary code execution.
This is the whole target of memory corruption: get attacker-controlled data into the instruction pointer, and you own program flow.
Deep dive — why the instruction pointer is different from every other register (worked exam answer, straight from a full-marks student response):
- What EIP/RIP holds normally: the address of the next instruction to fetch. During normal execution the CPU repeats fetch→decode→execute, and for most instructions simply advances EIP/RIP by the instruction's length. Control-flow instructions (
call,jmp, conditional jumps,ret) are the exception — they explicitly overwrite EIP/RIP with a new address, which is how loops, calls, and returns work. Under normal conditions, EIP/RIP only ever holds addresses the compiler/linker put there deliberately. - What it means for an attacker to control it: the CPU does not distinguish "an address the developer intended" from "an address an attacker managed to place there" — it has no concept of intent. It just fetches whatever bytes live at the current EIP/RIP and executes them. So if an attacker gets a chosen value into EIP/RIP, the very next fetch-decode-execute cycle jumps there and blindly executes whatever is there.
- Why this is so powerful (two reasons):
- Single point of total control — unlike corrupting some other piece of state (which might change one value), overwriting the instruction pointer redirects everything the CPU does from that moment on.
- Turns a memory-safety bug into arbitrary code execution — if the attacker's own bytes (shellcode) sit at a predictable, executable address, or fragments of the program's own code can be chained (return-oriented programming), controlling EIP/RIP is the difference between "the program misbehaves" and "the attacker now runs their own program using the victim process's privileges."
- Why other general-purpose registers (accumulator, counter) don't give the same power: they hold data — arithmetic results, loop counters, arguments. Corrupting one means a wrong computation, an incorrect loop count, or a bad argument — the program may misbehave, but the CPU is still fetching its next instruction from wherever EIP/RIP legitimately points. The corrupted value only becomes dangerous later, and only indirectly — e.g. if used as an unchecked array index, or as a pointer later dereferenced and jumped to. EIP/RIP is different because it is not consumed by a later operation — it is the operation: its value is read by the CPU's own fetch stage on the very next cycle, no intermediate "if this value happens to be used unsafely" condition. That directness is why exploit dev treats getting attacker-controlled data into EIP/RIP as the central goal — every other register is a means to that end at best; the instruction pointer is the end itself.
Can I touch a register? — kind of
It's a physical thing — transistors etched into silicon. From the name you see in a debugger down to the atoms:
EAX (logical name in ISA) → register renaming (RAT, logical) → physical register file
(~200 real slots) → one register (32 flip-flops, one per bit) → one flip-flop
(~6–20 transistors holding a bit) → transistors (patterned silicon — the matter)
Analogy: It's like calling someone "the manager" (a role/name) vs. pointing at the actual physical person in the chair. "EAX" is the role; the transistors are the person.
The stack & calling conventions
Registers hold fast temporary values; the stack holds call frames and locals. A stack frame is a dedicated block of memory managing the execution of a single function call. On most modern architectures, the stack grows from high to low memory addresses.
Stack layout (high → low memory):
caller's frame
arguments (7th+, stack-passed) — args 1–6 passed in registers on x64
return address [rbp+8] — sets where the function returns
saved RBP (caller's base pointer) [rbp] ← RBP
local variables (buffers, temps) [rbp-8] ← RSP
unused stack (grows into here, ↓ toward lower addresses)
- EIP/RIP decides what runs next — corrupt it and the CPU executes from an unintended location
- x64 passes args 1–6 in registers, not on the stack — corruption manifests differently than x86
- Calling conventions define the rules — which registers hold args, stack alignment, the return register
For security: understanding stack frames lets defenders read a crash and judge whether a bug is exploitable or merely a stability issue.
Endianness & data representation
The byte order of multi-byte values in memory. Get it wrong and a small number can be read as a huge one, straight into a bad allocation.
Storing 0x0A0B0C0D in memory:
| Address | Big-endian (MSB first) | Little-endian (LSB first) |
|---|---|---|
| addr+0 | 0x0A (MSB) | 0x0D (LSB) |
| addr+1 | 0x0B | 0x0C |
| addr+2 | 0x0C | 0x0B |
| addr+3 | 0x0D (LSB) | 0x0A (MSB) |
- Little-endian — x86, x86-64
- Big-endian — network protocols
- Configurable — ARM, MIPS
Common bug: a length field read in the wrong endian becomes a huge number, driving oversized allocations or copies. Use explicit conversion helpers, never assume host order.
7. Code to Machine — From Source to Machine Code
The CPU never sees your source. It sees bytes, and optimizations reshape everything.
Source → assembly → machine code
// Source code (human intent)
int square(int num) { return num * num; }; Assembly (readable CPU instructions)
push rbp
mov rbp, rsp
mov [rbp-4], edi
mov eax, [rbp-4]
imul eax, eax
pop rbp
retMachine code (bytes the CPU executes)
55
48 89 E5
89 7D FC
8B 45 FC
0F AF C0
5D
C3
Optimizations reshape structure while preserving behaviour. Variables vanish, functions get inlined, control flow is rearranged — this is why binaries are harder to reason about than source.
Compilation, linking & what ships
Pipeline: Source files (main.c, util.c...) → Object files (main.o, util.o — per module) → Linker (+ libraries, resolve symbols) → Executable (program.exe/.so)
- Static vs. dynamic linking — static embeds libraries; dynamic shares system ones — different patching and exposure
- Symbols can be stripped — debug info removed, behaviour stays the same
- Memory layout differs — ASLR, relocations, loader behaviour all shape the runtime image
- Release vs. debug builds — inlining, omitted checks, different timing — bugs can appear only under optimization
The security lesson: the same source can behave differently across builds. Reason about the binary that actually ships, not just the code that was written.
Disassembly vs. decompilation — NOT equal
| Disassembly | Decompilation | |
|---|---|---|
| Direction | machine code → assembly | machine code → high-level code |
| Nature | Exact and behaviour-preserving — one-to-one (if not obfuscated) | Approximate — best-effort reconstruction, not the original |
| Tool | IDA (Hex-Rays) | Ghidra (NSA) |
Assembler/disassembler are exact inverses. Compiler/decompiler are not — compilation loses information that decompilation can only estimate.
Common assembly instructions
| Instruction | Effect | What it does |
|---|---|---|
mov | dest ← src | copy data |
inc/dec | reg ± 1 | add or subtract one |
add/sub | dest ± src | arithmetic |
xor/neg | bitwise/negate | logical & arithmetic |
push | [esp] ← reg | put a value on the stack |
pop | reg ← [esp] | take a value off the stack |
⭐ Instructions that control EIP/RIP (exam-critical)
| Instruction | Effect on the instruction pointer |
|---|---|
call value | push return addr, then EIP = value |
jmp value | EIP = value (unconditional) |
je/jz | EIP = value if ZF=1 (conditional) |
jnz | EIP = value if ZF=0 (conditional) |
nop | EIP = EIP+1 (do nothing, advance) |
int 3 | breakpoint — trap to the debugger |
ret | EIP = [ESP] — pop return addr off stack |
retis the attacker's favourite. It loads EIP straight from the stack — overwrite the saved return address, andretjumps wherever you point it.
Two syntaxes — Intel vs. AT&T
Same machine instructions, written two ways — you'll meet both.
Why "AT&T"? AT&T owned Bell Labs, where Unix and C were created. Same underlying instructions, just different notation.
8. Putting It Together — The Whole Lecture in Seven Ideas
| Idea | Summary |
|---|---|
| Trust boundaries | Bugs become vulnerabilities when attacker input crosses one |
| Exploitability | Depends on privilege, memory safety, and mitigations together |
| Code review targets | Unsafe copies, parsing, integer math, lifecycle errors |
| Architecture | Helps you interpret crashes and root-cause corruption |
| Representation | Endianness and encoding cause subtle parser failures |
| Best defences | Least privilege, safe APIs, fuzzing, sanitizers, patching |
The goal is not zero bugs — that is unrealistic. It is making sure bugs do not automatically become system compromise.
Closing arc (memorize this chain — it's literally "the whole lecture"):
- A computer does exactly what it's told, not what the developer meant — that gap is the root of exploitation
- Buffer overflows & integer overflows exploit that gap — contiguous memory means writing past a buffer overwrites whatever sits beside it
- Adjacent to a stack buffer sits the saved return address — the prize for an overflow
- The instruction pointer (EIP/RIP) decides what executes next — the register attackers want to control
retloads the instruction pointer straight off the stack — an overwritten return address becomes a hijacked program- Defenses (canaries, ASLR, non-executable memory) each break a link in that chain — knowledge for defense, testing, and authorized use only
9. Post-Exploit — Password Cracking (theory recap)
Rather than breaking cryptography, attackers exploit password reuse and human habits.
| Property | Online Attacks | Offline Attacks |
|---|---|---|
| Target | Interact with live systems | Attack captured hashes |
| Speed | Slow, noisy, rate-limited | Billions of guesses/second |
| Defences | Lockouts & alerts trigger | No limits, no lockouts, no logs |
- Credential reuse — people reuse passwords across systems
- Hash vs. plaintext — weak/salt-less hashing accelerates recovery
- Human behaviour — small tweaks: +number, +year, one letter
- Post-exploitation value — one credential unlocks lateral movement
The cracking process (a deliberate sequence): hash identification → tool selection → wordlists → rule-based attacks → GPU acceleration → result interpretation
Success demonstrates risk — it is never an entitlement to access beyond your authorization.
10. 🖥️ LAB SECTION 1 — Assembly (ASM) Basics
Assembly = a very low-level programming language. Instead of "print text," you give the CPU direct instructions: move this number into this register. This is x86 assembly, Linux-style.
Analogy: Assembly is like giving very literal, step-by-step instructions instead of a general goal — instead of "make me a sandwich," you say "pick up the knife, pick up the bread, cut it in half..."
Worked example — line by line
section .data
hello: db '1337', 10
section .text
global _start
_start:
mov ebx, 1337| Line | Meaning |
|---|---|
section .data | Tells the assembler: the following describes data (stored values), not instructions — like where you store constants |
hello: db '1337', 10 | hello: = a label (a name marking a memory location). db = define bytes. '1337' = a string, each char stored as a byte. 10 = ASCII newline. Stores 1 3 3 7 \n in memory — like char hello[] = "1337\n"; in C. Nothing prints yet — this line just stores the text. |
section .text | Tells the assembler: the following are executable code (CPU instructions) |
global _start | Makes _start visible to the OS — on Linux, _start is the entry point where the OS begins running your program |
_start: | A label marking the program's beginning — the CPU jumps here first |
mov ebx, 1337 | The only real instruction: mov = move data, ebx = a CPU register, 1337 = the value. Meaning: put 1337 into register EBX. A register is a tiny, super-fast CPU-internal storage location |
What this program actually does: stores "1337\n" in memory → starts at _start → puts 1337 into ebx → ... then stops. What it does NOT do: print anything, exit properly, or use the hello string yet.
Analogy: _start is like the opening scene of a movie — the very first line of code that runs. Think of ebx like a small box the CPU uses to hold a number temporarily.
11. 🖥️ LAB SECTION 2 — Shellcode Workshop
Shellcoding = writing a tiny, self-contained note that you sneak into a program's memory, hoping the program will eventually "read it out loud" (execute it) instead of ignoring it as just data.
Setup: Kali VM in VirtualBox; exercises 1–4 in ~/Shellcode-Labs/, each with its own README.txt. Task: write shellcode meeting each exercise's requirements.
Full workflow (step by step)
1. Start the shellcode server:
./bin/shellcode-server2. Write the assembly program (in another terminal):
nano shellcode.asmsection .data
hello: db 'Hello world!', 10 ; 10 is the linefeed char
section .text
global _start
_start:
mov eax, 4
inc eax3. Assemble and link the code:
nasm -f elf shellcode.asmnasm= the Netwide Assembler (x86/x86_64)-f elf= output format ELF, produces an object file (shellcode.o) — not yet runnable, that's the linker's job
ld -m elf_i386 -o solution shellcode.o- The linking step — turns the object file into an actual executable binary
4. Extract the shellcode bytes:
objdump -d solution- Shows machine-code bytes (hex) AND the disassembled assembly instructions side by side
5. Incorporate the shellcode into a harness:
cat harness.py#!/usr/bin/env python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 8888))
# Python3
shellcode = b"\xbb\x39\x05\x00\x00"
print(f"sending shellcode ({len(shellcode)} bytes)")
s.send(shellcode)6. Run and verify — run the Python harness, check the shellcode server terminal for whether the challenge was solved.
Debugging hint: use
edborgdbto single-step through your shellcode. Set a breakpoint at thecall eaxinstruction in thetest()function — that's the line that calls your shellcode.
Handy extraction commands (turning a binary into pasteable Python bytes)
objcopy -O binary --only-section=.text solution text.bin
xxd -p text.bin | tr -d '\n' | sed 's/../\\x&/g'| Command | What it does |
|---|---|
objcopy --only-section=.text | Pulls out just the executable code section (no ELF headers/metadata) into a raw binary file |
xxd -p | Dumps the binary as a plain hex string |
tr -d '\n' | Strips newlines — one continuous string |
sed 's/../\\x&/g' | Converts each hex byte pair into \x-escaped format, ready to paste directly into a Python shellcode = b"..." string |
12. 🖥️ LAB SECTION 3 — Password Cracking Workshop (John the Ripper & Hashcat)
Post-exploitation, the interesting work is often offline. Once you've looted a password hash from a compromised machine, you can crack it on your own hardware, at your own pace.
Analogy: Cracking online is like trying every key on a locked front door while a neighbour watches and calls the police after 3 tries. Cracking offline is like taking the lock home and trying millions of keys in your garage with nobody watching.
Tools: John the Ripper (pre-installed on Kali) against the rockyou wordlist (also bundled).
Step 1 — Prepare rockyou (one-time)
sudo gunzip /usr/share/wordlists/rockyou.txt.gz
wc -l /usr/share/wordlists/rockyou.txtIf it reports the
.gzdoesn't exist, rockyou is already decompressed — good to go.
Step 2 — Create a target hash
HASH=$(openssl passwd -6 'iloveyou')
echo "victim:$HASH" > loot.txt
cat loot.txt # victim:$6$....- The
-6flag produces a SHA-512 crypt hash — the same$6$format used in/etc/shadow - A deliberately weak password is used so it cracks instantly
Step 3 — Crack it
john --wordlist=/usr/share/wordlists/rockyou.txt loot.txt- John auto-detects the hash type — no need to specify it
"iloveyou"sits near the top of rockyou → lands in well under a second
Step 4 — Read the result
john --show loot.txt # victim:iloveyouJohn caches cracks in
~/.john/john.pot— re-running step 3 reports "No password hashes left to crack." To reset:rm ~/.john/john.pot
Step 5 — The realistic version (dumping /etc/shadow)
This is what the "post-exploitation" slide is actually about. Kali uses
yescryptfor/etc/shadow.
sudo unshadow /etc/passwd /etc/shadow > shadow_hashes.txt
john --format=crypt --wordlist=/usr/share/wordlists/rockyou.txt shadow_hashes.txt
john --show shadow_hashes.txt- This only lands hits on accounts whose passwords are actually in rockyou. To guarantee a demo hit:
cp /usr/share/wordlists/rockyou.txt ~/rockyou-demo.txt && sed -i '1ikali' ~/rockyou-demo.txt⚠️ Do NOT use
>>here — that would append to the end of the file instead of inserting your test password at the beginning where it's needed.
Step 6 — Same thing in Hashcat
Hashcat wants just the hash, with no
"victim:"prefix. Mode1800= SHA-512 crypt.
echo "$HASH" > hash_only.txt
hashcat -m 1800 hash_only.txt /usr/share/wordlists/rockyou.txtWhy one credential unlocks so much more
You're cracking it offline, on your own hardware, with no account lockout and nothing logging the attempts. People reuse passwords. The admin whose workstation hash you cracked may have used the same one (or "iloveyou2") on the VPN, the database, and the domain admin account.
**One offline crack becomes lateral movement, and lateral movement becomes the whole environment.**The breach is not the finish line — it is the pivot.
13. 🖥️ WRITTEN WORKSHOP — Week 5 Exercise Format (no lab machine, two conceptual questions)
This week's workshop is different: no tool to run, no lab machine to attack. Two written questions on the core ideas behind exploit development. Answer in your own words; think on paper.
Grading philosophy: explain the mechanism, not just the label. "A buffer overflow overwrites the return address" is a start; showing why writing past a buffer reaches the return address is the actual understanding. A short, correct, well-argued answer beats a long one that never quite explains the mechanism.
Question 1 — The CPU, registers, and the instruction pointer
Task: explain, in your own words, addressing all of:
- What EIP/RIP holds, and what happens to it during normal execution
- What it means for an attacker to place a chosen value into it — what does the CPU do next, and why is that so powerful?
- Why other general-purpose registers (accumulator, counter) don't give the same direct control
(See the full worked model answer in Section 6 above — "EIP/RIP — The Instruction Pointer" deep-dive.)
Question 2 — The stack and the buffer overflow
Task: with a simple diagram + short written description, connect three things: the layout of the stack frame, what an over-long input does to it, and what happens when the function returns.
Diagram requirement: sketch a single function's stack frame showing at least the local buffer, saved frame pointer, and return address — make clear which direction a too-large write travels through the frame. Boxes and arrows are all that's needed; hand-drawn and photographed is fine.
Worked model diagram (as text — the actual structure to draw), high→low addresses:
┌─────────────────────────────────────┐ higher addresses
│ caller's frame / arguments │
├─────────────────────────────────────┤
│ return address [ebp+4] │ ← overflow reaches this LAST
├─────────────────────────────────────┤
│ saved EBP (frame pointer) [ebp] │ ← overflow reaches this 2nd
├─────────────────────────────────────┤
│ other local variables │ ← overflow reaches this 1st
├─────────────────────────────────────┤
│ buffer[ ] e.g. char username[16] │ ← overflow STARTS here
├─────────────────────────────────────┤
│ unused stack (grows downward ↓) │ lower addresses
└─────────────────────────────────────┘
↑
over-long write travels UPWARD (toward higher addresses)
through the frame: buffer → locals → saved EBP → return address
Key subtlety to get right: the stack grows downward (toward lower addresses) as new frames are pushed, but a buffer is filled from its start upward — so an over-long write into a low-address buffer travels upwardthrough the frame, through any other locals, then saved EBP, then the return address (all higher addresses) — not off into unrelated memory.
Written description — the full mechanism (model answer):
- Building the frame: when a function is called, its prologue pushes the caller's frame pointer (saved EBP) onto the stack, sets the new frame pointer, and reserves space below it for locals — which can include fixed-size buffers like
char username[16]. This reserved space is contiguous with the rest of the frame: buffer, saved EBP, and return address (pushed bycallbefore the function even began) all sit in one uninterrupted region, one after another. - The unbounded copy: if the function copies attacker-supplied input into that buffer with no bounds checking (e.g.
strcpy), the copy doesn't know or care the destination is only 16 bytes — it keeps copying until it hits a null terminator. If input is longer than the buffer, the copy keeps writing into whatever memory comes next — which, because of the frame's layout, is not empty space: it's (in order) any other locals declared after the buffer, then saved EBP, then the return address. A sufficiently long write overwrites each of these in turn, in the exact order they sit in memory. - The return instruction: the consequence only becomes visible at the function's epilogue. On return, the CPU executes
leave(restores the stack pointer, pops saved EBP back into EBP) thenret.retdoes exactly one thing: pops the value at the top of the stack — the return-address slot — into EIP. Normally that slot holds the legitimate addresscallpushed there, so the CPU resumes execution in the caller. But if the overflow reached and overwrote that slot,retpops the attacker's chosen value instead, and the CPU loads it straight into EIP with no validation whatsoever. Execution jumps to whatever address the attacker wrote — turning a simple, unbounded string copy into full control over what the CPU executes next.
What to submit
- One PDF to Google Classroom — written answers to both questions, in order, plus the diagram for Q2
- Name + student ID at the top
- Diagram can be hand-drawn/photographed or made with any tool (boxes & arrows are fine)
14. Rapid-Fire Recall Table (Last-Minute Review)
| Concept | One-liner |
|---|---|
| Vulnerability vs. exploit | Vulnerability = the weakness; exploit = the crafted trigger. One vuln, many possible exploits |
| Why CPU bugs happen | The CPU enforces nothing about strings, lengths, or pointer validity — only what the developer explicitly checks |
| A program as a state machine | Vulnerabilities = attacker input forcing an unintended state transition |
| Stack overflow direction | Buffer → other locals → saved EBP → return address (overflow travels toward higher addresses) |
| Buffer overflow ≠ crash | Many overflows silently corrupt memory with no visible crash — that's what makes them dangerous |
| Integer overflow | Fixed-size arithmetic wraps silently past its max — doesn't error, just rolls over |
| 32-bit max | 0xFFFFFFFF = 4,294,967,295; one more wraps to 0 |
| Integer overflow → memory bug | A wrapped size value → malloc too small → decoder writes real (large) size → out-of-bounds write |
| Fuzzing | Black-box, automated, malformed-input testing — no source code needed. AFL++ = coverage-guided |
| EIP/RIP | The instruction pointer — holds the address of the NEXT instruction; the single most important register for exploitation |
| Why EIP/RIP ≠ other registers | Other registers hold data consumed later, indirectly; EIP/RIP IS the operation — read directly by the CPU's fetch stage every cycle |
ret instruction | Pops the return address off the stack straight into EIP — "the attacker's favourite" |
| Register naming generations | 8086 (AX) → x86 "E" Extended (EAX) → x64 "R" Register (RAX) — backward compatible, same physical bits at different widths |
| Little vs. big-endian | x86/x64 = little-endian (LSB first); network protocols = big-endian; ARM/MIPS = configurable |
| Disassembly vs. decompilation | Disassembly = exact inverse of assembly (IDA); decompilation = approximate reconstruction (Ghidra) — NOT equally reliable |
| Static vs. dynamic linking | Static embeds libraries; dynamic shares system ones — different patching/exposure surface |
| Online vs. offline cracking | Online = slow, rate-limited, alerts fire; offline (captured hash) = billions of guesses/sec, no lockouts |
| John the Ripper | Auto-detects hash type; caches cracks in ~/.john/john.pot |
| Hashcat mode 1800 | SHA-512 crypt — wants the hash alone, no username prefix |
| Password cracking payoff | One offline crack → credential reuse → lateral movement → whole environment compromised |