# ZFS Native Encryption with Raw Send for Untrusted Remote Backups

This guide uses ZFS native encryption and raw send streams to copy encrypted snapshots to a backup system that does not have the decryption key. A raw send preserves the encrypted blocks and wrapped dataset key, so the receiving system can store and incrementally update the dataset without seeing its files.

The example uses two FreeBSD 15.x hosts and three Bastille jails:

- The source host runs a Bastille jail named `zhost`, which owns the data and is allowed to retrieve the encryption key.
- The backup host runs a Bastille jail named `zback` and never receives the key.
- A trusted host runs an optional nginx jail named `zkey`, which holds and serves the key to `zhost`.

The two jails may be created on one host for testing, but that is not a remote or disaster-recovery backup. For a real backup, put `zback` on another host and pool. Native encryption protects confidentiality; it does not stop the backup administrator from deleting snapshots or observing unencrypted ZFS metadata such as dataset names, snapshot names, properties, and space usage.

## Prerequisites

- Two FreeBSD 15.x hosts with ZFS
- Bastille installed and configured on each host
- Network connectivity from the initiating jail to the other jail's SSH service
- A separate, tested backup of the encryption key or passphrase

The examples use these names; replace them to match your systems:

| Purpose | Value |
|---|---|
| Source jail | `zhost` |
| Source parent dataset | `zroot/bastille/jails/zhost/root/data` |
| Encrypted source dataset | `zroot/bastille/jails/zhost/root/data/encrypt` |
| Backup jail | `zback` |
| Backup parent dataset | `zroot/bastille/jails/zback/root/data` |
| Received backup dataset | `zroot/bastille/jails/zback/root/data/encrypt` |
| HTTP key-service jail | `zkey` at `192.168.3.63` |

## 1. Key-loading options

An encrypted dataset must be created with both `encryption` and `keyformat`. `keylocation` tells ZFS where to obtain the user key that unwraps the dataset's master key.

| Method | Properties | Typical use |
|---|---|---|
| Passphrase prompt | `keyformat=passphrase`, `keylocation=prompt` | Interactive systems |
| Raw key file | `keyformat=raw`, `keylocation=file:///absolute/path` | Automated systems |
| HTTP or HTTPS | `keyformat=raw`, `keylocation=https://server/key` | Central key service |
| Raw key on standard input | `keyformat=raw`, `keylocation=prompt` | External key agent |

Raw and hexadecimal keys are always 32 bytes, regardless of the selected encryption suite. For standard input, pipe the key to an ordinary `zfs load-key`; `-n` only checks a key and does not load it:

```sh
key-agent get zhost-data | zfs load-key zroot/bastille/jails/zhost/root/data/encrypt
```

HTTP/HTTPS support depends on how OpenZFS was built and whether a `fetch(3)` or libcurl backend is available. The response body must contain key material matching `keyformat`; no special HTTP content type is required. Prefer HTTPS. OpenZFS documents CA and client-certificate environment variables, but it does not provide a general bearer-token configuration option.

## 2. Create and configure the Bastille jails

Run the source commands on the source host and the backup commands on the backup host. Bastille's `-B` option creates a bridged VNET jail, so the address needs a prefix length and the named interface must already be a bridge.

```sh
pkg install -y bastille
sysrc bastille_enable=YES
bastille setup
bastille bootstrap 15.1-RELEASE

# Source host
bastille create -B zhost 15.1-RELEASE 192.168.3.61/24 vm-public

# Backup host
bastille create -B zback 15.1-RELEASE 192.168.3.62/24 vm-public

# Trusted host for the optional HTTP key service
bastille create -B zkey 15.1-RELEASE 192.168.3.63/24 vm-public
```

Each ZFS-managing jail (`zhost` and `zback`) needs the following parameters in its Bastille `jail.conf`, normally under `/usr/local/bastille/jails/JAIL/jail.conf`. The HTTP-only `zkey` jail does not need them:

```conf
allow.mount;
allow.mount.zfs;
enforce_statfs = 1;
```
Or set via bastille: 
```bastille
bastille config zhost set enforce_statfs 1
bastille config zhost set allow.mount
bastille config zhost set allow.mount.zfs
```

`enforce_statfs = 1` is required here, not merely recommended. Bastille normally creates jails with `enforce_statfs = 2`; at that value, `allow.mount.zfs` is ineffective. The result is a permission error when root inside `zhost` tries to create `zroot/bastille/jails/zhost/root/data/encrypt`. Stop the jail, change the value to `1`, and then restart it.

