Potential PowerShell Obfuscation via Invalid Escape Sequences
Identifies PowerShell scripts that use invalid escape sequences as a form of obfuscation. This technique introduces backticks (`) between characters in a way that does not correspond to valid PowerShell escape sequences, breaking up strings and bypassing pattern-based detections while preserving execution logic. This is designed to evade static analysis and bypass security protections such as the Antimalware Scan Interface (AMSI).
Elastic rule (View on GitHub)
1[metadata]
2creation_date = "2025/04/15"
3integration = ["windows"]
4maturity = "production"
5updated_date = "2025/08/14"
6
7[rule]
8author = ["Elastic"]
9description = """
10Identifies PowerShell scripts that use invalid escape sequences as a form of obfuscation. This technique introduces
11backticks (`) between characters in a way that does not correspond to valid PowerShell escape sequences, breaking up
12strings and bypassing pattern-based detections while preserving execution logic. This is designed to evade static
13analysis and bypass security protections such as the Antimalware Scan Interface (AMSI).
14"""
15from = "now-9m"
16language = "esql"
17license = "Elastic License v2"
18name = "Potential PowerShell Obfuscation via Invalid Escape Sequences"
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 Potential PowerShell Obfuscation via Invalid Escape Sequences
25
26PowerShell, a powerful scripting language in Windows environments, can be exploited by adversaries using obfuscation techniques to evade detection. By inserting invalid escape sequences, attackers can obscure malicious scripts, bypassing static analysis and security tools like AMSI. The detection rule identifies such obfuscation by analyzing script patterns, specifically targeting unusual backtick usage, to flag potential threats.
27
28### Possible investigation steps
29
30- Review the `powershell.file.script_block_text` field to understand the context and content of the script block that triggered the alert. Look for patterns of invalid escape sequences and assess whether they appear intentionally obfuscated.
31- Examine the `file.name` and `file.path` fields to determine the origin and location of the script. This can help identify whether the script is part of a legitimate application or potentially malicious.
32- Check the `host.name` and `agent.id` fields to identify the affected system and the agent responsible for logging the event. This information is crucial for understanding the scope of the potential threat.
33- Analyze the `user.id` field to ascertain which user executed the script. This can provide insights into whether the user has a history of executing suspicious scripts or if their account may be compromised.
34- Investigate the `powershell.file.script_block_id` and `powershell.sequence` fields to trace the execution sequence and correlate it with other related script blocks, which may reveal additional obfuscation or malicious activity.
35- Assess the `count` field to evaluate the extent of obfuscation detected. A higher count may indicate more aggressive obfuscation techniques, warranting further scrutiny.
36
37### False positive analysis
38
39- Scripts from Visual Studio Code's PowerShell extension may trigger false positives due to its shell integration. To handle this, exclude scripts containing the pattern "$([char]0x1b)]633" from detection.
40- PowerShell modules with names starting with "TSS_" may be flagged incorrectly. Exclude these by adding a condition to ignore files matching the pattern "TSS_*.psm1".
41- Legitimate scripts that use backticks for formatting or other non-obfuscation purposes might be detected. Review such scripts and, if verified as safe, add them to an exception list based on their script block ID or file path.
42- Regularly update the exclusion list to reflect changes in legitimate script usage patterns, ensuring that new false positives are addressed promptly.
43
44### Response and remediation
45
46- Isolate the affected host immediately to prevent lateral movement and further execution of potentially malicious scripts. Disconnect the host from the network and disable remote access.
47
48- Analyze the script block text and file path to identify the source and nature of the obfuscated script. Determine if the script is part of a larger attack or if other systems are affected.
49
50- Remove or quarantine the identified malicious script and any associated files from the host. Ensure that all remnants of the obfuscated code are eliminated to prevent re-execution.
51
52- Conduct a thorough scan of the host using updated antivirus and antimalware tools to detect and remove any additional threats or indicators of compromise.
53
54- Review and update PowerShell execution policies and security settings to restrict the execution of scripts with invalid escape sequences. Implement stricter controls to prevent similar obfuscation techniques.
55
56- Escalate the incident to the security operations center (SOC) or relevant cybersecurity team for further investigation and monitoring. Provide detailed logs and findings to assist in understanding the scope and impact of the threat.
57
58- Implement enhanced logging and monitoring for PowerShell activities across the network to detect and respond to similar obfuscation attempts promptly. Use the identified patterns to refine detection capabilities.
59"""
60risk_score = 21
61rule_id = "64f17c52-6c6e-479e-ba72-236f3df18f3d"
62setup = """## Setup
63
64The 'PowerShell Script Block Logging' logging policy must be enabled.
65Steps 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" and powershell.file.script_block_text like "*`*"
17
18// replace the patterns we are looking for with the 🔥 emoji to enable counting them
19// The emoji is used because it's unlikely to appear in scripts and has a consistent character length of 1
20| eval Esql.script_block_tmp = replace(powershell.file.script_block_text, """[A-Za-z0-9_-]`(?![rntb]|\r|\n|\d)[A-Za-z0-9_-]""", "🔥")
21
22// count how many patterns were detected by calculating the number of 🔥 characters inserted
23| eval Esql.script_block_pattern_count = length(Esql.script_block_tmp) - length(replace(Esql.script_block_tmp, "🔥", ""))
24
25// keep the fields relevant to the query, although this is not needed as the alert is populated using _id
26| keep
27 Esql.script_block_pattern_count,
28 Esql.script_block_tmp,
29 powershell.file.script_block_text,
30 powershell.file.script_block_id,
31 file.name,
32 file.directory,
33 file.path,
34 powershell.sequence,
35 powershell.total,
36 _id,
37 _index,
38 host.name,
39 agent.id,
40 user.id
41
42// Filter for scripts that match the pattern at least 10 times
43| where Esql.script_block_pattern_count >= 10
44
45| where file.name not like "TSS_*.psm1"
46 // ESQL requires this condition, otherwise it only returns matches where file.name exists.
47 or file.name is null
48
49// VSCode Shell integration
50| where not powershell.file.script_block_text like "*$([char]0x1b)]633*"
51
52| where not file.directory == "C:\\Program Files\\MVPSI\\JAMS\\Agent\\Temp"
53 // ESQL requires this condition, otherwise it only returns matches where file.directory exists.
54 or file.directory is null
55'''
56
57
58[[rule.threat]]
59framework = "MITRE ATT&CK"
60[[rule.threat.technique]]
61id = "T1027"
62name = "Obfuscated Files or Information"
63reference = "https://attack.mitre.org/techniques/T1027/"
64
65[[rule.threat.technique]]
66id = "T1140"
67name = "Deobfuscate/Decode Files or Information"
68reference = "https://attack.mitre.org/techniques/T1140/"
69
70
71[rule.threat.tactic]
72id = "TA0005"
73name = "Defense Evasion"
74reference = "https://attack.mitre.org/tactics/TA0005/"
75[[rule.threat]]
76framework = "MITRE ATT&CK"
77[[rule.threat.technique]]
78id = "T1059"
79name = "Command and Scripting Interpreter"
80reference = "https://attack.mitre.org/techniques/T1059/"
81[[rule.threat.technique.subtechnique]]
82id = "T1059.001"
83name = "PowerShell"
84reference = "https://attack.mitre.org/techniques/T1059/001/"
85
86
87
88[rule.threat.tactic]
89id = "TA0002"
90name = "Execution"
91reference = "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 PowerShell Obfuscation via Invalid Escape Sequences
PowerShell, a powerful scripting language in Windows environments, can be exploited by adversaries using obfuscation techniques to evade detection. By inserting invalid escape sequences, attackers can obscure malicious scripts, bypassing static analysis and security tools like AMSI. The detection rule identifies such obfuscation by analyzing script patterns, specifically targeting unusual backtick usage, to flag potential threats.
Possible investigation steps
- Review the
powershell.file.script_block_text
field to understand the context and content of the script block that triggered the alert. Look for patterns of invalid escape sequences and assess whether they appear intentionally obfuscated. - Examine the
file.name
andfile.path
fields to determine the origin and location of the script. This can help identify whether the script is part of a legitimate application or potentially malicious. - Check the
host.name
andagent.id
fields to identify the affected system and the agent responsible for logging the event. This information is crucial for understanding the scope of the potential threat. - Analyze the
user.id
field to ascertain which user executed the script. This can provide insights into whether the user has a history of executing suspicious scripts or if their account may be compromised. - Investigate the
powershell.file.script_block_id
andpowershell.sequence
fields to trace the execution sequence and correlate it with other related script blocks, which may reveal additional obfuscation or malicious activity. - Assess the
count
field to evaluate the extent of obfuscation detected. A higher count may indicate more aggressive obfuscation techniques, warranting further scrutiny.
False positive analysis
- Scripts from Visual Studio Code's PowerShell extension may trigger false positives due to its shell integration. To handle this, exclude scripts containing the pattern "$([char]0x1b)]633" from detection.
- PowerShell modules with names starting with "TSS_" may be flagged incorrectly. Exclude these by adding a condition to ignore files matching the pattern "TSS_*.psm1".
- Legitimate scripts that use backticks for formatting or other non-obfuscation purposes might be detected. Review such scripts and, if verified as safe, add them to an exception list based on their script block ID or file path.
- Regularly update the exclusion list to reflect changes in legitimate script usage patterns, ensuring that new false positives are addressed promptly.
Response and remediation
-
Isolate the affected host immediately to prevent lateral movement and further execution of potentially malicious scripts. Disconnect the host from the network and disable remote access.
-
Analyze the script block text and file path to identify the source and nature of the obfuscated script. Determine if the script is part of a larger attack or if other systems are affected.
-
Remove or quarantine the identified malicious script and any associated files from the host. Ensure that all remnants of the obfuscated code are eliminated to prevent re-execution.
-
Conduct a thorough scan of the host using updated antivirus and antimalware tools to detect and remove any additional threats or indicators of compromise.
-
Review and update PowerShell execution policies and security settings to restrict the execution of scripts with invalid escape sequences. Implement stricter controls to prevent similar obfuscation techniques.
-
Escalate the incident to the security operations center (SOC) or relevant cybersecurity team for further investigation and monitoring. Provide detailed logs and findings to assist in understanding the scope and impact of the threat.
-
Implement enhanced logging and monitoring for PowerShell activities across the network to detect and respond to similar obfuscation attempts promptly. Use the identified patterns to refine detection capabilities.
Related rules
- Dynamic IEX Reconstruction via Method String Access
- Potential Dynamic IEX Reconstruction via Environment Variables
- Potential PowerShell Obfuscation via High Numeric Character Proportion
- Potential PowerShell Obfuscation via Reverse Keywords
- Potential PowerShell Obfuscation via String Reordering