vm-encrypt-sd.sh 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #!/bin/bash
  2. # =============================================================================
  3. # WaouW — Encrypt SD card rootfs partition from a Linux VM
  4. #
  5. # Run this script from a Linux VM (Ubuntu) where the SD card is mounted
  6. # via USB passthrough. The script:
  7. # 1. Identifies the SD card partitions
  8. # 2. Backs up the rootfs
  9. # 3. Formats the partition as LUKS2
  10. # 4. Restores the rootfs
  11. # 5. Updates fstab, crypttab, cmdline.txt
  12. # 6. Installs initramfs hooks inside the rootfs (for future boots)
  13. #
  14. # Usage: sudo ./vm-encrypt-sd.sh [device] [lot_key]
  15. # device: e.g. /dev/sdb (auto-detected if omitted)
  16. # lot_key: hex LUKS key (prompted if omitted)
  17. #
  18. # Prerequisites: cryptsetup, rsync
  19. # =============================================================================
  20. set -eo pipefail
  21. RED='\033[0;31m'
  22. GREEN='\033[0;32m'
  23. YELLOW='\033[1;33m'
  24. CYAN='\033[0;36m'
  25. NC='\033[0m'
  26. log() { echo -e "${CYAN}[LUKS]${NC} $*"; }
  27. ok() { echo -e "${GREEN}[OK]${NC} $*"; }
  28. warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
  29. error() { echo -e "${RED}[FATAL]${NC} $*"; exit 1; }
  30. [ "$(id -u)" = "0" ] || error "Ce script doit être lancé en root (sudo)"
  31. # ── Check prerequisites ─────────────────────────────────────────────────────
  32. for cmd in cryptsetup rsync lsblk mkfs.ext4 mount umount; do
  33. command -v "$cmd" >/dev/null 2>&1 || error "Commande manquante: $cmd (apt install cryptsetup)"
  34. done
  35. # ── Install cryptsetup if needed ────────────────────────────────────────────
  36. if ! command -v cryptsetup >/dev/null 2>&1; then
  37. log "Installation de cryptsetup..."
  38. apt-get update -qq && apt-get install -y cryptsetup
  39. fi
  40. # ── Identify SD card ────────────────────────────────────────────────────────
  41. SD_DEV="${1:-}"
  42. if [ -z "$SD_DEV" ]; then
  43. log "Recherche de la carte SD..."
  44. echo ""
  45. lsblk -o NAME,SIZE,TYPE,MODEL,MOUNTPOINT | grep -E "disk|part"
  46. echo ""
  47. # Try to auto-detect: look for a disk with 2 partitions, one FAT32
  48. for dev in /dev/sdb /dev/sdc /dev/sdd /dev/sde; do
  49. if [ -b "$dev" ] && [ -b "${dev}1" ] && [ -b "${dev}2" ]; then
  50. FS1=$(blkid -s TYPE -o value "${dev}1" 2>/dev/null || echo "")
  51. if [ "$FS1" = "vfat" ]; then
  52. SD_DEV="$dev"
  53. log "Carte SD détectée: $SD_DEV"
  54. break
  55. fi
  56. fi
  57. done
  58. if [ -z "$SD_DEV" ]; then
  59. read -p "Entrez le device de la SD (ex: /dev/sdb): " SD_DEV
  60. fi
  61. fi
  62. [ -b "$SD_DEV" ] || error "Device $SD_DEV introuvable"
  63. BOOT_PART="${SD_DEV}1"
  64. ROOT_PART="${SD_DEV}2"
  65. [ -b "$BOOT_PART" ] || error "Partition boot $BOOT_PART introuvable"
  66. [ -b "$ROOT_PART" ] || error "Partition root $ROOT_PART introuvable"
  67. # Check not already LUKS
  68. if cryptsetup isLuks "$ROOT_PART" 2>/dev/null; then
  69. ok "La partition $ROOT_PART est déjà chiffrée LUKS."
  70. exit 0
  71. fi
  72. BOOT_FS=$(blkid -s TYPE -o value "$BOOT_PART" 2>/dev/null || echo "?")
  73. ROOT_FS=$(blkid -s TYPE -o value "$ROOT_PART" 2>/dev/null || echo "?")
  74. ROOT_SIZE=$(lsblk -bno SIZE "$ROOT_PART" | head -1)
  75. ROOT_SIZE_GB=$(echo "scale=1; $ROOT_SIZE / 1073741824" | bc 2>/dev/null || echo "?")
  76. echo ""
  77. echo -e " ${CYAN}Carte SD:${NC} $SD_DEV"
  78. echo -e " ${CYAN}Partition boot:${NC} $BOOT_PART ($BOOT_FS)"
  79. echo -e " ${CYAN}Partition root:${NC} $ROOT_PART ($ROOT_FS, ${ROOT_SIZE_GB} GB)"
  80. echo ""
  81. [ "$ROOT_FS" = "ext4" ] || error "La partition root n'est pas ext4 ($ROOT_FS)"
  82. # ── LUKS key ────────────────────────────────────────────────────────────────
  83. LUKS_KEY="${2:-}"
  84. if [ -z "$LUKS_KEY" ]; then
  85. read -p "Clé LUKS (hex, 64 chars) ou 'generate' pour en créer une: " LUKS_KEY
  86. if [ "$LUKS_KEY" = "generate" ]; then
  87. LUKS_KEY=$(openssl rand -hex 32)
  88. log "Clé générée: $LUKS_KEY"
  89. fi
  90. fi
  91. [ ${#LUKS_KEY} -ge 32 ] || error "Clé LUKS trop courte (min 32 hex)"
  92. # ── Confirmation ────────────────────────────────────────────────────────────
  93. echo ""
  94. echo -e " ${RED}ATTENTION: La partition $ROOT_PART va être chiffrée.${NC}"
  95. echo -e " ${YELLOW}Les données seront préservées (backup + restore).${NC}"
  96. echo ""
  97. read -p " Continuer ? (oui/non): " CONFIRM
  98. [ "$CONFIRM" = "oui" ] || { log "Annulé."; exit 0; }
  99. # ── Step 1: Mount and backup rootfs ─────────────────────────────────────────
  100. log "Étape 1/7 — Montage et sauvegarde du rootfs..."
  101. mkdir -p /tmp/waouw-sd-root /tmp/waouw-sd-boot /tmp/waouw-sd-backup
  102. # Unmount if currently mounted
  103. umount "$ROOT_PART" 2>/dev/null || true
  104. umount "$BOOT_PART" 2>/dev/null || true
  105. mount -t ext4 -o ro "$ROOT_PART" /tmp/waouw-sd-root
  106. mount -t vfat "$BOOT_PART" /tmp/waouw-sd-boot
  107. USED_MB=$(df -BM /tmp/waouw-sd-root --output=used | tail -1 | tr -d ' M')
  108. log "Rootfs: ${USED_MB} MB utilisés"
  109. log "Copie du rootfs (peut prendre quelques minutes)..."
  110. rsync -aAX --info=progress2 \
  111. /tmp/waouw-sd-root/ /tmp/waouw-sd-backup/
  112. ok "Rootfs sauvegardé (${USED_MB} MB)"
  113. umount /tmp/waouw-sd-root
  114. # ── Step 2: Format as LUKS2 ────────────────────────────────────────────────
  115. log "Étape 2/7 — Formatage LUKS2..."
  116. echo -n "$LUKS_KEY" | cryptsetup luksFormat --type luks2 \
  117. --cipher aes-xts-plain64 --key-size 512 \
  118. --hash sha256 --iter-time 3000 \
  119. --batch-mode --key-file=- "$ROOT_PART"
  120. ok "Partition formatée en LUKS2"
  121. # ── Step 3: Open and create ext4 ───────────────────────────────────────────
  122. log "Étape 3/7 — Création du filesystem ext4..."
  123. echo -n "$LUKS_KEY" | cryptsetup luksOpen --key-file=- "$ROOT_PART" cryptroot
  124. mkfs.ext4 -F -q /dev/mapper/cryptroot
  125. ok "ext4 créé dans le volume LUKS"
  126. # ── Step 4: Restore rootfs ──────────────────────────────────────────────────
  127. log "Étape 4/7 — Restauration du rootfs..."
  128. mount /dev/mapper/cryptroot /tmp/waouw-sd-root
  129. rsync -aAX --info=progress2 \
  130. /tmp/waouw-sd-backup/ /tmp/waouw-sd-root/
  131. # Ensure mount points exist
  132. mkdir -p /tmp/waouw-sd-root/{proc,sys,dev,run,boot,tmp}
  133. chmod 1777 /tmp/waouw-sd-root/tmp
  134. ok "Rootfs restauré dans le volume LUKS"
  135. # ── Step 5: Update configs ──────────────────────────────────────────────────
  136. log "Étape 5/7 — Mise à jour des configurations..."
  137. CRYPT_NAME="cryptroot"
  138. # crypttab
  139. echo "$CRYPT_NAME $ROOT_PART none luks,initramfs,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" \
  140. > /tmp/waouw-sd-root/etc/crypttab
  141. ok "crypttab écrit"
  142. # fstab — replace root device
  143. ROOT_UUID=$(blkid -s UUID -o value "$ROOT_PART" 2>/dev/null || echo "")
  144. ROOT_PARTUUID=$(blkid -s PARTUUID -o value "$ROOT_PART" 2>/dev/null || echo "")
  145. sed -i "s|PARTUUID=[^ ]*|/dev/mapper/$CRYPT_NAME|" /tmp/waouw-sd-root/etc/fstab 2>/dev/null || true
  146. sed -i "s|$ROOT_PART|/dev/mapper/$CRYPT_NAME|g" /tmp/waouw-sd-root/etc/fstab 2>/dev/null || true
  147. if [ -n "$ROOT_UUID" ]; then
  148. sed -i "s|UUID=$ROOT_UUID|/dev/mapper/$CRYPT_NAME|g" /tmp/waouw-sd-root/etc/fstab 2>/dev/null || true
  149. fi
  150. ok "fstab mis à jour"
  151. # cmdline.txt on boot partition
  152. CMDLINE="/tmp/waouw-sd-boot/cmdline.txt"
  153. if [ -f "$CMDLINE" ]; then
  154. sed -i "s|root=[^ ]*|root=/dev/mapper/${CRYPT_NAME} cryptdevice=${ROOT_PART}:${CRYPT_NAME}|" "$CMDLINE"
  155. grep -q "ip=dhcp" "$CMDLINE" || sed -i 's|$| ip=dhcp|' "$CMDLINE"
  156. ok "cmdline.txt mis à jour"
  157. else
  158. warn "cmdline.txt non trouvé sur la partition boot"
  159. fi
  160. # ── Step 6: Save lot key locally for first boot ────────────────────────────
  161. log "Étape 6/7 — Sauvegarde de la clé locale pour le premier boot..."
  162. # The keyscript needs the lot_id OR a local key to unlock on first boot
  163. # Save the key temporarily on boot partition (will be deleted after re-keying)
  164. echo -n "$LUKS_KEY" > /tmp/waouw-sd-boot/.waouw-luks-localkey
  165. chmod 600 /tmp/waouw-sd-boot/.waouw-luks-localkey
  166. ok "Clé locale sauvée sur /boot"
  167. # ── Step 7: Cleanup ─────────────────────────────────────────────────────────
  168. log "Étape 7/7 — Nettoyage..."
  169. # Remove encrypt-pending flag (encryption is done)
  170. rm -f /tmp/waouw-sd-boot/.waouw-encrypt-pending
  171. umount /tmp/waouw-sd-root
  172. cryptsetup luksClose cryptroot
  173. umount /tmp/waouw-sd-boot
  174. rm -rf /tmp/waouw-sd-backup
  175. unset LUKS_KEY
  176. echo ""
  177. echo -e " ${GREEN}========================================${NC}"
  178. echo -e " ${GREEN} CHIFFREMENT LUKS TERMINÉ${NC}"
  179. echo -e " ${GREEN}========================================${NC}"
  180. echo ""
  181. echo -e " La partition rootfs de la SD est chiffrée."
  182. echo -e " Au premier boot, le Pi utilisera la clé locale"
  183. echo -e " (.waouw-luks-localkey sur /boot)."
  184. echo -e " Après le bootstrap, la clé sera remplacée par"
  185. echo -e " une clé unique enregistrée sur waouw-admin."
  186. echo ""
  187. echo -e " ${YELLOW}Conservez la clé LUKS en lieu sûr.${NC}"
  188. echo ""