Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 08 · 55 minutes

Tune, test and maintain detections as code

After this lesson you can
  • Remove false positives with a filter selection and prove what the filter saves
  • Test every rule against samples that must match and samples that must not, with an exit code for a CI job
  • Give a rule the facts that a team needs, and say what a single-event rule cannot detect
Lab files of this lesson (25)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Your Sigma rules work on your machine. The team lead is not finished: "In six months somebody will edit one of these rules on a Friday evening. How will we know that it still finds the attack, and that it has not started to fire on the catalogue again? I want every rule to carry its own proof, and I want the check to run without a person. And a colleague of the branch office sent six rules: tell me which ones may ship."

Recall

Lesson 7: how are the entries of a map joined in a Sigma selection, and how are the items of a list joined?

The entries of a map by AND, the items of a list by OR. The modifier all turns the OR of a list into AND.

Lesson 3: you raised the threshold of R1 to 20 and the rule became quieter. What did you lose?

The alert for the intruder, who made 16 failures and then got in. A tuned rule must be run again over a day that holds a known attack, to see that the alert you need is still there.

The idea

A rule that ships is a promise: it fires on the attack and stays quiet on normal work. Three things keep the promise.

A filter for the known false positive. In Sigma a filter is one more selection, which the examples of the specification name filter, and the condition takes it away: selection and not filter. It is the allow-list of lesson 3. Keep it as narrow: one exact value.

Samples for every rule. Each rule gets a folder with two files of events: match.jsonl (known bad: every event must match) and nomatch.jsonl (known good: no event may match). A program, the test harness, runs every rule over its samples and ends with exit code 1 when one answer is wrong. An automatic job that runs before a change is accepted (a CI job, from continuous integration) can stop on that code, so a broken rule does not ship.

Facts about the rule. A reader who opens the rule a year later needs to know who wrote it, when, why, and how far to trust it.

FieldWhat the specification saysPolicy of this team
statusexperimental (may be noisy), test (mostly stable), stable (may be used in production), deprecated (replaced by another rule), unsupported (cannot be used as it is)New rules start as experimental.
levelinformational, low, medium, high, criticalThe level is the severity of lesson 4: set before any context.
author, date, modifiedThe creator, and the dates of creation and of the last change, as YYYY-MM-DDMandatory here.
referencesThe sources that the rule came fromThe ticket or the report.
tagsLower-case labels with a namespace and a dotAt least one tag of the namespace attack.

The specification makes only title, logsource and detection mandatory. The rest is a decision of the team, and the harness enforces it.

The life of a detection
Draft ruleSamplesTest harnessReviewProductionmatch, no matchexit code 0 or 1a second readertest, then stablea false positiveDraft ruleSamplesTest harnessReviewProduction12345
  1. Draft rule → Samples: match, no match
  2. Samples → Test harness: exit code 0 or 1
  3. Test harness → Review: a second reader
  4. Review → Production: test, then stable
  5. Production → Draft rule: a false positive

ATT&CK tags. A tag says which technique a rule looks for, so that the team can count what it covers. These names were checked on attack.mitre.org on 2026-11-21. Take the current ones from there.

RuleTechnique (tactic)Tag
Database words in a web pathExploit Public-Facing Application, T1190 (Initial Access)attack.t1190
Failed logonsBrute Force, T1110 (Credential Access)attack.t1110
New accountCreate Account, T1136 (Persistence)attack.t1136
Remote Desktop logonRemote Desktop Protocol, T1021.001, under Remote Services, T1021 (Lateral Movement)attack.t1021
Cleared logClear Windows Event Logs, T1685.005, under Disable or Modify Tools, T1685 (Defense Impairment)attack.t1685

What one event cannot say. The rules of lesson 7 test one event. "Ten failed logons from one address in five minutes" is a statement about many events. The engine of lesson 3 did it with group_by, count and window_s. Sigma has a second kind of rule for it, the correlation rule (Sigma Correlation Rules Specification, version 2.1.0). It names other rules and has a type: event_count (how many events), value_count (how many different values of a field), temporal (several rules fire in the time span, in any order) and temporal_ordered (in the given order). Version 2.1.0 adds value_sum, value_avg and value_percentile. Step 5 shows one. sigma_lite.py does not run them.

