Bert-JanP / Hunting-Queries-Detection-Rules

KQL Queries. Defender For Endpoint and Azure Sentinel Hunting and Detection Queries in KQL. Out of the box KQL queries for: Advanced Hunting, Custom Detection, Analytics Rules & Hunting Rules.
https://kqlquery.com
BSD 3-Clause "New" or "Revised" License
1.1k stars 202 forks source link

custom rules fails to decode base64 encoded string #14

Closed mezzofix closed 11 months ago

mezzofix commented 11 months ago

Hi,

The detection https://github.com/Bert-JanP/Hunting-Queries-Detection-Rules/blob/main/Threat%20Hunting%20Cases/Suspicious%20Encoded%20Powershell.md is working however when tested with Red the base64_decode_tostring function fails to decode the base64 encoded string every time:

image

Here's the base64 string: VwByAGkAdABlAC0ASABvAHMAdAAgACIASABlAHkALAAgAEEAdABvAG0AaQBjACEAIgA=

As you can see decoding with base64 -d works just fine

image

Thanks !

Bert-JanP commented 11 months ago

Hi,

If you take a look at the decoded commandline it is successfully decoded. However, between each char a null value has been identified. The query below shows this in Unicode.

let x = "VwByAGkAdABlAC0ASABvAHMAdAAgACIASABlAHkALAAgAEEAdABvAG0AaQBjACEAIgA=";
let y = base64_decode_tostring(x);
let z = unicode_codepoints_from_string(y);
print z

The fix you can use is:

let x = "VwByAGkAdABlAC0ASABvAHMAdAAgACIASABlAHkALAAgAEEAdABvAG0AaQBjACEAIgA=";
let y = base64_decode_tostring(x);
let z = replace_string(y, '\0', '');
print z
Bert-JanP commented 11 months ago

Furthermore the string that you encode has null values, therefore the base64_decode_tostring() works as expected.

Without null values the encoded string would look like: V3JpdGUtSG9zdCAiSGV5LCBBdG9taWMhIg== instead of "VwByAGkAdABlAC0ASABvAHMAdAAgACIASABlAHkALAAgAEEAdABvAG0AaQBjACEAIgA="

mezzofix commented 11 months ago

Thanks for looking into this. But what’s unusual in an encoded PowerShell command if there are spaces ? Isn’t then a problem with the KQL function?