Monday morning, and nothing opens
A small accountancy firm opens its file share on Monday. Every file has a strange new ending and will not open. A note in each folder asks for money.
This happens to schools, hospitals and shops every week. In this module you learn how to make an attack like this survivable.
By the end of this lesson
Note
I can describe the stages of a ransomware attack and the evidence each one leaves.
Key words
| Word | What it means |
|---|---|
| Ransomware | an attack that makes data unusable and demands payment |
| Initial access | how an attacker first gets in |
| Lateral movement | spreading from one machine to others |
| Exfiltration | copying data out of an organisation |
| Extortion | demanding money with threats |
| Manifest | a list of files and their hashes |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsThe one rule
Important
The drill in this lesson runs only in your own lab copy, on sample files it made itself. Never run anything like it on a real machine without written permission. Unauthorised access to a computer, or changing its data, is an offence under the Computer Misuse Act 1990.
An attack has stages, not one moment
Public incident reports describe the same path again and again. Attackers get initial access, often through a stolen password, a phishing email or an unpatched VPN.
They spend days on lateral movement, looking for admin accounts and backups. They copy data out, which is exfiltration. Only then do they lock files and start the extortion.
Worked example: the stages and their evidence
| Stage | What happens | Evidence a defender can see |
|---|---|---|
| Initial access | A sign-in with a stolen password, often with no second step | A sign-in from a new place or at night |
| Lateral movement | Admin tools used to reach other machines | One account signing in to many machines |
| Exfiltration | Files packed and uploaded | A large upload to an unknown address |
| Inhibit recovery | Backups and shadow copies deleted | A command that deletes shadow copies |
| Encryption | Files made unreadable and renamed | Hundreds of renames in a minute |
| Extortion | A note demands payment, and threatens to publish | A new note file in every folder |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsA harmless drill on made-up files
Your lab copy is the incident response VM. Everything in this module goes in ~/rr, so the lab's own case is never touched.
You build Kestrel Accounts' share of 60 sample files and record a manifest. Then drill.py plays the impact: it overwrites each sample file with one sentence and renames it. Nothing is encrypted.
Make the module's folder and move into it
mkdir -p ~/rr && cd ~/rrShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the share maker, part 1
printf '%s\n' 'import os, random, sys' 'MARK = "KESTREL SAMPLE"' 'root, day = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 1' 'NAMES = ["Abbott", "Begum", "Chen", "Davies", "Evans", "Fofana", "Green", "Hughes", "Iqbal", "Jones",' ' "Khan", "Lewis", "Morgan", "Nowak", "Owen", "Patel", "Quinn", "Roberts", "Singh", "Taylor"]' 'def put(path, lines):' ' os.makedirs(os.path.dirname(path), exist_ok=True)' ' with open(path, "w") as f:' ' f.write(MARK + chr(10) + chr(10).join(lines) + chr(10))' 'def first_day(R):' ' for name in NAMES:' ' put(f"{root}/clients/{name.lower()}.txt", [f"Client: {name} Ltd", "Year end: 31 March", f"Fee: {R.randrange(400, 4000)} pounds"])' ' for month in range(1, 11):' ' put(f"{root}/payroll/2026-{month:02}.csv", ["name,pay"] + [f"staff{n:02},{R.randrange(1800, 3600)}" for n in range(1, 13)])' ' for n in range(1, 31):' > mkshare.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the share maker, part 2
printf '%s\n' ' put(f"{root}/letters/letter-{n:02}.txt", [f"Dear {R.choice(NAMES)},", "Your accounts are ready to sign.", "Kestrel Accounts"])' 'def later_day(R):' ' for name in R.sample(NAMES, 4):' ' with open(f"{root}/clients/{name.lower()}.txt", "a") as f:' ' f.write(f"Day {day}: invoice {R.randrange(100, 999)} sent" + chr(10))' ' put(f"{root}/letters/letter-{30 + day:02}.txt", [f"Dear {R.choice(NAMES)},", "A reminder about your tax return.", "Kestrel Accounts"])' 'if day == 1:' ' first_day(random.Random(138))' 'else:' ' later_day(random.Random(138 * day))' 'count = sum(len(files) for _, _, files in os.walk(root))' 'print("share:", root, " day:", day, " files:", count)' >> mkshare.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Build the share
python3 mkshare.py shareShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the manifest maker
printf '%s\n' 'import hashlib, os, sys' 'root = sys.argv[1]' 'for base, dirs, files in sorted(os.walk(root)):' ' for name in sorted(files):' ' path = os.path.join(base, name)' ' digest = hashlib.sha256(open(path, "rb").read()).hexdigest()' ' print(digest, os.path.relpath(path, root))' > manifest.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Record the manifest before anything happens
python3 manifest.py share > before.txt && wc -l before.txtShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the drill, part 1
printf '%s\n' 'import os, sys' 'MARK = "KESTREL SAMPLE"' 'if os.geteuid() == 0:' ' sys.exit("drill: refused, the drill never runs as root")' 'root = sys.argv[1]' 'done = refused = 0' 'for base, dirs, files in os.walk(root):' ' for name in sorted(files):' ' path = os.path.join(base, name)' ' if os.path.islink(path) or name.endswith(".locked"):' ' continue' ' try:' ' with open(path) as f:' ' first = f.readline().strip()' ' except (OSError, UnicodeDecodeError):' ' continue' ' if not first == MARK:' ' continue' ' try:' ' with open(path, "w") as f:' > drill.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the drill, part 2
printf '%s\n' ' f.write("LAB DRILL: drill.py replaced this sample file. Nothing was encrypted." + chr(10))' ' os.rename(path, path + ".locked")' ' done += 1' ' except OSError:' ' refused += 1' 'for extra in sys.argv[2:]:' ' for name in sorted(os.listdir(extra)):' ' if name.startswith("share-") and name.endswith(".tar.gz"):' ' os.remove(os.path.join(extra, name))' ' print("drill: deleted the backup", name)' 'try:' ' with open(os.path.join(root, "DRILL-NOTE.txt"), "w") as f:' ' f.write("This was a lab drill. A real attack leaves a ransom note here. Restore from a backup." + chr(10))' 'except OSError:' ' pass' 'print("drill: replaced and renamed", done, "sample files, refused", refused)' >> drill.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Run the drill on the share
python3 drill.py shareShown here, not run. Press Start lab to type it into your own lab’s terminal.
Look at what the drill left
ls share share/clients | head -8 && cat share/clients/abbott.txt.lockedShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the comparer, part 1
printf '%s\n' 'import collections, hashlib, os, sys' 'before = dict(line.split()[::-1] for line in open(sys.argv[1]))' 'root = sys.argv[2]' 'now = {}' 'for base, dirs, files in os.walk(root):' ' for name in files:' ' path = os.path.join(base, name)' ' now[os.path.relpath(path, root)] = hashlib.sha256(open(path, "rb").read()).hexdigest()' 'same = [p for p in before if now.get(p) == before[p]]' 'changed = [p for p in before if p in now and not now[p] == before[p]]' 'missing = [p for p in before if p not in now]' 'new = [p for p in now if p not in before]' 'renamed = [p for p in missing if p + ".locked" in now]' 'print("before:", len(before), " unchanged:", len(same), " changed:", len(changed), " missing:", len(missing), " new:", len(new))' 'exts = collections.Counter(os.path.splitext(p)[1] for p in new)' 'for ext, n in exts.most_common():' ' print(" new files ending", ext or "(none)", n)' 'if len(renamed) >= 10:' > compare.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the comparer, part 2
printf '%s\n' ' print("ALERT: mass rename,", len(renamed), "files now end in .locked")' 'if [p for p in new if "NOTE" in p.upper()]:' ' print("ALERT: a note file appeared:", ", ".join(p for p in new if "NOTE" in p.upper()))' 'if not (changed or missing or new):' ' print("OK: the folder matches the manifest")' >> compare.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Compare the share with the manifest
python3 compare.py before.txt shareShown 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 good backups end a ransomware attack. They bring the files back, but most attacks now copy data out first. The threat to publish stays, so backups answer only the encryption. Watch for the theft too.
The fix and how to detect it
The fix is a copy the attacker cannot reach, tested before you need it. Lessons 2 to 4 build one.
Detection looks for the stages, not the final note. Many renames to one new ending, a note in every folder and deleted shadow copies are the loudest signals.
Try it: a rename alarm
names = ["march.xlsx", "letter.docx.locked", "photo.jpg.locked", "notes.txt.locked", "plan.pdf"]
locked = [n for n in names if n.endswith(".locked")]
print(len(locked), "of", len(names), "files look locked")
print("ALERT" if len(locked) >= 3 else "quiet")
# Change 3 to 4 above, then press Run. Does it still alert?
Make a free account to save your work and track your progress.
Assignment: write the damage report
A manifest is a dictionary from a file's path to its hash. before is the manifest from before an incident and after the one from now.
changes(before, after) returns a dictionary with three sorted lists: "changed" (in both, different hash), "missing" (only in before) and "new" (only in after).
new_endings(before, after) returns a dictionary from each ending of the new paths to how many there are. The ending is the text from the last dot, such as ".locked", or "" when the name has no dot.
alarm(before, after, limit) returns True when one ending that no path in before has appears on at least limit new paths.
def changes(before, after):
return {"changed": [], "missing": [], "new": []}
def new_endings(before, after):
return {}
def alarm(before, after, limit):
return False
Make a free account to save your work and track your progress.
Exit quiz
Have a go