[Rule Tuning] PowerShell Rules Revamp - 6 (#5700)

* [Rule Tuning] PowerShell Rules Revamp - 6

* .

* [Rule Tuning] PowerShell Rules Revamp - 7

* Revert "[Rule Tuning] PowerShell Rules Revamp - 7"

This reverts commit 378f8c8b6409ea1e4bad0e86027c05e0a7db9950.

* update disclaimer
This commit is contained in:
Jonhnathan
2026-02-11 15:50:49 -03:00
committed by GitHub
parent 20450660df
commit 9be58755ae
5 changed files with 441 additions and 204 deletions
@@ -2,73 +2,97 @@
creation_date = "2025/04/16"
integration = ["windows"]
maturity = "production"
updated_date = "2025/12/09"
updated_date = "2026/02/09"
[rule]
author = ["Elastic"]
description = """
Identifies PowerShell scripts that reconstruct the IEX (Invoke-Expression) command at runtime using indexed slices of
environment variables. This technique leverages character access and join operations to build execution logic
dynamically, bypassing static keyword detection and evading defenses such as AMSI.
Detects PowerShell scripts that reconstructs IEX (Invoke-Expression) by indexing environment variable strings (for example, $env:VAR[1,2,3]) or related `.name[...]` slices and joining characters at runtime.
Attackers use environment-variable slicing to hide dynamic execution and evade keyword-based detections and AMSI.
"""
from = "now-9m"
language = "esql"
license = "Elastic License v2"
name = "Potential Dynamic IEX Reconstruction via Environment Variables"
note = """ ## Triage and analysis
note = """## Triage and analysis
> **Disclaimer**:
> This investigation guide was created using generative AI technology and has been reviewed to improve its accuracy and relevance. While every effort has been made to ensure its quality, we recommend validating the content and adapting it to suit your specific environment and operational needs.
> 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 Dynamic IEX Reconstruction via Environment Variables
PowerShell's Invoke-Expression (IEX) command is a powerful tool for executing strings as code, often exploited by attackers to run obfuscated scripts. Adversaries may dynamically reconstruct IEX using environment variables to evade static detection. The detection rule identifies scripts that manipulate environment variables to form IEX commands, focusing on patterns of character slicing and joining, which are indicative of obfuscation techniques. By analyzing script length and specific patterns, the rule effectively flags potential misuse, aiding in defense against such evasion tactics.
This alert indicates PowerShell Script Block Logging captured a script that builds "IEX" (Invoke-Expression) at runtime by indexing characters from environment variable strings or related name properties and combining them. This technique is commonly used to obscure dynamic execution and can indicate an attempt to execute attacker-controlled content.
### Possible investigation steps
#### Key alert fields to review
- Review the powershell.file.script_block_text field to understand the content and intent of the script, focusing on how environment variables are manipulated to reconstruct the IEX command.
- Examine the file.path and host.name fields to determine the origin and location of the script execution, which can provide context on whether the activity is expected or suspicious.
- Analyze the user.id and agent.id fields to identify the user and agent responsible for executing the script, checking for any anomalies or unauthorized access.
- Investigate the powershell.file.script_block_id and powershell.sequence fields to trace the execution sequence and correlate it with other related PowerShell activities on the host.
- Assess the count field to understand the extent of obfuscation patterns detected, which can indicate the complexity and potential maliciousness of the script.
- `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.
- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file.
- `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.
- `Esql.script_block_tmp`: Transformed script block where detection patterns replace original content with a marker to support scoring/counting and quickly spot match locations.
- `Esql.script_block_pattern_count`: Count of matches for the detection pattern(s) observed in the script block content.
- `powershell.file.script_block_entropy_bits`: Shannon entropy of the script block. Higher values may indicate obfuscation.
- `powershell.file.script_block_surprisal_stdev`: Standard deviation of surprisal across the script block. Low values indicate uniform randomness. High values indicate mixed patterns and variability.
- `powershell.file.script_block_unique_symbols`: Count of distinct characters present in the script block.
- `powershell.file.script_block_length`: Script block length (size) context.
#### Possible investigation steps
- Confirm scope and execution context:
- Review `host.name` and `host.id` to identify the impacted endpoint and determine whether it is a typical user workstation, server, or a special-purpose system in your environment.
- Review `user.name`, `user.domain`, and `user.id` to understand who executed the script and whether the account is expected to run PowerShell on this host (interactive user, service account, or administrative context).
- Use `agent.id` (if available) to identify the reporting agent and to support correlation with other telemetry collected from the same endpoint.
- Use the alert timestamp as the anchor to correlate activity immediately before and after the script block ran.
- Analyze the obfuscation and intended execution:
- Examine `powershell.file.script_block_text` to locate environment-variable slicing patterns (for example, `$env:<var>[<idx>]`, `$env:<var>[<idx1>,<idx2>,<idx3>]`, or `.name[<idx1>,<idx2>,<idx3>]`) and identify the variable names and indices being used.
- Use `Esql.script_block_tmp` to quickly find the match locations, then review the surrounding context in `powershell.file.script_block_text` to determine how the reconstructed string is used (assignment, concatenation/join, or immediate invocation).
- Determine whether the reconstructed output is used as a dynamic execution primitive (for example, passed to `Invoke-Expression` / `IEX`, used with the call operator, or invoked via a method). Focus on what content is ultimately evaluated or executed.
- Reconstruct full script content:
- If the script appears incomplete or staged across multiple events, use `powershell.file.script_block_id` with `powershell.sequence` and `powershell.total` to collect all fragments and rebuild the full script in order.
- After reconstruction, identify where string construction occurs versus where execution occurs to understand the end-to-end flow.
- Assess obfuscation level and intent using available enrichments:
- Review `Esql.script_block_pattern_count` to understand how frequently the reconstruction pattern appears within the script block; repeated occurrences can indicate systematic obfuscation rather than an isolated string operation.
- Review `powershell.file.script_block_length` for size context and compare it with typical script sizes seen for the same host or user.
- Review `powershell.file.script_block_entropy_bits`, `powershell.file.script_block_surprisal_stdev`, and `powershell.file.script_block_unique_symbols` to gauge whether the script contains encoded or highly obfuscated content (for example, large high-entropy blocks that may indicate packed or encoded data).
- Identify script origin and potential spread:
- If `file.path` is populated, review `file.name` and `file.directory` to determine where the script was sourced from and whether the location aligns with approved administrative tooling or software distribution paths.
- If `file.path` is not populated, treat the activity as potentially inline or dynamically generated and prioritize identifying the initiating process or source using adjacent telemetry.
- Scope for other alerts or script blocks on the same `host.id` or associated with the same `user.id` that show similar reconstruction patterns, especially within the same time window.
- Correlate with adjacent telemetry (as available in your environment):
- Using `host.id` / `host.name`, `user.id`, and the alert time, correlate with process execution data to identify the PowerShell host process and the initiating parent process or source (for example, interactive session, script runner, scheduled task, service, or another application).
- Correlate with network, file, registry, and authentication telemetry on the same host around the alert time to identify follow-on activity that supports malicious intent (download or retrieval of content, creation or modification of files, persistence-related changes, or suspicious logons).
### False positive analysis
- Scripts with legitimate use of environment variables for configuration management may trigger the rule. Users can create exceptions for specific scripts or processes known to use environment variables in a non-threatening manner.
- Automated scripts that dynamically construct commands for legitimate administrative tasks might be flagged. Review the script's purpose and source, and whitelist trusted scripts or processes.
- Development environments where scripts are frequently tested and modified may produce false positives. Implement monitoring exclusions for development machines or specific user accounts involved in script testing.
- Scripts using environment variables for localization or language settings can be mistakenly identified. Identify and exclude scripts that are part of standard localization processes.
- PowerShell scripts from trusted vendors or software packages that use environment variables for legitimate functionality should be reviewed and excluded from detection if verified as safe.
- Legitimate automation or administration scripts may construct command strings dynamically, including deriving short tokens from environment variables for compatibility or to reduce hard-coded strings.
- Security testing and purple-team or red-team activity may intentionally use environment-variable slicing to emulate evasive tradecraft.
- Developer tooling, obfuscation research, or PowerShell training content may include this technique. Benign usage is typically tied to known owners, consistent hosts, predictable execution windows, and the absence of suspicious downstream activity.
### Response and remediation
- Isolate the affected system from the network to prevent further execution of potentially malicious scripts and limit lateral movement.
- Terminate any suspicious PowerShell processes identified by the alert to stop ongoing malicious activity.
- Review the PowerShell script block text and associated file paths to understand the scope and intent of the script, focusing on any obfuscated commands or environment variable manipulations.
- Restore the system from a known good backup if malicious activity is confirmed and system integrity is compromised.
- Update endpoint protection and intrusion detection systems to recognize and block similar obfuscation patterns in PowerShell scripts.
- Escalate the incident to the security operations center (SOC) or incident response team for further investigation and to determine if additional systems are affected.
- Implement additional monitoring for unusual PowerShell activity and environment variable manipulations to enhance detection of similar threats in the future.
- If the activity is suspected or confirmed malicious:
- Contain the affected host to prevent additional execution and reduce lateral movement risk.
- Preserve evidence by collecting the complete script content using `powershell.file.script_block_id`, `powershell.sequence`, and `powershell.total`, and retain the original `powershell.file.script_block_text` for analysis.
- Extract and track indicators from the script content (for example, URLs, domains, IP addresses, file names, or unique strings) and scope for additional occurrences across the environment using `host.id`, `host.name`, `user.id`, and `file.path` when present.
- Identify and remediate the initial execution source (parent process or launching mechanism) and remove or quarantine any associated script files referenced by `file.path`.
- If account compromise is suspected, reset affected credentials and review for additional suspicious PowerShell activity associated with the same `user.id`.
- If the activity is determined to be benign:
- Document the business justification, owning team, expected hosts, and expected script location (`file.path` when present).
- Monitor for deviations in execution context (new hosts, new users, or materially different script content) and consider targeted tuning based on stable attributes such as `file.path` and known `user.id` values.
"""
risk_score = 47
rule_id = "b0c98cfb-0745-4513-b6f9-08dddb033490"
setup = """## Setup
The 'PowerShell Script Block Logging' logging policy must be enabled.
Steps to implement the logging policy with Advanced Audit Configuration:
```
Computer Configuration >
Administrative Templates >
Windows PowerShell >
Turn on PowerShell Script Block Logging (Enable)
```
Steps to implement the logging policy via registry:
```
reg add "hklm\\SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1
```
PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104).
Setup instructions: https://ela.st/powershell-logging-setup
"""
severity = "medium"
tags = [
@@ -114,6 +138,7 @@ from logs-windows.powershell_operational* metadata _id, _version, _index
_version,
_index,
host.name,
host.id,
agent.id,
user.id
@@ -157,3 +182,21 @@ id = "TA0002"
name = "Execution"
reference = "https://attack.mitre.org/tactics/TA0002/"
[rule.investigation_fields]
field_names = [
"@timestamp",
"user.name",
"user.id",
"user.domain",
"powershell.file.script_block_text",
"powershell.file.script_block_id",
"powershell.sequence",
"powershell.total",
"file.path",
"file.directory",
"file.name",
"process.pid",
"host.name",
"host.id",
"powershell.file.script_block_length"
]
@@ -2,74 +2,103 @@
creation_date = "2025/04/16"
integration = ["windows"]
maturity = "production"
updated_date = "2025/12/09"
updated_date = "2026/02/09"
[rule]
author = ["Elastic"]
description = """
Identifies PowerShell scripts that reconstruct the IEX (Invoke-Expression) command by accessing and indexing the string
representation of method references. This obfuscation technique uses constructs like ''.IndexOf.ToString() to expose
method metadata as a string, then extracts specific characters through indexed access and joins them to form IEX,
bypassing static keyword detection and evading defenses such as AMSI.
Detects PowerShell scripts that rebuilds IEX by converting method references to strings (for example,
''.IndexOf.ToString()) and extracting multiple indexed characters (for example, [n,n,n]). Attackers use method-string
reconstruction to conceal dynamic execution and bypass static detections and AMSI.
"""
from = "now-9m"
language = "esql"
license = "Elastic License v2"
name = "Dynamic IEX Reconstruction via Method String Access"
note = """ ## Triage and analysis
note = """## Triage and analysis
> **Disclaimer**:
> This investigation guide was created using generative AI technology and has been reviewed to improve its accuracy and relevance. While every effort has been made to ensure its quality, we recommend validating the content and adapting it to suit your specific environment and operational needs.
> 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 Dynamic IEX Reconstruction via Method String Access
PowerShell's flexibility allows dynamic command execution, which adversaries exploit by obfuscating commands like Invoke-Expression (IEX). They manipulate method strings to reconstruct IEX, evading static detection. The detection rule identifies scripts using this obfuscation by analyzing patterns in method string access, flagging suspicious activity for further investigation.
This alert indicates PowerShell script block content that uses method-to-string conversion and indexed character extraction to assemble an execution primitive at runtime, commonly "IEX" (Invoke-Expression). This obfuscation technique can conceal dynamic execution intent and is often used to reduce obvious keywords in the script body.
### Possible investigation steps
#### Key alert fields to review
- Review the powershell.file.script_block_text field to understand the content and intent of the script that triggered the alert. Look for any suspicious patterns or obfuscation techniques.
- Examine the file.path field to determine the location of the script on the host system, which can provide context about its origin and potential legitimacy.
- Check the host.name and user.id fields to identify the machine and user account involved in executing the script, which can help assess whether the activity aligns with expected behavior.
- Analyze the powershell.file.script_block_id and powershell.sequence fields to trace the execution sequence and correlate it with other PowerShell activities on the host, providing a broader view of the script's execution context.
- Investigate the agent.id field to verify the endpoint's security posture and ensure that it is up-to-date with the latest security patches and configurations.
- `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.
- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file.
- `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.
- `Esql.script_block_tmp`: Transformed script block where detection patterns replace original content with a marker to support scoring/counting and quickly spot match locations.
- `Esql.script_block_pattern_count`: Count of matches for the detection pattern(s) observed in the script block content.
- `powershell.file.script_block_entropy_bits`: Shannon entropy of the script block. Higher values may indicate obfuscation.
- `powershell.file.script_block_surprisal_stdev`: Standard deviation of surprisal across the script block. Low values indicate uniform randomness. High values indicate mixed patterns and variability.
- `powershell.file.script_block_unique_symbols`: Count of distinct characters present in the script block.
- `powershell.file.script_block_length`: Script block length (size) context.
#### Possible investigation steps
- Establish execution context and scope:
- Review `host.name` and `host.id` to identify the affected endpoint and its role/criticality.
- Review `user.name`, `user.domain`, and `user.id` to determine whether the activity aligns with expected administrative or automation usage.
- Review `file.path`, `file.directory`, and `file.name` (when present) to understand whether the script originated from an on-disk file.
- Review `agent.id` to pivot to other telemetry from the same endpoint and timeframe.
- Validate what matched and how extensively it appears:
- Review `Esql.script_block_pattern_count` to gauge how often the technique appears within the script block (higher counts can indicate heavier obfuscation).
- Use `Esql.script_block_tmp` to quickly locate the matched regions, then review the corresponding locations in `powershell.file.script_block_text` for the exact construct and nearby context.
- Review `powershell.file.script_block_length` alongside `powershell.file.script_block_entropy_bits`, `powershell.file.script_block_surprisal_stdev`, and `powershell.file.script_block_unique_symbols` to help distinguish isolated string tricks from broader obfuscation.
- Reconstruct the full script block when content is split:
- Pivot on `powershell.file.script_block_id` and order results by `powershell.sequence`.
- Use `powershell.total` to confirm you have all fragments before making a final assessment.
- Preserve the reassembled content from `powershell.file.script_block_text` for follow-on analysis and scoping.
- Determine the reconstructed token and follow-on behavior:
- In `powershell.file.script_block_text`, identify the method string being indexed and the associated index list (for example, [n,n,n]) to determine what characters are being assembled.
- Identify how the reconstructed string is used (for example, invoked directly, assigned to a variable, or passed as an argument) and what content it ultimately executes.
- Capture any secondary artifacts referenced in the script content (for example, embedded payload strings, additional script blocks, or external resource locations) and use them to drive further correlation.
- Validate likely origin and initiating source:
- If `file.path` is present, validate whether the script location is expected for the user and host, and whether it appears in a user-writable location or a standard administrative tooling path.
- If file origin fields are not present, the script may have been executed interactively or generated at runtime; rely on surrounding endpoint telemetry to identify the initiating process and any related activity.
- Correlate with adjacent activity to understand impact:
- Review other PowerShell script blocks on the same `host.id` and `user.id` around the alert time to identify staging steps and any follow-on execution.
- If process telemetry is available, identify the PowerShell process and its parent process that initiated execution, and check for suspicious child processes near the alert time.
- If network or file telemetry is available, look for downloads, outbound connections, and file writes temporally aligned with the script block execution and the content referenced within `powershell.file.script_block_text`.
- Assess prevalence across the environment:
- Search for similar patterns (including stable substrings from `powershell.file.script_block_text`) across other hosts and users.
- Prioritize results with higher `Esql.script_block_pattern_count` and higher obfuscation metrics to identify likely common tooling or shared payloads.
### False positive analysis
- Scripts with legitimate use of string manipulation methods like IndexOf or SubString may trigger false positives if they are part of complex PowerShell scripts used in administrative tasks. To manage this, review the context of the script and consider adding exceptions for known safe scripts or users.
- Automated scripts from trusted software that perform extensive string operations for configuration or data processing might be flagged. Identify these scripts and exclude them by their script block ID or file path to prevent unnecessary alerts.
- Development environments where PowerShell is used for testing or debugging purposes may generate alerts due to frequent use of string manipulation. Implement exclusions based on host names or user IDs associated with these environments to reduce noise.
- Security tools or monitoring solutions that use PowerShell for log analysis or system checks might inadvertently match the detection pattern. Verify the source of the script and whitelist these tools by agent ID or specific script characteristics.
- Regularly review and update the exclusion list to ensure it reflects the current environment and does not inadvertently allow malicious activity.
- PowerShell developers or automation teams may experiment with unconventional string manipulation, but method-string indexing to assemble execution primitives is uncommon in routine administration.
- Authorized security testing, malware analysis, or threat emulation activities can intentionally use this technique; validate against approved testing windows and operator accounts.
- Some script packaging or code protection approaches can introduce non-standard string operations; treat as benign only when the script origin (`file.path` / `file.name`), execution context (`user.id`), and surrounding host activity support a known, approved workflow.
### Response and remediation
- Isolate the affected host immediately to prevent further execution of potentially malicious scripts and limit lateral movement within the network.
- Terminate any suspicious PowerShell processes identified by the alert to stop ongoing malicious activity.
- Review the PowerShell script block text and script block ID from the alert to understand the scope and intent of the obfuscation technique used.
- Remove any unauthorized or malicious scripts from the affected system to prevent re-execution.
- Conduct a thorough scan of the isolated host using updated antivirus and anti-malware tools to identify and remove any additional threats.
- Restore the affected system from a known good backup if the integrity of the system is compromised and cannot be assured.
- Escalate the incident to the security operations center (SOC) or incident response team for further analysis and to determine if additional systems are affected.
- If malicious or suspicious activity is confirmed:
- Contain the affected host identified by `host.id` to prevent additional execution and lateral movement.
- Preserve evidence from the alert, including `powershell.file.script_block_text`, `powershell.file.script_block_id`, `powershell.sequence`, `powershell.total`, `file.path`, and `Esql.script_block_pattern_count`.
- Scope for related activity by searching for similar content patterns across the environment and identifying additional impacted hosts and accounts.
- If an on-disk script is involved (`file.path` present), collect the file for analysis and remove or quarantine it according to your incident handling process.
- Review the associated account (`user.id`) for additional suspicious activity and remediate credential exposure as appropriate (for example, reset credentials and review recent authentication activity).
- If the activity is determined to be benign:
- Document the legitimate script source, expected hosts, and operator accounts for future triage.
- Reduce noise with narrowly scoped suppression using stable characteristics available in the alert (for example, consistent `file.path` and repeatable non-sensitive substrings in `powershell.file.script_block_text`), while continuing to monitor for deviations.
"""
risk_score = 21
rule_id = "9f432a8b-9588-4550-838e-1f77285580d3"
setup = """## Setup
The 'PowerShell Script Block Logging' logging policy must be enabled.
Steps to implement the logging policy with Advanced Audit Configuration:
```
Computer Configuration >
Administrative Templates >
Windows PowerShell >
Turn on PowerShell Script Block Logging (Enable)
```
Steps to implement the logging policy via registry:
```
reg add "hklm\\SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1
```
PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104).
Setup instructions: https://ela.st/powershell-logging-setup
"""
severity = "low"
tags = [
@@ -116,6 +145,7 @@ from logs-windows.powershell_operational* metadata _id, _version, _index
_version,
_index,
host.name,
host.id,
agent.id,
user.id
@@ -166,3 +196,21 @@ id = "TA0002"
name = "Execution"
reference = "https://attack.mitre.org/tactics/TA0002/"
[rule.investigation_fields]
field_names = [
"@timestamp",
"user.name",
"user.id",
"user.domain",
"powershell.file.script_block_text",
"powershell.file.script_block_id",
"powershell.sequence",
"powershell.total",
"file.path",
"file.directory",
"file.name",
"process.pid",
"host.name",
"host.id",
"powershell.file.script_block_length"
]
@@ -2,72 +2,102 @@
creation_date = "2025/04/14"
integration = ["windows"]
maturity = "production"
updated_date = "2025/12/09"
updated_date = "2026/02/09"
[rule]
author = ["Elastic"]
description = """
Identifies PowerShell scripts that use reversed strings as a form of obfuscation. These methods are designed to evade
static analysis and bypass security protections such as the Antimalware Scan Interface (AMSI).
Detects PowerShell scripts containing reversed keyword strings associated with execution or network activity (for
example, ekovni, noisserpxe, daolnwod, tcejbo-wen, tcejboimw, etc.). Attackers reverse keywords and reconstruct them at
runtime to hide intent and evade static detection and AMSI.
"""
from = "now-9m"
language = "esql"
license = "Elastic License v2"
name = "Potential PowerShell Obfuscation via Reverse Keywords"
note = """ ## Triage and analysis
note = """## Triage and analysis
> **Disclaimer**:
> This investigation guide was created using generative AI technology and has been reviewed to improve its accuracy and relevance. While every effort has been made to ensure its quality, we recommend validating the content and adapting it to suit your specific environment and operational needs.
> 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 PowerShell Obfuscation via Reverse Keywords
PowerShell, a powerful scripting language in Windows environments, is often targeted by adversaries for obfuscation to bypass security measures like AMSI. Attackers reverse keywords in scripts to evade static analysis. The detection rule identifies such obfuscation by searching for reversed keywords, replacing them with a unique marker, and counting occurrences. This helps in flagging scripts with multiple obfuscated elements, indicating potential malicious activity.
This alert indicates PowerShell script block content contains multiple reversed keyword strings commonly associated with execution, string manipulation, environment discovery, or networking. Reversing strings is frequently paired with runtime reconstruction (for example, reversing character arrays or joining string fragments) to reduce readability and evade simple content inspection.
### Possible investigation steps
Determine whether the script is part of expected administrative automation, software tooling, or an unauthorized execution chain. Prioritize analysis that reconstructs the full script, deobfuscates the reversed tokens, and identifies any follow-on behaviors such as dynamic execution, network access, or system discovery.
- Review the `powershell.file.script_block_text` field to understand the context and content of the script that triggered the alert. Look for any suspicious or unexpected behavior in the script logic.
- Examine the `file.path` field to determine the location of the script on the system. This can provide insights into whether the script is part of a legitimate application or potentially malicious.
- Check the `powershell.file.script_block_id` and `powershell.sequence` fields to identify if the script is part of a larger sequence of commands. This can help in understanding the full scope of the script's execution.
- Investigate the `agent.id` field to identify the specific endpoint where the script was executed. This can help in correlating with other alerts or logs from the same machine.
- Assess the `count` field to determine the extent of obfuscation. A higher count may indicate a more heavily obfuscated script, suggesting a higher likelihood of malicious intent.
#### 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.
- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file.
- `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.
- `Esql.script_block_tmp`: Transformed script block where detection patterns replace original content with a marker to support scoring/counting and quickly spot match locations.
- `Esql.script_block_pattern_count`: Count of matches for the detection pattern(s) observed in the script block content.
- `powershell.file.script_block_entropy_bits`: Shannon entropy of the script block. Higher values may indicate obfuscation.
- `powershell.file.script_block_surprisal_stdev`: Standard deviation of surprisal across the script block. Low values indicate uniform randomness. High values indicate mixed patterns and variability.
- `powershell.file.script_block_unique_symbols`: Count of distinct characters present in the script block.
- `powershell.file.script_block_length`: Script block length (size) context.
#### Possible investigation steps
- Identify the execution scope and ownership:
- Review `host.name` / `host.id` to confirm the affected endpoint and its criticality.
- Review `user.id` (and `user.name` / `user.domain` if available) to understand the account context and whether this user is expected to run PowerShell on this host.
- Prioritize based on obfuscation signals:
- Review `Esql.script_block_pattern_count`; higher counts suggest more extensive keyword hiding and can increase suspicion.
- Use `powershell.file.script_block_length`, `powershell.file.script_block_entropy_bits`, `powershell.file.script_block_unique_symbols`, and `powershell.file.script_block_surprisal_stdev` to gauge how heavily obfuscated or machine-generated the content may be (treat these as supporting context, not proof of maliciousness).
- Reconstruct the full script content when split:
- If `powershell.total` is greater than 1, retrieve all events with the same `powershell.file.script_block_id` and order them by `powershell.sequence` to rebuild the complete script block content.
- Preserve both the reconstructed script and the original per-event `powershell.file.script_block_text` to maintain context and ordering.
- Deobfuscate and interpret intent:
- Review `powershell.file.script_block_text` for reversed tokens and reverse them to identify the intended keywords and operations (for example, indicators of dynamic execution, downloads, socket/connection handling, WMI usage, or Win32 references).
- Look for runtime string reconstruction patterns in the script content (for example, joins, character array operations, or replace operations) that turn reversed fragments into executable commands or parameters.
- Use `Esql.script_block_tmp` to quickly locate the matched areas, then validate findings against `powershell.file.script_block_text`.
- Evaluate file-origin context (when present):
- Review `file.path` (and `file.directory` / `file.name` if available) to determine whether the script is associated with an on-disk file and whether that location aligns with your organization's expected script locations and deployment practices.
- If an on-disk script is indicated, coordinate collection of the referenced file for offline analysis and determine whether it is present on other systems.
- Extract and operationalize indicators:
- From `powershell.file.script_block_text`, extract any embedded indicators such as hostnames, IP addresses, URLs, ports, file paths, or encoded blobs.
- Use extracted indicators to scope for related activity on the same `host.id` and across other hosts where the same `user.id` is active, focusing on the alert timeframe and immediately adjacent activity.
- Correlate with adjacent telemetry to identify the execution chain and impact (as available in your environment):
- Process activity: identify the PowerShell host process and the initiating parent process to understand whether execution was interactive, scheduled, or launched by another program.
- Network activity: look for outbound connections aligned with the alert timestamp, especially if deobfuscated content suggests downloads or socket connections.
- File and registry activity: look for payload staging, new or modified files, or persistence-related changes that occur shortly after the script block execution.
- Authentication activity: review for suspicious logons, remote session creation, or lateral movement attempts around the same time on the affected host.
- Determine severity and next actions:
- If the deobfuscated content indicates remote retrieval, execution of downloaded content, credential access, persistence, or lateral movement, treat the alert as potentially malicious and escalate for response.
- If the script appears benign, document the validated purpose, expected owner, and any recurring identifiers (such as file location patterns) to support future triage.
### False positive analysis
- Scripts with legitimate administrative functions may use reversed keywords for benign purposes, such as custom logging or debugging. Review the context of the script to determine if the usage is intentional and non-malicious.
- Automated scripts generated by legitimate software tools might include reversed keywords as part of their normal operation. Identify these tools and create exceptions for their known script patterns to prevent unnecessary alerts.
- Developers or IT personnel might use reversed keywords in test environments to simulate obfuscation techniques. Ensure these environments are well-documented and excluded from production monitoring to avoid false positives.
- PowerShell scripts used in educational or training settings may intentionally include obfuscation techniques for learning purposes. Exclude these scripts by identifying their unique characteristics or file paths.
- Regularly update the list of excluded scripts or patterns as new legitimate use cases are identified, ensuring the detection rule remains effective without generating excessive false positives.
- Internal scripts or tooling may use reversed strings as lightweight obfuscation to conceal configuration values or reduce casual readability. Validate the script's ownership, change history, and whether its presence and execution timing are expected for `host.id` and `user.id`.
- Commercial software, endpoint management agents, or security tooling may generate or embed obfuscated PowerShell during installation, updates, or health checks. Validate whether the activity aligns with known maintenance windows, expected endpoints, and consistent script content and `file.path` patterns.
- Authorized security testing may intentionally use string reversal. Confirm the scope, timing, and target hosts with the appropriate stakeholders before closing the alert.
### Response and remediation
- Isolate the affected system from the network to prevent further spread of potentially malicious scripts.
- Terminate any suspicious PowerShell processes identified by the alert to halt ongoing malicious activity.
- Conduct a thorough review of the script block text and associated files to understand the scope and intent of the obfuscation.
- Remove or quarantine any identified malicious scripts or files from the system to prevent re-execution.
- Restore affected systems from a known good backup if malicious activity has altered system integrity.
- Update endpoint protection and security tools to recognize and block similar obfuscation techniques in the future.
- Escalate the incident to the security operations center (SOC) or incident response team for further investigation and monitoring of potential lateral movement or additional threats.
- If activity is suspicious or unauthorized, contain the affected host to prevent further script execution and potential follow-on actions.
- Preserve evidence:
- Retain the full `powershell.file.script_block_text` (including all segments reconstructed via `powershell.file.script_block_id`, `powershell.sequence`, and `powershell.total`).
- Retain `file.path` context and the alert metadata needed to pivot (such as `host.id` and `user.id`).
- Identify and remediate the execution source:
- Determine how PowerShell was launched (interactive, scheduled, or by another process) using correlated telemetry, and remove the triggering mechanism.
- If an on-disk script is involved, remediate the file at `file.path` and any associated payloads or artifacts identified during analysis.
- Scope and hunt:
- Search for the same or similar obfuscated content and extracted indicators across other endpoints, prioritizing systems accessed by the same `user.id` and systems with similar `file.path` patterns.
- Account actions:
- If account misuse is suspected, follow organizational procedures to contain the account (for example, credential reset and session revocation) and review recent activity for additional suspicious behavior.
- Recovery and hardening:
- Verify PowerShell logging coverage and retention are sufficient for incident response, and monitor for recurrence of similar reversed-keyword patterns on affected hosts and users.
"""
risk_score = 21
rule_id = "f38633f4-3b31-4c80-b13d-e77c70ce8254"
setup = """## Setup
The 'PowerShell Script Block Logging' logging policy must be enabled.
Steps to implement the logging policy with Advanced Audit Configuration:
```
Computer Configuration >
Administrative Templates >
Windows PowerShell >
Turn on PowerShell Script Block Logging (Enable)
```
Steps to implement the logging policy via registry:
```
reg add "hklm\\SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1
```
PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104).
Setup instructions: https://ela.st/powershell-logging-setup
"""
severity = "low"
tags = [
@@ -111,7 +141,10 @@ from logs-windows.powershell_operational* metadata _id, _version, _index
_id,
_version,
_index,
agent.id
host.name,
host.id,
agent.id,
user.id
// Filter for scripts that match the pattern at least twice
| where Esql.script_block_pattern_count >= 2
@@ -153,3 +186,21 @@ id = "TA0002"
name = "Execution"
reference = "https://attack.mitre.org/tactics/TA0002/"
[rule.investigation_fields]
field_names = [
"@timestamp",
"user.name",
"user.id",
"user.domain",
"powershell.file.script_block_text",
"powershell.file.script_block_id",
"powershell.sequence",
"powershell.total",
"file.path",
"file.directory",
"file.name",
"process.pid",
"host.name",
"host.id",
"powershell.file.script_block_length"
]
@@ -2,75 +2,102 @@
creation_date = "2025/04/14"
integration = ["windows"]
maturity = "production"
updated_date = "2025/12/09"
updated_date = "2026/02/09"
[rule]
author = ["Elastic"]
description = """
Identifies PowerShell scripts that use string concatenation as a form of obfuscation. These methods are designed to
evade static analysis and bypass security protections such as the Antimalware Scan Interface (AMSI).
Detects PowerShell scripts that repeatedly concatenates multiple quoted string literals with + to assemble commands or tokens at runtime.
Attackers use string concatenation to fragment keywords or URLs and evade static analysis and AMSI.
"""
from = "now-9m"
language = "esql"
license = "Elastic License v2"
name = "Potential PowerShell Obfuscation via String Concatenation"
note = """ ## Triage and analysis
note = """## Triage and analysis
> **Disclaimer**:
> This investigation guide was created using generative AI technology and has been reviewed to improve its accuracy and relevance. While every effort has been made to ensure its quality, we recommend validating the content and adapting it to suit your specific environment and operational needs.
> 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 PowerShell Obfuscation via String Concatenation
PowerShell is a powerful scripting language used for task automation and configuration management. Adversaries exploit its flexibility to obfuscate malicious scripts, often using string concatenation to evade detection. The detection rule identifies scripts with excessive concatenation patterns, flagging potential obfuscation by analyzing script length and pattern frequency, thus aiding in uncovering hidden threats.
This rule identifies PowerShell script block content that uses repeated concatenation of quoted string literals. This technique is commonly used to fragment keywords, URLs, and command text so they are assembled only at runtime. Focus the investigation on reconstructing the final strings, understanding how they are used within the script, and scoping related activity from the same host and user.
### Possible investigation steps
#### Key alert fields to review
- Review the powershell.file.script_block_text field to understand the content and purpose of the script, focusing on the sections identified by the string concatenation patterns.
- Examine the file.path field to determine the location of the script on the host system, which can provide context about its origin and potential legitimacy.
- Check the host.name and agent.id fields to identify the affected system and correlate with other security events or alerts from the same host for broader context.
- Investigate the user.id field to determine which user executed the script, assessing their role and whether they have a legitimate reason to run such scripts.
- Analyze the powershell.file.script_block_id and powershell.sequence fields to trace the execution flow and sequence of the script blocks, which may reveal additional obfuscation or malicious behavior.
- Cross-reference the _id and _index fields with other logs or alerts to identify any related incidents or patterns of activity that might indicate a larger threat campaign.
- `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.
- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file.
- `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.
- `Esql.script_block_tmp`: Transformed script block where detection patterns replace original content with a marker to support scoring/counting and quickly spot match locations.
- `Esql.script_block_pattern_count`: Count of matches for the detection pattern(s) observed in the script block content.
- `powershell.file.script_block_entropy_bits`: Shannon entropy of the script block. Higher values may indicate obfuscation.
- `powershell.file.script_block_surprisal_stdev`: Standard deviation of surprisal across the script block. Low values indicate uniform randomness. High values indicate mixed patterns and variability.
- `powershell.file.script_block_unique_symbols`: Count of distinct characters present in the script block.
- `powershell.file.script_block_length`: Script block length (size) context.
#### Possible investigation steps
- Establish alert context and prioritize review:
- Review `host.name` / `host.id` and `user.name` / `user.domain` / `user.id` to understand where and under which account the script executed.
- Use `Esql.script_block_pattern_count` to gauge how heavily the script relies on concatenation. Higher counts can indicate more deliberate obfuscation.
- Review `powershell.file.script_block_length` and the statistical fields (`powershell.file.script_block_entropy_bits`, `powershell.file.script_block_surprisal_stdev`, `powershell.file.script_block_unique_symbols`) to assess whether the script contains high-variance or high-randomness content that may indicate encoding, packing, or layered obfuscation.
- Identify the most likely script origin:
- Review `file.path`, `file.directory`, and `file.name` (when present) to determine whether the script block content was sourced from an on-disk script. Note whether the location is expected for administrative tooling or is user-writable/unusual for the host role.
- If file origin fields are not populated, treat the activity as potentially inline/interactive execution and prioritize identifying what initiated it through correlation with surrounding telemetry.
- Recover the assembled strings and intent:
- Start with `Esql.script_block_tmp` to find where concatenation patterns occur, then inspect the surrounding text in `powershell.file.script_block_text` for the full logic.
- Reconstruct concatenated literals by joining the quoted fragments (preserving ordering and separators) to reveal the final keywords, paths, URLs, arguments, or identifiers the script is attempting to hide.
- Look for how reconstructed strings are used, especially:
- Dynamic invocation of reconstructed commands or expressions.
- Download or retrieval of remote content.
- Decoding/decryption routines and second-stage content handling.
- Construction of file paths, scheduled execution artifacts, or configuration changes.
- Capture any reconstructed indicators (domains, URLs, file names, directories, command fragments) that can be used to scope other activity.
- Reconstruct full script content when split across events:
- Pivot on `powershell.file.script_block_id` to collect related script block events from the same execution context.
- If `powershell.total` is greater than 1, gather all fragments and order them by `powershell.sequence` to rebuild the complete script content before making a final determination.
- Review whether additional script blocks were executed in close succession by the same `user.id` on the same `host.id`, which may indicate staging or multi-step execution.
- Scope the activity across hosts and accounts:
- On the same `host.id`, look for other script blocks that share the same `file.path` or distinctive reconstructed strings to determine if this is a single run or repeated behavior.
- Pivot on `user.id` to identify the same technique on other endpoints, which can indicate credential misuse or automated distribution.
- Correlate with adjacent telemetry (as available in your environment):
- Process execution: identify the PowerShell host process and its parent process near the alert time to determine whether execution was interactive or spawned by another program.
- Network activity: if reconstructed strings include URLs/domains, check for outbound connections, downloads, or callbacks that align with the alert timeframe.
- Host changes: review nearby file and registry activity for payload drops, persistence creation, or configuration changes that match reconstructed paths or names.
- Authentication: review recent logon activity for `user.id` and `host.id` for anomalies that may explain the execution (new logon source, unusual logon type, or unexpected access patterns).
### False positive analysis
- Scripts with legitimate string concatenation for logging or configuration purposes may trigger the rule. Review the script context to determine if the concatenation is part of a benign operation.
- Automated scripts generated by development tools might use string concatenation extensively. Identify these tools and consider excluding their output directories or specific script patterns from the rule.
- PowerShell scripts used in complex data processing tasks may naturally contain high levels of string concatenation. Analyze the script's purpose and, if deemed safe, add exceptions for specific script block IDs or paths.
- Frequent administrative scripts that concatenate strings for dynamic command execution could be flagged. Verify the script's source and function, then whitelist known safe scripts by user ID or host name.
- Consider adjusting the threshold for pattern detection if legitimate scripts frequently exceed the current limit, ensuring that the rule remains effective without generating excessive false positives.
- Legitimate administrative or operational scripts may concatenate many string literals to generate dynamic content (for example, configuration files, templated output, or complex argument strings). Validate whether the reconstructed strings align with expected internal tooling and whether the execution context (`host.id`, `user.id`, and `file.path`) matches normal operations.
### Response and remediation
- Isolate the affected host immediately to prevent further spread of potentially malicious scripts across the network. Disconnect it from the network and any shared resources.
- Terminate any suspicious PowerShell processes identified by the alert to halt the execution of potentially obfuscated scripts.
- Conduct a thorough examination of the script block text and associated files to identify and remove any malicious code or artifacts. Use a secure, isolated environment for analysis.
- Restore the affected system from a known good backup if malicious activity is confirmed and cannot be easily remediated.
- Update and run a full antivirus and antimalware scan on the affected system to ensure no additional threats are present.
- Escalate the incident to the security operations center (SOC) or incident response team for further investigation and to determine if additional systems are compromised.
- Implement enhanced monitoring and logging for PowerShell activities across the network to detect similar obfuscation attempts in the future, ensuring that alerts are configured to notify the appropriate personnel promptly.
- If malicious or suspicious activity is confirmed:
- Contain the affected host to prevent follow-on execution or lateral movement.
- Preserve evidence from the alert, including `powershell.file.script_block_text`, `powershell.file.script_block_id`, `powershell.sequence` / `powershell.total`, and any `file.path` details that indicate script origin.
- Use reconstructed strings to scope across the environment for related script blocks and any referenced artifacts (additional scripts, payload files, or remote destinations).
- Identify and remediate the initial execution vector by tracing the execution chain (user context and initiating process) and removing any persistence mechanisms discovered during investigation.
- If account compromise is suspected, reset credentials for the affected `user.id`, review recent access patterns, and apply least-privilege controls to limit further abuse.
- If the activity is determined to be benign:
- Document the script purpose, expected execution context, and the specific concatenated strings that explain the detection.
- Monitor for deviations from the established baseline (new hosts, new accounts, unexpected file paths, or substantially different reconstructed content).
"""
risk_score = 47
risk_score = 73
rule_id = "f6d8c743-0916-4483-8333-3c6f107e0caa"
setup = """## Setup
The 'PowerShell Script Block Logging' logging policy must be enabled.
Steps to implement the logging policy with Advanced Audit Configuration:
```
Computer Configuration >
Administrative Templates >
Windows PowerShell >
Turn on PowerShell Script Block Logging (Enable)
```
Steps to implement the logging policy via registry:
```
reg add "hklm\\SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1
```
PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104).
Setup instructions: https://ela.st/powershell-logging-setup
"""
severity = "medium"
severity = "high"
tags = [
"Domain: Endpoint",
"OS: Windows",
@@ -114,6 +141,7 @@ from logs-windows.powershell_operational* metadata _id, _version, _index
_version,
_index,
host.name,
host.id,
agent.id,
user.id
@@ -157,3 +185,21 @@ id = "TA0002"
name = "Execution"
reference = "https://attack.mitre.org/tactics/TA0002/"
[rule.investigation_fields]
field_names = [
"@timestamp",
"user.name",
"user.id",
"user.domain",
"powershell.file.script_block_text",
"powershell.file.script_block_id",
"powershell.sequence",
"powershell.total",
"file.path",
"file.directory",
"file.name",
"process.pid",
"host.name",
"host.id",
"powershell.file.script_block_length"
]
@@ -2,74 +2,104 @@
creation_date = "2025/04/03"
integration = ["windows"]
maturity = "production"
updated_date = "2025/12/17"
updated_date = "2026/02/09"
[rule]
author = ["Elastic"]
description = """
Identifies PowerShell scripts that use string reordering and runtime reconstruction techniques as a form of obfuscation.
These methods are designed to evade static analysis and bypass security protections such as the Antimalware Scan
Interface (AMSI).
Detects PowerShell scripts that uses format placeholders like "{0}{1}" with the -f operator or ::Format to reorder strings at runtime.
Attackers use format-based reconstruction to hide commands or payload strings and evade static analysis and AMSI.
"""
from = "now-9m"
language = "esql"
license = "Elastic License v2"
name = "Potential PowerShell Obfuscation via String Reordering"
note = """ ## Triage and analysis
note = """## Triage and analysis
> **Disclaimer**:
> This investigation guide was created using generative AI technology and has been reviewed to improve its accuracy and relevance. While every effort has been made to ensure its quality, we recommend validating the content and adapting it to suit your specific environment and operational needs.
> 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 PowerShell Obfuscation via String Reordering
PowerShell, a powerful scripting language in Windows environments, can be exploited by adversaries using obfuscation techniques like string reordering to evade detection. This involves rearranging strings and reconstructing them at runtime, bypassing static analysis and security measures. The detection rule identifies scripts with excessive length and specific patterns, flagging those with multiple occurrences of string format expressions, which are indicative of obfuscation attempts. By filtering out known benign patterns, it reduces false positives, focusing on genuine threats.
This alert indicates a PowerShell script block used indexed format placeholders (for example, "{0}{1}") with runtime formatting (for example, the `-f` operator or `::Format`) to reorder and reconstruct strings. This technique can hide meaningful strings (commands, URLs, artifact names) from straightforward text inspection and can be used as part of staged execution.
### Possible investigation steps
Because the detection requires repeated occurrences of these patterns in a larger script block, triage should focus on (1) execution context (host and user), (2) script origin (file-backed vs. in-memory/interactive), and (3) what strings are being reconstructed and what actions they enable.
- Review the script block text by examining the powershell.file.script_block_text field to understand the nature of the obfuscation and identify any potentially malicious commands or patterns.
- Check the file.path and file.name fields to determine the origin and context of the script, which can provide insights into whether the script is part of a legitimate application or a potential threat.
- Investigate the host.name and user.id fields to identify the affected system and user, which can help in assessing the potential impact and scope of the incident.
- Analyze the powershell.file.script_block_id and powershell.sequence fields to trace the execution sequence and history of the script, which may reveal additional suspicious activities or related scripts.
- Correlate the alert with other security events or logs from the same host or user to identify any patterns or additional indicators of compromise that may suggest a broader attack campaign.
#### 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.
- `file.path`, `file.directory`, `file.name`: File-origin context when the script block is sourced from an on-disk file.
- `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.
- `Esql.script_block_tmp`: Transformed script block where detection patterns replace original content with a marker to support scoring/counting and quickly spot match locations.
- `Esql.script_block_pattern_count`: Count of matches for the detection pattern(s) observed in the script block content.
- `powershell.file.script_block_entropy_bits`: Shannon entropy of the script block. Higher values may indicate obfuscation.
- `powershell.file.script_block_surprisal_stdev`: Standard deviation of surprisal across the script block. Low values indicate uniform randomness. High values indicate mixed patterns and variability.
- `powershell.file.script_block_unique_symbols`: Count of distinct characters present in the script block.
- `powershell.file.script_block_length`: Script block length (size) context.
#### Possible investigation steps
- Confirm the execution context and initial scope:
- Identify the affected endpoint using `host.name` and `host.id`. Check for other security alerts or suspicious activity on the same host around the alert time.
- Identify the account context using `user.name`, `user.domain`, and `user.id`. Prioritize alerts where the user is unexpected for the host role or where the user does not typically run PowerShell.
- If `file.path` / `file.directory` / `file.name` are present, capture the script location and assess whether the path and filename are expected for that host and user. If file fields are missing, treat the activity as potentially interactive or in-memory and increase emphasis on correlated telemetry.
- Review the script block content and determine what is being reconstructed:
- Start with `Esql.script_block_tmp` to quickly locate where formatting patterns occur, then use `powershell.file.script_block_text` as the authoritative source for analysis and evidence.
- Identify how formatting is used:
- Placeholder-only or placeholder-heavy format strings that primarily consist of `{n}` tokens.
- Out-of-order placeholder indexes (for example, `{3}{0}{2}{1}`) and repeated reordering blocks.
- Multiple reconstruction stages where formatted output is subsequently reformatted or concatenated.
- Reconstruct key strings by mapping placeholder indexes to the arguments/fragments used in each formatting operation. Record any reconstructed strings that indicate follow-on behavior (remote addresses, filenames, persistence identifiers, or execution flow).
- Use the available scoring and statistics fields to guide prioritization:
- Review `Esql.script_block_pattern_count` to understand how heavily the script relies on formatting-based reconstruction. Higher counts generally increase suspicion.
- Review `powershell.file.script_block_entropy_bits`, `powershell.file.script_block_unique_symbols`, `powershell.file.script_block_surprisal_stdev`, and `powershell.file.script_block_length` to differentiate structured, readable scripts from highly variable or packed content.
- Treat these values as supporting signals; base the decision primarily on reconstructed strings and correlated activity.
- Reconstruct full script content when split across multiple events:
- Pivot on `powershell.file.script_block_id` to gather all fragments for the same script block.
- Order fragments using `powershell.sequence` and confirm completeness using `powershell.total` before drawing conclusions.
- Correlate and validate impact using adjacent telemetry available in your environment:
- Review other PowerShell script blocks from the same `host.id` and `user.id` to identify staging, deobfuscation, or follow-on execution.
- Correlate with endpoint telemetry for the same host and timeframe to understand how PowerShell was started and what occurred next (process ancestry, network activity, file/registry changes, and authentication activity). Use reconstructed strings to focus this correlation.
- Expand the hunt to assess prevalence:
- Search for the same or similar content in `powershell.file.script_block_text` (shared fragments, repeated placeholder patterns) across other hosts.
- Use `Esql.script_block_pattern_count` and the script block statistics fields to identify other high-similarity or high-complexity scripts that may represent the same technique.
### False positive analysis
- Scripts related to the Icinga Framework may trigger false positives due to their use of string formatting. To handle this, ensure that the file name "framework_cache.psm1" is excluded from the detection rule.
- PowerShell scripts that include specific sentinel patterns, such as "sentinelbreakpoints" or paths like ":::::\\windows\\sentinel", combined with variables like "$local:Bypassed" or "origPSExecutionPolicyPreference", are known to be benign. These should be excluded to reduce noise.
- Regularly review and update the exclusion list to include any new benign patterns that are identified over time, ensuring the rule remains effective without generating unnecessary alerts.
- Consider implementing a whitelist of known safe scripts or script authors to further minimize false positives, especially in environments with frequent legitimate use of complex PowerShell scripts.
- Legitimate automation can use indexed placeholders to build dynamic output, reports, or templated configuration content. Benign usage is more likely when the resulting strings are human-readable and the script has an expected on-disk origin (`file.path` / `file.name`) and consistent execution over time.
- Some internally developed frameworks generate PowerShell dynamically and may include repeated formatting patterns. Validate ownership of the script source and whether execution by the identified `user.id` on the identified `host.id` is expected.
- Localization or templating logic may use indexed placeholders. This is typically associated with readable templates and stable execution patterns rather than multi-stage reconstruction of operational strings.
### Response and remediation
- Isolate the affected system from the network to prevent further spread of potentially malicious scripts.
- Terminate any suspicious PowerShell processes identified by the alert to stop ongoing malicious activity.
- Conduct a thorough review of the PowerShell script block text flagged by the alert to understand the intent and potential impact of the obfuscated script.
- Remove any malicious scripts or files identified during the investigation from the affected system to prevent re-execution.
- Restore the system from a known good backup if the script has caused significant changes or damage to the system.
- Update and strengthen endpoint protection measures, ensuring that AMSI and other security tools are fully operational and configured to detect similar obfuscation techniques.
- Escalate the incident to the security operations center (SOC) or incident response team for further analysis and to determine if additional systems are affected.
- If malicious or suspicious activity is confirmed:
- Contain the affected endpoint identified by `host.name` / `host.id` to prevent further execution and limit lateral movement.
- Preserve evidence, including `powershell.file.script_block_text`, `powershell.file.script_block_id`, `powershell.sequence`, `powershell.total`, and the alert enrichment fields (`Esql.script_block_tmp`, `Esql.script_block_pattern_count`, and script block statistics).
- Use reconstructed strings to drive scoping and impact assessment (look for related activity on the same host, and search for the same indicators across other hosts and users).
- Eradication and recovery:
- Identify the execution mechanism and remove it (for example, an unexpected script file, a startup trigger, or other persistence identified during correlation).
- Remove or quarantine related artifacts discovered during analysis and validate that similar activity is not occurring on other endpoints.
- If the activity is determined to be benign:
- Document the expected script source (`file.path` / `file.name`), the responsible team, and the expected execution context (`host.id`, `user.id`) to support faster triage of future alerts.
- Monitor for deviations from the established baseline (new hosts, new users, or materially different reconstructed strings).
"""
risk_score = 21
risk_score = 47
rule_id = "e903ce9a-5ce6-4246-bb14-75ed3ec2edf5"
setup = """## Setup
The 'PowerShell Script Block Logging' logging policy must be enabled.
Steps to implement the logging policy with Advanced Audit Configuration:
```
Computer Configuration >
Administrative Templates >
Windows PowerShell >
Turn on PowerShell Script Block Logging (Enable)
```
Steps to implement the logging policy via registry:
```
reg add "hklm\\SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1
```
PowerShell Script Block Logging must be enabled to generate the events used by this rule (e.g., 4104).
Setup instructions: https://ela.st/powershell-logging-setup
"""
severity = "low"
severity = "medium"
tags = [
"Domain: Endpoint",
"OS: Windows",
@@ -114,6 +144,7 @@ from logs-windows.powershell_operational* metadata _id, _version, _index
_version,
_index,
host.name,
host.id,
agent.id,
user.id
@@ -176,3 +207,21 @@ id = "TA0002"
name = "Execution"
reference = "https://attack.mitre.org/tactics/TA0002/"
[rule.investigation_fields]
field_names = [
"@timestamp",
"user.name",
"user.id",
"user.domain",
"powershell.file.script_block_text",
"powershell.file.script_block_id",
"powershell.sequence",
"powershell.total",
"file.path",
"file.directory",
"file.name",
"process.pid",
"host.name",
"host.id",
"powershell.file.script_block_length"
]