In the modern threat landscape, attackers frequently leverage PowerShell as a primary weapon for initial access, lateral movement, and data exfiltration. Because PowerShell is often enabled by default on Windows endpoints and can bypass traditional signature-based antivirus solutions, relying solely on standard logging is insufficient. This guide provides a practical, step-by-step exercise for IT students and junior engineers to write custom Sigma rules that detect suspicious PowerShell execution patterns in a production environment. By mastering this process, defenders can significantly reduce their dwell time and improve incident response capabilities.
Understanding the Threat Vector and Sigma Architecture
Before writing code, it is essential to understand why standard detection fails. Attackers often use obfuscated scripts, encoded commands, or legitimate administrative tools (like PowerShell.exe invoked by System) to mask malicious activity. Sigma rules offer a vendor-agnostic way to define these patterns using structured JSON. A typical Sigma rule consists of four key fields: the title, description, status, and the core detection logic within the detection section.
To begin this exercise, you must ensure your environment is set up correctly. You will need access to a Windows machine with PowerShell logging enabled (Event ID 4104) or an endpoint detection and response (EDR) agent that exports logs in a standard format like EQL or JSON. If you are working in an authorized lab, verify that your security team has granted permission to modify detection logic. Important: Never apply untested Sigma rules directly to a live production environment without a period of observation in a staging zone first.
Step 1: Analyzing Sample Malicious Logs
The foundation of any good threat hunt is high-quality data. Start by capturing logs from a known malicious activity or a simulated attack using a safe tool like Atomic Red Team. For example, an attacker might execute a command to download and run a payload: powershell -enc UEsDBAoAAAAAA....
In this scenario, the PowerShell process will generate Event ID 4104 in the Windows Security log. The log entry will include the full command line string. Open your preferred log viewer (such as Splunk, ELK Stack, or Microsoft Sentinel) and query for recent PowerShell executions. Look specifically for:
* Commands starting with -enc (base64 encoded strings).
* Commands using -encodedcommand.
* Processes spawned by powershell.exe rather than cmd.exe or other interpreters.
* The presence of <unknown> in the command line, which often indicates a dropped file or a specific evasion technique.
Save these log entries as your “ground truth.” These samples will serve as the input for your Sigma rule generation.
Step 2: Drafting the Initial Detection Logic
Now that you have identified the patterns, translate them into Sigma syntax. Open a text editor and create a new JSON file named suspicious_powershell_execution.yml. The following is an illustrative example of how to construct a rule for detecting encoded commands:
title: 'Suspicious PowerShell Encoded Command Execution'
status: 'experimental'
description: 'Detects the use of -enc or -encodedcommand flags in PowerShell, commonly used by malware.'
logsource:
category: 'process_creation'
product: 'windows'
service: 'security'
id: 4104
detection:
selection:
command_line|contains: '-enc'
command_line|contains: '-encodedcommand'
filter:
# Exclude common legitimate uses to reduce noise, though this is a starting point
command_line|not_contains: '-ep bypass'
command_line|not_contains: '-window hidden'
false positives:
- 'Office365 Outlook.exe'
- 'PowerShell.exe (System)'
level: 'high'
tags:
- 'attack.t1059' # Execution
- 'mitre_ps_execution'
In this example, the selection block defines what triggers an alert. The filter block attempts to reduce false positives by excluding common benign arguments, though this is often a trade-off between sensitivity and noise. The false positives section lists known safe processes that might trigger the rule if not handled correctly in your specific EDR configuration.
Step 3: Testing and Refining the Rule
Writing the rule is only half the battle; verification is critical. Before deploying, test your rule against your lab logs. If you are using Microsoft Sentinel or similar platforms, upload the JSON file to the “Sigma Rules” section. Run a query to see if it matches the known malicious samples from Step 1.
Expected Output:
When successful, the system should return an alert for the specific log entries containing -enc. It should ideally not return alerts for standard administrative scripts unless those scripts are also encoded (which is rare for legitimate admin work).
If you see too many false positives, refine the filter or false positives sections. For instance, if legitimate IT staff frequently use -ep bypass, you may need to exclude that specific flag combination in your rule logic. Remember that Sigma rules are static; they do not learn automatically. You must manually update them as new evasion techniques emerge.
Step 4: Deployment and Production Considerations
Once the rule is validated in a lab, create a copy for the production environment. Crucial Safety Step: Do not enable the rule globally immediately. Apply it to a small subset of endpoints or a specific group (e.g., “Test Group”). Monitor the alert volume for 24–48 hours. If the alert rate is unmanageable, tune the rule further before rolling it out to the entire organization.
During this phase, document any legitimate use cases that trigger false positives. Common errors during deployment include:
* Version Mismatch: Sigma syntax can vary slightly between EDR versions (e.g., Splunk vs. Microsoft Defender for Endpoint). Ensure your JSON is compatible with your specific platform.
* Field Name Errors: Different EDRs name log fields differently (e.g., CommandLine vs command_line). Verify the field names in the rule match your actual log schema exactly.
* Encoding Issues: Ensure the JSON file is saved with UTF-8 encoding to prevent parsing errors when uploading.
Step 5: Incident Response Integration
A detection is useless without a response plan. When this Sigma rule triggers, what happens? Define your workflow immediately.
1. Alert Triage: The security operations center (SOC) receives the alert.
2. Enrichment: Use the EDR interface to inspect the process tree and network connections associated with the PowerShell execution.
3. Containment: If confirmed malicious, isolate the endpoint and kill the process.
4. Hunting: Search for other indicators of compromise (IOCs) on that host and across the network.
Student Practice Task and Industry Application
Student Practice Task:
In your authorized lab environment, simulate an attack using Atomic Red Team technique T1059.001 (PowerShell with encoded command). Extract the Event ID 4104 log entry. Manually write a Sigma rule that detects only this specific pattern without relying on pre-built templates. Test it against both clean and malicious logs. Document your findings in a report.
Industry Application:
For experienced practitioners, this exercise translates to hardening an organization’s detection posture. By customizing Sigma rules, teams can move beyond generic alerts provided by vendors. This proactive approach allows for the detection of novel threats that haven’t yet been added to vendor threat intelligence feeds. However, always consult authoritative sources like MITRE ATT&CK for the latest tactics and techniques, and verify policy terms with your insurer or legal counsel before making significant changes to production security controls.
Conclusion
Writing custom Sigma rules for PowerShell execution is a vital skill for defensive security professionals. It bridges the gap between raw log data and actionable intelligence. By following these steps—analyzing logs, drafting logic, testing rigorously, and deploying cautiously—you can build a resilient detection capability that adapts to evolving threats. Remember that security is an iterative process; rules must be reviewed and updated regularly as attacker techniques change.
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.

