Install

rapid7/metasploit-framework

Metasploit Framework Wiki

Last updated on Dec 18, 2025 (Commit: 019ac75)

Overview

Relevant Files
  • lib/msf.rb
  • lib/msf/core/framework.rb
  • lib/msf/core/module.rb
  • lib/msf/core/module_manager.rb
  • README.md

Metasploit Framework is an open-source penetration testing platform that provides a comprehensive toolkit for security professionals. It is released under a BSD-style license and serves as the primary interface for conducting security assessments, vulnerability research, and exploitation.

Core Architecture

The framework is built around three fundamental components:

  1. Framework Instance (Msf::Framework) - The central context that ties everything together. It manages modules, sessions, jobs, plugins, and events. Every module, script, and user interface interacts through this single framework instance.

  2. Module System - A flexible plugin architecture supporting six module types:

    • Exploits - Modules that target specific vulnerabilities
    • Payloads - Code executed after successful exploitation
    • Encoders - Obfuscate payloads to evade detection
    • Auxiliary - Scanning, enumeration, and utility modules
    • Post - Post-exploitation modules for system interaction
    • Evasion - Techniques to bypass security controls
    • NOPs - No-operation instructions for payload alignment
  3. Module Manager (Msf::ModuleManager) - Handles loading, instantiation, and lifecycle management of all modules. It maintains module sets by type and provides search and creation capabilities.

Module Structure

Every module inherits from Msf::Module, which provides:

  • Metadata - Name, description, version, authors, references, and platform information
  • Options - Configurable parameters with validation and defaults
  • DataStore - Runtime configuration storage for each module instance
  • Workspace Tracking - Association with database workspaces for multi-user environments
  • Replication - Fresh copies of modules for concurrent execution

Modules are defined with an information hash containing metadata and options, then instantiated on-demand. The framework automatically extends modules with type-specific functionality through mixins.

Event System

The framework uses an event-driven architecture with subscribers for:

  • Module Events - Execution, completion, and error handling
  • Session Events - Creation, closure, and interaction logging
  • Exploit Events - Success and failure tracking
  • Database Events - Persistence of framework activities
  • UI Events - Command execution and interface state

Initialization Flow

Loading diagram...

Key Features

  • Database Integration - Optional PostgreSQL backend for storing hosts, services, credentials, and exploitation history
  • Plugin System - Extensible plugins for custom functionality and integrations
  • Job Management - Background execution of modules with thread pooling
  • Search Capability - Metadata-based module discovery and filtering
  • Multi-User Support - Workspace isolation for team-based assessments

Architecture & Core Components

Relevant Files
  • lib/msf/core/framework.rb
  • lib/msf/core/event_dispatcher.rb
  • lib/msf/core/module_manager.rb
  • lib/msf/core/session_manager.rb
  • lib/msf/core/db_manager.rb

Framework Core

The Framework (Msf::Framework) is the central hub that orchestrates all Metasploit operations. It initializes and manages critical subsystems including the module system, event dispatcher, session manager, database connection, and job scheduler. Every module, script, and user interface interacts through a single framework instance.

framework = Msf::Framework.new
framework.modules.exploits['windows/smb/ms17_010_eternalblue']
framework.sessions  # Access active sessions
framework.db        # Access database

Module System Architecture

Metasploit supports seven module types, each with distinct responsibilities:

  1. Exploits - Target vulnerabilities and execute payloads
  2. Payloads - Code executed after successful exploitation (stagers, singles, adapters)
  3. Encoders - Obfuscate payloads to evade detection
  4. Auxiliary - Scanning, enumeration, brute-forcing, DoS
  5. Post - Post-exploitation tasks on compromised systems
  6. Evasion - Techniques to bypass security controls
  7. NOPs - No-operation instructions for payload alignment

The ModuleManager (Msf::ModuleManager) loads and instantiates modules from disk. Each module type has a dedicated ModuleSet that maintains loaded modules and provides creation/lookup methods.

