Lesson 03 · 50 minutes
Write detection rules as data and tune them against noise
- Write rules with a condition, a threshold, a time window, a group and an allow-list
- Run the rules over events and read the alerts that they raise
- Tune a noisy rule and measure what a looser rule would miss
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
Until now you found the attack because you looked for it. Nobody can look all day. The team lead says: "Write down what we look for as rules, in a file that we can review, so that a program raises the alert and not your memory. Start with three rules: password guessing, scanning for pages, and very large answers. Then show me how noisy they are." A rule that fires a hundred times a day on harmless traffic is worse than no rule, because the team stops reading alerts.
Recall
Lesson 2: what does the parser do with a line that it cannot read?
It returns None. The loader keeps the file name, the line number and the text of that line and reports the count, so that nobody believes that every line was read.
Lesson 2: why does a rule on events work for every log, although each log has its own format?
Because the parsers gave every line the same fields and the same clock. A rule reads action, outcome, ip and ts, and it does not care which file a line came from.
The idea
A detection rule says: when events like this happen, raise an alert. It has a condition, a group, a threshold in a window, an allow-list and a severity. Rule R1 below shows them as keys of the rule file.
Besides where (a field must equal a value), a condition can use contains (a field must hold a text, or one of a list of texts) and at_least (a number must be at least this). allow (the allow-list: events that never count, such as a known good source) is not in R1, but any rule can have it. severity is low, medium or high.
After an alert, the rule is quiet for one window for that group. One burst of 40 failures then gives one alert and not eight.
- Events → Condition: where, at_least
- Condition → Allow-list: skip known good
- Allow-list → Group and window: count by address
- Group and window → Alert: rule, time, proof
A rule can be wrong in two ways. A false positive is an alert for harmless activity. A false negative is no alert for an attack. A rule that is tuned against one always moves towards the other, so you measure both.
Two public standards are worth knowing by name. Sigma is an open format for detection rules, written in YAML. A Sigma rule has a title, a logsource (which logs), a detection part with a condition, and a level. Tools convert a Sigma rule into the query language of a log system, so one rule can be shared. MITRE ATT&CK is a public knowledge base of the techniques that attackers use. Its technique Brute Force (T1110, in the tactic Credential Access) is what rule R1 below looks for. A real team runs rules in a SIEM (security information and event management) tool, which collects logs, runs the rules and keeps the alerts. This lesson uses a tiny format of its own, so that you can see every line of the engine. Lessons 7 and 8 write, run and test the same detections as Sigma rules.
One more thing helps with rule R5 of "Your turn". SQL injection is an attack on a web page that builds a database question (an SQL query) from text that the visitor typed, for example in a search box. A visitor who types an apostrophe and a command can change the question, so that the database gives more data than the page meant to give. A URL cannot hold every character, so it writes some as % and two hexadecimal digits: %27 is an apostrophe, %20 a space, %3B a semicolon and %3D an equals sign. UNION SELECT adds a second question to the first, DROP TABLE deletes a table, and -- ends the query. This line of data/access.log asks the page for ' UNION SELECT password FROM users--:
198.51.100.23 - - [20/Nov/2026:10:31:16 +0000] "GET /shop/search?q=%27%20UNION%20SELECT%20password%20FROM%20users-- HTTP/1.1" 400 312 "-" "sqlmap-lab/1.0"A rule only sees the attempt. The status and the size of the answer tell whether it worked, and the scenario test asks you to read them.
Worked example
1. Write three rules as data
A rule is a JSON object. R1 counts failed logins for each address: 5 in 300 seconds. R2 counts answers with status 404 for each address: 20 in 60 seconds. R3 fires for every successful answer of 1,000,000 bytes or more. The rules go in a list in rules.json.
cat > rules.json <<'EOT'
[
{"id": "R1", "title": "Many failed logins from one address", "severity": "medium",
"where": {"action": "login", "outcome": "failure"}, "group_by": "ip", "count": 5, "window_s": 300},
{"id": "R2", "title": "Many missing pages from one address", "severity": "low",
"where": {"action": "request", "status": 404}, "group_by": "ip", "count": 20, "window_s": 60},
{"id": "R3", "title": "Large web response", "severity": "medium",
"where": {"action": "request", "status": 200}, "at_least": {"bytes": 1000000}, "group_by": "ip"}
]
EOT2. Save the engine
rules.py reads events and rules and returns alerts. New in it: datetime.fromisoformat turns the text of a time into a time, and .timestamp() turns that into seconds so that two times can be subtracted. any(...) is true when one item of a sequence is true, and all(...) when every item is. {**a} copies a dictionary into a new one. sort(key=...) sorts by the value that the function gives.
The core of run_rules is two dictionaries for each rule. recent holds, for each group, the matching events of the last window_s seconds (Python lesson 8 builds such a window). quiet holds the time before which the group raises no new alert. When the list reaches count, the engine writes an alert, clears the list and sets the quiet time.
rules.py
"""rules.py: run detection rules over events.
python3 rules.py [events.jsonl] [rules.json]
"""
import json
import sys
from collections import Counter
from datetime import datetime
def when(ts):
"""The time of an event as seconds, so that two times can be subtracted."""
return datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp()
def has(value, wanted):
"""True when the text `value` contains the text `wanted`, or any text of the list `wanted`."""
return value is not None and any(w in str(value) for w in ([wanted] if isinstance(wanted, str) else wanted))
def matches(rule, ev):
"""Does one event pass the conditions of a rule? An event of the allow-list never passes."""
if any(ev.get(k) != v for k, v in rule.get("where", {}).items()):
return False
if any(not has(ev.get(k), v) for k, v in rule.get("contains", {}).items()):
return False
if any((ev.get(k) or 0) < v for k, v in rule.get("at_least", {}).items()):
return False
return all(ev.get(k) not in values for k, values in rule.get("allow", {}).items())
def run_rules(events, rules):
"""Return the alerts of all rules. `events` must be in time order."""
found = []
for rule in rules:
need, window = rule.get("count", 1), rule.get("window_s", 0)
recent, quiet = {}, {} # per group: the events in the window, and when the next alert may come
for ev in events:
key = ev.get(rule["group_by"])
if key is None or not matches(rule, ev):
continue
now = when(ev["ts"])
if now < quiet.get(key, 0):
continue
hits = [h for h in recent.get(key, []) if now - when(h["ts"]) <= window] + [ev]
recent[key] = hits
if len(hits) >= need:
found.append({"rule": rule["id"], "title": rule["title"], "severity": rule["severity"],
"host": ev["host"], "by": rule["group_by"], "group": key, "first": hits[0]["ts"],
"last": ev["ts"], "count": len(hits), "refs": [h["ref"] for h in hits]})
quiet[key] = now + window
recent[key] = []
found.sort(key=lambda a: a["last"])
return [{"id": f"A{n:03d}", **a} for n, a in enumerate(found, 1)]
def load_events(path):
with open(path) as src:
return [json.loads(line) for line in src]
if __name__ == "__main__":
events = load_events(sys.argv[1] if len(sys.argv) > 1 else "events.jsonl")
rules = json.load(open(sys.argv[2] if len(sys.argv) > 2 else "rules.json"))
alerts = run_rules(events, rules)
for a in alerts:
print(f"{a['id']} {a['last']} {a['severity']:8s} {a['rule']} {a['group']} x{a['count']}")
print(f"{len(alerts)} alerts:", ", ".join(f"{r} {n}" for r, n in sorted(Counter(a["rule"] for a in alerts).items())))3. Run the rules
python3 rules.py reads events.jsonl and rules.json, prints one line for each alert and, at the end, a count for each rule. head -n 4 shows the first four lines and tail -n 1 the last one.
python3 rules.py | head -n 4
python3 rules.py | tail -n 1A001 2026-11-20T00:30:38Z low R2 192.0.2.7 x20
A002 2026-11-20T02:31:24Z medium R3 198.51.100.111 x1
A003 2026-11-20T02:40:28Z low R2 198.51.100.77 x20
A004 2026-11-20T02:50:32Z medium R1 198.51.100.77 x5
110 alerts: R1 2, R2 2, R3 106The three rules raise 110 alerts, and 106 of them are R3. Almost every one is the same public file.
python3 rules.py | grep " R3 " | head -n 2
grep -c "catalogue-2026.pdf" data/access.logA002 2026-11-20T02:31:24Z medium R3 198.51.100.111 x1
A005 2026-11-20T03:02:18Z medium R3 198.51.100.114 x1
1054. Tune with an allow-list
A download of the public catalogue is normal. Add an allow-list to R3 with the exact path. An allow-list is a decision to never look at something again, so keep it narrow: one rule, one exact value. Here is the whole file again.
cat > rules.json <<'EOT'
[
{"id": "R1", "title": "Many failed logins from one address", "severity": "medium",
"where": {"action": "login", "outcome": "failure"}, "group_by": "ip", "count": 5, "window_s": 300},
{"id": "R2", "title": "Many missing pages from one address", "severity": "low",
"where": {"action": "request", "status": 404}, "group_by": "ip", "count": 20, "window_s": 60},
{"id": "R3", "title": "Large web response", "severity": "medium",
"where": {"action": "request", "status": 200}, "at_least": {"bytes": 1000000}, "group_by": "ip",
"allow": {"path": ["/downloads/catalogue-2026.pdf"]}}
]
EOTpython3 rules.pyA001 2026-11-20T00:30:38Z low R2 192.0.2.7 x20
A002 2026-11-20T02:40:28Z low R2 198.51.100.77 x20
A003 2026-11-20T02:50:32Z medium R1 198.51.100.77 x5
A004 2026-11-20T12:56:04Z medium R1 203.0.113.50 x5
A005 2026-11-20T13:03:51Z medium R3 203.0.113.50 x1
5 alerts: R1 2, R2 2, R3 1Five alerts are left. R1 fired for two addresses, R2 for two, and R3 once, for the export of customer data. One R2 alert is the scan from 192.0.2.7, which is the company's own scanner. You could allow-list that address, but you do not: whether it is harmless depends on a change ticket for that hour. Lesson 4 decides it with context, alert by alert.
5. Measure what a looser rule misses
A rule with a higher threshold is quieter. Copy the file, set R1 to 20 failures, and run it.
sed 's/"count": 5/"count": 20/' rules.json > rules-loose.json
python3 rules.py events.jsonl rules-loose.json | grep " R1 "A003 2026-11-20T02:52:07Z medium R1 198.51.100.77 x20
4 alerts: R1 1, R2 2, R3 1Only the address with 40 failures is left. The intruder made 16 failures and then got in, and the loose rule is silent about it. That is a false negative. Always run a tuned rule over a day that holds a known attack, and keep the alert you need.
Your turn
Add three rules to your rules.json, keeping R1, R2 and R3 as they are in step 4. R4 fires on every new account: the action is user_add, it is grouped by user, and its severity is high. R5 looks for words from a database attack in the path of a request: the action is request, the path contains %27, UNION or DROP, it is grouped by ip, the window is 60 seconds, and its severity is medium. One matching request is enough, so give R5 no count. R6 looks for a burst of blocks of the firewall: the action is firewall_block, it is grouped by ip, five events in 120 seconds, severity low. Then make the events of a second day with a different intruder and run the six rules over both days.
python3 gen_logs.py 2 data2
python3 logparse.py data2 2026 events2.jsonl | head -n 1auth.log 181 lines sha256 ee5e508e8d9b
access.log 1083 lines sha256 2abf6a6e08ee
syslog 42 lines sha256 32cdbc480250
1303 events written to events2.jsonl, 3 lines not readCheck yourself
R1 asks for 5 failures in 300 seconds. How can a guesser stay below it, and what rule would you add?
By slowing down: four guesses in five minutes is 48 an hour, and R1 never fires. A second rule with a long window (for example 30 failures in 24 hours for one address) catches the slow guesser. A short window finds speed, and a long window finds patience.
Why is an allow-list on the exact path safer than an allow-list on a whole address range?
A range hides everything that comes from it, including an attacker who uses one of those addresses or a stolen machine. An exact path hides one known harmless thing and still lets the same address trigger the rule on any other path. Keep allow-lists narrow, give each one an owner, and review it.
The engine clears the list and stays quiet for one window after an alert. What would happen without that?
Every event after the threshold would raise another alert, so one burst of 40 failures would give 36 alerts. The analyst gets a flood and stops reading. One alert should carry the count and the line references of the whole burst.
What does the field "refs" of an alert hold, and why?
The file names and line numbers of the events that made the alert. The analyst of lesson 4 starts from them, and a report can quote them. An alert that cannot show its proof must be trusted, and a tool that must be trusted is a poor tool.
Field notes
- Treat rules as code. Keep the rule file in Git (the course "Linux" Part 4 has a lesson on it), review every change, and write a test for each rule: a small log with a known attack that must alert, and a known harmless day that must not.
- Track each rule by its alert count and by how many alerts were real. A rule that is never real needs a new design, and a rule that is silent for a year needs a test that proves that it still works.
- Give every allow-list an owner and an expiry date. Allow-lists grow and nobody removes them, and they become the hole that the next attacker walks through.
- Map each rule to a technique of MITRE ATT&CK, so that you can see which techniques you detect and which you do not. Take the current technique names and numbers from the ATT&CK site.
- Write rules on behaviour (a new account after a login from a new address), not only on a single bad value (one address), because attackers change addresses and rarely change what they must do.