Tag: backups

  • Horcrux: I backed up a Postgres container, deleted it, restored it, and the tables were gone

    Horcrux: I backed up a Postgres container, deleted it, restored it, and the tables were gone

    Full disclosure: I make Horcrux. It’s my Gentoo-based hypervisor, it’s pre-1.0, and this is my notebook for the week.

    Everybody has a backup story that ends with “and then I found out it didn’t include the data”. I didn’t want that story to be about my own software, so last Saturday morning I tested exactly that. A Postgres container, a backup from the Backups page, everything deleted, a restore. The restore finished with a running database in it and no tables.

    The setup

    The daily server image from that morning (horcrux-bin 0.1.0_p202611210632), installed by answer file onto a ZFS root in a KVM guest on one of my lab laptops. 4 vCPUs, 6 GB of RAM, OpenRC. I logged into the web UI as the administrator account the installer makes and clicked everything below. The only things I did outside the browser are marked.

    The workload is a stack from the Stacks page: postgres:16-alpine with a named volume called pgdata, and a second container that inserts a row into a table every 5 seconds so there is something to lose. It was 26 rows when I broke things. I used the Docker runtime, not Podman, and the compose file went in as plain text.

    Stacks page with a two service compose file: a postgres db with a named volume and a ticker service
    The stack. The password in it is a throwaway for this VM.

    The backup

    Backups page, pick the container, mode snapshot, zstd, a note that says “db before I break it”, Back up now. It was done inside the 12 seconds I recorded and wrote a 102.8 MiB archive. Then Verify, which said “verified OK (2 file(s) checked)”.

    Backing up the database container. 13 seconds, real time.
    Backups page showing one archive marked OK after verification
    Verified OK.

    Then I looked inside the archive, which is a thing I should have done before the video. It holds three files: a manifest, inspect.json, and rootfs.tar, about 297 MB uncompressed. That is the container’s file system as docker export writes it. In the tar, /var/lib/postgresql/data/ is an empty directory. On the live container that directory was 9.3 MB. Verify checks the checksums of what is in the archive, so it passed. The data was never in it.

    Breaking it

    I removed the stack from the Stacks page. The confirm text says it “stops and deletes every container in it”, and that’s accurate. The pgdata volume survived, which is Docker’s normal behaviour. Then I went to the Volumes page and removed the leftovers, the way you tidy up when you think a project is gone.

    Removing the stack and then the volume. 16 seconds, real time.
    Volumes page listing pgdata and an anonymous volume, with the Actions column off screen to the right
    The Volumes page at 1440 pixels wide. The Remove buttons are past the right edge, so I clicked them with a script. A person would scroll sideways.

    Restoring

    Backups page, Restore on the archive, original id, start after restore. It failed:

    Red banner: Restore failed, HTTP 500, network notes_default not found
    The first restore attempt.

    The stack’s network, notes_default, went away with the stack, and the container’s config in the backup still points at it. What the failure left behind was a container in the Created state and a brand new empty pgdata volume. I made the network again on the Container Networks page, pressed Start on the Containers page, and it ran. The image is a new one, horcrux-restore/notes_db_9405c03c:94a20893, imported from the tar.

    The failed restore, the network, and starting the container. 39 seconds, real time.
    Containers page with the restored notes_db container, stopped, image horcrux-restore/notes_db
    Restored and stopped, before I pressed Start.

    Then I asked the database. The notes database exists, because the restored config still has POSTGRES_DB=notes and the Postgres image creates it on first start. It has no tables. The 26 rows are gone, and so is the table they were in. Nothing on any page warned me before or after.

    Terminal output: restored notes_db container up, database list including notes, no relations found, relation readings does not exist
    From a root shell on the node (the one other thing I did outside the browser): the list of databases, then “Did not find any relations”.

    Getting the data back by hand

    /var/lib/docker is its own ZFS dataset on a Horcrux install, so a ZFS snapshot of it contains every Docker volume. I tried that on the restored database: made a table with 1000 rows, took rpool/var/lib/docker@hand-before-drop (0 bytes used when it was taken), dropped the table, stopped the container, emptied the volume directory, copied pgdata back out of the snapshot’s .zfs/snapshot directory, and started it. Postgres logged “redo done” and “ready to accept connections”, and select count(*) said 1000.

    Terminal session: zfs snapshot, drop table, copy from the snapshot directory, redo done, count 1000
    The commands and the output, from the node.

    This isn’t a Horcrux feature. The Snapshots page only knows about VMs. It also worked once, on an idle database of one table, and a snapshot taken under write load only gives you crash recovery. For a database you care about, run pg_dump on a schedule. The file system layout just makes the snapshot trick possible.

    What doesn’t work (yet)

    • Container backups don’t include named volumes. This one matters most. I already had it in my QA notes from the Thursday before, with a fix on a branch that adds the volume data to the archive. I checked main again this morning, a week later, and that branch still isn’t merged, so a fresh daily image won’t have it either.
    • Restore only found out the network was gone at the start step. A failed restore leaves a half-made container and an empty volume behind. It should fail before it creates anything, or it should create the network.
    • The Volumes and Networks lists don’t refresh after you remove or create something with Docker selected. I watched the Networks list for 30 seconds after creating one and it never appeared. A reload showed it. Same on the Volumes page after removing pgdata: it was gone from disk and still on screen.
    • On the Volumes page at 1440 pixels the Actions column is off the right edge. On a 390 pixel phone the backup archive table is 887 pixels wide, so the Restore and Verify buttons sit behind a sideways scroll.
    • The times don’t agree. The Backups page shows 10:16:27 -08:00, the Containers page shows the creation time as 18:19:38 UTC, and the node’s own logs are in UTC.
    • Every container row carries the same warning that CRIU isn’t installed, so state can’t be saved. The warning is accurate, and it appears on every row.
    • The UI listens on port 8006 and not 443, and the certificate is self-signed, so the browser stops you at a warning first. I told the browser to ignore it.
    Phone-width Backups page with the archive table cut off after the Size column
    Backup archives on a 390 pixel wide screen. Time and Size fit, the buttons don’t.

    Design decisions

    The backup code calls itself a vzdump equivalent, and it follows Proxmox’s behaviour on purpose: a catalog of archives with SHA-256 checksums, Verify that re-reads them, retention per guest, restore into the same or a new id. Its header comment says a no-pause snapshot, a copy-before-write block job, isn’t implemented, so in snapshot mode a running container is frozen for the copy and then resumed. The restore form says the archive is verified first and that a corrupt one never touches the existing guest, and that part I believe, because the UI states it and the verify step exists.

    Containers go in with docker export, which is a file system and nothing else. The code has a comment saying so next to the function that puts the image config back by hand. I haven’t found anything written down about why volumes were left out, and I’m not going to invent a reason. My QA notes file it as a bug, not as a decision.

    ZFS is under all of this for the reason I gave in the last post: recovery and bit rot protection. The separate dataset for Docker’s data comes from the same layout that keeps the root file system rollbackable on its own. That layout is why the snapshot trick above works at all.

    Where it stands

    Backups work for containers that store their state inside the container. They don’t work for containers that use a volume, and that includes the usual way to run Postgres. The fix exists and isn’t merged yet. Until it is, I wouldn’t trust a container backup from this build to hold a database.

    Next: get that branch merged, then run this same test again on the build that has it, with a database big enough to take more than a second to copy. I haven’t re-run any of this on a newer image than the one from last Saturday, so the other items above are as of that build.

    Horcrux lives at horcrux.errant.solutions.

  • Restore testing and your real recovery time

    Restore testing and your real recovery time

    Part 3 of 3 in the Surviving ransomware series. Part 1: Backups an attacker can’t delete. Part 2: Segmentation and limiting lateral movement.

    Ask a team for its recovery time objective and you’ll usually get a confident number, often 4 hours or 24 hours. Ask when they last restored a whole system from backup and timed it, and the confidence drops fast. In my experience the RTO on the slide and the time you’d actually get differ by a factor of several. Nobody finds out until the day it matters.

    This is the last part of the series. Part 1 covered backups an attacker can’t delete, and part 2 covered segmentation that limits how much gets hit. This one is the dull question: once you have clean backups, how long until you’re running again?

    Two numbers, defined plainly

    Illustrative recovery timeline in dependency order compared with a 24-hour stated RTO

    The recovery point objective (RPO) is how much data you can afford to lose, measured as time between the last good copy and the incident. The recovery time objective (RTO) is how long you can afford to be down. Both are business decisions, and the backup software doesn’t set either one for you.

    The trap is that people derive RTO from the time it takes to restore one file or one VM, then quietly assume the whole estate restores in parallel at that speed. It doesn’t, for two reasons: bandwidth and dependencies.

    Do the arithmetic before the drill

    Restore throughput is usually far below the vendor’s quoted ingest speed, because restores are bottlenecked by whatever’s slowest: deduplication rehydration, the network link, the target storage’s write rate, or the cloud egress path. Measure it, then do the multiplication.

    # Wall-clock hours to move data at a sustained restore rate
    def restore_hours(terabytes, mb_per_sec):
        return terabytes * 1_000_000 / mb_per_sec / 3600
    
    for tb, rate in [(5, 500), (50, 500), (50, 200), (200, 1000)]:
        print(f"{tb:>4} TB at {rate:>4} MB/s: {restore_hours(tb, rate):6.1f} h")
       5 TB at  500 MB/s:    2.8 h
      50 TB at  500 MB/s:   27.8 h
      50 TB at  200 MB/s:   69.4 h
     200 TB at 1000 MB/s:   55.6 h

    If your critical data is 50 TB and your measured restore rate from the immutable tier is 200 MB/s, a 24-hour RTO isn’t achievable, regardless of how good everything else is. You can find that out with a calculator in five minutes, or during an incident that drags on for three days.

    Dependencies decide the order

    You can’t restore the order system until there’s something for it to authenticate against. A realistic recovery happens in layers. First the backup infrastructure itself has to be up, along with its catalogue and its encryption keys. If the backup server was encrypted too, you’re rebuilding it from scratch before restoring anything else. Then identity and core network services: Active Directory or your identity provider, DNS, DHCP, PKI and time. Then the data stores, then the applications on top of them, then everything else.

    Maersk’s NotPetya recovery is the best-known example of how fragile that first layer can be. As reported by Wired, its domain controllers had all been wiped except one in Ghana, which survived only because a power outage had taken it offline before the attack. That single machine became the seed for rebuilding the company’s Active Directory. Don’t count on a lucky power cut.

    Write the dependency order down, along with who restores each layer and roughly how long each takes. Then look at the critical path. Sequential layers add up, and the result is usually much longer than the RTO anyone quotes.

    Pick a clean restore point

    After ransomware, the newest backup is often the wrong one. The attacker may have been inside for days or weeks, with tools planted, accounts created and scheduled tasks waiting. Restoring last night’s backup can bring the intrusion back with it.

    This is where the logging work from the Detection engineering series pays off. Choosing a restore point means you need a reasonably confident time of first compromise for each affected system. Then you restore into an isolated recovery network, scan the restored systems, check them against known indicators from the investigation, reset every credential, and only then reconnect them. Budget time for this. In a real incident it often takes longer than the data copy.

    Automate restore tests

    A backup you haven’t restored is a hypothesis. The cheapest way to keep testing is to automate small restores often and big ones on a schedule.

    Automated tests should check the application, not just the files. A database restore test that confirms the dump file exists proves very little. One that restores into a scratch instance, runs real queries and records how long it took proves a lot:

    #!/usr/bin/env bash
    set -euo pipefail
    start=$(date +%s)
    
    dropdb --if-exists -h restore-test.internal orders_check
    createdb -h restore-test.internal orders_check
    pg_restore -h restore-test.internal -d orders_check --jobs=8 \
      /restore/latest/orders.dump
    
    # The data should be recent and non-trivial
    recent=$(psql -h restore-test.internal -d orders_check -Atc \
      "select count(*) from orders where created_at > now() - interval '2 days'")
    [ "$recent" -gt 0 ] || { echo "restore is stale or empty"; exit 1; }
    
    echo "restore_seconds=$(( $(date +%s) - start )) recent_rows=$recent"

    Run something like this weekly against a randomly chosen system, ship the timing to your metrics system, and alert when a test fails or when restore time creeps past what the RTO allows. Over a few months you have a measured recovery time for each system. That’s worth more than any number on a slide.

    Run a full drill at least once a year

    Automated tests cover individual systems. They don’t cover the dependency chain, the people, or the coordination. Once a year, more often for critical services, run a drill that restores a meaningful slice of production into an isolated environment from the immutable or offline copies, in dependency order, with the people who’d actually do it.

    Assume the worst during the drill: the primary backup server is gone, the identity provider is down, and the wiki with the runbooks is encrypted. Keep printed copies of the recovery runbook, the dependency order, key contacts and break-glass procedures somewhere physical. Have an out-of-band way to communicate, since your email and chat may be part of what’s down.

    Time every step. The drill’s output isn’t a pass or fail. It’s a list of measured durations and a list of things that surprised you.

    Report the real number

    After the drill, publish the measured recovery time next to the RTO, per service, to the people who set the RTO. If they differ, that’s a business decision to make with real data: spend money on faster restores, change the architecture, or accept a longer outage knowingly. Any of those is fine. Finding out during an incident isn’t.

    If you do one thing after reading this, pick one important system, restore it somewhere isolated this week, and time it. That number will tell you more about your ransomware readiness than any policy document.

  • Backups an attacker can’t delete

    Backups an attacker can’t delete

    Part 1 of 3 in the Surviving ransomware series.

    Modern ransomware crews don’t start by encrypting things. They start by finding your backups. The playbook described in incident reports from the last few years is depressingly consistent: get domain admin, locate the backup server, delete the restore points or wipe the repository, and only then run the encryptor. If the backups survive, the ransom demand is a negotiation. If they don’t, it’s a hostage situation.

    So the question for this series isn’t “do we have backups?” Almost everyone does. It’s whether an attacker who holds your most privileged credentials can destroy them.

    3-2-1 was written for a different threat

    Backup architecture with production, backup and immutable zones and one-way data flows

    The classic 3-2-1 rule says three copies of your data, on two different types of media, with one copy offsite. It’s a great rule for fires, floods and failed RAID controllers. It says nothing about an adversary who logs in with valid credentials and deletes all three copies, because in most environments the same admin accounts can reach all of them.

    The extension you’ll often see now is 3-2-1-1-0. The extra 1 is a copy that is offline, air-gapped or immutable. The 0 is zero errors when you verify a restore. I like it because both additions target real failure modes: deletion by a privileged attacker, and backups that turn out to be unrestorable on the worst day of your year.

    The backup system is a target in its own right

    Backup servers are attractive because they hold everything and they usually hold credentials to reach everything. CVE-2023-27532 in Veeam Backup & Replication is a good illustration. It let an unauthenticated user who could reach the backup service port pull encrypted credentials out of the configuration database. It was exploited in the wild and added to CISA’s Known Exploited Vulnerabilities catalog in August 2023.

    The lessons I take from it are architectural rather than vendor-specific:

    • Put the backup server’s management interfaces on a network segment that ordinary servers and workstations can’t reach.
    • Don’t join backup infrastructure to the production Active Directory domain. If domain admin is compromised, the backup console shouldn’t fall with it.
    • Require MFA for the backup console and for any cloud account that holds backup copies, using accounts that exist only for that purpose.
    • Patch backup software on the same urgency as internet-facing systems, because for an intruder it effectively is one.

    Immutability, done properly

    Immutable storage means a backup can’t be modified or deleted until its retention period ends, no matter who asks. The details decide whether it holds up against a real admin-level compromise.

    On AWS, S3 Object Lock has two modes. Governance mode can be bypassed by users with the s3:BypassGovernanceRetention permission, which makes it useful against mistakes and useless against someone who has stolen an admin role. Compliance mode can’t be shortened or removed by anyone, including the account root user, until the retention date passes.

    aws s3api create-bucket --bucket example-backups-immutable \
      --region us-west-2 \
      --create-bucket-configuration LocationConstraint=us-west-2 \
      --object-lock-enabled-for-bucket
    
    aws s3api put-object-lock-configuration \
      --bucket example-backups-immutable \
      --object-lock-configuration '{
        "ObjectLockEnabled": "Enabled",
        "Rule": { "DefaultRetention": { "Mode": "COMPLIANCE", "Days": 35 } }
      }'

    Test with a small bucket and short retention first. Compliance mode is unforgiving: if you set a year by mistake, you’re paying for that storage for a year.

    Put the bucket in a separate AWS account dedicated to backups, with its own tightly held credentials, so production compromise doesn’t hand over the backup account too. The same idea applies to other clouds and to on-premises object stores that support WORM retention.

    For self-hosted setups, I prefer a pull model. The backup server reaches into production to fetch data, and production holds no credentials that work on the backup server. With ZFS, the source host can delegate just enough to a dedicated user:

    # On the production host: allow the backup user to snapshot and send, nothing else
    zfs allow -u backupsvc send,snapshot,hold tank/data

    The backup server then pulls incremental snapshots over SSH and keeps its own snapshot history. An attacker with root on the production host can destroy production’s snapshots, but has no path to the copies on the backup server.

    Retention has to outlast the intrusion

    Immutability with seven days of retention doesn’t help if the attacker was inside for three weeks before encrypting anything, because every restore point you have may contain their tooling, or their changes to your data. Mandiant’s M-Trends 2024 report put median global dwell time at 10 days in 2023, and the median isn’t the case you should plan for.

    I’d treat 30 days of immutable restore points as a floor, with a longer, sparser tail (weekly or monthly) beyond that. Part 3 of this series covers how to pick a clean restore point, which depends heavily on having logs that tell you when the intrusion started.

    Offline still has a place

    Tape and removable disks rotated offsite feel old fashioned, and they’re slow. They’re also the one copy that no network-borne attacker can touch. For a smaller organisation, a weekly full backup to a disk that’s disconnected and locked away is a cheap and effective last line. Keep the backup encryption keys stored separately from the backups, including an offline copy, because encrypted backups you can’t decrypt are no backups at all.

    Watch for attacks on the backups

    Deleting backups is noisy if you’re listening. Alert on deletion or retention changes in backup jobs, on someone disabling Volume Shadow Copy or running vssadmin delete shadows, on failed or skipped jobs across many systems at once, and on new admin accounts in the backup console. These events often come hours before encryption, and those hours are your window to respond.

    Verifying the restore

    The final 0 is the one most often skipped. A green “job succeeded” status means data was written somewhere. It doesn’t mean you can restore a working system from it in a reasonable time. Part 3 is about proving that, with real restore tests and measured recovery times. Before that, part 2 looks at segmentation, which decides how far an intruder gets before they reach the backup server at all.

    Other parts: Part 2: Segmentation and limiting lateral movement. Part 3: Restore testing and your real recovery time.