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

Triage eight alerts with context and decide what to do first

After this lesson you can
  • Say what a true positive, a false positive and an impact are, and tell them apart with context
  • Enrich an alert from an asset file, a staff file, a threat feed and a change record
  • Give every alert a verdict and a priority, and explain the decision in one line
Lab files of this lesson (13)

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

Monday morning. The six rules of lesson 3 have raised eight alerts on the logs of Friday. The team lead does not ask for more rules. She asks: "Which of these are real, which got in, and what do I do first? Give me a reason for each one, in one line." Triage is that job: fast, with the facts that you can look up, and with a decision that you can defend.

Recall

Lesson 3: what is a false positive, and which alerts of lesson 3 were one?

An alert for harmless activity. The 105 downloads of the public catalogue were false positives of R3 before the allow-list. The scan from 192.0.2.7 may be one too, which is what this lesson decides.

Lesson 3: why did we not put 192.0.2.7 on the allow-list of R2?

An allow-list says "never look at this again". The scan is harmless only when an approved change covers that hour, and that is a fact to check for each alert, not for ever.

The idea

Triage is the first decision about an alert. It answers four questions, in this order: who or what is it, is it expected, did it work, and what do we do first.

Two sets of words matter. A true positive is an alert about real activity that you do not want. A false positive is an alert about harmless activity. A true positive can still be harmless in effect: a scanner that tried and failed is real, and nothing was lost. In this course an approved scan counts as a false positive, because the alert needs no action. Other teams may use the words in a different way. Impact means that the activity succeeded. Severity is what the rule author thought about one alert of the rule, before looking at anything. Priority is what you do first, after the context. Context can raise or lower the priority.

Enrichment is adding facts to an alert from other sources. It is the largest part of the work of a first-level analyst.

The triage questions
AlertWho is itIs it expectedDid it workPrioritycontext filesapproved change?success from addressP1 now to P4 closeAlertWho is itIs it expectedDid it workPriority1234
  1. Alert → Who is it: context files
  2. Who is it → Is it expected: approved change?
  3. Is it expected → Did it work: success from address
  4. Did it work → Priority: P1 now to P4 close

The decision table that this lesson builds is a policy, and your team sets its own:

VerdictPriority
True positive, impactP1: act now
True positive, no impact, severity mediumP2: look today
True positive, no impact, severity lowP3: look this week
False positiveP4: close, and tune the rule

A threat feed is only a hint. An address that is not on a feed is not safe: every attacker is new once.

Worked example

1. Check your rules and write the context files

The triage works on the alerts of the six rules of lesson 3. Your rules.json should be the file below. If yours differs, save this one, so that your numbers match this lesson.

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"]}},
  {"id": "R4", "title": "New account created", "severity": "high",
   "where": {"action": "user_add"}, "group_by": "user"},
  {"id": "R5", "title": "Database words in a web path", "severity": "medium",
   "where": {"action": "request"}, "contains": {"path": ["%27", "UNION", "DROP"]}, "group_by": "ip", "window_s": 60},
  {"id": "R6", "title": "Many firewall blocks from one address", "severity": "low",
   "where": {"action": "firewall_block"}, "group_by": "ip", "count": 5, "window_s": 120}
]
EOT

Then four small files, all invented. assets.csv lists the machines of the company by address. staff.csv gives each user and the usual address of that user. known_bad.csv is a feed of reported addresses. changes.csv lists approved tasks with a ticket and a time range in UTC.

cat > assets.csv <<'EOT'
ip,host,owner,role,criticality
192.0.2.5,monitor01,it,monitoring,2
192.0.2.7,scan01,it,vulnerability scanner,2
192.0.2.8,ci01,dev,build server,3
192.0.2.10,web01,web,public web server,4
192.0.2.20,db01,web,customer database,5
192.0.2.101,ws-alice,editorial,workstation,2
192.0.2.102,ws-bob,editorial,workstation,2
192.0.2.103,ws-carol,sales,workstation,2
192.0.2.104,ws-mwebb,editorial,workstation,2
192.0.2.105,ws-pdiaz,sales,workstation,2
EOT
cat > staff.csv <<'EOT'
user,name,team,usual_ip
alice,Alice Okafor,editorial,192.0.2.101
bob,Bob Lind,editorial,192.0.2.102
carol,Carol Nwosu,sales,192.0.2.103
mwebb,Mara Webb,editorial,192.0.2.104
pdiaz,Pedro Diaz,sales,192.0.2.105
deploy,Deploy job,dev,192.0.2.8
EOT
cat > known_bad.csv <<'EOT'
ip,note
198.51.100.77,listed by a public feed as a mass scanner
198.51.100.23,listed by a public feed for attacks on web forms
EOT
cat > changes.csv <<'EOT'
ip,what,start,end,ticket
192.0.2.7,vulnerability scan of web01,2026-11-20T00:20:00Z,2026-11-20T00:50:00Z,CHG-1042
EOT

