#!/usr/bin/env bash
# ==============================================================================
# alfred-zfs-harden — Alfred Linux ZFS Physical-Seizure Hardening CLI (v2)
# Audits /etc/zfs/initramfs-tools-load-key & ALL /boot + /boot/efi initrd copies
# and migrates cleanly from unattended auto-boot to Zero-Key-on-Disk:
#   - Workstation / Laptop mode: Console passphrase prompt at boot
#   - Headless Server mode:      dropbear-initramfs pre-boot SSH unlock
#
# Honest Threat Model & OpenZFS Cryptographic Notes:
#   1. Dropbear / Console unlock protects against physical disk theft, seizure,
#      or disposal ("cold-disk extraction"). Because /boot and /boot/efi (ESP)
#      are unencrypted, it does NOT defeat an "evil maid" / malicious VPS host
#      with persistent write access to /boot or /boot/efi (that requires signed
#      UKI + Secure Boot + TPM2 PCR sealing).
#   2. Per OpenZFS man zfs-change-key(8): `zfs change-key` only re-wraps the
#      existing master key; old key-wrapping blocks can persist forensically on
#      disk. For true forensic master-key rotation after any plaintext keyfile
#      exposure, either reinstall cleanly in Zero-Key mode OR perform a non-raw
#      `zfs send | zfs recv` (without `-w`) into a new encrypted dataset, destroy
#      old datasets/snapshots, and run `zpool trim --secure` / `zpool initialize`.
# ==============================================================================
set -euo pipefail

KEYFILE="/etc/zfs/initramfs-tools-load-key"

detect_enc_root() {
  if ! command -v zfs >/dev/null 2>&1; then
    echo ""
    return 0
  fi
  local root_ds enc_root
  root_ds="$(findmnt -n -o SOURCE / 2>/dev/null || true)"
  if [ -n "$root_ds" ] && zfs list -H "$root_ds" >/dev/null 2>&1; then
    enc_root="$(zfs get -H -o value encryptionroot "$root_ds" 2>/dev/null || true)"
    if [ -n "$enc_root" ] && [ "$enc_root" != "-" ]; then
      echo "$enc_root"
      return 0
    fi
  fi
  # Fallback to first encrypted root pool if root_ds lookup failed
  zfs list -H -o name,encryptionroot 2>/dev/null | awk '$2 != "-" && $2 != "" {print $2; exit}'
}

usage() {
  cat <<'EOF'
Usage:
  alfred-zfs-harden status
      Audit /etc/zfs/initramfs-tools-load-key, ZFS encryptionroot, AND every
      initrd/initramfs image under /boot and /boot/efi (ESP).

  alfred-zfs-harden console [--yes]
      WORKSTATION / LAPTOP MODE (Zero-Key-on-Disk):
      Removes /etc/zfs/initramfs-tools-load-key, rebuilds initramfs, overwrites
      ALL /boot and /boot/efi initrd copies, runs fstrim on /boot and /boot/efi
      when supported, and verifies 0 plaintext ZFS keyfiles remain anywhere.

  alfred-zfs-harden dropbear --pubkey-file <path> [--ip <ip>::<gw>:<mask>:<host>:<iface>:off] [--port 2222] [--yes]
      HEADLESS DATACENTER / VPS MODE (Zero-Key-on-Disk + Remote SSH Unlock):
      PREREQUISITE: Confirm IPMI / KVM / provider rescue console access first!
      Installs & configures dropbear-initramfs locked strictly to the owner's
      SSH public key, verifies dropbear inside the rebuilt initramfs BEFORE
      removing the keyfile, overwrites ALL /boot and /boot/efi initrd copies,
      and verifies 0 plaintext ZFS keyfiles remain in /boot or /boot/efi.

IMPORTANT (OpenZFS Forensic Master-Key Note):
  `zfs change-key <encryptionroot>` ONLY re-wraps the existing master key and
  leaves old CoW wrapping metadata forensically recoverable (see man zfs-change-key).
  For full forensic key rotation after prior plaintext exposure in /boot or /boot/efi:
    1) Create a fresh encrypted dataset/pool (new master key) or clean Zero-Key install,
    2) Copy data via non-raw `zfs send | zfs recv` (NO `-w`), destroy old datasets &
       snapshots, and scrub free space with `zpool trim --secure` or `zpool initialize`.