framework.modules['exploit/windows/smb/ms17_010_eternalblue']
framework.exploits['windows/smb/ms17_010_eternalblue']
framework.auxiliary['scanner/http/dir_scanner']

Event Dispatcher System

The EventDispatcher implements a publish-subscribe pattern for framework events. Subscribers register for specific event types and receive notifications when events occur.

Event Categories:

  • Exploit Events - Exploitation success/failure
  • Session Events - Session creation/closure
  • Database Events - Data changes
  • UI Events - User interface updates
  • General Events - Module loading, framework state changes
framework.events.add_exploit_subscriber(my_handler)
framework.events.on_exploit_success(exploit, target)

Session Management

The SessionManager tracks active sessions created by successful exploits. It maintains a background monitor thread that:

  • Reads incoming data from stream-based sessions
  • Stores data in ring buffers
  • Detects dead/closed sessions
  • Updates session state in the database
  • Cleans stale sessions from orphaned framework instances

Sessions are identified by unique session IDs (SIDs) and implement various interfaces for interaction (shell, meterpreter, etc.).

Database Integration

The DBManager provides persistent storage for:

  • Hosts, services, and vulnerabilities
  • Credentials and logins
  • Exploitation attempts and results
  • Sessions and session events
  • Loot and notes
  • Workspaces for organizing assessments

It uses a modular architecture with specialized mixins for each data domain (hosts, credentials, services, etc.) and supports multiple database adapters (PostgreSQL, MySQL).

Data Flow Diagram

Loading diagram...

Key Design Patterns

Offspring Mixin - Modules and managers include Framework::Offspring to maintain a reference to the framework instance, enabling access to shared resources.

Module Duplication - Modules are duplicated at instantiation to allow independent state management while sharing the original class definition for reloading.

Thread Safety - Framework uses MonitorMixin for synchronization of lazy-initialized components (sessions, threads, database).

Lazy Initialization - Heavy components like sessions and database are initialized on first access to reduce startup time.

Module System & Loading

Relevant Files
  • lib/msf/core/module.rb
  • lib/msf/core/module_manager.rb
  • lib/msf/core/module_manager/loading.rb
  • lib/msf/core/module_manager/cache.rb
  • lib/msf/core/module_set.rb
  • lib/msf/core/modules/loader/base.rb
  • lib/msf/core/modules/loader/directory.rb
  • modules/README.md

Overview

The module system is the core of Metasploit's extensibility. It manages the discovery, loading, instantiation, and organization of all modules (exploits, auxiliaries, payloads, encoders, post-exploitation, evasion, and NOP modules). The system uses a multi-layered architecture with loaders, module sets, and caching to efficiently handle thousands of modules.

Module Architecture

Loading diagram...

Module Loading Pipeline

1. Path Registration: Modules are discovered from registered paths using add_module_path(). Paths are validated as directories and stored in module_paths.

2. Loader Selection: The system uses two loader classes:

  • Directory Loader: Loads standard Ruby modules from the filesystem
  • Executable Loader: Loads external modules (Python, Go, etc.) via shim generation

3. Module Evaluation: Each loader reads module content and evaluates it within a namespace using module_eval_with_lexical_scope(). This creates the module class with proper inheritance from Msf::Module.

4. Registration: After successful evaluation, on_module_load() registers the module in the appropriate ModuleSet and updates the in-memory cache.

Module Sets and Organization

Modules are organized by type into separate ModuleSet instances:

  • auxiliary โ€“ Non-shell-gaining activities (scanning, enumeration)
  • exploit โ€“ Vulnerability exploitation modules
  • payload โ€“ Payload delivery mechanisms (uses PayloadSet for special handling)
  • encoder โ€“ Payload encoding/obfuscation
  • post โ€“ Post-exploitation modules
  • evasion โ€“ Evasion techniques
  • nop โ€“ NOP sled generators

Each set is a Hash-like container that supports lazy-loading via the [] operator.

Module Instantiation

