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 13 · 50 minutes

Write the incident report and a runbook that someone else can follow

After this lesson you can
  • Generate the facts of an incident report from the logs, and add the judgement of the analyst
  • Measure how long detection, reaction and containment took
  • Write a runbook and check it with a program
Lab files of this lesson (50)

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 incident of Friday is contained. The director wants a report that she can read in five minutes and that the auditor can check: what happened, what it cost, how fast the team was, and what will change. The team lead wants a second paper: "Next time it may be you on call at three in the morning. Write the steps of the first fifteen minutes, so that anyone can follow them."

Recall

Lesson 12: the hash of a sealed file matches the manifest. What does that prove, and what does it not prove?

It proves that the file is the same as when you sealed it, not that the log was true when it was written.

Lesson 11: how do you write something that you believe but have not checked?

As an assumption, with its reason and the time when it will be checked, so that nobody acts on a guess as if it were known.

The idea

A report is written for readers who were not there: management, who need the summary and the decisions, and reviewers, who need the timeline and the sources. A good report has the same parts every time.

PartWhat it holds
SummaryWhat happened, in three sentences, and where the incident stands
ImpactWhat was touched: accounts, systems, the data that left, in numbers
TimelineThe key events in UTC, each with the file and line that prove it
MetricsTime to react and time to contain
Root causeWhy it was possible: a missing control, not a person
ChangesWhat will be different, each with an owner

Write facts first and name their source. Put assumptions in their own place. Use no blame and no adjective that you cannot measure. A program should produce every number, so that you copy none by hand.

Two measures show where the process is slow. The time to react runs from the first alert to the moment that an analyst takes it. The time to contain runs from the moment that the intruder got in to the moment that the access was cut.

A runbook is a short procedure for one kind of incident. It is read under stress, so it has numbered steps, an owner for each step, and no choice that is hidden in a paragraph of prose.

From a case to a better next time
Logs and alertsReportRoot causeChangesRunbookfacts and metricswhy it was possibleowners and datessteps for next timeLogs and alertsReportRoot causeChangesRunbook1234
  1. Logs and alerts → Report: facts and metrics
  2. Report → Root cause: why it was possible
  3. Root cause → Changes: owners and dates
  4. Changes → Runbook: steps for next time

Worked example

1. Write the notes of the analyst

The program computes the facts. You write what only a person knows: the times of your own actions, the root cause and the changes.

cat > case.json <<'EOT'
{
  "title": "Stolen account on web01",
  "address": "203.0.113.50",
  "acknowledged": "2026-11-20T13:10:00Z",
  "contained": "2026-11-20T13:25:00Z",
  "root_cause": "The password of mwebb was guessed. The account has no second factor and ssh accepts passwords from any address.",
  "changes": ["Turn on a second factor for every account that can log in by ssh", "Allow ssh only from the office network and the VPN", "Page the analyst on duty when rule R1 fires"]
}
EOT

2. Save the report program

report.py reads the notes, runs the rules, builds the timeline of lesson 12 with build, and writes incident-report.md. It finds the first successful login, the first alert about the address, and the largest response that the address received. max(items, key=...) returns the item with the largest key, and lambda e: e["bytes"] is a small function without a name that gives it. In an f-string, {n:,} writes a number with thousands separators. If the address has no successful login or no alert, it stops with a message. The list key holds the lines of the timeline that the report keeps: the first event, the first failure, the login, every sudo, user_add and cron_edit event, and every answer of one million bytes or more.

rows = build(events, case["address"])
entered = next((e for e in rows if e["action"] == "login" and e["outcome"] == "success"), None)
first_alerts = [a["last"] for a in alerts if a["group"] == case["address"]]
if not entered or not first_alerts:
    sys.exit("no successful login, or no alert, for " + case["address"])
alerted = min(first_alerts)
requests = [e for e in rows if e["action"] == "request"]
biggest = max(requests, key=lambda e: e["bytes"]) if requests else None
key = [(e["ts"], what(e), e["ref"]) for e in rows if e in (rows[0], failed, entered) or e["action"] in
       ("sudo", "user_add", "cron_edit") or (e["action"] == "request" and e["bytes"] >= 1000000)]

The rest builds the lines of the Markdown file from these facts and your notes. Save the whole program.

The finished file: report.py

report.py

"""report.py: write incident-report.md from the logs and the notes of the analyst.

    python3 report.py CASE.json [events.jsonl] [rules.json]
"""
import json
import sys
from datetime import datetime

from rules import load_events, run_rules
from timeline import build, what


