Automatically mounting a LUKS/dm_crypt partition on user login using pam

Last Updated: 2015-05-21

Automounting an encrypted partition with a keyfile when you login is actually quite straight forward, but unfortunately, there is not that much documentation available online on how to do this. Most of the examples only deal with automatically mounting your /home partition using LUKS/dm_crypt and crypttab. But if you already have an encrypted home using ecryptfs and you want to mount another partition not at boot time (for this scenario crypttab is what you want) but only when a user logs in, you can use pam_mount. After installing libpam-mount, check if the following lines are present in your pam configuration files:

# grep pam_mount /etc/pam.d/*
/etc/pam.d/common-auth:auth optional 
/etc/pam.d/common-session:session optional 
/etc/pam.d/common-session-noninteractive:session optional

They should be added automatically during the installation, though.

In the end, you only have to do a couple of steps to make the magic happen:

  1. Utilize another keyslot in your LUKS-volume using a keyfile
  2. Add two lines to your /etc/security/pam_mount_conf.xml
  3. voila, that's it :)

ad 1) First, create a random keyfile and make it read-only to root

sudo dd if=/dev/random of=/home/USER/.keyfile_data bs=1024 count=4
sudo chmod 0400 /home/USER/.keyfile_data

Once created, you have to add this keyfile to your LUKS/dm_crypt enabled device, which may hold up to 10 different keyfiles/passwords. Keep in mind that this file must NOT be accessable by anyone else and should only be stored in your encrypted home-directory. If you want to save it somewhere else, you really should encrypt it using openssl (do not forget to adjust the fskeycipher parameter in this case).

sudo cryptsetup luksAddKey /dev/your_dm_crypt_device /home/USER/.keyfile_data

Doing so, you'll be prompted to enter your password to unlock the drive. If everything works well, you should get an output like this:

Enter any LUKS passphrase:
key slot 0 unlocked.
Command successful.

ad 2) Add the following two lines right before the closing tag </pam_moun> in your /etc/security/pam_mount_conf.xml file:

<volume user="USER" fstype="crypt" path="/dev/your_dm_crypt_device" mountpoint="/data" options="fsck,noatime" fskeypath="/home/USER/.keyfile_data" fskeycipher="none" fskeysize="256" fskeyhash="none" />
<mkmountpoint enable="1" remove="true" />

You can find out the keysize of your partition with:

sudo cryptsetup status mapper-name

ad 3) Finally, just login on another tty to see if everything mounts and logout again and check if it unmounts correctly.

Not yet rated