from logs-windows.powershell_operational* metadata _id, _version, _index
| where event.code == "4104"
// replace repeated spaces used for formatting after a new line with a single space to reduce FPs
| eval Esql.script_block_tmp = replace(powershell.file.script_block_text, """\n\s+""", "\n ")
// Look for scripts with more than 1000 chars
| eval Esql.script_block_length = length(Esql.script_block_tmp)
| where Esql.script_block_length > 1000
// replace the patterns we are looking for with the 🔥 emoji to enable counting them
// The emoji is used because it's unlikely to appear in scripts and has a consistent character length of 1
| eval Esql.script_block_tmp = replace(
Esql.script_block_tmp,
"""[\s\$\{\}\+\@\=\(\)\^\\\"~\[\]\?\.]""",
"🔥"
)
// count how many patterns were detected by calculating the number of 🔥 characters inserted
| eval Esql.script_block_count = Esql.script_block_length - length(replace(Esql.script_block_tmp, "🔥", ""))
// Calculate the ratio of special characters to total length
| eval Esql.script_block_ratio = Esql.script_block_count::double / Esql.script_block_length::double
// keep the fields relevant to the query, although this is not needed as the alert is populated using _id
| keep
Esql.script_block_count,
Esql.script_block_length,
Esql.script_block_ratio,
Esql.script_block_tmp,
powershell.file.script_block_text,
powershell.file.script_block_id,
file.path,
powershell.sequence,
powershell.total,
_id,
_index,
host.name,
agent.id,
user.id
// Filter for scripts with high whitespace and special character ratio
| where Esql.script_block_ratio > 0.75
Install detection rules in Elastic Security
Detect Potential PowerShell Obfuscation via Special Character Overuse in the Elastic Security detection engine by installing this rule into your Elastic Stack.
To setup this rule, check out the installation guide for Prebuilt Security Detection Rules(opens in a new tab or window).