Open LUKS encrypted device via key on USB stick

Background

If you want to encrypt the root file system of a computer running Linux with LUKS, you usually have to entere the encryption password at every system boot. Especially in the case of a headless computer acting as a server this is not suitable. To overcome this problem LUKS offers the possibility to store the encryption key as a keyfile and use it to open the encrypted disk.

There also exist several guides how the keyfile can be stored on a USB stick. Examples include here, here or here (the second and third guides are only available in German).

However, all the guides we found did not work with recent versions of Debian or Ubuntu. The problem seems to be a combination of systemd not supporting the keyscript mechanism used in some guides and incomplete support of keyfiles in the script /usr/share/initramfs-tools/hooks/cryptroot. The cryptroot script is responsible to generate the crypttab file in the initramfs which is used during the boot process to unlock the encrypted disks.

Solution

To overcome the problem we created a minimal hook that generates a correct crypttab file in the initramfs. The script is placed in /etc/initramfs-tools/hooks/xyz-crypttab. Thereby it is executed at the end of the process to generate an initramfs. The script looks as follows:

#!/bin/sh

PREREQ=""

prereqs()
{
    echo "$PREREQ"
}

case "$1" in
    prereqs)
        prereqs
        exit 0
        ;;
esac

. /usr/share/initramfs-tools/hook-functions
. /lib/cryptsetup/functions
TABFILE="/etc/crypttab"

cp "$TABFILE" "${DESTDIR}/cryptroot/crypttab"
exit 0

The script simply copies the original crypttab file into the correct destination in the initramfs. After the scripted is set as executable, the existing initramfs can be regenerated by executing sudo update-initramfs -u. At the next boot your system should be able to unlock the encrypted root file system by the keyfile stored on the USB stick.

Leave a Reply