Creating a module instance involves two steps:

  1. Class Loading: ModuleSet#load_module_class() loads the module class if not already loaded
  2. Instance Creation: ModuleSet#create() instantiates the class and fires on_module_created events

The ModuleManager#create() method provides a unified interface that accepts module names with optional type prefixes (e.g., exploit/windows/smb/ms17_010_eternalblue).

Caching System

The cache prevents unnecessary reloading of unchanged modules:

  • In-Memory Cache: Stores modification times, reference names, and parent paths in module_info_by_path
  • File Change Detection: file_changed?() compares current file modification time with cached value
  • Filesystem Cache: Metadata persisted to database via Msf::Modules::Metadata::Cache
  • Lazy Loading: Modules marked as nil in sets are loaded on-demand when accessed

Module Base Class

All modules inherit from Msf::Module, which provides:

  • Metadata: Name, description, version, author, references, platforms, architectures
  • Options: Configuration parameters (standard, advanced, evasion)
  • DataStore: Runtime configuration values for module instances
  • Lifecycle: Initialization, replication (via replicant()), and extension hooks
  • Utilities: Platform checking, workspace tracking, owner identification

Module Aliases and References

Modules can have multiple reference names (aliases) for backward compatibility. The system maintains bidirectional alias mappings:

  • aliases โ€“ Maps alias names to canonical reference names
  • inv_aliases โ€“ Reverse mapping for efficient lookup

When a module is loaded, its aliases are registered and can be used interchangeably with the canonical name.

Exploit & Payload Generation

Relevant Files
  • lib/msf/core/exploit.rb
  • lib/msf/core/payload_generator.rb
  • lib/msf/core/encoded_payload.rb
  • lib/msf/core/handler.rb
  • lib/msf/core/encoder.rb
  • lib/msf/core/nop.rb

The exploit and payload generation system is the core mechanism for creating, encoding, and delivering payloads to target systems. It orchestrates multiple components to transform raw shellcode into deployable, obfuscated payloads that bypass security filters.

Architecture Overview

Loading diagram...

Core Components

Exploit Module (lib/msf/core/exploit.rb) The base class for all exploit modules. It manages payload generation through methods like generate_payload() and generate_single_payload(). Exploits define payload requirements including bad characters, space constraints, and encoder preferences. They also handle handler setup via add_handler() to listen for incoming sessions.

PayloadGenerator (lib/msf/core/payload_generator.rb) A high-level orchestrator for payload creation, primarily used by msfvenom. It accepts configuration options (architecture, platform, encoder, format) and coordinates the entire generation pipeline. Supports multiple output formats (raw, exe, jar, war) and handles iterative encoding.

EncodedPayload (lib/msf/core/encoded_payload.rb) The central payload transformation engine. It orchestrates three main phases:

  1. Raw Generation: Combines base payload with prepend/append data
  2. Encoding: Applies encoders iteratively to bypass bad characters and filters
  3. NOP Sled: Prepends NOP instructions for buffer alignment and evasion

Encoding Pipeline

Encoders transform shellcode to avoid detection and bypass character restrictions. The system:

  • Iterates through ranked encoders until one succeeds
  • Validates encoder compatibility with exploit requirements
  • Respects space constraints and bad character lists
  • Supports chained encoding (multiple encoders in sequence)

Key encoder methods: encode() accepts raw shellcode and bad characters, returning encoded output. The EncoderState class tracks encoding progress and keys.

NOP Sled Generation

NOP generators create instruction sequences that do nothing but consume space, useful for buffer overflow exploits. The system:

  • Selects compatible NOP generators by architecture/platform
  • Generates sleds respecting bad character constraints
  • Supports register preservation for specific architectures
  • Pads payloads to exact size requirements

Handler Integration

Handlers (lib/msf/core/handler.rb) manage post-exploitation communication. They:

  • Listen for incoming connections from deployed payloads
  • Create sessions upon successful connection
  • Support multiple transport types (TCP, UDP, HTTP, HTTPS)
  • Integrate with the session manager for multi-handler scenarios

