TExcelTAD
Home › Defensive Security: SOC, SIEM, Detection Engineering & Threat Hunting › A Custom Wazuh Rule and a Simulated Incident

A Custom Wazuh Rule and a Simulated Incident

The lab from the previous lesson collects logs from a Linux server and two Windows machines. Now it needs to detect something specific to this environment and to be used for a real (simulated) incident from first alert to written report. This lesson writes a correlation rule in Wazuh's rule language (SSH success after repeated failures from the same source), tests it with wazuh-logtest, runs an authorised simulated attack in the lab, builds the incident timeline from the alerts in Python, documents the detection, and places Velociraptor in the response toolkit.

How Wazuh rules work

Wazuh evaluates each event in three phases: pre-decoding (syslog header, timestamp, program name), decoding (decoders extract fields such as srcip and srcuser), and rule matching. Rules are XML; each has an id, a level (0–15, where higher means more severe and 0 means "never alert"), conditions, and a description. Rules build on each other: <if_sid> makes a rule a child of another rule (it is only evaluated when the parent matched), and frequency rules count matches over time. The default rule set covers SSH, for example rule 5716 (authentication failed), 5710 (non-existent user) and 5715 (authentication success). Your own rules go into /var/ossec/etc/rules/local_rules.xml with IDs from 100000 upward (the documentation recommends 100000 to 120000), which the default set does not use.

The rule

Two rules: the first fires when one source has five SSH failures within five minutes; the second fires when that source then succeeds within ten minutes, the brute force followed by success pattern.

xml
<!-- /var/ossec/etc/rules/local_rules.xml on wazuh.lab.test -->
<group name="local,sshd,authentication,">
  <rule id="100100" level="10" frequency="5" timeframe="300">
    <if_matched_sid>5716</if_matched_sid>
    <same_source_ip />
    <description>lab: 5 SSH authentication failures from $(srcip) within 5 minutes</description>
    <mitre><id>T1110.001</id></mitre>
  </rule>

  <rule id="100101" level="13" timeframe="600">
    <if_sid>5715</if_sid>
    <if_matched_sid>100100</if_matched_sid>
    <same_source_ip />
    <description>lab: SSH login from $(srcip) after repeated failures: likely guessed password</description>
    <mitre><id>T1110.001</id><id>T1078</id></mitre>
  </rule>
</group>

Rule 100100 counts children of 5716 from the same source; rule 100101 is evaluated for each successful login (5715) and fires only if 100100 fired for the same source address within the last ten minutes. After editing, restart the manager (systemctl restart wazuh-manager) and test.

Testing with wazuh-logtest

wazuh-logtest runs log lines through the decoders and rules without a real event:

console
lab session (wazuh.lab.test; synthetic log lines pasted into the tool)
$ sudo /var/ossec/bin/wazuh-logtest
Starting wazuh-logtest v4.14.x
Type one log per line
Jan 15 10:20:01 web01 sshd[2211]: Failed password for deploy from 10.10.0.66 port 50122 ssh2
**Phase 1: Completed pre-decoding.
        full event: 'Jan 15 10:20:01 web01 sshd[2211]: Failed password for deploy from 10.10.0.66 port 50122 ssh2'
        timestamp: 'Jan 15 10:20:01'
        hostname: 'web01'
        program_name: 'sshd'
**Phase 2: Completed decoding.
        name: 'sshd'
        parent: 'sshd'
        dstuser: 'deploy'
        srcip: '10.10.0.66'
        srcport: '50122'
**Phase 3: Completed filtering (rules).
        id: '5716'
        level: '5'
        description: 'sshd: authentication failed.'
        groups: '['syslog', 'sshd', 'authentication_failed']'
        firedtimes: '1'
        mail: 'False'
        mitre.id: '['T1110']'
        mitre.tactic: '['Credential Access']'
        mitre.technique: '['Brute Force']'
        (compliance mappings such as gdpr, hipaa and pci_dss omitted here)
**Alert to be generated.

Pasting the same line five times in the session (within the timeframe) produces rule 100100 once the count reaches the frequency, on the fifth line here (confirm the count your version needs: that number is exactly what the fixture tests), and an Accepted password for deploy from 10.10.0.66 line afterwards produces 100101. Keep these lines as the rule's test fixtures, alongside a negative: four failures and a success, or failures from one address and a success from another, which must not produce 100101 (Testing Detections).

The simulated incident

Authorisation and scope: written approval from the lab owner (you), scope web01 (10.10.0.10) only, from the lab attacker VM 10.10.0.66, against the lab-only account deploy whose password was deliberately set to a weak value for the exercise, during one agreed hour. The guessing uses a short list of ten candidate passwords; no real credentials anywhere. After the guess succeeds, the "attacker" runs id and sudo -l, downloads a harmless test file from a lab web server and adds a line to deploy's authorized_keys (a common persistence step, using a key generated for the exercise). The alerts the lab produced, extracted from alerts.json (synthetic here, in Wazuh's format, shortened):

