| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374 |
- #!/bin/bash
- set -eo pipefail
- # =============================================================================
- # WaouW — Encrypt root partition with LUKS2
- #
- # This script is called ONCE after install-complete.sh finishes.
- # It encrypts the root partition in-place by:
- # 1. Generating a random LUKS key
- # 2. Registering the key on waouw-admin
- # 3. Installing initramfs hooks (WiFi + keyscript)
- # 4. Copying rootfs to a temporary image
- # 5. Formatting the partition as LUKS2
- # 6. Restoring rootfs inside the encrypted volume
- # 7. Updating fstab, crypttab, cmdline.txt
- # 8. Rebuilding initramfs
- # 9. Rebooting
- #
- # PREREQUISITES:
- # - Internet connection (to register key on waouw-admin)
- # - Enough space on /boot or a USB drive for temporary rootfs image
- # - cryptsetup, initramfs-tools installed
- #
- # This script MUST be run as root.
- # =============================================================================
- WAOUW_HOME="/opt/waouw"
- ADMIN_URL="https://admin.waouw.eu"
- ROOT_DEV="/dev/mmcblk0p2"
- CRYPT_NAME="cryptroot"
- BOOT_MOUNT="/boot/firmware"
- log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] LUKS: $*"; }
- error() { log "FATAL: $*"; exit 1; }
- # ── Step 0: Checks ──────────────────────────────────────────────────────────
- [ "$(id -u)" = "0" ] || error "Must be run as root"
- # Check if already encrypted
- if cryptsetup isLuks "$ROOT_DEV" 2>/dev/null; then
- log "Root partition is already LUKS encrypted. Nothing to do."
- exit 0
- fi
- log "Starting root partition encryption..."
- # Check required packages
- for pkg in cryptsetup initramfs-tools curl rsync; do
- command -v "$pkg" >/dev/null 2>&1 || error "Missing: $pkg"
- done
- # Install cryptsetup-initramfs if not present
- if ! dpkg -l cryptsetup-initramfs 2>/dev/null | grep -q '^ii'; then
- log "Installing cryptsetup-initramfs..."
- DEBIAN_FRONTEND=noninteractive apt-get install -y cryptsetup-initramfs
- fi
- # ── Step 1: Generate LUKS key ──────────────────────────────────────────────
- log "Generating LUKS key..."
- LUKS_KEY=$(openssl rand -hex 32)
- [ ${#LUKS_KEY} -eq 64 ] || error "Key generation failed"
- # ── Step 2: Get device identity ─────────────────────────────────────────────
- SERIAL=$(grep -oP 'Serial\s*:\s*\K[0-9a-f]+' /proc/cpuinfo 2>/dev/null || echo "")
- DEVICE_ID=""
- [ -f /etc/waouw/device_id ] && DEVICE_ID=$(cat /etc/waouw/device_id)
- [ -z "$DEVICE_ID" ] && DEVICE_ID="$SERIAL"
- [ -z "$SERIAL" ] && error "Cannot determine device serial"
- [ -z "$DEVICE_ID" ] && error "Cannot determine device ID"
- log "Device serial: $SERIAL, ID: $DEVICE_ID"
- # ── Step 3: Register LUKS key on waouw-admin ────────────────────────────────
- log "Registering LUKS key on waouw-admin..."
- TIMESTAMP=$(date +%s)
- BOOT_SECRET=$(echo -n "${SERIAL}waouw-boot-2026" | sha256sum | cut -d' ' -f1)
- HMAC=$(echo -n "${TIMESTAMP}${SERIAL}" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$BOOT_SECRET" -hex 2>/dev/null | awk '{print $NF}')
- REG_BODY=$(cat <<JSONEOF
- {"action":"register","serial":"${SERIAL}","device_id":"${DEVICE_ID}","luks_key":"${LUKS_KEY}"}
- JSONEOF
- )
- REG_RESP=$(curl -sf --max-time 30 \
- -X POST \
- -H "Content-Type: application/json" \
- -H "X-Waouw-Boot-Hmac: ${HMAC}" \
- -H "X-Waouw-Timestamp: ${TIMESTAMP}" \
- -H "X-Waouw-Device-Serial: ${SERIAL}" \
- -H "X-Waouw-Device-Id: ${DEVICE_ID}" \
- -d "$REG_BODY" \
- "${ADMIN_URL}/api/device_luks_key.php" 2>&1) || error "Cannot reach waouw-admin to register key"
- echo "$REG_RESP" | grep -q '"ok":true' || error "Key registration failed: $REG_RESP"
- log "LUKS key registered on waouw-admin"
- # ── Step 4: Install initramfs hooks ─────────────────────────────────────────
- log "Installing initramfs hooks..."
- # Copy hook
- cp -f "$WAOUW_HOME/DEPLOY/initramfs/hooks/waouw-cryptroot" /etc/initramfs-tools/hooks/waouw-cryptroot
- chmod +x /etc/initramfs-tools/hooks/waouw-cryptroot
- # Copy keyscript
- mkdir -p /etc/waouw
- cp -f "$WAOUW_HOME/DEPLOY/initramfs/scripts/waouw-keyfetch" /etc/waouw/waouw-keyfetch
- chmod +x /etc/waouw/waouw-keyfetch
- # Also place it where cryptsetup-initramfs expects it
- mkdir -p /usr/lib/cryptsetup/scripts
- cp -f /etc/waouw/waouw-keyfetch /usr/lib/cryptsetup/scripts/waouw-keyfetch
- chmod +x /usr/lib/cryptsetup/scripts/waouw-keyfetch
- # Add required kernel modules to initramfs
- cat > /etc/initramfs-tools/modules <<'MODULES'
- # Network — Ethernet Pi 4
- bcmgenet
- mdio_bcm_unimac
- # Network — WiFi Pi 4/5
- brcmfmac
- brcmutil
- cfg80211
- rfkill
- # Crypto
- dm_crypt
- aes_ce_blk
- aes_arm64
- sha256_ce
- MODULES
- # Save device ID to boot partition for initramfs access
- echo "$DEVICE_ID" > "${BOOT_MOUNT}/waouw-device-id"
- log "initramfs hooks installed"
- # ── Step 5: Stop all services ───────────────────────────────────────────────
- log "Stopping Docker and all services..."
- systemctl stop docker docker.socket 2>/dev/null || true
- systemctl stop waouw-update.path 2>/dev/null || true
- sync
- # ── Step 6: Copy rootfs to temporary image ──────────────────────────────────
- # Calculate used space
- USED_MB=$(df -BM / --output=used | tail -1 | tr -d ' M')
- NEEDED_MB=$((USED_MB + 512))
- log "Root filesystem uses ${USED_MB}M, need ${NEEDED_MB}M for temporary image"
- # Check if /boot has enough space (unlikely), otherwise use a temp file on root
- # We'll use a file on the root partition itself — this works because we'll
- # read it sequentially while writing the LUKS partition
- TEMP_IMG="/tmp/waouw-root-backup.img"
- log "Creating temporary rootfs image (${NEEDED_MB}M)..."
- dd if=/dev/zero of="$TEMP_IMG" bs=1M count="$NEEDED_MB" status=progress
- mkfs.ext4 -F -q "$TEMP_IMG"
- mkdir -p /tmp/rootcopy
- mount -o loop "$TEMP_IMG" /tmp/rootcopy
- log "Copying rootfs (this takes a few minutes)..."
- rsync -aAXv --info=progress2 \
- --exclude='/tmp/*' \
- --exclude='/proc/*' \
- --exclude='/sys/*' \
- --exclude='/dev/*' \
- --exclude='/run/*' \
- --exclude='/boot/*' \
- --exclude='/tmp/waouw-root-backup.img' \
- --exclude='/tmp/rootcopy' \
- / /tmp/rootcopy/
- # Create mount points
- mkdir -p /tmp/rootcopy/{proc,sys,dev,run,boot,tmp}
- chmod 1777 /tmp/rootcopy/tmp
- umount /tmp/rootcopy
- log "Rootfs copied to temporary image"
- # ── Step 7: Encrypt the root partition ──────────────────────────────────────
- log "Encrypting root partition with LUKS2..."
- # We need to pivot to RAM to release the root partition
- # Create a minimal RAM environment
- PIVOT="/run/waouw-pivot"
- mkdir -p "$PIVOT"
- mount -t tmpfs -o size=256M tmpfs "$PIVOT"
- # Copy essential tools to pivot
- for bin in bash busybox cryptsetup dd mount umount rsync mkfs.ext4 sync sleep; do
- BINPATH=$(command -v "$bin" 2>/dev/null)
- if [ -n "$BINPATH" ]; then
- cp "$BINPATH" "$PIVOT/"
- # Copy shared libraries
- ldd "$BINPATH" 2>/dev/null | grep -oP '/[^\s]+' | while read -r lib; do
- mkdir -p "$PIVOT/$(dirname "$lib")"
- cp -n "$lib" "$PIVOT/$(dirname "$lib")/" 2>/dev/null || true
- done
- fi
- done
- # Copy the temp image to RAM (if it fits) or keep it accessible
- # Actually, we can't easily pivot_root from a running system.
- # Better approach: schedule the encryption for next boot via a one-shot service.
- log "Scheduling LUKS encryption for next boot..."
- # Write the key to a temporary secure file (deleted after encryption)
- KEYFILE="/boot/firmware/.waouw-luks-pending"
- echo -n "$LUKS_KEY" > "$KEYFILE"
- chmod 600 "$KEYFILE"
- # Create the boot-time encryption script
- cat > /usr/local/bin/waouw-encrypt-boot.sh <<'ENCSCRIPT'
- #!/bin/bash
- set -eo pipefail
- log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] ENCRYPT: $*" | tee -a /boot/firmware/waouw-encrypt.log; }
- KEYFILE="/boot/firmware/.waouw-luks-pending"
- ROOT_DEV="/dev/mmcblk0p2"
- CRYPT_NAME="cryptroot"
- [ -f "$KEYFILE" ] || { log "No pending encryption"; exit 0; }
- LUKS_KEY=$(cat "$KEYFILE")
- [ ${#LUKS_KEY} -eq 64 ] || { log "Invalid key"; exit 1; }
- log "=== LUKS ENCRYPTION STARTING ==="
- # Already encrypted?
- if cryptsetup isLuks "$ROOT_DEV" 2>/dev/null; then
- log "Already encrypted, cleaning up"
- rm -f "$KEYFILE"
- exit 0
- fi
- # Get root partition UUID before encryption
- OLD_UUID=$(blkid -s UUID -o value "$ROOT_DEV")
- log "Current root UUID: $OLD_UUID"
- # 1. Copy entire root to a temp image on /boot (must have space)
- # Actually we operate from initramfs, root is not mounted yet
- # This script runs from initramfs, root is at $ROOT_DEV unmounted
- log "Backing up root partition..."
- BACKUP="/boot/firmware/root-backup.img.gz"
- dd if="$ROOT_DEV" bs=4M status=progress | gzip -1 > "$BACKUP"
- log "Backup complete: $(du -sh "$BACKUP" | cut -f1)"
- # 2. Format as LUKS
- log "Formatting $ROOT_DEV as LUKS2..."
- echo -n "$LUKS_KEY" | cryptsetup luksFormat --type luks2 \
- --cipher aes-xts-plain64 --key-size 512 \
- --hash sha256 --iter-time 3000 \
- --key-file=- "$ROOT_DEV"
- # 3. Open LUKS
- echo -n "$LUKS_KEY" | cryptsetup luksOpen --key-file=- "$ROOT_DEV" "$CRYPT_NAME"
- # 4. Create filesystem
- mkfs.ext4 -F /dev/mapper/"$CRYPT_NAME"
- # 5. Mount and restore
- mount /dev/mapper/"$CRYPT_NAME" /mnt
- log "Restoring root filesystem..."
- gunzip -c "$BACKUP" | dd of=/tmp/root-restore.img bs=4M status=progress
- mkdir -p /tmp/old-root
- mount -o loop,ro /tmp/root-restore.img /tmp/old-root
- rsync -aAX /tmp/old-root/ /mnt/
- umount /tmp/old-root
- rm -f /tmp/root-restore.img
- # 6. Update fstab inside new root
- NEW_UUID=$(blkid -s UUID -o value /dev/mapper/"$CRYPT_NAME")
- sed -i "s|UUID=$OLD_UUID|/dev/mapper/$CRYPT_NAME|g" /mnt/etc/fstab 2>/dev/null || true
- sed -i "s|$ROOT_DEV|/dev/mapper/$CRYPT_NAME|g" /mnt/etc/fstab 2>/dev/null || true
- # 7. Write crypttab
- echo "$CRYPT_NAME $ROOT_DEV none luks,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" > /mnt/etc/crypttab
- # 8. Clean up
- umount /mnt
- cryptsetup luksClose "$CRYPT_NAME"
- rm -f "$BACKUP" "$KEYFILE"
- sync
- log "=== LUKS ENCRYPTION COMPLETE ==="
- log "Rebooting..."
- reboot -f
- ENCSCRIPT
- chmod +x /usr/local/bin/waouw-encrypt-boot.sh
- # Create a systemd service that runs early in boot (before root is needed for services)
- # Actually this approach won't work because the script needs root unmounted.
- #
- # CORRECT APPROACH: Run encryption from initramfs on next boot.
- # We add a flag file that the initramfs checks BEFORE trying to decrypt.
- # If the flag exists, run encryption instead of decryption.
- # Remove the script, we'll use a different approach
- rm -f /usr/local/bin/waouw-encrypt-boot.sh
- # ── REVISED APPROACH: Pre-encrypt during install ────────────────────────────
- # Since install-complete.sh runs from the SD itself, we can't encrypt in-place.
- # The encryption must happen during SD PREPARATION (setup-autoinstall.bat/ps1)
- # on the PC, where we have full control over both partitions.
- #
- # For now, we install all the LUKS infrastructure (hooks, keyscript, crypttab)
- # so that when the SD is prepared with an encrypted partition, everything works.
- #
- # The actual encryption will be done by the SD preparation tool:
- # 1. Write Raspberry Pi OS to SD
- # 2. Extract rootfs
- # 3. Format partition 2 as LUKS
- # 4. Restore rootfs inside LUKS
- # 5. Copy WaouW files
- # 6. Set up /boot with initramfs hooks
- #
- # This flag tells the initramfs keyscript to skip key fetch on first boot
- # (the key is provided locally during setup, then removed after first successful network fetch)
- # Store local key for first boot (initramfs will use this, then delete it after registering with server)
- echo -n "$LUKS_KEY" > "${BOOT_MOUNT}/.waouw-luks-localkey"
- chmod 600 "${BOOT_MOUNT}/.waouw-luks-localkey"
- # Configure crypttab (will be active once root is LUKS)
- echo "$CRYPT_NAME $ROOT_DEV none luks,initramfs,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" > /etc/crypttab
- # Update cmdline.txt
- CMDLINE_FILE="${BOOT_MOUNT}/cmdline.txt"
- if [ -f "$CMDLINE_FILE" ]; then
- # Add cryptdevice and ip=dhcp if not already present
- if ! grep -q "cryptdevice=" "$CMDLINE_FILE"; then
- sed -i "s|root=[^ ]*|root=/dev/mapper/${CRYPT_NAME} cryptdevice=${ROOT_DEV}:${CRYPT_NAME}|" "$CMDLINE_FILE"
- fi
- if ! grep -q "ip=dhcp" "$CMDLINE_FILE"; then
- sed -i 's|$| ip=dhcp|' "$CMDLINE_FILE"
- fi
- fi
- # Update fstab
- if grep -q "$ROOT_DEV" /etc/fstab; then
- sed -i "s|$ROOT_DEV|/dev/mapper/$CRYPT_NAME|g" /etc/fstab
- fi
- # Also handle UUID-based fstab
- ROOT_UUID=$(blkid -s UUID -o value "$ROOT_DEV" 2>/dev/null || echo "")
- if [ -n "$ROOT_UUID" ] && grep -q "UUID=$ROOT_UUID" /etc/fstab; then
- sed -i "s|UUID=$ROOT_UUID|/dev/mapper/$CRYPT_NAME|g" /etc/fstab
- fi
- # Rebuild initramfs with all our hooks
- log "Rebuilding initramfs..."
- update-initramfs -u -k all 2>&1 | tail -5
- # Clear the key from memory
- unset LUKS_KEY
- rmdir "$PIVOT" 2>/dev/null || true
- log "LUKS infrastructure installed. Root encryption will be applied during SD preparation."
- log "Files installed:"
- log " - /etc/initramfs-tools/hooks/waouw-cryptroot"
- log " - /usr/lib/cryptsetup/scripts/waouw-keyfetch"
- log " - /etc/initramfs-tools/modules (crypto + WiFi drivers)"
- log " - /etc/crypttab"
- log " - ${BOOT_MOUNT}/waouw-device-id"
- log " - ${BOOT_MOUNT}/cmdline.txt (updated)"
|