Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 10 · 50 minutes

Back up, restore and prove it with a restore test

After this lesson you can
  • Set recovery time and recovery point objectives in a business impact analysis
  • Make a backup with checksums and restore it into a fresh folder
  • Measure the recovery point and write a restore test record that a checker accepts
Lab files of this lesson (59)

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 backup log of Brindle Books says OK on six nights of seven. Jonas is not impressed: "A backup is a file. Show me a restore." Nobody at the company has ever restored the order data. Risk R2 in the register says "nightly backup with a restore test every quarter", and control C06 names a restore test record as its evidence. Today you do the test: back up the shop data, lose the disk, restore, compare, and measure how much was lost.

Recall

Lesson 9: who backs up the data of Brindle Books at CloudNorth, by the responsibility table?

Brindle Books itself: the row "backup of our data" says us, with control C06. The provider keeps the platform running. The copies of the data are the customer's job.

Lesson 6: what does a hash in a manifest prove about a file?

That the file did not change after it was sealed. It does not prove that the content was true when it was collected.

The idea

Business continuity is the ability to keep the important work going during a disruption, and to return to normal after it. Backup and restore are one part of it. The planning starts with a business impact analysis (BIA): a table of the processes of the business with the harm that an outage does, and two targets for each.

  • The recovery time objective (RTO) is how long the process may be down. It looks forward from the failure.
  • The recovery point objective (RPO) is how much recent data may be lost, as a span of time. It looks back from the failure to the last good copy.
Two clocks around one failure
02:00the nightly backup runs: the last good copy07:00 to 15:40orders come in: this work is not in any backup15:40the disk fails: the RPO looks back from here to 02:0015:40 to 16:10restore and check: the RTO runs from the failure16:10the shop takes orders again02:00the nightly backup runs: the last good copy07:00 to 15:40orders come in: this work is not in anybackup15:40the disk fails: the RPO looks back from hereto 02:0015:40 to 16:10restore and check: the RTO runs from thefailure16:10the shop takes orders again

The RPO decides how often you back up: a backup every 24 hours cannot meet an RPO of 4 hours. The RTO decides how you restore: a copy on a tape in another city cannot meet an RTO of one hour.

The 3-2-1 rule is the usual shape of a backup: at least 3 copies of the data, on 2 different kinds of storage, with 1 copy off site. The live data counts as one copy. The rule protects against a failed disk, against a fault that hits one kind of storage, and against a fire or a theft at one place.

The 3-2-1 rule for the shop data
Server roomCloud off siteLive dataBackup deviceOffsite copy12Server roomCloud off siteLive dataBackup deviceOffsite copy12
  1. Live data → Backup device: nightly backup, copy 2 on other storage
  2. Backup device → Offsite copy: copy 3 off site, out of reach of a fire

A backup that nobody restored is a hope. A restore test brings the data back to a fresh place, compares it with checksums that were made at backup time, and measures the two clocks. Its record names who tested, who watched, and the result.

Worked example

Work in ~/krlab/security-governance. You made archives with tar in the course "Linux" (Part 1, lesson 9). If you run the lesson again, remove the folders of the earlier run first. rm -rf removes folders with everything in them and does not complain about a folder that is not there, so run it only inside the lab folder. && runs the second command only if the first one worked, so rm never runs in the wrong folder.

cd ~/krlab/security-governance && rm -rf shopdata lost-disk restore backup clinicdata clinic-backup

1. Write the business impact analysis

Each row is a process with the asset behind it (lesson 3), the two targets in hours, and the backup that exists: how often it runs, how many copies there are, on how many kinds of storage, and how many are off site.

bia.csv

process,asset,owner,impact,rto_hours,rpo_hours,backup_every_hours,copies,media,offsite
Take and ship orders,A1,Greta,No sales and no shipping,8,24,24,3,2,1
Pay staff,A4,Efe,Late salaries at the end of the month,72,168,168,3,2,1
Show the book catalogue,A8,Greta,Customers cannot browse,24,168,24,3,2,1

2. Save the data generator and the continuity tool

make_shopdata.py writes the lab data. You do not need to read it: it writes invented files, and its random generator has a fixed start, so every reader gets the same files. Save it, from the collapsed block or from the zip.

The finished file: make_shopdata.py

make_shopdata.py