EOF
}

require_root() {
  if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: Run as root (sudo alfred-zfs-harden ...)." >&2
    exit 1
  fi
}

find_all_initrds() {
  find /boot -maxdepth 4 \( -iname "initrd*" -o -iname "initramfs*" \) -type f 2>/dev/null | sort -u
}

scan_initrds() {
  local found=0
  local count=0
  while IFS= read -r img; do
    [ -f "$img" ] || continue
    count=$((count + 1))
    if lsinitramfs "$img" 2>/dev/null | grep -q "initramfs-tools-load-key"; then
      echo "  [EXPOSED_IN_INITRD] $img contains etc/zfs/initramfs-tools-load-key"
      found=1
    else
      echo "  [CLEAN_INITRD]      $img (0 ZFS keyfiles)"
    fi
  done < <(find_all_initrds)
  if [ "$count" -eq 0 ]; then
    echo "  [WARN] No initrd/initramfs images found under /boot or /boot/efi."
  fi
  return $found
}

cmd_status() {
  local enc_root
  enc_root="$(detect_enc_root)"
  echo "=== Alfred Linux ZFS Encryption & Physical-Seizure Audit ==="
  if [ -f "$KEYFILE" ]; then
    echo "  [KEYFILE]  PRESENT ($KEYFILE, perms=$(stat -c %a "$KEYFILE"), bytes=$(stat -c %s "$KEYFILE"))"
  else
    echo "  [KEYFILE]  ABSENT (Clean — no unattended ZFS keyfile in /etc/zfs)"
  fi
  if dpkg -s dropbear-initramfs >/dev/null 2>&1; then
    echo "  [DROPBEAR] INSTALLED (Remote pre-boot SSH unlock available)"
  else
    echo "  [DROPBEAR] NOT INSTALLED"
  fi
  if [ -n "$enc_root" ]; then
    echo "  [ENCROOT]  $enc_root ($(zfs get -H -o property,value encryption,keylocation,keyformat "$enc_root" 2>/dev/null | tr '\t' '=' | tr '\n' ' '))"
  else
    echo "  [ENCROOT]  NONE / UNENCRYPTED"
  fi
  echo "=== /boot & /boot/efi (ESP) Initramfs Scan ==="
  if scan_initrds; then
    echo "VERDICT: ZERO-KEY-ON-DISK VERIFIED (No plaintext ZFS keyfile in /boot or /boot/efi)."
    echo "NOTE:    Protects against cold-disk theft/seizure. Does not defend against live"
    echo "         boot-partition tampering ('evil maid' / malicious VPS host) without Secure Boot + TPM2."
  else
    echo "VERDICT: UNATTENDED AUTO-BOOT ACTIVE (Passphrase embedded in unencrypted /boot or /boot/efi initrd)."
    echo "         Verify IPMI/console access first, then run:"
    echo "           - Laptop/Desktop: sudo alfred-zfs-harden console"
    echo "           - Headless Server: sudo alfred-zfs-harden dropbear --pubkey-file ~/.ssh/id_ed25519.pub"
  fi
}

rebuild_and_sync_all_initrds() {
  echo "[*] Rebuilding initramfs images..."
  update-initramfs -u -k all
  local newest_initrd
  newest_initrd="$(ls -t /boot/initrd.img-* 2>/dev/null | head -n 1 || true)"
  if [ -n "$newest_initrd" ] && [ -f "$newest_initrd" ]; then
    # Overwrite ALL Alfred & UEFI ESP initrd locations so ZERO stale copies retain old keyfiles!
    local targets=(
      /boot/alfred-boot/initrd.img
      /boot/boot/alfred-boot/initrd.img
      /boot/efi/initrd.img
      /boot/efi/alfred-boot/initrd.img
    )
    # Also catch any other custom initrd*.img inside /boot/efi
    while IFS= read -r extra; do
      [ -f "$extra" ] && targets+=("$extra")
    done < <(find /boot/efi -maxdepth 4 \( -iname "initrd*" -o -iname "initramfs*" \) -type f 2>/dev/null | sort -u)

    local seen=" "
    for dst in "${targets[@]}"; do
      if [ -f "$dst" ] && [[ "$seen" != *" $dst "* ]]; then
        seen+="$dst "
        cp -f "$newest_initrd" "$dst"
        echo "  Overwrote initramfs -> $dst"
      fi
    done
  fi
  sync
  # Trim unallocated blocks on /boot and /boot/efi where SSD/NVMe supports discard
  for mp in /boot /boot/efi; do
    if mountpoint -q "$mp" 2>/dev/null; then
      fstrim "$mp" 2>/dev/null && echo "  Trimmed free blocks on $mp" || true
    fi
  done
}

