Computer Stuff

Jul 05, 2014

How to encrypt an external disk with dm-crypt, LUKS and LVM

First of all if you are like i was, confused about dm-crypt/LUKS/cryptsetup you need to look at the man of cryptsetup. It does a very good job at what exactly LUKS is. Basically, dm-crypt is a kernel module that deals with the encryption at the disk sector level. This allows to encrypt any kind of filesystem. LUKS on the other hand is an extension to the bare dm-crypt, it adds features such as:

  • Use of PBKDF2 for key stretching
  • Multiple passphrases

Finally cryptsetup is a frontend to both dm-crypt and LUKS, it is a tool to setup encrypted partitions with their various settings, with or without LUKS.

First you’ll want to luksFormat the target partition:

cryptsetup --verbose luksFormat /dev/sd?? -h sha512

Why -h sha512? With cryptsetup --help you can see the defaults used by cryptsetup on your system. On mine it used sha1 to hash the LUKS header.

If you issue the following command you’ll be able to see the luks header:

cryptsetup luksDump /dev/sd??

Now let’s open the encrypted partition:

cryptsetup luksOpen /dev/sd?? some_name

The decrypted partition will be /dev/mapper/some_name. Now let’s prepare the LVM volume. LVM has no runtime cost and usually makes your life easier managing partitions.

pvcreate /dev/mapper/some_name
vgcreate vg_name /dev/mapper/some_name
lvcreate -n lv_name vg_name -l100%VG

These commands will in order, prepare the partition for LVM, create a volume group, create a logical volume in the just created volume. We only need to format the logical volume now:

mkfs.ext4 -L a_name -m 0 /dev/vg_name/lv_name

I used -m 0 because this is an external drive and I don’t care about root reserved blocks. Remember also to backup your LUKS header (to a secure location and outside your encrypted partition obviously) because all your data will be lost if this header is destroyed:

cryptsetup luksHeaderBackup /dev/sd?? --header-backup-file backup_file