Disk encryption

Posted on 2010-08-23

This is just a quick reminder to mostly myself on what to do when installing a new disk. Note that all of the following commands need to be run as root/with sudo.

Begin by writing random data to the disk, this is very important, if it is skipped the security might be severely compromised. I use badblocks for this as /dev/urandom (and definitely /dev/random) is to slow to be practical (takes weeks, or years in the case of /dev/random).

badblocks -c 10240 -s -w -t random -v $DEVICE

Where -c sets the block size, -s shows the progress, -w sets badblocks to write mode, -t specifies the test pattern, in this case random and -v is verbose, naturally.

This usually takes a couple of hours.


Its not a good idea to use badblocks, instead use dd if=/dev/urandom of=$DEVICE. I was planning to do this in the future, and will give details on it once I do it. One cool thing is that its possible to run one instance of dd on each core you got, in your entire household. Its not that hard to use nc and help with the random generation over the network.

When done, we need to create a partition with fdisk


n - create new partition
w - write the partition table to disk and quit

I usually create just one partition that covers the whole disk, because I have no need for several partitions as most of my drives is used for storage.

Now we create the luks partition:

cryptsetup --verbose --verify-passphrase --key-size 128 luksFormat $DEVICE

i use 128 bits as it has been shown that it is more resistant to a brute-force attack then AES 192 and 256 bits. cryptsetup will ask for a pass phrase, I usually have this as a backup in case I loose my encryption key, like in a disk crash.

Lets add the encryption key.

cryptsetup luksAddKey $DEVICE $NEW_KEY_FILE

Now we open the luks device in order to format it.

cryptsetup luksOpen $DEVICE $DEVICE_NAME --key-file $KEY_FILE

This will create a new entry in /dev/mapper on which we will write the new file system.

Writing the file system:

mkfs.ext3 -L $DEVICE_LABEL -m 0 /dev/mapper/$DEVICE_NAME

The -m switch specifies how much space will be reserved for the super-user, as my drives is mostly for storage, he doesn't get any.

Now we just need to make sure the device is added automatically when we boot. We need to edit (add a new line) both /etc/crypttab and /etc/fstab in order to get this to work. The first file opens the luks devices and the second mounts the unencrypted devices in the file system.




/dev/mapper/$DEVICE_NAME    $MOUNT_POINT ext3   defaults    0   2

A tip is to get the device path from /dev/disk/by-id/, because then it doesn't matter where on your motherboard/controller card the drive is connected.

That should be all you need to know to get a proper setup with encrypted drives.