The Complete Custom Wazuh Rules and Decoders Guide

Out of the box, Wazuh can detect thousands of security events across Windows, Linux, macOS, cloud platforms, network devices, containers, and applications. However, every environment eventually produces logs that Wazuh doesn’t understand natively. Custom applications, proprietary software, internally developed APIs, specialized appliances, and third-party SaaS platforms often generate unique log formats that require custom parsing before they become useful security events. This is where Wazuh rules and decoders become essential.

Decoders tell Wazuh how to read and extract information from raw logs, while rules determine whether those extracted fields represent something worth alerting on.

Together, they form the heart of Wazuh’s detection engine, allowing organizations to build highly customized threat detection logic tailored to their infrastructure.

Whether you’re parsing authentication logs from a custom web application, creating Sysmon detections for advanced Windows attacks, monitoring proprietary APIs, or enriching cloud events with custom metadata, understanding how rules and decoders interact is one of the most valuable Wazuh skills you can develop.

In this guide, you’ll learn:

  • How the complete Wazuh event processing pipeline works
  • The differences between decoders and rules
  • When to create custom decoders versus custom rules
  • How Wazuh processes JSON, Syslog, Windows, and custom log formats
  • Best practices for building scalable, maintainable detection logic
  • Common troubleshooting techniques for decoder and rule issues
  • Advanced techniques including dynamic fields, parent-child decoders, and Sysmon event detection

By the end of this guide, you’ll understand not only how to build custom Wazuh rules and decoders, but also how to design a detection pipeline that remains accurate, performant, and easy to maintain as your environment grows.


What Are Wazuh Rules and Decoders?

At a high level, every log entering Wazuh passes through two major processing stages:

  1. Decoding
  2. Rule evaluation

Although they’re closely related, they solve entirely different problems.

Overview of the Wazuh Event Processing Pipeline

A simplified processing flow looks like this:

Log Source
      │
      ▼
Log Collector
      │
      ▼
Pre-decoding
      │
      ▼
Decoder
      │
Extracted Fields
      │
      ▼
Rule Engine
      │
      ▼
Alert Generated
      │
      ▼
Indexer
      │
      ▼
Dashboard

Every stage builds upon the previous one.

If a decoder fails, the rule engine has little or no structured data to evaluate.

What Decoders Do

A decoder converts unstructured log text into structured fields that Wazuh can understand.

For example, consider the raw authentication log:

User=jdoe IP=192.168.10.25 Status=Failed

A decoder extracts information such as:

  • Username
  • Source IP
  • Authentication result
  • Timestamp
  • Session ID
  • Hostname
  • Event category

After decoding, the event becomes structured:

username = jdoe
srcip = 192.168.10.25
status = Failed

Instead of searching raw text repeatedly, Wazuh evaluates structured fields much more efficiently.

Custom decoders become necessary whenever:

  • Wazuh doesn’t recognize a log format
  • New fields need to be extracted
  • Vendor logs contain proprietary structures
  • Nested JSON requires custom parsing
  • Multiple log formats share common prefixes

Related Guide: Wazuh Decoder Guide

What Rules Do

Rules evaluate decoded events and determine whether they represent normal activity, suspicious behavior, or confirmed security incidents.

A rule can examine:

  • Extracted usernames
  • Source IP addresses
  • Event IDs
  • File paths
  • Process names
  • Registry keys
  • Network ports
  • Parent processes
  • Dynamic fields
  • Previous matching events

For example:

IF

status = Failed

AND

username = administrator

THEN

Generate Alert Level 10

Rules can also:

  • Correlate multiple events
  • Detect brute-force attacks
  • Identify privilege escalation
  • Detect malware behavior
  • Trigger Active Response
  • Suppress false positives

Unlike decoders, rules never parse raw logs, they rely entirely on decoded fields.

Related Guide: How to Create Custom Detection Rules in Wazuh (With Examples)

How Decoders and Rules Work Together

Think of decoders and rules as two consecutive stages.

The decoder answers:

“What information exists inside this log?”

The rule answers:

“Does this information indicate something important?”

Without a decoder:

Raw Log

↓

No extracted fields

↓

Rules cannot match correctly

Without rules:

Fields extracted successfully

↓

No alert generated

Only when both components work together can Wazuh transform raw log data into actionable security alerts.

This separation also improves maintainability.

Multiple rules can reuse the same decoder, while a single rule can apply to logs parsed by different decoders, reducing duplication across your ruleset.

Why Custom Rules and Decoders Are Important

The default Wazuh ruleset supports thousands of event types, but no security platform can anticipate every organization’s infrastructure.

Custom rules and decoders allow security teams to monitor:

  • Internal applications
  • Proprietary software
  • Manufacturing systems
  • Industrial control systems
  • Cloud-native services
  • Business-specific workflows
  • Custom APIs
  • Third-party SaaS platforms

Organizations also use custom rules to:

  • Reduce false positives
  • Add organization-specific detection logic
  • Enforce compliance requirements
  • Detect insider threats
  • Monitor sensitive assets
  • Identify business logic abuse

According to the MITRE ATT&CK framework, effective detection engineering depends on collecting relevant telemetry and creating detection logic tailored to an organization’s environment rather than relying solely on default signatures.

Guidance from NIST Special Publication 800-61 Rev. 2 (Computer Security Incident Handling Guide) also emphasizes the importance of customizing monitoring and detection capabilities to align with organizational risks and incident response processes.

Common Use Cases for Customization

Custom rules and decoders are commonly used for:

  • Monitoring custom authentication systems
  • Parsing proprietary application logs
  • Detecting API abuse
  • Identifying suspicious PowerShell activity
  • Monitoring Kubernetes workloads
  • Creating cloud-specific detections
  • Parsing firewall logs unsupported by default decoders
  • Monitoring database audit logs
  • Building ransomware detections
  • Creating compliance-specific alerts
  • Monitoring industrial equipment
  • Correlating business events with security events

Advanced users also customize Sysmon rules to detect:

  • Credential dumping
  • Process injection
  • DLL sideloading
  • Encoded PowerShell
  • LOLBins
  • Lateral movement

Related Guide: Step-by-Step: Custom Wazuh Sysmon Rules Guide


How Wazuh Processes Logs

Understanding the complete event processing pipeline makes it much easier to troubleshoot why alerts fail, decoders don’t match, or rules never execute.

Every event follows a predictable sequence before appearing in the Wazuh Dashboard.

Log Collection

Everything begins with log collection.

The Wazuh agent (or manager) gathers logs from sources such as:

  • Linux system logs
  • Windows Event Logs
  • Sysmon
  • Authentication logs
  • Firewalls
  • Cloud services
  • Containers
  • Web servers
  • Databases
  • APIs
  • Syslog devices

Logs are forwarded to the Wazuh manager through encrypted communication channels, where they enter the analysis engine.

Different collection modules normalize timestamps and metadata before the logs continue through the pipeline.

Pre-decoding

Before attempting to decode the log, Wazuh performs a lightweight parsing phase called pre-decoding.

This stage extracts universal metadata such as:

  • Timestamp
  • Hostname
  • Program name
  • Syslog priority
  • Log source

For Syslog messages, Wazuh separates the Syslog header from the message body.

Example:

Jul 18 09:41:22 server01 sshd[1122]:

Produces:

hostname = server01

program_name = sshd

timestamp = Jul 18 09:41:22

This metadata helps determine which decoder should process the remaining message.

Decoding

Once pre-decoding finishes, Wazuh evaluates available decoders.

Each decoder attempts to match the log using:

  • Program name
  • Prematch expressions
  • Regular expressions
  • JSON parsers
  • Parent decoders
  • Child decoders

If a decoder matches successfully, Wazuh extracts structured fields such as:

  • Username
  • Source IP
  • Destination IP
  • Process name
  • Command line
  • Registry key
  • URL
  • File path
  • Hash
  • User agent
  • Session ID

The quality of your decoder largely determines how effective downstream rule matching will be.

Related Guide: How to Use Wazuh Dynamic Fields to Extract Custom Log Data

Rule Evaluation

Once fields have been extracted, the rule engine begins evaluating events.

Rules can inspect:

  • Static fields
  • Dynamic fields
  • Previous events
  • Time windows
  • Frequency thresholds
  • Groups
  • MITRE mappings
  • Compliance tags

Rule conditions may include:

if_sid

if_group

match

regex

field

frequency

timeframe

same_source_ip

same_user

Rules execute in sequence until the highest-priority applicable alert is produced.

Alert Generation

When a rule matches successfully, Wazuh creates an alert containing:

  • Rule ID
  • Severity level
  • Description
  • Extracted fields
  • MITRE ATT&CK mappings
  • Compliance mappings (PCI DSS, HIPAA, GDPR, etc.)
  • Agent information
  • Original log
  • Timestamp

This structured alert is significantly easier to search, correlate, and investigate than the original raw log.

Indexing and Dashboard Visualization

