PL EN
WB-C7415F47TLP:CLEARWazuh 4

Wazuh 4 training, part 6: rules

Wazuh 4 training part 6: levels 0-16, groups, rule syntax, overriding rule 5706, a custom rule family with correlation and a rule with a time window.

Part six of the Wazuh 4 training builds on the decoders from part 5: the decoder extracts fields from an event, and the rule decides whether an alert is created and how important it is. The three exercises cover overriding a built-in rule, a family of custom rules with correlation, and a rule that depends on the time of day, based on the Wazuh 4.14 documentation and the rule file 0095-sshd_rules.xml from release 4.14.0.

Rule levels

The level is a number from 0 to 16 and, according to the documentation, it expresses the severity of the alert created when the rule conditions are met. No default rule uses level 16, and the documentation reserves it for custom rules of the highest severity.

LevelName in the documentationMeaning
0Ignoredno action, used to avoid false positives; these rules are scanned before all others and do not appear in the security events dashboard
1Low relevance informationevents of very low relevance, context or a base for other rules, for example rule 5754
2System low priority notificationsystem and status messages with no security relevance
3Successful/Authorized eventssuccessful logins, firewall allow events
4System low priority errorerrors from bad configuration or unused devices and applications
5User generated errormistyped passwords, denied actions, no relevance on their own
6Low relevance attacka worm or virus with no effect on the system, frequent IDS events and frequent errors
7“Bad word” matchingevents containing words such as “bad” or “error”, usually unclassified
8First time seenthe first IDS event, the first login of a user, a sniffer being activated
9Error from invalid sourcelogin to an unknown account or from an invalid source, errors on the “admin” (root) account
10Multiple user generated errorsmultiple bad passwords and failed logins
11Integrity checking warningmodification of binaries, rootkits detected by Rootcheck
12High importance eventerror or warning messages from the system and kernel
13Unusual error (high importance)most often matches a known attack pattern
14High importance security eventusually the result of correlation, indicates an attack
15Severe attackno chance of a false positive, needs immediate attention
16Maximum severitythe highest allowed level, reserved for custom rules

Level 1 is below the default alerting threshold: log_alert_level is 3, so such events do not create alerts until you lower the threshold. According to the log data analysis page, the server generates alerts by default for every rule with a level above 2. The threshold and its interaction with e-mail are described in the post on rule levels and alert thresholds.

Rule groups

The documentation requires every rule to belong to at least one group. Groups organize alerts and let you filter them in the dashboard, for example with the query rule.groups: attack or rule.groups: (syscheck OR syslog). The default ruleset uses groups such as syscheck, attack and syslog.

A group is set in two ways. The first is a group element with the name attribute wrapping the rule definitions, the second is a group element inside the rule itself, which adds more groups:

<group name="limits,">
  <rule id="100234" level="3">
    <if_sid>230</if_sid>
    <field name="alert_type">normal</field>
    <description>The file limit set for this agent is $(file_limit). Now, $(file_count) files are being monitored.</description>
    <group>syscheck,fim_db_state,</group>
  </rule>
</group>

All examples in the documentation end the group list with a comma, including the list in the element inside the rule. I use the same convention. Groups also work as a condition: the if_group and if_matched_group options tie a rule to rules that matched the given group earlier.

Rule syntax

A rule starts with the rule element. Its attributes have exactly described ranges in the documentation:

AttributeValuesMeaning
level0 to 16rule level, used by alerts and responses
id1 to 999999rule identifier
maxsize1 to 9999maximum size of the event
frequency2 to 9999number of matches after which the rule generates an alert
timeframe1 to 99999window in seconds, used together with frequency
ignore1 to 999999time in seconds during which the rule is ignored after it fires (flood protection)
overwriteyes, noreplace an existing rule with the local version
noalert0 or 1the value 1 disables the alert, but the event is still evaluated by other rules

The example from the documentation combines four of them: rule 50180 has level 10, frequency="8", timeframe="120" and ignore="60", so it alerts after eight matches of rule 50125 within 120 seconds and is skipped for the next 60 seconds.

The documentation tells you to pick custom rule IDs from the range 100000 to 120000 to avoid conflicts with the rules shipped with Wazuh. Small changes go to /var/ossec/etc/rules/local_rules.xml, and for larger changes the vendor recommends separate files in the /var/ossec/etc/rules/ directory.

Match conditions

Conditions inside a rule combine as a conjunction: the rule fires when all of them are met. Most elements compare a regular expression with one field of the event.