print_post_key_guidance() {
  local enc_root="$1"
  echo ""
  echo "=== IMPORTANT: Post-Hardening Key & Forensic Guidance ==="
  echo "  Detected ZFS encryptionroot: ${enc_root:-UNKNOWN}"
  echo "  1. Operational passphrase update (ONLY after confirming clean /boot + /boot/efi above):"
  if [ -n "$enc_root" ]; then
    echo "       sudo zfs change-key ${enc_root}"
  else
    echo "       sudo zfs change-key <your-encryptionroot>"
  fi
  echo "  2. Forensic Master-Key Limitation (OpenZFS man zfs-change-key):"
  echo "     - 'rm' on ZFS does not overwrite CoW blocks or old snapshots (low risk inside encrypted root)."
  echo "     - 'zfs change-key' ONLY re-wraps the existing master key; prior wrapping blocks may remain"
  echo "       forensically recoverable if an adversary already holds the old passphrase + disk image."
  echo "     - For full forensic immunity: migrate via non-raw 'zfs send | zfs recv' (WITHOUT -w) into"
  echo "       a new encrypted dataset/pool (new master key), destroy old datasets & snapshots, and run"
  echo "       'zpool trim --secure' or 'zpool initialize' (or clean-reinstall in Zero-Key mode)."
}

cmd_console() {
  require_root
  local yes_flag="${1:-}"
  local enc_root
  enc_root="$(detect_enc_root)"
  if [ "$yes_flag" != "--yes" ]; then
    echo "WARNING: Removing unattended ZFS auto-unlock means this machine will prompt"
    echo "         for your ZFS passphrase on the local keyboard/console on EVERY reboot."
    echo "         Do NOT run 'console' mode on a headless remote server without KVM/IPMI!"
    read -r -p "Proceed with Zero-Key-on-Disk console hardening? [y/N] " ans
    [[ "$ans" =~ ^[Yy]$ ]] || { echo "Aborted."; exit 0; }
  fi
  rm -f "$KEYFILE"
  rm -rf /etc/zfs/initramfs-tools-load-key.d 2>/dev/null || true
  echo "[+] Removed $KEYFILE (note: ZFS is Copy-on-Write; old snapshots inside encrypted root are unaffected)"

  rebuild_and_sync_all_initrds

  echo "=== Post-Hardening Verification (/boot & /boot/efi) ==="
  if scan_initrds; then
    echo "[PASS] Zero plaintext ZFS keyfiles remain in /boot or /boot/efi!"
    print_post_key_guidance "$enc_root"
  else
    echo "[FAIL] An initrd under /boot or /boot/efi still contains initramfs-tools-load-key! Do NOT change key until resolved." >&2
    exit 1
  fi
}

