Skip to main content

Linux Unified Key Setup (LUKS)

All the examples below assume wanting to setup a btrfs pool on two disks /dev/sdX and /dev/sdY that will be used just for additional storage.

Prepare Disks

Before encrypting a drive, it is recommended to perform a secure erase of the disk by overwriting the entire drive with random data. To prevent cryptographic attacks or unwanted file recovery, this data is ideally indistinguishable from data later written by dm-crypt.

Source

There are multiple ways to prepare a disk and some other potentially better ones listed on the page linked to above. Because I wanted to wipe my disks as quickly as possible and they were both the same size I used a slightly more complicated method. This method creates the equivalent of /dev/urandom but faster by using the output of encrypting /dev/zero and writing that to the disks. I save even more time by using tee and process substitution to redirect the output to both drives at once. Just for good measure I used pv to measure the speed at which I am writing and to track my progress.

PASS=$(tr -cd '[:alnum:]' < /dev/urandom | head -c128)
openssl enc -aes-256-ctr -pass pass:"$PASS" -nosalt < /dev/zero | dd ibs=4K | pv | tee >(dd obs=64K oflag=direct of=/dev/sdX) | dd obs=64K oflag=direct of=/dev/sdY

Partition

Although LUKS can be layered on top of redundant storage (btrfs/mdadm+dm-integrity) for my usages it almost always makes sense to layer those things on top of LUKS. Also I don't use LUKS for my boot drives so I just needed the drives to have one partition.

sgdisk --clear --new=0:0:0 /dev/sdX
sgdisk --clear --new=0:0:0 /dev/sdY

Encrypt

Setup LUKS with passphrase encrypted drives.

cryptsetup open /dev/sdX1 cryptbtrpool_1
cryptsetup open /dev/sdY1 cryptbtrpool_2

Add keyfile as optional decryption key.

dd if=/dev/urandom bs=512 count=4 of=/etc/keyfile
cryptsetup luksAddKey /dev/sdX1 /etc/keyfile
cryptsetup luksAddKey /dev/sdY1 /etc/keyfile

Unlock Devices

cryptsetup open /dev/sdX1 cryptbtrpool_1 --key-file=/etc/keyfile
cryptsetup open /dev/sdY1 cryptbtrpool_2 --key-file=/etc/keyfile

Create btrfs Pool

mkfs.btrfs --data raid1 --metadata raid1 --label btrpool /dev/mapper/cryptbtrpool_1 /dev/mapper/cryptbtrpool_2

Add to crypttab

need to do this still

Add to fstab

need to do this still