"""make_shopdata.py: lab data for the backup lesson. Every value is invented.

    python3 make_shopdata.py night    write shopdata/ as it stands at the nightly backup
    python3 make_shopdata.py day      add the orders of the next day to shopdata/orders.csv
    python3 make_shopdata.py clinic   write clinicdata/ for the Your turn
    python3 make_shopdata.py damage   damage clinicdata/ after your backup
"""
import json
import random
import sys
from datetime import datetime, timedelta
from pathlib import Path


def orders(seed, start, count, first):
    rnd, t, rows = random.Random(seed), datetime.fromisoformat(start), []
    for i in range(count):
        t += timedelta(minutes=2 + int(rnd.random() * 40))
        rows.append(f"O{first + i:04d},{t.isoformat(timespec='minutes')},C{1 + int(rnd.random() * 30):03d},"
                    f"{5 + int(rnd.random() * 60)}.00")
    return "\n".join(rows) + "\n"


def write(folder, files):
    Path(folder).mkdir(exist_ok=True)
    for name, text in files.items():
        (Path(folder) / name).write_text(text)
    print(f"wrote {len(files)} files to {folder}/")


command = sys.argv[1]
if command == "night":
    write("shopdata", {
        "orders.csv": "order,time,customer,total\n" + orders(7, "2026-11-19T08:00", 40, 1),
        "customers.csv": "id,name,mail\n" + "".join(f"C{i:03d},Customer {i},customer{i}@mail.example\n" for i in range(1, 31)),
        "stock.json": json.dumps({f"Book {i}": 3 * i % 17 for i in range(1, 11)}, indent=1) + "\n"})
elif command == "day":
    with open("shopdata/orders.csv", "a") as f:
        f.write(orders(8, "2026-11-20T07:00", 23, 41))
    print("added 23 orders to shopdata/orders.csv")
elif command == "clinic":
    write("clinicdata", {
        "patients.csv": "id,name\n" + "".join(f"P{i:03d},Patient {i}\n" for i in range(1, 21)),
        "visits.csv": "visit,patient,treatment\n" + "".join(f"V{i:03d},P{1 + i * 7 % 20:03d},T{1 + i % 4}\n" for i in range(1, 31)),
        "rota.txt": "Mon Priya\nTue Quentin\nWed Sam\nThu Priya\nFri Quentin\n",
        "forms.txt": "Consent form, version 3\n"})
elif command == "damage":
    path = Path("clinicdata/visits.csv")
    path.write_text(path.read_text().replace("V017,P020,T2", "V017,P020,T4"))
    Path("clinicdata/rota.txt").unlink()
    print("clinicdata/ is damaged")

continuity.py has three commands. bia checks the table. measure compares a restored folder with a checksum list and computes the recovery point from two times. check tests a restore test record against the targets of the table. JSON is a text format for records: names in double quotes, a colon and a value, with braces around one record. json.loads turns JSON text into a dictionary. total_seconds() / 3600 turns a span of time into hours.

continuity.py

"""continuity.py: check a business impact analysis, measure a restore, check a restore test record.

    python3 continuity.py bia bia.csv
    python3 continuity.py measure RESTORED_FOLDER SHA256SUMS BACKUP_TIME FAILURE_TIME
    python3 continuity.py check restore_test.json bia.csv
"""
import hashlib
import json
import sys
from datetime import datetime
from pathlib import Path

from grc import TODAY, day, finish, load

FIELDS = ["system", "backup_taken", "failure", "tested_on", "restored_by", "witness", "files_in_backup",
          "files_matching", "rpo_measured_hours", "rto_measured_hours", "result"]
MAX_AGE = 180       # days after which a restore test is too old


def bia_problems(path):
    found = []
    for r in load(path):
        name = r["process"]
        if not r["owner"]:
            found.append(f"{name}: no owner")
        if int(r["backup_every_hours"]) > int(r["rpo_hours"]):
            found.append(f"{name}: a backup every {r['backup_every_hours']} hours cannot meet an RPO of {r['rpo_hours']} hours")
        if int(r["copies"]) < 3 or int(r["media"]) < 2 or int(r["offsite"]) < 1:
            found.append(f"{name}: not 3-2-1: copies {r['copies']}, media {r['media']}, off site {r['offsite']}")
    return found