ElementWhat it compares
matchan expression against the event content, default type osmatch (sregex)
regexthe same, but the default type is osregex
decoded_asthe name of the decoder that processed the event
categorythe decoder type
fieldthe content of a field extracted by the decoder, name in the name attribute
srcip, dstipthe IP address from the srcip and dstip fields
srcport, dstportthe port from the srcport and dstport fields
user, data, extra_data, id, url, action, status, protocol, system_namethe value of the field with the same name
program_name, hostname, locationa value already set at the pre-decoding stage
srcgeoip, dstgeoipsource and destination GeoIP location
timeevent time according to the Wazuh server clock
weekdayday of the week according to the Wazuh server clock

The match, regex, field, user elements and the other elements that compare expressions accept two optional attributes. negate (no or yes, default no) inverts the match, and type selects the expression engine: osmatch, osregex or pcre2. The documentation gives an example with negation: <user negate="yes">wazuh|root</user> in a rule based on the authentication_success group matches the login of any user except wazuh and root. When the same element appears in a rule several times, the values are concatenated into one, and the attributes are taken from the last occurrence.

The time element accepts ranges in four notations: hh:mm-hh:mm, hh:mm am-hh:mm pm, hh-hh and hh am-hh pm. The reference example is 6 pm - 8:30 am. The weekday element accepts monday to sunday as well as weekdays and weekends. The documentation repeats for both: the server time is checked, not the event timestamp, so the local server time must be set correctly.

Dependencies and correlation

Rules form a tree. A child rule points to its parent with one of these elements:

ElementCondition
if_sidthe event previously matched one of the rules on the list, IDs separated by commas or spaces
if_groupthe event previously matched a rule from the given group
if_levelthe event previously triggered the given level, from 1 to 16
if_matched_sidan alert with the given ID was raised within a set time, used with frequency and timeframe
if_matched_groupan alert from the given group was raised within a set time, used with frequency and timeframe

The documentation compares if_sid to a child decoder, with one difference: an alert can have as many descendants as needed, while decoders have no “grandchildren”. A note on if_matched_sid: level 0 rules are discarded immediately and are not suitable as the target of this option. The correlated rule must have a level of at least 1, and to keep it out of the logs you add the no_log option to it.

Correlation is extended by modifiers that match properties of events within the window. Each works together with frequency and timeframe:

Element pairRequired property
same_srcip, different_srcipthe same or a different source IP address
same_dstip, different_dstipthe same or a different destination IP address
same_srcport, different_srcportthe same or a different source port
same_dstport, different_dstportthe same or a different destination port
same_user, different_userthe same or a different user
same_srcuser, different_srcuserthe same or a different source user
same_id, different_idthe same or a different id field
same_location, different_locationthe same or a different event location
same_protocol, same_action, same_data, same_extra_data, same_status, same_system_name, same_urlthe same field value, with different_* counterparts
same_srcgeoip, same_dstgeoipthe same GeoIP location, with different_* counterparts
same_field, different_fieldthe same or a different dynamic field, field name in the element body

The older labels same_source_ip and not_same_source_ip are deprecated and work as aliases of same_srcip and different_srcip. The rule file 0095-sshd_rules.xml from tag v4.14.0 still uses same_source_ip in rule 5712, so you will meet both spellings in the shipped ruleset. For static fields (user, srcip, dstip and similar) use the dedicated elements, because same_field works only with dynamic fields.

By default the frequency counter counts events from one agent. The global_frequency element extends it to events from all agents, but the documentation notes that despite the name it works at the manager level, not at the cluster level.

Other rule elements

ElementEffect
descriptionalert description; multiple elements are concatenated, and decoder fields are inserted with the $(field_name) syntax
optionsone element per option: alert_by_email, no_email_alert, no_log, no_full_log, no_counter
infoextra information, type attribute: text (default), link, cve, ovsdb
mitreMITRE ATT&CK technique IDs in id elements
check_diffdetects a change in command output
listCDB list lookup, attributes field, lookup and check_value
vara variable available in the whole rule file, defined at its top level

The no_counter option omits the rule.firedtimes field from the JSON alert, and no_full_log omits full_log. The BAD_WORDS variable is a typical use of the var element: <var name="BAD_WORDS">error|warning|failure</var>, and a rule refers to it with <match>$BAD_WORDS</match>. CDB lists are covered in part 9 of the series.

Load and evaluation order

