Query Details
//Finds encoded PowerShell commands and then decodes the encoded string
//Data connector required for this query - M365 Defender - Device* tables
//Query modified from this post - https://techcommunity.microsoft.com/t5/microsoft-sentinel/finding-base64-encoded-commands/m-p/1891876
DeviceProcessEvents
| where ProcessCommandLine contains "powershell" or InitiatingProcessCommandLine contains "powershell"
| where ProcessCommandLine contains "-enc"
or ProcessCommandLine contains "-encodedcommand"
or InitiatingProcessCommandLine contains "-enc"
or InitiatingProcessCommandLine contains "-encodedcommand"
//Extract encoded command using regex
//This query will only return results when the command can be matched via regex and decoded, if you run only the above lines it will return all encoded commands without attempting to match and decode
| extend EncodedCommand = extract(@'\s+([A-Za-z0-9+/]{20}\S+$)', 1, ProcessCommandLine)
| where EncodedCommand != ""
| extend DecodedCommand = base64_decode_tostring(EncodedCommand)
| where DecodedCommand != ""
| project
TimeGenerated,
DeviceName,
InitiatingProcessAccountName,
InitiatingProcessCommandLine,
ProcessCommandLine,
EncodedCommand,
DecodedCommandThis query searches for encoded PowerShell commands and decodes them. It uses the M365 Defender - Device* tables as the data source. The query looks for processes with "powershell" in the command line or initiating process command line. It also checks for specific flags like "-enc" or "-encodedcommand" in the command lines. The query then extracts the encoded command using regular expressions and decodes it using base64_decode_tostring function. Finally, it projects several fields including the time generated, device name, initiating process account name, command lines, encoded command, and decoded command.

Matt Zorich
Released: June 17, 2022
Tables
Keywords
Operators