Dynamic IEX Reconstruction via Method String Access

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.

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 by accessing and indexing the string
11representation of method references. This obfuscation technique uses constructs like ''.IndexOf.ToString() to expose
12method metadata as a string, then extracts specific characters through indexed access and joins them to form IEX,
13bypassing static keyword detection and evading defenses such as AMSI.
14"""
15from = "now-9m"
16language = "esql"
17license = "Elastic License v2"
18name = "Dynamic IEX Reconstruction via Method String Access"
19note = """ ## Triage and analysis
20
21> **Disclaimer**:
22> 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.
23
24### Investigating Dynamic IEX Reconstruction via Method String Access
25
26PowerShell'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.
27
28### Possible investigation steps
29
30- 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.
31- 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.
32- 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.
33- 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.
34- 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.
35
36### False positive analysis
37
38- 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.
39- 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.
40- 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.
41- 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.
42- Regularly review and update the exclusion list to ensure it reflects the current environment and does not inadvertently allow malicious activity.
43
44### Response and remediation
45
46- Isolate the affected host immediately to prevent further execution of potentially malicious scripts and limit lateral movement within the network.
47- Terminate any suspicious PowerShell processes identified by the alert to stop ongoing malicious activity.
48- Review the PowerShell script block text and script block ID from the alert to understand the scope and intent of the obfuscation technique used.
49- Remove any unauthorized or malicious scripts from the affected system to prevent re-execution.
50- Conduct a thorough scan of the isolated host using updated antivirus and anti-malware tools to identify and remove any additional threats.
51- Restore the affected system from a known good backup if the integrity of the system is compromised and cannot be assured.
52- Escalate the incident to the security operations center (SOC) or incident response team for further analysis and to determine if additional systems are affected.
53"""
54risk_score = 21
55rule_id = "9f432a8b-9588-4550-838e-1f77285580d3"
56setup = """## Setup
57
58The 'PowerShell Script Block Logging' logging policy must be enabled.
59Steps 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 = "low"
 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)['"]['"].(Insert|Normalize|Chars|substring|Remove|LastIndexOfAny|LastIndexOf|IsNormalized|IndexOfAny|IndexOf)[^\[]+\[\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    file.directory,
42    powershell.sequence,
43    powershell.total,
44    _id,
45    _index,
46    host.name,
47    agent.id,
48    user.id
49
50// Filter for scripts that match the pattern at least once
51| where Esql.script_block_pattern_count >= 1
52
53| where not (
54    file.directory like "C:\\\\Program Files\\\\WindowsPowerShell\\\\Modules\\\\Maester\\\\1.1.0*" or
55    file.directory like "C:\\\\Users\\\\*\\\\Documents\\\\WindowsPowerShell\\\\Modules\\\\Maester\\\\1.1.0*"
56  )
57  // ESQL requires this condition, otherwise it only returns matches where file.directory exists.
58  or file.directory is null
59'''
60
61
62[[rule.threat]]
63framework = "MITRE ATT&CK"
64[[rule.threat.technique]]
65id = "T1027"
66name = "Obfuscated Files or Information"
67reference = "https://attack.mitre.org/techniques/T1027/"
68
69[[rule.threat.technique]]
70id = "T1140"
71name = "Deobfuscate/Decode Files or Information"
72reference = "https://attack.mitre.org/techniques/T1140/"
73
74
75[rule.threat.tactic]
76id = "TA0005"
77name = "Defense Evasion"
78reference = "https://attack.mitre.org/tactics/TA0005/"
79[[rule.threat]]
80framework = "MITRE ATT&CK"
81[[rule.threat.technique]]
82id = "T1059"
83name = "Command and Scripting Interpreter"
84reference = "https://attack.mitre.org/techniques/T1059/"
85[[rule.threat.technique.subtechnique]]
86id = "T1059.001"
87name = "PowerShell"
88reference = "https://attack.mitre.org/techniques/T1059/001/"
89
90
91
92[rule.threat.tactic]
93id = "TA0002"
94name = "Execution"
95reference = "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 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.

Possible investigation steps

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

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.

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.

Related rules

to-top