Detection as code. Rules are text, so treat them as code (lesson 3, Field notes): keep them in Git (the course "Linux", Part 4), let a second person review every change, run the harness before the change is accepted, and write one line in a changelog: the date, the rule, what changed and why.

Worked example

1. Tune a noisy rule with a filter

This lesson needs events.jsonl (lesson 2) and win-events.jsonl (lesson 7); if one is missing, make it as those lessons show. The team ships from a folder detections. Copy the two rules of lesson 7 into it. cp copies files.

mkdir -p detections
cp sigma/web_sql_words.yml sigma/win_failed_logon.yml detections/

Rule one of "Your turn" in lesson 7 matched every download of the public catalogue. Here is that rule with a filter for the exact path, and with the facts that the team asks for. No ATT&CK technique fits "a large answer", so the tag names the tactic only.

detections/web_large_response.yml

title: Large web response
id: 3e9b7a64-1d2f-4c85-b6a0-9f4e2d8c1a57
status: test
description: A web request that was answered with 1,000,000 bytes or more. Rule R3 of lesson 3.
author: Fernwood Press security team
date: 2026-11-21
references:
    - 'Ticket SEC-212, the export of customer data on 2026-11-20'
logsource:
    product: fernwood
    service: events
    definition: 'The normalised events of logparse.py (lesson 2), with its field names'
detection:
    selection:
        action: 'request'
        status: 200
        bytes|gte: 1000000
    filter:
        path: '/downloads/catalogue-2026.pdf'
    condition: selection and not filter
falsepositives:
    - A new large public file that is not in the filter yet
level: medium
tags:
    - attack.exfiltration
The condition of the tuned rule
selectionanswers of 1,000,000+ bytesand nottake away what followsfilterone exact path, the catalogueselectionanswers of 1,000,000+ bytesand nottake away what followsfilterone exact path, the catalogue
python3 sigma_lite.py detections/web_large_response.yml events.jsonl
2026-11-20T13:03:51Z action=request status=200 bytes=2481722 path=/admin/export/customers.csv
1 of 1290 events match: Large web response (level medium)

One event is left: the export of customer data.

2. Save the test harness and run it

sigma_test.py reads every .yml file of a folder. For the rule NAME.yml it reads tests/NAME/match.jsonl and tests/NAME/nomatch.jsonl. The function check returns the problems of one rule: first those of metadata (the table above, as code), then one line for each sample with the wrong answer. path.stem is the file name without .yml, and enumerate(events, 1) numbers the samples from 1.

        for name, want in (("match.jsonl", True), ("nomatch.jsonl", False)):
            file = path.parent / "tests" / path.stem / name
            events = samples(file) if file.exists() else []
            if not events:
                found.append(f"no samples in tests/{path.stem}/{name}")
            found += [f"{name} line {n}: {'no match' if want else 'match'}"
                      for n, event in enumerate(events, 1) if matches(rule, event) != want]

In metadata, uuid.UUID and datetime.date.fromisoformat raise an error for a text that is not a UUID or not a date of the form YYYY-MM-DD.

The finished file: sigma_test.py

sigma_test.py

"""sigma_test.py: test every Sigma rule of a folder before it ships. Needs sigma_lite.py.

    python3 sigma_test.py [folder]      default: detections

For the rule NAME.yml it reads tests/NAME/match.jsonl (every event must match) and tests/NAME/nomatch.jsonl
(no event may match), and it checks the facts about the rule that the team needs.
Exit code: 0 when there is no problem, 1 when there is one. A CI job can stop on it.
"""
import datetime
import json
import re
import sys
import uuid
from pathlib import Path

from sigma_lite import load_rule, matches

STATUS = {"stable", "test", "experimental", "deprecated", "unsupported"}
LEVEL = {"informational", "low", "medium", "high", "critical"}
TAG = re.compile(r"[a-z0-9_-]+(\.[a-z0-9_-]+)+")