Payload Execution Flow

  1. Exploit calls generate_payload() with target requirements
  2. EncodedPayload.create() instantiates the generation engine
  3. Raw payload is generated from the payload module
  4. Encoders are applied iteratively if needed
  5. NOP sled is prepended based on space calculations
  6. Final payload is returned to exploit for delivery
  7. Handler waits for connection and creates session

Error Handling

The system defines specific exceptions for common failures:

  • NoEncodersSucceededError: All encoders failed to encode the payload
  • NoNopsSucceededError: NOP generators couldn't create required sled
  • PayloadSpaceViolation: Payload exceeds allocated space
  • EncoderSpaceViolation: Encoder output too large

Session Management & Handlers

Relevant Files
  • lib/msf/core/session_manager.rb
  • lib/msf/base/sessions/meterpreter.rb
  • lib/msf/base/sessions/command_shell.rb
  • lib/msf/base/sessions/custom.rb
  • lib/msf/core/session.rb
  • lib/msf/core/session_event.rb

Overview

The session management system is the backbone of post-exploitation in Metasploit. It tracks all active sessions created by successful exploits, manages their lifecycle, and provides interfaces for interaction. Sessions are registered with unique IDs, monitored for health, and deregistered when they die or are closed.

Session Lifecycle

Loading diagram...

Sessions follow a clear lifecycle: creation by handlers, registration with unique session IDs (SIDs), active monitoring, and eventual deregistration. The SessionManager maintains a hash of all active sessions indexed by SID.

Core Components

SessionManager (lib/msf/core/session_manager.rb) is a Hash-based registry that:

  • Allocates unique session IDs via allocate_sid()
  • Registers sessions with register() and deregisters with deregister()
  • Runs a monitor thread that checks session health every 0.5 seconds
  • Maintains 5 scheduler threads for processing registration tasks
  • Updates database records every 150 seconds to mark sessions as alive
  • Removes stale sessions orphaned by dead framework instances

Session Interfaces define capabilities:

  • Msf::Session::Basic - Basic I/O interaction
  • Msf::Session::Interactive - User interaction with rstream
  • Msf::Session::Comm - Network pivoting via the session
  • Msf::Session::Provider::SingleCommandShell - Command shell operations

Session Types

Meterpreter (lib/msf/base/sessions/meterpreter.rb) is the most feature-rich session type:

  • Includes Interactive, Comm, and SingleCommandShell interfaces
  • Provides a console for command execution
  • Supports extension loading (stdapi, priv, etc.)
  • Handles TLV encryption negotiation and session GUIDs
  • Implements shell operations via channelized processes

CommandShell (lib/msf/base/sessions/command_shell.rb) provides basic shell access:

  • Implements SingleCommandShell for read/write operations
  • Supports meta-commands (background, download, upload, irb, pry)
  • Includes file transfer capabilities
  • Handles shell verification and banner capture

Custom (lib/msf/base/sessions/custom.rb) is a minimal session for custom payloads that don't require persistent interaction.

Event System

Sessions emit events through Msf::SessionEvent:

  • on_session_open - Session registered and ready
  • on_session_close - Session deregistered with reason
  • on_session_interact - User begins interaction
  • on_session_command - Command written to session
  • on_session_output - Output received from session

The EventDispatcher routes these to registered subscribers (plugins, UI, database). This allows plugins like session_tagger and session_notifier to hook into session lifecycle events.

Data Flow

The monitor thread continuously:

  1. Selects on all session rstreams with 0.5s timeout
  2. Reads available data into ring buffers
  3. Fires on_session_output events
  4. Checks if sessions are still alive
  5. Deregisters dead sessions with appropriate cleanup

Scheduler threads process registration tasks asynchronously, preventing blocking during session creation. This ensures the framework remains responsive even with many concurrent sessions.

Database & Persistent Storage

