Building a Detection Rule From Scratch: A Complete Sigma Walkthrough With Real Examples

Retool's new app builder is where AI-generated code ships safely
Building apps with AI is easy. Getting them to production safely is another story.
Sigma is a generic, vendor-neutral format for writing detection rules that can be converted to query syntax for any SIEM platform. The concept is straightforward: write your detection logic once, convert it anywhere. In practice, new detection engineers hit a wall at the same place: the documentation shows you the YAML syntax, but not how to think through what to actually detect, which fields to use, and how to keep false positives under control.
This guide walks through building a complete, production-quality Sigma rule from scratch for PSExec-style lateral movement detection. We start at the whiteboard question 'what am I trying to detect?' and end with tested, converted rules for Splunk, Elastic, and Microsoft Sentinel.
Start With the Technique, Not the Tool
The first question for any detection rule is not 'what Sigma fields should I use?' It is 'what does this technique actually look like on the wire and in logs?'
For PSExec-style lateral movement (MITRE ATT&CK T1569.002, System Services: Service Execution), the attacker:
- Copies a binary to the target host's ADMIN$ share (the C:\Windows share, accessible over SMB)
- Creates a remote service on the target host using the Windows Service Control Manager (SCM)
- Starts that service, which executes the binary
- Optionally deletes the service and binary after use
Each of these steps leaves traces in different log sources:
| Step | Log Source | Event ID |
|---|---|---|
| Copy binary to ADMIN$ | Windows Security log | 5145 (SMB file access) |
| Create remote service | Windows System log | 7045 (New service installed) |
| Service started by SCM | Windows Security log | 4624 (Type 3 network logon) + 4697 |
| Remote command execution | Sysmon Event ID 1 | Process creation |
For a Sigma rule, we want to find the detection signal that is:
- High specificity (not generated by legitimate tools constantly)
- Available in most environments without special audit configuration
- Hard for attackers to suppress or modify
The best candidate is Windows System Event 7045 (A new service was installed in the system). Legitimate service installation happens infrequently and through known paths. Remote service creation with a random service name, a binary path in a temp directory, and a binary that was just copied over the network is distinctive.
Understanding the Sigma Rule Structure
A Sigma rule is a YAML document with these top-level fields:
title: <human-readable title> id: <UUID> status: <experimental | test | stable> description: <one paragraph of what this detects> references: <list of URLs> author: <your name or handle> date: <YYYY-MM-DD> modified: <YYYY-MM-DD> tags:
- attack.<tactic>
- attack.<technique_id> logsource: category: <logsource category> product: <product> service: <service> detection: <selection_name>: <field>: <value> condition: <selection_name> falsepositives:
- <list of known benign triggers>
level: <informational | low | medium | high | critical>
The three sections that determine everything are logsource, detection, and condition.
Briefings like this, every morning before 9am.
Threat intel, active CVEs, and campaign alerts, distilled for practitioners. 50,000+ subscribers. No noise.
Choosing Your Log Source
Sigma's logsource taxonomy has three fields that work together:
- category: Defines the normalized log type (e.g., process_creation, network_connection)
- product: The platform (e.g., windows, linux)
- service: The specific Windows service generating the log (e.g., system, security, sysmon)
For Windows System Event 7045, we use:
logsource: product: windows service: system
This tells sigma-cli to look for the Windows System event log, and Sigma's backend will map this to the correct index or data source in each target SIEM.
For a rule that detects service creation via Sysmon (which gives richer process context), you would use:
logsource: category: process_creation product: windows
We will write both variants.
Building the Detection: Variant 1 (Windows System 7045)
Service installations that look like PSExec or similar tools share predictable characteristics:
- The service name is randomly generated or uses known PSExec patterns (PSEXESVC)
- The ImagePath (binary path) points to an unusual location, often a temp directory or the Windows root
- The service type is typically User-Mode Service (type 0x10 or 0x20)
- There is no corresponding scheduled deployment or software inventory entry
Here is the core detection block:
title: Suspicious Remote Service Installation - PSExec Pattern id: a8b5a9d1-4c2e-4f8a-b5c6-d7e8f9012345 status: experimental description: | Detects the creation of a Windows service that matches patterns associated with PSExec-style lateral movement. PSExec and similar tools create short-lived services on target hosts to execute commands remotely. This rule triggers on service names and ImagePath patterns consistent with this behavior. references:
- https://attack.mitre.org/techniques/T1569/002/
- https://docs.microsoft.com/en-us/sysinternals/downloads/psexec author: Your Name date: 2026-05-20 tags:
- attack.lateral_movement
- attack.t1569.002
- attack.execution
logsource:
product: windows
service: system
detection:
service_install:
EventID: 7045
service_psexec_name:
ServiceName|contains:
- 'PSEXESVC'
- 'psexesvc' service_suspicious_path: ImagePath|contains:
- '\ADMIN$'
- '\IPC$'
- '\C$\Windows\Temp'
- 'C:\Windows\PSEXESVC' service_random_name: ServiceName|re: '^[A-Za-z]{4,8}[0-9]{4,8}$' condition: service_install and (service_psexec_name or service_suspicious_path or service_random_name) falsepositives:
- Legitimate remote administration tools using service-based execution
- Software deployment systems that create temporary services
- Security tools that test for this behavior level: high
Let us break down the detection logic:
service_install: Filters to only Windows Event ID 7045. Everything else is scoped out.
service_psexec_name: Checks for the literal PSEXESVC service name, which is the default name PSExec uses. This is a high-specificity signal: very few legitimate tools use this name.
service_suspicious_path: Checks if the ImagePath (where the service binary lives) contains UNC path patterns (network shares) or known PSExec destinations. A service binary that lives on a network share is almost never legitimate.
service_random_name: A regex to catch renamed PSExec variants. The pattern ^[A-Za-z]{4,8}[0-9]{4,8}$ matches names like 'abcd1234' or 'svchost9182', which are common patterns in random service name generation.
condition: We require a service install event AND at least one of our three suspicious indicator sets. This reduces false positives compared to triggering on any service install.
Building the Detection: Variant 2 (Sysmon Process Creation)
When you have Sysmon deployed, you can write richer rules that include the parent process context. PSExec on the remote target creates a child process under the PSEXESVC service. The parent process is services.exe (the Windows Service Control Manager), and the command line shows the executed command.
title: PSExec Remote Execution via Service - Sysmon id: b9c6a2d3-5d3f-4g9b-c6d7-e8f9012346ab status: experimental description: | Detects remote command execution patterns associated with PSExec on the target host. PSExec creates a service (PSEXESVC) and executes commands as child processes of services.exe with network logon context. This rule targets the process creation pattern on target hosts. references:
- https://attack.mitre.org/techniques/T1569/002/ author: Your Name date: 2026-05-20 tags:
- attack.lateral_movement
- attack.t1569.002
logsource:
category: process_creation
product: windows
detection:
process_parent_service:
ParentImage|endswith: '\services.exe'
process_psexec_service:
ParentCommandLine|contains: 'PSEXESVC'
process_suspicious_child:
Image|endswith:
- '\cmd.exe'
- '\powershell.exe'
- '\wscript.exe'
- '\cscript.exe'
- '\mshta.exe' process_network_logon: LogonType: '3' condition: process_parent_service and process_psexec_service and process_suspicious_child falsepositives:
- Legitimate remote management solutions that create services level: high
False Positive Analysis: The Critical Step Most Skip
Before you deploy any rule, you need to answer: what legitimate behavior does this also match?
For the 7045-based rule, the common false positives are:
Software deployment systems. SCCM, Intune, and similar tools often install temporary services during patch deployment. These will have consistent naming patterns (usually matching the software being deployed) rather than random names. You can reduce noise by adding an allowlist for known deployment service names:
filter_deployment: ServiceName|startswith: - 'SCCM_' - 'MicrosoftUpdate' - 'WindowsUpdate' condition: service_install and (service_psexec_name or service_suspicious_path or service_random_name) and not filter_deployment
Security tools. Some vulnerability scanners and EDR tools create temporary services during scans. Get a list of the service names your tools use and add them to the filter.
RMM platforms. ConnectWise, Kaseya, and similar remote management platforms use service-based execution. These should have consistent, identifiable service names.
The goal is not zero false positives (that is too aggressive and will miss real attacks). The goal is a false positive rate that is low enough for your tier-1 analyst to triage the alerts in a reasonable time, typically fewer than 5-10 per day for a rule at 'high' severity.
If your rule would generate hundreds of alerts per day from legitimate tools, either:
- Add more specific filters to exclude the legitimate traffic
- Reduce the severity level so it goes into a lower-priority queue
- Convert to a hunting query rather than an alert rule
Converting to Target SIEM Formats
Once your Sigma rule is written and reviewed, use sigma-cli to convert it to your SIEM's native format.
Install sigma-cli and backends:
pip install sigma-cli pip install pySigma-backend-splunk pip install pySigma-backend-elasticsearch pip install pySigma-backend-microsoft365defender
Convert to Splunk:
sigma convert -t splunk -p splunk_windows path/to/your/rule.yml
Output: EventID=7045 (ServiceName="PSEXESVC" OR ServiceName IN ("\ADMIN$", "\IPC$", "C:\Windows\PSEXESVC") OR ServiceName=~"^[A-Za-z]{4,8}[0-9]{4,8}$")
Convert to Elasticsearch/OpenSearch (EQL):
sigma convert -t elasticsearch -p ecs_windows path/to/your/rule.yml
Convert to Microsoft Sentinel (KQL):
sigma convert -t microsoft365defender path/to/your/rule.yml
Convert to YAML for Elastic Security detection rules:
sigma convert -t elasticsearch -p ecs_windows -f kibana_ndjson path/to/your/rule.yml
After conversion, always manually review the output query in your SIEM. Backend conversion is not perfect, and field name mappings occasionally differ between environments. Run the query against historical data before enabling it as an alert to confirm it behaves as expected.
Testing Your Rule Before Production
Test against three datasets:
1. Synthetic true positives. Run PSExec (or a tool that generates equivalent events) in a test environment. Confirm your rule fires on the events generated. If you cannot reproduce the technique in a lab, use the sample logs from the SigmaHQ repository's test data.
2. Historical production data. Run your converted query against 30 days of production logs with no alerting. How many results does it return? Are they actual suspicious events, or known-good tools? This tells you your baseline false positive rate.
3. Sigma's built-in test framework. The sigma-cli testing feature lets you define expected true and false positive events in a .yml test file and run automated validation against the rule. This is valuable for regression testing when you modify rules.
Submitting to SigmaHQ
If your rule detects something not already covered in the SigmaHQ community repository, consider contributing it back. The process:
- Fork the SigmaHQ/sigma repository on GitHub
- Add your rule to the appropriate subdirectory under rules/ (organized by OS and category)
- Follow the naming convention: <verb>_<noun>.yml (e.g., psexec_lateral_movement.yml)
- Ensure the rule passes the SigmaHQ linting checks: sigma check path/to/rule.yml
- Submit a pull request with a description of what the rule detects, what log source it requires, and any test data you have
High-quality community contributions that are properly scoped, have reasonable false positive rates, and include complete metadata (ATT&CK tags, references, description) are generally accepted within a few weeks.
Rule Maintenance: What Nobody Tells You
Detection rules are not write-and-forget. They require ongoing maintenance:
Platform updates change field names. When your SIEM vendor releases a major update, field names sometimes change or are normalized differently. A rule that worked for 18 months may suddenly produce no results because a field name changed.
Attacker tools evolve. PSExec has many successors (Impacket, SharpExec, wmiexec) that avoid the PSEXESVC service name. Your rule that detects the original PSExec behavior will miss variants that changed a single parameter. Track ATT&CK technique updates and threat intel on tool evolution.
Your environment changes. When you onboard a new RMM platform, run a software deployment tool, or deploy a new security product, audit your detection rules for new false positive sources introduced by that tool.
Log sources go offline. A forwarder misconfiguration, a network change, or a Windows audit policy reset can silently stop events from flowing to your SIEM. Build detection coverage monitoring (an alert that fires if you see zero service creation events in a 24-hour window) so you know when a log source has gone dark.
Schedule a quarterly review of your top 20 detection rules to confirm they are still firing correctly on test data and that false positive rates remain acceptable.
The bottom line
Writing a Sigma rule is not primarily a YAML exercise. It is a detection engineering discipline that starts with understanding the technique, selecting the highest-signal log source, building precise detection logic, and then rigorously validating against both true positives and false positives before production. The sigma-cli conversion step is the last 10% of the work. The first 90% is understanding what you are trying to catch and why your chosen signal is specific enough to be actionable.
Frequently asked questions
What is the difference between Sigma and YARA?
Sigma is designed for log-based detection in SIEM platforms, it matches against structured event data (Windows Event logs, authentication logs, network flow records). YARA is designed for file and memory analysis, it matches patterns in binary files, memory dumps, and network traffic captured at the packet level. For a detection engineer, Sigma answers 'did this suspicious behavior appear in my logs?' while YARA answers 'does this file contain patterns matching known malware?' They are complementary, not competing. A complete detection program uses both: Sigma for behavioral detection in the SIEM, YARA for file scanning in your EDR, email gateway, and sandbox.
How do I handle Sigma field mapping differences between SIEM platforms?
Sigma backends and pipelines handle field mapping between the generic Sigma field names and your SIEM's actual field names. The pipeline file defines the mapping (e.g., Sigma's 'Image' field maps to 'process.executable' in ECS-normalized Elasticsearch). When you install a Sigma backend package, the default pipeline covers the most common field mappings for that platform. For custom log sources or non-standard field names in your environment, you can create a custom pipeline YAML file that maps Sigma fields to your specific field names. Review the generated query after conversion and compare the field names to what actually exists in your data to catch mapping gaps.
Should I set a Sigma rule to 'stable' or keep it as 'experimental'?
Use 'experimental' for any rule you have not yet validated against real production data. Use 'test' when you have validated the rule in a test environment or against historical logs but have not yet run it in a live alert context for at least 30 days. Use 'stable' only when the rule has been running in production for 30+ days with an acceptable false positive rate and you have confirmed it fires correctly on true positive test data. The status field does not affect rule behavior in most SIEMs, but it is important metadata for your team (so analysts know how much to trust it) and for the SigmaHQ community review process.
How many Sigma rules should an enterprise SOC have in production?
Quality over quantity. An organization with 50 well-tuned, high-confidence rules covering the most relevant ATT&CK techniques for their environment will have better detection outcomes than one with 500 poorly tuned rules generating constant noise. A reasonable starting target for an enterprise SOC is 75-150 active detection rules, covering: initial access, credential access, lateral movement, execution, persistence, and exfiltration techniques most commonly used against your industry vertical. The SigmaHQ community rule set has thousands of rules, but you should evaluate each one against your environment before enabling it as an alert.
Can I use Sigma with Microsoft Sentinel without sigma-cli?
Microsoft Sentinel has native support for importing Sigma rules through the Sigma Analytics Rule gallery in the Content Hub. You can also convert rules manually to KQL using sigma-cli with the microsoft365defender backend. The Sentinel backend in sigma-cli generates KQL that works in both Microsoft Sentinel and Microsoft Defender XDR advanced hunting. For production deployments, sigma-cli conversion is more flexible because you can apply custom pipelines that account for your specific log sources and field naming conventions.
How do I write a Sigma rule for a cloud environment like AWS or Azure?
Use the appropriate Sigma logsource category for cloud platforms: logsource: product: aws service: cloudtrail for AWS CloudTrail events, logsource: product: azure service: activitylogs for Azure Activity Log, or logsource: category: cloud service: gcp for Google Cloud. Sigma field names for cloud logs map to the fields available in your cloud logging platform. For AWS, Sigma's eventName field maps to CloudTrail's eventName. The SigmaHQ repository includes cloud rules under rules/cloud/ that you can use as reference templates. Cloud detection rule writing follows the same logical process as Windows rules: start with the technique, understand what the API calls or log entries look like, build your detection condition, and analyze false positives from legitimate cloud operations.
How do I integrate Sigma rule updates from the SigmaHQ community into my own detection pipeline?
Set up a CI/CD pipeline that pulls from the SigmaHQ GitHub repository on a scheduled basis (weekly is typical), runs sigma-cli conversion against your target SIEM backends, performs automated validation against your known test data, and then promotes passing rules through a staging environment before production. Tools like Sigmac (older), sigma-cli, and commercial platforms like Panther, Matano, and SOC Prime automate parts of this workflow. Treat community rule updates like software dependency updates: they require testing before production promotion, and you need to track which community rules you have customized locally to avoid overwriting your changes with upstream updates.
Sources & references
Free resources
Critical CVE Reference Card 2025–2026
25 actively exploited vulnerabilities with CVSS scores, exploit status, and patch availability. Print it, pin it, share it with your SOC team.
Ransomware Incident Response Playbook
Step-by-step 24-hour IR checklist covering detection, containment, eradication, and recovery. Built for SOC teams, IR leads, and CISOs.
Get threat intel before your inbox does.
50,000+ security professionals read Decryption Digest for early warnings on zero-days, ransomware, and nation-state campaigns. Free, daily, no spam.
Unsubscribe anytime. We never sell your data.

Founder & Cybersecurity Evangelist, Decryption Digest
Cybersecurity professional with expertise in threat intelligence, vulnerability research, and enterprise security. Covers zero-days, ransomware, and nation-state operations for 50,000+ security professionals every morning.
Win a $2,495 Black Hat pass.
Full-access to Black Hat USA 2026 in Las Vegas. Subscribe free to enter.