Generated alerts are forwarded to the Wazuh Indexer, where they’re indexed for searching and analytics.

The Wazuh Dashboard enables analysts to:

  • Search alerts
  • Filter by rule
  • Investigate timelines
  • Build dashboards
  • Create visualizations
  • Run threat hunting queries
  • Correlate related events

Well-designed decoders also improve searchability because extracted fields become individually searchable rather than remaining embedded in raw log text.

Active Response Integration

After an alert is generated, Wazuh can automatically execute predefined response actions.

Examples include:

  • Blocking malicious IP addresses
  • Disabling compromised user accounts
  • Killing suspicious processes
  • Isolating endpoints
  • Updating firewall rules
  • Executing custom scripts

This automation allows organizations to reduce response times for high-confidence detections.

Related Guide: How to Configure Wazuh Active Response


Understanding Wazuh Decoders

Decoders are the foundation of every custom detection workflow.

If logs aren’t parsed correctly, even perfectly written rules won’t produce accurate alerts.

Understanding how decoders operate helps you build reliable, scalable parsing logic for virtually any log source.

What Is a Decoder?

A decoder is an XML definition that tells Wazuh how to identify a particular log format and extract useful information from it.

Rather than inspecting every possible rule against raw text, Wazuh first converts logs into structured data.

Typical extracted values include:

  • Username
  • Source IP
  • Destination IP
  • Process
  • Event ID
  • File path
  • Registry key
  • URL
  • Hash
  • Command line
  • Device name
  • Session ID

These structured fields become available for rule evaluation, dashboards, searches, and automated responses.

Parent vs Child Decoders

Large log formats often share common prefixes.

Instead of duplicating parsing logic, Wazuh supports hierarchical decoders.

A parent decoder identifies the general log type.

Example:

CustomApp:

Child decoders then parse specific message variations.

For example:

1. Child 1:

Login Success

2. Child 2:

Login Failed

3. Child 3:

Password Changed

Benefits include:

  • Less duplicated XML
  • Easier maintenance
  • Better performance
  • More modular parsing logic
  • Cleaner rule design

Related Guide: How to Map Complex Log Fields Using Wazuh Parent Child Rules

Static and Dynamic Fields

Wazuh supports two categories of extracted fields.

Static fields are predefined by Wazuh.

Examples include:

  • srcip
  • dstip
  • user
  • hostname
  • id
  • status

These integrate seamlessly with built-in rules.

Dynamic fields allow you to extract virtually any custom value.

Examples:

  • customer_id
  • tenant_name
  • api_endpoint
  • device_score
  • transaction_id
  • application_role
  • session_token

Dynamic fields are especially valuable for monitoring proprietary applications and business-specific workflows.

Regex and PCRE2 Support

Most decoders use regular expressions to identify and capture log data.

Wazuh supports traditional POSIX regular expressions as well as PCRE2, enabling advanced pattern matching features such as lookarounds, atomic groups, and more expressive capture logic where appropriate.

PCRE2 can simplify parsing of complex or inconsistent log formats, though overly complex expressions should be used carefully to avoid unnecessary processing overhead.

The Wazuh documentation recommends keeping expressions as specific and efficient as possible to improve decoder performance and reduce false matches.

JSON Decoders

Modern applications increasingly generate structured JSON logs.

Unlike plain-text parsing, JSON decoders access fields directly.

Example:

{
  "username":"alice",
  "action":"login",
  "status":"failed"
}

Fields can be extracted without relying on lengthy regular expressions, making JSON parsing more reliable and easier to maintain as schemas evolve.

Dynamic Field Extraction

Dynamic field extraction allows security teams to retain valuable business context that doesn’t fit Wazuh’s predefined schema.

Common examples include:

  • Customer IDs
  • Tenant IDs
  • Order numbers
  • Device fingerprints
  • Risk scores
  • API versions
  • Subscription plans
  • Session identifiers

This additional context enables more precise detection logic and richer investigations, especially in multi-tenant or custom application environments.

Related Guide: How to Use Wazuh Dynamic Fields to Extract Custom Log Data

Decoder Matching Order

When processing an event, Wazuh evaluates decoders in a defined order until it finds the appropriate match.

In general, the process follows this pattern:

  1. Pre-decoding extracts basic metadata.
  2. Candidate decoders are filtered using attributes such as program_name or prematch.
  3. Parent decoders identify the overall log family.
  4. Child decoders refine parsing for specific message types.
  5. Matching regular expressions or JSON extraction rules capture the required fields.

Designing decoders with selective prematch expressions and logical parent-child hierarchies reduces unnecessary evaluations and improves performance in large environments.

Decoder Best Practices

When building custom decoders:

  • Keep each decoder focused on a single log format.
  • Use parent-child hierarchies to eliminate duplicated parsing logic.
  • Prefer JSON parsing over regular expressions when structured logs are available.
  • Extract only the fields needed for detection and investigation.
  • Use descriptive names for custom dynamic fields.
  • Test every decoder with wazuh-logtest before deploying to production.
  • Store custom decoders separately from the default ruleset to simplify upgrades.
  • Validate changes in a staging environment before rolling them out broadly.

These practices improve long-term maintainability, minimize false matches, and make it easier to extend your detection pipeline as new log sources are introduced.

Related Guide: How to Use Wazuh Logtest


Understanding Wazuh Rules

Rules are the intelligence layer of Wazuh’s detection engine.

After decoders extract structured information from raw logs, rules analyze that data to determine whether an event is informational, suspicious, or malicious.

Every alert displayed in the Wazuh Dashboard is the result of one or more rules successfully matching decoded fields.

Well-designed rules enable security teams to detect attacks, reduce false positives, correlate related events, trigger automated responses, and map detections to industry security frameworks.

Rule IDs

Every Wazuh rule must have a unique numeric rule ID.

For example:

<rule id="100500" level="10">

The rule ID uniquely identifies the detection logic and allows other rules to reference it.

Rule IDs are commonly used with directives such as:

  • if_sid
  • if_matched_sid
  • if_group
  • if_matched_group

These references enable rules to build upon previous detections instead of evaluating every event independently.

When creating custom rules, avoid modifying the default Wazuh rules directly.

Instead, assign custom rule IDs within your organization’s designated range and store them in local rule files. This approach simplifies upgrades and prevents your customizations from being overwritten.

Related Guide: How to Safely Overwrite Local Rule IDs Without Wazuh Conflicts

Rule Levels

Every rule contains a level attribute that represents the severity of the generated alert.

Higher levels indicate events that deserve greater attention from security analysts.

A common guideline is:

Rule LevelSeverity
0Ignore or informational
1–3Low priority
4–6Warning
7–9Medium severity
10–12High severity
13–16Critical

For example:

  • Successful user login → Level 3
  • Failed administrator login → Level 7
  • Malware detected → Level 12
  • Confirmed ransomware behavior → Level 15

Consistent severity assignments help analysts prioritize investigations and reduce alert fatigue.

Rule Conditions

Rules evaluate one or more conditions before generating an alert.

Conditions can inspect:

  • Decoded fields
  • Static fields
  • Dynamic fields
  • Event IDs
  • Process names
  • File paths
  • Registry keys
  • Command lines
  • Source IP addresses
  • Usernames
  • Previous rule matches

A simplified example:

status = failed

AND

username = administrator

AND

srcip = 192.168.1.25

Only when every required condition is satisfied does the rule trigger.

Rules may also use:

  • Exact matches
  • Regular expressions
  • Wildcards
  • Numeric comparisons
  • String comparisons
  • Field existence checks

Combining multiple conditions generally produces more accurate detections than relying on a single field.

Rule Groups

Rule groups categorize related detections.

Examples include:

  • authentication
  • ssh
  • windows
  • sysmon
  • malware
  • web
  • firewall
  • cloud
  • vulnerability_detection
  • compliance

Groups simplify:

  • Rule organization
  • Dashboard searches
  • Alert filtering
  • Rule inheritance
  • Reporting

For example, every SSH authentication rule can belong to the authentication and ssh groups while still detecting different attack techniques.

Grouping related rules also makes long-term maintenance much easier as custom rulesets grow.

Frequency and Timeframe Correlation

Many attacks consist of repeated events rather than a single suspicious log entry.

Wazuh allows rules to correlate activity over time using frequency and timeframe conditions.

Examples include:

  • Five failed logins within two minutes
  • Twenty PowerShell executions in one minute
  • Multiple privilege escalation attempts
  • Repeated malware detections on the same endpoint

Instead of generating five individual alerts, Wazuh can generate one higher-confidence alert indicating a possible attack.

This greatly reduces alert noise while improving detection accuracy.

Common use cases include:

  • Brute-force attacks
  • Password spraying
  • Port scanning
  • Web enumeration
  • Credential stuffing
  • Denial-of-service attacks

Related Guide: Wazuh Brute Force Detection Guide

Rule Chaining