The default jail devfs ruleset, ruleset 4, exposes `/dev/zfs`; `mount.devfs` must also remain enabled.

Create a dedicated parent dataset on each host while its jail is stopped:

```sh
# Source host
zfs create -o jailed=on zroot/bastille/jails/zhost/root/data

# Backup host
zfs create -o jailed=on zroot/bastille/jails/zback/root/data
```

On FreeBSD 15.0 and later, use Bastille to set the appropriate `zfs.dataset` jail parameter while each jail is stopped:

```sh
# Source host
bastille config zhost set zfs.dataset zroot/bastille/jails/zhost/root/data

# Backup host
bastille config zback set zfs.dataset zroot/bastille/jails/zback/root/data
```

The dataset in each command must match that jail. In particular, do not configure `zback` with `zroot/bastille/jails/zhost/root/data`; that would attach the source jail's dataset instead of the `zback` dataset created above.

On FreeBSD 14.x, use an `exec.created` hook instead:

```conf
exec.created += "zfs jail ${name} pool/jailed/dataset";
```

Bastille's `bastille zfs JAIL jail DATASET /path` command is another supported way to maintain the attachment. Do not configure both mechanisms for the same dataset.

Start the jails after saving the configuration:

```sh
bastille start zhost       # source host
bastille start zback       # backup host
bastille start zkey        # trusted key-service host
```

Inside a jail, ZFS still uses the dataset's real pool-qualified name. Attaching `zroot/bastille/jails/zhost/root/data` does not create a virtual pool named `data`. Jailed root can administer the attached subtree, while the host retains control of the pool and datasets outside that subtree. `zfs allow` is needed only if ZFS commands will run as a non-root user.

### Optional HTTP key host: `zkey`

The `zkey` jail does not need a delegated ZFS dataset or `allow.mount.zfs`. Install nginx from the host:

```sh
bastille pkg zkey install -y nginx
```

Enter `zkey`, create a 32-byte raw key, and make it readable by nginx's `www` group:

```sh
bastille console zkey

install -d -o root -g www -m 750 /usr/local/www/zkeys
dd if=/dev/urandom of=/usr/local/www/zkeys/data-encrypted.key bs=32 count=1
chown root:www /usr/local/www/zkeys/data-encrypted.key
chmod 440 /usr/local/www/zkeys/data-encrypted.key
```

Add this `server` block inside the `http` block in `/usr/local/etc/nginx/nginx.conf`. The address restriction lets only `zhost` request the key:

```nginx
worker_processes auto;

events {
    worker_connections 1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile on;
    keepalive_timeout 65;

    server {
        listen 80;
        server_name 192.168.3.63;

        location = /data-encrypted.key {
            alias /usr/local/www/zkeys/data-encrypted.key;
            default_type application/octet-stream;

            allow 192.168.3.61;
            deny all;
        }

        location / {
            return 404;
        }
    }
}
```

Check the configuration and start nginx:

```sh
nginx -t
sysrc nginx_enable=YES
service nginx start
```

From `zhost`, confirm that the endpoint returns exactly 32 bytes without saving or displaying the binary key:

```sh
fetch -q -o - http://192.168.3.63/data-encrypted.key | wc -c
# Expected output: 32
```

Plain HTTP provides no confidentiality against network capture. Use it only on an isolated, trusted network for testing. For production, configure TLS on `zkey`, change the URL to `https://`, verify the server certificate, and preferably require a client certificate. Keep `zkey` off the untrusted backup host and retain a separate offline copy of the key.

## 3. Create the encrypted source dataset

Enter `zhost` and choose one key method. The examples set an explicit mount point inside the jail.

### Raw key file

```sh
bastille console zhost

install -d -m 700 /root/keys
dd if=/dev/urandom of=/root/keys/data-encrypted.key bs=32 count=1
chmod 400 /root/keys/data-encrypted.key

zfs create \
  -o encryption=aes-256-gcm \
  -o keyformat=raw \
  -o keylocation=file:///root/keys/data-encrypted.key \
  -o mountpoint=/data/encrypt \
  zroot/bastille/jails/zhost/root/data/encrypt
```

### Passphrase

```sh
zfs create \
  -o encryption=aes-256-gcm \
  -o keyformat=passphrase \
  -o keylocation=prompt \
  -o mountpoint=/data/encrypt \
  zroot/bastille/jails/zhost/root/data/encrypt
```

### Key from the `zkey` HTTP service