python · try it yourself
import json
import pandas as pd

lines = [
    *[f'{{"timestamp":"2026-01-15T10:20:{s:02d}Z","agent":{{"name":"web01"}},"rule":{{"id":"5716","level":5,"description":"sshd: authentication failed."}},"data":{{"srcip":"10.10.0.66","dstuser":"deploy"}}}}'
      for s in (1, 4, 7, 10, 13, 16, 19, 22, 25)],
    '{"timestamp":"2026-01-15T10:20:13Z","agent":{"name":"web01"},"rule":{"id":"100100","level":10,"description":"lab: 5 SSH authentication failures from 10.10.0.66 within 5 minutes"},"data":{"srcip":"10.10.0.66"}}',
    '{"timestamp":"2026-01-15T10:20:28Z","agent":{"name":"web01"},"rule":{"id":"5715","level":3,"description":"sshd: authentication success."},"data":{"srcip":"10.10.0.66","dstuser":"deploy"}}',
    '{"timestamp":"2026-01-15T10:20:28Z","agent":{"name":"web01"},"rule":{"id":"100101","level":13,"description":"lab: SSH login from 10.10.0.66 after repeated failures: likely guessed password"},"data":{"srcip":"10.10.0.66","dstuser":"deploy"}}',
    '{"timestamp":"2026-01-15T10:21:05Z","agent":{"name":"web01"},"rule":{"id":"5402","level":3,"description":"Successful sudo to ROOT executed."},"data":{"srcuser":"deploy","command":"/usr/bin/sudo -l"}}',
    '{"timestamp":"2026-01-15T10:23:40Z","agent":{"name":"web01"},"rule":{"id":"550","level":7,"description":"Integrity checksum changed."},"syscheck":{"path":"/home/deploy/.ssh/authorized_keys","event":"modified"}}',
    '{"timestamp":"2026-01-15T10:02:00Z","agent":{"name":"ws02"},"rule":{"id":"60122","level":5,"description":"Logon Failure - Unknown user or bad password"},"data":{"srcip":"10.10.0.22","dstuser":"erin"}}',
]
a = pd.DataFrame([json.loads(l) for l in lines])
a["time"] = pd.to_datetime(a.timestamp).dt.strftime("%H:%M:%S")
a["agent"] = a.agent.str["name"]
a["rule_id"], a["level"], a["desc"] = a.rule.str["id"], a.rule.str["level"], a.rule.str["description"]
a["detail"] = [d.get("command", d.get("srcip", "")) if isinstance(d, dict) else "" for d in a.data]
a.loc[a.syscheck.notna(), "detail"] = a.syscheck.dropna().str["path"]

# Incident scope: the host of the high-level alert, from the first related event to the last.
trigger = a[a.level >= 12].iloc[0]
inc = a[(a.agent == trigger.agent)].sort_values("time")
print(f"trigger: rule {trigger.rule_id} at {trigger.time} on {trigger.agent}\n")
folded = inc[inc.rule_id == "5716"]
print(f"{folded.time.min()} to {folded.time.max()}  {len(folded)} x 5716 L5 sshd: authentication failed.  [{folded.detail.iloc[0]}]")
for r in inc[inc.rule_id != "5716"].itertuples():
    print(f"{r.time}  {r.rule_id:>6} L{r.level:<2} {r.desc}" + (f"  [{r.detail}]" if r.detail else ""))
print(f"\nunrelated alerts outside the incident: {len(a) - len(inc)} (on {sorted(set(a.agent) - {trigger.agent})})")
trigger: rule 100101 at 10:20:28 on web01

10:20:01 to 10:20:25  9 x 5716 L5 sshd: authentication failed.  [10.10.0.66]
10:20:13  100100 L10 lab: 5 SSH authentication failures from 10.10.0.66 within 5 minutes  [10.10.0.66]
10:20:28    5715 L3  sshd: authentication success.  [10.10.0.66]
10:20:28  100101 L13 lab: SSH login from 10.10.0.66 after repeated failures: likely guessed password  [10.10.0.66]
10:21:05    5402 L3  Successful sudo to ROOT executed.  [/usr/bin/sudo -l]
10:23:40     550 L7  Integrity checksum changed.  [/home/deploy/.ssh/authorized_keys]

unrelated alerts outside the incident: 1 (on ['ws02'])

