Lesson 07 · 55 minutes
Write a detection as a Sigma rule and run it
- Name the parts of a Sigma rule and say what each one is for
- Write a rule with selections, value modifiers and a condition
- Run your rules over Linux and Windows events with a small evaluator, and name the real tools
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
Fernwood Press buys a SIEM. The team lead says: "Our six rules are in a format that only our own program reads. The SIEM speaks its own query language, and the next one will speak another. Write the detections in Sigma, the format that every vendor can convert. Start with the database words rule and with the failed logons of the Windows machines, and prove that the Sigma rules find the same events." The SIEM is not installed yet, so you run the rules offline.
Recall
Lesson 3: rule R5 has "contains" with a list of three texts for the path. When does an event pass?
When the path holds at least one of the three texts. A list in contains means "or". The where part must also be true, so the parts of a rule are joined by "and".
Lesson 5: which field of event 4625 gives the specific reason of a failed logon in the sample?
SubStatus. Status holds the generic code 0xC000006D, and SubStatus holds 0xC0000064 (no such user) or 0xC000006A (bad password).
The idea
Sigma is an open format for detection rules that belongs to no vendor. A rule is a small text file. A converter turns it into the query language of a SIEM product, so a team writes a detection once and can share it. The facts of this lesson come from the Sigma Rules Specification, version 2.1.0 (released 2025-08-02), in the sigma-specification repository of SigmaHQ, as read on 2026-11-21. The format changes: take the current text from that source.
A rule is written in YAML, a text format for data. key: value is an entry of a map, a line that starts with - is an item of a list, and the indentation (four spaces in Sigma) shows what belongs to what. Text values go in single quotes. Rule files end in .yml.
Three more keys: id is a UUID (a random identifier of 32 hexadecimal digits) that names the rule for ever, status says how far the rule is trusted (lesson 8), and description says what the rule looks for. logsource has category (a kind of log, such as process_creation), product (such as windows) and service (such as security, the Security channel); definition is a note for people. level is informational, low, medium, high or critical.
A selection is a map of field names and values. The specification gives two rules that you must know by heart: all entries of a map are joined by AND, and the items of a list by OR. Text is compared without regard to case, and * (any text) and ? (one character) are wildcards. A value modifier after a | changes the comparison:
| Modifier | The field must |
|---|---|
| (none) | equal the value |
contains, startswith, endswith | hold the value anywhere, at the start, at the end |
all | fit every item of the list, not only one (`path |
re | fit a regular expression (here the case matters) |
cidr | be an address inside a network, such as 192.0.2.0/24 |
gt, gte, lt, lte | be greater, greater or equal, less, less or equal |
The specification has more modifiers (for example base64offset, windash and exists). The condition joins the selections by name with and, or, not and brackets. 1 of selection_* is true when one selection with such a name is true, and all of selection_* when every one is.
- Sigma rule → Converter: sigma-cli reads YAML
- Converter → Pipeline: maps fields
- Pipeline → Backend: writes the query
- Backend → SIEM query: runs in the SIEM
A rule names fields as the log source names them. A pipeline renames them for one SIEM, and a backend writes the query. This lesson has no SIEM, so a small program of the lab plays that part: sigma_lite.py reads a rule and tests each event against it. It knows only the part of Sigma that this lesson teaches (step 2 lists the limits).
Worked example
1. Write rule R5 as a Sigma rule
Rule R5 of lesson 3 was "where": {"action": "request"}, "contains": {"path": ["%27", "UNION", "DROP"]}. In Sigma the where part becomes an entry of a map, and the list of texts becomes a list under path|contains. The events are the normalised events of lesson 2 (events.jsonl; if it is missing, make it as lesson 2 shows), which are a log source of our own, so the rule says so in logsource. mkdir -p sigma makes the folder for the rules.
mkdir -p sigmasigma/web_sql_words.yml
title: Database words in a web path
id: 6f0a1c52-3b7e-4d19-9a40-2c8d5e7f1b63
status: experimental
description: A web request whose path holds words of an SQL injection attempt. Rule R5 of lesson 3.
author: Fernwood Press security team
date: 2026-11-21
logsource:
product: fernwood
service: events
definition: 'The normalised events of logparse.py (lesson 2), with its field names'
detection:
selection:
action: 'request'
path|contains:
- '%27'
- 'UNION'
- 'DROP'
condition: selection
falsepositives:
- A search for a book title that holds one of the words
level: medium
tags:
- attack.initial-access
- attack.t1190The technique is Exploit Public-Facing Application (T1190, tactic Initial Access). R5 also had group_by and window_s. A Sigma rule of this kind looks at one event at a time, so they have no place here (lesson 8).
2. Save the evaluator
sigma_lite.py has three parts: a reader for the YAML subset, the matching, and the condition. The key function is selection_matches. It splits each key at | into the field and its modifiers, makes a list of the values, and tests each one with value_matches. One entry that fails ends the selection (AND). Inside an entry, any is the OR of a list, and all takes its place when the modifier all is there.
def selection_matches(event, selection):
for key, wanted in selection.items():
field, *mods = key.split("|")
hits = [value_matches(event.get(field), w, mods) for w in (wanted if isinstance(wanted, list) else [wanted])]
if not (all(hits) if "all" in mods else any(hits)):
return False
return Truevalue_matches turns the value into a regular expression (re.escape makes every sign literal, then * becomes "any text") and compares with re.IGNORECASE, so case does not matter. evaluate reads the condition word by word. The program does not support: keyword lists (text without a field), lists of maps, null, the other modifiers, a list of conditions, text in double quotes and comments at the end of a line. It does not read logsource: you choose the file of events. It knows no correlation rules, pipelines or backends. The second file, win_jsonl.py, is for step 5.
The finished files: sigma_lite.py and win_jsonl.py
sigma_lite.py
"""sigma_lite.py: run one Sigma rule over events in JSON lines. A teaching tool for a SUBSET of Sigma.
python3 sigma_lite.py RULE.yml EVENTS.jsonl
It reads: maps, lists of plain values, values in single quotes or none, comments on a line of their own.
It matches: named selections that are maps; a list of values as OR; the modifiers contains, startswith, endswith,
all, re, cidr, gt, gte, lt, lte; the wildcards * and ?; a condition with and, or, not, brackets, "1 of" and "all of".
It does not do: keyword lists, lists of maps, null, the other modifiers, a list of conditions, correlation rules,
filter files, pipelines or backends. It does not use logsource: you choose the file of events.
"""
import fnmatch
import ipaddress
import json
import re
import sys
COMPARE = {"gt": lambda a, b: a > b, "gte": lambda a, b: a >= b, "lt": lambda a, b: a < b, "lte": lambda a, b: a <= b}
KNOWN = {"contains", "startswith", "endswith", "all", "re", "cidr", *COMPARE}
def scalar(text):
"""One YAML value: text in single quotes is taken as written, a number becomes a number."""
if len(text) > 1 and text[0] == text[-1] == "'":
return text[1:-1].replace("''", "'")
if text[:1] in ('"', "[", "{", "|", ">"):
raise ValueError(f"not in the subset of this reader: {text}")
if re.fullmatch(r"-?\d+", text):
return int(text)
return {"true": True, "false": False, "null": None}.get(text, text)
def read_yaml(text):
"""Read the YAML subset of the lesson into dictionaries and lists. The indentation gives the structure."""
lines = [(len(raw) - len(raw.lstrip()), raw.strip()) for raw in text.splitlines()
if raw.strip() and not raw.strip().startswith("#")]
def block(i, indent):
if lines[i][1].startswith("- "): # a list of plain values
items = []
while i < len(lines) and lines[i][0] == indent and lines[i][1].startswith("- "):
items.append(scalar(lines[i][1][2:].strip()))
i += 1
return items, i
result = {}
while i < len(lines) and lines[i][0] == indent:
key, colon, rest = lines[i][1].partition(":")
if not colon or (rest and not rest.startswith(" ")):
raise ValueError(f"expected 'key: value', found: {lines[i][1]}")
i += 1
if rest.strip():
result[key] = scalar(rest.strip())
elif i < len(lines) and lines[i][0] > indent: # the value is the deeper block that follows
result[key], i = block(i, lines[i][0])
else:
result[key] = None
if i < len(lines) and lines[i][0] > indent:
raise ValueError(f"wrong indentation: {lines[i][1]}")
return result, i
return block(0, lines[0][0])[0] if lines else {}
def value_matches(have, want, mods):
"""Does the value of one field of an event fit one value of the rule?"""
if have is None:
return False
if "re" in mods: # a regular expression: case matters
return re.search(str(want), str(have)) is not None
if "cidr" in mods:
try:
return ipaddress.ip_address(str(have)) in ipaddress.ip_network(str(want))
except ValueError:
return False
for name in COMPARE:
if name in mods:
try:
return COMPARE[name](float(have), float(want))
except ValueError:
return False
pattern = re.escape(str(want)).replace(r"\*", ".*").replace(r"\?", ".") # * is any text, ? is one character
if "contains" in mods:
pattern = ".*" + pattern + ".*"
elif "startswith" in mods:
pattern += ".*"
elif "endswith" in mods:
pattern = ".*" + pattern
return re.fullmatch(pattern, str(have), re.IGNORECASE | re.DOTALL) is not None
def selection_matches(event, selection):
"""A selection is a map: every field must fit (AND). A list of values is OR, and AND with the modifier all."""
if not isinstance(selection, dict):
raise ValueError("this tool reads only selections that are maps of field: value")
for key, wanted in selection.items():
field, *mods = key.split("|")
if set(mods) - KNOWN:
raise ValueError(f"modifier not supported: {key}")
hits = [value_matches(event.get(field), w, mods) for w in (wanted if isinstance(wanted, list) else [wanted])]
if not (all(hits) if "all" in mods else any(hits)):
return False
return True
def evaluate(condition, truth):
"""The condition with the result of each selection. From weakest to strongest: or, and, not, 'x of', brackets."""
tokens = re.findall(r"[()]|[^\s()]+", condition)
def take():
return tokens.pop(0) if tokens else ""
def either():
value = both()
while tokens[:1] == ["or"]:
take()
value = both() or value
return value
def both():
value = negated()
while tokens[:1] == ["and"]:
take()
value = negated() and value
return value
def negated():
if tokens[:1] == ["not"]:
take()
return not negated()
token = take()
if token == "(":
value = either()
take() # the closing bracket
return value
if token in ("1", "all") and tokens[:1] == ["of"]:
take()
pattern = take()
hits = [v for name, v in truth.items()
if (not name.startswith("_") if pattern == "them" else fnmatch.fnmatchcase(name, pattern))]
return any(hits) if token == "1" else bool(hits) and all(hits)
if token not in truth:
raise ValueError(f"the condition names '{token}', which is not a selection")
return truth[token]
value = either()
if tokens:
raise ValueError(f"cannot read the condition near: {' '.join(tokens)}")
return value
def load_rule(path):
"""Read a rule file and check the three parts that the specification makes mandatory."""
with open(path) as src:
rule = read_yaml(src.read())
for part in ("title", "logsource", "detection"):
if not rule.get(part):
raise ValueError(f"{path}: the rule has no {part}")
if not isinstance(rule["detection"].get("condition"), str):
raise ValueError(f"{path}: the detection needs one condition")
return rule
def matches(rule, event):
"""True when the event fits the condition of the rule."""
detection = rule["detection"]
truth = {name: selection_matches(event, sel) for name, sel in detection.items() if name != "condition"}
return evaluate(detection["condition"], truth)
def fields(rule):
"""The field names that the selections of the rule use, in order."""
names = [key.split("|")[0] for name, sel in rule["detection"].items() if name != "condition" for key in sel]
return list(dict.fromkeys(names))
if __name__ == "__main__":
if len(sys.argv) != 3:
sys.exit(__doc__)
try:
rule = load_rule(sys.argv[1])
with open(sys.argv[2]) as src:
events = [json.loads(line) for line in src if line.strip()]
found = [e for e in events if matches(rule, e)]
except (OSError, ValueError) as err:
sys.exit(f"error: {err}")
for e in found:
print(e.get("ts", ""), " ".join(f"{name}={e.get(name)}" for name in fields(rule)))
print(f"{len(found)} of {len(events)} events match: {rule['title']} (level {rule.get('level', 'not set')})")win_jsonl.py
"""win_jsonl.py: write the events of a Windows export as JSON lines, with the field names that Windows gives them.
python3 win_jsonl.py [export.xml] [out.jsonl] defaults: data/win/export.xml win-events.jsonl
"""
import json
import sys
from winevents import parse
source = sys.argv[1] if len(sys.argv) > 1 else "data/win/export.xml"
target = sys.argv[2] if len(sys.argv) > 2 else "win-events.jsonl"
events = parse(source)
with open(target, "w") as out:
for e in events:
row = {"ts": e["ts"], "EventID": e["id"], "Computer": e["computer"], "Channel": e["channel"], **e["data"]}
out.write(json.dumps(row) + "\n")
print(len(events), "events written to", target)3. Run the rule
The program takes the rule and the events. It prints the time of each match with the fields that the rule names, and a count.
python3 sigma_lite.py sigma/web_sql_words.yml events.jsonl2026-11-20T10:31:07Z action=request path=/shop/search?q=1%27%20OR%20%271%27%3D%271
2026-11-20T10:31:16Z action=request path=/shop/search?q=%27%20UNION%20SELECT%20password%20FROM%20users--
2026-11-20T10:31:25Z action=request path=/shop/search?q=1%27%3B%20DROP%20TABLE%20books--
3 of 1290 events match: Database words in a web path (level medium)Three events match. The engine of lesson 3 made one alert of them, because it grouped them by address in a window of 60 seconds. A SIEM does that grouping after the query.
4. See what the modifier all changes
sed writes a copy of the rule in which path|contains is path|contains|all. Now the path must hold all three texts.
sed 's/path|contains:/path|contains|all:/' sigma/web_sql_words.yml > all-words.yml
python3 sigma_lite.py all-words.yml events.jsonl0 of 1290 events match: Database words in a web path (level medium)No path holds %27, UNION and DROP together. One word in a key turned OR into AND, and the rule went silent. Delete all-words.yml.
5. Write the Windows events as JSON lines
win_jsonl.py uses parse of lesson 5 and writes one JSON object for each event: the time as ts, then EventID, Computer, Channel and every data field under the name that Windows gives it. Rules for the Windows Security log use these names.
python3 win_jsonl.py124 events written to win-events.jsonl6. Write the condition of R1 for Windows
R1 counted failed logins. Its condition, for Windows, is event 4625 with logon type 3 (network). A second selection, reason, keeps the two causes that a guesser produces. The codes are written in capitals, as Microsoft writes them, and the sample holds them in small letters: Sigma does not care.
sigma/win_failed_logon.yml
title: Failed network logon with a bad name or a bad password
id: b2d4e8a1-7c35-4f6e-8d92-51a0c3e9f7d4
status: experimental
description: One failed logon over the network. The condition of rule R1 of lesson 3, for Windows events.
author: Fernwood Press security team
date: 2026-11-21
logsource:
product: windows
service: security
detection:
selection:
EventID: 4625
LogonType: 3
reason:
SubStatus:
- '0xC0000064'
- '0xC000006A'
condition: selection and reason
falsepositives:
- A user who types a wrong password
level: low
tags:
- attack.credential-access
- attack.t1110tail -n 3 prints the last three lines.
python3 sigma_lite.py sigma/win_failed_logon.yml win-events.jsonl | tail -n 32026-11-24T13:21:57Z EventID=4625 LogonType=3 SubStatus=0xc000006a
2026-11-24T13:21:59Z EventID=4625 LogonType=3 SubStatus=0xc000006a
36 of 124 events match: Failed network logon with a bad name or a bad password (level low)36 events match: the guesses from outside that lesson 5 found. The three typing mistakes of alice are logon type 2 and do not match. The rule says "one failed logon". It cannot say "ten in five minutes", so its level is low.
7. Know the real tools
pySigma is the Python library of the Sigma project that parses rules and converts them into queries. sigma-cli is the command-line tool that is built on it: its command is sigma. The project's guide installs it with pip3 install sigma-cli, adds a backend with sigma plugin install splunk, and converts a folder of rules with a line of this form:
sigma convert --target splunk --pipeline splunk_windows ./rulesThis lab does not install them (no network is needed here). They add what sigma_lite.py lacks: the whole specification, pipelines for field names, and backends for many products (sigma list targets names them).
Your turn
Write two rules of your own in the folder sigma and run them on the second day. First make the Windows events of day 2: python3 win_jsonl.py day2/export.xml win-events2.jsonl (the export of "Your turn" of lesson 5).
Rule one is R3 of lesson 3, without its allow-list, for events2.jsonl: the action is request, the status is 200, and bytes is 1,000,000 or more. Count the matches. Then add one entry that keeps only paths that end in .csv, and count again.
Rule two is for win-events2.jsonl and has two selections whose names start with selection_: a new account (event 4720), and a member added to the group Administrators (event 4732, the group is in TargetUserName). Run it with the condition 1 of selection_*, then with all of selection_*.
Check yourself
A selection has the entries EventID 4625 and LogonType 3. A second rule puts 4625 and 4624 in a list under EventID. Which is AND and which is OR?
The entries of a map are joined by AND: the event must be a 4625 and of type 3. The items of a list are joined by OR: the event may be a 4625 or a 4624.
Why does "all of selection_*" match no event in "Your turn"?
One event has one EventID. It cannot be 4720 and 4732 at the same time, so both selections are never true for the same event. A single-event rule cannot say "this event and later that event". That needs a correlation rule (lesson 8).
Your rule says path|contains 'union'. Does it match a path with UNION in capitals?
Yes. Sigma compares text without regard to case, unless a modifier says otherwise. A regular expression (re) is the exception: there the case matters.
The rule of step 1 uses the field names action and path. What must happen before a SIEM can run it?
The SIEM must hold the events under those names, or a pipeline must rename the fields of the rule to the names of that SIEM. For common log sources, such as Windows events, pipelines exist. For a log source of your own you write the mapping.
Field notes
- The SigmaHQ project keeps a public repository of rules: its page says more than 3,000. Read them before you write your own: most common detections exist, with their known false positives.
- A rule is only as good as the log source. A rule for
process_creationfinds nothing when the audit policy does not record process creation (lesson 5). Note the settings that a rule needs indefinition. - Sigma has a taxonomy of log sources and field names (an appendix of the specification). Use its names when your log source is in it, so that shared pipelines work.
- A converted query is not a tested query. After a conversion, run the query on events that must match, in the SIEM itself.
- The specification says that searches named with a leading underscore are left out of
1 of themby convention, and it advises againstall of them. Name your selections and state the condition in full.