def measure(folder, sums, taken, failure):
    lines = [line.split() for line in Path(sums).read_text().splitlines()]
    good = sum((Path(folder) / name).is_file() and hashlib.sha256((Path(folder) / name).read_bytes()).hexdigest() == digest
               for digest, name in lines)
    hours = (datetime.fromisoformat(failure) - datetime.fromisoformat(taken)).total_seconds() / 3600
    print(f"files in the backup: {len(lines)}\nfiles restored and matching: {good}\nrecovery point: {hours:.2f} hours before the failure")


def problems(record_path, bia_path):
    record = json.loads(Path(record_path).read_text())
    missing = [f for f in FIELDS if f not in record]
    target = next((r for r in load(bia_path) if r["asset"] == record.get("system")), None)
    if missing or target is None:
        return [f"restore test: field missing: {f}" for f in missing] or ["restore test: the system is not in the BIA"]
    found = []
    if record["files_matching"] != record["files_in_backup"]:
        found.append(f"restore test: only {record['files_matching']} of {record['files_in_backup']} files match")
    for name in ("rpo", "rto"):
        got, limit = record[f"{name}_measured_hours"], int(target[f"{name}_hours"])
        if got > limit:
            found.append(f"restore test: {name.upper()} measured {got} hours, target {limit}")
    if record["result"] != "pass":
        found.append("restore test: the result is not a pass")
    elif found:
        found.append("restore test: the result says pass, but a measure failed")
    if not record["restored_by"] or record["restored_by"] == record["witness"]:
        found.append("restore test: needs a tester and a second person as witness")
    if (TODAY - day(record["tested_on"])).days > MAX_AGE:
        found.append(f"restore test: {(TODAY - day(record['tested_on'])).days} days old")
    return found


if __name__ == "__main__":
    if sys.argv[1] == "bia":
        finish(bia_problems(sys.argv[2]))
    elif sys.argv[1] == "measure":
        measure(*sys.argv[2:6])
    else:
        finish(problems(sys.argv[2], sys.argv[3]))
python3 continuity.py bia bia.csv
problems: 0

3. Back up at night

It is 02:00 on 20 November. Make the data as it stands, write the checksums, and pack the archive. sha256sum * prints the hash of each file in the folder (on macOS: shasum -a 256 *). The brackets run the two commands in a subshell, so the cd ends with them. tar -czf creates (c) a compressed (z) archive file (f), and -tzf lists what is in one. sort puts the lines in order.

python3 make_shopdata.py night
mkdir -p backup
(cd shopdata && sha256sum *) > backup/SHA256SUMS
tar -czf backup/shop-2026-11-20.tar.gz shopdata
tar -tzf backup/shop-2026-11-20.tar.gz | sort
cut -c1-16,65- backup/SHA256SUMS
wrote 3 files to shopdata/
shopdata/
shopdata/customers.csv
shopdata/orders.csv
shopdata/stock.json
c0c90fd131396ac0  customers.csv
cbd23be072c3c108  orders.csv
9468567102898d08  stock.json

The last command shows the first 16 characters of each hash and the file name. Your hashes are the same as these, because the data is the same.

4. Lose the disk

The shop sells all day. At 15:40 the disk of the database fails. mv renames the folder to lost-disk, so the live data is gone from where the shop expects it.

python3 make_shopdata.py day
mv shopdata lost-disk
added 23 orders to shopdata/orders.csv

5. Restore into a fresh folder and compare

Never restore over the remains of the old data: you may need them, and a failed restore must not make things worse. tar -xzf extracts (x), and -C restore puts the files into the folder restore. sha256sum -c checks files against a list of hashes (on macOS: shasum -a 256 -c).

mkdir restore
tar -xzf backup/shop-2026-11-20.tar.gz -C restore
(cd restore/shopdata && sha256sum -c ../../backup/SHA256SUMS)
customers.csv: OK
orders.csv: OK
stock.json: OK

Every file came back exactly as it was at 02:00. Now ask what is missing. diff -rq compares two folders and names the files that differ. wc -l counts lines.

diff -rq lost-disk restore/shopdata
wc -l lost-disk/orders.csv restore/shopdata/orders.csv
tail -1 restore/shopdata/orders.csv
Files lost-disk/orders.csv and restore/shopdata/orders.csv differ
  64 lost-disk/orders.csv
  41 restore/shopdata/orders.csv
 105 total
O0040,2026-11-19T21:02,C027,52.00

