Home NewsX Monitoring PowerShell through Azure Monitor Agent (AMA) and Microsoft Sentinel

Monitoring PowerShell through Azure Monitor Agent (AMA) and Microsoft Sentinel

by info.odysseyx@gmail.com
0 comment 16 views


This is part 2 of a blog series on how to collect events using DCR for advanced use cases. For part 1, see: The Power of Data Collection Rules: Event Collection for Advanced Use Cases in Microsoft USOP – Mic….

PowerShell is a useful tool for administrators to manage devices and servers in their environment. When you use PSRemoting to manage remote systems, you do not leave credentials on the target system. This is in contrast to RDP, where credentials are stored in the Local Security Authority (LSA). This provides many security benefits. Prevent Pass-The-Hash attacks and other credential theft scenarios

Because it is a pre-installed tool, adversaries are known to use PowerShell to attack organizations. Companies that set up robust PowerShell configuration and monitoring have a clear advantage over these adversaries! PowerShell’s numerous built-in security and monitoring features make it easy to detect and disrupt adversaries.

In this article Let’s look at how to set up your own monitoring mechanism using Microsoft Sentinel and the Unified SecOps Platform to detect PowerShell code running in your environment.. We will not discuss the various security features that can be configured for a robust PowerShell environment. As mentioned in the first article, a good resource for learning more about PowerShell security is “PowerShell Automation and Scripting for Cybersecurity: Hacking and defense for red and blue teamers” by Miriam C. Wiesner. https://aka.ms/mw-book.

Step 1: Configure ScriptBlockLogging

In PowerShell, you can think of a script block as a collection of commands and expressions that are run together as a single command—a “script block.”

Many companies only realize the importance of logging after an incident occurs. At that point, they cannot detect what happened. That’s why the PowerShell team decided to implement basic script block logging starting with PowerShell 5. This can be useful for tracking malicious activity that was performed before an incident.

The default script block logging feature captures only some basic security-related script blocks by default if not configured otherwise. This can provide insight into basic malicious activity executed on a computer in the event of a security incident, but it also means that not all activities are captured in this default configuration. Therefore, to track all activities on business-critical servers and high-value assets, you should configure script block logging before you start collecting and reviewing all relevant events.

You can do this using Group Policy. Depending on the version of PowerShell you want to configure script block logging for, navigate to the following GPO path:

  • Windows PowerShell: Computer Configuration > Policies > Administrative Templates > Windows Components > Windows PowerShell > Turn on PowerShell Script Block Logging
  • PowerShell Core: Computer Configuration > Administrative Templates > PowerShell Core > Turn on PowerShell Script Block Logging

Configure this setting to “.Activated” and click “OK”.great“. do ~ No Check the box “Log script block call start/stop events”. This setting is verbose and generates a lot of noise.

Miriam Wisner_7-1725448039477.png

Miriam Wisner_8-1725448039488.png

Miriam Wisner_9-1725448039502.png

Miriam Wisner_10-1725448039514.png

If you use both versions of PowerShell in your environment, we recommend configuring and monitoring both.

In the PowerShell Core policy, you will find the option “Use Windows PowerShell policy settings.” Unless you have a use case that requires different configurations for the two versions, you can enable this option to synchronize your Windows PowerShell script block settings.

Before you can use the PowerShell Core Administrative Template files (*.admx), you may need to obtain them first. This article explains how to locate and install these files. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_group_poli…

Step 2: Detect and review the executed PowerShell code

Now that we have everything configured, it’s time to collect PowerShell script block logging events and examine the code that was executed. The following script searches for and filters event ID 4104 in Windows PowerShell and PowerShell Core (excluding specific paths and user IDs), then formats and displays the filtered event details.

$PSWinEventLog = @{ ProviderName = "Microsoft-Windows-PowerShell"; Id = 4104 }

$PSCoreEventLog = @{ ProviderName = "PowerShellCore"; Id = 4104 }

