tpm2-luks-enroll.sh
# === Xubuntu 26.04 (dracut): LUKS2 auto-unlock via TPM2 with recovery key ===
# Assumes: LUKS2 on /dev/, TPM present, NO clevis/initramfs-tools installed
DEV=$(lsblk -prno NAME,FSTYPE | awk '$2=="crypto_LUKS"{print $1}')
echo "Using LUKS device: $DEV"
# --- Pre-flight ---
ls /dev/tpm0 /dev/tpmrm0
dpkg -l | grep -E "clevis|initramfs-tools" || echo "clean"
which lsinitrd dracut
dracut --list-modules | grep -Ei "crypt|tpm2"
sudo cryptsetup luksDump "$DEV" | grep -E "Version" # should say 2
# --- Install tools, back up current initrd ---
sudo apt update
sudo apt install -y tpm2-tools
sudo cp /boot/initrd.img-$(uname -r) /boot/initrd.img-$(uname -r).good
# --- Recovery key (SAVE THE PRINTED KEY OFF THE VM), then test it ---
sudo systemd-cryptenroll --recovery-key "$DEV"
sudo cryptsetup open --test-passphrase "$DEV" # paste recovery key; silent = success
# --- Enroll TPM2 (PCR 7) and list keyslots ---
sudo systemd-cryptenroll --tpm2-device=auto --tpm2-pcrs=7 "$DEV"
sudo systemd-cryptenroll "$DEV" # should show password, recovery, tpm2
# --- Update crypttab to use the TPM ---
sudo sed -i 's/^\(dm_crypt-0 .* none \)luks.*$/\1luks,tpm2-device=auto/' /etc/crypttab
cat /etc/crypttab # expect: dm_crypt-0 UUID=... none luks,tpm2-device=auto
# --- Rebuild initrd with TPM support and verify BEFORE rebooting ---
echo 'add_dracutmodules+=" tpm2-tss "' | sudo tee /etc/dracut.conf.d/90-tpm2.conf
sudo dracut --force --kver "$(uname -r)"
sudo lsinitrd /boot/initrd.img-$(uname -r) | grep -Ei "systemd-cryptsetup|libtss2|tpm2"
# Must show both systemd-cryptsetup and libtss2*. If not, DON'T reboot; restore:
# sudo cp /boot/initrd.img-$(uname -r).good /boot/initrd.img-$(uname -r)
# --- Reboot: should go straight to login with no passphrase prompt ---
sleep 10
sudo reboot
# --- Optional, only after TPM boot AND recovery key both verified ---
# Remove the original password slot (check slot numbers first!):
# sudo cryptsetup luksDump "$DEV" | grep -E "^\s+[0-9]+: luks2"
# sudo cryptsetup luksKillSlot "$DEV" <password-slot-number>
# --- Optional: back up the LUKS header (store off the VM) ---
# sudo cryptsetup luksHeaderBackup "$DEV" --header-backup-file luks-header.img
# --- Optional: If the TPM isn't visible early in boot, add drivers and rebuild ---
# echo 'add_drivers+=" tpm_tis tpm_crb "' | sudo tee -a /etc/dracut.conf.d/90-tpm2.conf
# sudo dracut --force --kver "$(uname -r)"