dm-crypt/Mounting at login
This tutorial assumes you have already created your encrypted partition, as described in Dm-crypt/Encrypting a non-root file system.
- You need to use the same password for your user account and for LUKS.
- In all the examples, replace
usernamewith your username,
1000with your user ID and
PARTITIONwith the name of your encrypted partition's device.
Unlocking at login
pam_exec can be used to unlock the device at login. Edit
/etc/pam.d/system-login and add the line below emphasized in bold after
auth include system-auth:
... auth include system-auth auth optional pam_exec.so expose_authtok /etc/pam_cryptsetup.sh ...
Then create the mentioned script.
#!/bin/sh CRYPT_USER="username" PARTITION="/dev/sdXY" NAME="home-$CRYPT_USER" if [ "$PAM_USER" = "$CRYPT_USER" ] && [ ! -e "/dev/mapper/$NAME" ]; then /usr/bin/cryptsetup open "$PARTITION" "$NAME" fi
Make the script executable.
Mounting and unmounting automatically
firstname.lastname@example.org for as long as at least one session is active for the user. It is started automatically after a first successful login and stopped after a logout from the last session. Hence, we can create and enable a unit for the mapped volume and connect it to
email@example.com in order to make it mount and unmount automatically:
[Unit] Requiresfirstname.lastname@example.org Beforeemail@example.com [Mount] Where=/home/username What=/dev/mapper/home-username Type=btrfs Options=defaults,relatime,compress=zstd [Install] RequiredByfirstname.lastname@example.org
Locking after unmounting
After unmounting, the device will still be unlocked, and it will be possible to mount it without re-entering password. You can create and enable a service that starts when the device gets unlocked (
BindsTo=dev-mapper-home\x2dusername.device) and dies after the device gets unmounted (
Requires,Before=home-username.mount), locking the device in the process (
[Unit] DefaultDependencies=no BindsTo=dev-PARTITION.device After=dev-PARTITION.device BindsTo=dev-mapper-home\x2dusername.device Requires=home-username.mount Before=home-username.mount Conflicts=umount.target Before=umount.target [Service] Type=oneshot RemainAfterExit=yes TimeoutSec=0 ExecStop=/usr/bin/cryptsetup close home-username [Install] RequiredBy=dev-mapper-home\x2dusername.device
dev-PARTITIONis the result of
systemd-escape -p /dev/PARTITION