Encrypted Virtual Disk in Linux

In the last couple presentations we discussed how to create and mount virtual disks in Linux. Virtual disks can emulate a block based storage device inside of a single file. You can also create an encrypted virtual disk in Linux. We can use the Linux Unified Key Setup (LUKS) to create and access encrypted storage inside of a virtual disk.

Make sure that cryptsetup is installed on your system:

sudo apt install cryptsetup

Create a blank file to host the disk. In this example I create a 50MB file in the media folder.

sudo dd if=/dev/urandom of=/media/encrypted-disk.img bs=1M count=50

Set up encryption on the disk image file. There are other choices for the hash, key size and cipher that you can read about in the documentaiton:

sudo cryptsetup luksFormat --type=luks2 --hash=sha512 --key-size=512 --cipher=aes-xts-plain64 /media/encrypted-disk.img

Check to see that the disk image file is encrypted:

file /media/encrypted-disk.img

Connect/open the encrypted image file to be able to use it:

sudo cryptsetup luksOpen /media/encrypted-disk.img encrypted-disk

Check the status of the encrypted image now that we are connected to it:

sudo cryptsetup -v status encrypted-disk

Format the disk:

sudo mkfs.ext4 /dev/mapper/encrypted-disk

See that there is a file system on the disk:

ls -l /dev/mapper/encrypted-disk

Create a mount point for the disk:

sudo mkdir /mnt/encrypted-disk

Mount the disk using the mount point:

sudo mount /dev/mapper/encrypted-disk /mnt/encrypted-disk

I changed the file ownership to my account in order to be able to access the disk without sudo privilege:

sudo chown scott:scott /mnt/encrypted-disk

I moved to the mount point and created files inside the encrypted disk:

cd /mnt/encrypted-disk
mkdir test
touch a-file-test

To dismount the disk and disconnect from the encrypted access:

cd ~
sudo umount /mnt/encrypted-disk
sudo cryptsetup luksClose encrypted-disk

I demonstrated also that you cannot mount the disk directly without connecting it encrypted. This command fails:

sudo mount -o loop /media/encrypted-disk.img /mnt/encrypted-disk

To mount the existing encrypted disk:

sudo cryptsetup luksOpen /media/encrypted-disk.img encrypted-disk
sudo mount /dev/mapper/encrypted-disk /mnt/encrypted-disk

If you want to delete your encrypted disk and all the data in it including the mount point folder:

sudo umount /mnt/encrypted-disk
sudo cryptsetup luksClose encrypted-disk
sudo rm /media/encrypted-disk.img
sudo rmdir /mnt/encrypted-disk