Auto Mount Encrypted Drive on Boot
Pretty simple way to auto mount an encrypted drive on boot without prompting for a password.
Essentially all we’ll be doing is generating a key, keeping that on our main drive, and mount our secondary drive using that key.
Format the drive
Let’s find out drive
lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
sda 8:0 0 2.7T 0 disk
├─sda1 8:1 0 128M 0 part
└─sda2 8:2 0 2.7T 0 part
sdb 8:16 0 111.8G 0 disk
└─sdb1 8:17 0 111.8G 0 part
Let’s say we want to format the sdb
drive.
Format it using sgdisk
(pacman -S gptfdisk)
sgdisk -Z /dev/sdb
Create a new partition.
sgdisk -n 1:/dev/sdb1 /dev/sdb
Encrypt the drive
CRYPT_NAME
is the name we’ll use for our crypt map. I like to keep it the same as the alias for the drive.
cryptsetup luksFormat --type luks2 /dev/sdb1
cryptsetup luksOpen /dev/sdb1 linuxroot
Create the file system
mkfs.btrfs -f -L DRIVE_NAME /dev/mapper/DRIVE_NAME
Generating the key
KEY_NAME
is whatever you want the name of the key to be. For convenience you could use an alias for the drive, if you want to obscure it it could be random text.
Generate the key:
dd if=/dev/random bs=32 count=1 of=/root/KEY_NAME
Change they key’s permission to readonly for root.
sudo chmod 0400 /root/KEY_NAME
Adding the key
Add our key to the partition (note it is sdb1
not sdb
).
cryptsetup luksAddKey /dev/sdb1 /root/KEY_NAME
Add the drive to crypttab
First we want to get the UUID
of our partition.
sudo blkid -o value -s UUID /dev/sdb1
Make note of it.
Now add the following line to /etc/crypttab
(replacing the values DRIVE_NAME
, UUID_VALUE
and KEY_NAME
).
DRIVE_NAME UUID=UUID_VALUE /root/KEY_NAME
Mount using fstab
First you want to make the mountpoint.
mkdir -p /media/DRIVE_NAME
Final stretch, add this line to /etc/fstab
/dev/mapper/DRIVE_NAME /media/DRIVE_NAME btrfs defaults,nofail 0 0
Moment of truth
Verify there aren’t any errors in fstab.
sudo findmnt --verify --verbose
Bonus use softlinks with your connected drive.
I like to softlink some of the larger directories under home to my secondary drive.
rm -rf ~/Documents
ln -s /media/DRIVE_NAME/Documents/ ~/Documents