Recently, I decided to encrypt the VPSes of Project Segfault, as it coincided with the migration of one of our servers, our EU node.
However, while moving our US node, we faced a few problems, in the fact that I didn’t want to wipe the disk, nor did I want to do some jank stuff like reinstalling debian and then replacing the files.
Therefore, my only solution came down to creating a new encrypted partition, copying the entire directory tree of the old partition to the new one via rsync, and then making grub and co. point to the new stuff.
So, in order to do this, you first need to shrink your existing partition so you can create the new one, which I did using GParted on the GParted LiveCD.
Past that, you have to create the new primary partition in the empty space created, which I did via CFDisk, since GParted requires you to format while creating a partition (from what I could see), and it doesn’t support creating LUKS partitions.
Additionally, since you can’t use the “good” PBKDF, argon2i(d) (which is more secure and gives faster speeds) with the current version of grub available on Debian 12, you have to move boot to a separate unencrypted partition. This can be done by merely creating a new ~512 MiB ext2 primary partition via GParted
Past this, I had to create the LUKS stuff. To do so, I ran the following commands:
# Format partition as LUKS encrypted
cryptsetup luksFormat --type luks2 --pbkdf argon2i /dev/DEVICE
# Open partition, and map it to /dev/mapper/crypt
cryptsetup luksOpen /dev/DEVICE crypt
# Overwrite the entire device with 0s, just to be a bit more secure
dd if=/dev/zero of=/dev/mapper/crypt status=progress bs=4096
# Create ext4 partition on the mapped device
mkfs.ext4 /dev/mapper/crypt
Then, to copy the content to the new partition, I used the following commands:
mkdir -p /mnt/{old,new}
mount /dev/OLD_DEVICE /mnt/old
mount /dev/mapper/crypt /mnt/new
mkdir -p /mnt/new/boot
mount /dev/BOOT_DEVICE /mnt/new/boot
rsync -av /mnt/old/* /mnt/new
After all the data is copied, I need to enter a chroot environment in order to configure a few more things. This is done through the following commands:
mount -t sysfs /sys /mnt/new/sys/
mount -t proc /proc /mnt/new/proc/
mount --rbind /dev /mnt/new/dev/
chroot /mnt/new
Inside the chroot environment, you need to first install some cryptsetup related stuff, and then update the fstab file:
apt install cryptsetup cryptsetup-initramfs
/etc/crypttab (the file which tells the system what encrypted partitions to mount):
crypt UUID=UUID_OF_PARTITION_FROM_BLKID none luks,discard
/etc/fstab:
/dev/mapper/crypt / ext4 rw 0 1
/dev/BOOT_PARTITION /boot ext2 rw 0 1
Past this, you need to reinstall grub:
grub-install /dev/DISK # for legacy BIOS, note this is the disk not the partition (ie. /dev/vda not /dev/vda1)
update-grub
And that should be it, once you reboot, you should boot into a password prompt, past which you can boot into your newly encrypted system!
PS: don’t forget to remove the old partition :D