```sh
zfs create \
  -o encryption=aes-256-gcm \
  -o keyformat=raw \
  -o keylocation=http://192.168.3.63/data-encrypted.key \
  -o mountpoint=/data/encrypt \
  zroot/bastille/jails/zhost/root/data/encrypt
```

For a TLS-enabled `zkey`, use `https://192.168.3.63/data-encrypted.key` or, preferably, a hostname that matches the server certificate.

Verify the result:

```sh
zfs get encryption,encryptionroot,keystatus,keyformat,keylocation,mountpoint \
  zroot/bastille/jails/zhost/root/data/encrypt
```

Back up the actual key or passphrase offline. Saving the value of `keylocation` backs up only a path, URL, or the word `prompt`, not the key itself.

## 4. Restrict SSH on the backup jail

The push and restore examples use a forced command for root's SSH key. The wrapper accepts only three operations:

- `latest` prints the newest received snapshot.
- `receive` receives a stream into the fixed backup dataset without mounting it.
- `send SNAPSHOT` raw-sends one backup snapshot for restoration.

Install this root-owned script as `/usr/local/sbin/zfs-backup-target` inside `zback`:

```sh
#!/bin/sh
set -eu

DST="zroot/bastille/jails/zback/root/data/encrypt"
set -f
set -- ${SSH_ORIGINAL_COMMAND-}

valid_snapshot()
{
    case "$1" in
        backup_[0-9A-Za-z_.:-]*) ;;
        *) return 1 ;;
    esac
    case "$1" in
        *[!0-9A-Za-z_.:-]*) return 1 ;;
    esac
}

case "${1-}" in
    latest)
        [ "$#" -eq 1 ] || exit 64
        zfs list -H -t snapshot -o name -S creation -r "$DST" 2>/dev/null |
          awk -v prefix="${DST}@" 'index($0, prefix) == 1 { print; exit }'
        ;;
    receive)
        [ "$#" -eq 1 ] || exit 64
        exec zfs receive -u "$DST"
        ;;
    send)
        [ "$#" -eq 2 ] && valid_snapshot "$2" || exit 64
        exec zfs send -w "${DST}@$2"
        ;;
    *)
        exit 64
        ;;
esac
```

Set ownership and permissions:

```sh
chown root:wheel /usr/local/sbin/zfs-backup-target
chmod 755 /usr/local/sbin/zfs-backup-target
```

Add the source jail's public key to `/root/.ssh/authorized_keys` in `zback`:

```text
command="/usr/local/sbin/zfs-backup-target",restrict ssh-ed25519 AAAA... zhost-backup
```

Configure `sshd` to permit public-key root login but never password login (`PermitRootLogin prohibit-password`), then start or reload it. A separate restoration key can use the same forced command. Protect private keys and verify host keys rather than disabling SSH host-key checking.

## 5. Push backups from `zhost`

Install the following as `/usr/local/sbin/zfs-encrypted-push` inside `zhost`. FreeBSD `sh` supports `pipefail`; this prevents pruning after either side of the transfer pipeline fails.

```sh
#!/bin/sh
set -eu
set -o pipefail

SRC="zroot/bastille/jails/zhost/root/data/encrypt"
DST="zroot/bastille/jails/zback/root/data/encrypt"
REMOTE="root@192.168.3.62"
KEEP=7

SNAP="backup_$(date -u +%Y%m%dT%H%M%SZ)"
NEW="${SRC}@${SNAP}"
zfs snapshot "$NEW"

REMOTE_LATEST=$(ssh "$REMOTE" latest)

if [ -n "$REMOTE_LATEST" ]; then
    case "$REMOTE_LATEST" in
        "${DST}@"backup_*) ;;
        *) echo "Unexpected destination snapshot: $REMOTE_LATEST" >&2; exit 1 ;;
    esac

    BASE_NAME=${REMOTE_LATEST#*@}
    BASE="${SRC}@${BASE_NAME}"
    if ! zfs list -H -t snapshot "$BASE" >/dev/null 2>&1; then
        echo "No common source snapshot for $REMOTE_LATEST" >&2
        echo "Create a new destination dataset for a fresh full backup." >&2
        exit 1
    fi

    zfs send -w -i "$BASE" "$NEW" | ssh "$REMOTE" receive
else
    zfs send -w "$NEW" | ssh "$REMOTE" receive
fi

# Prune only after a successful transfer. Newest snapshots are listed first.
zfs list -H -t snapshot -o name -S creation -r "$SRC" |
  awk -v prefix="${SRC}@" 'index($0, prefix) == 1' |
  tail -n +$((KEEP + 1)) |
  while IFS= read -r old; do
      [ -n "$old" ] && zfs destroy "$old"
  done
```