Relevant Files
  • lib/msf/core/db_manager.rb
  • lib/msf/core/db_manager/host.rb
  • lib/msf/core/db_manager/service.rb
  • lib/msf/core/db_manager/cred.rb
  • lib/msf/core/db_manager/connection.rb
  • app/models/application_record.rb
  • db/schema.rb

The database layer provides persistent storage for all reconnaissance, exploitation, and post-exploitation data. It uses a modular architecture built on Rails ActiveRecord with PostgreSQL as the primary adapter.

Architecture Overview

The Msf::DBManager class orchestrates all database operations through a collection of specialized mixins, each handling a specific data domain. This design separates concerns and makes the codebase maintainable.

Loading diagram...

Connection Management

Database connections are established through Msf::DBManager::Connection, which handles:

  1. Connection Pooling - Maintains a pool of 75 connections by default with a 300-second timeout
  2. Database Creation - Automatically creates the database if it doesn't exist
  3. Schema Migration - Runs pending migrations after connection establishment
  4. Connection Verification - Ensures the connection is active before operations
# Connection is established via ApplicationRecord
ApplicationRecord.establish_connection(config_hash)

# All database operations use connection pooling
ApplicationRecord.connection_pool.with_connection do
  # Database operation here
end

Core Data Models

The database stores five primary data types:

Hosts - Target systems with attributes like IP address, OS, architecture, and state. Each host belongs to a workspace and tracks associated services, vulnerabilities, and credentials.

Services - Network services running on hosts (ports, protocols, names). Services link hosts to vulnerabilities and credentials.

Credentials - Authentication data including usernames, passwords, hashes, and SSH keys. Credentials are associated with services and can be sourced from vulnerabilities or other credentials.

Vulnerabilities - Security issues discovered on hosts, linked to services and exploitation attempts. Supports references (CVE, BID, etc.).

Sessions - Active connections to compromised systems, tracking session type, user context, and exploitation history.

Data Reporting Pattern

Modules report data using report_* methods that follow a consistent pattern:

# Report a host
framework.db.report_host(
  host: '192.168.1.1',
  os_name: 'Windows',
  os_flavor: 'Server 2019',
  workspace: workspace_obj
)

# Report a service
framework.db.report_service(
  host: host_obj,
  port: 445,
  proto: 'tcp',
  name: 'smb'
)

# Report credentials
framework.db.report_auth_info(
  host: '192.168.1.1',
  port: 445,
  user: 'admin',
  pass: 'password123',
  ptype: 'password',
  proof: 'admin share accessible'
)

Workspace Isolation

All data is organized into workspaces, enabling multi-user assessments. Each workspace maintains separate hosts, services, credentials, and vulnerabilities. This allows teams to run parallel assessments without data collision.

Connection Pooling and Thread Safety

All database operations wrap queries in ApplicationRecord.connection_pool.with_connection blocks. This ensures thread-safe access and proper connection lifecycle management, preventing connection leaks in multi-threaded environments.

Console Interface & Commands

Relevant Files
  • lib/msf/ui/console/driver.rb
  • lib/msf/ui/console/command_dispatcher.rb
  • lib/msf/ui/console/command_dispatcher/core.rb
  • lib/msf/ui/console/command_dispatcher/exploit.rb
  • lib/msf/ui/console/command_dispatcher/session.rb
  • lib/msf/ui/console/module_command_dispatcher.rb

The console interface is built on a dispatcher stack architecture where command handling is delegated through multiple layers. This design allows different contexts (core, modules, sessions) to provide their own commands while maintaining a unified command-line experience.

Architecture Overview

Loading diagram...

Dispatcher Stack System

The console uses a stack-based command routing system where dispatchers are pushed and popped as context changes:

  1. Core Dispatcher (CommandDispatcher::Core) - Always at the base, handles global commands like use, sessions, set, exploit, etc.
  2. Module Dispatchers - Pushed when a module is selected (e.g., CommandDispatcher::Exploit, CommandDispatcher::Auxiliary)
  3. Session Dispatchers - Pushed when interacting with an active session

