PowerShell Script with Token Impersonation Capabilities
Detects PowerShell scripts that references token manipulation and impersonation APIs such as CreateProcessWithTokenW, DuplicateToken/ImpersonateLoggedOnUser, or AdjustTokenPrivileges (SeDebugPrivilege). Attackers abuse token impersonation to elevate privileges and bypass access controls.
Elastic rule (View on GitHub)
1[metadata]
2creation_date = "2022/08/17"
3integration = ["windows"]
4maturity = "production"
5updated_date = "2026/02/09"
6
7[rule]
8author = ["Elastic"]
9description = """
10Detects PowerShell scripts that references token manipulation and impersonation APIs such as CreateProcessWithTokenW,
11DuplicateToken/ImpersonateLoggedOnUser, or AdjustTokenPrivileges (SeDebugPrivilege). Attackers abuse token impersonation
12to elevate privileges and bypass access controls.
13"""
14from = "now-9m"
15index = ["winlogbeat-*", "logs-windows.powershell*"]
16language = "kuery"
17license = "Elastic License v2"
18name = "PowerShell Script with Token Impersonation Capabilities"
19note = """## Triage and analysis
20
21> **Disclaimer**:
22> This guide was created by humans with the assistance of generative AI. While its contents have been manually curated to include the most valuable information, always validate assumptions and adjust procedures to match your internal runbooks and incident triage and response policies.
23
24### Investigating PowerShell Script with Token Impersonation Capabilities
25
26This rule Detects PowerShell scripts that includes token manipulation and impersonation primitives. Such functionality can be used to execute follow-on actions under a different security context, including elevated or alternate user tokens. The primary investigation goals are to (1) reconstruct and understand the script intent, (2) validate whether the activity is authorized, and (3) identify any resulting privileged execution on the host.
27
28#### Key alert fields to review
29
30- `user.name`, `user.domain`, `user.id`: Account execution context for correlation, prioritization, and scoping.
31- `host.name`, `host.id`: Host execution context for correlation, prioritization, and scoping.
32- `powershell.file.script_block_text`: Script block content that matched the detection logic.
33- `powershell.file.script_block_id`, `powershell.sequence`, `powershell.total`: Script block metadata to pivot to other fragments or reconstruct full script content when split across multiple events.
34- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file.
35- `powershell.file.script_block_length`: Script block length (size) context.
36
37#### Possible investigation steps
38
39- Preserve and reconstruct the full script block content:
40 - Capture `powershell.file.script_block_text` from the alert for analysis and evidence retention.
41 - If the script is logged in multiple fragments, pivot on `powershell.file.script_block_id` and reassemble in order using `powershell.sequence`. Use `powershell.total` to confirm you have the complete set of fragments.
42 - Use `powershell.file.script_block_length` to help gauge completeness and identify unusually large blocks that may contain reusable libraries or modules.
43
44- Identify which token technique is present and what outcome the script is attempting:
45 - Review the reconstructed content for indicators of:
46 - Token duplication and impersonation (for example: `DuplicateToken`, `DuplicateTokenEx`, `SetThreadToken`, `ImpersonateLoggedOnUser`, `NtImpersonateThread`).
47 - Named pipe impersonation (`ImpersonateNamedPipeClient`).
48 - Privilege enablement (`AdjustTokenPrivileges` with `SeDebugPrivilege`).
49 - Token-based process creation (for example: `CreateProcessWithTokenW`, `CreateProcessAsUserW`, `CreateProcessAsUserA`) and related extended startup attributes (`STARTUPINFOEX`, `UpdateProcThreadAttribute`).
50 - Higher-level wrappers commonly associated with token manipulation (for example: `Invoke-TokenManipulation`).
51 - Determine whether the script only defines helper functions/types versus actively invoking them. Content that both defines and calls token APIs within the same execution window is higher risk.
52 - Note any embedded targeting details in the script content (for example: intended user context, target process identifiers, or follow-on payload references), and preserve them for scoping and hunting.
53
54- Validate execution context and expectedness:
55 - Use `host.name` and `host.id` to understand where the activity occurred and whether the system role typically requires privileged PowerShell usage.
56 - Use `user.name`, `user.domain`, and `user.id` to identify the executing account and determine whether this user is expected to run scripts that manipulate access tokens on this host.
57 - Prioritize alerts involving unexpected users, unusual hosts (for example, servers with limited admin access), or repeated/recurrent script blocks indicating persistence or automation.
58
59- Assess script provenance when file context is present:
60 - If `file.path` is populated, determine whether the script came from a known module or an on-disk script file, and whether the location and naming are consistent with approved tooling.
61 - If only `file.directory` and `file.name` are populated, use them to pivot to related script blocks and identify other executions from the same origin.
62 - If the origin appears unfamiliar or user-writable, treat the artifact as suspicious and prioritize collecting the referenced file (and any adjacent module content) for deeper analysis.
63
64- Correlate with surrounding host activity to determine impact:
65 - Pivot on `host.name` and the alert `@timestamp` into adjacent telemetry to identify the PowerShell host process and its initiating parent/source (interactive session, remote management, scheduled execution, or another process).
66 - Look for follow-on activity shortly after the alert time that would indicate successful impersonation or privilege escalation, such as:
67 - New process execution under a different user context than `user.name`.
68 - Privileged actions that require elevated rights (for example, service/task changes, registry modifications, or access to protected resources).
69 - If multiple script blocks occur close together for the same `user.id` and `host.id`, review them as a single activity chain to understand staging, execution, and any post-escalation behavior.
70
71- Scope and hunt for related activity:
72 - Search for additional occurrences of distinctive substrings from `powershell.file.script_block_text` (function names, API names, unique strings) across other users and hosts to identify reuse.
73 - Review whether the same `user.id` is associated with similar script blocks on other `host.id` values, which can indicate broad automation or a compromised account used across systems.
74 - If `file.path` is present, check for the same path and file name across the environment, and identify unexpected hosts where the artifact appears.
75
76### False positive analysis
77
78- Legitimate administrative automation may use token impersonation to run tasks under alternate credentials, perform controlled privilege transitions, or integrate with management workflows.
79- Development and troubleshooting scripts may contain token API references as reusable helpers without being used for malicious outcomes.
80
81To reduce false positives, focus on provenance and behavior: scripts from known, approved sources and executed by expected administrative identities on expected hosts are more likely benign, while ad-hoc or newly introduced scripts, unfamiliar file origins, and follow-on privileged execution increase concern.
82
83### Response and remediation
84
85- If the activity is unauthorized or suspicious:
86 - Contain the host to prevent further privileged execution and limit lateral movement according to your incident response procedures.
87 - Preserve evidence: the reconstructed script block content, associated `powershell.file.script_block_id` fragments, and any referenced on-disk artifacts from `file.path` (or `file.directory`/`file.name`).
88 - Investigate and remediate outcomes of token impersonation, including processes started under unexpected security contexts and any privileged system changes occurring after the alert time.
89
90- Reduce attacker access and recurrence:
91 - Review the executing account identified in `user.id`; reset credentials and invalidate active sessions as appropriate.
92 - Review privileged access assignments for the involved accounts and hosts, and remove unauthorized privilege grants where identified.
93 - If the script enabled sensitive privileges (for example, `SeDebugPrivilege`), assess for additional post-exploitation activity that could leverage enhanced access to protected processes and resources.
94
95- Eradicate and recover:
96 - Remove unauthorized scripts/modules and any secondary artifacts or persistence mechanisms discovered during investigation.
97 - Monitor for repeat executions by hunting for the same token manipulation indicators observed in `powershell.file.script_block_text` across the environment.
98 - Ensure PowerShell script block logging is enabled and retained on systems where PowerShell is permitted so future activity can be reconstructed and scoped effectively.
99"""
100references = [
101 "https://github.com/decoder-it/psgetsystem",
102 "https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/Get-System.ps1",
103 "https://github.com/EmpireProject/Empire/blob/master/data/module_source/privesc/Invoke-MS16032.ps1",
104 "https://github.com/atc-project/atc-data/blob/master/docs/Logging_Policies/LP_0109_windows_powershell_script_block_log.md",
105]
106risk_score = 47
107rule_id = "11dd9713-0ec6-4110-9707-32daae1ee68c"
108setup = """## Setup
109
110PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104).
111Setup instructions: https://ela.st/powershell-logging-setup
112"""
113severity = "medium"
114tags = [
115 "Domain: Endpoint",
116 "OS: Windows",
117 "Use Case: Threat Detection",
118 "Tactic: Privilege Escalation",
119 "Data Source: PowerShell Logs",
120 "Resources: Investigation Guide",
121]
122timestamp_override = "event.ingested"
123type = "query"
124
125query = '''
126event.category:process and host.os.type:windows and
127 powershell.file.script_block_text:(
128 "Invoke-TokenManipulation" or
129 "ImpersonateNamedPipeClient" or
130 "NtImpersonateThread" or
131 (
132 "STARTUPINFOEX" and
133 "UpdateProcThreadAttribute"
134 ) or
135 (
136 "AdjustTokenPrivileges" and
137 "SeDebugPrivilege"
138 ) or
139 (
140 ("DuplicateToken" or
141 "DuplicateTokenEx") and
142 ("SetThreadToken" or
143 "ImpersonateLoggedOnUser" or
144 "CreateProcessWithTokenW" or
145 "CreatePRocessAsUserW" or
146 "CreateProcessAsUserA")
147 )
148 ) and
149 not (
150 user.id:("S-1-5-18" or "S-1-5-19" or "S-1-5-20") and
151 file.directory: "C:\\ProgramData\\Microsoft\\Windows Defender Advanced Threat Protection\\Downloads"
152 ) and
153 not powershell.file.script_block_text : (
154 "sentinelbreakpoints" and "Set-PSBreakpoint" and "PowerSploitIndicators"
155 ) and
156 not (
157 powershell.file.script_block_text : "New-HPPrivateToastNotificationLogo" and
158 file.path : "C:\Program Files\HPConnect\hp-cmsl-wl\modules\HP.Notifications\HP.Notifications.psm1"
159 )
160'''
161
162
163[[rule.threat]]
164framework = "MITRE ATT&CK"
165[[rule.threat.technique]]
166id = "T1134"
167name = "Access Token Manipulation"
168reference = "https://attack.mitre.org/techniques/T1134/"
169[[rule.threat.technique.subtechnique]]
170id = "T1134.001"
171name = "Token Impersonation/Theft"
172reference = "https://attack.mitre.org/techniques/T1134/001/"
173
174
175
176[rule.threat.tactic]
177id = "TA0004"
178name = "Privilege Escalation"
179reference = "https://attack.mitre.org/tactics/TA0004/"
180[[rule.threat]]
181framework = "MITRE ATT&CK"
182[[rule.threat.technique]]
183id = "T1059"
184name = "Command and Scripting Interpreter"
185reference = "https://attack.mitre.org/techniques/T1059/"
186[[rule.threat.technique.subtechnique]]
187id = "T1059.001"
188name = "PowerShell"
189reference = "https://attack.mitre.org/techniques/T1059/001/"
190
191
192[[rule.threat.technique]]
193id = "T1106"
194name = "Native API"
195reference = "https://attack.mitre.org/techniques/T1106/"
196
197
198[rule.threat.tactic]
199id = "TA0002"
200name = "Execution"
201reference = "https://attack.mitre.org/tactics/TA0002/"
202
203[rule.investigation_fields]
204field_names = [
205 "@timestamp",
206 "user.name",
207 "user.id",
208 "user.domain",
209 "powershell.file.script_block_text",
210 "powershell.file.script_block_id",
211 "powershell.sequence",
212 "powershell.total",
213 "file.path",
214 "file.directory",
215 "file.name",
216 "process.pid",
217 "host.name",
218 "host.id",
219 "powershell.file.script_block_length"
220]
Triage and analysis
Disclaimer: This guide was created by humans with the assistance of generative AI. While its contents have been manually curated to include the most valuable information, always validate assumptions and adjust procedures to match your internal runbooks and incident triage and response policies.
Investigating PowerShell Script with Token Impersonation Capabilities
This rule Detects PowerShell scripts that includes token manipulation and impersonation primitives. Such functionality can be used to execute follow-on actions under a different security context, including elevated or alternate user tokens. The primary investigation goals are to (1) reconstruct and understand the script intent, (2) validate whether the activity is authorized, and (3) identify any resulting privileged execution on the host.
Key alert fields to review
user.name,user.domain,user.id: Account execution context for correlation, prioritization, and scoping.host.name,host.id: Host execution context for correlation, prioritization, and scoping.powershell.file.script_block_text: Script block content that matched the detection logic.powershell.file.script_block_id,powershell.sequence,powershell.total: Script block metadata to pivot to other fragments or reconstruct full script content when split across multiple events.file.path,file.directory,file.name: File-origin context when the script block is sourced from an on-disk file.powershell.file.script_block_length: Script block length (size) context.
Possible investigation steps
-
Preserve and reconstruct the full script block content:
- Capture
powershell.file.script_block_textfrom the alert for analysis and evidence retention. - If the script is logged in multiple fragments, pivot on
powershell.file.script_block_idand reassemble in order usingpowershell.sequence. Usepowershell.totalto confirm you have the complete set of fragments. - Use
powershell.file.script_block_lengthto help gauge completeness and identify unusually large blocks that may contain reusable libraries or modules.
- Capture
-
Identify which token technique is present and what outcome the script is attempting:
- Review the reconstructed content for indicators of:
- Token duplication and impersonation (for example:
DuplicateToken,DuplicateTokenEx,SetThreadToken,ImpersonateLoggedOnUser,NtImpersonateThread). - Named pipe impersonation (
ImpersonateNamedPipeClient). - Privilege enablement (
AdjustTokenPrivilegeswithSeDebugPrivilege). - Token-based process creation (for example:
CreateProcessWithTokenW,CreateProcessAsUserW,CreateProcessAsUserA) and related extended startup attributes (STARTUPINFOEX,UpdateProcThreadAttribute). - Higher-level wrappers commonly associated with token manipulation (for example:
Invoke-TokenManipulation).
- Token duplication and impersonation (for example:
- Determine whether the script only defines helper functions/types versus actively invoking them. Content that both defines and calls token APIs within the same execution window is higher risk.
- Note any embedded targeting details in the script content (for example: intended user context, target process identifiers, or follow-on payload references), and preserve them for scoping and hunting.
- Review the reconstructed content for indicators of:
-
Validate execution context and expectedness:
- Use
host.nameandhost.idto understand where the activity occurred and whether the system role typically requires privileged PowerShell usage. - Use
user.name,user.domain, anduser.idto identify the executing account and determine whether this user is expected to run scripts that manipulate access tokens on this host. - Prioritize alerts involving unexpected users, unusual hosts (for example, servers with limited admin access), or repeated/recurrent script blocks indicating persistence or automation.
- Use
-
Assess script provenance when file context is present:
- If
file.pathis populated, determine whether the script came from a known module or an on-disk script file, and whether the location and naming are consistent with approved tooling. - If only
file.directoryandfile.nameare populated, use them to pivot to related script blocks and identify other executions from the same origin. - If the origin appears unfamiliar or user-writable, treat the artifact as suspicious and prioritize collecting the referenced file (and any adjacent module content) for deeper analysis.
- If
-
Correlate with surrounding host activity to determine impact:
- Pivot on
host.nameand the alert@timestampinto adjacent telemetry to identify the PowerShell host process and its initiating parent/source (interactive session, remote management, scheduled execution, or another process). - Look for follow-on activity shortly after the alert time that would indicate successful impersonation or privilege escalation, such as:
- New process execution under a different user context than
user.name. - Privileged actions that require elevated rights (for example, service/task changes, registry modifications, or access to protected resources).
- New process execution under a different user context than
- If multiple script blocks occur close together for the same
user.idandhost.id, review them as a single activity chain to understand staging, execution, and any post-escalation behavior.
- Pivot on
-
Scope and hunt for related activity:
- Search for additional occurrences of distinctive substrings from
powershell.file.script_block_text(function names, API names, unique strings) across other users and hosts to identify reuse. - Review whether the same
user.idis associated with similar script blocks on otherhost.idvalues, which can indicate broad automation or a compromised account used across systems. - If
file.pathis present, check for the same path and file name across the environment, and identify unexpected hosts where the artifact appears.
- Search for additional occurrences of distinctive substrings from
False positive analysis
- Legitimate administrative automation may use token impersonation to run tasks under alternate credentials, perform controlled privilege transitions, or integrate with management workflows.
- Development and troubleshooting scripts may contain token API references as reusable helpers without being used for malicious outcomes.
To reduce false positives, focus on provenance and behavior: scripts from known, approved sources and executed by expected administrative identities on expected hosts are more likely benign, while ad-hoc or newly introduced scripts, unfamiliar file origins, and follow-on privileged execution increase concern.
Response and remediation
-
If the activity is unauthorized or suspicious:
- Contain the host to prevent further privileged execution and limit lateral movement according to your incident response procedures.
- Preserve evidence: the reconstructed script block content, associated
powershell.file.script_block_idfragments, and any referenced on-disk artifacts fromfile.path(orfile.directory/file.name). - Investigate and remediate outcomes of token impersonation, including processes started under unexpected security contexts and any privileged system changes occurring after the alert time.
-
Reduce attacker access and recurrence:
- Review the executing account identified in
user.id; reset credentials and invalidate active sessions as appropriate. - Review privileged access assignments for the involved accounts and hosts, and remove unauthorized privilege grants where identified.
- If the script enabled sensitive privileges (for example,
SeDebugPrivilege), assess for additional post-exploitation activity that could leverage enhanced access to protected processes and resources.
- Review the executing account identified in
-
Eradicate and recover:
- Remove unauthorized scripts/modules and any secondary artifacts or persistence mechanisms discovered during investigation.
- Monitor for repeat executions by hunting for the same token manipulation indicators observed in
powershell.file.script_block_textacross the environment. - Ensure PowerShell script block logging is enabled and retained on systems where PowerShell is permitted so future activity can be reconstructed and scoped effectively.
References
Related rules
- Potential PowerShell HackTool Script by Function Names
- PowerShell PSReflect Script
- Suspicious Portable Executable Encoded in Powershell Script
- Potential PowerShell HackTool Script by Author
- Potential PowerShell Obfuscation via Special Character Overuse