Containment Under Pressure and Ransomware-Ready Recovery
Work through the first hour of a ransomware incident, then run a real backup and restore drill with PostgreSQL 17: a backup role that cannot delete, a vault the database host cannot reach, checksum verification that catches a tampered copy, a timed restore on a clean host compared with RTO and RPO, and an identity-first recovery order.
Contentsand lesson path
On this page
- The problem
- Step 1: Contain the first hour
- Step 2: Build the production database
- Step 3: Prove the backup account cannot destroy data
- Step 4: Back up from a separate host into a vault
- Step 5: Let the attack happen
- Step 6: Verify the backup before you trust it
- Step 7: Restore onto a clean host and time it
- Step 8: Compare the drill with RTO and RPO
- Step 9: Write the recovery order, identity first
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Security Incident Response & Forensics
- From Alert to Incident: Triage, Severity and Scope Concept · 20 min
- Containment Under Pressure and Ransomware-Ready Recovery Worked example · 30 min
- Collecting Evidence Without Destroying It Lab · 30 min
- Building a Timeline from Host and Log Artifacts Lab · 30 min
- Tabletop Exercises and the Incident Report Worked example · 25 min
- Incident Response Check Knowledge check · 10 questions
What you will learn
- Triage a security alert into an incident, classify severity and scope, and choose containment actions that balance evidence preservation against business impact.
- Assess an organisation's ability to recover from ransomware (immutable or offline backup copies, separately protected backup credentials, restore tests against RTO and RPO) and write the recovery sequence for a ransomware scenario.
01. The problem
It is Friday at 14:31 UTC at a small online shop. The order website shows errors. The orders table in its PostgreSQL database is empty, and a new table holds a ransom note. The endpoint detection and response (EDR) console shows the same encryption tool on two file servers. The attacker used the application's own database owner account, so that password is stolen.
The business has set two recovery objectives for the order system. The recovery time objective (RTO) is the longest the system may be unavailable before the impact becomes unacceptable: here 4 hours. The recovery point objective (RPO) is how much recent data the business can afford to lose, measured back from the outage to the last good copy: here 24 hours. Both terms come from contingency planning (NIST SP 800-34 Rev. 1).
You have two jobs: contain the incident without losing the evidence or the backups, and show with a real drill whether the orders can come back within those objectives. The drill uses Docker, the postgres:17-alpine image and Python 3.11 or later, and takes about 50 MB of disk. Create the folder with mkdir drill && cd drill and save every file below in it.
02. Step 1: Contain the first hour
Name an incident lead, open a ticket and bring in IT operations, legal, communications and management. Talk on a channel that does not depend on the systems under attack, such as phones or a separate chat service; the NIST ransomware profile, IR 8374 Rev. 1, recommends planning these out-of-band communications in advance. Then act in this order:
- Stop the spread. Isolate the infected hosts through the EDR agent, which keeps them powered on, so memory stays available for lesson 3. If a machine is still encrypting and cannot be isolated, pulling its cable or power is a fair trade: you lose memory but save data.
- Cut off the stolen identity. Rotate the
app_ownerpassword and end its sessions. Disable any other account the attacker used. - Protect the backups. Ransomware operators look for them early, because deleting them raises the pressure to pay. Check that the store is out of reach and pause jobs that could overwrite good copies.
- Preserve evidence before you rebuild. Image or snapshot the affected hosts first; once a host is wiped, you cannot answer how the attacker got in.
Coordinated eviction from lesson 1 does not fit here: encryption is active, so you contain at once, even with scoping unfinished. Then comes recovery.
03. Step 2: Build the production database
seed.sql creates an owner role for the application, seven days of orders (one every two minutes, the last at 02:00 UTC on 2 November), and a separate backup_reader login. The predefined role pg_read_all_data lets it read every table as if it had SELECT rights, and nothing more. The data has fixed timestamps, so your numbers will match the lesson.
-- Production: an owner role for the app, seven days of orders, a read-only backup role.
CREATE ROLE app_owner LOGIN PASSWORD 'app-lab-only';
CREATE DATABASE orders OWNER app_owner;
\connect orders
SET ROLE app_owner;
CREATE TABLE orders (
id int PRIMARY KEY,
customer text NOT NULL,
amount_cents int NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO orders
SELECT g, 'cust-' || (g % 97), (g * 37) % 10000 + 100,
timestamptz '2026-10-26 02:00:00+00' + g * interval '2 minutes'
FROM generate_series(1, 5040) AS g;
RESET ROLE;
CREATE ROLE backup_reader LOGIN PASSWORD 'backup-lab-only';
GRANT pg_read_all_data TO backup_reader;Start the database. --tmpfs keeps its files in memory. The loop waits for the real server on 127.0.0.1, because the image first runs a setup server that accepts only socket connections.
docker run -d --name ir-orders-db -e POSTGRES_PASSWORD=admin-lab-only \
--tmpfs /var/lib/postgresql/data postgres:17-alpine > /dev/null
until docker exec ir-orders-db pg_isready -h 127.0.0.1 -q; do sleep 1; done
docker exec -i ir-orders-db psql -U postgres -q -v ON_ERROR_STOP=1 < seed.sql
docker exec ir-orders-db psql -U postgres -d orders -At \
-c "SELECT count(*), max(created_at) FROM orders"5040|2026-11-02 02:00:00+0004. Step 3: Prove the backup account cannot destroy data
Try a read, a delete and a drop as backup_reader.
for sql in "SELECT count(*) FROM orders" "DELETE FROM orders" "DROP TABLE orders"; do
docker exec ir-orders-db psql -U backup_reader -d orders -At -c "$sql" 2>&1
done5040
ERROR: permission denied for table orders
ERROR: must be owner of table ordersThe delete fails because the role has no DELETE right, and the drop fails because only the owner may drop a table. A thief with this password can copy data but not wipe it, which is still a leak, so the password lives in its own file and not in the application's configuration.
05. Step 4: Back up from a separate host into a vault
The nightly backup runs from a second container that stands in for a backup server. It connects over the network with the backup password from backup.env, which the first two lines create and make readable only by you. The vault folder is mounted into the backup container only, never into the database container. pg_dump takes a consistent copy while the database is in use, and -Fc writes the compressed custom format that pg_restore reads. A SHA-256 checksum of the file goes to the vault and a second copy to offline.
printf 'PGPASSWORD=backup-lab-only\nPGUSER=backup_reader\n' > backup.env
chmod 600 backup.env
mkdir -p vault offline
DB_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' \
ir-orders-db)
docker run --rm --name ir-backup --user "$(id -u):$(id -g)" --env-file backup.env \
-v "$PWD/vault:/vault" postgres:17-alpine \
pg_dump -h "$DB_IP" -d orders -Fc -f /vault/orders-20261102T0200Z.dump
cd vault
sha256sum orders-20261102T0200Z.dump > orders-20261102T0200Z.dump.sha256
cp orders-20261102T0200Z.dump.sha256 ../offline/
cd .. && ls vault offlineoffline:
orders-20261102T0200Z.dump.sha256
vault:
orders-20261102T0200Z.dump
orders-20261102T0200Z.dump.sha256A folder on your laptop is not immutable: anyone with your account can delete it. The classic 3-2-1 rule asks for three copies of the data, on two different kinds of media, with one copy off-site. Against ransomware, add two more conditions. At least one copy must be immutable or offline: object storage with a retention lock (often called WORM, write once read many), or media that is disconnected. And the backup system needs credentials that are separate from production, for example accounts that are not in the main directory and use multi-factor authentication. IR 8374 Rev. 1 says it under PR.DS-11: keep a copy offline or otherwise out of the attacker's reach. A domain-joined backup share written with a domain admin account fails, because domain admin is what ransomware operators usually obtain.
06. Step 5: Let the attack happen
During the day the shop takes 375 more orders, the last at 14:30. Then the "ransomware" in attack.sql runs with the stolen owner password. day.sql and attack.sql are short: the first inserts the day's orders, the second empties the table and leaves a note.
-- Orders placed after the 02:00 backup: one every two minutes until 14:30.
INSERT INTO orders
SELECT 5040 + g, 'cust-' || (g % 97), 2500,
timestamptz '2026-11-02 02:00:00+00' + g * interval '2 minutes'
FROM generate_series(1, 375) AS g;-- The "ransomware": it wipes the table and leaves a note.
TRUNCATE orders;
CREATE TABLE read_me (note text);
INSERT INTO read_me VALUES ('your orders are encrypted; pay to get them back');docker exec -i ir-orders-db psql -U postgres -d orders -q < day.sql
docker exec ir-orders-db psql -U postgres -d orders -At \
-c "SELECT count(*), max(created_at) FROM orders"
docker exec -i ir-orders-db psql -U app_owner -d orders -q < attack.sql
docker exec ir-orders-db psql -U postgres -d orders -At \
-c "SELECT count(*) FROM orders" -c "SELECT note FROM read_me"
docker exec ir-orders-db ls /vault 2>&15415|2026-11-02 14:30:00+00
0
your orders are encrypted; pay to get them back
ls: /vault: No such file or directoryThe last line matters most: from the database host the vault does not exist, so whoever owns that host cannot reach the backups. The 375 orders placed after 02:00 are in no backup; they are the data loss the RPO measures.
07. Step 6: Verify the backup before you trust it
NIST SP 800-61 Rev. 3 asks you to verify the integrity of backups before you restore from them (RC.RP-03). Check the vault copy against the offline checksum. Then run a negative test: damage one byte of a copy and check that the same command catches it.
cd vault && sha256sum -c ../offline/orders-20261102T0200Z.dump.sha256 && cd ..
mkdir -p scratch
cp vault/orders-20261102T0200Z.dump scratch/orders-20261102T0200Z.dump
printf 'X' | dd of=scratch/orders-20261102T0200Z.dump bs=1 seek=4096 conv=notrunc \
status=none
cd scratch && sha256sum -c ../offline/orders-20261102T0200Z.dump.sha256orders-20261102T0200Z.dump: OK
orders-20261102T0200Z.dump: FAILED
sha256sum: WARNING: 1 computed checksum did NOT matchThe checksum proves the file is the one written at 02:00, not that the data is clean. If the attacker had been inside since Monday, Thursday's backup could hold their persistence, so choose a restore point from before the intrusion and check restored systems before production use (RC.RP-05).
08. Step 7: Restore onto a clean host and time it
restore.sh refuses to continue if the checksum fails (set -e stops at the first error), starts a new database container, creates the app_owner role with a new password, restores the dump and counts the rows. pg_dump saves one database, not the server's roles, so the old, stolen password does not come back. The script prints how many seconds the restore took.
#!/usr/bin/env bash
# Restore the verified backup onto a clean database host and time it.
set -euo pipefail
DUMP=orders-20261102T0200Z.dump
CLEAN=${CLEAN:-ir-orders-clean} # the clean host
start=$(date +%s)
(cd vault && sha256sum -c --quiet "../offline/$DUMP.sha256") # stop if it fails
docker run -d --name "$CLEAN" -e POSTGRES_PASSWORD=new-admin-lab-only \
--tmpfs /var/lib/postgresql/data postgres:17-alpine > /dev/null
until docker exec "$CLEAN" pg_isready -h 127.0.0.1 -q; do sleep 1; done
docker exec "$CLEAN" psql -U postgres -q \
-c "CREATE ROLE app_owner LOGIN PASSWORD 'rotated-app-lab-only'" \
-c "CREATE DATABASE orders OWNER app_owner"
docker exec -i "$CLEAN" pg_restore -U postgres -d orders --exit-on-error \
< "vault/$DUMP"
docker exec "$CLEAN" psql -U postgres -d orders -At \
-c "SELECT count(*), max(created_at) FROM orders"
echo "restore_seconds=$(( $(date +%s) - start ))"bash restore.sh5040|2026-11-02 02:00:00+00
restore_seconds=309. Step 8: Compare the drill with RTO and RPO
The data loss is the time between the incident and the newest data in the restored copy. Pass the max(created_at) value and your restore_seconds to the script below; the command shows the values from the run above.
"""Compare one restore drill with the recovery objectives for the order system."""
import sys
from datetime import datetime, timedelta
RTO = timedelta(hours=4) # longest acceptable outage for the order system
RPO = timedelta(hours=24) # most recent order data the business accepts to lose
incident = datetime.fromisoformat("2026-11-02 14:31:00+00")
restored_up_to = datetime.fromisoformat(sys.argv[1]) # max(created_at) after restore
restore = timedelta(seconds=int(sys.argv[2])) # restore_seconds from restore.sh
rpo = timedelta(hours=float(sys.argv[3])) if len(sys.argv) > 3 else RPO
def hm(span):
minutes = int(span.total_seconds() // 60)
return f"{minutes // 60}h{minutes % 60:02d}m"
failed = 0
for name, achieved, target in [("data loss (RPO)", incident - restored_up_to, rpo),
("restore (RTO)", restore, RTO)]:
verdict = "met" if achieved <= target else "NOT MET"
failed += verdict != "met"
print(f"{name:<16} achieved {hm(achieved):>7} target {hm(target):>7} {verdict}")
print("not timed here: detection, decisions, identity rebuild, app checks, cutover")
sys.exit(1 if failed else 0)python3 drill_report.py "2026-11-02 02:00:00+00" 3data loss (RPO) achieved 12h31m target 24h00m met
restore (RTO) achieved 0h00m target 4h00m met
not timed here: detection, decisions, identity rebuild, app checks, cutoverThe RPO is met: 12 hours 31 minutes of orders are lost against 24 hours allowed, and someone must rebuild those 375 orders from payment records. The restore fits the RTO easily, but it is only part of it. A real outage also includes detection, decisions, rebuilding identity, checking the application and moving traffic back. Timing only pg_restore can make a four-hour RTO look safe when the whole sequence takes two days, so time the full sequence in an isolated network regularly.
10. Step 9: Write the recovery order, identity first
After a domain-wide attack, everything depends on identity: the database trusts accounts, the application trusts the directory, and staff sign in through it. If you restore applications while the directory is still compromised, the attacker simply logs in again. recovery_order.py writes the dependencies down and lets Python's graphlib derive a safe order. It also checks a plan that a stressed team might write by hand.
"""Derive a ransomware recovery order from dependencies, and reject unsafe plans."""
from graphlib import TopologicalSorter
NEEDS = { # service: what must be clean and running before it
"recovery-network": [], # isolated, no path to the old network
"identity": ["recovery-network"], # clean directory, MFA, admin passwords reset
"backup-vault": ["identity"], # access with the separate backup accounts
"orders-db": ["backup-vault"], # restored from a verified, clean backup
"order-app": ["orders-db", "identity"],
"laptops": ["identity"], # reimaged, users sign in with new passwords
}
def check(plan):
"""Return the problems in a human-written plan (an ordered list of services)."""
done, problems = set(), []
for service in plan:
for need in NEEDS[service]:
if need not in done:
problems.append(f"{service} before {need}")
done.add(service)
return problems
if __name__ == "__main__":
order = list(TopologicalSorter(NEEDS).static_order())
print("derived order:", ", ".join(order))
print("problems in derived order:", check(order) or "none")
rushed = ["recovery-network", "orders-db", "order-app", "identity",
"backup-vault", "laptops"]
print("problems in rushed plan:")
for problem in check(rushed):
print(" -", problem)python3 recovery_order.pyderived order: recovery-network, identity, backup-vault, laptops, orders-db, order-app
problems in derived order: none
problems in rushed plan:
- orders-db before backup-vault
- order-app before identityThe derived order rebuilds a clean network, then identity with new admin passwords and multi-factor authentication, then backup access, and only then data and applications. The rushed plan restores the database before the vault is checked and starts the app under the old directory. When you finish, remove the containers with docker rm -f ir-orders-db ir-orders-clean.
11. Common mistakes
12. Check your understanding
13. Apply it
For the skill project, do the backup half for real:
- Back up a lab service to a target it cannot write to or delete from, with credentials that exist only for backups. If you have a cloud lab, try object storage with a retention lock and prove that a delete is refused.
- Restore onto a clean host and time the whole sequence, from the decision to restore to a working application, then record the achieved RTO and RPO against the targets.
- Extend
recovery_order.pywith your real dependencies and runcheck()on the plan in your current runbook.
14. Review prompt
Without looking back:
- What are RTO and RPO, and which one does backup frequency change?
- Name three properties that make a backup survive ransomware.
- Why does a checksum not prove that a backup is clean?
- Why is identity rebuilt before the database and the application?
References
- NIST IR 8374 Rev. 1: Ransomware Risk Management, a CSF 2.0 Community Profile (June 2026)
- NIST SP 800-61 Rev. 3: Incident Response Recommendations and Considerations for Cybersecurity Risk Management
- NIST SP 800-34 Rev. 1: Contingency Planning Guide (RTO and RPO)
- PostgreSQL 17 documentation: pg_dump
- PostgreSQL 17 documentation: Predefined roles
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.