Rule chaining allows multiple rules to build upon each other.

Rather than creating one large, complicated rule, Wazuh encourages smaller rules that reference previous detections.

For example:

Rule 100100

↓

Failed Login

↓

Rule 100200

↓

Five Failed Logins

↓

Rule 100300

↓

Possible SSH Brute Force

↓

Rule 100400

↓

Trigger Active Response

This layered design provides several benefits:

  • Easier troubleshooting
  • Better rule reuse
  • Reduced duplication
  • Simpler maintenance
  • Improved readability

Rule chaining is commonly implemented using directives such as if_sid and if_matched_sid, allowing higher-level detections to build on simpler foundational rules.

MITRE ATT&CK Mapping

Modern detection engineering extends beyond simply generating alerts.

Analysts also need to understand which attacker techniques those alerts represent.

Wazuh supports mapping rules to the MITRE ATT&CK framework.

For example:

DetectionATT&CK Technique
Encoded PowerShellT1059.001
Credential DumpingT1003
Remote ServicesT1021
Scheduled Task PersistenceT1053

These mappings help:

  • Prioritize investigations
  • Perform threat hunting
  • Measure detection coverage
  • Identify gaps in monitoring
  • Standardize reporting across security teams

The MITRE ATT&CK framework is widely recognized as the industry standard for documenting adversary tactics, techniques, and procedures (TTPs).

Compliance Mapping (PCI DSS, HIPAA, NIST, GDPR)

In addition to ATT&CK mappings, Wazuh rules can include references to major compliance frameworks.

Common examples include:

  • PCI DSS
  • HIPAA
  • NIST Cybersecurity Framework
  • GDPR
  • CIS Controls

Compliance mappings help organizations:

  • Demonstrate security monitoring
  • Produce audit reports
  • Track regulatory requirements
  • Simplify compliance assessments

For example, authentication monitoring rules may contribute toward PCI DSS requirements for access control and logging, while file integrity monitoring supports multiple compliance standards requiring change detection.

The NIST Cybersecurity Framework (CSF) 2.0 emphasizes continuous security monitoring and event detection as key capabilities for identifying cybersecurity incidents.

Active Response Integration

Rules don’t have to stop at generating alerts.

High-confidence detections can automatically trigger Active Response actions.

Examples include:

  • Blocking an IP address
  • Disabling a compromised account
  • Killing a malicious process
  • Isolating a host
  • Updating firewall rules
  • Running custom response scripts

For example:

Rule Matches

↓

Alert Generated

↓

Active Response Triggered

↓

Firewall Blocks Source IP

Automating response actions helps reduce attacker dwell time and allows security teams to react to threats within seconds instead of minutes or hours.

When implementing Active Response, it’s important to carefully tune rules and thoroughly test them in a non-production environment to avoid unintended disruptions caused by false positives.

Related Guide: How to Configure Wazuh Active Response


How Rules and Decoders Work Together

Rules and decoders are designed to complement one another.

Decoders transform raw log data into structured fields, while rules evaluate those fields to determine whether an alert should be generated.

Neither component is particularly useful on its own.

A decoder without rules only parses data, while a rule without decoded fields has little meaningful information to evaluate.

Together, they form the complete detection pipeline.

Event Processing Workflow

Every event follows a predictable sequence inside Wazuh.

Raw Log

↓

Log Collection

↓

Pre-decoding

↓

Decoder

↓

Extracted Fields

↓

Rule Evaluation

↓

Alert

↓

Indexer

↓

Dashboard

↓

Active Response (Optional)

Each stage depends on the successful completion of the previous stage.

Decoder Extracts Data

Consider the following raw log:

User=jdoe IP=192.168.1.50 Status=Failed

A decoder extracts structured information such as:

username = jdoe

srcip = 192.168.1.50

status = Failed

Instead of evaluating raw text repeatedly, Wazuh now works with structured fields that can be searched, correlated, and indexed efficiently.

Rule Evaluates Extracted Fields

Once decoding completes, rules inspect the extracted values.

For example:

IF

status = Failed

AND

username = administrator

THEN

Generate Level 10 Alert

Rules may also inspect:

  • Previous events
  • Time windows
  • Frequency thresholds
  • Dynamic fields
  • Parent rule matches
  • Rule groups

This separation keeps the parsing logic independent from the detection logic.

Alert Generation

If all rule conditions are satisfied, Wazuh generates a structured alert.

Typical alert information includes:

  • Rule ID
  • Severity
  • Description
  • Timestamp
  • Agent
  • Original log
  • Decoded fields
  • MITRE ATT&CK mapping
  • Compliance references

The alert is then indexed for searching, visualization, and automated response.

Practical Processing Example

Imagine a custom web application produces the following log:

LOGIN user=alice ip=198.51.100.20 result=failed

Step 1 — Decoder

The decoder extracts:

user = alice

srcip = 198.51.100.20

result = failed

Step 2 — Rule

A custom rule evaluates:

result = failed

The rule generates a level 5 authentication failure alert.

Step 3 — Correlation Rule

A second rule detects:

  • Five failed logins
  • Same IP address
  • Two-minute window

A higher-severity brute-force alert is generated.

Step 4 — Active Response

The firewall automatically blocks the attacking IP address for a predefined period.

This layered workflow illustrates how decoders, rules, correlation logic, and automated responses work together to detect and mitigate threats.

Common Design Patterns

Experienced Wazuh administrators often follow several design patterns when creating custom detection content.

One Decoder, Many Rules

A single decoder extracts reusable fields that multiple rules evaluate.

Example:

Authentication Decoder

↓

Failed Login Rule

↓

Successful Login Rule

↓

Impossible Travel Rule

↓

Privilege Escalation Rule

This avoids duplicating parsing logic.

Parent-Child Decoder Hierarchy

Use parent decoders for shared log prefixes and child decoders for specific event types.

Benefits include:

  • Less XML duplication
  • Easier maintenance
  • Better scalability

Related Guide: How to Map Complex Log Fields Using Wazuh Parent Child Rules

Multi-Stage Detection

Build simple foundational rules before creating advanced correlation rules.

For example:

Rule A

↓

Rule B

↓

Rule C

Each layer increases detection confidence while minimizing false positives.

Dynamic Field Design

Extract business-specific information using dynamic fields rather than forcing custom data into predefined Wazuh fields.

Examples include:

  • Customer ID
  • API endpoint
  • Tenant ID
  • Risk score
  • Subscription plan

This approach produces more flexible and maintainable detection logic.

Related Guide: How to Use Wazuh Dynamic Fields to Extract Custom Log Data


Creating Your First Custom Decoder

Creating a custom decoder is often the first step toward supporting a new log source in Wazuh.

The process involves identifying the log structure, extracting the fields you need, validating the parser, and deploying it so that rules can evaluate the resulting data.

Identify the Log Format

Before writing any XML, collect several examples of the logs you want to parse.

Look for:

  • Fixed prefixes
  • Consistent delimiters
  • Key-value pairs
  • Timestamps
  • Usernames
  • IP addresses
  • Event IDs
  • JSON structures
  • Optional fields

Comparing multiple samples helps you identify which parts of the log are constant and which parts vary, making it easier to design a reliable decoder.

Create the Decoder XML

Create a new decoder file inside your custom decoder directory (commonly local_decoder.xml or another custom XML file included by Wazuh).

A basic decoder typically defines:

  • A unique decoder name
  • A prematch expression to identify the log type
  • One or more regular expressions or JSON parsing directives
  • The order in which captured fields are assigned

Using a prematch filter helps Wazuh skip unrelated logs and improves parsing performance.

Extract Required Fields

Next, determine which values should become searchable fields.

Common fields include:

  • Username
  • Source IP
  • Destination IP
  • Hostname
  • Event type
  • Status
  • Process name
  • File path
  • URL
  • Session ID

Avoid extracting every possible value.

Instead, focus on the information required for detection, investigation, reporting, and correlation.

If your application generates business-specific metadata, consider using dynamic fields with descriptive names rather than repurposing built-in fields.

Related Guide: How to Use Wazuh Dynamic Fields to Extract Custom Log Data

Validate with wazuh-logtest

Always validate new decoders before deploying them.

The wazuh-logtest utility shows:

  • Which decoder matched
  • Extracted fields
  • Rule matches
  • Generated alerts
  • Parsing errors

Testing with multiple log samples, including valid, malformed, and unexpected inputs, helps identify parsing issues early and reduces the risk of missed detections in production.

Related Guides:

Deploy the Decoder

Once validation is complete:

  1. Save the decoder XML in your custom decoder directory.
  2. Ensure the file is included in the Wazuh configuration.
  3. Restart or reload the Wazuh manager so the new decoder is loaded.
  4. Confirm there are no syntax errors in the manager logs.

Keeping custom decoders separate from the default ruleset makes future Wazuh upgrades significantly easier because your customizations won’t be overwritten.

Verify Successful Parsing

