Lesson 12 · 55 minutes
Contain an intrusion, keep the evidence safe and build the timeline
- Seal log files as evidence with hashes, and prove that a copy has not changed
- Turn the urgent alerts into a list of addresses to block and accounts to disable
- Build the timeline of an intrusion from the events of several logs
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 three P1 alerts of Friday are confirmed: someone guessed the password of mwebb, logged in, took an export of customer data and made a new account. The incident lead says: "Stop it, and keep proof. Before anybody touches the server, I want the logs sealed, because this may go to a lawyer. Then tell me what happened, in order." You work on your own lab copy of the logs. The rules are the rules of a real case: preserve, contain, then analyse the copies.
Recall
Lesson 11: why does the state "contained" come before "eradicated"?
Containing stops the harm from growing. Removing the cause takes time and a clear picture, and if you do it first you may warn the attacker and destroy evidence. Stop first, then clean.
Lesson 2: what is the field ref of an event for?
It names the file and the line that the event came from. Every alert and every line of a report can then be traced back to the raw line.
The idea
Digital evidence is any data that can show what happened. It is useful only if you can show that it is the same as when you took it. Four habits make that possible.
- Preserve first. Copy the data before you change anything. Data that disappears fast (memory, open connections, running processes) goes first, and files and logs after it. This lab holds files only.
- Hash the copy. A hash such as SHA-256 is a fixed-length fingerprint of the bytes of a file. If one bit changes, the hash changes completely. A list of hashes is a manifest.
- Work on copies. The sealed copy is read-only. You analyse a second copy, and you can always compare it with the seal.
- Write a chain of custody. A chain of custody is a record of who handled each item, when, and what they did with it.
A hash proves that a file did not change after you sealed it. It does not prove that the log was true when it was written: a root user could have edited it before you took it.
Containment stops the harm from spreading: block the address, disable the account, isolate the host. Choose the smallest action that works, and write down its time. A timeline lists everything that is connected to the case, in time order, from every log, each line with its source. Build it by pivoting: start from one fact (the address), add what it touched (the account), and add what that account did (a new account and its jobs).
- Preserve → Contain: copy and hash logs
- Contain → Analyse copies: block and disable
- Analyse copies → Timeline: all logs, one clock
- Timeline → Report: facts, assumptions
Worked example
1. Save the three programs
This lesson uses three programs: evidence.py (keeps the evidence), contain.py (lists what to stop) and timeline.py (orders the events). Save them from the block below, then read the steps: each step explains the part of a program that matters and runs it.
The finished files: evidence.py, contain.py and timeline.py
evidence.py
"""evidence.py: keep copies of evidence, prove that they did not change, and note who handled them.
python3 evidence.py seal FOLDER FILE... copy the files into case/evidence, write case/manifest.sha256
python3 evidence.py verify check the copies against the manifest (exit code 1 if one differs)
"""
import getpass
import hashlib
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path
CASE = Path("case")
MANIFEST = CASE / "manifest.sha256"
CUSTODY = CASE / "custody.csv"
def digest(path):
"""The SHA-256 hash of a file, read in blocks so that a big file does not fill the memory."""
h = hashlib.sha256()
with open(path, "rb") as src:
for block in iter(lambda: src.read(65536), b""):
h.update(block)
return h.hexdigest()
def note(action, name, hexdigest):
"""Append one line to the chain of custody: when, who, what was done, to which file, and its hash."""
if not CUSTODY.exists():
CUSTODY.write_text("time,who,action,file,sha256\n")
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
with open(CUSTODY, "a") as out:
out.write(f"{now},{getpass.getuser()},{action},{name},{hexdigest}\n")
def seal(folder, names):
(CASE / "evidence").mkdir(parents=True, exist_ok=True)
taken = [n for n in names if (CASE / "evidence" / n).exists()]
if taken: # evidence is never overwritten
sys.exit(f"already sealed: {', '.join(taken)} (use a new case folder)")
lines = []
for name in names:
copy = CASE / "evidence" / name
shutil.copy2(Path(folder) / name, copy)
copy.chmod(0o444) # read-only: a slip of the hand cannot change it
h = digest(copy)
if h != digest(Path(folder) / name):
sys.exit(f"{name}: the copy differs from the original")
lines.append(f"{h} {name}\n")
note("sealed", name, h)
print(f"sealed {name} {h[:12]}")
with open(MANIFEST, "a") as out: # the same format as the tool sha256sum
out.write("".join(lines))
def verify():
if not MANIFEST.exists():
sys.exit("no manifest: run seal first")
bad = 0
for line in MANIFEST.read_text().splitlines():
want, name = line.split(" ", 1)
path = CASE / "evidence" / name
got = digest(path) if path.exists() else None
state = "OK" if got == want else "FAILED" if got else "MISSING"
bad += state != "OK"
note("verified" if state == "OK" else "MISMATCH", name, got or "-")
print(f"{name}: {state}")
return 1 if bad else 0
if __name__ == "__main__":
if sys.argv[1:2] == ["seal"] and len(sys.argv) > 3:
seal(sys.argv[2], sys.argv[3:])
elif sys.argv[1:2] == ["verify"]:
sys.exit(verify())
else:
sys.exit(__doc__)contain.py
"""contain.py: from the urgent alerts, list the addresses to block and the accounts to disable.
python3 contain.py [events.jsonl] [rules.json] [context folder]
"""
import json
import sys
from rules import load_events, run_rules
from triage import load_context, triage
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")))
block, disable = {}, {} # what to act on -> why
for r in triage(alerts, events, load_context(sys.argv[3] if len(sys.argv) > 3 else ".")):
a = r["alert"]
if r["priority"] != 1:
continue
if a["by"] == "ip":
block.setdefault(a["group"], []).append(a["id"])
if a["by"] == "user":
disable.setdefault(a["group"], []).append(a["id"])
for e in r["facts"]["odd"]:
disable.setdefault(e["user"], []).append(a["id"])
for what, items in (("block", block), ("disable", disable)):
for name, why in sorted(items.items()):
print(f"{what:8s}{name:16s}alerts {', '.join(sorted(set(why)))}")
open("blocklist.txt", "w").write("".join(f"{ip}\n" for ip in sorted(block)))
open("disable.txt", "w").write("".join(f"{user}\n" for user in sorted(disable)))
print(f"{len(block)} address(es) in blocklist.txt, {len(disable)} account(s) in disable.txt")timeline.py
"""timeline.py: build the timeline of one intruder address from the events of all logs.
python3 timeline.py ADDRESS [events.jsonl] writes timeline.csv
"""
import csv
import sys
from rules import load_events
def build(events, address):
"""The events of the address, of the accounts that it reached, and of the accounts that those accounts made.
A sudo line such as "useradd -m svc-update" names the account that was made."""
mine = [e for e in events if e["ip"] == address]
if not mine:
return []
start = mine[0]["ts"]
first_in = next((e for e in mine if e["action"] == "login" and e["outcome"] == "success"), None)
users = {first_in["user"]} if first_in else set()
rows = []
for _ in range(2): # the second pass sees the accounts that the first pass found
rows = [e for e in events if e["ts"] >= start and (e["ip"] == address or e["user"] in users)]
users |= {e["msg"].split()[-1] for e in rows if e["action"] == "sudo" and "useradd" in e["msg"]}
return rows
def what(e):
"""One short line that says what happened."""
if e["action"] == "request":
return f"{e['method']} {e['path']} -> {e['status']}, {e['bytes']} bytes"
if e["action"] == "login":
return f"login {e['outcome']} for {e['user']}"
if e["action"] == "firewall_block":
return f"firewall blocked {e['ip']} on port {e['port']}"
detail = e["msg"] if e["action"] == "sudo" else ""
return " ".join(part for part in (e["action"], e["outcome"], e["user"], detail) if part)
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(__doc__)
rows = build(load_events(sys.argv[2] if len(sys.argv) > 2 else "events.jsonl"), sys.argv[1])
if not rows:
sys.exit("no events for " + sys.argv[1])
with open("timeline.csv", "w", newline="") as out:
writer = csv.writer(out)
writer.writerow(["time", "source", "what", "ref"])
for e in rows:
writer.writerow([e["ts"], e["source"], what(e), e["ref"]])
print(f"{len(rows)} events from {rows[0]['ts']} to {rows[-1]['ts']} in timeline.csv")2. Seal the logs
evidence.py has two jobs. seal copies the files you name into case/evidence, makes each copy read-only, checks that the copy has the same hash as the original, writes the manifest in the format of the Linux tool sha256sum, and adds a line to the chain of custody for each file. It refuses to seal a name twice, because evidence is never overwritten. verify hashes the copies again and compares them with the manifest. It says MISSING for a copy that is gone.
The first function, digest, makes the hash. hashlib.sha256() makes a hash that you feed with update, and iter(function, b"") calls the function until it returns an empty value, so a big file is read in blocks.
def digest(path):
h = hashlib.sha256()
with open(path, "rb") as src:
for block in iter(lambda: src.read(65536), b""):
h.update(block)
return h.hexdigest()The heart of seal is four lines for each file. shutil.copy2 copies a file with its times, chmod(0o444) makes the copy read-only, and sys.exit(text) stops the program with that message if the copy and the original do not give the same hash.
shutil.copy2(Path(folder) / name, copy)
copy.chmod(0o444) # read-only: a slip of the hand cannot change it
h = digest(copy)
if h != digest(Path(folder) / name):
sys.exit(f"{name}: the copy differs from the original")The rest is writing the manifest and the custody line (getpass.getuser() is the name of the user). Now seal the three logs of day 1.
python3 evidence.py seal data auth.log access.log syslog
cut -c1-12,65- case/manifest.sha256sealed auth.log 20c90abd2b56
sealed access.log 4552a5c6d74b
sealed syslog a6d4a1dbfbea
20c90abd2b56 auth.log
4552a5c6d74b access.log
a6d4a1dbfbea syslogThe first twelve characters of each hash are the ones that the generator printed in lesson 1. Now the chain of custody.
cut -d, -f1-4 case/custody.csvtime,who,action,file
2026-11-21T14:23:01Z,you,sealed,auth.log
2026-11-21T14:23:01Z,you,sealed,access.log
2026-11-21T14:23:01Z,you,sealed,syslogThe times and the user name are yours. If you run the seal command a second time, the tool stops with already sealed and changes nothing.
3. Check with the standard tool
The manifest has the format of sha256sum, so the tool that every Linux system has can check it. The option -c (check) reads a list of hashes and tests each file. Run it inside the folder of the copies. The brackets run the commands in a small shell of their own, so that you stay in your lab folder.
(cd case/evidence && sha256sum -c ../manifest.sha256)auth.log: OK
access.log: OK
syslog: OK4. Change one letter, and see it
Make the copy writable, replace the name mwebb by mwebc in it, and verify. sed -i edits a file in place. The program must stop with an exit code of 1.
chmod u+w case/evidence/auth.log
sed -i 's/Accepted password for mwebb/Accepted password for mwebc/' case/evidence/auth.log
python3 evidence.py verify
echo "exit code $?"auth.log: FAILED
access.log: OK
syslog: OK
exit code 1One changed letter is found. Put the file back from the original (cp -p keeps the file times), make it read-only again, and verify once more.
cp -p data/auth.log case/evidence/auth.log
chmod 444 case/evidence/auth.log
python3 evidence.py verify
echo "exit code $?"
grep -c MISMATCH case/custody.csvauth.log: OK
access.log: OK
syslog: OK
exit code 0
1The mismatch stays in the chain of custody, which is right: the record shows the check, the failure and the repair.
5. Decide what to stop
contain.py runs the triage of lesson 4, keeps the alerts of priority 1, and makes two lists. An alert grouped by an address puts the address on the block list. An alert grouped by a user, and every user that logged in from an address that is not theirs, goes on the list of accounts to disable. It writes blocklist.txt and disable.txt, and says which alerts caused each entry. The loop is the heart of it. setdefault(key, []) gives the list of a key and makes it first if it is new. The line for e in r["facts"]["odd"] takes the users that logged in from an address that is not theirs.
for r in triage(alerts, events, load_context(sys.argv[3] if len(sys.argv) > 3 else ".")):
a = r["alert"]
if r["priority"] != 1:
continue
if a["by"] == "ip":
block.setdefault(a["group"], []).append(a["id"])
if a["by"] == "user":
disable.setdefault(a["group"], []).append(a["id"])
for e in r["facts"]["odd"]:
disable.setdefault(e["user"], []).append(a["id"])Run it.
python3 contain.py
cat blocklist.txt disable.txtblock 203.0.113.50 alerts A006, A007
disable mwebb alerts A006, A007
disable svc-update alerts A008
1 address(es) in blocklist.txt, 2 account(s) in disable.txt
203.0.113.50
mwebb
svc-updateOne address and two accounts: mwebb, whose password was guessed, and svc-update, the account that the intruder made. The program only writes the lists. An administrator applies them with the firewall ("Linux", Part 3, lesson 3) and the account tools (Part 2, lesson 6). That needs administrator rights, so this lab does not do it.
6. Build the timeline
timeline.py takes the intruder's address. build collects the events of that address, the events of the accounts that it reached by a successful login, and the events of any account that those accounts created (a sudo line with useradd -m NAME names it). It makes two passes, because the new account becomes known only after the first one. The events are already in time order and in UTC. timeline.csv gets one line for each event, with its source and its ref. The function build is the key part. If the address has no successful login, it follows the address only.
def build(events, address):
mine = [e for e in events if e["ip"] == address]
if not mine:
return []
start = mine[0]["ts"]
first_in = next((e for e in mine if e["action"] == "login" and e["outcome"] == "success"), None)
users = {first_in["user"]} if first_in else set()
rows = []
for _ in range(2): # the second pass sees the accounts that the first pass found
rows = [e for e in events if e["ts"] >= start and (e["ip"] == address or e["user"] in users)]
users |= {e["msg"].split()[-1] for e in rows if e["action"] == "sudo" and "useradd" in e["msg"]}
return rowsThe helper what writes one short line for an event, and the last part writes the CSV.
python3 timeline.py 203.0.113.50
grep -E "blocked|success|admin/|sudo|user_add|cron_edit|closed" timeline.csv | cut -c1-10531 events from 2026-11-20T12:37:20Z to 2026-11-20T13:27:21Z in timeline.csv
2026-11-20T12:37:20Z,syslog,firewall blocked 203.0.113.50 on port 3389,syslog:27
2026-11-20T12:37:27Z,syslog,firewall blocked 203.0.113.50 on port 23,syslog:28
2026-11-20T12:53:21Z,web,"GET /admin/ -> 401, 197 bytes",access.log:663
2026-11-20T12:59:21Z,auth,login success for mwebb,auth.log:128
2026-11-20T13:01:26Z,web,"POST /admin/login -> 302, 0 bytes",access.log:674
2026-11-20T13:01:30Z,web,"GET /admin/ -> 200, 8120 bytes",access.log:675
2026-11-20T13:02:21Z,auth,sudo mwebb /usr/bin/less /var/log/auth.log,auth.log:131
2026-11-20T13:03:51Z,web,"GET /admin/export/customers.csv -> 200, 2481722 bytes",access.log:676
2026-11-20T13:04:21Z,auth,sudo mwebb /usr/sbin/useradd -m svc-update,auth.log:132
2026-11-20T13:04:22Z,auth,user_add svc-update,auth.log:133
2026-11-20T13:07:21Z,syslog,cron_edit svc-update,syslog:29
2026-11-20T13:27:21Z,auth,session closed mwebb,auth.log:140grep picks the key lines. The first two are blocked connection attempts at 12:37 UTC, 18 minutes before the first guess: the address was knocking before it guessed. After the login at 12:59:21 the admin page opens, the customer export is taken at 13:03:51, and the new account is made at 13:04:22 (the sudo line names it). The last lines are the job of the new account and the end of the stolen session.
Your turn
Do the same for day 2 (the logs in data2, the events in events2.jsonl, the context in day2). Seal its three logs in a case folder of their own: mkdir case2, then (cd case2 && python3 ../evidence.py seal ../data2 auth.log access.log syslog). The tool makes its folder case inside the folder where it runs, so the custody file is case2/case/custody.csv. Then contain, and build the timeline of the intruder's address. Both programs take the events file first, so write python3 contain.py events2.jsonl rules.json day2 and python3 timeline.py ADDRESS events2.jsonl, with the address that contain.py lists. Both programs overwrite the files of day 1. Count the events as the program writes them.
Check yourself
You sealed a copy and you analyse a second copy. Why not analyse the sealed one?
Every program that opens a file can change it by accident (a time stamp, a lock, an editor that adds a line end). The sealed copy is the reference: if the working copy looks odd, you compare it with the seal. If you work on the seal itself, you have nothing left to compare with.
The hash in the manifest matches. Does that prove that the attacker did not edit the log?
No. It proves that the file is the same as when you sealed it. If the attacker edited the file before you took it, the hash of the edited file matches. Only a second copy that the attacker could not reach (a log server) can show that.
Why does the timeline start 18 minutes before the first failed login?
Because the pivot is the address, and the address has events before it started to guess: two blocked connection attempts in the firewall lines. Without the pivot on the address, the story would start at the first failed login and miss the sign that the address was already looking.
Why does contain.py write lists and not block the address itself?
Acting on production systems needs rights and a decision by the people who own them. A list is a reviewed proposal that the lead can approve and an administrator can apply, and it shows what was decided and why. A tool that blocks by itself needs strong limits, so that a wrong alert cannot lock out the company.
Field notes
- On a real host, capture memory and the list of connections before you copy files, because they change in seconds. Test your tools before the incident.
- Hash with a strong function (SHA-256 or better), store the manifest away from the evidence, and sign it if the case may go to court. Where someone must trust you, a signed manifest (the course "Security fundamentals", lesson 5) adds proof of who made it.
- A real tool also lists files that are in the evidence folder but not in the manifest, because a file that nobody sealed is also a finding.
- Note the clock offset of every source in the custody record: a timeline is only as good as its clocks.
- Blocking an address tells the intruder, who may move to another one. When the scope is not clear, the lead may decide to watch for a short time before cutting. Write the decision down.
- A timeline built by a script is a first draft. Read each line, remove the lines that do not belong (the user's own later logins from the usual address), and add what the logs cannot show.