Two in the morning
At 02:14 an alert says files on the server are being renamed, fast. The on-call person has never seen this before.
Do they switch the server off, ring the boss, or pay? A playbook decides that in advance, so nobody has to invent it at 2am.
By the end of this lesson
Note
I can use a playbook to respond to a ransomware alert.
Key words
| Word | What it means | Example |
|---|---|---|
| Playbook | steps agreed in advance for one kind of incident | |
| Indicator | a sign in the logs that something is wrong | |
| Shadow copy | a snapshot Windows keeps for restoring files | |
| Containment | stopping an attack from spreading | |
| Approved change | planned work with a ticket | CHG-1042 |
| Scope | everything an incident touched |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsFive indicators, louder together
Each stage from lesson 1 leaves an indicator. Deleting shadow copies, a large upload, a burst of renames, a new file ending, and changes at night.
One alone can be innocent. Several from one account in minutes are not. detect.py checks a made-up log of Kestrel's file server for all five.
Move into the folder
cd ~/rr && ls mkshare.py manifest.py drill.py compare.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the log maker, part 1
printf '%s\n' 'import random' 'R = random.Random(1380)' 'STAFF = {"amorgan": "PC-02", "bpatel": "PC-03", "ckhan": "PC-04", "dowen": "PC-05", "jbrook": "PC-07", "lsingh": "PC-08"}' 'FOLDERS = ["clients", "letters", "payroll"]' 'rows = []' 'DAY = 86400' 'def at(sec):' ' day, sec = divmod(sec, DAY)' ' return "2026-11-%02d %02d:%02d:%02d" % (17 + day, sec // 3600, sec % 3600 // 60, sec % 60)' 'def add(sec, user, host, action, path, size=0):' ' rows.append((sec, at(sec), user, host, action, path, size))' 'for _ in range(420):' ' user = R.choice(sorted(STAFF))' ' folder = R.choice(FOLDERS)' ' add(R.randrange(8 * 3600, 18 * 3600), user, STAFF[user], R.choice(["read", "read", "write"]), f"{folder}/file-{R.randrange(1, 90):02}.txt", R.randrange(2000, 90000))' 'for n in range(40):' ' add(12 * 3600 + 1800 + n, "itadmin", "SRV-01", "rename", f"letters/2025/letter-{n + 1:02}.txt -> archive/2025/letter-{n + 1:02}.txt")' 'for n in range(6):' > mklog.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the log maker, part 2
printf '%s\n' ' add(DAY + 1 * 3600 + 30 * n, "svcbackup", "SRV-02", "read", f"backup/night-{n + 1}.part", 400000000)' 't = DAY + 2 * 3600 + 6 * 60 + 12' 'add(t, "jbrook", "PC-07", "logon", "remote desktop from 10.20.0.99")' 'add(t + 150, "jbrook", "PC-07", "process", "vssadmin delete shadows /all /quiet")' 'for n in range(60):' ' add(t + 200 + n, "jbrook", "PC-07", "read", f"payroll/file-{n + 1:02}.txt", R.randrange(20000, 90000))' 'add(t + 270, "jbrook", "PC-07", "upload", "203.0.113.50:443", 1800000000)' 'start = t + 330' 'for n in range(180):' ' folder = FOLDERS[n % 3]' ' add(start + n // 2, "jbrook", "PC-07", "rename", f"{folder}/file-{n // 3 + 1:02}.txt -> {folder}/file-{n // 3 + 1:02}.txt.locked")' 'for folder in FOLDERS:' ' add(start + 95, "jbrook", "PC-07", "write", f"{folder}/HOW-TO-RECOVER.txt", 900)' 'rows.sort()' 'with open("fileserver.csv", "w") as f:' ' f.write("time,user,host,action,path,bytes" + chr(10))' ' for row in rows:' >> mklog.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the log maker, part 3
printf '%s\n' ' f.write(",".join(str(x) for x in row[1:]) + chr(10))' 'print("wrote fileserver.csv,", len(rows), "events")' >> mklog.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Make the file server's log
python3 mklog.py && head -3 fileserver.csvShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the detector, part 1
printf '%s\n' 'import csv, collections, sys' 'rows = list(csv.DictReader(open(sys.argv[1])))' 'changes = list(csv.DictReader(open(sys.argv[2]))) if len(sys.argv) > 2 else []' 'def secs(row):' ' h, m, s = row["time"][11:].split(":")' ' return int(h) * 3600 + int(m) * 60 + int(s)' 'def approved(user, when):' ' for c in changes:' ' if c["user"] == user and c["start"] <= when <= c["end"]:' ' return c["ticket"]' 'alerts = []' 'def alert(rule, row, text):' ' ticket = approved(row["user"], row["time"])' ' alerts.append((row["time"], rule, row["user"], row["host"], text, ticket))' 'renames = collections.defaultdict(list)' 'for row in rows:' ' if row["action"] == "rename":' ' renames[row["user"]].append(row)' 'for user, items in renames.items():' ' for i, row in enumerate(items):' > detect.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the detector, part 2
printf '%s\n' ' window = [r for r in items[i:] if secs(r) - secs(row) < 60]' ' if len(window) >= 20:' ' alert("R1 rename burst", row, f"{len(window)} renames in 60 seconds")' ' break' 'seen = set()' 'for row in rows:' ' if row["action"] == "rename":' ' ext = row["path"].rsplit(".", 1)[-1]' ' old = row["path"].split(" -> ")[0].rsplit(".", 1)[-1]' ' if not ext == old and ext not in seen:' ' seen.add(ext)' ' alert("R2 new extension", row, "files renamed to ." + ext)' ' if row["action"] == "process" and "delete shadows" in row["path"].lower():' ' alert("R3 shadow copies deleted", row, row["path"])' ' if row["action"] == "upload" and int(row["bytes"]) > 500000000:' ' mb = int(row["bytes"]) // 1000000' ' alert("R4 large upload", row, f"{mb} MB to " + row["path"])' >> detect.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the detector, part 3
printf '%s\n' ' if row["action"] in ("write", "rename") and row["time"][11:] < "06:00:00" and not row["user"].startswith("svc"):' ' if not [a for a in alerts if a[1] == "R5 night-time changes" and a[2] == row["user"]]:' ' alert("R5 night-time changes", row, "changes files between midnight and 06:00")' 'for when, rule, user, host, text, ticket in sorted(alerts):' ' print(when, "APPROVED " + ticket if ticket else "ALERT", rule.ljust(25), user, host, text)' >> detect.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Run the five rules over the log
python3 detect.py fileserver.csvShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsA common mistake
Warning
Many people think a burst of renames always means ransomware. An administrator moving last year's letters does the same. Check the change tickets before you raise the alarm, and look for the other indicators beside it.
Write the day's approved changes
printf '%s\n' 'user,start,end,ticket' 'itadmin,2026-11-17 12:00:00,2026-11-17 13:00:00,CHG-1042' > changes.csvShown here, not run. Press Start lab to type it into your own lab’s terminal.
Run the rules again with the approved changes
python3 detect.py fileserver.csv changes.csvShown here, not run. Press Start lab to type it into your own lab’s terminal.
Find the scope before you restore
Before restoring, find the scope: which account, which machines, which folders, and what left the building. Restore too little and files stay broken. Restore before containment and they are locked again.
scope.py lists what one account did since a time.
Write the scoper
printf '%s\n' 'import csv, collections, sys' 'user, since = sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else ""' 'rows = [r for r in csv.DictReader(open(sys.argv[1])) if r["user"] == user and r["time"] >= since]' 'print("Account:", user, " events since", since or "the start", len(rows))' 'print("First:", rows[0]["time"], rows[0]["action"], rows[0]["path"])' 'print("Last: ", rows[-1]["time"], rows[-1]["action"], rows[-1]["path"])' 'print("Hosts:", ", ".join(sorted({r["host"] for r in rows})))' 'locked = collections.Counter(r["path"].split("/")[0] for r in rows if r["path"].endswith(".locked"))' 'for folder, n in sorted(locked.items()):' ' print("Folder to restore:", folder, n, "files renamed")' 'for r in rows:' ' if r["action"] in ("upload", "process"):' ' print("Also:", r["time"][11:], r["action"], r["path"], r["bytes"] if r["action"] == "upload" else "")' > scope.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Scope what jbrook did that night
python3 scope.py fileserver.csv jbrook "2026-11-18 00:00"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsThe playbook, in order
Contain first: take PC-07 off the network and disable jbrook. Keep the machine powered on, since memory holds evidence.
Preserve the logs, find the scope, then rebuild what was touched. Recover from the locked copy after a restore test. Report, and write down what to change.
Worked example: Kestrel's playbook
| Step | What Kestrel does | Who |
|---|---|---|
| 1 Contain | Unplug PC-07 from the network, disable jbrook, block 203.0.113.50 | On-call |
| 2 Preserve | Copy the logs and the vault's log somewhere safe | On-call |
| 3 Scope | Run scope.py; list folders, machines and data taken | Security lead |
| 4 Eradicate | Rebuild PC-07, reset passwords, close the way in | IT |
| 5 Recover | Restore the three folders from the vault, after a restore test | IT |
| 6 Report | The ICO within 72 hours if personal data is at risk; the police and the NCSC | Director |
| 7 Learn | Review within two weeks: what worked, what to change | Everyone |
The cells students fill in are left blank in this preview.
What the authorities say about paying
The NCSC and UK law enforcement do not encourage or condone paying a ransom. Paying does not guarantee the data back, and the stolen copy may still be published.
Paying can also break sanctions law. In July 2025 the government said it would ban payments by public bodies and critical services. Check the law as it stands.
Check
Have a go
Check
3 questionsAssignment: find bursts and follow the playbook
An event is a tuple (seconds, user, action).
bursts(events, window, limit) returns the sorted users with at least limit events whose action is "rename" inside some stretch shorter than window seconds (from one rename to another less than window later).
approved(user, time, changes) returns True when a change in changes (dictionaries with "user", "start" and "end") is for that user and start <= time <= end.
next_step(done) returns the first step of PLAYBOOK not in the set done, or None when all are done.
PLAYBOOK = ["contain", "preserve", "scope", "eradicate", "recover", "report", "learn"]
def bursts(events, window, limit):
return []
def approved(user, time, changes):
return False
def next_step(done):
return None
Make a free account to save your work and track your progress.
Exit quiz
Have a go