1
0

encrypt-sd-rootfs.ps1 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <#
  2. .SYNOPSIS
  3. WaouW — Encrypt the rootfs partition of a Raspberry Pi SD card using LUKS2.
  4. Requires: WSL2 with cryptsetup installed.
  5. .PARAMETER SdDisk
  6. The physical disk number of the SD card (e.g., 1 for \\.\PhysicalDrive1).
  7. .EXAMPLE
  8. .\encrypt-sd-rootfs.ps1 -SdDisk 1
  9. #>
  10. param(
  11. [int]$SdDisk = -1,
  12. [switch]$NoConfirm
  13. )
  14. $ErrorActionPreference = 'Stop'
  15. Write-Host ""
  16. Write-Host " WaouW - Chiffrement LUKS de la carte SD" -ForegroundColor Cyan
  17. Write-Host " ========================================" -ForegroundColor Cyan
  18. Write-Host ""
  19. # ── Check WSL ───────────────────────────────────────────────────────────────
  20. Write-Host "[1/8] Verification de WSL et cryptsetup..." -ForegroundColor Yellow
  21. $wslCheck = wsl -- bash -c "cryptsetup --version 2>/dev/null"
  22. if (-not $wslCheck -or $wslCheck -notmatch "cryptsetup") {
  23. Write-Error "WSL ou cryptsetup non disponible."
  24. exit 1
  25. }
  26. Write-Host " OK: $wslCheck" -ForegroundColor Green
  27. # ── Identify SD card ────────────────────────────────────────────────────────
  28. Write-Host "[2/8] Identification de la carte SD..." -ForegroundColor Yellow
  29. if ($SdDisk -lt 0) {
  30. $disks = Get-Disk | Where-Object { $_.Size -lt 128GB -and $_.Size -gt 4GB -and $_.Number -ne 0 }
  31. if ($disks.Count -eq 0) {
  32. Write-Error "Aucune carte SD detectee. Specifiez -SdDisk."
  33. exit 1
  34. }
  35. if ($disks.Count -gt 1) {
  36. Write-Host " Plusieurs disques:" -ForegroundColor Yellow
  37. foreach ($d in $disks) {
  38. $sz = [math]::Round($d.Size/1GB,1)
  39. Write-Host " Disk $($d.Number): $($d.FriendlyName) ($sz GB)"
  40. }
  41. $SdDisk = [int](Read-Host " Numero du disque SD")
  42. } else {
  43. $SdDisk = $disks[0].Number
  44. }
  45. }
  46. $disk = Get-Disk -Number $SdDisk
  47. $sizeGB = [math]::Round($disk.Size / 1GB, 1)
  48. Write-Host " Disque $SdDisk : $($disk.FriendlyName) ($sizeGB GB)" -ForegroundColor Green
  49. # Find boot partition drive letter
  50. $partitions = Get-Partition -DiskNumber $SdDisk | Sort-Object PartitionNumber
  51. if ($partitions.Count -lt 2) {
  52. Write-Error "La carte SD doit avoir au moins 2 partitions (boot + rootfs)"
  53. exit 1
  54. }
  55. $bootPart = $partitions[0]
  56. $bootLetter = ""
  57. try { $bootLetter = ($bootPart | Get-Volume -ErrorAction SilentlyContinue).DriveLetter } catch {}
  58. if (-not $bootLetter) {
  59. Write-Error "Partition boot sans lettre de lecteur. Assignez-en une dans Gestion des disques."
  60. exit 1
  61. }
  62. Write-Host " Partition boot: ${bootLetter}:" -ForegroundColor Green
  63. # Confirm
  64. Write-Host ""
  65. Write-Host " ATTENTION: La partition rootfs va etre chiffree." -ForegroundColor Red
  66. Write-Host " Les donnees seront preservees." -ForegroundColor Yellow
  67. if (-not $NoConfirm) {
  68. $confirm = Read-Host " Continuer ? (oui/non)"
  69. if ($confirm -ne "oui") { exit 0 }
  70. }
  71. # ── Generate LUKS key ──────────────────────────────────────────────────────
  72. Write-Host "[3/8] Generation de la cle LUKS..." -ForegroundColor Yellow
  73. $luksKey = (wsl -- bash -c "openssl rand -hex 32 2>/dev/null").Trim()
  74. if ($luksKey.Length -ne 64) {
  75. Write-Error "Generation de cle echouee"
  76. exit 1
  77. }
  78. Write-Host " Cle generee (64 hex)" -ForegroundColor Green
  79. # ── Write WSL encryption script ─────────────────────────────────────────────
  80. Write-Host "[4/8] Preparation du script de chiffrement..." -ForegroundColor Yellow
  81. # Convert Windows paths to WSL paths
  82. $wslScriptPath = "/tmp/waouw-encrypt.sh"
  83. # Write the bash script to a temp file
  84. $bashScript = @'
  85. #!/bin/bash
  86. set -eo pipefail
  87. LUKS_KEY="$1"
  88. DISK_NUM="$2"
  89. SUDO_PASS="Reynerie75013"
  90. sp() { echo "$SUDO_PASS" | sudo -S "$@"; }
  91. log() { echo "[LUKS] $*"; }
  92. # Find the root partition (2nd partition on the mounted disk)
  93. log "Recherche de la partition rootfs..."
  94. sleep 2
  95. ROOT_DEV=""
  96. # Method 1: direct /dev/sdX2
  97. for dev in /dev/sda2 /dev/sdb2 /dev/sdc2 /dev/sdd2 /dev/sde2 /dev/sdf2; do
  98. if [ -b "$dev" ]; then
  99. ROOT_DEV="$dev"
  100. break
  101. fi
  102. done
  103. # Method 2: find the last mounted disk and use partprobe
  104. if [ -z "$ROOT_DEV" ]; then
  105. log "Pas de partition directe, tentative partprobe..."
  106. LAST_DISK=$(lsblk -rno NAME,TYPE | grep disk | tail -1 | awk '{print $1}')
  107. if [ -n "$LAST_DISK" ]; then
  108. sp partprobe "/dev/$LAST_DISK" 2>/dev/null || true
  109. sleep 2
  110. if [ -b "/dev/${LAST_DISK}2" ]; then
  111. ROOT_DEV="/dev/${LAST_DISK}2"
  112. fi
  113. fi
  114. fi
  115. # Method 3: use sfdisk to find partition offset and losetup
  116. if [ -z "$ROOT_DEV" ]; then
  117. log "Tentative via sfdisk + losetup..."
  118. LAST_DISK=$(lsblk -rno NAME,TYPE | grep disk | awk '{d=$1} END{print d}')
  119. if [ -n "$LAST_DISK" ] && [ -b "/dev/$LAST_DISK" ]; then
  120. # Get second partition offset and size
  121. PART_INFO=$(sp sfdisk -J "/dev/$LAST_DISK" 2>/dev/null | python3 -c "
  122. import json,sys
  123. d=json.load(sys.stdin)
  124. parts=d.get('partitiontable',{}).get('partitions',[])
  125. if len(parts)>=2:
  126. p=parts[1]
  127. print(p['start']*512, p['size']*512)
  128. " 2>/dev/null)
  129. if [ -n "$PART_INFO" ]; then
  130. OFFSET=$(echo "$PART_INFO" | awk '{print $1}')
  131. SIZE=$(echo "$PART_INFO" | awk '{print $2}')
  132. ROOT_DEV=$(sp losetup --find --show --offset "$OFFSET" --sizelimit "$SIZE" "/dev/$LAST_DISK" 2>/dev/null)
  133. log "Loop device: $ROOT_DEV (offset=$OFFSET, size=$SIZE)"
  134. fi
  135. fi
  136. fi
  137. if [ -z "$ROOT_DEV" ]; then
  138. log "ERREUR: Partition rootfs introuvable"
  139. log "Disques visibles: $(lsblk -rno NAME,SIZE,TYPE 2>/dev/null)"
  140. exit 1
  141. fi
  142. log "Partition: $ROOT_DEV"
  143. # Mount and backup
  144. log "Montage de la partition rootfs..."
  145. sp mkdir -p /tmp/waouw-rootfs /tmp/waouw-backup
  146. sp mount -t ext4 "$ROOT_DEV" /tmp/waouw-rootfs
  147. USED=$(df -BM /tmp/waouw-rootfs --output=used | tail -1 | tr -d ' M')
  148. log "Espace utilise: ${USED} MB"
  149. log "Sauvegarde du rootfs (tar)..."
  150. sp tar czf /tmp/waouw-backup/rootfs.tar.gz -C /tmp/waouw-rootfs --one-file-system .
  151. BACKUP_SIZE=$(du -sh /tmp/waouw-backup/rootfs.tar.gz | cut -f1)
  152. log "Sauvegarde: $BACKUP_SIZE"
  153. sp umount /tmp/waouw-rootfs
  154. # Format LUKS
  155. log "Formatage LUKS2..."
  156. echo -n "$LUKS_KEY" | sp cryptsetup luksFormat --type luks2 \
  157. --cipher aes-xts-plain64 --key-size 512 \
  158. --hash sha256 --iter-time 3000 \
  159. --batch-mode --key-file=- "$ROOT_DEV"
  160. log "Ouverture du volume LUKS..."
  161. echo -n "$LUKS_KEY" | sp cryptsetup luksOpen --key-file=- "$ROOT_DEV" cryptroot
  162. log "Creation du filesystem ext4..."
  163. sp mkfs.ext4 -F /dev/mapper/cryptroot
  164. # Restore
  165. log "Restauration du rootfs..."
  166. sp mount /dev/mapper/cryptroot /tmp/waouw-rootfs
  167. sp tar xzf /tmp/waouw-backup/rootfs.tar.gz -C /tmp/waouw-rootfs
  168. # Update fstab
  169. log "Mise a jour fstab..."
  170. sp sed -i "s|$ROOT_DEV|/dev/mapper/cryptroot|g" /tmp/waouw-rootfs/etc/fstab 2>/dev/null || true
  171. sp sed -i 's|PARTUUID=[^ ]*|/dev/mapper/cryptroot|' /tmp/waouw-rootfs/etc/fstab 2>/dev/null || true
  172. # Write crypttab
  173. log "Ecriture crypttab..."
  174. echo "cryptroot /dev/mmcblk0p2 none luks,initramfs,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" | sp tee /tmp/waouw-rootfs/etc/crypttab > /dev/null
  175. # Cleanup
  176. log "Demontage..."
  177. sp umount /tmp/waouw-rootfs
  178. sp cryptsetup luksClose cryptroot
  179. sp rm -rf /tmp/waouw-backup
  180. log "CHIFFREMENT TERMINE"
  181. '@
  182. # Write script to WSL filesystem
  183. $bashScript | wsl -- bash -c "cat > $wslScriptPath && chmod +x $wslScriptPath"
  184. Write-Host " Script pret" -ForegroundColor Green
  185. # ── Mount disk in WSL ───────────────────────────────────────────────────────
  186. Write-Host "[5/8] Montage du disque dans WSL..." -ForegroundColor Yellow
  187. # Remove rootfs from Windows (Paragon ExtFS) if mounted
  188. try {
  189. $rootPart = $partitions[1]
  190. $rootVol = $rootPart | Get-Volume -ErrorAction SilentlyContinue
  191. if ($rootVol -and $rootVol.DriveLetter) {
  192. Write-Host " Demontage rootfs de Windows ($($rootVol.DriveLetter):)..."
  193. $rootPart | Remove-PartitionAccessPath -AccessPath "$($rootVol.DriveLetter):" -ErrorAction SilentlyContinue
  194. Start-Sleep -Seconds 2
  195. }
  196. } catch {}
  197. wsl --mount "\\.\PhysicalDrive$SdDisk" --bare 2>&1 | Out-Null
  198. Start-Sleep -Seconds 3
  199. # Verify the disk is visible and create partition devices if needed
  200. $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"
  201. if ($wslDevCheck -match "NONE") {
  202. # Force partition scan
  203. $wslDisks = wsl -- bash -c "lsblk -rno NAME,SIZE,TYPE | grep disk | tail -1 | awk '{print `$1}'"
  204. $wslDisks = $wslDisks.Trim()
  205. if ($wslDisks) {
  206. wsl -- bash -c "sudo partprobe /dev/$wslDisks 2>/dev/null; sudo kpartx -av /dev/$wslDisks 2>/dev/null; sleep 2" 2>&1 | Out-Null
  207. }
  208. }
  209. Write-Host " OK" -ForegroundColor Green
  210. # ── Run encryption ──────────────────────────────────────────────────────────
  211. Write-Host "[6/8] Chiffrement en cours (peut prendre plusieurs minutes)..." -ForegroundColor Yellow
  212. Write-Host ""
  213. wsl -- bash -c "sudo $wslScriptPath '$luksKey' '$SdDisk'" 2>&1 | ForEach-Object { Write-Host " $_" }
  214. if ($LASTEXITCODE -ne 0) {
  215. Write-Error "Echec du chiffrement"
  216. wsl --unmount "\\.\PhysicalDrive$SdDisk" 2>&1 | Out-Null
  217. exit 1
  218. }
  219. # ── Unmount WSL ─────────────────────────────────────────────────────────────
  220. Write-Host ""
  221. Write-Host "[7/8] Demontage WSL..." -ForegroundColor Yellow
  222. wsl --unmount "\\.\PhysicalDrive$SdDisk" 2>&1 | Out-Null
  223. Write-Host " OK" -ForegroundColor Green
  224. # ── Update boot partition ───────────────────────────────────────────────────
  225. Write-Host "[8/8] Mise a jour partition boot..." -ForegroundColor Yellow
  226. # Update cmdline.txt
  227. $cmdlinePath = $null
  228. foreach ($p in @("${bootLetter}:\cmdline.txt", "${bootLetter}:\firmware\cmdline.txt")) {
  229. if (Test-Path $p) { $cmdlinePath = $p; break }
  230. }
  231. if ($cmdlinePath) {
  232. $cmdline = (Get-Content $cmdlinePath -Raw).Trim()
  233. $cmdline = $cmdline -replace 'root=[^\s]+', 'root=/dev/mapper/cryptroot cryptdevice=/dev/mmcblk0p2:cryptroot'
  234. if ($cmdline -notmatch 'ip=dhcp') { $cmdline += ' ip=dhcp' }
  235. [System.IO.File]::WriteAllText($cmdlinePath, $cmdline + "`n")
  236. Write-Host " cmdline.txt mis a jour" -ForegroundColor Green
  237. } else {
  238. Write-Host " ATTENTION: cmdline.txt non trouve" -ForegroundColor Red
  239. }
  240. # Save local key for first boot
  241. $luksKey | Set-Content "${bootLetter}:\.waouw-luks-localkey" -NoNewline -Encoding ASCII
  242. Write-Host " Cle locale sauvee sur /boot" -ForegroundColor Green
  243. # Save device-id placeholder
  244. "pending-encryption" | Set-Content "${bootLetter}:\waouw-device-id" -NoNewline -Encoding ASCII
  245. Write-Host ""
  246. Write-Host " ========================================" -ForegroundColor Green
  247. Write-Host " CHIFFREMENT LUKS TERMINE" -ForegroundColor Green
  248. Write-Host " ========================================" -ForegroundColor Green
  249. Write-Host ""
  250. Write-Host " Cle LUKS (a conserver) :" -ForegroundColor Cyan
  251. Write-Host " $luksKey" -ForegroundColor White
  252. Write-Host ""
  253. $luksKey = $null
  254. [System.GC]::Collect()
  255. pause