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:

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:

ArrangementSurvives disk failureSurvives ransomware on the production hostWhy
Snapshots on the same pool/volumePartlyNoSnapshots protect against overwrites, not against an attacker who gets the storage admin credential and deletes them
External USB disk, permanently attachedYesNoMounted or auto-mounted means writable by anything running as the same user
NAS share with a saved credential in the backup clientYesNoThe credential is on the compromised host; the share is a delete away
Cloud bucket with a write-only keyYesYes, if versioning/object lock is onOverwrites and deletes need permissions the client does not have
Rotated disk, disconnected after each runYesYes, for the disks that are offlinePhysically absent when the attack happens
Append-only repository (borg --append-only, REST server --append-only, object lock)YesYes, until the attacker reaches the backup host itselfThe 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.

Be precise about what this buys you. Append-only stops the client from deleting. It does not stop someone with shell on the backup host, and it does not stop an attacker from filling the repository with garbage until the next genuine backup fails. Pair it with a size quota and an alert on repository growth.

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.

CadenceDrillPasses whenTime
Weekly (automated)Restore one folder, hash it against the manifestHashes match, run finished inside its windowminutes
Monthly (automated)Restore the newest snapshot of one service and start itHealth endpoint and one real query succeedunder an hour
Quarterly (manual)Restore every service to a spare disk, boot it in an isolated VLANAll services start; logins and data look right; measured RTO recordedhalf a day
Every six months (tabletop)Walk the ransomware playbook with the actual people involvedEach step has a named owner and a known credential source90 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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 credential that hurts most is the one in the backup client. If production could write to the repository, the attacker could too — which is why pulling from the backup host and keeping the passphrase off production is the single highest-value change in this whole article.

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.

MetricTargetWhere it comes from
Age of newest snapshot< 24 h (alert at 36 h)Repository listing, checked by monitoring
Last successful integrity check< 35 daysCheck job log
Last successful restore test< 31 daysRestore-check evidence file
Measured restore time, largest serviceunder your RTOQuarterly drill stopwatch, recorded
Backup size vs. previous runwithin ±20%Backup summary line
Snapshots older than the retention policy0Prune log
Offline copy age< 7 days since last rotationRotation checklist / calendar

Failure modes

What it looks likeWhat is actually happeningFix
Job reports success every nightExit 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 nightA container image or cache directory is inside the backup setExclude caches and images; version them instead
Prune deleted the only good snapshotRetention ran before the integrity check, or the policy counted a failed backup as a successCheck first, then prune; alert when snapshot count drops unexpectedly
Restore works but the service will not startConfiguration, secrets, or an external dependency were outside the backup setRestore tests find this; add the missing paths to the set
Passphrase stored next to the repositoryConvenience during setup, never revisitedKeep it in a password manager and in a sealed offline copy; never on the backup host or production
Offline disk stopped being rotatedReminder lived in someone's headPut the rotation in the timer and alert on offline-copy age

One-page checklist

References