Potential Process Injection via PowerShell

Detects PowerShell scripts that combines Win32 APIs for allocation/protection or process access (for example, VirtualAlloc/VirtualProtect/OpenProcess/AdjustTokenPrivileges/LoadLibrary/GetProcAddress) with injection or execution APIs (WriteProcessMemory/CreateRemoteThread/NtCreateThreadEx/QueueUserAPC/ResumeThread). Attackers use these API chains to inject code into remote processes and execute payloads in memory for defense evasion.

Elastic rule (View on GitHub)

  1[metadata]
  2creation_date = "2021/10/14"
  3integration = ["windows"]
  4maturity = "production"
  5updated_date = "2026/02/09"
  6
  7[rule]
  8author = ["Elastic"]
  9description = """
 10Detects PowerShell scripts that combines Win32 APIs for allocation/protection or process access (for example,
 11VirtualAlloc/VirtualProtect/OpenProcess/AdjustTokenPrivileges/LoadLibrary/GetProcAddress) with injection or execution
 12APIs (WriteProcessMemory/CreateRemoteThread/NtCreateThreadEx/QueueUserAPC/ResumeThread). Attackers use these API chains
 13to inject code into remote processes and execute payloads in memory for defense evasion.
 14"""
 15false_positives = ["Legitimate PowerShell scripts that make use of these functions."]
 16from = "now-9m"
 17index = ["winlogbeat-*", "logs-windows.powershell*"]
 18language = "kuery"
 19license = "Elastic License v2"
 20name = "Potential Process Injection via PowerShell"
 21note = """## Triage and analysis
 22
 23> **Disclaimer**:
 24> 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.
 25
 26### Investigating Potential Process Injection via PowerShell
 27
 28This rule Detects PowerShell scripts that references a combination of Win32 APIs commonly used to open a target process, allocate or change memory protections, write data into another process, and execute it via a remote thread or APC. This behavior is frequently associated with process injection and in-memory payload execution on Windows hosts.
 29
 30#### Key alert fields to review
 31
 32- `user.name`, `user.domain`, `user.id`: Account execution context for correlation, prioritization, and scoping.
 33- `host.name`, `host.id`: Host execution context for correlation, prioritization, and scoping.
 34- `powershell.file.script_block_text`: Script block content that matched the detection logic.
 35- `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.
 36- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file.
 37- `powershell.file.script_block_length`: Script block length (size) context.
 38
 39#### Possible investigation steps
 40
 41- Review and preserve the script content:
 42  - Inspect `powershell.file.script_block_text` for the full API chain and surrounding logic (function definitions, payload construction, and execution flow).
 43  - If the content is split across multiple events, reconstruct it by grouping on `powershell.file.script_block_id`, ordering by `powershell.sequence`, and validating completeness with `powershell.total`. Preserve the reconstructed content for follow-up analysis.
 44  - Use `powershell.file.script_block_length` to help gauge whether the script is a small launcher or a larger framework with embedded payloads.
 45
 46- Identify the injection technique and likely target:
 47  - Determine which execution primitive is being used (for example, `CreateRemoteThread`, `NtCreateThreadEx`, `QueueUserAPC`, or thread `SuspendThread`/`ResumeThread` patterns) and whether it suggests immediate or deferred execution.
 48  - Look for how the target process is selected (process name strings, PID variables, or process enumeration logic) and capture any referenced process names or IDs for scoping.
 49  - Note any privilege manipulation via `OpenProcessToken` and `AdjustTokenPrivileges`, which can indicate attempts to access protected processes.
 50
 51- Assess how native APIs are being invoked:
 52  - Identify dynamic resolution patterns such as `LoadLibrary*`/`LdrLoadDll` with `GetProcAddress`, which are commonly used to avoid static imports and hinder analysis.
 53  - If `GetDelegateForFunctionPointer` is present, review the surrounding text for delegate definitions and indirect invocation logic.
 54
 55- Validate execution context and script provenance:
 56  - Review `user.name`, `user.domain`, and `user.id` for signs of unusual execution (unexpected account type, first-time observation on the host, or activity outside expected administrative workflows).
 57  - Review `host.name` and `host.id` to understand the asset impacted and whether the behavior aligns with the host's role in your environment.
 58  - If `file.path`, `file.directory`, or `file.name` are populated, assess whether the script originated from a controlled location and naming convention, or from a user-writable or temporary location.
 59
 60- Scope related PowerShell activity:
 61  - On the same `host.id` and `user.id`, review additional script block events near `@timestamp` to identify staging actions that commonly bracket injection attempts (download, decode/decrypt, reflective loading, or cleanup).
 62  - Search for repeated use of distinctive substrings from `powershell.file.script_block_text` across other hosts or users to determine prevalence and potential reuse.
 63
 64- Correlate with adjacent host telemetry (if available in your environment):
 65  - Pivot from `host.name` and `@timestamp` to process activity to identify the PowerShell host process, its parent process, and any processes that may have been targeted for injection.
 66  - Review network activity from the same `host.name` around the alert time for potential payload retrieval, command-and-control, or lateral movement.
 67  - Review file activity related to `file.path` (when present) and for any new or modified scripts or binaries referenced by the script block.
 68
 69- Make a disposition:
 70  - Treat as higher risk when the script combines process access (`OpenProcess`), memory modification (`VirtualAlloc*`/`VirtualProtect`), and execution (`CreateRemoteThread`/`NtCreateThreadEx`/`QueueUserAPC`), especially when coupled with privilege adjustment or dynamic API resolution.
 71  - Treat as lower risk only when there is a clear, documented administrative or testing justification tied to the same `user.id`, `host.id`, and script origin.
 72
 73### False positive analysis
 74
 75- Legitimate PowerShell can use Win32 API interop for diagnostics, automation, or compatibility work; however, the combination of remote memory operations and remote execution APIs is uncommon in routine administration.
 76- Developer tooling or monitoring frameworks may load libraries or resolve symbols dynamically; validate that the script content aligns with expected tool behavior and that the script origin (`file.path`/`file.name`) is consistent and controlled.
 77
 78### Response and remediation
 79
 80- If the activity is confirmed or strongly suspected malicious:
 81  - Contain the affected host to prevent follow-on actions and lateral movement.
 82  - Preserve evidence by retaining the reconstructed `powershell.file.script_block_text` (and associated `powershell.file.script_block_id`) and recording the alert context (`user.*`, `host.*`, and `file.*` where present).
 83  - Identify the intended injection target from the script content and investigate that process and its recent activity for signs of compromise or anomalous behavior.
 84  - Review the associated user account activity for additional suspicious behavior on the same host and other hosts, and take appropriate account actions if compromise is suspected.
 85  - Hunt for the same script patterns across the environment using stable substrings from `powershell.file.script_block_text` and common `file.path`/`file.name` values, and remediate any additional impacted systems.
 86
 87- If the activity is verified as benign:
 88  - Document the script purpose, owner, expected execution context (hosts and accounts), and expected script origin (`file.path`/`file.name`).
 89  - Consider controlled rule tuning using stable, high-confidence identifiers from the verified benign workflow to reduce repeat alerts while maintaining coverage for new or unauthorized variants.
 90"""
 91references = [
 92    "https://github.com/EmpireProject/Empire/blob/master/data/module_source/management/Invoke-PSInject.ps1",
 93    "https://github.com/EmpireProject/Empire/blob/master/data/module_source/management/Invoke-ReflectivePEInjection.ps1",
 94    "https://github.com/BC-SECURITY/Empire/blob/master/empire/server/data/module_source/credentials/Invoke-Mimikatz.ps1",
 95    "https://www.elastic.co/security-labs/detect-credential-access",
 96]
 97risk_score = 73
 98rule_id = "2e29e96a-b67c-455a-afe4-de6183431d0d"
 99setup = """## Setup
100
101PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104).
102Setup instructions: https://ela.st/powershell-logging-setup
103"""
104severity = "high"
105tags = [
106    "Domain: Endpoint",
107    "OS: Windows",
108    "Use Case: Threat Detection",
109    "Tactic: Defense Evasion",
110    "Tactic: Execution",
111    "Resources: Investigation Guide",
112    "Data Source: PowerShell Logs",
113]
114timestamp_override = "event.ingested"
115type = "query"
116
117query = '''
118event.category:process and host.os.type:windows and
119  powershell.file.script_block_text : (
120   (VirtualAlloc or VirtualAllocEx or VirtualProtect or LdrLoadDll or LoadLibrary or LoadLibraryA or
121      LoadLibraryEx or GetProcAddress or OpenProcess or OpenProcessToken or AdjustTokenPrivileges) and
122   (WriteProcessMemory or CreateRemoteThread or NtCreateThreadEx or CreateThread or QueueUserAPC or
123      SuspendThread or ResumeThread or GetDelegateForFunctionPointer)
124  ) and not 
125  file.directory: (
126    "C:\ProgramData\Microsoft\Windows Defender Advanced Threat Protection\SenseCM" or
127    "C:\ProgramData\Microsoft\Windows Defender Advanced Threat Protection\Downloads"
128  )
129'''
130
131[[rule.filters]]
132
133[rule.filters.meta]
134negate = true
135[rule.filters.query.wildcard."file.path"]
136case_insensitive = true
137value = "?:\\\\ProgramData\\\\Microsoft\\\\Windows Defender Advanced Threat Protection\\\\DataCollection\\\\*"
138
139
140[[rule.threat]]
141framework = "MITRE ATT&CK"
142[[rule.threat.technique]]
143id = "T1055"
144name = "Process Injection"
145reference = "https://attack.mitre.org/techniques/T1055/"
146[[rule.threat.technique.subtechnique]]
147id = "T1055.001"
148name = "Dynamic-link Library Injection"
149reference = "https://attack.mitre.org/techniques/T1055/001/"
150
151[[rule.threat.technique.subtechnique]]
152id = "T1055.002"
153name = "Portable Executable Injection"
154reference = "https://attack.mitre.org/techniques/T1055/002/"
155
156
157
158[rule.threat.tactic]
159id = "TA0005"
160name = "Defense Evasion"
161reference = "https://attack.mitre.org/tactics/TA0005/"
162[[rule.threat]]
163framework = "MITRE ATT&CK"
164[[rule.threat.technique]]
165id = "T1059"
166name = "Command and Scripting Interpreter"
167reference = "https://attack.mitre.org/techniques/T1059/"
168[[rule.threat.technique.subtechnique]]
169id = "T1059.001"
170name = "PowerShell"
171reference = "https://attack.mitre.org/techniques/T1059/001/"
172
173
174[[rule.threat.technique]]
175id = "T1106"
176name = "Native API"
177reference = "https://attack.mitre.org/techniques/T1106/"
178
179
180[rule.threat.tactic]
181id = "TA0002"
182name = "Execution"
183reference = "https://attack.mitre.org/tactics/TA0002/"
184
185[rule.investigation_fields]
186field_names = [
187    "@timestamp",
188    "user.name",
189    "user.id",
190    "user.domain",
191    "powershell.file.script_block_text",
192    "powershell.file.script_block_id",
193    "powershell.sequence",
194    "powershell.total",
195    "file.path",
196    "file.directory",
197    "file.name",
198    "process.pid",
199    "host.name",
200    "host.id",
201    "powershell.file.script_block_length"
202]

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 Potential Process Injection via PowerShell