The restored order file has 23 lines fewer: the 23 orders of the day are lost. In a real failure you could not count them like this, because the lost disk would be unreadable. You would ask the payment provider for the day's payments and enter the orders again.

6. Measure and write the record

python3 continuity.py measure restore/shopdata backup/SHA256SUMS 2026-11-20T02:00 2026-11-20T15:40
files in the backup: 3
files restored and matching: 3
recovery point: 13.67 hours before the failure

The recovery point is 13.67 hours before the failure, inside the RPO of 24 hours. The restore itself took minutes here. For a real system you time it from the failure to the moment when the shop takes orders again. Write the record, with your own measured time if you used a clock.

restore_test.json

{
  "system": "A1",
  "backup_file": "backup/shop-2026-11-20.tar.gz",
  "backup_taken": "2026-11-20T02:00",
  "failure": "2026-11-20T15:40",
  "tested_on": "2026-11-21",
  "restored_by": "Ben",
  "witness": "Carys",
  "files_in_backup": 3,
  "files_matching": 3,
  "rpo_measured_hours": 13.67,
  "rto_measured_hours": 0.5,
  "result": "pass"
}
python3 continuity.py check restore_test.json bia.csv
problems: 0

Your turn

Marlow Physio backs up its clinic data at 22:00. Run python3 make_shopdata.py clinic, and make your own backup of clinicdata with checksums, in a folder clinic-backup. Then run python3 make_shopdata.py damage: something goes wrong at 10:30 the next morning, and nobody knows what. Restore into a fresh folder and find out what the damage was. There are no steps.

Then save the table and the record that Omar wrote after his own test in the spring, and check them.

marlow/bia.csv

process,asset,owner,impact,rto_hours,rpo_hours,backup_every_hours,copies,media,offsite
Treat patients with their records,M1,Priya,Treatment without history,4,4,24,2,2,0
Book appointments,M2,Nadia,No new bookings,8,24,24,3,1,1

marlow/restore_test.json

{
  "system": "M1",
  "backup_file": "clinic-2026-04-01.tar.gz",
  "backup_taken": "2026-03-31T22:00",
  "failure": "2026-04-01T10:30",
  "tested_on": "2026-04-02",
  "restored_by": "Omar",
  "witness": "Omar",
  "files_in_backup": 4,
  "files_matching": 3,
  "rpo_measured_hours": 12.5,
  "rto_measured_hours": 3,
  "result": "pass"
}

Last, write the sentence that you would say to Priya about her RPO of 4 hours and a backup at 22:00.

Check yourself

The backup log says OK every night. Why is that not evidence that the data can be recovered?

The log shows that a job ran and wrote a file. It does not show that the file holds the right data, that it can be read, or that the restore fits inside the RTO. Only a restore test shows those, and it compares the result with checksums from backup time.

A process has an RPO of 4 hours and a backup every 24 hours. What are the two honest ways out?

Back up more often, at least every 4 hours, or let the process owner accept a larger loss and change the RPO. The owner decides, because the owner knows what a lost day of work costs. Leaving both numbers as they are means that the table promises something that the system cannot do.

Why do you restore into a fresh folder and not over the damaged data?

The damaged data may hold the only copy of recent work, and it is evidence of what happened. A restore can also fail halfway. In a fresh place you can compare, decide, and then switch over.

Brindle Books keeps three copies of its backup on three disks in the server room. Which part of 3-2-1 is missing, and what does it protect against?

The copy off site, and possibly the second kind of storage. A fire, a flood, a theft or ransomware that reaches the room takes all three copies at once. One copy must be somewhere that the same event cannot reach.

Field notes

  • Checksums made at backup time must be stored with the same care as the backup, and apart from the live system. An attacker who can change the data and the checksum list defeats the comparison.
  • Keep at least one copy that the live systems cannot change or delete: off line, or on storage that forbids changes for a set time. Ransomware looks for the backups first.
  • Test the restore of each important system on a schedule, and after every large change. Rotate which system you test, and restore on other hardware once a year: that is what a real disaster asks for.
  • The RTO of a process includes everything: noticing, deciding, getting hardware, restoring, checking, switching over. The time of the tar command is the small part.
  • ISO 22301 is the international standard for business continuity management systems. Annex A of ISO/IEC 27001 also has controls on backup and on readiness for disruptions. Take the wording from the standards.