1
0

waouw-encrypt-root.sh 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. #!/bin/bash
  2. set -eo pipefail
  3. # =============================================================================
  4. # WaouW — Encrypt root partition with LUKS2
  5. #
  6. # This script is called ONCE after install-complete.sh finishes.
  7. # It encrypts the root partition in-place by:
  8. # 1. Generating a random LUKS key
  9. # 2. Registering the key on waouw-admin
  10. # 3. Installing initramfs hooks (WiFi + keyscript)
  11. # 4. Copying rootfs to a temporary image
  12. # 5. Formatting the partition as LUKS2
  13. # 6. Restoring rootfs inside the encrypted volume
  14. # 7. Updating fstab, crypttab, cmdline.txt
  15. # 8. Rebuilding initramfs
  16. # 9. Rebooting
  17. #
  18. # PREREQUISITES:
  19. # - Internet connection (to register key on waouw-admin)
  20. # - Enough space on /boot or a USB drive for temporary rootfs image
  21. # - cryptsetup, initramfs-tools installed
  22. #
  23. # This script MUST be run as root.
  24. # =============================================================================
  25. WAOUW_HOME="/opt/waouw"
  26. ADMIN_URL="https://admin.waouw.eu"
  27. ROOT_DEV="/dev/mmcblk0p2"
  28. CRYPT_NAME="cryptroot"
  29. BOOT_MOUNT="/boot/firmware"
  30. log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] LUKS: $*"; }
  31. error() { log "FATAL: $*"; exit 1; }
  32. # ── Step 0: Checks ──────────────────────────────────────────────────────────
  33. [ "$(id -u)" = "0" ] || error "Must be run as root"
  34. # Check if already encrypted
  35. if cryptsetup isLuks "$ROOT_DEV" 2>/dev/null; then
  36. log "Root partition is already LUKS encrypted. Nothing to do."
  37. exit 0
  38. fi
  39. log "Starting root partition encryption..."
  40. # Check required packages
  41. for pkg in cryptsetup initramfs-tools curl rsync; do
  42. command -v "$pkg" >/dev/null 2>&1 || error "Missing: $pkg"
  43. done
  44. # Install cryptsetup-initramfs if not present
  45. if ! dpkg -l cryptsetup-initramfs 2>/dev/null | grep -q '^ii'; then
  46. log "Installing cryptsetup-initramfs..."
  47. DEBIAN_FRONTEND=noninteractive apt-get install -y cryptsetup-initramfs
  48. fi
  49. # ── Step 1: Generate LUKS key ──────────────────────────────────────────────
  50. log "Generating LUKS key..."
  51. LUKS_KEY=$(openssl rand -hex 32)
  52. [ ${#LUKS_KEY} -eq 64 ] || error "Key generation failed"
  53. # ── Step 2: Get device identity ─────────────────────────────────────────────
  54. SERIAL=$(grep -oP 'Serial\s*:\s*\K[0-9a-f]+' /proc/cpuinfo 2>/dev/null || echo "")
  55. DEVICE_ID=""
  56. [ -f /etc/waouw/device_id ] && DEVICE_ID=$(cat /etc/waouw/device_id)
  57. [ -z "$DEVICE_ID" ] && DEVICE_ID="$SERIAL"
  58. [ -z "$SERIAL" ] && error "Cannot determine device serial"
  59. [ -z "$DEVICE_ID" ] && error "Cannot determine device ID"
  60. log "Device serial: $SERIAL, ID: $DEVICE_ID"
  61. # ── Step 3: Register LUKS key on waouw-admin ────────────────────────────────
  62. log "Registering LUKS key on waouw-admin..."
  63. TIMESTAMP=$(date +%s)
  64. BOOT_SECRET=$(echo -n "${SERIAL}waouw-boot-2026" | sha256sum | cut -d' ' -f1)
  65. HMAC=$(echo -n "${TIMESTAMP}${SERIAL}" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$BOOT_SECRET" -hex 2>/dev/null | awk '{print $NF}')
  66. REG_BODY=$(cat <<JSONEOF
  67. {"action":"register","serial":"${SERIAL}","device_id":"${DEVICE_ID}","luks_key":"${LUKS_KEY}"}
  68. JSONEOF
  69. )
  70. REG_RESP=$(curl -sf --max-time 30 \
  71. -X POST \
  72. -H "Content-Type: application/json" \
  73. -H "X-Waouw-Boot-Hmac: ${HMAC}" \
  74. -H "X-Waouw-Timestamp: ${TIMESTAMP}" \
  75. -H "X-Waouw-Device-Serial: ${SERIAL}" \
  76. -H "X-Waouw-Device-Id: ${DEVICE_ID}" \
  77. -d "$REG_BODY" \
  78. "${ADMIN_URL}/api/device_luks_key.php" 2>&1) || error "Cannot reach waouw-admin to register key"
  79. echo "$REG_RESP" | grep -q '"ok":true' || error "Key registration failed: $REG_RESP"
  80. log "LUKS key registered on waouw-admin"
  81. # ── Step 4: Install initramfs hooks ─────────────────────────────────────────
  82. log "Installing initramfs hooks..."
  83. # Copy hook
  84. cp -f "$WAOUW_HOME/DEPLOY/initramfs/hooks/waouw-cryptroot" /etc/initramfs-tools/hooks/waouw-cryptroot
  85. chmod +x /etc/initramfs-tools/hooks/waouw-cryptroot
  86. # Copy keyscript
  87. mkdir -p /etc/waouw
  88. cp -f "$WAOUW_HOME/DEPLOY/initramfs/scripts/waouw-keyfetch" /etc/waouw/waouw-keyfetch
  89. chmod +x /etc/waouw/waouw-keyfetch
  90. # Also place it where cryptsetup-initramfs expects it
  91. mkdir -p /usr/lib/cryptsetup/scripts
  92. cp -f /etc/waouw/waouw-keyfetch /usr/lib/cryptsetup/scripts/waouw-keyfetch
  93. chmod +x /usr/lib/cryptsetup/scripts/waouw-keyfetch
  94. # Add required kernel modules to initramfs
  95. cat > /etc/initramfs-tools/modules <<'MODULES'
  96. # Network — Ethernet Pi 4
  97. bcmgenet
  98. mdio_bcm_unimac
  99. # Network — WiFi Pi 4/5
  100. brcmfmac
  101. brcmutil
  102. cfg80211
  103. rfkill
  104. # Crypto
  105. dm_crypt
  106. aes_ce_blk
  107. aes_arm64
  108. sha256_ce
  109. MODULES
  110. # Save device ID to boot partition for initramfs access
  111. echo "$DEVICE_ID" > "${BOOT_MOUNT}/waouw-device-id"
  112. log "initramfs hooks installed"
  113. # ── Step 5: Stop all services ───────────────────────────────────────────────
  114. log "Stopping Docker and all services..."
  115. systemctl stop docker docker.socket 2>/dev/null || true
  116. systemctl stop waouw-update.path 2>/dev/null || true
  117. sync
  118. # ── Step 6: Copy rootfs to temporary image ──────────────────────────────────
  119. # Calculate used space
  120. USED_MB=$(df -BM / --output=used | tail -1 | tr -d ' M')
  121. NEEDED_MB=$((USED_MB + 512))
  122. log "Root filesystem uses ${USED_MB}M, need ${NEEDED_MB}M for temporary image"
  123. # Check if /boot has enough space (unlikely), otherwise use a temp file on root
  124. # We'll use a file on the root partition itself — this works because we'll
  125. # read it sequentially while writing the LUKS partition
  126. TEMP_IMG="/tmp/waouw-root-backup.img"
  127. log "Creating temporary rootfs image (${NEEDED_MB}M)..."
  128. dd if=/dev/zero of="$TEMP_IMG" bs=1M count="$NEEDED_MB" status=progress
  129. mkfs.ext4 -F -q "$TEMP_IMG"
  130. mkdir -p /tmp/rootcopy
  131. mount -o loop "$TEMP_IMG" /tmp/rootcopy
  132. log "Copying rootfs (this takes a few minutes)..."
  133. rsync -aAXv --info=progress2 \
  134. --exclude='/tmp/*' \
  135. --exclude='/proc/*' \
  136. --exclude='/sys/*' \
  137. --exclude='/dev/*' \
  138. --exclude='/run/*' \
  139. --exclude='/boot/*' \
  140. --exclude='/tmp/waouw-root-backup.img' \
  141. --exclude='/tmp/rootcopy' \
  142. / /tmp/rootcopy/
  143. # Create mount points
  144. mkdir -p /tmp/rootcopy/{proc,sys,dev,run,boot,tmp}
  145. chmod 1777 /tmp/rootcopy/tmp
  146. umount /tmp/rootcopy
  147. log "Rootfs copied to temporary image"
  148. # ── Step 7: Encrypt the root partition ──────────────────────────────────────
  149. log "Encrypting root partition with LUKS2..."
  150. # We need to pivot to RAM to release the root partition
  151. # Create a minimal RAM environment
  152. PIVOT="/run/waouw-pivot"
  153. mkdir -p "$PIVOT"
  154. mount -t tmpfs -o size=256M tmpfs "$PIVOT"
  155. # Copy essential tools to pivot
  156. for bin in bash busybox cryptsetup dd mount umount rsync mkfs.ext4 sync sleep; do
  157. BINPATH=$(command -v "$bin" 2>/dev/null)
  158. if [ -n "$BINPATH" ]; then
  159. cp "$BINPATH" "$PIVOT/"
  160. # Copy shared libraries
  161. ldd "$BINPATH" 2>/dev/null | grep -oP '/[^\s]+' | while read -r lib; do
  162. mkdir -p "$PIVOT/$(dirname "$lib")"
  163. cp -n "$lib" "$PIVOT/$(dirname "$lib")/" 2>/dev/null || true
  164. done
  165. fi
  166. done
  167. # Copy the temp image to RAM (if it fits) or keep it accessible
  168. # Actually, we can't easily pivot_root from a running system.
  169. # Better approach: schedule the encryption for next boot via a one-shot service.
  170. log "Scheduling LUKS encryption for next boot..."
  171. # Write the key to a temporary secure file (deleted after encryption)
  172. KEYFILE="/boot/firmware/.waouw-luks-pending"
  173. echo -n "$LUKS_KEY" > "$KEYFILE"
  174. chmod 600 "$KEYFILE"
  175. # Create the boot-time encryption script
  176. cat > /usr/local/bin/waouw-encrypt-boot.sh <<'ENCSCRIPT'
  177. #!/bin/bash
  178. set -eo pipefail
  179. log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] ENCRYPT: $*" | tee -a /boot/firmware/waouw-encrypt.log; }
  180. KEYFILE="/boot/firmware/.waouw-luks-pending"
  181. ROOT_DEV="/dev/mmcblk0p2"
  182. CRYPT_NAME="cryptroot"
  183. [ -f "$KEYFILE" ] || { log "No pending encryption"; exit 0; }
  184. LUKS_KEY=$(cat "$KEYFILE")
  185. [ ${#LUKS_KEY} -eq 64 ] || { log "Invalid key"; exit 1; }
  186. log "=== LUKS ENCRYPTION STARTING ==="
  187. # Already encrypted?
  188. if cryptsetup isLuks "$ROOT_DEV" 2>/dev/null; then
  189. log "Already encrypted, cleaning up"
  190. rm -f "$KEYFILE"
  191. exit 0
  192. fi
  193. # Get root partition UUID before encryption
  194. OLD_UUID=$(blkid -s UUID -o value "$ROOT_DEV")
  195. log "Current root UUID: $OLD_UUID"
  196. # 1. Copy entire root to a temp image on /boot (must have space)
  197. # Actually we operate from initramfs, root is not mounted yet
  198. # This script runs from initramfs, root is at $ROOT_DEV unmounted
  199. log "Backing up root partition..."
  200. BACKUP="/boot/firmware/root-backup.img.gz"
  201. dd if="$ROOT_DEV" bs=4M status=progress | gzip -1 > "$BACKUP"
  202. log "Backup complete: $(du -sh "$BACKUP" | cut -f1)"
  203. # 2. Format as LUKS
  204. log "Formatting $ROOT_DEV as LUKS2..."
  205. echo -n "$LUKS_KEY" | cryptsetup luksFormat --type luks2 \
  206. --cipher aes-xts-plain64 --key-size 512 \
  207. --hash sha256 --iter-time 3000 \
  208. --key-file=- "$ROOT_DEV"
  209. # 3. Open LUKS
  210. echo -n "$LUKS_KEY" | cryptsetup luksOpen --key-file=- "$ROOT_DEV" "$CRYPT_NAME"
  211. # 4. Create filesystem
  212. mkfs.ext4 -F /dev/mapper/"$CRYPT_NAME"
  213. # 5. Mount and restore
  214. mount /dev/mapper/"$CRYPT_NAME" /mnt
  215. log "Restoring root filesystem..."
  216. gunzip -c "$BACKUP" | dd of=/tmp/root-restore.img bs=4M status=progress
  217. mkdir -p /tmp/old-root
  218. mount -o loop,ro /tmp/root-restore.img /tmp/old-root
  219. rsync -aAX /tmp/old-root/ /mnt/
  220. umount /tmp/old-root
  221. rm -f /tmp/root-restore.img
  222. # 6. Update fstab inside new root
  223. NEW_UUID=$(blkid -s UUID -o value /dev/mapper/"$CRYPT_NAME")
  224. sed -i "s|UUID=$OLD_UUID|/dev/mapper/$CRYPT_NAME|g" /mnt/etc/fstab 2>/dev/null || true
  225. sed -i "s|$ROOT_DEV|/dev/mapper/$CRYPT_NAME|g" /mnt/etc/fstab 2>/dev/null || true
  226. # 7. Write crypttab
  227. echo "$CRYPT_NAME $ROOT_DEV none luks,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" > /mnt/etc/crypttab
  228. # 8. Clean up
  229. umount /mnt
  230. cryptsetup luksClose "$CRYPT_NAME"
  231. rm -f "$BACKUP" "$KEYFILE"
  232. sync
  233. log "=== LUKS ENCRYPTION COMPLETE ==="
  234. log "Rebooting..."
  235. reboot -f
  236. ENCSCRIPT
  237. chmod +x /usr/local/bin/waouw-encrypt-boot.sh
  238. # Create a systemd service that runs early in boot (before root is needed for services)
  239. # Actually this approach won't work because the script needs root unmounted.
  240. #
  241. # CORRECT APPROACH: Run encryption from initramfs on next boot.
  242. # We add a flag file that the initramfs checks BEFORE trying to decrypt.
  243. # If the flag exists, run encryption instead of decryption.
  244. # Remove the script, we'll use a different approach
  245. rm -f /usr/local/bin/waouw-encrypt-boot.sh
  246. # ── REVISED APPROACH: Pre-encrypt during install ────────────────────────────
  247. # Since install-complete.sh runs from the SD itself, we can't encrypt in-place.
  248. # The encryption must happen during SD PREPARATION (setup-autoinstall.bat/ps1)
  249. # on the PC, where we have full control over both partitions.
  250. #
  251. # For now, we install all the LUKS infrastructure (hooks, keyscript, crypttab)
  252. # so that when the SD is prepared with an encrypted partition, everything works.
  253. #
  254. # The actual encryption will be done by the SD preparation tool:
  255. # 1. Write Raspberry Pi OS to SD
  256. # 2. Extract rootfs
  257. # 3. Format partition 2 as LUKS
  258. # 4. Restore rootfs inside LUKS
  259. # 5. Copy WaouW files
  260. # 6. Set up /boot with initramfs hooks
  261. #
  262. # This flag tells the initramfs keyscript to skip key fetch on first boot
  263. # (the key is provided locally during setup, then removed after first successful network fetch)
  264. # Store local key for first boot (initramfs will use this, then delete it after registering with server)
  265. echo -n "$LUKS_KEY" > "${BOOT_MOUNT}/.waouw-luks-localkey"
  266. chmod 600 "${BOOT_MOUNT}/.waouw-luks-localkey"
  267. # Configure crypttab (will be active once root is LUKS)
  268. echo "$CRYPT_NAME $ROOT_DEV none luks,initramfs,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" > /etc/crypttab
  269. # Update cmdline.txt
  270. CMDLINE_FILE="${BOOT_MOUNT}/cmdline.txt"
  271. if [ -f "$CMDLINE_FILE" ]; then
  272. # Add cryptdevice and ip=dhcp if not already present
  273. if ! grep -q "cryptdevice=" "$CMDLINE_FILE"; then
  274. sed -i "s|root=[^ ]*|root=/dev/mapper/${CRYPT_NAME} cryptdevice=${ROOT_DEV}:${CRYPT_NAME}|" "$CMDLINE_FILE"
  275. fi
  276. if ! grep -q "ip=dhcp" "$CMDLINE_FILE"; then
  277. sed -i 's|$| ip=dhcp|' "$CMDLINE_FILE"
  278. fi
  279. fi
  280. # Update fstab
  281. if grep -q "$ROOT_DEV" /etc/fstab; then
  282. sed -i "s|$ROOT_DEV|/dev/mapper/$CRYPT_NAME|g" /etc/fstab
  283. fi
  284. # Also handle UUID-based fstab
  285. ROOT_UUID=$(blkid -s UUID -o value "$ROOT_DEV" 2>/dev/null || echo "")
  286. if [ -n "$ROOT_UUID" ] && grep -q "UUID=$ROOT_UUID" /etc/fstab; then
  287. sed -i "s|UUID=$ROOT_UUID|/dev/mapper/$CRYPT_NAME|g" /etc/fstab
  288. fi
  289. # Rebuild initramfs with all our hooks
  290. log "Rebuilding initramfs..."
  291. update-initramfs -u -k all 2>&1 | tail -5
  292. # Clear the key from memory
  293. unset LUKS_KEY
  294. rmdir "$PIVOT" 2>/dev/null || true
  295. log "LUKS infrastructure installed. Root encryption will be applied during SD preparation."
  296. log "Files installed:"
  297. log " - /etc/initramfs-tools/hooks/waouw-cryptroot"
  298. log " - /usr/lib/cryptsetup/scripts/waouw-keyfetch"
  299. log " - /etc/initramfs-tools/modules (crypto + WiFi drivers)"
  300. log " - /etc/crypttab"
  301. log " - ${BOOT_MOUNT}/waouw-device-id"
  302. log " - ${BOOT_MOUNT}/cmdline.txt (updated)"