When a command is executed, the driver iterates through the dispatcher stack from top to bottom, stopping at the first dispatcher that recognizes the command.

Command Dispatcher Base Class

All dispatchers inherit from Msf::Ui::Console::CommandDispatcher, which provides:

  • Access to the framework instance via driver.framework
  • Access to active module and session via driver.active_module and driver.active_session
  • Helper methods like build_range_array() for parsing ID ranges and remove_lines() for text filtering
  • Configuration loading via load_config()

Module-Specific Dispatchers

When you execute use exploit/windows/smb/ms17_010_eternalblue, the console:

  1. Creates a module instance
  2. Determines the module type (exploit, auxiliary, payload, etc.)
  3. Pushes the appropriate dispatcher onto the stack
  4. Sets driver.active_module to the new module

Each module type has specialized commands:

  • Exploit: exploit, check, rexploit (reload & exploit)
  • Auxiliary: run, check
  • Payload: generate, to_handler
  • Post: run

Session Command Dispatcher

When you interact with a session via sessions -i 1, a session-specific dispatcher is pushed that provides:

  • background / bg - Return to main console
  • exit / quit - Terminate the session
  • irb - Open interactive Ruby shell
  • resource - Execute resource scripts within the session

Command Resolution Flow

Loading diagram...

Key Features

  • Tab Completion: Each dispatcher implements cmd_*_tabs() methods for context-aware completion
  • Help System: Commands can define cmd_*_help() methods for detailed documentation
  • Configuration Persistence: Dispatchers can load/save configuration via load_config() and get_config()
  • Error Handling: Exceptions are caught and logged with stack traces for debugging
  • Command Passthrough: Unknown commands can be executed as system shell commands if AllowCommandPassthru is enabled

Protocol Support & Network Libraries

Relevant Files
  • lib/rex/proto - Protocol implementations
  • lib/rex/proto/http - HTTP client/server
  • lib/rex/proto/smb - SMB protocol
  • lib/rex/proto/dcerpc - DCERPC protocol
  • lib/rex/proto/ssh - SSH protocol
  • lib/rex/proto/dns - DNS resolver and server
  • lib/rex/proto/kerberos - Kerberos authentication
  • lib/msf/core/exploit/remote - Socket connection mixins

Metasploit provides comprehensive protocol support through the Rex library, enabling communication with diverse network services and targets. The framework uses rex-socket (an external gem) for low-level socket operations, while protocol-specific implementations are built on top.

Core Socket Types

The framework supports multiple socket types through Rex::Socket:

  • TCP Sockets (Rex::Socket::Tcp) - Reliable, connection-oriented communication
  • UDP Sockets (Rex::Socket::Udp) - Connectionless, datagram-based communication
  • TCP Servers (Rex::Socket::TcpServer) - Accept incoming connections with callbacks
  • IP Sockets (Rex::Socket::Ip) - Raw IP protocol access (requires root)

All sockets are created via Rex::Socket::Tcp.create() or similar factory methods, accepting configuration hashes with parameters like PeerHost, PeerPort, LocalHost, LocalPort, SSL, and Context.

Protocol Implementations

The framework includes protocol handlers for:

  • HTTP - Client and server implementations with WebSocket support
  • SMB - Full SMB protocol with NTLMSSP authentication and signing
  • DCERPC - Distributed Computing Environment RPC for Windows services
  • SSH - SSH client and server using hrr_rb_ssh library
  • DNS - Resolver and server with caching and custom nameserver support
  • Kerberos - KDC client with TCP/UDP transport options
  • MQTT - IoT protocol support
  • RFB/VNC - Remote framebuffer protocol
  • LDAP - Directory access with authentication
  • TFTP - Trivial File Transfer Protocol
  • MSSQL - SQL Server protocol (TDS)
  • MySQL - MySQL protocol
  • FTP - File Transfer Protocol

SSL/TLS Support

All TCP-based protocols support SSL/TLS encryption through socket parameters:

Rex::Socket::Tcp.create(
  'PeerHost' => 'example.com',
  'PeerPort' => 443,
  'SSL' => true,
  'SSLVersion' => 'TLSv1_2',
  'SSLCipher' => 'HIGH:!aNULL'
)

Server Implementation Pattern

Protocol servers follow a consistent pattern using TcpServer with callbacks:

server = Rex::Socket::TcpServer.create(
  'LocalHost' => '0.0.0.0',
  'LocalPort' => 8080
)
server.on_client_connect_proc = Proc.new { |client| handle_connect(client) }
server.on_client_data_proc = Proc.new { |client| handle_data(client) }
server.start

Exploit Integration

Exploits use protocol mixins for simplified socket creation:

  • Msf::Exploit::Remote::Tcp - TCP client connections
  • Msf::Exploit::Remote::Udp - UDP client connections
  • Msf::Exploit::Remote::TcpServer - Passive TCP server exploits
  • Msf::Exploit::Remote::SocketServer - Generic socket server base

These mixins handle socket lifecycle, evasion options, and context management automatically.

Context & Logging

All sockets accept a Context hash containing framework references for logging and event tracking. The Comm parameter allows routing through proxies or specific network interfaces.

Post-Exploitation & Session Capabilities

Relevant Files
  • lib/rex/post/meterpreter
  • lib/msf/core/post
  • lib/rex/post/file.rb
  • lib/rex/post/process.rb
  • modules/post
  • scripts/meterpreter

Overview

Post-exploitation capabilities in Metasploit enable attackers to interact with compromised systems after gaining initial access. The framework provides a unified API across different session types (Meterpreter, shell, PowerShell) through mixins and extensions, abstracting platform and session differences.

Session Types & Interfaces

Metasploit supports multiple session types, each with distinct capabilities:

  • Meterpreter - Feature-rich in-memory agent with extension support (stdapi, priv, incognito, kiwi)
  • Command Shell - Basic shell access with limited capabilities
  • PowerShell - Windows-specific shell with scripting support
  • SMB - Protocol-specific session for SMB operations

Each session implements interfaces like Msf::Session::Interactive for user interaction and Msf::Session::Comm for network pivoting.

Meterpreter Extensions

Extensions provide specialized functionality loaded dynamically into Meterpreter sessions:

Core Extensions:

  • stdapi - Standard API for file, process, registry, network operations
  • priv - Privilege escalation (getsystem, SAM hash dumping, MACE manipulation)
  • incognito - Token impersonation and user management

Specialized Extensions:

  • kiwi - Credential extraction via mimikatz integration
  • extapi - Extended API (WMI, clipboard, services, ADSI, pageant)
  • powershell - PowerShell execution engine
  • sniffer - Network packet capture
  • lanattacks - DHCP/TFTP attacks
  • android, espia, python - Platform-specific capabilities

Post-Exploitation Mixins

Mixins in lib/msf/core/post/ provide consistent APIs across session types:

Msf::Post::Common - Core utilities for command execution and session interaction:

create_process(executable, args: [], time_out: 15, opts: {})
cmd_exec(command)
rhost, rport, peer  # Session connection info

Msf::Post::File - Remote file operations:

cd(path), pwd()
file_exist?(path), file_stat(path)
read_file(path), write_file(path, data)
upload(local, remote), download(remote, local)

Msf::Post::Process - Process management:

get_processes()
pidof(program)
kill_process(pid)
has_pid?(pid)

Post Modules

Post modules (modules/post/) execute on active sessions for data gathering and system manipulation. Organized by platform:

  • multi/ - Cross-platform modules (escalation, gathering, management)
  • windows/ - Windows-specific (registry, services, event logs, credentials)
  • linux/ - Linux-specific (kernel, packages, privilege escalation)
  • android/, osx/, solaris/ - Platform-specific modules

Modules inherit from Msf::Post and require a SESSION option specifying the target session ID.

Session Lifecycle & Pivoting