After deployment, generate test events that match your new log format and verify that:

  • The correct decoder is selected.
  • All required fields are extracted.
  • No parsing warnings or errors appear.
  • Expected rules trigger successfully.
  • Alerts are visible in the Wazuh Dashboard.
  • Extracted fields can be searched and filtered.

Successful parsing confirms that your decoder is ready for production use and provides a solid foundation for building custom detection rules on top of the newly structured data.


Creating Your First Custom Rule

Once your decoder successfully extracts structured fields, the next step is creating a custom rule that evaluates those fields and generates meaningful alerts.

A well-designed rule should be easy to understand, produce actionable alerts, minimize false positives, and integrate with your organization’s detection strategy.

This section walks through the basic workflow for creating your first custom Wazuh rule.

Choose a Rule ID

Every custom rule requires a unique rule ID.

Rule IDs allow Wazuh to:

  • Identify individual rules
  • Reference previous rule matches
  • Build rule hierarchies
  • Correlate related detections

For example:

<rule id="100500" level="8">

Choose IDs that do not conflict with existing Wazuh rules or your organization’s other custom rules.

Many administrators reserve a dedicated range of IDs exclusively for local rules, making future maintenance significantly easier.

Avoid modifying the default rules distributed with Wazuh.

Instead, place your custom rules in local_rules.xml or another custom rules file that is preserved during upgrades.

Related Guide: How to Safely Overwrite Local Rule IDs Without Wazuh Conflicts

Match Decoder Fields

Rules evaluate the structured fields extracted by decoders rather than the raw log itself.

For example, suppose a decoder extracts:

username = administrator

srcip = 198.51.100.10

status = failed

A custom rule can then evaluate those values:

status = failed

AND

username = administrator

Rules can inspect virtually any decoded information, including:

  • Username
  • Source IP
  • Destination IP
  • Process name
  • File path
  • Registry key
  • Command line
  • Event ID
  • Dynamic fields
  • JSON values

The more accurate your decoder, the simpler and more reliable your rules become.

Assign Alert Severity

Each rule includes a level that represents the alert’s severity.

Choosing appropriate severity levels helps analysts prioritize investigations.

For example:

Alert TypeSuggested Level
Informational login3
Failed authentication5
Multiple failed logins8
Privilege escalation10
Malware execution12
Confirmed ransomware behavior15

Avoid assigning high severity levels to routine administrative events, as doing so can overwhelm analysts with unnecessary alerts.

A useful approach is to begin with conservative severity levels during testing and adjust them as you observe real-world behavior in your environment.

Add MITRE and Compliance Tags

Modern detection engineering extends beyond simply generating alerts.

Custom rules should include mappings to relevant security frameworks whenever appropriate.

Typical mappings include:

  • MITRE ATT&CK
  • PCI DSS
  • HIPAA
  • NIST Cybersecurity Framework
  • GDPR
  • CIS Controls

For example, a rule detecting encoded PowerShell commands may map to:

  • T1059.001 – PowerShell

A failed authentication rule may contribute toward PCI DSS authentication monitoring requirements.

Adding these mappings helps:

  • Standardize detections
  • Improve reporting
  • Support compliance audits
  • Measure ATT&CK coverage
  • Simplify threat hunting

The MITRE ATT&CK framework is widely used to classify adversary behaviors and improve detection coverage across security tools.

Test the Rule

Every custom rule should be validated before production deployment.

The recommended testing process is:

  1. Feed representative logs into wazuh-logtest.
  2. Confirm the correct decoder matches.
  3. Verify that all expected fields are extracted.
  4. Ensure the intended rule triggers.
  5. Test malformed and unexpected log formats.
  6. Verify that unrelated logs do not trigger the rule.

Testing multiple scenarios helps identify edge cases and reduce false positives before deployment.

Experienced detection engineers typically create both positive tests (the rule should fire) and negative tests (the rule should not fire).

Related Guide: How to Use Wazuh Logtest

Deploy and Reload Wazuh

After testing is complete:

  1. Save the custom rule file.
  2. Verify the XML syntax.
  3. Reload or restart the Wazuh manager.
  4. Generate test events.
  5. Confirm alerts appear in the Dashboard.

After deployment, monitor the rule for several days to identify:

  • Unexpected matches
  • False positives
  • Missed detections
  • Performance issues

Periodic tuning is a normal part of maintaining an effective detection library.


Testing Rules and Decoders

Testing is one of the most important phases of custom detection development.

Even small mistakes in a decoder or rule can prevent alerts from being generated or create excessive false positives.

Fortunately, Wazuh includes powerful tools that allow administrators to validate every stage of the event processing pipeline before deploying changes into production.

Using wazuh-logtest

wazuh-logtest is the primary utility for testing custom decoders and rules.

Instead of waiting for real events to occur, you can submit sample logs directly to the analysis engine.

The utility displays:

  • Pre-decoding results
  • Decoder selection
  • Extracted fields
  • Rule evaluation
  • Generated alerts

This allows you to quickly verify whether your custom logic behaves as expected.

Testing with wazuh-logtest is generally much faster than repeatedly generating live events and checking the Dashboard.

Related Guide: How to Use Wazuh Logtest

Reading Decoder Output

The decoder section of the output confirms whether Wazuh successfully recognized the log.

Verify that:

  • The correct decoder matched.
  • Expected fields are extracted.
  • Dynamic fields contain the correct values.
  • No fields are missing.
  • No unexpected values appear.

If a required field isn’t extracted, downstream rules cannot evaluate it correctly.

Always verify decoder output before troubleshooting rule logic.

Understanding Rule Matches

After decoding completes, wazuh-logtest displays every matching rule.

Review:

  • Rule ID
  • Alert level
  • Rule description
  • Rule groups
  • MITRE mappings
  • Compliance tags

If multiple rules match, Wazuh typically generates the highest-priority applicable alert while preserving the evaluation chain.

Understanding which rules fired, and why, helps identify unnecessary matches and opportunities for tuning.

Debugging Failed Matches

If a rule doesn’t trigger, work through the pipeline systematically.

Common causes include:

  • Incorrect decoder selection
  • Missing extracted fields
  • Typographical errors
  • Case-sensitive comparisons
  • Incorrect regular expressions
  • Invalid field names
  • Rule order dependencies
  • Frequency or timeframe conditions not being met

Rather than modifying several components simultaneously, change one variable at a time and retest. This methodical approach makes it much easier to isolate the root cause.

Related Guide: Troubleshooting wazuh-logtest: Why Alerts Are Missing from JSON Output

Testing JSON Logs

JSON logs require slightly different validation than plain-text logs.

Verify that:

  • Nested objects are parsed correctly.
  • Arrays contain the expected values.
  • Dynamic fields are created where appropriate.
  • Numeric values remain numeric.
  • Special characters are handled correctly.
  • Optional fields do not break parsing.

Testing several variations of the same JSON structure helps ensure your decoder remains reliable as application schemas evolve.

Validating Production Deployments

Testing shouldn’t end after a rule is deployed.

In production, verify that:

  • Alerts appear in the Wazuh Dashboard.
  • Indexed fields are searchable.
  • Severity levels are appropriate.
  • Active Response triggers only when intended.
  • Alert volume remains manageable.
  • False positives stay within acceptable limits.

Many organizations deploy new rules in a monitoring-only mode before enabling automated responses, allowing analysts to fine-tune detection logic based on real production data.


Working with JSON Logs

Modern security monitoring increasingly relies on structured JSON logs generated by cloud platforms, SaaS applications, containers, Kubernetes, APIs, and custom software.

Unlike traditional Syslog messages, JSON logs already contain structured data, allowing Wazuh to extract fields more efficiently and with fewer regular expressions.

Properly leveraging JSON decoding enables richer detections, simpler rule creation, and more detailed investigations.

Native JSON Decoding

Wazuh includes built-in support for parsing JSON-formatted logs.

Instead of relying entirely on regular expressions, Wazuh reads key-value pairs directly from the JSON document.

For example:

{
  "user": "alice",
  "action": "login",
  "status": "failed",
  "srcip": "198.51.100.25"
}

After decoding, fields such as user, status, and srcip become immediately available to custom rules.

Using native JSON decoding is generally more reliable and easier to maintain than writing complex regular expressions for structured data.

Nested Objects

Many applications organize related information into nested JSON objects.

For example:

{
  "user": {
    "name": "alice",
    "role": "administrator"
  },
  "network": {
    "srcip": "198.51.100.25"
  }
}

Nested structures improve readability but also require your decoder and rules to reference the appropriate fields correctly.

Common nested objects include:

  • User information
  • Device metadata
  • Authentication details
  • Cloud resources
  • Network information
  • API request metadata

Understanding how nested fields are represented allows you to create more precise detection logic without flattening the original data.

Arrays

JSON arrays are frequently used to represent lists of values.

Examples include:

  • Multiple IP addresses
  • User roles
  • Security groups
  • Requested permissions
  • API scopes
  • File hashes

