Potential Dynamic IEX Reconstruction via Environment Variables

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.

Elastic rule (View on GitHub)

 1[metadata]
 2creation_date = "2025/04/16"
 3integration = ["windows"]
 4maturity = "production"
 5updated_date = "2025/08/14"
 6
 7[rule]
 8author = ["Elastic"]
 9description = """
10Identifies PowerShell scripts that reconstruct the IEX (Invoke-Expression) command at runtime using indexed slices of
11environment variables. This technique leverages character access and join operations to build execution logic
12dynamically, bypassing static keyword detection and evading defenses such as AMSI.
13"""
14from = "now-9m"
15language = "esql"
16license = "Elastic License v2"
17name = "Potential Dynamic IEX Reconstruction via Environment Variables"
18note = """ ## Triage and analysis
19
20> **Disclaimer**:
21> 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.
22
23### Investigating Potential Dynamic IEX Reconstruction via Environment Variables
24
25PowerShell'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.
26
27### Possible investigation steps
28
29- 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.
30- 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.
31- 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.
32- 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.
33- Assess the count field to understand the extent of obfuscation patterns detected, which can indicate the complexity and potential maliciousness of the script.
34
35### False positive analysis
36
37- 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.
38- 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.
39- 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.
40- Scripts using environment variables for localization or language settings can be mistakenly identified. Identify and exclude scripts that are part of standard localization processes.
41- 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.
42
43### Response and remediation
44
45- Isolate the affected system from the network to prevent further execution of potentially malicious scripts and limit lateral movement.
46- Terminate any suspicious PowerShell processes identified by the alert to stop ongoing malicious activity.
47- 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.
48- Restore the system from a known good backup if malicious activity is confirmed and system integrity is compromised.
49- Update endpoint protection and intrusion detection systems to recognize and block similar obfuscation patterns in PowerShell scripts.
50- Escalate the incident to the security operations center (SOC) or incident response team for further investigation and to determine if additional systems are affected.
51- Implement additional monitoring for unusual PowerShell activity and environment variable manipulations to enhance detection of similar threats in the future.
52"""
53risk_score = 47
54rule_id = "b0c98cfb-0745-4513-b6f9-08dddb033490"
55setup = """## Setup
56
57The 'PowerShell Script Block Logging' logging policy must be enabled.
58Steps to implement the logging policy with Advanced Audit Configuration:

Computer Configuration > Administrative Templates > Windows PowerShell > Turn on PowerShell Script Block Logging (Enable)

1
2Steps to implement the logging policy via registry:

reg add "hklm\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1

 1"""
 2severity = "medium"
 3tags = [
 4    "Domain: Endpoint",
 5    "OS: Windows",
 6    "Use Case: Threat Detection",
 7    "Tactic: Defense Evasion",
 8    "Data Source: PowerShell Logs",
 9    "Resources: Investigation Guide",
10]
11timestamp_override = "event.ingested"
12type = "esql"
13
14query = '''
15from logs-windows.powershell_operational* metadata _id, _version, _index
16| where event.code == "4104"
17
18// Filter out smaller scripts that are unlikely to implement obfuscation using the patterns we are looking for
19| eval Esql.script_block_length = length(powershell.file.script_block_text)
20| where Esql.script_block_length > 500
21
22// replace the patterns we are looking for with the 🔥 emoji to enable counting them
23// The emoji is used because it's unlikely to appear in scripts and has a consistent character length of 1
24| eval Esql.script_block_tmp = replace(
25    powershell.file.script_block_text,
26    """(?i)(\$(?:\w+|\w+\:\w+)\[\d++\]\+\$(?:\w+|\w+\:\w+)\[\d++\]\+['"]x['"]|\$(?:\w+\:\w+)\[\d++,\d++,\d++\]|\.name\[\d++,\d++,\d++\])""",
27    "🔥"
28)
29
30// count how many patterns were detected by calculating the number of 🔥 characters inserted
31| eval Esql.script_block_pattern_count = length(Esql.script_block_tmp) - length(replace(Esql.script_block_tmp, "🔥", ""))
32
33// keep the fields relevant to the query, although this is not needed as the alert is populated using _id
34| keep
35    Esql.script_block_pattern_count,
36    Esql.script_block_length,
37    Esql.script_block_tmp,
38    powershell.file.script_block_text,
39    powershell.file.script_block_id,
40    file.path,
41    powershell.sequence,
42    powershell.total,
43    _id,
44    _index,
45    host.name,
46    agent.id,
47    user.id
48
49// Filter for scripts that match the pattern at least once
50| where Esql.script_block_pattern_count >= 1
51'''
52
53
54[[rule.threat]]
55framework = "MITRE ATT&CK"
56[[rule.threat.technique]]
57id = "T1027"
58name = "Obfuscated Files or Information"
59reference = "https://attack.mitre.org/techniques/T1027/"
60
61[[rule.threat.technique]]
62id = "T1140"
63name = "Deobfuscate/Decode Files or Information"
64reference = "https://attack.mitre.org/techniques/T1140/"
65
66
67[rule.threat.tactic]
68id = "TA0005"
69name = "Defense Evasion"
70reference = "https://attack.mitre.org/tactics/TA0005/"
71[[rule.threat]]
72framework = "MITRE ATT&CK"
73[[rule.threat.technique]]
74id = "T1059"
75name = "Command and Scripting Interpreter"
76reference = "https://attack.mitre.org/techniques/T1059/"
77[[rule.threat.technique.subtechnique]]
78id = "T1059.001"
79name = "PowerShell"
80reference = "https://attack.mitre.org/techniques/T1059/001/"
81
82
83
84[rule.threat.tactic]
85id = "TA0002"
86name = "Execution"
87reference = "https://attack.mitre.org/tactics/TA0002/"

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.

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.

Possible investigation steps

  • 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.

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.

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.

Related rules

to-top