def metadata(rule):
    """The problems in the facts about a rule. Title, logsource and detection are checked when the rule is read."""
    found = []
    try:
        uuid.UUID(str(rule.get("id")))
    except ValueError:
        found.append("id is not a UUID")
    if rule.get("status") not in STATUS:
        found.append(f"status '{rule.get('status')}' is not a value of the specification")
    if rule.get("level") not in LEVEL:
        found.append(f"level '{rule.get('level')}' is not a value of the specification")
    for name in ("description", "author", "falsepositives"):
        if not rule.get(name):
            found.append(f"no {name}")
    try:
        datetime.date.fromisoformat(str(rule.get("date")))
    except ValueError:
        found.append(f"date '{rule.get('date')}' is not YYYY-MM-DD")
    tags = rule.get("tags") or []
    found += [f"tag '{t}' is not lower-case namespace.name" for t in tags if not TAG.fullmatch(str(t))]
    if not any(str(t).startswith("attack.") for t in tags):
        found.append("no tag of the attack namespace")
    return found


def samples(path):
    with open(path) as src:
        return [json.loads(line) for line in src if line.strip()]


def check(path):
    """Every problem of one rule file: it cannot be read, a fact is wrong or missing, or a sample gives the wrong answer."""
    try:
        rule = load_rule(path)
        found = metadata(rule)
        for name, want in (("match.jsonl", True), ("nomatch.jsonl", False)):
            file = path.parent / "tests" / path.stem / name
            events = samples(file) if file.exists() else []
            if not events:
                found.append(f"no samples in tests/{path.stem}/{name}")
            found += [f"{name} line {n}: {'no match' if want else 'match'}"
                      for n, event in enumerate(events, 1) if matches(rule, event) != want]
    except ValueError as err:
        return [str(err)]
    return found


if __name__ == "__main__":
    folder = Path(sys.argv[1] if len(sys.argv) > 1 else "detections")
    rules = sorted(folder.glob("*.yml"))
    total = 0
    for path in rules:
        found = check(path)
        total += len(found)
        print(("FAIL " if found else "ok   ") + path.stem)
        for text in found:
            print("     " + text)
    print(f"{len(rules)} rule(s), {total} problem(s)")
    sys.exit(1 if total or not rules else 0)
python3 sigma_test.py
echo "exit code $?"
FAIL web_large_response
     no samples in tests/web_large_response/match.jsonl
     no samples in tests/web_large_response/nomatch.jsonl
FAIL web_sql_words
     no samples in tests/web_sql_words/match.jsonl
     no samples in tests/web_sql_words/nomatch.jsonl
FAIL win_failed_logon
     no samples in tests/win_failed_logon/match.jsonl
     no samples in tests/win_failed_logon/nomatch.jsonl
3 rule(s), 6 problem(s)
exit code 1

The facts of the three rules are in order. But a rule without samples is a rule without proof, and the harness counts that as a problem.

3. Give every rule its samples

Take the samples from the logs that you know. Known bad: the export, the three injection requests, three guesses of the intruder. Known good: two catalogue downloads, two requests for the shop page, two logons at the keyboard. grep -m 2 stops after two matching lines.

mkdir -p detections/tests/web_large_response detections/tests/web_sql_words detections/tests/win_failed_logon
grep "customers.csv" events.jsonl > detections/tests/web_large_response/match.jsonl
grep -m 2 "catalogue-2026.pdf" events.jsonl > detections/tests/web_large_response/nomatch.jsonl
grep "sqlmap-lab" events.jsonl > detections/tests/web_sql_words/match.jsonl
grep -m 2 '"path": "/shop/"' events.jsonl > detections/tests/web_sql_words/nomatch.jsonl
grep -m 3 '"IpAddress": "203.0.113.66"' win-events.jsonl > detections/tests/win_failed_logon/match.jsonl
grep -m 2 '"LogonType": "2"' win-events.jsonl > detections/tests/win_failed_logon/nomatch.jsonl
python3 sigma_test.py
echo "exit code $?"
ok   web_large_response
ok   web_sql_words
ok   win_failed_logon
3 rule(s), 0 problem(s)
exit code 0