Example:

{
  "roles": [
    "admin",
    "developer"
  ]
}

When designing custom decoders and rules, consider whether you need to inspect individual array elements or simply determine whether a specific value exists within the collection.

Proper handling of arrays is particularly important when monitoring cloud identity platforms and Kubernetes workloads, where a single event often contains multiple related objects.

Related Guide: How to Parse Flattened Nested Keys and Arrays in Wazuh JSON Logs

Dynamic Fields

One of the biggest advantages of JSON logs is the ability to extract custom fields without being limited to Wazuh’s predefined schema.

Examples include:

  • Customer ID
  • Tenant ID
  • Session ID
  • API endpoint
  • Device fingerprint
  • Risk score
  • Subscription plan
  • Transaction ID

These dynamic fields can then be referenced directly within custom rules, making it possible to create detections based on organization-specific context.

For example, a rule might alert only when a failed login occurs against a premium customer account or when an API request exceeds a certain risk score.

Related Guide: How to Use Wazuh Dynamic Fields to Extract Custom Log Data

Cloud Service Logs

Cloud providers generate large volumes of JSON-formatted security logs.

Common examples include:

  • AWS CloudTrail
  • Microsoft Azure Activity Logs
  • Google Cloud Audit Logs
  • Kubernetes audit logs
  • Container runtime logs
  • Identity provider logs

JSON decoding allows Wazuh to extract fields such as:

  • Account IDs
  • Resource names
  • IAM users
  • Regions
  • Service names
  • Request parameters
  • API actions

These structured fields enable detailed cloud detections without extensive custom parsing.

Related Guide: How to Monitor AWS CloudTrail Logs Using Wazuh

API Audit Logs

Modern applications increasingly expose audit events as JSON through REST APIs and microservices.

Typical API audit logs contain information such as:

  • Authenticated user
  • HTTP method
  • Endpoint
  • Response status
  • Client IP address
  • User agent
  • Request ID
  • Authentication method
  • Execution time

By decoding these fields, Wazuh can detect behaviors such as:

  • Repeated failed authentication attempts
  • Privilege changes
  • Excessive API usage
  • Access to sensitive endpoints
  • Suspicious administrative actions
  • Unusual geographic access patterns

Combining API audit logs with dynamic fields and custom rules enables organizations to extend Wazuh beyond traditional infrastructure monitoring into application-layer threat detection, providing greater visibility into business-critical systems.


Building Advanced Detection Rules

Basic Wazuh rules are useful for detecting individual events, but advanced security monitoring requires more than simple field matching.

Modern attacks often involve multiple steps, occur across different systems, and attempt to blend into normal administrative activity.

Advanced detection rules combine multiple techniques, including event correlation, frequency analysis, multi-stage logic, and threat hunting patterns, to identify suspicious behavior with higher confidence.

A mature Wazuh deployment typically evolves from simple alerts into a detection engineering platform where rules model attacker behavior rather than isolated events.

Multi-Stage Detection

Multi-stage detection identifies attacks by analyzing a sequence of related activities instead of a single event.

Attackers rarely perform one action. A typical intrusion may involve:

Initial Access

↓

Credential Discovery

↓

Privilege Escalation

↓

Lateral Movement

↓

Data Collection

↓

Exfiltration

A single event may appear harmless:

  • A PowerShell command executes.
  • A user logs in remotely.
  • A new scheduled task is created.

However, when these events occur together, they may indicate malicious activity.

For example:

Stage 1

A user authenticates successfully through SSH.

Stage 2

The same user executes privileged commands.

Stage 3

Sensitive files are accessed.

Stage 4

Large outbound network transfers occur.

Individually, these events may not trigger high-severity alerts. Together, they represent a potential compromise.

Wazuh supports this approach using:

  • Rule dependencies
  • if_sid
  • if_matched_sid
  • Frequency conditions
  • Timeframe correlation
  • Rule groups

This detection model improves accuracy because it evaluates attacker behavior rather than isolated log entries.

Parent Child Rule Relationships

Similar to decoder hierarchies, Wazuh rules can also be structured using parent-child relationships.

A parent rule identifies a broad event category, while child rules detect more specific behaviors.

Example:

Parent Rule

Windows Process Creation

        |

        |

Child Rule 1

PowerShell Execution

        |

Child Rule 2

Encoded PowerShell Command

        |

Child Rule 3

PowerShell Downloading Remote Payload

Benefits include:

  • Reduced duplicated logic
  • Easier maintenance
  • Better rule organization
  • More accurate alert escalation

A parent rule may identify all PowerShell executions, while child rules focus only on suspicious variants.

This layered structure is especially valuable for:

  • Windows Event Logs
  • Sysmon monitoring
  • Authentication events
  • Cloud audit logs

Frequency-Based Detection

Frequency-based detection identifies repeated behavior within a specific time period.

Many attacks are not obvious because individual events look normal.

Examples:

  • One failed login → Normal
  • Fifty failed logins → Possible brute-force attack

A frequency rule might detect:

10 failed authentication attempts

FROM

same source IP

WITHIN

60 seconds

Common frequency-based detections include:

  • SSH brute-force attacks
  • Password spraying
  • API abuse
  • Port scanning
  • Web enumeration
  • Repeated malware execution

Frequency rules reduce analyst workload by grouping many low-value events into fewer high-confidence alerts.

Related Guide: Wazuh Brute Force Detection Guide

Timeframe Correlation

Timeframe correlation extends frequency detection by evaluating relationships between events over time.

Instead of asking:

“Did this event happen?”

The rule asks:

“Did this sequence of events happen within a suspicious timeframe?”

Examples:

Authentication Correlation

Failed Login

↓

Successful Login

↓

Same User

↓

Within 5 Minutes

Possible interpretation:

A user account may have been compromised.

Privilege Escalation Correlation

New User Created

↓

User Added to Administrators Group

↓

Privileged Command Executed

↓

Within 10 Minutes

Possible interpretation:

An attacker established persistence.

Time-based correlation is one of the most effective ways to detect real attack behavior while reducing false positives.

Suppressing False Positives

False positives are one of the biggest challenges in security monitoring.

A detection that fires constantly loses value because analysts begin ignoring alerts.

Common false-positive sources include:

  • Automated administrative scripts
  • Vulnerability scanners
  • Backup systems
  • Monitoring tools
  • Software updates
  • Development environments
  • Legitimate automation

Wazuh provides several methods for reducing unnecessary alerts:

Field Exclusions

Ignore known trusted values:

Exclude:

scanner.company.com

backup-service-account

Rule Exceptions

Modify conditions so that only suspicious behavior triggers alerts.

Example:

Instead of:

Any PowerShell execution

Use:

PowerShell execution

AND

Encoded command detected

AND

Unknown user

Threshold Tuning

Increase frequency requirements:

Before:

3 failed logins

After:

15 failed logins within 5 minutes

Continuous tuning ensures detections remain useful as environments change.

Event Correlation Across Multiple Sources

Advanced detections often require combining information from multiple systems.

A single log source rarely provides complete attack visibility.

For example:

Firewall Logs

Shows:

Outbound connection to suspicious IP

Endpoint Logs

Shows:

Unknown process created network connection

Authentication Logs

Shows:

User logged in shortly before activity

Together, these events create a stronger detection.

Common multi-source correlation examples include:

  • User authentication + endpoint activity
  • Firewall traffic + malware detection
  • Cloud API activity + IAM changes
  • Kubernetes audit logs + container execution

This approach provides broader visibility across hybrid environments.

Threat Hunting Rules

Threat hunting rules are designed to proactively search for attacker behavior rather than waiting for alerts.

Unlike traditional detections, threat hunting rules often focus on:

  • Suspicious patterns
  • Rare activity
  • Anomalies
  • Known attacker techniques

Examples:

Windows Threat Hunting

Detect:

  • Suspicious parent-child processes
  • Unusual PowerShell usage
  • Credential dumping tools
  • DLL loading anomalies

Related Guide: Step-by-Step: Custom Wazuh Sysmon Rules Guide

Linux Threat Hunting

Detect:

  • Unexpected root commands
  • SSH key modifications
  • Privilege escalation attempts
  • Suspicious cron jobs

Cloud Threat Hunting

Detect:

  • Unusual API calls
  • New IAM permissions
  • Geographic anomalies
  • Disabled security controls

Threat hunting rules allow analysts to continuously search for adversary behavior before traditional alerts are generated.


Real-World Rule and Decoder Examples

Custom rules and decoders become most valuable when applied to real operational scenarios.

Every organization has unique applications, infrastructure, and workflows that require customized detection logic.

The following examples demonstrate how Wazuh can extend beyond default monitoring capabilities.

Custom Web Application Authentication Logs

Many organizations operate custom applications that generate proprietary authentication events.

Example log:

LOGIN user=john ip=203.0.113.20 result=failed application=customer_portal

Decoder