$PSWinEventLog, $PSCoreEventLog | ForEach-Object {
    try {
        Get-WinEvent -FilterHashtable $_ | Where-Object  {
            !($_.Properties[4].Value -Match "C:\\ProgramData\\Microsoft\\Windows Defender Advanced Threat Protection\\DataCollection\\") `
            -and ($_.Properties[2].Value -ne "prompt") `
            -and ($_.UserId -ne "S-1-5-18") `
            -and ($_.UserId -ne "S-1-5-19") `
            -and !( $_.Properties[4].Value -Match ".vscode\\extensions\\") `
            -and !($_.Properties[4].Value -Match "C:\\Windows\\TEMP\\SDIAG_([A-Za-z0-9]+(-[A-Za-z0-9]+)+)\\CL_Utility\.ps1")
        } | Select-Object TimeCreated, `
            @{Name="ExecutedCode";Expression={ $_.Properties[2].Value }},`
            UserId, `
            LevelDisplayName, `
            @{Name="Path";Expression={$_.Properties[4].Value}}, `
            ProviderName, `
            @{Name="ScriptblockId";Expression={$_.Properties[3].Value}},`
            @{Name="CurrentPart";Expression={$_.Properties[0].Value}},`
            @{Name="TotalParts";Expression={$_.Properties[1].Value}}`
        | fl
    }
    catch {}

If the executed script block is too large, the PowerShell script block event may be split into multiple events. In this case, the “CurrentPart” field indicates this by containing a value greater than 1. The “CurrentPart” field indicates the order of the script block fragments.

You may want to tailor this query to your environment. Are there any script blocks that run on specific programs in your environment that you can safely exclude from review? You can use the following article as a reference for filtering. Creating a Get-WinEvent Query Using FilterHashtable – PowerShell | Microsoft Learn.

PowerShell is a useful tool for administrators to manage devices and servers in their environment. When used to manage remotely,

If the executed script block is too large, a PowerShell script block event may be split into multiple events. In this case, the “CurrentPart” field indicates this by containing a value greater than 1. The “CurrentPart” field indicates the order of the script block fragments.

You may want to tailor this query to your environment. Are there any script blocks that run on specific programs in your environment that you can safely exclude from review? You can use the following article as a reference for filtering. Creating a Get-WinEvent Query Using FilterHashtable – PowerShell | Microsoft Learn.

Step 3: Configure Data Collection Rules (DCR) to collect the required events.

Azure Monitor Agent (AMA) allows you to select the events you want to collect from your servers using Xpath queries (see: Filter Windows Events Using Xpath Queries For reference). If you are unfamiliar with the agent or have not yet installed AMA on the server you wish to monitor, check out the first article in this series: link included.

To create a DCR, this time we are collecting non-security events, so go to Connectors and select Windows Forwarded Events. From there, select Create DCR, add the server, and then select Custom under Collection. Paste in the following xPath query:

For Windows PowerShell:

Microsoft-Windows-PowerShell/Operational!*[System[(EventID=4104)]]

For PowerShell Core:

PowerShellCore/Operational!*[System[(EventID=4104)]]

Miriam Wisner_11-1725448039517.png

If you do not want to receive events that you do not need (such as events from background processes or system accounts) based on the query you configured in step 2, you can create a transformation in DCR to prevent those events from being collected in Microsoft Sentinel. This is because the events may be too detailed to be of interest. To do this, you can add this transformation to DCR.

"transformKql": "source | where SystemUserId !in ('S-1-5-18', 'S-1-5-19') | extend ScriptBlockText =  parse_json(EventData).ScriptBlockText, ScriptBlockId = tostring(EventData.ScriptBlockId), MessageNumber = tostring(EventData.MessageNumber), MessageTotal = tostring(EventData.MessageTotal), Path = tostring(EventData.Path) | where tostring(ScriptBlockText) != 'prompt' | where Path != '.vscode\\\\extensions\\\\' and Path != 'C:\\\\Windows\\\\TEMP\\\\SDIAG_([A-Za-z0-9]+(-[A-Za-z0-9]+)+)\\\\CL_Utility.ps1' and Path != 'C:\\\\ProgramData\\\\Microsoft\\\\Windows Defender Advanced Threat Protection\\\\DataCollection\\\\'"

Alternatively, you can deploy this template from GitHub, which already includes the xPath queries and transformations described above. Azure-Sentinel/DataConnectors/WindowsEvents/DataCollectionRulePowerShellEvents at master · Azure/Azu…

Step 4: Create a Detection

You can now move to the Unified Security Operations Platform, which integrates Microsoft Sentinel or Microsoft Sentinel and Microsoft Defender XDR into a single, unified portal (see how). Connect Microsoft Sentinel to Microsoft Defender XDR) queries the logs and generates detection results.

It also makes sense to monitor devices that have never run PowerShell code before. These devices are unexpectedly running PowerShell code. Are there devices that should not run PowerShell code (e.g., devices in accounting or marketing)? For this purpose, you can use: Watchlist. A watchlist allows you to create a list of items to use for correlation (e.g., high-value assets, terminated employees, service accounts, etc.). In our scenario, we created a watchlist that determined which team the machine belongs to (Operations, Security, Marketing).

First, let’s take a look at the logs. You can find them under Advanced Hunting in Microsoft Defender XDR. Using this query, we detect machines that are not part of the groups (Security and Operations) that we expect to run PowerShell code.

let AllowedGroups = dynamic(["Security","Operations"]);
WindowsEvent
| where EventID == 4104
| extend ScriptBlockText =  parse_json(EventData).ScriptBlockText, ScriptBlockId = tostring(EventData.ScriptBlockId), MessageNumber = tostring(EventData.MessageNumber), MessageTotal = tostring(EventData.MessageTotal), Path = tostring(EventData.Path)
| lookup kind=inner _GetWatchlist('devicegroups') on $left.Computer == $right.SearchKey
| where Group !in (AllowedGroups)
| project TimeGenerated, ScriptBlockText, SystemUserId, DeviceName, Group, EventLevelName, Path, MessageNumber, MessageTotal, ScriptBlockId, Channel
| sort by TimeGenerated, ScriptBlockId, MessageNumber

Miriam Wisner_12-1725448039526.png

Above, you can see that we ran the PowerShell code on a computer that was not the expected department.

After refining your watchlist and queries, you’re ready to create detections in Analytics.

Miriam Wisner_13-1725448039535.png

When creating an analytics rule, don’t forget to match the host entity in “Entity Mapping”. This is important for correlation between data sources and alerts.

This is the end Part 2 Our 3-part blog series We will cover how to collect events using DCR for advanced use cases. For Part 1, see: The Power of Data Collection Rules: Event Collection for Advanced Use Cases in Microsoft USOP – Mic… In Part 3, we’ll show you how to monitor signs that Defender for Endpoint (MDE) has been shut down.

We welcome your feedback and questions about this or any other part of this blog article series, and look forward to hearing from you.

Miriam Wiesner (@miriamxyra) – Principal Security Research PM, Microsoft Defender XDR | Maria de Sousa-Valadas Castaño – Principal Product Manager, Unified SocOps Platform | Shirley Kochavi – Unified SocOps Platform





Source link

You may also like

Leave a Comment

Our Company

Welcome to OdysseyX, your one-stop destination for the latest news and opportunities across various domains.

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

Laest News

@2024 – All Right Reserved. Designed and Developed by OdysseyX