Choose the known-good samples with care: the best ones are the events that once were false positives.

4. Break a rule and let the harness find it

Play the colleague on a Friday evening: sed -i edits a file in place, and here it takes and not filter out of the condition. The filter selection stays in the file and looks fine.

sed -i 's/ and not filter//' detections/web_large_response.yml
python3 sigma_lite.py detections/web_large_response.yml events.jsonl | tail -n 1
python3 sigma_test.py
echo "exit code $?"
106 of 1290 events match: Large web response (level medium)
FAIL web_large_response
     nomatch.jsonl line 1: match
     nomatch.jsonl line 2: match
ok   web_sql_words
ok   win_failed_logon
3 rule(s), 2 problem(s)
exit code 1
Events that match Large web response, of 1290
With the filter1Without the filter106With the filter1Without the filter106

The filter removed 105 matching events in one day, and the harness saw at once that it was gone. Put the condition back and test again.

sed -i 's/condition: selection$/condition: selection and not filter/' detections/web_large_response.yml
python3 sigma_test.py | tail -n 1
3 rule(s), 0 problem(s)

5. Read a correlation rule

This is rule R1 of lesson 3 in Sigma: ten matches of the failed-logon rule of lesson 7, for one address, in five minutes. rules names the base rule by its id, group-by is the group_by of lesson 3, timespan is the window (s, m, h or d), and condition holds the threshold (gte is "greater or equal"). Read it. Do not save it in detections: the tools of this lab do not run it.

title: Many failed network logons from one address
status: experimental
correlation:
    type: event_count
    rules:
        - b2d4e8a1-7c35-4f6e-8d92-51a0c3e9f7d4
    group-by:
        - IpAddress
    timespan: 5m
    condition:
        gte: 10
level: medium

A converter writes the count into the query of the SIEM, if its backend supports correlation. win_hunt.py of lesson 5 computed the same thing in Python.

Your turn

A colleague of the branch office sends six rules with samples. The generator writes them into the folder set2.

The finished file: gen_sigma_set.py

gen_sigma_set.py

"""gen_sigma_set.py: write six Sigma rules of a colleague, with samples for each, into the folder set2.

    python3 gen_sigma_set.py [folder]      default: set2. The same files every time. Every name and address is invented.
Some of the rules have a problem. Find each one with sigma_test.py.
"""
import hashlib
import json
import random
import sys
from pathlib import Path

out = Path(sys.argv[1] if len(sys.argv) > 1 else "set2")
r = random.Random(43)  # only random() is used: the same numbers on every Python version

HEAD = """title: {title}
id: {id}
status: {status}
description: {description}
{author}date: {date}
logsource:
    product: {product}
    service: {service}
detection:
{detection}
falsepositives:
    - {fp}
level: {level}
tags:
{tags}
"""


def uid():
    """A UUID of version 4 from the seeded generator."""
    h = "".join("0123456789abcdef"[int(r.random() * 16)] for _ in range(32))
    return f"{h[:8]}-{h[8:12]}-4{h[13:16]}-a{h[17:20]}-{h[20:]}"


def web(clock, ip, path, status, size):
    """One normalised web event, with the fields of lesson 2."""
    return {"ts": f"2026-12-01T{clock}Z", "source": "web", "host": "web01", "process": "nginx", "action": "request",
            "outcome": None, "user": None, "ip": ip, "port": None, "method": "GET", "path": path, "status": status,
            "bytes": size, "agent": "Mozilla/5.0", "msg": None, "ref": f"access.log:{1 + int(r.random() * 900)}"}


def win(clock, eid, host="APP01", channel="Security", **data):
    """One Windows event as win_jsonl.py writes it."""
    return {"ts": f"2026-12-01T{clock}Z", "EventID": eid, "Computer": host, "Channel": channel, **data}