The program starts from the highest-level alert (100101, level 13) and pulls everything on the same agent into the incident, folding the nine individual failures into one line. Read top to bottom, it is the whole attack in under four minutes: nine failed passwords from 10.10.0.66 starting 10:20:01, the custom rule 100100 at the fifth failure (10:20:13), the successful login at 10:20:28 and rule 100101 on the same second, sudo -l 37 seconds later (the attacker checking what deploy may run as root), and at 10:23:40 the file-integrity monitor reporting that deploy's authorized_keys changed: persistence, a way back in that survives a password reset. The failed Windows logon on ws02 is correctly left out of the incident. What is missing is just as important: the test file download produced no alert, because nothing in the lab watches outbound HTTP from web01. That goes into the lessons learned.

Response

Following the brute-force playbook (Playbooks, Runbooks and Handover):

  1. Contain: block 10.10.0.66 at the lab firewall (Wazuh's active response can run a firewall-drop script automatically on rule 100101; in production, automate blocking only with an allow-list of addresses that must never be blocked), lock the deploy account, kill its sessions.
  2. Preserve: export the alerts and web01's auth.log, copy the modified authorized_keys, hash everything (Evidence Handoff to DFIR).
  3. Eradicate: remove the added key, check for other persistence (cron, systemd units, other users' keys), reset the password and require key-only SSH.
  4. Recover and learn: re-enable the service, then the lessons: why was password SSH allowed on web01, why could 10.10.0.66 reach it at all, and does the rule need a variant for spraying across accounts?

Velociraptor, as a concept

For the "look at the host" steps, many teams use Velociraptor (open source, now maintained by Rapid7): an endpoint agent and server for digital forensics and incident response at scale. Analysts write queries in VQL (Velociraptor Query Language) or use packaged artifacts (for example, collecting authentication logs, listing users' SSH authorized keys, listing scheduled tasks or running processes), and run them as a hunt across all endpoints at once. In this incident, a hunt for "authorized_keys modified in the last 24 hours" across all Linux servers would answer the scoping question in minutes. In the lab it runs as one more server VM with clients on web01, ws02 and dc01.

Documenting the detection

text
DETECTION 100101  SSH login after repeated failures from the same source          owner: lab SOC
Goal        : detect a guessed SSH password being used (T1110.001, then T1078)
Logic       : 5 x rule 5716 from one srcip within 300 s (100100), then 5715 from that srcip within 600 s
Data        : Linux auth log via Wazuh agent (sshd); all Linux servers
Blind spots : spraying (1 failure per account); failures and success from different addresses; keys
              stolen rather than guessed; SSH on hosts without an agent
False pos.  : an admin mistyping five times, then succeeding (severity stays high: confirm with the admin)
Validation  : wazuh-logtest fixtures in rules/tests/100101/ (positive + 2 negatives); purple test each quarter
Response    : playbook PB-04 brute force; active response firewall-drop on 100101 (lab only)

Pitfalls

  • Rules that depend on decoder fields you didn't check. same_source_ip needs srcip decoded; test with real log lines from your sshd version.
  • Active response without safeguards. Automatic blocking can be abused to block your own gateways; keep a never-block list.
  • Lab scripts outside the lab. The guessing in this exercise is only for the lab account on the lab host, with written scope.

Practice

1. Why is rule 100101 evaluated only for 5715 events, and what would happen without ``?

<if_sid>5715</if_sid> makes it a child of "authentication success", so it is checked only for successful logins. Without same_source_ip, any success anywhere within ten minutes of any 100100 alert would fire it, including an admin logging in from the office while a scanner fails elsewhere.

2. Write a third rule that alerts on a modified `authorized_keys` file at level 12.

<rule id="100102" level="12"><if_sid>550</if_sid><field name="file">\.ssh/authorized_keys

lt;/field><description>lab: SSH authorized_keys modified</description><mitre><id>T1098.004</id></mitre></rule>, with the file monitored by syscheck (realtime or whodata for that path). Check the exact field name in your version's FIM alerts.

3. Which line of the incident timeline proves persistence, and which control would have prevented the initial access?

The file-integrity alert (rule 550) on /home/deploy/.ssh/authorized_keys at 10:23:40. Key-only SSH (no passwords), plus SSH reachable only from the admin network or a bastion, would have made password guessing impossible.

Test yourself

What does <if_sid>5715</if_sid> do in a Wazuh rule?

  1. Deletes rule 5715
  2. Makes the rule a child of 5715: it is only evaluated when 5715 matched
  3. Sets the level to 5715
  4. Sends an e-mail

Which ID range should your own Wazuh rules use?

  1. 1-1000
  2. From 100000 upward (100000-120000 recommended), unused by the default rule set
  3. Any ID of a default rule
  4. Negative numbers

What is wazuh-logtest used for?

  1. Load testing the indexer
  2. Running log lines through decoders and rules to see what fires, without real events
  3. Deleting old logs
  4. Installing agents

What is Velociraptor mainly used for?

  1. Web application firewalling
  2. Endpoint forensics and response at scale: VQL queries and artifacts collected as hunts across many endpoints
  3. Email filtering
  4. Password cracking