#!/bin/bash # ============================================================================= # WaouW — Encrypt SD card rootfs partition from a Linux VM # # Run this script from a Linux VM (Ubuntu) where the SD card is mounted # via USB passthrough. The script: # 1. Identifies the SD card partitions # 2. Backs up the rootfs # 3. Formats the partition as LUKS2 # 4. Restores the rootfs # 5. Updates fstab, crypttab, cmdline.txt # 6. Installs initramfs hooks inside the rootfs (for future boots) # # Usage: sudo ./vm-encrypt-sd.sh [device] [lot_key] # device: e.g. /dev/sdb (auto-detected if omitted) # lot_key: hex LUKS key (prompted if omitted) # # Prerequisites: cryptsetup, rsync # ============================================================================= set -eo pipefail RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' CYAN='\033[0;36m' NC='\033[0m' log() { echo -e "${CYAN}[LUKS]${NC} $*"; } ok() { echo -e "${GREEN}[OK]${NC} $*"; } warn() { echo -e "${YELLOW}[WARN]${NC} $*"; } error() { echo -e "${RED}[FATAL]${NC} $*"; exit 1; } [ "$(id -u)" = "0" ] || error "Ce script doit être lancé en root (sudo)" # ── Check prerequisites ───────────────────────────────────────────────────── for cmd in cryptsetup rsync lsblk mkfs.ext4 mount umount; do command -v "$cmd" >/dev/null 2>&1 || error "Commande manquante: $cmd (apt install cryptsetup)" done # ── Install cryptsetup if needed ──────────────────────────────────────────── if ! command -v cryptsetup >/dev/null 2>&1; then log "Installation de cryptsetup..." apt-get update -qq && apt-get install -y cryptsetup fi # ── Identify SD card ──────────────────────────────────────────────────────── SD_DEV="${1:-}" if [ -z "$SD_DEV" ]; then log "Recherche de la carte SD..." echo "" lsblk -o NAME,SIZE,TYPE,MODEL,MOUNTPOINT | grep -E "disk|part" echo "" # Try to auto-detect: look for a disk with 2 partitions, one FAT32 for dev in /dev/sdb /dev/sdc /dev/sdd /dev/sde; do if [ -b "$dev" ] && [ -b "${dev}1" ] && [ -b "${dev}2" ]; then FS1=$(blkid -s TYPE -o value "${dev}1" 2>/dev/null || echo "") if [ "$FS1" = "vfat" ]; then SD_DEV="$dev" log "Carte SD détectée: $SD_DEV" break fi fi done if [ -z "$SD_DEV" ]; then read -p "Entrez le device de la SD (ex: /dev/sdb): " SD_DEV fi fi [ -b "$SD_DEV" ] || error "Device $SD_DEV introuvable" BOOT_PART="${SD_DEV}1" ROOT_PART="${SD_DEV}2" [ -b "$BOOT_PART" ] || error "Partition boot $BOOT_PART introuvable" [ -b "$ROOT_PART" ] || error "Partition root $ROOT_PART introuvable" # Check not already LUKS if cryptsetup isLuks "$ROOT_PART" 2>/dev/null; then ok "La partition $ROOT_PART est déjà chiffrée LUKS." exit 0 fi BOOT_FS=$(blkid -s TYPE -o value "$BOOT_PART" 2>/dev/null || echo "?") ROOT_FS=$(blkid -s TYPE -o value "$ROOT_PART" 2>/dev/null || echo "?") ROOT_SIZE=$(lsblk -bno SIZE "$ROOT_PART" | head -1) ROOT_SIZE_GB=$(echo "scale=1; $ROOT_SIZE / 1073741824" | bc 2>/dev/null || echo "?") echo "" echo -e " ${CYAN}Carte SD:${NC} $SD_DEV" echo -e " ${CYAN}Partition boot:${NC} $BOOT_PART ($BOOT_FS)" echo -e " ${CYAN}Partition root:${NC} $ROOT_PART ($ROOT_FS, ${ROOT_SIZE_GB} GB)" echo "" [ "$ROOT_FS" = "ext4" ] || error "La partition root n'est pas ext4 ($ROOT_FS)" # ── LUKS key ──────────────────────────────────────────────────────────────── LUKS_KEY="${2:-}" if [ -z "$LUKS_KEY" ]; then read -p "Clé LUKS (hex, 64 chars) ou 'generate' pour en créer une: " LUKS_KEY if [ "$LUKS_KEY" = "generate" ]; then LUKS_KEY=$(openssl rand -hex 32) log "Clé générée: $LUKS_KEY" fi fi [ ${#LUKS_KEY} -ge 32 ] || error "Clé LUKS trop courte (min 32 hex)" # ── Confirmation ──────────────────────────────────────────────────────────── echo "" echo -e " ${RED}ATTENTION: La partition $ROOT_PART va être chiffrée.${NC}" echo -e " ${YELLOW}Les données seront préservées (backup + restore).${NC}" echo "" read -p " Continuer ? (oui/non): " CONFIRM [ "$CONFIRM" = "oui" ] || { log "Annulé."; exit 0; } # ── Step 1: Mount and backup rootfs ───────────────────────────────────────── log "Étape 1/7 — Montage et sauvegarde du rootfs..." mkdir -p /tmp/waouw-sd-root /tmp/waouw-sd-boot /tmp/waouw-sd-backup # Unmount if currently mounted umount "$ROOT_PART" 2>/dev/null || true umount "$BOOT_PART" 2>/dev/null || true mount -t ext4 -o ro "$ROOT_PART" /tmp/waouw-sd-root mount -t vfat "$BOOT_PART" /tmp/waouw-sd-boot USED_MB=$(df -BM /tmp/waouw-sd-root --output=used | tail -1 | tr -d ' M') log "Rootfs: ${USED_MB} MB utilisés" log "Copie du rootfs (peut prendre quelques minutes)..." rsync -aAX --info=progress2 \ /tmp/waouw-sd-root/ /tmp/waouw-sd-backup/ ok "Rootfs sauvegardé (${USED_MB} MB)" umount /tmp/waouw-sd-root # ── Step 2: Format as LUKS2 ──────────────────────────────────────────────── log "Étape 2/7 — Formatage LUKS2..." echo -n "$LUKS_KEY" | cryptsetup luksFormat --type luks2 \ --cipher aes-xts-plain64 --key-size 512 \ --hash sha256 --iter-time 3000 \ --batch-mode --key-file=- "$ROOT_PART" ok "Partition formatée en LUKS2" # ── Step 3: Open and create ext4 ─────────────────────────────────────────── log "Étape 3/7 — Création du filesystem ext4..." echo -n "$LUKS_KEY" | cryptsetup luksOpen --key-file=- "$ROOT_PART" cryptroot mkfs.ext4 -F -q /dev/mapper/cryptroot ok "ext4 créé dans le volume LUKS" # ── Step 4: Restore rootfs ────────────────────────────────────────────────── log "Étape 4/7 — Restauration du rootfs..." mount /dev/mapper/cryptroot /tmp/waouw-sd-root rsync -aAX --info=progress2 \ /tmp/waouw-sd-backup/ /tmp/waouw-sd-root/ # Ensure mount points exist mkdir -p /tmp/waouw-sd-root/{proc,sys,dev,run,boot,tmp} chmod 1777 /tmp/waouw-sd-root/tmp ok "Rootfs restauré dans le volume LUKS" # ── Step 5: Update configs ────────────────────────────────────────────────── log "Étape 5/7 — Mise à jour des configurations..." CRYPT_NAME="cryptroot" # crypttab echo "$CRYPT_NAME $ROOT_PART none luks,initramfs,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" \ > /tmp/waouw-sd-root/etc/crypttab ok "crypttab écrit" # fstab — replace root device ROOT_UUID=$(blkid -s UUID -o value "$ROOT_PART" 2>/dev/null || echo "") ROOT_PARTUUID=$(blkid -s PARTUUID -o value "$ROOT_PART" 2>/dev/null || echo "") sed -i "s|PARTUUID=[^ ]*|/dev/mapper/$CRYPT_NAME|" /tmp/waouw-sd-root/etc/fstab 2>/dev/null || true sed -i "s|$ROOT_PART|/dev/mapper/$CRYPT_NAME|g" /tmp/waouw-sd-root/etc/fstab 2>/dev/null || true if [ -n "$ROOT_UUID" ]; then sed -i "s|UUID=$ROOT_UUID|/dev/mapper/$CRYPT_NAME|g" /tmp/waouw-sd-root/etc/fstab 2>/dev/null || true fi ok "fstab mis à jour" # cmdline.txt on boot partition CMDLINE="/tmp/waouw-sd-boot/cmdline.txt" if [ -f "$CMDLINE" ]; then sed -i "s|root=[^ ]*|root=/dev/mapper/${CRYPT_NAME} cryptdevice=${ROOT_PART}:${CRYPT_NAME}|" "$CMDLINE" grep -q "ip=dhcp" "$CMDLINE" || sed -i 's|$| ip=dhcp|' "$CMDLINE" ok "cmdline.txt mis à jour" else warn "cmdline.txt non trouvé sur la partition boot" fi # ── Step 6: Save lot key locally for first boot ──────────────────────────── log "Étape 6/7 — Sauvegarde de la clé locale pour le premier boot..." # The keyscript needs the lot_id OR a local key to unlock on first boot # Save the key temporarily on boot partition (will be deleted after re-keying) echo -n "$LUKS_KEY" > /tmp/waouw-sd-boot/.waouw-luks-localkey chmod 600 /tmp/waouw-sd-boot/.waouw-luks-localkey ok "Clé locale sauvée sur /boot" # ── Step 7: Cleanup ───────────────────────────────────────────────────────── log "Étape 7/7 — Nettoyage..." # Remove encrypt-pending flag (encryption is done) rm -f /tmp/waouw-sd-boot/.waouw-encrypt-pending umount /tmp/waouw-sd-root cryptsetup luksClose cryptroot umount /tmp/waouw-sd-boot rm -rf /tmp/waouw-sd-backup unset LUKS_KEY echo "" echo -e " ${GREEN}========================================${NC}" echo -e " ${GREEN} CHIFFREMENT LUKS TERMINÉ${NC}" echo -e " ${GREEN}========================================${NC}" echo "" echo -e " La partition rootfs de la SD est chiffrée." echo -e " Au premier boot, le Pi utilisera la clé locale" echo -e " (.waouw-luks-localkey sur /boot)." echo -e " Après le bootstrap, la clé sera remplacée par" echo -e " une clé unique enregistrée sur waouw-admin." echo "" echo -e " ${YELLOW}Conservez la clé LUKS en lieu sûr.${NC}" echo ""