def logon(clock, eid, user, ltype, ip):
    extra = {"SubStatus": "0xc000006a"} if eid == 4625 else {"TargetLogonId": hex(0x100000 + int(r.random() * 0x900000))}
    return win(clock, eid, TargetUserName=user, LogonType=str(ltype), IpAddress=ip, IpPort=str(49152 + int(r.random() * 16000)), **extra)


def rule(name, match, nomatch, tags, author="author: Fernwood Press security team\n", **parts):
    parts["tags"] = "\n".join("    - " + t for t in tags)
    (out / f"{name}.yml").write_text(HEAD.format(id=uid(), author=author, **parts))
    folder = out / "tests" / name
    folder.mkdir(parents=True, exist_ok=True)
    for file, events in (("match.jsonl", match), ("nomatch.jsonl", nomatch)):
        (folder / file).write_text("".join(json.dumps(e) + "\n" for e in events))


out.mkdir(parents=True, exist_ok=True)
WEB = {"product": "fernwood", "service": "events"}
SEC = {"product": "windows", "service": "security"}

rule("web_sql_words", title="Database words in a web path", status="test", date="2026-12-01", level="medium", **WEB,
     description="A web request whose path holds words of an SQL injection attempt.",
     detection="    selection:\n        action: 'request'\n        path|contains:\n            - '%27'\n            - 'UNION'\n"
               "            - 'DROP'\n            - 'select'\n    condition: selection",
     fp="A search for a book title that holds one of the words", tags=["attack.initial-access", "attack.t1190"],
     match=[web("10:31:07", "198.51.100.23", "/shop/search?q=1%27%20OR%20%271%27%3D%271", 500, 312),
            web("10:31:16", "198.51.100.23", "/shop/search?q=%27%20UNION%20SELECT%20password%20FROM%20users--", 400, 312),
            web("10:31:25", "198.51.100.23", "/shop/search?q=1%27%3B%20DROP%20TABLE%20books--", 400, 312)],
     nomatch=[web("09:12:40", "198.51.100.131", "/shop/selection/summer-reading", 200, 18220),
              web("09:13:02", "198.51.100.131", "/shop/search?q=garden", 200, 9120)])

rule("win_failed_logon_service", title="Failed logon for a service account", status="test", date="2026-12-01", level="low", **SEC,
     description="A failed logon for an account whose name starts with svc-. Service accounts do not type passwords.",
     detection="    selection:\n        EventID: 4625\n        UserName|startswith: 'svc-'\n    condition: selection",
     fp="A service that runs with an old password after a password change", tags=["attack.credential-access", "attack.t1110"],
     match=[logon("09:05:31", 4625, "svc-print", 3, "198.51.100.200"), logon("09:05:36", 4625, "svc-print", 3, "198.51.100.200")],
     nomatch=[logon("08:31:05", 4625, "alice", 2, "127.0.0.1"), logon("09:07:44", 4624, "svc-print", 10, "198.51.100.200")])

rule("win_rdp_logon", title="Remote Desktop logon from outside the office", status="test", date="2026-12-01", level="high", **SEC,
     description="A successful logon of type 10 (Remote Desktop) from an address outside the office network 192.0.2.0/24.",
     detection="    selection:\n        EventID: 4624\n        LogonType: 10\n    condition: selection",
     fp="A member of staff who works from home without the VPN", tags=["attack.lateral-movement", "attack.t1021"],
     match=[logon("09:07:44", 4624, "svc-print", 10, "198.51.100.200")],
     nomatch=[logon("09:40:02", 4624, "adm-ops", 10, "192.0.2.50"), logon("09:44:10", 4624, "carol", 3, "198.51.100.61")])

rule("win_log_cleared", title="A Windows event log was cleared", status="testing", date="01/12/2026", level="urgent", **SEC,
     description="The Security log (1102) or another log (104) was cleared.",
     detection="    selection:\n        EventID:\n            - 1102\n            - 104\n    condition: selection",
     fp="An administrator who clears a log on a test machine", tags=["attack.t1685"],
     match=[win("09:16:44", 1102, SubjectUserName="svc-print"), win("09:16:46", 104, channel="System", SubjectUserName="svc-print")],
     nomatch=[win("09:09:45", 4720, TargetUserName="support-tmp", SubjectUserName="svc-print")])

