Detecting Base64 Code In Commands
Query
DeviceFileEvents
| extend CommandWords = split(InitiatingProcessCommandLine, " ") // Split the command into words
| extend Word1 = CommandWords[0], // First word
Word2 = CommandWords[1], // Second word
Word3 = CommandWords[2], // Third word
Word4 = CommandWords[3], // Fourth word
Word5 = CommandWords[4]
| extend LongestWord = case(
strlen(Word1) >= strlen(Word2) and strlen(Word1) >= strlen(Word3) and strlen(Word1) >= strlen(Word4) and strlen(Word1) >= strlen(Word5), Word1,
strlen(Word2) >= strlen(Word1) and strlen(Word2) >= strlen(Word3) and strlen(Word2) >= strlen(Word4) and strlen(Word2) >= strlen(Word5), Word2,
strlen(Word3) >= strlen(Word1) and strlen(Word3) >= strlen(Word2) and strlen(Word3) >= strlen(Word4) and strlen(Word3) >= strlen(Word5), Word3,
strlen(Word4) >= strlen(Word1) and strlen(Word4) >= strlen(Word2) and strlen(Word4) >= strlen(Word3) and strlen(Word4) >= strlen(Word5), Word4,
Word5 // Default case if Column5 is the longest
)
| extend tostring(LongestWord)
| extend DecodedBytes = base64_decode_tostring(LongestWord)
| extend DecodedString = tostring(DecodedBytes)
| where isnotempty(DecodedString)
| distinct DeviceName,InitiatingProcessCommandLine,LongestWord,DecodedStringAbout this query
MITRE ATT&CK Technique(s)
| Technique ID | Title |
|---|---|
| T1027 | Obfuscated Files or Information |
Author: Sergio Albea (14/01/2025)
Detecting Base64 Code in Commands
This KQL Query is oriented to detect strings added into executed command lines which are base64coded. After it, it decoded the corresponding string and show the results decoded.
Explanation
This KQL query is designed to identify and decode Base64-encoded strings found in command lines executed on devices. Here's a simple breakdown of what the query does:
-
Data Source: It starts by examining events related to file operations on devices (
DeviceFileEvents). -
Command Splitting: The query splits the command line of the initiating process into individual words.
-
Identify Longest Word: It then identifies the longest word from the first five words of the command line. This is based on the assumption that the longest word might be a Base64-encoded string.
-
Base64 Decoding: The longest word is decoded from Base64 format to a readable string.
-
Filter Non-Empty Results: It filters out any results where the decoded string is empty, meaning it only keeps entries where a valid Base64 decoding occurred.
-
Display Results: Finally, it displays distinct results showing the device name, the original command line, the longest word (potentially Base64-encoded), and the decoded string.
This query helps in detecting potential obfuscation techniques where attackers might use Base64 encoding to hide malicious commands.