Extract:

username=john

srcip=203.0.113.20

status=failed

application=customer_portal

Rule

Detect:

Failed login

AND

Application = customer_portal

AND

Multiple failures from same IP

Possible alert:

Possible customer portal brute-force attack

This allows Wazuh to monitor applications that have no built-in integration.

Windows Event Logs

Windows environments generate thousands of security events through:

  • Security Event Logs
  • Sysmon
  • PowerShell logging
  • Defender events

Custom rules can detect:

  • Suspicious account creation
  • Privilege escalation
  • Remote execution
  • Credential theft
  • Persistence mechanisms

Example:

Event ID 4720

+

New administrator account created

Potential detection:

Unauthorized privileged account creation

Related Guide: How to Monitor Windows Event Logs Using Wazuh

Linux Authentication Monitoring

Linux systems generate valuable authentication telemetry through:

  • SSH logs
  • sudo logs
  • PAM events
  • system authentication logs

Example detection:

Multiple failed SSH attempts

+

Successful login

+

Privilege escalation

Possible alert:

Potential compromised SSH account

Custom decoders can parse non-standard Linux authentication systems and custom PAM modules.

Sysmon Detection Rules

Sysmon provides detailed Windows endpoint telemetry.

Custom Wazuh rules can detect:

  • Process creation
  • Network connections
  • Registry modifications
  • File creation
  • DLL loading
  • Process injection

Example:

Process:

powershell.exe

AND

Command contains:

-EncodedCommand

AND

Parent process:

winword.exe

Detection:

Possible malicious document execution

Related Guide: Step-by-Step: Custom Wazuh Sysmon Rules Guide

Firewall and IDS Logs

Firewall and IDS systems provide network visibility.

Common integrations include:

  • Suricata
  • OPNsense
  • Palo Alto
  • Cisco
  • Fortinet
  • pfSense

Custom rules can detect:

  • Port scans
  • Malware communication
  • Suspicious outbound connections
  • Exploit attempts

Example:

Suricata alert

+

Internal host connection

+

Known malicious IP

Detection:

Possible malware infection

Related Guide: How to Integrate Wazuh with Suricata for Better Threat Detection

Cloud Audit Logs

Cloud providers generate extensive JSON audit data.

Examples:

  • AWS CloudTrail
  • Azure Activity Logs
  • Google Cloud Audit Logs

Custom rules can detect:

  • IAM privilege changes
  • Disabled logging
  • Suspicious API usage
  • Unusual regions
  • New access keys

Example:

{
 "eventName":"CreateUser",
 "user":"admin"
}

Detection:

Unexpected cloud account creation

Related Guide: How to Monitor AWS CloudTrail Logs Using Wazuh

Kubernetes Audit Events

Kubernetes environments generate detailed audit logs.

Custom rules can detect:

  • Privileged container creation
  • Secret access
  • Unauthorized deployments
  • Role changes
  • API abuse

Example:

{
 "verb":"create",
 "resource":"pods",
 "namespace":"production"
}

Detection:

New workload created in production namespace

Related Guide: How to Monitor Kubernetes Using Wazuh


Organizing Custom Rules and Decoders

As your Wazuh deployment grows, maintaining hundreds or thousands of custom rules and decoders becomes a major operational challenge.

A structured organization strategy improves:

  • Troubleshooting
  • Collaboration
  • Version control
  • Upgrades
  • Documentation
  • Long-term maintenance

Directory Structure

A common organization approach is separating custom content by function.

Example:

wazuh/
│
├── decoders/
│   ├── applications.xml
│   ├── cloud.xml
│   ├── firewall.xml
│   └── custom-auth.xml
│
├── rules/
│   ├── authentication.xml
│   ├── malware.xml
│   ├── cloud.xml
│   └── compliance.xml
│
└── documentation/
    ├── detection-notes.md
    └── changelog.md

This structure makes it easier to locate and update specific detection logic.

local_decoder.xml

local_decoder.xml is commonly used for custom decoder definitions.

Advantages:

  • Preserved during upgrades
  • Separate from vendor content
  • Easy to back up
  • Simple to test

Custom decoders should avoid modifying built-in decoder files because updates may overwrite changes.

local_rules.xml

local_rules.xml is commonly used for custom rules.

It allows administrators to:

  • Add organization-specific detections
  • Override existing behavior
  • Create new alerts
  • Customize severity levels

Keeping custom rules separate improves upgrade safety.

Splitting Large Rule Files

Large environments should avoid placing thousands of rules into a single file.

Instead, organize by category:

rules/
|
├── authentication_rules.xml
├── malware_rules.xml
├── sysmon_rules.xml
├── cloud_rules.xml
└── compliance_rules.xml

Benefits:

  • Faster troubleshooting
  • Easier reviews
  • Better collaboration
  • Cleaner version history

Naming Conventions

Consistent naming improves maintainability.

Recommended practices:

Use descriptive names:

Good:

custom_cloudtrail_rules.xml

Poor:

rules2.xml

For dynamic fields:

Good:

customer_id

api_risk_score

tenant_name

Avoid:

field1

custom_value

Clear naming reduces confusion when detections become complex.

Version Control

Custom rules and decoders should be stored in version control systems such as Git.

Benefits include:

  • Change tracking
  • Rollback capability
  • Code review
  • Team collaboration
  • Audit history

A mature workflow treats detection logic similarly to application code:

Create Change

↓

Review

↓

Test

↓

Deploy

↓

Monitor

Documentation

Every custom rule and decoder should include documentation explaining:

  • Purpose
  • Log source
  • Detection logic
  • Expected behavior
  • False-positive considerations
  • Owner
  • Creation date
  • Testing results

Example:

Rule Name:
Suspicious Admin Login

Purpose:
Detect unexpected administrator authentication.

Source:
Custom VPN logs.

False Positives:
Approved maintenance windows.

Response:
Investigate source IP.

Good documentation prevents detection knowledge from being lost when team members change roles.

Backup Strategy

Custom Wazuh content should be included in regular backups.

Important files include:

  • Custom decoder files
  • Custom rule files
  • Configuration files
  • Integration scripts
  • Active Response scripts
  • Documentation

Recommended backup practices:

  • Store configurations in Git.
  • Maintain offline backups.
  • Test restoration procedures.
  • Document deployment steps.

A backup strategy ensures that carefully developed detection logic can be recovered after system failures, migrations, or upgrades.


Common Mistakes When Creating Wazuh Rules and Decoders

Creating custom Wazuh rules and decoders requires careful planning.

Small mistakes in XML syntax, field extraction, rule logic, or pattern matching can prevent detections from working correctly or create unnecessary alert noise.

Understanding the most common problems helps security teams build reliable detection content and troubleshoot issues faster.

Incorrect Regex

Regular expressions are one of the most common sources of decoder failures.

A decoder may fail because:

  • The pattern does not match the actual log format.
  • Special characters are not escaped correctly.
  • Capture groups are missing.
  • The regex is too broad.
  • The regex expects fields in the wrong order.

Example log:

LOGIN user=admin ip=192.168.1.10 status=failed

Incorrect regex:

user=(.*) status=(.*)

This may capture unexpected values if additional fields appear later.

A more precise pattern:

user=(\S+) ip=(\S+) status=(\S+)

Good decoder design focuses on predictable patterns instead of attempting to match every possible variation with one complex expression.

Testing regex patterns with wazuh-logtest before deployment prevents many parsing issues.

Related Guide: How to Use Wazuh Logtest

Decoder Never Matching

A decoder that never matches prevents every rule built on top of it from working.

Common causes include:

  • Incorrect prematch values.
  • Wrong program_name.
  • Decoder stored in the wrong location.
  • XML syntax problems.
  • Incorrect parent decoder reference.
  • Log format differs from the expected sample.

A troubleshooting workflow:

  1. Copy the exact raw log.
  2. Test it using wazuh-logtest.
  3. Check the pre-decoding output.
  4. Verify the decoder name.
  5. Review extracted fields.

The first question should always be:

“Is Wazuh decoding this event correctly?”

If the decoder fails, rule troubleshooting will not solve the problem.

Rule IDs Conflicting

Every Wazuh rule requires a unique ID.

Duplicate IDs can cause:

  • Rules being ignored.
  • Unexpected matches.
  • Difficult troubleshooting.
  • Upgrade conflicts.

Example:

<rule id="100500">

If another rule uses:

<rule id="100500">

Wazuh cannot reliably determine which rule should execute.

Best practices:

  • Maintain a dedicated custom rule ID range.
  • Document assigned IDs.
  • Avoid copying IDs from examples.
  • Use version control to track changes.

Related Guide: How to Safely Overwrite Local Rule IDs Without Wazuh Conflicts

Missing Field References

Rules depend on fields extracted by decoders.

A common mistake is creating a rule that references fields that do not exist.

Example rule:

field:

customer_role

equals:

administrator

However, the decoder only extracts:

username