Sessions are managed by Msf::SessionManager, tracking active sessions with unique IDs. Meterpreter supports pivoting through Rex::Post::Meterpreter::Pivot, allowing lateral movement through compromised hosts. Pivot sessions maintain parent-child relationships and can be chained for multi-hop exploitation.

Practical Workflow

  1. Exploit creates session (Meterpreter preferred for post-exploitation)
  2. Extensions auto-load (stdapi, priv on Windows)
  3. Post modules execute against session
  4. Data gathered and stored in database
  5. Pivot to new targets or escalate privileges
  6. Clean up artifacts and close session

Auxiliary Modules & Utilities

Relevant Files
  • lib/msf/core/auxiliary.rb
  • lib/msf/core/auxiliary/scanner.rb
  • lib/msf/core/auxiliary/dos.rb
  • lib/msf/util/exe.rb
  • lib/msf/util/dot_net_deserialization.rb
  • lib/rex/parser/nmap_xml.rb
  • modules/auxiliary

Auxiliary modules are non-exploit tools that perform reconnaissance, data gathering, administration, denial-of-service attacks, and other tasks that don't fit the exploit paradigm. They form a critical part of Metasploit's offensive and defensive capabilities.

Auxiliary Module Architecture

The Msf::Auxiliary base class (in lib/msf/core/auxiliary.rb) provides the foundation for all auxiliary modules. Unlike exploits, auxiliary modules don't require payloads or targets. They inherit from Msf::Module and include the HasActions mixin, allowing them to define multiple execution paths.

Key features:

  • Actions: Modules can define multiple actions (e.g., CHECK, DOWNLOAD, BRUTE_FORCE) that users select at runtime
  • Passive Actions: Some actions run as background jobs without blocking the console
  • Failure Handling: Custom fail_with() method for detailed error reporting
  • Autofilter: Optional parameter validation before execution

Auxiliary Module Categories

Metasploit organizes auxiliary modules into functional categories:

  • Scanner (Auxiliary::Scanner): Multi-threaded reconnaissance across host ranges. Includes RHOSTS parameter and per-host execution via run_host(ip) method
  • Gather: Single-target data collection (credentials, configuration, enumeration)
  • Admin: Modify or manipulate target systems (user management, service control)
  • DoS: Denial-of-service attacks (crashes, resource exhaustion)
  • Analyze: Password cracking and hash analysis
  • Server: Listener modules (DHCP, DNS, FTP, LDAP, SOCKS proxy)
  • Fuzzer: Protocol fuzzing and mutation testing
  • Sniffer: Network traffic capture and analysis
  • Client: Social engineering and client-side attacks

Utility Modules

The lib/msf/util/ directory provides reusable utilities:

  • EXE (exe.rb): Executable generation for multiple platforms (Windows PE, Linux ELF, macOS Mach-O, ASPX, PowerShell)
  • Deserialization: Gadget chain generation for .NET, Java, Python, and Ruby deserialization attacks
  • Windows Registry: Registry parsing and remote registry access
  • Service Helper: Process execution and management utilities

Parser Framework

The lib/rex/parser/ directory contains stream and document parsers for security tool output:

  • Nmap XML (nmap_xml.rb): Stream parser for nmap results with host/port enumeration
  • Vulnerability Scanners: Nessus, Nexpose, OpenVAS, Acunetix, Burp, AppScan
  • Configuration Files: Unattend.xml, Group Policy Preferences, WinSCP, DBEaver
  • Filesystem: NTFS and BitLocker parsing

Parsers use REXML stream listeners for memory-efficient processing of large XML files.

Example: Scanner Module

class MetasploitModule < Msf::Auxiliary
  include Msf::Auxiliary::Scanner

  def initialize(info = {})
    super(update_info(info,
      'Name' => 'HTTP Service Scanner',
      'Description' => 'Scan for HTTP services'
    ))
  end

  def run_host(ip)
    # Called once per host in RHOSTS
    res = http_get(ip, 80, '/')
    print_good("Found HTTP on #{ip}") if res
  end
end

Mermaid Diagram

Loading diagram...