def seconds(a, b):
    """Whole seconds between two times of the form 2026-11-20T13:03:00Z."""
    return int((datetime.fromisoformat(b.replace("Z", "+00:00")) - datetime.fromisoformat(a.replace("Z", "+00:00"))).total_seconds())


def span(s):
    return f"{s // 60} min {s % 60} s"


case = json.load(open(sys.argv[1]))
events = load_events(sys.argv[2] if len(sys.argv) > 2 else "events.jsonl")
alerts = run_rules(events, json.load(open(sys.argv[3] if len(sys.argv) > 3 else "rules.json")))
rows = build(events, case["address"])
entered = next((e for e in rows if e["action"] == "login" and e["outcome"] == "success"), None)
first_alerts = [a["last"] for a in alerts if a["group"] == case["address"]]
if not entered or not first_alerts:
    sys.exit("no successful login, or no alert, for " + case["address"])
alerted = min(first_alerts)
requests = [e for e in rows if e["action"] == "request"]
biggest = max(requests, key=lambda e: e["bytes"]) if requests else None
accounts = sorted({e["user"] for e in rows if e["user"]})
failed = next((e for e in rows if e["action"] == "login" and e["outcome"] == "failure"), None)
key = [(e["ts"], what(e), e["ref"]) for e in rows if e in (rows[0], failed, entered) or e["action"] in
       ("sudo", "user_add", "cron_edit") or (e["action"] == "request" and e["bytes"] >= 1000000)]
key += [(alerted, "first alert about the address", "alerts"), (case["acknowledged"], "analyst takes the alert", "notes"),
        (case["contained"], "account disabled and address blocked", "notes")]
lines = [f"# Incident report: {case['title']}", "", "## Summary", "",
         f"At {entered['ts']} the address {case['address']} logged in as {entered['user']} after "
         f"{sum(1 for e in rows if e['action'] == 'login' and e['outcome'] == 'failure')} failed guesses. "
         f"The incident was contained at {case['contained']}.", "", "## Impact", "",
         f"- Accounts involved: {', '.join(accounts)}",
         f"- Largest response sent to the address: {biggest['path']}, {biggest['bytes']:,} bytes" if biggest
         else "- No web request came from the address", "",
         "## Timeline (UTC)", "", "| Time | What | Source |", "|---|---|---|"]
lines += [f"| {t} | {w} | {r} |" for t, w, r in sorted(key)]
lines += ["", "## Metrics", "",
          f"- First alert to the analyst: {span(seconds(alerted, case['acknowledged']))}",
          f"- Access to containment: {span(seconds(entered['ts'], case['contained']))}", "",
          "## Root cause", "", case["root_cause"], "", "## Changes", ""]
lines += [f"- {c}" for c in case["changes"]]
open("incident-report.md", "w").write("\n".join(lines) + "\n")
print(f"incident-report.md written, {len(lines)} lines")

3. Run it and read the report

python3 report.py case.json
nl -ba -w2 -s' ' incident-report.md | sed -n '1,10p;28,31p' | cut -c1-120
incident-report.md written, 41 lines
 1 # Incident report: Stolen account on web01
 2 
 3 ## Summary
 4 
 5 At 2026-11-20T12:59:21Z the address 203.0.113.50 logged in as mwebb after 16 failed guesses. The incident was contain
 6 
 7 ## Impact
 8 
 9 - Accounts involved: mwebb, svc-update
10 - Largest response sent to the address: /admin/export/customers.csv, 2,481,722 bytes
28 ## Metrics
29 
30 - First alert to the analyst: 13 min 56 s
31 - Access to containment: 25 min 39 s
The two measures of the case (UTC)
12:56:04first alert: R1, 5 failed guesses12:59:21the intruder logs in as mwebb13:10:00analyst takes it, 13 min 56 s on13:25:00contained, 25 min 39 s on12:56:04first alert: R1, 5 failed guesses12:59:21the intruder logs in as mwebb13:10:00analyst takes it, 13 min 56 s on13:25:00contained, 25 min 39 s on

nl -ba numbers all lines of a file, and sed -n '1,10p;28,31p' prints lines 1 to 10 and 28 to 31: the summary, the impact and the metrics. The timeline in between has the key events of lesson 12. Check it like a reviewer: count the failed guesses in the timeline.csv of lesson 12 with grep -c "login failure" timeline.csv (-c prints the number of matching lines). It prints 16, the number in the summary. The first alert came at 12:56:04, three minutes before the login succeeded at 12:59:21, but the analyst took it 13 minutes 56 seconds later. A page at the first alert would have caught the intruder before the login. That is a finding about the process, so the notes ask for paging.