cmd_dropbear() {
  require_root
  local pubkey="" ip_cfg="" port="2222" yes_flag=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --pubkey-file) pubkey="${2:-}"; shift 2 ;;
      --ip)          ip_cfg="${2:-}"; shift 2 ;;
      --port)        port="${2:-2222}"; shift 2 ;;
      --yes)         yes_flag="--yes"; shift ;;
      *) echo "Unknown argument: $1" >&2; usage; exit 1 ;;
    esac
  done
  if [ -z "$pubkey" ] || [ ! -s "$pubkey" ]; then
    echo "ERROR: --pubkey-file <path-to-owner-public-key.pub> is required." >&2
    exit 1
  fi
  if ! grep -qE '^(ssh-ed25519|ssh-rsa|ecdsa-sha2-)' "$pubkey"; then
    echo "ERROR: $pubkey does not look like a valid OpenSSH public key." >&2
    exit 1
  fi
  local enc_root
  enc_root="$(detect_enc_root)"
  if [ "$yes_flag" != "--yes" ]; then
    echo "SAFETY PREREQUISITE: Confirm you have working IPMI / KVM / rescue console access"
    echo "                     before rebooting, in case Dropbear network/IP config differs."
    echo "This will:"
    echo "  1. Install & configure dropbear-initramfs (SSH port $port, locked ONLY to $pubkey)"
    echo "  2. Verify dropbear builds cleanly into initramfs BEFORE removing $KEYFILE"
    echo "  3. Remove $KEYFILE, rebuild & overwrite ALL /boot and /boot/efi initrd copies"
    echo "  4. On future reboots, unlock remotely via: ssh -p $port root@<server-ip> -> zfsunlock"
    read -r -p "Confirm you have IPMI/console fallback and wish to proceed? [y/N] " ans
    [[ "$ans" =~ ^[Yy]$ ]] || { echo "Aborted."; exit 0; }
  fi

  export DEBIAN_FRONTEND=noninteractive
  apt-get update -qq
  apt-get install -y -qq dropbear-initramfs

  mkdir -p /etc/dropbear/initramfs
  cp -f "$pubkey" /etc/dropbear/initramfs/authorized_keys
  chmod 0600 /etc/dropbear/initramfs/authorized_keys

  cat > /etc/dropbear/initramfs/dropbear.conf <<EOF
DROPBEAR_OPTIONS="-I 300 -j -k -p ${port} -s -c /usr/share/initramfs-tools/zfsunlock"
EOF

  if [ -n "$ip_cfg" ]; then
    if grep -qE '^IP=' /etc/initramfs-tools/initramfs.conf; then
      sed -i -E "s|^IP=.*|IP=${ip_cfg}|" /etc/initramfs-tools/initramfs.conf
    else
      echo "IP=${ip_cfg}" >> /etc/initramfs-tools/initramfs.conf
    fi
  fi

  # Step 1: Verify dropbear actually compiles into initramfs BEFORE removing unattended keyfile!
  command -v dropbear >/dev/null 2>&1 || { echo "ERROR: dropbear binary missing; aborting BEFORE removing keyfile!" >&2; exit 1; }
  update-initramfs -u -k "$(uname -r)"
  local cur_initrd="/boot/initrd.img-$(uname -r)"
  if [ ! -f "$cur_initrd" ] || ! lsinitramfs "$cur_initrd" 2>/dev/null | grep -q "dropbear"; then
    echo "ERROR: dropbear not present in $cur_initrd — aborting BEFORE removing $KEYFILE!" >&2
    exit 1
  fi
  echo "[+] Verified dropbear present in $cur_initrd BEFORE removing $KEYFILE."

  # Step 2: Now remove keyfile and rebuild + overwrite EVERY /boot and /boot/efi initrd copy
  rm -f "$KEYFILE"
  rm -rf /etc/zfs/initramfs-tools-load-key.d 2>/dev/null || true
  rebuild_and_sync_all_initrds

  echo "=== Post-Hardening Verification (/boot & /boot/efi) ==="
  local dropbear_ok=1
  while IFS= read -r img; do
    [ -f "$img" ] || continue
    if ! lsinitramfs "$img" 2>/dev/null | grep -q "dropbear"; then
      echo "  [WARN_NO_DROPBEAR] $img does not contain dropbear!" >&2
      dropbear_ok=0
    fi
  done < <(find_all_initrds)
  if [ "$dropbear_ok" -eq 1 ]; then
    echo "[PASS] dropbear-initramfs verified inside ALL /boot and /boot/efi initrd images (port $port)."
  fi

  if scan_initrds; then
    echo "[PASS] Zero plaintext ZFS keyfiles remain in /boot or /boot/efi!"
    echo "       Test unlock on reboot via: ssh -p ${port} root@<your-server-ip> (with IPMI/console open)."
    print_post_key_guidance "$enc_root"
  else
    echo "[FAIL] An initrd under /boot or /boot/efi still contains initramfs-tools-load-key! Do NOT change key until resolved." >&2
    exit 1
  fi
}

case "${1:-}" in
  status)   cmd_status ;;
  console)  shift; cmd_console "${1:-}" ;;
  dropbear) shift; cmd_dropbear "$@" ;;
  *)        usage; exit 1 ;;
esac