This rule Detects PowerShell scripts that references a combination of Win32 APIs commonly used to open a target process, allocate or change memory protections, write data into another process, and execute it via a remote thread or APC. This behavior is frequently associated with process injection and in-memory payload execution on Windows hosts.

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

  • Review and preserve the script content:

    • Inspect powershell.file.script_block_text for the full API chain and surrounding logic (function definitions, payload construction, and execution flow).
    • If the content is split across multiple events, reconstruct it by grouping on powershell.file.script_block_id, ordering by powershell.sequence, and validating completeness with powershell.total. Preserve the reconstructed content for follow-up analysis.
    • Use powershell.file.script_block_length to help gauge whether the script is a small launcher or a larger framework with embedded payloads.
  • Identify the injection technique and likely target:

    • Determine which execution primitive is being used (for example, CreateRemoteThread, NtCreateThreadEx, QueueUserAPC, or thread SuspendThread/ResumeThread patterns) and whether it suggests immediate or deferred execution.
    • Look for how the target process is selected (process name strings, PID variables, or process enumeration logic) and capture any referenced process names or IDs for scoping.
    • Note any privilege manipulation via OpenProcessToken and AdjustTokenPrivileges, which can indicate attempts to access protected processes.
  • Assess how native APIs are being invoked:

    • Identify dynamic resolution patterns such as LoadLibrary*/LdrLoadDll with GetProcAddress, which are commonly used to avoid static imports and hinder analysis.
    • If GetDelegateForFunctionPointer is present, review the surrounding text for delegate definitions and indirect invocation logic.
  • Validate execution context and script provenance:

    • Review user.name, user.domain, and user.id for signs of unusual execution (unexpected account type, first-time observation on the host, or activity outside expected administrative workflows).
    • Review host.name and host.id to understand the asset impacted and whether the behavior aligns with the host's role in your environment.
    • If file.path, file.directory, or file.name are populated, assess whether the script originated from a controlled location and naming convention, or from a user-writable or temporary location.
  • Scope related PowerShell activity:

    • On the same host.id and user.id, review additional script block events near @timestamp to identify staging actions that commonly bracket injection attempts (download, decode/decrypt, reflective loading, or cleanup).
    • Search for repeated use of distinctive substrings from powershell.file.script_block_text across other hosts or users to determine prevalence and potential reuse.
  • Correlate with adjacent host telemetry (if available in your environment):

    • Pivot from host.name and @timestamp to process activity to identify the PowerShell host process, its parent process, and any processes that may have been targeted for injection.
    • Review network activity from the same host.name around the alert time for potential payload retrieval, command-and-control, or lateral movement.
    • Review file activity related to file.path (when present) and for any new or modified scripts or binaries referenced by the script block.
  • Make a disposition:

    • Treat as higher risk when the script combines process access (OpenProcess), memory modification (VirtualAlloc*/VirtualProtect), and execution (CreateRemoteThread/NtCreateThreadEx/QueueUserAPC), especially when coupled with privilege adjustment or dynamic API resolution.
    • Treat as lower risk only when there is a clear, documented administrative or testing justification tied to the same user.id, host.id, and script origin.

