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.
#!/usr/bin/env bash 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
email@example.com 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
firstname.lastname@example.org in order to make it mount and unmount automatically:
[Unit] Requiresemail@example.com Beforefirstname.lastname@example.org [Mount] Where=/home/username What=/dev/mapper/home-username Type=btrfs Options=defaults,relatime,compress=zstd [Install] RequiredByemail@example.com
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