Make it executable and run it once interactively before adding it to cron:

```sh
chmod 755 /usr/local/sbin/zfs-encrypted-push
/usr/local/sbin/zfs-encrypted-push
```

The first run performs a full raw send. Later runs use the newest destination snapshot as the incremental base. `-i` sends only the new endpoint snapshot; use `-I` only when you intentionally want every intermediate snapshot included.

The backup jail should run its own retention job. For example:

```sh
#!/bin/sh
set -eu

DST="zroot/bastille/jails/zback/root/data/encrypt"
KEEP=30

zfs list -H -t snapshot -o name -S creation -r "$DST" |
  awk -v prefix="${DST}@" 'index($0, prefix) == 1' |
  tail -n +$((KEEP + 1)) |
  while IFS= read -r old; do
      [ -n "$old" ] && zfs destroy "$old"
  done
```

Keep enough snapshots on both systems to preserve at least one common incremental base.

## 6. Pull backups from `zback`

Pull mode lets the backup jail control scheduling, but it requires `zback` to initiate an SSH connection to `zhost`. If `zhost` is behind NAT, provide a VPN, port forward, or another reachable path. A host that has only outbound connectivity is normally better suited to push mode.

### Restricted source wrapper

Install this as `/usr/local/sbin/zfs-raw-source` inside `zhost`:

```sh
#!/bin/sh
set -eu

SRC="zroot/bastille/jails/zhost/root/data/encrypt"
set -f
set -- ${SSH_ORIGINAL_COMMAND-}

valid_snapshot()
{
    case "$1" in
        backup_[0-9A-Za-z_.:-]*) ;;
        *) return 1 ;;
    esac
    case "$1" in
        *[!0-9A-Za-z_.:-]*) return 1 ;;
    esac
}

case "${1-}" in
    latest)
        [ "$#" -eq 1 ] || exit 64
        zfs list -H -t snapshot -o name -S creation -r "$SRC" |
          awk -v prefix="${SRC}@" 'index($0, prefix) == 1 { print; exit }'
        ;;
    send)
        if [ "$#" -eq 2 ] && valid_snapshot "$2"; then
            exec zfs send -w "${SRC}@$2"
        elif [ "$#" -eq 3 ] && valid_snapshot "$2" && valid_snapshot "$3"; then
            exec zfs send -w -i "${SRC}@$2" "${SRC}@$3"
        fi
        exit 64
        ;;
    *)
        exit 64
        ;;
esac
```

Make it root-owned and executable, then associate `zback`'s public key with it in `zhost`'s `/root/.ssh/authorized_keys`:

```text
command="/usr/local/sbin/zfs-raw-source",restrict ssh-ed25519 AAAA... zback-pull
```

### Snapshot creation on `zhost`

Run this from cron in `zhost` before the pull schedule:

```sh
#!/bin/sh
set -eu
SRC="zroot/bastille/jails/zhost/root/data/encrypt"
zfs snapshot "${SRC}@backup_$(date -u +%Y%m%dT%H%M%SZ)"
```

### Pull script on `zback`

```sh
#!/bin/sh
set -eu
set -o pipefail

SRC="zroot/bastille/jails/zhost/root/data/encrypt"
DST="zroot/bastille/jails/zback/root/data/encrypt"
REMOTE="root@192.168.3.61"

SOURCE_LATEST=$(ssh "$REMOTE" latest)
[ -n "$SOURCE_LATEST" ] || { echo "No source snapshots" >&2; exit 1; }

case "$SOURCE_LATEST" in
    "${SRC}@"backup_*) ;;
    *) echo "Unexpected source snapshot: $SOURCE_LATEST" >&2; exit 1 ;;
esac

LATEST_NAME=${SOURCE_LATEST#*@}
if zfs list -H -t snapshot "${DST}@${LATEST_NAME}" >/dev/null 2>&1; then
    echo "${DST}@${LATEST_NAME} already exists"
    exit 0
fi

if zfs list -H -o name "$DST" >/dev/null 2>&1; then
    DEST_LATEST=$(
      { zfs list -H -t snapshot -o name -S creation -r "$DST" 2>/dev/null || true; } |
        awk -v prefix="${DST}@" 'index($0, prefix) == 1 { print; exit }'
    )
else
    DEST_LATEST=""
fi

if [ -n "$DEST_LATEST" ]; then
    BASE_NAME=${DEST_LATEST#*@}
    ssh "$REMOTE" send "$BASE_NAME" "$LATEST_NAME" | zfs receive -u "$DST"
else
    ssh "$REMOTE" send "$LATEST_NAME" | zfs receive -u "$DST"
fi
```

