sylvain durand

Encrypt and automatically mount a disk

I have a personal server at home, fully encrypted, and I regularly add hard drives to store data. To prevent any data leaks in case of theft, it’s crucial to ensure the data is also encrypted on the drives. This guide will walk you through the process of formatting the drive, encrypting it, and setting it up to be automatically decrypted and mounted at startup.

Formatting the hard drive

First, identify the disk you want to format:

lsblk

In this example, it will be /dev/sdX (commonly sda, sdb, sdc, or nvme01, nvme02 for SSDs).

You can then completely wipe the disk (be careful: naturally, all data will be erased, so make sure you have backed everything up and that you are selecting the correct disk):

sudo wipefs -af /dev/sdX

We use parted in this example to create a disk with a single partition:

sudo parted /dev/sdX mklabel gpt
sudo parted -s -a optimal /dev/sdX mkpart primary ext4 0% 100%

Creating the encrypted storage

The cryptsetup tool allows you to create an encrypted space. Be sure to remember the password you use, as there is no way to recover the encrypted data without it.

sudo cryptsetup -y -v luksFormat --iter-time 100 /dev/sdX1

We then open this partition by assigning it a name (in this case, media). It will then be accessible from /dev/mapper/media. We can then create a filesystem (here ext4).

sudo cryptsetup luksOpen /dev/sdX1 media
sudo mkfs.ext4 /dev/mapper/media

You can then mount this disk with:

sudo mount /dev/mapper/media /mnt/media

Automatic mounting of the disk at startup

Assuming the main disk (on which the system is running) is encrypted, you can create an encryption key that will be automatically read at startup to mount our disk. We create this key:

sudo mkdir /etc/luks-keys/
sudo dd if=/dev/urandom of=/etc/luks-keys/media.key bs=512 count=8 iflag=fullblock
sudo chown root:root /etc/luks-keys/media.key
sudo chmod 400 /etc/luks-keys/media.key
sudo cryptsetup -v luksAddKey /dev/sdX1 /etc/luks-keys/media.key

To automate the decryption, we will need the UUID of the partition, which does not change after restarts:

sudo blkid /dev/sdX1 -s UUID -o value

To decrypt the disk at startup, we add the following line to /etc/crypttab, adding the previously obtained UUID:

media UUID=UUID_HERE /etc/luks-keys/media.key luks

All that’s left is to automate the mounting of this volume, and to do so, we add a line to /etc/fstab:

/dev/mapper/media /mnt/media ext4 nofail,rw