2. Save the triage program

triage.py has four functions. enrich collects the facts: the asset row, the feed note, the successful logins from the same address, those logins that are not from the usual address of the user (odd), and the change record that covers the time of the alert. verdict and priority apply the table above. triage does it for all alerts and sorts them, most urgent first. New in it: csv.DictReader reads a CSV file as dictionaries (Python lesson 4), next(generator, None) takes the first item of a sequence or None, and f["odd"] is a list that is empty when there is no such login.

triage.py

"""triage.py: add context to alerts and decide what each alert is.

    python3 triage.py [events.jsonl] [rules.json] [context folder]
"""
import csv
import json
import sys

from rules import load_events, run_rules


def read_csv(path):
    with open(path, newline="") as src:
        return list(csv.DictReader(src))


def load_context(folder="."):
    """The fixed files that give an alert its context."""
    return {"assets": {r["ip"]: r for r in read_csv(f"{folder}/assets.csv")},
            "staff": {r["user"]: r for r in read_csv(f"{folder}/staff.csv")},
            "known": {r["ip"]: r["note"] for r in read_csv(f"{folder}/known_bad.csv")},
            "changes": read_csv(f"{folder}/changes.csv")}


def enrich(alert, events, ctx):
    """Collect the facts that an analyst looks up: who is it, is there a change, did it get in?"""
    who = alert["group"]
    success = [e for e in events if e["ip"] == who and e["action"] == "login" and e["outcome"] == "success"]
    odd = [e for e in success if e["user"] in ctx["staff"] and ctx["staff"][e["user"]]["usual_ip"] != who]
    change = next((c for c in ctx["changes"] if c["ip"] == who and c["start"] <= alert["first"]
                   and alert["last"] <= c["end"]), None)
    return {"asset": ctx["assets"].get(who), "known": ctx["known"].get(who), "success": success, "odd": odd,
            "change": change}


def verdict(alert, facts):
    """False positive, true positive with impact, or true positive without impact."""
    if facts["change"]:
        return "false positive"
    if facts["odd"] or alert["severity"] == "high":
        return "true positive, impact"
    return "true positive, no impact"


def priority(alert, decision):
    """1 is the most urgent."""
    if decision == "false positive":
        return 4
    if decision == "true positive, impact":
        return 1
    return 2 if alert["severity"] == "medium" else 3


def triage(alerts, events, ctx):
    """One record for each alert, the most urgent first."""
    records = []
    for a in alerts:
        facts = enrich(a, events, ctx)
        decision = verdict(a, facts)
        records.append({"alert": a, "facts": facts, "verdict": decision, "priority": priority(a, decision)})
    return sorted(records, key=lambda r: (r["priority"], r["alert"]["last"]))


if __name__ == "__main__":
    events = load_events(sys.argv[1] if len(sys.argv) > 1 else "events.jsonl")
    alerts = run_rules(events, json.load(open(sys.argv[2] if len(sys.argv) > 2 else "rules.json")))
    for r in triage(alerts, events, load_context(sys.argv[3] if len(sys.argv) > 3 else ".")):
        a, f = r["alert"], r["facts"]
        note = f["change"]["ticket"] if f["change"] else (f["known"] or "")
        print(f"P{r['priority']} {a['id']} {a['rule']} {a['group']:15s} {r['verdict']:24s} {note}")

3. Run it on Friday

python3 triage.py
P1 A006 R1 203.0.113.50    true positive, impact    
P1 A007 R3 203.0.113.50    true positive, impact    
P1 A008 R4 svc-update      true positive, impact    
P2 A004 R1 198.51.100.77   true positive, no impact listed by a public feed as a mass scanner
P2 A005 R5 198.51.100.23   true positive, no impact listed by a public feed for attacks on web forms
P3 A002 R6 198.51.100.77   true positive, no impact listed by a public feed as a mass scanner
P3 A003 R2 198.51.100.77   true positive, no impact listed by a public feed as a mass scanner
P4 A001 R2 192.0.2.7       false positive           CHG-1042
One line of the triage output
P1priority, 1 is the most urgentA006alert idR1rule that fired203.0.113.50address that the alert groupstrue positive, impactverdictP1priority, 1 is the most urgentA006alert idR1rule that fired203.0.113.50address that the alert groupstrue positive, impactverdict
Alerts of Friday by priority
P1 act now3P2 look today2P3 look this week2P4 close1P1 act now3P2 look today2P3 look this week2P4 close1