The documentation states two ordering rules explicitly. The rules directory from the rule_dir element is loaded in alphabetical order, and files with a repeated name are skipped. The default rule_dir value is ruleset/rules, and the pattern attribute selects files with a regular expression. The second rule comes from the level classification: level 0 rules are scanned before all the others. The example block from the documentation:

<ruleset>
  <rule_include>ruleset/rules/my_rules.xml</rule_include>
  <rule_dir pattern="_rules.xml$">ruleset/rules</rule_dir>
  <rule_exclude>0215-policy_rules.xml</rule_exclude>
</ruleset>

Log analysis goes through three phases: pre-decoding, decoding and rule matching. In the documentation example the sshd-success decoder from 0310-ssh_decoders.xml extracts the user, address and port, and rule 5715 matches the entry and creates an alert, because its level 3 exceeds the threshold. The /var/ossec/ruleset/ directory is overwritten on upgrade, so I keep my own files in /var/ossec/etc/rules/. Loading details are described in the post on ruleset loading.

Exercise 1: changing the level of a built-in rule

Rule 5706 detects an SSH connection attempt that sends no identification string and, according to 0095-sshd_rules.xml from tag v4.14.0, has level 6. The task is to raise the level to 7 so that Wazuh upgrades do not undo the change. As the documentation describes, I copy the definition to /var/ossec/etc/rules/local_rules.xml, change level and add overwrite="yes":

<group name="syslog,sshd,">
  <rule id="5706" level="7" overwrite="yes">
    <if_sid>5700</if_sid>
    <match>Did not receive identification string from</match>
    <description>sshd: insecure connection attempt (scan).</description>
    <mitre>
      <id>T1021.004</id>
    </mitre>
    <group>gdpr_IV_35.7.d,gpg13_4.12,nist_800_53_SI.4,pci_dss_11.4,recon,tsc_CC6.1,tsc_CC6.8,tsc_CC7.2,tsc_CC7.3,</group>
  </rule>
</group>

Two details decide success. First: on overwrite the if_sid, if_group, if_level, if_matched_sid and if_matched_group elements are ignored and the original value applies, so you cannot move the rule in the tree this way. Second: I copy the definition from the installed version’s file, not from the documentation page. The page on custom rules shows an example of rule 5710 in an older form (one MITRE identifier and a different group order than in the 4.14.0 file), and an overwrite replaces the rule as a whole, so a copy from the page would bring back the older fields.

Test in the dashboard under Tools > Ruleset test, or in a terminal with /var/ossec/bin/wazuh-logtest. The test event:

Jun 26 09:51:26 agent-01 sshd[21487]: Did not receive identification string from 198.51.100.7

In phase 3 I should see rule 5706 with level 7. Each logtest session has its own set of rules and decoders and its own firedtimes counter, so after changing the files I open a new session (a recommendation). The documentation notes that saving the file is enough for the test, but alerts with the new level value appear only after a manager restart:

# Restart the manager to generate alerts from the changed rules
sudo systemctl restart wazuh-manager

Exercise 2: a family of custom rules

Events of the example application example-app have four shapes. All four go through one decoder, and the rules tell them apart by fields and content:

Dec  4 17:07:01 agent-01 example-app: Accepted password for user example-user, IP: 192.0.2.10
Dec  4 17:07:01 agent-01 example-app: Failed password for user example-user, IP: 192.0.2.10
Dec  4 17:07:01 agent-01 example-app: Application is shutting down: Internal error
Dec  4 17:07:01 agent-01 example-app: DEBUG: Received OK.

The decoder is the subject of part 5. A pair is enough here: a parent decoder on program_name and a child decoder extracting three fields (result, user, srcip) with the order element. The program_name, parent, regex and order elements appear in the sshd decoders in the log data analysis documentation. I save the decoder in /var/ossec/etc/decoders/local_decoder.xml:

<decoder name="example-app">
  <program_name>^example-app</program_name>
</decoder>

<decoder name="example-app-auth">
  <parent>example-app</parent>
  <regex>^(\w+) password for user (\w+), IP: (\S+)</regex>
  <order>result,user,srcip</order>
</decoder>

I arrange the rules as a tree. The parent has level 0 and always matches events of the decoder, so its children get the event to evaluate, and it creates no alert itself. The children have rising levels depending on the weight of the event, and the composite rule builds on rule 100101 and counts failures from one address:

<group name="example_app,">
  <rule id="100100" level="0">
    <decoded_as>example-app</decoded_as>
    <description>example-app: parent rule, no alert.</description>
  </rule>

  <rule id="100101" level="5">
    <if_sid>100100</if_sid>
    <field name="result">Failed</field>
    <description>example-app: failed password.</description>
    <group>authentication_failed,</group>
  </rule>

  <rule id="100102" level="3">
    <if_sid>100100</if_sid>
    <field name="result">Accepted</field>
    <description>example-app: accepted password.</description>
    <group>authentication_success,</group>
  </rule>

  <rule id="100103" level="10">
    <if_sid>100100</if_sid>
    <match>Internal error</match>
    <description>example-app: internal error.</description>
  </rule>

  <rule id="100104" level="10" frequency="5" timeframe="60">
    <if_matched_sid>100101</if_matched_sid>
    <same_srcip />
    <description>example-app: multiple failed passwords from one source.</description>
    <group>authentication_failures,</group>
  </rule>
</group>

The fourth line (DEBUG: Received OK.) ends at rule 100100 with level 0, so no alert is created. The third gives a level 10 alert from rule 100103. The first gives level 3 from 100102, and the second level 5 from 100101. Rule 100104 needs the parent to have a level of at least 1, which 100101 (level 5) satisfies. The documentation shows on rule 5712 that frequency of 8 produces an alert on the eighth pasted event, so with frequency="5" the fifth Failed password event from the same address within 60 seconds triggers 100104. The earlier events match 100101, just as in the documentation 5710 matches each of the first seven events before the eighth.

The logtest run is the same as in exercise 1: I paste the four events one at a time, then the same Failed password event five times. The firedtimes counters grow within the session. Session details, CLI options and the API are described in the post on wazuh-logtest, and working with decoders in the post on custom decoders.

Exercise 3: a rule with a time window

An alert should be created when the user example-user logs in over SSH to the host example-finance outside business hours. The base is rule 5715, which in 0095-sshd_rules.xml has level 3, if_sid equal to 5700 and match equal to ^Accepted|authenticated.$. I do not copy it into local_rules.xml, because the child rule refers to it through if_sid. That reference is what makes 5715 the parent:

<group name="local,">
  <rule id="100110" level="12">
    <if_sid>5715</if_sid>
    <time>6 pm - 8 am</time>
    <hostname>example-finance</hostname>
    <user>example-user</user>
    <description>Login to example-finance outside business hours.</description>
    <group>policy_violation,login_time,</group>
  </rule>
</group>

The time condition compares the Wazuh server clock at the moment of analysis, so the timestamp inside the event text does not affect the result. The test needs a range that covers the current server hour. I check the server time with date and pick a range that contains it, for example <time>6 pm - 8 am</time> in the evening. The test event:

Apr 18 19:02:01 example-finance sshd[21488]: Accepted publickey for example-user from 192.0.2.25 port 33030 ssh2

The documentation shows an identical pattern in rule 17101: <time>6 pm - 8:30 am</time> with the authentication_success group. An alternative without a clock is weekday with the value weekends, as in rule 17102.

Checklist after part 6

  • Levels 0 to 16 known, log_alert_level and the threshold of 3 checked in ossec.conf.
  • Rule 5706 copied from the installed version’s file, with overwrite="yes" and level 7, in local_rules.xml.
  • Decoder example-app saved in local_decoder.xml.
  • Rule family 100100 to 100104 with IDs from the range 100000 to 120000.
  • The event DEBUG: Received OK. ends at rule 100100 with no alert.
  • Five repetitions of Failed password from one address trigger 100104.
  • Rule 100110 tested with a time range covering the server time.
  • Manager restarted after the changes, systemctl restart wazuh-manager finished without an error.

Part 7 moves on to file integrity monitoring: the syscheck options, the realtime and whodata modes and FIM events, including the rules that classify them.

What the documentation does not specify

  • The 4.14 documentation does not describe the full algorithm for traversing the rule tree: the order by file name, level and position in the file, and which of the matching rules decides the alert. It confirms only alphabetical loading in rule_dir and scanning of level 0 rules before the others.
  • The documentation does not explain why group lists end with a comma. All examples show it, but the rule is not stated.
  • The page on custom rules shows rule 5710 in an older form than the file from tag v4.14.0. When copying a rule, the file of the installed version applies.
  • The documentation does not describe reloading rules within an open logtest session.

Sources

↑↓ select Enter open Esc close