srcip

status

The rule will never match.

Before writing rules:

  1. Confirm decoder output.
  2. Identify available fields.
  3. Reference only extracted values.
  4. Test with realistic events.

Dynamic fields are especially prone to spelling mistakes because custom names are not validated automatically.

Incorrect Rule Order

Wazuh evaluates rules according to rule relationships and processing logic.

Poor ordering can cause:

  • Generic rules matching before specific rules.
  • Child rules never executing.
  • Unexpected severity levels.

Example:

Incorrect approach:

Rule 1:

Any PowerShell execution

Level 10


Rule 2:

Malicious encoded PowerShell

Level 14

The broad rule may prevent the more specific detection from providing the correct classification.

Better approach:

General Detection

↓

Specific Detection

↓

High Confidence Alert

Organizing rules from broad conditions to increasingly specific logic improves accuracy.

XML Syntax Errors

Wazuh rules and decoders use XML formatting, making syntax errors common.

Examples:

Incorrect:

<rule id="100500">

<description>
Test Rule
</rule>

Correct:

<rule id="100500">

<description>
Test Rule
</description>

</rule>

Common XML problems include:

  • Missing closing tags
  • Invalid characters
  • Incorrect nesting
  • Duplicate attributes
  • Malformed XML comments

Always validate XML before restarting the Wazuh manager.

Poor Rule Performance

Poorly designed rules can impact Wazuh manager performance.

Common performance problems include:

  • Extremely complex regex expressions.
  • Matching every incoming log.
  • Excessive event correlation.
  • Large numbers of unnecessary rules.
  • Broad wildcard matching.

A rule that processes millions of irrelevant events wastes CPU resources and slows detection.

Good detection engineering focuses on:

  • Narrow matching conditions.
  • Efficient expressions.
  • Relevant data sources.
  • Proper filtering.

Excessive False Positives

False positives reduce trust in security monitoring.

Common causes include:

  • Overly broad detection logic.
  • Missing exclusions.
  • Incorrect severity levels.
  • Ignoring normal administrative behavior.

Example:

Poor rule:

Detect every PowerShell execution

Better rule:

Detect PowerShell execution

AND

Encoded command

AND

External network connection

High-quality detections focus on suspicious combinations of behavior rather than individual events.


Performance Best Practices

Large Wazuh environments may process millions of events daily. Poorly designed rules and decoders can increase CPU usage, slow alert processing, and make investigations more difficult.

Performance optimization should be considered during detection development, not after problems appear.

Optimize Regular Expressions

Regular expressions directly affect decoder performance.

Poor regex patterns may cause excessive processing time, especially when applied to high-volume logs.

Avoid:

  • Nested wildcards.
  • Extremely broad matches.
  • Multiple unnecessary capture groups.

Example:

Slow:

.*user=.*status=.*.*

Better:

user=(\S+)\sstatus=(\S+)

Recommended practices:

  • Anchor patterns when possible.
  • Match fixed text first.
  • Capture only required values.
  • Avoid unnecessary complexity.

Reduce Decoder Complexity

A decoder should perform one specific parsing task.

Avoid creating a single decoder responsible for:

  • Multiple unrelated applications.
  • Hundreds of log formats.
  • Complex conditional parsing.

Instead:

Application Decoder

↓

Authentication Decoder

↓

Authorization Decoder

↓

API Decoder

Smaller decoders are easier to test, maintain, and optimize.

Limit Rule Correlation Windows

Correlation rules are powerful but expensive.

Example:

100 failed logins

within

24 hours

This requires Wazuh to maintain event history for a large period.

Better:

10 failed logins

within

5 minutes

Use the smallest practical timeframe that accurately represents suspicious behavior.

Minimize Expensive Matching

Some operations require more processing than others.

Avoid:

  • Applying complex regex to every log.
  • Matching unnecessary fields.
  • Creating rules without filtering conditions.

Better design:

Check application name

↓

Check event type

↓

Run detailed matching

Filtering early reduces workload.

Tune Alert Severity

Not every detection deserves a high severity level.

Incorrect severity tuning causes:

  • Alert fatigue.
  • Poor prioritization.
  • Increased analyst workload.

Examples:

Low severity:

  • Successful administrative login.

Medium severity:

  • Multiple failed authentication attempts.

High severity:

  • Credential dumping detected.

Critical severity:

  • Active ransomware behavior.

Severity should represent actual risk, not simply the presence of suspicious activity.

Monitor Manager Performance

After deploying custom rules and decoders, monitor Wazuh manager health.

Important metrics include:

  • CPU usage.
  • Memory consumption.
  • Event processing latency.
  • Alert generation rate.
  • Queue utilization.
  • Decoder performance.

Performance problems often appear after adding:

  • Large rule sets.
  • Complex regex.
  • High-volume integrations.
  • Excessive correlation rules.

Regular monitoring helps identify problematic detection logic before it affects the entire platform.


Troubleshooting Wazuh Rules and Decoders

When custom detections fail, troubleshooting should follow the same order as Wazuh’s processing pipeline.

The correct approach is:

Log Collection

↓

Decoder

↓

Extracted Fields

↓

Rule Matching

↓

Alert

↓

Dashboard

Troubleshooting the wrong stage often leads to wasted time.

Decoder Does Not Match

If the decoder does not match, rules cannot trigger.

Check:

  • Is the log reaching Wazuh?
  • Does pre-decoding identify the correct program?
  • Does the prematch expression match?
  • Are regex capture groups correct?
  • Is the decoder loaded?

Use:

wazuh-logtest

to verify decoder behavior.

Common fixes:

  • Correct the regex.
  • Adjust the prematch.
  • Fix parent decoder relationships.
  • Reload Wazuh manager services.

Related Guide: Wazuh Decoder Guide

Rule Never Fires

If decoding works but alerts do not appear, investigate the rule.

Common causes:

  • Incorrect field references.
  • Wrong rule ID relationships.
  • Missing conditions.
  • Incorrect severity configuration.
  • Rule file not loaded.

Troubleshooting steps:

  1. Confirm decoder fields.
  2. Check rule matching in wazuh-logtest.
  3. Verify rule XML syntax.
  4. Restart Wazuh manager.
  5. Generate a fresh event.

XML Validation Errors

Invalid XML prevents rules and decoders from loading.

Common errors:

  • Missing closing tags.
  • Invalid attributes.
  • Incorrect nesting.
  • Unsupported characters.

Check Wazuh manager logs after configuration changes.

Always validate changes before restarting production services.

JSON Fields Missing

JSON parsing problems are common with:

  • Nested objects.
  • Arrays.
  • Changing application schemas.
  • Incorrect field paths.

Example:

Expected:

{
"user":{
"name":"alice"
}
}

But rule expects:

username

The field names do not match.

Solutions:

  • Verify actual JSON structure.
  • Update field references.
  • Use dynamic fields correctly.
  • Test with real samples.

Related Guide: How to Parse Flattened Nested Keys and Arrays in Wazuh JSON Logs

Duplicate Rule IDs

Duplicate IDs create unpredictable behavior.

Check:

  • Custom rule files.
  • Imported rules.
  • Recently added detections.

Maintain an inventory of assigned IDs to prevent conflicts.

High CPU Usage

High CPU after adding rules or decoders usually indicates:

  • Inefficient regex.
  • Too many correlation rules.
  • Excessive log volume.
  • Broad matching conditions.

Solutions:

  • Optimize patterns.
  • Reduce unnecessary rules.
  • Filter irrelevant events.
  • Review high-volume integrations.

Related Guide: Why Is Wazuh Using High CPU? Troubleshooting Guide

Alerts Not Appearing in the Dashboard

If rules trigger but alerts are missing from the Dashboard, investigate later stages of the pipeline.

Check:

  • Wazuh manager alert files.
  • Filebeat connectivity.
  • Indexer status.
  • Dashboard index patterns.
  • Authentication permissions.

The event may exist but fail during indexing or visualization.

Related Guide: Wazuh Dashboard Not Loading? Complete Troubleshooting Guide

False Positives

When a rule generates too many alerts:

Analyze:

  • Which fields are causing matches.
  • Whether trusted systems need exclusions.
  • Whether severity is appropriate.
  • Whether correlation should be added.

Common tuning methods:

  • Add exceptions.
  • Require multiple conditions.
  • Increase thresholds.
  • Narrow the detection scope.

Effective Wazuh deployments continuously tune rules based on operational experience and analyst feedback.

A detection that is accurate today may require adjustment as infrastructure, applications, and attacker techniques evolve.


Related Wazuh Guides

Building effective custom Wazuh rules and decoders is an ongoing process that involves parsing new log sources, improving detection logic, reducing false positives, and troubleshooting issues as your environment changes.

The following guides expand on the concepts covered in this article and provide deeper walkthroughs for specific Wazuh customization tasks.

Wazuh Decoder Guide — Complete Guide to Building Custom Decoders

