PL EN
WB-914027BCTLP:CLEARWazuh 4

PowerShell 4104 in Wazuh: script block logging, channel and custom rules

Event 4104 in Wazuh: enabling Script Block Logging, the PowerShell/Operational channel, built-in rules 91801-91846, win.* fields and a custom pcre2 child rule.

Event 4104 carries the content of PowerShell script blocks, so it is one of the richest detection sources on a Windows workstation. For it to raise an alert in Wazuh, four things must line up: logging enabled on Windows, the channel collected by the agent, the field names in the rule, and the way the text is compared.

What event 4104 is

According to Microsoft Learn (about_Logging for Windows PowerShell 5.1), enabled Script Block Logging records the content of all script blocks processed by PowerShell, and every new session logs them once the option is on. The event goes to the Microsoft-Windows-PowerShell/Operational channel with the parameters from the table.

ParameterValue
EventId4104 / 0x1008
ChannelOperational
LevelVerbose
OpcodeCreate
TaskCommandStart
KeywordRunspace

The same documentation warns that with script logging enabled, the log may contain credentials and other sensitive data used in the script. For uses other than diagnostics, Microsoft recommends Protected Event Logging, which encrypts entries with a public key (CMS standard). The private key should not end up on the machines that log the events. Decryption on the collector is shown in an example from the documentation:

Get-WinEvent Microsoft-Windows-PowerShell/Operational |
    Where-Object Id -EQ 4104 | Unprotect-CmsMessage

The Wazuh documentation does not describe how Protected Event Logging works with the agent, so before you enable this option, check in a lab what form the scriptBlockText field has when it reaches the rules.

Enabling logging on Windows

For Windows PowerShell 5.1 the documentation gives two routes: Group Policy and the registry. The policy is named “Turn on PowerShell Script Block Logging” and sits in Administrative Templates, Windows Components, Windows PowerShell. The registry variant from the documentation sets the EnableScriptBlockLogging value to “1”:

function Enable-PSScriptBlockLogging {
    $basePath = @(
        'HKLM:\Software\Policies\Microsoft\Windows'
        'PowerShell\ScriptBlockLogging'
    ) -join '\'

    if (-not (Test-Path $basePath)) {
        $null = New-Item $basePath -Force
    }

    Set-ItemProperty $basePath -Name EnableScriptBlockLogging -Value "1"
}

A separate option, Script Block Invocation Logging, additionally logs the start and end of a command, block, function or script invocation. The Microsoft documentation notes that it generates a large volume of events, so it is not needed for detection based on the 4104 content alone.

PowerShell 7 has its own PowerShellCore log and PowerShellCore/Operational channel, the key HKLM:\Software\Policies\Microsoft\PowerShellCore\ScriptBlockLogging and its own policy in the “PowerShell Core” branch. The event ID stays 4104. The built-in Wazuh rules compare the channel only with Microsoft-Windows-PowerShell/Operational (details below), so for PowerShell 7 you need to check separately which channel the agent actually sees.

Collecting the channel in Wazuh

The Wazuh documentation states that the channels monitored by default are System, Security and Application. You have to add the PowerShell channel with a localfile block in the agent’s ossec.conf (on Windows C:\Program Files (x86)\ossec-agent\ossec.conf), inside the ossec_config tags:

<localfile>
  <location>Microsoft-Windows-PowerShell/Operational</location>
  <log_format>eventchannel</log_format>
</localfile>

After the change, restart the agent from an elevated PowerShell with Restart-Service -Name wazuh. The elements of the block:

ElementMeaning according to the documentation
locationName of the event channel the agent reads
log_formateventchannel: Windows channels since Vista, with fields in JSON format
queryOptional XPath filter narrowing the channel’s events

The query filter makes sense when the channel is noisy. The documentation example for the System channel uses the syntax Event/System[EventID=7040]. For 4104 the analogous narrowing would be Event/System[EventID=4104], but that is a recommendation assembled from the documentation’s syntax, not an example from it. With such a filter the rules will not see other events from the channel. The XPath syntax is covered in the post EventChannel filtering in Wazuh.

Fields after decoding

An event from the eventchannel format is decoded as windows_eventchannel, and its fields go into the win.system.* hierarchy (system fields, for example channel, providerName, eventID, message) and win.eventdata.* (event-specific fields). For 4104 the built-in rules use three fields: win.system.channel, win.eventdata.ScriptBlockId and win.eventdata.scriptBlockText, and in one case win.system.message.

In the same rules file one field starts with a capital letter (ScriptBlockId) and the other with a lowercase one (scriptBlockText). The Wazuh documentation does not say whether the name in the name attribute of the field element is case sensitive. Copy the names exactly from the built-in file or from a real event, never from memory.

The fragment below illustrates the field layout, it is not a record of a real event:

{
  "win": {
    "system": {
      "channel": "Microsoft-Windows-PowerShell/Operational",
      "eventID": "4104",
      "providerName": "Microsoft-Windows-PowerShell"
    },
    "eventdata": {
      "ScriptBlockId": "example-id",
      "scriptBlockText": "Write-Output 'example'"
    }
  }
}

The general model of win.* fields and an example rule for another channel are in the post Sysmon in Wazuh.

Built-in rules 91801-91846

The PowerShell rules live in the file 0915-win-powershell_rules.xml (ID range 91801 - 92000, 45 rules in version 4.14.0). The first two are level 0 groups and form the parent chain.

RuleLevelCondition
600000decoded_as windows_eventchannel and non-empty win.system.providerName
918010if_sid 60000, 60010 and win.system.channel equal to ^Microsoft-Windows-PowerShell/Operational$
918020if_sid 91801 and non-empty win.eventdata.ScriptBlockId (pcre2)

