Home / Articles / Home lab operations
Home lab operations · English edition
Offline Backup Verification and Ransomware Recovery Drills for Self-Hosted Servers
A backup that has never been restored is a hypothesis. This article is about turning that hypothesis into a measured fact: one copy that the production host cannot delete even with root, an automated check that reads the data instead of trusting an exit code, a restore test that starts the service and not just the file copy, and a rehearsal of the ransomware case where the last clean copy is the whole recovery plan.
What a backup has to prove
Two numbers decide whether a backup is useful: how much data you are willing to lose (RPO, recovery point objective) and how long you are willing to be down (RTO, recovery time objective). Everything else — tool, medium, retention, encryption — is a way of meeting those two numbers at a cost you accept.
The trap is that both numbers are usually written down from optimism rather than measurement. A nightly job suggests an RPO of 24 hours, but only if the job actually completes every night, and only if the restore you would perform is the one from last night. A self-hosted setup with a handful of services should be able to state three things without looking anything up:
- The timestamp of the most recent backup that was restored and started, not merely written.
- The measured time to restore the largest service from that backup, including the time to fetch it.
- Which copy is guaranteed to exist even if the production host is fully compromised, and where the key for it is kept.
If any of those answers is "I think so", the rest of this article is the work of turning it into a number with a date attached.
The copy rules, and why connected copies die
The classic 3-2-1 rule — three copies, on two media, one off-site — was written for disk failures and site disasters. Ransomware adds a requirement that the classic rule does not express: at least one copy must be unreachable from the machine that holds the data, because the attacker is now inside that machine.
A copy is not unreachable just because it is "a backup". These are the common arrangements that look like protection and are not:
| Arrangement | Survives disk failure | Survives ransomware on the production host | Why |
|---|---|---|---|
| Snapshots on the same pool/volume | Partly | No | Snapshots protect against overwrites, not against an attacker who gets the storage admin credential and deletes them |
| External USB disk, permanently attached | Yes | No | Mounted or auto-mounted means writable by anything running as the same user |
| NAS share with a saved credential in the backup client | Yes | No | The credential is on the compromised host; the share is a delete away |
| Cloud bucket with a write-only key | Yes | Yes, if versioning/object lock is on | Overwrites and deletes need permissions the client does not have |
| Rotated disk, disconnected after each run | Yes | Yes, for the disks that are offline | Physically absent when the attack happens |
Append-only repository (borg --append-only, REST server --append-only, object lock) | Yes | Yes, until the attacker reaches the backup host itself | The client cannot delete history; only the server side can |
The last two rows are the ones worth building. They fail differently, which is the point: the offline disk fails when you forget to rotate it, and the append-only repository fails when the backup host's own credentials are stolen. Having one of each means neither failure is total.
Making one copy production cannot delete
There are three mechanisms that do this in practice, and they compose well.
1. Pull instead of push
Have the backup host initiate the connection to production, not the other way round. Production then never holds a credential that can write to the repository, so a compromised production host has nothing to delete with. This alone removes the most common ransomware-vs-backup failure.
2. Append-only server-side restriction
With borg, an SSH forced command makes the client unable to prune or delete, regardless of what it asks for:
# backup host: ~/.ssh/authorized_keys
command="borg serve --append-only --restrict-to-path /srv/borg/prod",restrict ssh-ed25519 AAAAC3... pull@prod
# production host, run by the backup host over SSH:
borg create --stats --compression auto,zstd \
ssh://backup@backup.example.com/srv/borg/prod::prod-{now:%Y%m%dT%H%M%S} \
/srv/data /etc
With restic, the equivalent is a REST server started with --append-only, and with object storage it is a policy, not a flag — S3 Object Lock in compliance mode or a bucket policy that denies DeleteObject to the backup principal.
3. Physical rotation
Two disks, one always disconnected and off-site. The script that runs the backup mounts the current disk, writes, unmounts, and reminds you to swap. Rotation is the only mechanism that survives a total compromise of every always-on machine, and it is also the one people stop doing in week three — which is why the reminder belongs in the automation, not in a note.
Repository integrity is not data integrity
Both major open-source tools distinguish between "the repository is structurally consistent" and "the stored data still matches its checksums". The first is fast enough to run daily; the second reads everything and is the one that finds bit rot and truncated uploads.
# borg: structure only (fast), then full data verification (slow)
borg check /srv/borg/prod
borg check --verify-data /srv/borg/prod
# restic: metadata and pack integrity, then a sampled data read
restic -r /srv/restic check
restic -r /srv/restic check --read-data-subset=10%
A practical schedule for a small repository: structure check daily, full data verification monthly or as a rotating sample (10% weekly covers everything in about ten weeks and keeps each run short). The sampled check is not a compromise on rigour if the rotation is actually automated; it is a compromise if the same 10% is read forever, which is what happens when someone hard-codes a subset instead of deriving it from the week number.
Two more checks belong in the same job, because they catch the failures that verification cannot: snapshot count and size deltas (a backup that suddenly shrinks by 80% is a backup that is skipping files), and repository age (no new snapshot in 48 hours means the job stopped running, whatever the last exit code said).
Automating the schedule without lying to yourself
Cron and systemd timers both work; systemd is easier to observe because systemctl list-timers and the journal give you a history without extra tooling. A minimal unit pair:
# /etc/systemd/system/backup.service
[Unit]
Description=Backup to append-only repository
OnFailure=backup-alert@%n.service
[Service]
Type=oneshot
User=backup
ExecStart=/usr/local/bin/backup-run.sh
TimeoutStartSec=6h
Nice=10
IOSchedulingClass=idle
# /etc/systemd/system/backup.timer
[Unit]
Description=Nightly backup
[Timer]
OnCalendar=*-*-* 02:30:00
RandomizedDelaySec=15m
Persistent=true
[Install]
WantedBy=timers.target
Persistent=true matters more than it looks: without it, a machine that was off at 02:30 simply skips the run, and the gap is invisible until you go looking. OnFailure= gives you an alert on the exit code. Neither of those tells you the backup is restorable — that is the next section.
The script itself should do four things in order, and fail loudly at the first problem: check the destination is mounted (a backup that writes to an empty mount point fills the root filesystem instead), create the snapshot, apply retention, and print a machine-readable summary line that your monitoring can parse.
#!/usr/bin/env bash
set -euo pipefail
REPO="ssh://backup@backup.example.com/srv/borg/prod"
mountpoint -q /mnt/backup || { echo "FATAL: /mnt/backup not mounted"; exit 2; }
borg create --stats --compression auto,zstd \
"$REPO::prod-$(date -u +%Y%m%dT%H%M%S)" /srv/data /etc
borg prune --list --keep-daily 7 --keep-weekly 4 --keep-monthly 6 "$REPO"
echo "OK snapshots=$(borg list --short "$REPO" | wc -l)"
Automating the verification: restore, start, assert
A file copy that lands in a directory is not a restore. The test that means something restores into a scratch location, starts the service against it, and asks the service whether it is healthy. Here is the shape of a script that does that for one service, in about forty lines:
#!/usr/bin/env bash
set -euo pipefail
REPO="ssh://backup@backup.example.com/srv/borg/prod"
WORK=$(mktemp -d /var/tmp/restore-check.XXXXXX)
trap 'rm -rf "$WORK"' EXIT
# 1) restore the newest snapshot into a scratch directory
restic -r "$REPO" restore latest --target "$WORK" --include /srv/data
# 2) start the service against the restored data, on a throwaway port
docker run -d --rm --name restore-check \
-v "$WORK/srv/data:/data:ro" -p 127.0.0.1:18080:8080 \
app:stable
# 3) assert on behaviour, not on file count
for i in $(seq 1 30); do
curl -fsS http://127.0.0.1:18080/health >/dev/null && break
sleep 2
done
curl -fsS http://127.0.0.1:18080/api/items?limit=1 >/dev/null
# 4) record evidence
echo "{\"result\":\"pass\",\"restored\":\"$(du -sh "$WORK" | cut -f1)\",\"at\":\"$(date -u +%FT%TZ)\"}" \
> /var/log/restore-check/last.json
docker stop restore-check >/dev/null
Four decisions in that script are worth making deliberately. Restoring with --include keeps the test fast enough to run weekly. Mounting the data read-only prevents the test from "fixing" the backup. The health endpoint should touch the database, not return a static string. And the evidence file should be written every run, including failures, because the failure date is the interesting one when you are asked how long this has been broken.
If the service cannot be started in a container, the next best assertion is a checksum manifest: restore, then compare sha256sum of a known set of files against a manifest captured during backup. That proves the bytes survived; it does not prove the application can use them, which is why it is the fallback and not the first choice.
The drill ladder
Restore tests fail for two reasons: the backup is bad, or the restore procedure is. The only way to distinguish them is to practise at increasing depth, frequently enough that the shallow rung is boring and rarely enough that the deep rung is not a project.
| Cadence | Drill | Passes when | Time |
|---|---|---|---|
| Weekly (automated) | Restore one folder, hash it against the manifest | Hashes match, run finished inside its window | minutes |
| Monthly (automated) | Restore the newest snapshot of one service and start it | Health endpoint and one real query succeed | under an hour |
| Quarterly (manual) | Restore every service to a spare disk, boot it in an isolated VLAN | All services start; logins and data look right; measured RTO recorded | half a day |
| Every six months (tabletop) | Walk the ransomware playbook with the actual people involved | Each step has a named owner and a known credential source | 90 minutes |
The quarterly rung is the one that produces the number you will be asked for in a real incident. It is also the rung most likely to find the problem nobody expected: a restore that needs a licence key, a service whose configuration lived outside the backup set, or a DNS record that only the old container knew about. Every one of those is cheaper to find on a Sunday afternoon than at 3 a.m.
The ransomware case, step by step
The playbook below assumes an append-only or offline copy exists and has been verified. If it has not, stop reading and fix that first; the rest is recovery, and recovery without a clean copy is negotiation.
- Stop the spread before you stop the evidence. Disconnect the affected host from the network, but do not wipe or reinstall it: memory and the disk hold the timeline you will need to know whether the backup is clean.
- Assume every credential on it is burned. Rotate the SSH keys, service accounts, API tokens, and any password stored in a config file or a browser profile on that host. This includes the credential the backup client used.
- Find the last clean snapshot by time, then confirm by content. The backup system's own timestamps are the reliable signal. Inspect the candidate snapshot for the signs of an already-encrypted payload: unexpected file extensions, high-entropy files where documents should be, and file counts that jumped by thousands. Treat any scan for "encrypted files" as a heuristic, not proof.
- Restore into isolation first. Bring the service up on a separate VLAN or an isolated host with no route to production storage. Malware that runs on boot will run again here, and it is much better that it runs where nothing else is reachable.
- Verify before reconnecting. Confirm the restored service answers real queries, that the data looks like the data, and that no unexpected scheduled task, SSH key, or container image came back with it. Restores bring back persistence, not only files.
- Rebuild rather than clean, when you can. If the host's cost of death is a reinstall and a config restore, take it. Cleaning a compromised host is a judgement call that keeps costing attention for months.
- Reconnect with new credentials and a new backup chain. Keep the old chain for the investigation, start a fresh append-only chain for the rebuilt host, and change the repository passphrase if it was ever present on the compromised machine.
The numbers that prove it works
Keep these in one place and update them from the automated runs. When someone asks "are we covered", this table is the answer, and it does not depend on memory.
| Metric | Target | Where it comes from |
|---|---|---|
| Age of newest snapshot | < 24 h (alert at 36 h) | Repository listing, checked by monitoring |
| Last successful integrity check | < 35 days | Check job log |
| Last successful restore test | < 31 days | Restore-check evidence file |
| Measured restore time, largest service | under your RTO | Quarterly drill stopwatch, recorded |
| Backup size vs. previous run | within ±20% | Backup summary line |
| Snapshots older than the retention policy | 0 | Prune log |
| Offline copy age | < 7 days since last rotation | Rotation checklist / calendar |
Failure modes
| What it looks like | What is actually happening | Fix |
|---|---|---|
| Job reports success every night | Exit code 0 while files were skipped (permission errors, excluded paths, unreadable mounts) | Parse the summary: file count and bytes, not just the exit code |
| Repository grows by 40 GB a night | A container image or cache directory is inside the backup set | Exclude caches and images; version them instead |
| Prune deleted the only good snapshot | Retention ran before the integrity check, or the policy counted a failed backup as a success | Check first, then prune; alert when snapshot count drops unexpectedly |
| Restore works but the service will not start | Configuration, secrets, or an external dependency were outside the backup set | Restore tests find this; add the missing paths to the set |
| Passphrase stored next to the repository | Convenience during setup, never revisited | Keep it in a password manager and in a sealed offline copy; never on the backup host or production |
| Offline disk stopped being rotated | Reminder lived in someone's head | Put the rotation in the timer and alert on offline-copy age |
One-page checklist
- RPO and RTO written down, with the restore time that was actually measured
- At least one copy that production cannot delete: pull model, append-only, or offline rotation
- Daily structure check; full or rotating sample data verification monthly
- Alert on snapshot age, not only on job failure
- Automated weekly restore-and-hash; monthly restore-and-start
- Quarterly full-service restore into an isolated network, with the measured time recorded
- Restore tests include configuration, secrets, and the access review that follows a restore
- Retention runs after verification, and an unexpected drop in snapshot count alerts
- Repository passphrase stored off both production and the backup host, with a sealed offline copy
- Ransomware playbook rehearsed with named owners and known credential sources
References
- CISA — #StopRansomware Guide
- NIST SP 800-34 Rev. 1 — Contingency Planning Guide for Federal Information Systems
- BorgBackup — Central repository server, append-only mode
- restic — Working with repositories (check, --read-data-subset)
- restic REST server — --append-only option
- Amazon S3 — Object Lock
- systemd.timer — Persistent and OnCalendar