Decoders are the foundation of custom detection engineering in Wazuh.

Before a rule can identify suspicious activity, Wazuh must first understand the structure of the incoming log data.

The Wazuh Decoder Guide covers:

  • How decoder processing works.
  • Creating custom decoder XML files.
  • Using regex-based extraction.
  • Working with parent and child decoders.
  • Extracting static and dynamic fields.
  • Troubleshooting decoder matching failures.

If you are working with unsupported log formats or proprietary applications, this guide provides the foundation needed to build reliable parsing logic.

How to Use Wazuh Logtest — Validate Rules and Decoders Before Deployment

Testing detection logic before production deployment prevents broken decoders, missed alerts, and unnecessary false positives.

The Wazuh Logtest Guide explains how to:

  • Submit sample logs for testing.
  • Verify decoder matches.
  • Review extracted fields.
  • Confirm rule execution.
  • Debug failed detections.

Using wazuh-logtest should become part of every custom detection workflow because it allows administrators to validate changes without waiting for real security events.

How to Use Wazuh Dynamic Fields to Extract Custom Log Data

Many organizations generate logs containing information that does not fit into Wazuh’s default field structure.

Dynamic fields allow security teams to extract custom values such as:

  • Customer IDs.
  • Transaction identifiers.
  • API endpoints.
  • Device fingerprints.
  • Application-specific metadata.
  • Risk scores.

The Wazuh Dynamic Fields Guide explains how to transform proprietary application logs into searchable, actionable security data.

How to Map Complex Log Fields Using Wazuh Parent Child Rules

Large environments often contain many related log formats that share common structures.

Parent-child decoder relationships allow administrators to create scalable parsing architectures by separating:

  • Common log identification logic.
  • Specific event extraction.
  • Application-specific parsing.

This approach reduces duplicated XML, improves maintainability, and simplifies future expansion.

How to Parse Flattened Nested Keys and Arrays in Wazuh JSON Logs

Modern applications, cloud services, and APIs frequently generate complex JSON logs containing:

  • Nested objects.
  • Arrays.
  • Dynamic structures.
  • Multiple levels of metadata.

This guide explains how to handle complex JSON parsing scenarios and ensure important fields become available for detection rules.

Step-by-Step: Custom Wazuh Sysmon Rules Guide

Windows environments generate some of the richest security telemetry through Sysmon.

Custom Sysmon rules allow Wazuh to detect advanced behaviors such as:

  • Suspicious PowerShell activity.
  • Process injection.
  • Credential dumping.
  • DLL loading anomalies.
  • Malicious parent-child process relationships.

This guide explains how to build Windows endpoint detections using Sysmon events and Wazuh rules.

Wazuh Brute Force Detection Guide

Authentication attacks are among the most common security events organizations monitor.

Custom Wazuh rules can identify:

  • SSH brute-force attacks.
  • RDP password attacks.
  • Web application login abuse.
  • Password spraying attempts.
  • Repeated authentication failures.

The Wazuh Brute Force Detection Guide demonstrates how to combine decoders, frequency conditions, and correlation rules to detect credential attacks.

Troubleshooting wazuh-logtest: Why Alerts Are Missing from JSON Output

Sometimes a decoder appears to work, but expected JSON output or alerts are missing.

This troubleshooting guide covers:

  • Missing extracted fields.
  • Decoder matching problems.
  • Rule evaluation issues.
  • JSON formatting problems.
  • Testing workflow mistakes.

It provides practical solutions for diagnosing detection development issues.

How to Safely Overwrite Local Rule IDs Without Wazuh Conflicts

As custom detection libraries grow, rule ID management becomes increasingly important.

This guide explains how to:

  • Avoid duplicate rule IDs.
  • Safely customize existing detections.
  • Maintain upgrade compatibility.
  • Organize local rule modifications.

Proper rule ID management prevents unexpected behavior and makes large Wazuh deployments easier to maintain.

How to Fix “Field Already Defined” Syntax Errors in Wazuh Decoders

Decoder syntax issues are among the most common problems encountered when creating custom parsing logic.

This guide explains how to troubleshoot:

  • Duplicate field definitions.
  • Invalid decoder syntax.
  • XML configuration mistakes.
  • Field extraction conflicts.

Understanding these issues helps administrators build cleaner and more reliable decoder configurations.


Frequently Asked Questions

 

Question: What Is the Difference Between Wazuh Rules and Decoders?

Decoders extract structured information from raw logs, while rules analyze that extracted information to determine whether an event should generate an alert.

A decoder answers:

“What data exists in this log?”

A rule answers:

“Does this data represent suspicious activity?”

Both components work together to transform raw events into actionable security detections.

Question: Do I Need a Custom Decoder Before Creating a Custom Rule?

Not always.

If Wazuh already understands the log format and extracts the required fields, you can create a custom rule directly.

However, if the required information does not exist in the decoded event, you must create or modify a decoder first.

A common workflow is:

Unknown Log Format

↓

Create Decoder

↓

Extract Fields

↓

Create Rule

↓

Generate Alert

Question: Where Are Custom Rules and Decoders Stored?

Custom rules are commonly stored in:

/var/ossec/etc/rules/

Custom decoders are commonly stored in:

/var/ossec/etc/decoders/

Many administrators use:

  • local_rules.xml
  • local_decoder.xml

to keep custom configurations separate from the default Wazuh ruleset.

This separation prevents customizations from being overwritten during upgrades.

Question: How Do I Test a Decoder Without Restarting Wazuh?

Use:

wazuh-logtest

This utility allows you to test:

  • Decoder matching.
  • Extracted fields.
  • Rule execution.
  • Alert generation.

It is the preferred method for validating detection logic before production deployment.

Question: Can Wazuh Decode JSON Logs Automatically?

Yes.

Wazuh supports native JSON decoding for many structured log formats.

However, custom work may still be required when:

  • Fields are nested.
  • Applications use proprietary schemas.
  • Important values require transformation.
  • Arrays contain detection-relevant data.

Question: What Are Dynamic Fields in Wazuh?

Dynamic fields are custom fields extracted from logs that are not part of Wazuh’s predefined field structure.

Examples include:

  • Customer IDs.
  • API actions.
  • Risk scores.
  • Application-specific values.
  • Tenant information.

They allow organizations to build detections around unique business and application data.

Question: How Do I Prevent Rule ID Conflicts?

Prevent rule ID conflicts by:

  • Reserving a custom rule ID range.
  • Documenting assigned IDs.
  • Using version control.
  • Avoiding direct modifications to default rules.
  • Reviewing new rules before deployment.

A consistent rule management process becomes increasingly important as custom detections grow.

Question: Why Is My Custom Rule Not Generating Alerts?

Common causes include:

  • The decoder is not matching.
  • Required fields are missing.
  • The rule conditions are incorrect.
  • The rule file was not loaded.
  • XML syntax errors exist.
  • The event does not meet frequency requirements.

Start troubleshooting with wazuh-logtest to determine whether the issue occurs during decoding or rule evaluation.

Question: How Do I Reduce False Positives in Custom Rules?

Reduce false positives by:

  • Adding more specific conditions.
  • Using multiple fields.
  • Adding frequency thresholds.
  • Excluding trusted systems.
  • Correlating multiple events.
  • Adjusting severity levels.

The goal is not to detect every possible event, but to detect meaningful security behavior.

Question: What Is the Best Way to Organize Large Collections of Custom Rules?

Large Wazuh deployments should organize rules by:

  • Detection category.
  • Data source.
  • Application.
  • Security framework.
  • Business purpose.

Recommended practices include:

  • Splitting large XML files.
  • Using descriptive names.
  • Maintaining documentation.
  • Storing files in Git.
  • Testing changes before deployment.

A structured detection library makes troubleshooting and future expansion significantly easier.


Conclusion

Custom Wazuh rules and decoders are the foundation of building a detection platform tailored to your organization’s environment.

Decoders transform raw logs into structured security data by extracting important fields such as usernames, IP addresses, processes, API actions, and application metadata.

Rules then evaluate those fields to identify suspicious behavior, generate alerts, map detections to security frameworks, and trigger automated responses.

Creating effective detection content requires more than writing XML. Successful Wazuh customization depends on:

  • Designing accurate decoders.
  • Creating focused detection rules.
  • Testing changes with wazuh-logtest.
  • Organizing custom XML files properly.
  • Managing rule IDs carefully.
  • Monitoring performance.
  • Continuously tuning detections to reduce false positives.

As environments become more complex, custom rules and decoders allow Wazuh to monitor everything from traditional infrastructure to cloud platforms, Kubernetes environments, custom applications, and advanced endpoint telemetry.

Continue expanding your Wazuh detection capabilities by exploring the supporting guides in this series.

These resources cover advanced decoder design, dynamic field extraction, JSON parsing, Sysmon detection engineering, brute-force monitoring, and troubleshooting techniques needed to build production-ready Wazuh deployments.

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *