| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316 |
- <#
- .SYNOPSIS
- WaouW — Encrypt the rootfs partition of a Raspberry Pi SD card using LUKS2.
- Requires: WSL2 with cryptsetup installed.
- .PARAMETER SdDisk
- The physical disk number of the SD card (e.g., 1 for \\.\PhysicalDrive1).
- .EXAMPLE
- .\encrypt-sd-rootfs.ps1 -SdDisk 1
- #>
- param(
- [int]$SdDisk = -1,
- [switch]$NoConfirm
- )
- $ErrorActionPreference = 'Stop'
- Write-Host ""
- Write-Host " WaouW - Chiffrement LUKS de la carte SD" -ForegroundColor Cyan
- Write-Host " ========================================" -ForegroundColor Cyan
- Write-Host ""
- # ── Check WSL ───────────────────────────────────────────────────────────────
- Write-Host "[1/8] Verification de WSL et cryptsetup..." -ForegroundColor Yellow
- $wslCheck = wsl -- bash -c "cryptsetup --version 2>/dev/null"
- if (-not $wslCheck -or $wslCheck -notmatch "cryptsetup") {
- Write-Error "WSL ou cryptsetup non disponible."
- exit 1
- }
- Write-Host " OK: $wslCheck" -ForegroundColor Green
- # ── Identify SD card ────────────────────────────────────────────────────────
- Write-Host "[2/8] Identification de la carte SD..." -ForegroundColor Yellow
- if ($SdDisk -lt 0) {
- $disks = Get-Disk | Where-Object { $_.Size -lt 128GB -and $_.Size -gt 4GB -and $_.Number -ne 0 }
- if ($disks.Count -eq 0) {
- Write-Error "Aucune carte SD detectee. Specifiez -SdDisk."
- exit 1
- }
- if ($disks.Count -gt 1) {
- Write-Host " Plusieurs disques:" -ForegroundColor Yellow
- foreach ($d in $disks) {
- $sz = [math]::Round($d.Size/1GB,1)
- Write-Host " Disk $($d.Number): $($d.FriendlyName) ($sz GB)"
- }
- $SdDisk = [int](Read-Host " Numero du disque SD")
- } else {
- $SdDisk = $disks[0].Number
- }
- }
- $disk = Get-Disk -Number $SdDisk
- $sizeGB = [math]::Round($disk.Size / 1GB, 1)
- Write-Host " Disque $SdDisk : $($disk.FriendlyName) ($sizeGB GB)" -ForegroundColor Green
- # Find boot partition drive letter
- $partitions = Get-Partition -DiskNumber $SdDisk | Sort-Object PartitionNumber
- if ($partitions.Count -lt 2) {
- Write-Error "La carte SD doit avoir au moins 2 partitions (boot + rootfs)"
- exit 1
- }
- $bootPart = $partitions[0]
- $bootLetter = ""
- try { $bootLetter = ($bootPart | Get-Volume -ErrorAction SilentlyContinue).DriveLetter } catch {}
- if (-not $bootLetter) {
- Write-Error "Partition boot sans lettre de lecteur. Assignez-en une dans Gestion des disques."
- exit 1
- }
- Write-Host " Partition boot: ${bootLetter}:" -ForegroundColor Green
- # Confirm
- Write-Host ""
- Write-Host " ATTENTION: La partition rootfs va etre chiffree." -ForegroundColor Red
- Write-Host " Les donnees seront preservees." -ForegroundColor Yellow
- if (-not $NoConfirm) {
- $confirm = Read-Host " Continuer ? (oui/non)"
- if ($confirm -ne "oui") { exit 0 }
- }
- # ── Generate LUKS key ──────────────────────────────────────────────────────
- Write-Host "[3/8] Generation de la cle LUKS..." -ForegroundColor Yellow
- $luksKey = (wsl -- bash -c "openssl rand -hex 32 2>/dev/null").Trim()
- if ($luksKey.Length -ne 64) {
- Write-Error "Generation de cle echouee"
- exit 1
- }
- Write-Host " Cle generee (64 hex)" -ForegroundColor Green
- # ── Write WSL encryption script ─────────────────────────────────────────────
- Write-Host "[4/8] Preparation du script de chiffrement..." -ForegroundColor Yellow
- # Convert Windows paths to WSL paths
- $wslScriptPath = "/tmp/waouw-encrypt.sh"
- # Write the bash script to a temp file
- $bashScript = @'
- #!/bin/bash
- set -eo pipefail
- LUKS_KEY="$1"
- DISK_NUM="$2"
- SUDO_PASS="Reynerie75013"
- sp() { echo "$SUDO_PASS" | sudo -S "$@"; }
- log() { echo "[LUKS] $*"; }
- # Find the root partition (2nd partition on the mounted disk)
- log "Recherche de la partition rootfs..."
- sleep 2
- ROOT_DEV=""
- # Method 1: direct /dev/sdX2
- for dev in /dev/sda2 /dev/sdb2 /dev/sdc2 /dev/sdd2 /dev/sde2 /dev/sdf2; do
- if [ -b "$dev" ]; then
- ROOT_DEV="$dev"
- break
- fi
- done
- # Method 2: find the last mounted disk and use partprobe
- if [ -z "$ROOT_DEV" ]; then
- log "Pas de partition directe, tentative partprobe..."
- LAST_DISK=$(lsblk -rno NAME,TYPE | grep disk | tail -1 | awk '{print $1}')
- if [ -n "$LAST_DISK" ]; then
- sp partprobe "/dev/$LAST_DISK" 2>/dev/null || true
- sleep 2
- if [ -b "/dev/${LAST_DISK}2" ]; then
- ROOT_DEV="/dev/${LAST_DISK}2"
- fi
- fi
- fi
- # Method 3: use sfdisk to find partition offset and losetup
- if [ -z "$ROOT_DEV" ]; then
- log "Tentative via sfdisk + losetup..."
- LAST_DISK=$(lsblk -rno NAME,TYPE | grep disk | awk '{d=$1} END{print d}')
- if [ -n "$LAST_DISK" ] && [ -b "/dev/$LAST_DISK" ]; then
- # Get second partition offset and size
- PART_INFO=$(sp sfdisk -J "/dev/$LAST_DISK" 2>/dev/null | python3 -c "
- import json,sys
- d=json.load(sys.stdin)
- parts=d.get('partitiontable',{}).get('partitions',[])
- if len(parts)>=2:
- p=parts[1]
- print(p['start']*512, p['size']*512)
- " 2>/dev/null)
- if [ -n "$PART_INFO" ]; then
- OFFSET=$(echo "$PART_INFO" | awk '{print $1}')
- SIZE=$(echo "$PART_INFO" | awk '{print $2}')
- ROOT_DEV=$(sp losetup --find --show --offset "$OFFSET" --sizelimit "$SIZE" "/dev/$LAST_DISK" 2>/dev/null)
- log "Loop device: $ROOT_DEV (offset=$OFFSET, size=$SIZE)"
- fi
- fi
- fi
- if [ -z "$ROOT_DEV" ]; then
- log "ERREUR: Partition rootfs introuvable"
- log "Disques visibles: $(lsblk -rno NAME,SIZE,TYPE 2>/dev/null)"
- exit 1
- fi
- log "Partition: $ROOT_DEV"
- # Mount and backup
- log "Montage de la partition rootfs..."
- sp mkdir -p /tmp/waouw-rootfs /tmp/waouw-backup
- sp mount -t ext4 "$ROOT_DEV" /tmp/waouw-rootfs
- USED=$(df -BM /tmp/waouw-rootfs --output=used | tail -1 | tr -d ' M')
- log "Espace utilise: ${USED} MB"
- log "Sauvegarde du rootfs (tar)..."
- sp tar czf /tmp/waouw-backup/rootfs.tar.gz -C /tmp/waouw-rootfs --one-file-system .
- BACKUP_SIZE=$(du -sh /tmp/waouw-backup/rootfs.tar.gz | cut -f1)
- log "Sauvegarde: $BACKUP_SIZE"
- sp umount /tmp/waouw-rootfs
- # Format LUKS
- log "Formatage LUKS2..."
- echo -n "$LUKS_KEY" | sp cryptsetup luksFormat --type luks2 \
- --cipher aes-xts-plain64 --key-size 512 \
- --hash sha256 --iter-time 3000 \
- --batch-mode --key-file=- "$ROOT_DEV"
- log "Ouverture du volume LUKS..."
- echo -n "$LUKS_KEY" | sp cryptsetup luksOpen --key-file=- "$ROOT_DEV" cryptroot
- log "Creation du filesystem ext4..."
- sp mkfs.ext4 -F /dev/mapper/cryptroot
- # Restore
- log "Restauration du rootfs..."
- sp mount /dev/mapper/cryptroot /tmp/waouw-rootfs
- sp tar xzf /tmp/waouw-backup/rootfs.tar.gz -C /tmp/waouw-rootfs
- # Update fstab
- log "Mise a jour fstab..."
- sp sed -i "s|$ROOT_DEV|/dev/mapper/cryptroot|g" /tmp/waouw-rootfs/etc/fstab 2>/dev/null || true
- sp sed -i 's|PARTUUID=[^ ]*|/dev/mapper/cryptroot|' /tmp/waouw-rootfs/etc/fstab 2>/dev/null || true
- # Write crypttab
- log "Ecriture crypttab..."
- echo "cryptroot /dev/mmcblk0p2 none luks,initramfs,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" | sp tee /tmp/waouw-rootfs/etc/crypttab > /dev/null
- # Cleanup
- log "Demontage..."
- sp umount /tmp/waouw-rootfs
- sp cryptsetup luksClose cryptroot
- sp rm -rf /tmp/waouw-backup
- log "CHIFFREMENT TERMINE"
- '@
- # Write script to WSL filesystem
- $bashScript | wsl -- bash -c "cat > $wslScriptPath && chmod +x $wslScriptPath"
- Write-Host " Script pret" -ForegroundColor Green
- # ── Mount disk in WSL ───────────────────────────────────────────────────────
- Write-Host "[5/8] Montage du disque dans WSL..." -ForegroundColor Yellow
- # Remove rootfs from Windows (Paragon ExtFS) if mounted
- try {
- $rootPart = $partitions[1]
- $rootVol = $rootPart | Get-Volume -ErrorAction SilentlyContinue
- if ($rootVol -and $rootVol.DriveLetter) {
- Write-Host " Demontage rootfs de Windows ($($rootVol.DriveLetter):)..."
- $rootPart | Remove-PartitionAccessPath -AccessPath "$($rootVol.DriveLetter):" -ErrorAction SilentlyContinue
- Start-Sleep -Seconds 2
- }
- } catch {}
- wsl --mount "\\.\PhysicalDrive$SdDisk" --bare 2>&1 | Out-Null
- Start-Sleep -Seconds 3
- # Verify the disk is visible and create partition devices if needed
- $wslDevCheck = wsl -- bash -c "ls /dev/sd*2 2>/dev/null || (sudo partprobe 2>/dev/null; sleep 1; ls /dev/sd*2 2>/dev/null) || echo NONE"
- if ($wslDevCheck -match "NONE") {
- # Force partition scan
- $wslDisks = wsl -- bash -c "lsblk -rno NAME,SIZE,TYPE | grep disk | tail -1 | awk '{print `$1}'"
- $wslDisks = $wslDisks.Trim()
- if ($wslDisks) {
- wsl -- bash -c "sudo partprobe /dev/$wslDisks 2>/dev/null; sudo kpartx -av /dev/$wslDisks 2>/dev/null; sleep 2" 2>&1 | Out-Null
- }
- }
- Write-Host " OK" -ForegroundColor Green
- # ── Run encryption ──────────────────────────────────────────────────────────
- Write-Host "[6/8] Chiffrement en cours (peut prendre plusieurs minutes)..." -ForegroundColor Yellow
- Write-Host ""
- wsl -- bash -c "sudo $wslScriptPath '$luksKey' '$SdDisk'" 2>&1 | ForEach-Object { Write-Host " $_" }
- if ($LASTEXITCODE -ne 0) {
- Write-Error "Echec du chiffrement"
- wsl --unmount "\\.\PhysicalDrive$SdDisk" 2>&1 | Out-Null
- exit 1
- }
- # ── Unmount WSL ─────────────────────────────────────────────────────────────
- Write-Host ""
- Write-Host "[7/8] Demontage WSL..." -ForegroundColor Yellow
- wsl --unmount "\\.\PhysicalDrive$SdDisk" 2>&1 | Out-Null
- Write-Host " OK" -ForegroundColor Green
- # ── Update boot partition ───────────────────────────────────────────────────
- Write-Host "[8/8] Mise a jour partition boot..." -ForegroundColor Yellow
- # Update cmdline.txt
- $cmdlinePath = $null
- foreach ($p in @("${bootLetter}:\cmdline.txt", "${bootLetter}:\firmware\cmdline.txt")) {
- if (Test-Path $p) { $cmdlinePath = $p; break }
- }
- if ($cmdlinePath) {
- $cmdline = (Get-Content $cmdlinePath -Raw).Trim()
- $cmdline = $cmdline -replace 'root=[^\s]+', 'root=/dev/mapper/cryptroot cryptdevice=/dev/mmcblk0p2:cryptroot'
- if ($cmdline -notmatch 'ip=dhcp') { $cmdline += ' ip=dhcp' }
- [System.IO.File]::WriteAllText($cmdlinePath, $cmdline + "`n")
- Write-Host " cmdline.txt mis a jour" -ForegroundColor Green
- } else {
- Write-Host " ATTENTION: cmdline.txt non trouve" -ForegroundColor Red
- }
- # Save local key for first boot
- $luksKey | Set-Content "${bootLetter}:\.waouw-luks-localkey" -NoNewline -Encoding ASCII
- Write-Host " Cle locale sauvee sur /boot" -ForegroundColor Green
- # Save device-id placeholder
- "pending-encryption" | Set-Content "${bootLetter}:\waouw-device-id" -NoNewline -Encoding ASCII
- Write-Host ""
- Write-Host " ========================================" -ForegroundColor Green
- Write-Host " CHIFFREMENT LUKS TERMINE" -ForegroundColor Green
- Write-Host " ========================================" -ForegroundColor Green
- Write-Host ""
- Write-Host " Cle LUKS (a conserver) :" -ForegroundColor Cyan
- Write-Host " $luksKey" -ForegroundColor White
- Write-Host ""
- $luksKey = $null
- [System.GC]::Collect()
- pause
|