Eight alerts: three P1, two P2, two P3 and one P4. The P4 is the scan of the company's own scanner, closed by ticket CHG-1042. The two P1 alerts for 203.0.113.50 are the same intruder, and the third P1 is the new account. The address 198.51.100.77 is on the feed, but nothing got in, so it is not P1.

4. Go from an alert to the raw lines

Never trust the decision of a program that you have not checked once by hand. The field refs of an alert holds the file and line of every event behind it. Print the alert A006 and open two of its lines. sed -n '112p;116p' prints lines 112 and 116 of a file and nothing else.

python3 - <<'PYEND'
import json
from rules import load_events, run_rules

alerts = run_rules(load_events("events.jsonl"), json.load(open("rules.json")))
a = next(a for a in alerts if a["id"] == "A006")
print(a["rule"], a["group"], a["first"], a["last"], a["count"])
print(a["refs"][:3])
PYEND
sed -n '112p;116p' data/auth.log
R1 203.0.113.50 2026-11-20T12:55:04Z 2026-11-20T12:56:04Z 5
['auth.log:112', 'auth.log:113', 'auth.log:114']
Nov 20 13:55:04 web01 sshd[1582]: Failed password for mwebb from 203.0.113.50 port 51191 ssh2
Nov 20 13:56:04 web01 sshd[1606]: Failed password for mwebb from 203.0.113.50 port 35409 ssh2

The alert says five failures for one address from 12:55:04 to 12:56:04 UTC. The raw lines show the same user, mwebb, guessed from 203.0.113.50. The triage program then found a success from that address for mwebb, whose usual address is 192.0.2.104. That is what made it P1.

5. Know what the program cannot see

verdict knows only what the files and the events tell it. It does not know that a customer export is damage, and it did not need to here, because the same address had a success. It would call a lone SQL injection attempt "no impact" even if the server had answered it with a large page. Lesson 15 shows such a case. Lesson 6 triages alerts of an endpoint tool in the same way. The tool ranks. The analyst decides.

Your turn

Day 2 is the second set of logs from lesson 3 (events2.jsonl). Ticket CHG-1043 covers a scan from 192.0.2.7 on 2026-11-23, from 00:20 to 00:50 UTC. Make a context folder day2 that holds the four context files of this lesson with that ticket added to the changes. Run the triage program over day 2 with that folder, and then once with the folder of Friday (the current folder .), and compare the verdict for 192.0.2.7. The program takes the context folder as its third argument.

Check yourself

An alert is a true positive but has no impact. Why is it not closed?

It is real activity by someone who wants in, and the next attempt may use what the first one learned. You note it, you may block the address, and you watch whether the same address comes back. It gets a lower priority, not none.

The feed does not list 203.0.113.50. What follows from that?

Nothing. A feed only knows what others have seen and reported. The intruder of lesson 1 used an address that was on no list, and the decision came from the logs: a login for a user from an address that is not that user's usual address.

Why does the change record decide the scanner alert and not the address in assets.csv?

The asset file says that 192.0.2.7 is our scanner, but a scanner that starts at an unusual hour may have been misused, or the address may have been copied. The change record says that this scan was approved for this time. Who it is and whether it is expected are two questions.

The alert for the new account has no address. Which part of the triage still works?

The change record and the staff file work if you look the user up. The "did it work" step needs an address, so for an alert that is grouped by a user (rule R4) the program leans on the severity of the rule, which is high. An analyst would also read the sudo line before it.

Field notes

  • Write the triage questions as a checklist in the ticket form, so that every analyst answers the same questions in the same order, and a second person can review the decision.
  • Measure the work. Track for each rule how many alerts were false positives, how long triage took, and how many alerts were not looked at. These three numbers tell you which rule to tune first.
  • Never close an alert because of one fact. An approved scan time is a reason for a false positive only when the source and the activity both match the ticket.
  • Keep the asset, staff and change data fresh. Triage with a stale asset list is wrong in a quiet way: it calls a new unknown server "ours" or an old server "unknown".
  • Alert fatigue is a security risk. When analysts see hundreds of false alerts, they miss the real one. Tuning rules is part of the job, and so is the right to switch a rule off with a reason.