4. Check a runbook

A runbook of this lab is a plain text file. The title is the first line. Each section starts with a line # Name. The sections with numbered steps start every step with an owner in brackets: [SOC], [LEAD], [OWNER], [IT], [COMMS] or [LEGAL], the roles of lesson 11. A numbered step has three parts:

One step of a runbook
4.the number of the step[SOC]the role that actsSearch every log for the address...one action, at most 25 words4.the number of the step[SOC]the role that actsSearch every log for the address...one action, at most 25 words

runbook_check.py tests seven things: that all seven sections are there, that Severity names a level (SEV1 to SEV4), that Exit criteria has at least two points, and that every numbered step has a known owner and at most 25 words. It prints one problem on each line and exits with 1 if there is any. New in it: re.findall returns all matches of a pattern, (?m) lets ^ match at the start of every line, and sys.exit(1) ends the program with exit code 1. (The program also uses re.split to cut the text at every line that starts with # , one part for each section.) The check of the steps is the core.

for name in STEPS:
    for step in re.findall(r"(?m)^\d+\. (.*)$", body.get(name, "")):
        tag = re.match(r"\[(\w+)\] (.*)", step)
        if not tag:
            problems.append(f"{name}: step has no [ROLE]: {step[:30]}")
        elif tag[1] not in ROLES:
            problems.append(f"{name}: unknown role [{tag[1]}]")
        elif len(tag[2].split()) > MAX_WORDS:
            problems.append(f"{name}: step has more than {MAX_WORDS} words: {tag[2][:30]}")

Save the whole program.

The finished file: runbook_check.py

runbook_check.py

"""runbook_check.py: check that a runbook has what an analyst needs at three in the morning.

    python3 runbook_check.py RUNBOOK.txt        exit code 0 when it has no problem, 1 when it has
"""
import re
import sys

SECTIONS = ["Trigger", "Severity", "First 15 minutes", "Contain", "Evidence", "Communicate", "Exit criteria"]
STEPS = ["First 15 minutes", "Contain", "Evidence", "Communicate"]  # these sections hold numbered steps
ROLES = {"SOC", "LEAD", "OWNER", "IT", "COMMS", "LEGAL"}
MAX_WORDS = 25

text = open(sys.argv[1]).read()
parts = re.split(r"(?m)^# ", text)[1:]
body = {p.split("\n", 1)[0].strip(): p.split("\n", 1)[1] for p in parts}
problems = []
for name in SECTIONS:
    if name not in body:
        problems.append(f"missing section: {name}")
if "Severity" in body and not re.search(r"SEV[1-4]", body["Severity"]):
    problems.append("Severity: no level (SEV1 to SEV4) is named")
if "Exit criteria" in body and len(re.findall(r"(?m)^- ", body["Exit criteria"])) < 2:
    problems.append("Exit criteria: fewer than 2 points")
for name in STEPS:
    for step in re.findall(r"(?m)^\d+\. (.*)$", body.get(name, "")):
        tag = re.match(r"\[(\w+)\] (.*)", step)
        if not tag:
            problems.append(f"{name}: step has no [ROLE]: {step[:30]}")
        elif tag[1] not in ROLES:
            problems.append(f"{name}: unknown role [{tag[1]}]")
        elif len(tag[2].split()) > MAX_WORDS:
            problems.append(f"{name}: step has more than {MAX_WORDS} words: {tag[2][:30]}")
for p in problems:
    print("problem:", p)
print(f"{len(problems)} problem(s)")
sys.exit(1 if problems else 0)

A colleague wrote a first draft of the runbook for a stolen account.

cat > runbook-draft.txt <<'EOT'
Runbook: stolen account

# Trigger

An alert shows a successful login from an address that is not the usual address of the user.

# Severity

Customer data may have left: treat it as high until the facts say otherwise.

# First 15 minutes

1. [SOC] Open the alert and write down its id, the user and the address.
2. [SOC] Check the user file for the usual address of the account.
3. [LEAD] Decide the severity level and tell the people that the plan names.
4. [SOC] Search every log for the address and for the account, from the first failed login to now, and write each result into the ticket with the file name and the line number.

# Contain

1. [IT] Disable the account.
2. Block the address at the firewall.
3. [BOB] Reset the password of the account.

# Communicate

1. [LEAD] Send the first message in the time that the plan sets.
2. [COMMS] Write to the customers only when the lead agrees.

# Exit criteria

- The account is disabled.
EOT
python3 runbook_check.py runbook-draft.txt
echo "exit code $?"
problem: missing section: Evidence
problem: Severity: no level (SEV1 to SEV4) is named
problem: Exit criteria: fewer than 2 points
problem: First 15 minutes: step has more than 25 words: Search every log for the addre
problem: Contain: step has no [ROLE]: Block the address at the firew
problem: Contain: unknown role [BOB]
6 problem(s)
exit code 1

5. Fix it

The draft has six problems, one for each line of the output. [BOB] is a person and not a role: a runbook must stay valid when people change jobs. Fix each one in runbook-stolen-account.txt: add an Evidence section, name a level, add a second exit point, cut the long step in two, give the blocking step the owner [IT], and use [OWNER] for [BOB].

The fixed file, runbook-stolen-account.txt, is below. Compare it with yours.

runbook-stolen-account.txt

Runbook: stolen account

# Trigger

An alert shows a successful login from an address that is not the usual address of the user.

# Severity

SEV1 when customer data may have left. SEV2 when it did not.

# First 15 minutes

1. [SOC] Open the alert and write down its id, the user and the address.
2. [SOC] Check the user file for the usual address of the account.
3. [LEAD] Decide the severity level and tell the people that the plan names.
4. [SOC] Search every log for the address and for the account, from the first failed login to now.
5. [SOC] Write each result into the ticket with the file name and the line number.

# Contain

1. [IT] Disable the account.
2. [IT] Block the address at the firewall.
3. [OWNER] Reset the password of the account.

# Evidence

1. [SOC] Copy the logs into the case folder and write the hash of each file.
2. [SOC] Write the time of each action in the chain of custody.

# Communicate

1. [LEAD] Send the first message in the time that the plan sets.
2. [COMMS] Write to the customers only when the lead agrees.

# Exit criteria

- The account is disabled.
- The address is blocked.
python3 runbook_check.py runbook-stolen-account.txt
echo "exit code $?"
0 problem(s)
exit code 0

The checker tests the shape, not the sense. Only a made-up case, which the scenario test gives you, shows whether a step is right.

Your turn

First, write the report for day 2. The intruder is 198.51.100.140. The analyst took the alert at 09:55:00 UTC on 2026-11-23, and the access was cut at 10:05:00 UTC. Write case2.json with the root cause and two changes of your own, and run the report program over day 2 (events2.jsonl, rules.json). Second, a colleague wrote a runbook for password guessing from the internet. Fix it until the checker is silent. The runbook also needs a Communicate section: one [LEAD] step and one [COMMS] step.

cat > runbook-draft2.txt <<'EOT'
Runbook: scan and password guessing from the internet

# Trigger

Rule R1 or R2 fires for an address outside the company, and no login from that address succeeded.

# Severity

SEV4 when nothing got in. SEV2 when one login succeeded.

# First 15 minutes

1. [SOC] Open the alert and read the lines that it names.
2. [SOC] Search the auth log for a successful login from the same address.

# Contain

1. [ADMIN] Add the address to the block list.
2. Tell the owner of the system.

# Evidence

1. [SOC] Copy the logs of the day into the case folder, write the hash of each file, check the hash again before you open the copy, and keep the sealed copy read-only for the whole case.
2. [SOC] Write the time of each action in the chain of custody.

# Exit criteria

- The address is on the block list.
- The ticket holds the lines that show that no login succeeded.
EOT

Check yourself

Why does the report give the root cause as a missing control and not as the name of the person whose password was guessed?

One mistake was enough because the system allowed it. The fix that lasts is a control (a second factor, a limit on guesses, a restricted address). Blame stops people from reporting early.

The metrics show 13 minutes 56 seconds from the first alert to the analyst. What would you change, and how would you know it worked?

Page the analyst on duty when the rule fires, or raise the priority of that rule. You would know that it worked from the same measure in the next incident, and from the monthly figure for all alerts of that rule.

The checker says "0 problems". Is the runbook good?

Not necessarily. The shape is right, but whether the steps are right, in order and possible for the people on duty is known only after someone has followed the runbook on a realistic case.

Field notes

  • Hold a short blameless review after every incident of SEV2 or higher: what we knew when, what slowed us down, what helped. Give every change an owner and a date.
  • Keep the management report to one page. Put the full timeline, the hashes and the raw lines in a technical annex.
  • Know who must be told outside the company (authorities, customers, the insurer) and by when. The rules change, so take them from legal advice and the current texts.
  • Store runbooks next to the alert rules and review them together. Test each runbook at least once a year.