Encrypting root on an existing Debian lenny installation

Once in a time, I get to travel to places that make me worry about the data on my laptop. This time, it is not the US, but another openly democratic country where they kill you for a joint, let alone nude pictures. Enough politics, though.

I have a laptop with the /boot in a separate partition, followed by a /root partition and a /swap. Having a separate /boot is mandatory, as the BIOS has to load an unencrypted kernel and its initrd before being able to access the encrypted partition. Another option is to keep /boot on a USB stick, but its setup can take a whole other post.

First things first, let us install software for managing encrypted disks and updating the initrd image:

aptitude install cryptsetup initramfs-tools

We have to make sure that the encryption modules are present on the initrd, so I add the following three modules to the initrd config:

echo aes-i586 >>/etc/initramfs-tools/modules
echo dm-crypt >>/etc/initramfs-tools/modules
echo dm-mod >>/etc/initramfs-tools/modules

Next step is to inform cryptsetup and inittab of the partition mapping between /dev/hda2 (the physical device) and /dev/mapper/root (its encryption interface).

echo "root /dev/hda2 none luks" >>/etc/crypttab
sed -i 's#/dev/hda2#/dev/mapper/root#' /etc/fstab

We also have to change the root device for grub the same way we did it for inittab:

sed -i 's#/dev/hda2#/dev/mapper/root#' /boot/grub/menu.lst

Now, recreate the initrd image by issuing

 update-initramfs -k all -u

We are now ready to shutdown and to boot from a LiveCD in order to make a backup, create an encrypted partition and copy back the root filesystem contents on an already encrypted partition. I leave the reader at the exercise of choosing available backup options. A simple cp -ax /mnt/root/* /mnt/backup command will be enough to backup, though.

Once the backup is ready, erase the data on the partition by issuing

shred -n1 /dev/hda2

and then create the encrypted partition with

cryptsetup luksFormat /dev/hda2
cryptsetup luksOpen /dev/hda2 root

After the encrypted device is set up and open, create a filesystem, mount it and copy the backup of the root partition to the encrypted device.

mkfs.ext3 /dev/mapper/root
mount /dev/mapper/root /mnt/root
cp -ax /mnt/backup/* /mnt/root

You are now ready to boot into the encrypted root partition.

Once the root encryption works, addding swap encryption is a piece of cake. Just add it to crypttab and modify the fstab accordingly:

echo "swap /dev/hda3 /dev/random swap" >>/etc/crypttab
sed -i 's#/dev/hda3#/dev/mapper/swap#' /etc/fstab