All child rules of 91802 check win.eventdata.scriptBlockText with type="pcre2" and the (?i) prefix, and rule 91803 stands out by using the win.system.message field. The file has no condition on win.system.eventID: the parent 91802 relies on the presence of ScriptBlockId. Selected rules:

RuleLevelMatch and description
9180314CopyFromScreen text in win.system.message: screen capture
918053Get-ADComputer
9180910FromBase64String: possible Base64 decoding
9181010CreateThread: suspicious code execution through an API
9182212Invoke-Command used to run a sub-script
9182314Child of 91822: ComputerName or Cn, meaning code on a remote computer
9184412Registry path CurrentVersion\Run: possible autostart entry
9184510Microsoft.Office.Interop.Outlook
9184610::CreateFromDirectory: .NET compression

The structure is multi-level. Rule 91807 (Get-ItemProperty) has level 0, and only its child 91808 (an HKCU or HKLM path) generates a level 3 alert. Likewise 91812 is a group and 91813 raises the alert. When reviewing coverage, read the if_sid chains, not just the list of IDs.

A rule’s level is not a measure of confidence. Rule 91837 (level 4) catches IEX, among others, and its pattern contains the spelling Invoke-Expresion, so a typo in a built-in pattern is one more reason to test your own patterns on events. The patterns are textual: a hit proves that the string appeared in the block, not that the command ran successfully. How to set levels and thresholds is described in the post Rule levels and thresholds in Wazuh.

Letter case on three levels

A mismatch in how a name is written can disable a rule without any message: it loads, logs arrive, and there is no alert. This applies to three independent places.

Block content. The documentation says it outright: PCRE2 is case sensitive by default, and (?i) turns on case-insensitive matching. Example from the documentation: the string post matches (?i)POST|GET|PUT, but not POST|GET|PUT. PowerShell is case insensitive for command names, so invoke-command, Invoke-Command and INVOKE-COMMAND are the same command.

Channel value. Rule 91801 compares win.system.channel with the expression ^Microsoft-Windows-PowerShell/Operational$. For the field element the default type is osregex. The documentation describes the OS_Regex limitations (no alternation inside a group, \s only for the ASCII space, the ^ and $ anchors), but does not say whether this matching is case sensitive. So copy the channel name from a real event, and when in doubt use type="pcre2" with an explicit (?i).

Field name. Described above: the file contains ScriptBlockId and scriptBlockText, and the documentation does not settle whether the letter case in name matters.

A custom child rule

The documentation recommends IDs from 100000 to 120000 for custom rules, small changes in /var/ossec/etc/rules/local_rules.xml, and larger sets in separate files in /var/ossec/etc/rules/. The rule below is a child of 91802 and requires both the event ID and a pattern in the block content. Multiple field elements in one rule combine as a logical AND.

<group name="windows,powershell,">
  <rule id="100100" level="10">
    <if_sid>91802</if_sid>
    <field name="win.system.eventID">^4104$</field>
    <field name="win.eventdata.scriptBlockText" type="pcre2">(?i)DownloadString\(</field>
    <options>no_full_log</options>
    <description>PowerShell: script block calls DownloadString</description>
  </rule>
</group>

The 0915 file in version 4.14.0 has no DownloadString pattern, so the rule does not duplicate a built-in one. The ^4104$ notation in win.system.eventID matches the style of the Windows Security rules from 0580-win-security_rules.xml, which compares win.system.eventID with expressions like ^4625$. If a pattern must contain a literal < or > character, the Wazuh XML parser does not decode entities, so in PCRE2 you write them as \x3C and \x3E. The built-in patterns in the 0915 file write the backslash in registry paths four times (\\\\), so when writing rules for paths, copy this exactly.

For custom rules keep the same principles as in the built-in ones: one rule per scenario, a pattern with (?i), a description in the form <Technology>: what happened. Changes in files from the /var/ossec/ruleset/rules directory are overwritten during an upgrade, so keep custom rules in /var/ossec/etc/rules/.

Testing

The /var/ossec/bin/wazuh-logtest tool uses the same rules as the analysis engine, works in sessions and counts firedtimes. In a cluster the master processes the events. For a test it is enough to save the rules file, but for the rule to generate alerts you have to restart the manager (systemctl restart wazuh-manager).

The documentation shows logtest only with syslog examples. The API specification for PUT /logtest lists eventchannel among the allowed log_format values (next to syslog, json, eventlog and others), and the location field is required. There is, however, no description of how to correctly submit an EventChannel event in JSON format, nor a guarantee that the result matches production. A proposed procedure, not a documentation requirement:

  1. Save the rule and check that the manager loads it without errors.
  2. In the lab, generate a 4104 event with a harmless pattern, for example a one-line script containing the string you look for.
  3. Compare the alert with the rule: ID, level and the win.eventdata fields.
  4. Repeat with a changed letter case of the command and with an event that does not contain the pattern.

The general session-based test scheme is described in the post Testing rules and decoders with wazuh-logtest, and custom decoders in the post Custom Wazuh decoders.

What the documentation does not specify

  • Whether letter case in the name of the field element matters, and whether the default osregex matching is case sensitive.
  • How to feed an EventChannel event into the wazuh-logtest CLI, and whether decoding in logtest is complete for win.* fields.
  • The form of the block content after enabling Protected Event Logging and how it works with the Wazuh agent.
  • The impact of collecting 4104 on agent and manager performance, and which of several matching child rules of 91802 wins for a single event.

Sources

↑↓ select Enter open Esc close