How to setup a (Fedora 33) linux system to automatically mount luks encrypted partitions on demand (for instance by `cd`ing into the mount point).

This is not a tutorial. This is a series of personal notes. Use at your own risk.
  • Add the encrypted device we are trying to automount to /etc/crypttab by inserting a line similar to this:

    <enc_dev_name> UUID=<enc_dev_UUID> none noauto

    Where:

    • the first item is the encrypted device name.

    • the second item is the device UUID.

      Use lsblk -l -o NAME,UUID to find the device UUID
    • none will tell the system to load the key from /etc/cryptsetup-keys.d/<enc_dev_name>.key (see below)

    • noauto tells the system NOT to mount the device on boot

    • Example:

      luks-d2b992ae-662f-43b0-ba3c-4037c4f86ceb UUID=d2b992ae-662f-43b0-ba3c-4037c4f86ceb none noauto
  • Create the directory where our decryption keyfiles will be stored

    # mkdir /etc/cryptsetup-keys.d/
  • Create the actual keyfile passphrase

    # echo -n 'passphrase' > /etc/cryptsetup-keys.d/<enc_dev_name>.key
    Make sure that the key file is owned by root and has permission set to octal 400 (only root can read the file)
  • Add the keyfile to the disk drive partition that hosts the encrypted partition:

    # cryptsetup luksAddKey /dev/<disk> /<enc_dev_name>.key
    • Example:

      cryptsetup luksAddKey /dev/sdc2 /etc/cryptsetup-keys.d/luks-d2b992ae-662f-43b0-ba3c-4037c4f86ceb.key
  • Test that the encrypted partition is unlocked without asking for a passphrase

    # systemctl restart systemd-cryptsetup@luks\\x2dd2b992ae\\x2d662f\\x2d43b0\\x2dba3c\\x2d4037c4f86ceb.service
    unlocked != mounted
  • Add the mountpoint to /etc/fstab by using a line similar to this:

    /dev/mapper/<enc_dev_name> /<mount_point> <fs_type> noauto,x-systemd.automount 0 0

    Where:

    • noauto tells the system not to mount the partition at boot time

    • x-systemd.automount mounts the partition only when the mount point directory is being accessed

    • additionally x-systemd.idle-timeout can be added to unmount the partition after a set amount of idle time

    • For example:

      /dev/mapper/luks-ad1e166c-2d4f-4ed5-816d-a8216f52f4d8 /media/PersCrypt        btrfs   subvol=snapshots,noauto,x-systemd.automount,x-systemd.idle-timeout=5min 0 0
  • Create the mountpoints as needed. Example: # mkdir /media/PersCrypt

Notes and Troubleshooting

  • # systemctl daemon-reload must be run after altering /etc/fstab and/or /etc/crypttab

  • # findmnt --verify can be used to verify that the /etc/fstab syntax is correct

  • # systemctl start run-media-<mount_point>.automount can be run to see if the device is unlocked and mounted correctly. Example: # systemctl start run-media-PersCrypt.mount

  • My /etc/fstab file SElinux labels were incorrect for some reason and I was getting an AVC Denial issue. To fix the labels I had to issue: # restorecon -rv /etc/fstab