Token Impersonation (Win)
Windows access tokens are critical to privilege escalation, as they encapsulate user identity, group memberships, and privileges. Manipulating or impersonating these tokens allows attackers to bypass access controls, execute commands under elevated contexts, or pivot within a network. This section explores token manipulation and impersonation techniques commonly used in Windows privilege escalation, including tools like Impacket and Mimikatz.
Impersonation Techniques¶
Using runas and PsExec¶
The runas command allows executing processes under another user's token, provided credentials are available. For example:
PsExec (from Sysinternals) can launch processes remotely under a specified account:
Both methods rely on valid credentials and may be mitigated by enforcing password complexity and restricting account privileges.
Code-Based Impersonation¶
Windows APIs like LogonUser and DuplicateToken enable programmatic token manipulation. A C# example using LogonUser to impersonate a user:
using System;
using System.Runtime.InteropServices;
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
// Example: Impersonate a user
IntPtr tokenHandle;
if (LogonUser("Administrator", ".", "P@ssw0rd", 2, 0, out tokenHandle)) {
// Use tokenHandle for impersonation
}
ImpersonateToken or SetThreadToken.
Token Manipulation Methods¶
Privilege Dropping with PsExec¶
While privilege escalation often involves gaining higher privileges, dropping privileges (e.g., from SYSTEM to a regular user) can be achieved by executing processes under a lower-privilege token. For example:
This is less common in escalation but useful for maintaining access after privilege gain.Mimikatz Token Manipulation¶
Mimikatz can extract and manipulate tokens, including impersonating a user's token:
Thetoken::elevate command attempts to elevate the current token to a higher privilege level, often used after credential theft.
Tools and Examples¶
Impacket's smbexec.py¶
Impacket's smbexec.py leverages SMB protocol to execute commands under a target user's token:
Token Manipulation with Invoke-Command (PowerShell)¶
PowerShell can impersonate a user via Invoke-Command with credentials:
$cred = Get-Credential
Invoke-Command -ComputerName target -Credential $cred -ScriptBlock { whoami }
Key takeaways¶
- Tokens are the foundation of Windows access control; manipulating them enables privilege escalation.
- Impersonation tools like
PsExecand Impacket'ssmbexec.pyare critical for executing commands under elevated contexts. - Code-based impersonation (e.g., C# or C APIs) provides fine-grained control but requires deep system access.
- Defenders should monitor for unusual token manipulation activities, such as unexpected privilege elevation or credential reuse.