rule("linux_new_account", title="New account created", status="stable", date="2026-12-01", level="high", **WEB, author="",
     description="A new local account on a Linux host. Rule R4 of lesson 3.",
     detection="    selection:\n        action: 'user_add'\n    condition: selection",
     fp="An administrator who adds an account with an approved change", tags=["attack.persistence", "attack.T1136"],
     match=[{**web("09:49:25", None, None, None, None), "source": "auth", "process": "useradd", "action": "user_add",
             "user": "svc-update", "method": None, "agent": None, "msg": "new user: name=svc-update, UID=1010", "ref": "auth.log:133"}],
     nomatch=[web("09:50:00", "192.0.2.5", "/healthz", 200, 2)])

rule("web_large_response", title="Large web response", status="test", date="2026-12-01", level="medium", **WEB,
     description="A web request that was answered with 1,000,000 bytes or more.",
     detection="    selection:\n        action: 'request'\n        status: 200\n        bytes|gte: 1000000\n    filter:\n"
               "        path: '/downloads/catalogue-2026.pdf'\n    condition: selection and not filter",
     fp="A new large public file that is not in the filter yet", tags=["attack.exfiltration"],
     match=[web("10:03:51", "198.51.100.140", "/admin/export/customers.csv", 200, 2481722)],
     nomatch=[web("02:31:24", "198.51.100.111", "/downloads/catalogue-2026.pdf", 200, 5242880),
              web("10:01:30", "198.51.100.140", "/admin/", 200, 8120)])

files = sorted(p for p in out.rglob("*") if p.is_file())
digest = hashlib.sha256(b"".join(p.read_bytes() for p in files)).hexdigest()[:12]
print(f"{len(files)} files written to {out}, sha256 {digest}")
python3 gen_sigma_set.py
18 files written to set2, sha256 9cfd6d9f0e72

Run the harness on set2 (it takes the folder as its argument) and count the problems before you change anything. Then fix the rules, not the samples: the samples are right. Among the problems are a value that is too broad, a wrong field name, a missing filter and wrong facts. Read the description of each rule, and look at the sample that fails. The office network is 192.0.2.0/24. When the harness is silent, run your fixed win_failed_logon_service.yml and win_rdp_logon.yml over win-events.jsonl, the first day of lesson 7.

Check yourself

A rule has samples that must match and none that must not. What can go wrong without anybody seeing it?

The rule can become too broad. A rule that matches every event passes all its "must match" samples. Only the known-good samples show that it has started to fire on normal work.

A rule uses a field name that does not exist in the events. What does it do, and which sample shows it?

It matches nothing, in silence: a missing field is not an error. Only a "must match" sample shows it. In a SIEM the same mistake gives a rule that never fires, and nobody notices a rule that is quiet.

Why is "ten failures in five minutes" a correlation rule and not a selection?

A selection tests the fields of one event. A count needs many events, a group and a time span. In Sigma that is a correlation rule of type event_count on top of a base rule.

Field notes

  • Sigma also has filter files (the Sigma Filters Specification): a separate document that adds an exclusion to the rules that it lists. Use one for an exclusion that is true only in your environment, so that the shared rule stays unchanged.
  • Give each filter an owner and a review date in the changelog, as for the allow-lists of lesson 3. A filter on an account name or an address range is a place to hide.
  • Samples age. When a parser or a log format changes, make new samples from new logs, and keep the old ones until the old format is gone.
  • The harness of this lab checks our policy with our small evaluator. In a real project the CI job also converts each rule with sigma-cli for your SIEM, because a rule that our tool accepts can use a feature that your backend does not support. Every SIEM has its own query language, such as SPL or KQL, and the first week in a job is learning the local one. A converted rule is a good text to read it by.
  • The tags appendix of the specification gives the form of a technique tag (attack.t1110) and the names of the tactic tags. Before you tag a sub-technique or a new tactic, read the current appendix.