If the source has already pruned the destination's newest snapshot, the incremental send fails safely. Do not use `zfs receive -F` automatically; investigate the divergence or start a new full-backup dataset.

## 7. Restore on a trusted system

The restore destination must not already exist for a full stream. The backup can raw-send the snapshot without loading its key:

```sh
RESTORE="tank/restore/encrypted"

# Confirm that RESTORE does not exist, then receive the raw stream.
zfs list "$RESTORE" >/dev/null 2>&1 && {
  echo "$RESTORE already exists" >&2
  exit 1
}

ssh root@192.168.3.62 send backup_20260903T120000Z |
  zfs receive -u "$RESTORE"
```

The raw stream preserves `encryption`, `keyformat`, and the wrapped master key. Its received `keylocation` normally defaults to `prompt`. Load the original key on the trusted system.

For a raw key file:

```sh
zfs set keylocation=file:///root/keys/data-encrypted.key "$RESTORE"
zfs load-key "$RESTORE"
```

For a passphrase:

```sh
zfs set keylocation=prompt "$RESTORE"
zfs load-key "$RESTORE"
```

Finally set an appropriate mount point and mount it:

```sh
zfs set mountpoint=/restore/encrypted "$RESTORE"
zfs mount "$RESTORE"
ls /restore/encrypted
```

Test restoration before relying on the backup, and periodically repeat the test on a clean trusted system.

## 8. Key management

- Keep an offline copy of the actual key or passphrase, separate from the backup pool.
- Protect key files with restrictive ownership and permissions and store them on an encrypted system volume.
- Do not place keys in command-line arguments; process listings and logs may expose them.
- For HTTPS key services, validate TLS certificates and restrict which clients can fetch each key.
- To rotate the user key, keep the old key loaded and run `zfs change-key` with the new key material. Merely replacing a file or HTTP response makes the existing wrapped key inaccessible.
- Losing the only user key makes the encrypted dataset unrecoverable. A weak passphrase may still be vulnerable to offline guessing.

## 9. Verification and monitoring

On `zback`, an unloaded raw-received dataset should report `keystatus=unavailable`:

```sh
zfs get encryption,encryptionroot,keyformat,keylocation,keystatus \
  zroot/bastille/jails/zback/root/data/encrypt
```

Attempting to mount it without the key should fail:

```sh
zfs mount zroot/bastille/jails/zback/root/data/encrypt
```

That failure demonstrates only that no usable key is currently loaded. The real controls are keeping the key off the backup system and testing that the received dataset remains encrypted.

List snapshots with numeric creation times for monitoring:

```sh
zfs list -H -p -t snapshot -o name,creation -S creation -r \
  zroot/bastille/jails/zback/root/data/encrypt
```

Estimate an incremental raw-send size without producing a stream:

```sh
zfs send -nPvw -i \
  zroot/bastille/jails/zhost/root/data/encrypt@backup_old \
  zroot/bastille/jails/zhost/root/data/encrypt@backup_new
```

Alert on command failure, stale snapshots, low pool capacity, and ZFS pool health. Check exit status rather than treating the presence of a snapshot name as proof that a transfer completed.

## Common pitfalls

| Mistake | Consequence | Correction |
|---|---|---|
| Omitting `-w` | The source sends a plaintext stream and needs its key loaded | Always use `-w` for this workflow |
| Pre-creating the raw receive target | A full receive cannot create the intended dataset | Receive into a nonexistent child dataset |
| Mixing raw and non-raw history | Later raw incremental receives can fail because IV sets differ | Use raw sends consistently |
| Losing the common snapshot | Incremental send has no valid base | Retain overlapping snapshots or start a new full destination |
| Putting both jails on one pool | Host or pool loss destroys both copies | Use a second physical or virtual host and pool |
| Assuming encryption hides all metadata | Dataset names, snapshot names, properties, and usage remain visible | Avoid sensitive names and document the threat model |
| Treating key omission as deletion protection | The backup administrator can still destroy ciphertext | Add separate retention, snapshots, or immutable/offline copies |

## Result

With raw sends used consistently, `zback` stores encrypted blocks and can replicate them without a loaded key. The backup remains confidential as long as the original key or passphrase is strong and never reaches the backup system. Availability and deletion resistance require separate controls; ZFS encryption alone provides neither.