False positive analysis

  • Legitimate PowerShell can use Win32 API interop for diagnostics, automation, or compatibility work; however, the combination of remote memory operations and remote execution APIs is uncommon in routine administration.
  • Developer tooling or monitoring frameworks may load libraries or resolve symbols dynamically; validate that the script content aligns with expected tool behavior and that the script origin (file.path/file.name) is consistent and controlled.

Response and remediation

  • If the activity is confirmed or strongly suspected malicious:

    • Contain the affected host to prevent follow-on actions and lateral movement.
    • Preserve evidence by retaining the reconstructed powershell.file.script_block_text (and associated powershell.file.script_block_id) and recording the alert context (user.*, host.*, and file.* where present).
    • Identify the intended injection target from the script content and investigate that process and its recent activity for signs of compromise or anomalous behavior.
    • Review the associated user account activity for additional suspicious behavior on the same host and other hosts, and take appropriate account actions if compromise is suspected.
    • Hunt for the same script patterns across the environment using stable substrings from powershell.file.script_block_text and common file.path/file.name values, and remediate any additional impacted systems.
  • If the activity is verified as benign:

    • Document the script purpose, owner, expected execution context (hosts and accounts), and expected script origin (file.path/file.name).
    • Consider controlled rule tuning using stable, high-confidence identifiers from the verified benign workflow to reduce repeat alerts while maintaining coverage for new or unauthorized variants.

References

Related rules

to-top