Systemd: decrypt luks device on access


I have an external drive with a LUKS-encrypted partition. As the device is an external USB device and I don't always need it, I only want to decrypt and automount on demand. I can easily automount the fileystem on the decrypted partition with x-systemd.automount in /etc/fstab. However, I cannot decrypt the partition on demand. I've tried two different approaches:

  1. I added the line

    mnt-usb-crypt UUID=<UUID> /path/to/keyfile luks

    to /etc/crypttab. However, now the partition is always decrypted, even if I don't specify a mountpoint in /etc/fstab.

  2. I changed /etc/crypttab and added the noauto option:

    mnt-usb-crypt UUID=<UUID> /path/to/keyfile luks,noauto

    Now, there is no systemd device at all, the expected dev-mapper-mnt-usb.device does not exist.

According to the manpage of crypttab, there is no option like x-systemd.automount for crypt devices.

Is there a possibility to configure systemd to decrypt the device only if it is accessed?

Best Answer

  • Option 2 in the question actually works, but you have to use the same names for the crypt device in both /etc/crypttab and /etc/fstab.

    /etc/crypttab looks as follows:

    # <name>        <device>            <password>      <options>
    mnt-usb-crypt   UUID=<device-uuid>  /path/to/key    luks,noauto

    /etc/fstab looks as follows:

    # <file system>             <dir>       <type>  <options>                             <dump>    <pass>
    /dev/mapper/mnt-usb-crypt   /mnt/usb    btrfs   defaults,noauto,x-systemd.automount   0         2

    Note that if you use the UUID of the decrypted filesystem instead of the path /dev/mapper/mnt-usb-crypt, then systemd cannot determine the device it has to decrypt. But if you use the device name as above, the device is automatically decrypted and mounted as expected.

    A different solution would be to explicitly specify a requirement for the systemd crypt device.