LUKS encrypted USB drive with Btrfs

Recently I bought a Yubikey 4 Nano from Yubico and I started to play a bit with GnuPG as I needed to generate a few new subkeys for the smartcard feature of it. While doing this, I figurered that I needed a way to safely store away my secret keys and also that it would be nice if I could easily create snapshots of the .gnupg directory over time.

What I ended up with was a LUKS encrypted USB drive and a Btrfs filesystem for easy snapshot creation.

Here are some good links if you wish to read up a bit on LUKS, cryptsetup and dm-crypt before proceeding:

Prepare USB drive

So, first step is to get hold of a USB drive, partition it and then securely erase the partition with random data. In my case I first created the LUKS container directly followed by writing a Btrfs filesystem to it. Then using dd I wiped it with pseudorandom data as I was inside the encrypted container. It’s really important that you don’t skip this step, otherwise it might be possible to carry out cryptographic attacks against the container and possible usage patterns.

I assume that you now have a USB drive partitioned the way you want it, in this example my partition is /dev/sdb1.

Initialize LUKS partition

First step is to initialize the partition with cryptsetup using the luksFormat action.

I followed the recommendations in the higher specification example from the Archlinux wiki regarding encryption options.

cryptsetup -v --cipher aes-xts-plain64 --key-size 512 --hash sha512 --iter-time 5000 --use-random luksFormat /dev/sdb1

WARNING!
========
This will overwrite data on /dev/sdb1 irrevocably.

Are you sure? (Type uppercase yes): YES
Enter passphrase:
Verify passphrase:
Command successful.

Open LUKS device and set up mapping

The following will try to open /dev/sdb1 as /dev/mapper/encrypted.

Use your passphrase to open your encrypted container.

cryptsetup open /dev/sdb1 encrypted

Setup Btrfs

I will use Btrfs as filesystem for my setup.

mkfs.btrfs /dev/mapper/encrypted

Mount device mapped container

Mount the block device and enjoy the benefits of having a device where writes are encrypted and reads decrypted transparently.

mount /dev/mapper/encrypted /mnt/encrypted

Close and lock the device

Finally when you are done, then close the device properly.

umount /mnt/encrypted
cryptsetup close encrypted

Image backup with dd

I know that this step probably not recommended but I will put it here anyway. It’s rather simple to create a image backup of the partition with dd if you feel the need.

dd if=/dev/sdb1 of=encrypted.img status=progress

Then you can either transfer it to a VPS or wherever so you have a backup or just write it to another USB drive.

Mount the backup image

The image can easily be mounted with losetup if you wish.

losetup /dev/loop1 encrypted.img
cryptsetup open /dev/loop1 encrypted
comments powered by Disqus