Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 30 min · revision 2

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

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:

  1. 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.
  2. Cut off the stolen identity. Rotate the app_owner password and end its sessions. Disable any other account the attacker used.
  3. 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.
  4. 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.

SQL · drill/seed.sql
-- 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.

Terminal
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"
Expected output
5040|2026-11-02 02:00:00+00

04. Step 3: Prove the backup account cannot destroy data

Try a read, a delete and a drop as backup_reader.

Terminal
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
done
Expected output
5040
ERROR:  permission denied for table orders
ERROR:  must be owner of table orders

The 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.

Terminal
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 offline
Expected output
offline:
orders-20261102T0200Z.dump.sha256

vault:
orders-20261102T0200Z.dump
orders-20261102T0200Z.dump.sha256

A 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.

SQL · drill/day.sql
-- 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;
SQL · drill/attack.sql
-- 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');
Terminal
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>&1
Expected output
5415|2026-11-02 14:30:00+00
0
your orders are encrypted; pay to get them back
ls: /vault: No such file or directory

The 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.

Terminal
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.sha256
Expected output
orders-20261102T0200Z.dump: OK
orders-20261102T0200Z.dump: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match

The 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.

Bash · drill/restore.sh
#!/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 ))"
Terminal
bash restore.sh
Illustrative output (the restore time depends on your machine)
5040|2026-11-02 02:00:00+00
restore_seconds=3

09. 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.

Python · drill/drill_report.py
"""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)
Terminal
python3 drill_report.py "2026-11-02 02:00:00+00" 3
Expected output (with restore_seconds=3)
data loss (RPO)  achieved  12h31m  target  24h00m  met
restore (RTO)    achieved   0h00m  target   4h00m  met
not timed here: detection, decisions, identity rebuild, app checks, cutover

The 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.

Python · drill/recovery_order.py
"""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)
Terminal
python3 recovery_order.py
Expected output
derived 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 identity

The 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

Practice check · 3 questions

Backups, restores and recovery order

Three questions about the drill you ran.

Q1. The business lowers the RPO for orders to 4 hours, and `drill_report.py` now prints NOT MET for data loss. Which change most directly lets the next drill meet it?
Q2. To simplify step 4, a colleague mounts `vault` into `ir-orders-db` and runs `pg_dump` there as `postgres`. What does the shop lose?
Q3. In `recovery_order.py`, someone changes `"order-app"` to need only `["orders-db"]`. What does `check()` report for the rushed plan now?
Practice only: not graded, not saved, not evidence.

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.py with your real dependencies and run check() on the plan in your current runbook.

14. Review prompt

Without looking back:

  1. What are RTO and RPO, and which one does backup frequency change?
  2. Name three properties that make a backup survive ransomware.
  3. Why does a checksum not prove that a backup is clean?
  4. Why is identity rebuilt before the database and the application?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check