Lesson 09 · 40 minutes
Build a detection and response kit with one command
- Join the log writer, the detectors, the cost watcher, the playbook checker and the rollback check in one kit
- Run the kit on a quiet week and on a week with trouble and read both reports
- Make the kit fail when its own checks fail, and keep that apart from alerts
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
The security lead of Orbit Parcels asks for one thing before the next quarter: "Give the on-call engineer one command that runs everything you built, and tells her in one screen what needs a person." You have eight modules from eight lessons, each with its own small script. You write the part that is missing: the kit that calls them all on one week of logs, prints one line for each check, writes a report file, and has an exit code that means something.
Recall
Lesson 6: why does the playbook checker end with exit code 1 for an empty folder?
A checker that finds nothing must not report success. An empty folder means that the playbooks are missing, which is the worst state, so the kit treats it as a failure.
Lesson 5: the detector ends with an allow-list. What does the kit have to do with that?
Nothing special. The kit calls extract.flagged with the last rule, which already removes the users of the allow-list. The kit must not repeat the logic of a module. It calls the function and counts.
The idea
A kit is not new logic. It is a thin layer: one function that calls the modules on the same input, and one place where the results are shown. Its value is that nobody has to remember eight commands at 03:10, and that two runs on the same data give the same page.
The kit has two kinds of line, and the exit code separates them:
| Kind | Examples | Exit code |
|---|---|---|
| Own checks: is the kit itself sound? | A secret in the log, a playbook with a missing section | 1 if the count is above 0 |
| Findings: is something happening? | Alerts, drift, spikes, extraction | Always 0. They are the content of the report |
If an alert made the exit code 1, the engineer would learn to ignore a failing kit. A kit that fails only when it cannot be trusted keeps its signal.
- Engineer → kit.py: python3 kit.py
- kit.py → Log file: load one week of records
- kit.py → Detectors: rules, drift, cost, extraction, access
- kit.py → Checks: log scan, playbooks, test set
- kit.py → Report file: write kit-report.json
- kit.py → Engineer: one line each, and an exit code
| Module | Built in lesson | The kit uses |
|---|---|---|
logrec.py | 1 | load and violations |
detect.py | 2 | record_alerts, refusal_alerts |
drift.py | 3 | drift_days, review_queue |
cost.py | 4 | daily_cost, spike_hours, user_hour_alerts |
extract.py | 5 | features, flagged, RULES |
check_playbooks.py | 6 | problems |
respond.py | 7 | score |
audit.py | 8 | access_audit |
Worked example
1. Check the parts
ls with several names prints each name that exists, and an error for each one that does not. Then python3 makelogs.py puts the state files back to their first form: the kit reads state/config.json to learn which model is live, and lesson 7 changed it.
ls logrec.py detect.py drift.py cost.py extract.py check_playbooks.py respond.py audit.py
python3 makelogs.pyaudit.py
check_playbooks.py
cost.py
detect.py
drift.py
extract.py
logrec.py
respond.py
wrote logs/, testset/, state/ and audit/If one is missing, go back to its lesson, or run kr-lab.sh for this lesson (lesson 0).
2. Write the kit
kit.py is the only new file. checks(week_path) returns a list of (alert id, section, what is counted, count). The alert id is the one of lesson 6, so that a line points to its playbook, and it is empty for a line that raises no alert. sys.argv holds the words of the command line, so sys.argv[1] is the path of the week to check. any(...) (lesson 2) tests the rows of the own-checks sections. Path("playbooks").glob("*.md") lists the playbook files, and or int(not files) counts 1 when the list is empty: a folder with no playbook is a problem, as in the checker of lesson 6 (int(True) is 1). json.dump writes the report as a file.
kit.py
"""kit.py: the detection and response kit in one command.
python3 kit.py [week.jsonl] default logs/week2.jsonl; the baseline is always logs/week1.jsonl
It prints one line for each check and writes kit-report.json. Exit code 0 means that the kit's own checks pass:
no secret in the log and every playbook complete. Alerts are findings, not failures.
"""
import json
import sys
from pathlib import Path
import audit
import check_playbooks
import cost
import detect
import drift
import extract
import respond
from logrec import load, violations
BASELINE = "logs/week1.jsonl"
OWN = {"log", "playbooks"} # a count above 0 in these sections makes the exit code 1
def checks(week_path):
"""A list of (alert id, section, what is counted, count)."""
base, week = load(BASELINE), load(week_path)
access = audit.access_audit(week, json.load(open("audit/access.json")))
files = sorted(Path("playbooks").glob("*.md"))
_, right, total = respond.score()
return [
("A-LOG-SECRET", "log", "records with something that must not be logged", sum(bool(violations(r)) for r in week)),
("A-INJ", "detect", "record alerts (score of 2 or more)", len(detect.record_alerts(week))),
("A-REFUSE", "detect", "user-days with a high refusal rate", len(detect.refusal_alerts(week))),
("A-DRIFT", "drift", "days with a PSI above the threshold", sum(d[3] == "DRIFT" for d in drift.drift_days(base, week))),
("", "drift", "answers in the review queue", len(drift.review_queue(week))),
("A-COST", "cost", "days over the budget", sum(v > cost.DAY_BUDGET for v in cost.daily_cost(week).values())),
("A-RATE", "cost", "hours with a request spike", len(cost.spike_hours(base, week))),
("A-RATE", "cost", "user-hours over the limit", len(cost.user_hour_alerts(week))),
("A-EXTRACT", "extraction", "users flagged", len(extract.flagged(extract.features(week), extract.RULES["+ not on allow-list"]))),
("", "access", "uses of a tool outside the role", sum(n for *_, n in access["outside_role"])),
("", "playbooks", "playbooks with a problem", sum(bool(check_playbooks.problems(p.read_text())) for p in files) or int(not files)),
("", "recovery", "test questions that the active model fails", total - right),
]
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "logs/week2.jsonl"
rows = checks(path)
print(f"detection and response kit: {path}")
for alert, section, what, count in rows:
print(f"{alert:14}{section:11}{what:50}{count:5}")
json.dump([{"alert": a, "section": s, "check": w, "count": c} for a, s, w, c in rows], open("kit-report.json", "w"), indent=2)
sys.exit(1 if any(c for _, s, _, c in rows if s in OWN) else 0)3. Run it on the week with trouble
python3 kit.py
echo "exit code $?"detection and response kit: logs/week2.jsonl
A-LOG-SECRET log records with something that must not be logged 0
A-INJ detect record alerts (score of 2 or more) 4
A-REFUSE detect user-days with a high refusal rate 1
A-DRIFT drift days with a PSI above the threshold 3
drift answers in the review queue 118
A-COST cost days over the budget 1
A-RATE cost hours with a request spike 3
A-RATE cost user-hours over the limit 3
A-EXTRACT extraction users flagged 2
access uses of a tool outside the role 2
playbooks playbooks with a problem 0
recovery test questions that the active model fails 7
exit code 0Read the report as the on-call engineer would. Four record alerts, one user with a high refusal rate, and two tool uses outside the role: the injection of lesson 2. Three days of drift, and the model fails 7 test questions: lesson 3, and the cause lesson 7 removes. One day over the budget, three spikes and three user-hours over the limit: lesson 4. Two extractors: lesson 5. The own checks, the log scan and the playbooks, show 0, so the exit code is 0.
4. Run it on the quiet week
Week 1 is the baseline, and so it should be quiet. Pass its path to the kit.
python3 kit.py logs/week1.jsonldetection and response kit: logs/week1.jsonl
A-LOG-SECRET log records with something that must not be logged 0
A-INJ detect record alerts (score of 2 or more) 0
A-REFUSE detect user-days with a high refusal rate 0
A-DRIFT drift days with a PSI above the threshold 0
drift answers in the review queue 51
A-COST cost days over the budget 0
A-RATE cost hours with a request spike 0
A-RATE cost user-hours over the limit 0
A-EXTRACT extraction users flagged 0
access uses of a tool outside the role 0
playbooks playbooks with a problem 0
recovery test questions that the active model fails 7Every alert line is 0. Two lines are not: the review queue still holds the sample of answers for people, and the test set still shows the 7 wrong answers of the live model. Neither is an alert. They are standing work. The test-set line is a finding, not an own check: it says that the live model is weak, not that the kit is broken. If your policy says that the kit must not pass while the live model fails, add recovery to OWN.
5. Break the playbooks on purpose
The kit must fail when its own checks fail. First add a playbook with one empty section, run the kit, then remove it. Then put the whole folder away, so that the kit finds no playbook at all, and bring it back. printf writes the text it is given (\n is a new line), rm removes a file, mv moves or renames a folder, and rmdir removes an empty one. > /dev/null throws the output away, so that only the exit code shows.
printf '### Trigger\n\nnothing\n' > playbooks/bad.md
python3 kit.py | grep playbooks
python3 kit.py > /dev/null
echo "exit code $?"
rm playbooks/bad.md
mv playbooks playbooks.off
mkdir playbooks
python3 kit.py | grep playbooks
python3 kit.py > /dev/null
echo "exit code $?"
rmdir playbooks
mv playbooks.off playbooks
python3 kit.py > /dev/null playbooks playbooks with a problem 1
exit code 1
playbooks playbooks with a problem 1
exit code 1Both counts are 1 and both exit codes are 1. The kit has told you that it cannot be trusted until the playbook is fixed, and that missing playbooks are the same state, not a quiet one. The last run writes the report again from the sound folder.
6. Read the report file
kit-report.json holds the same lines for another program, such as a dashboard or a ticket. Print the lines with a count above 0: the alert id, or a dash, then the section and the count.
python3 -c "
import json
for r in json.load(open('kit-report.json')):
if r['count']:
print(r['alert'] or '-', r['section'], r['count'])
"A-INJ detect 4
A-REFUSE detect 1
A-DRIFT drift 3
- drift 118
A-COST cost 1
A-RATE cost 3
A-RATE cost 3
A-EXTRACT extraction 2
- access 2
- recovery 7All the files of the kit have been printed whole in their own lessons: eight modules, the generator and the data scripts, the playbooks and the leaky log. kit.py above is the last. After kr-lab.sh for this lesson (lesson 0), the lab folder is the kit.
Your turn
Files you need: all the modules of the table above, kit.py and the data of lesson 0 (kr-lab.sh for this lesson, then python3 makelogs.py). Add two rows to checks() in your copy of kit.py, with an empty alert id.
- A row
audit, "findings in the audit table": the number of rows ofaudit.findings(...)whose last item isFINDING. Build its three inputs as the end ofaudit.pydoes. - A row
retention, "records that retain() would delete": the number of records of the week thatretainreturnsNonefor, withnowset todatetime(2027, 1, 12).
Run the kit on week 2 and on week 1.
Check yourself
Why does the kit not exit with 1 when it finds alerts?
An alert says that something is happening in the world. A failure says that the kit cannot be trusted. If the two share one exit code, a busy week looks like a broken kit, and people stop looking at either. The report carries the alerts, and the exit code carries the health.
The kit calls each module and does not copy its rules. What does that buy you?
One place for each rule. When you change a threshold in detect.py, the kit, the lesson scripts and the review all follow, and no one has to hunt for a second copy that still has the old value.
The baseline file is fixed in the kit as `logs/week1.jsonl`. Name one risk and one remedy.
The baseline can become old, and nobody notices, so drift and spikes are measured against a week that no longer fits. Keep the baseline in the registry with its dates, review it on a calendar, and change it on purpose, with the old file kept.
What would you add to the kit for a real system that this lab does not have?
A source for the live log instead of a file, a place to send the report, a limit on how old the log may be, and a check that the detectors ran at all. A kit that silently reads an empty file would report a quiet week.
Field notes
- The kit needs the excerpt, which lives 7 days (lesson 1). Run it within that time, and keep its report: the report holds counts and ids, not text.
- Make the kit read the log in a stream if the log is large. The modules of this course load the whole file, which is fine for 1,400 records and not for 14 million.
- Run the kit from a scheduler, and alert when it does not run: a missing report is a signal of its own. Version the report. When someone asks in a year "what did we know on that Thursday?", the old reports are the answer, and the thresholds that were in force are in the repository at that date.
- Keep the kit in the same repository as the playbooks and the detectors, so that a change to a detector comes with a changed playbook, in one review. Run it in the build on a recorded attack week whose answers you know, so that a change that silences a detector fails the build.
- Measure the response in time: time to detect (the first bad record to the alert), time to contain and time to recover, taken from the record times and from
state/changes.jsonl. A programme is judged by these three numbers, so keep them for every incident.