Updated 2 min read

Create an encrypted volume with LUKS

Keep sensitive files in a LUKS-encrypted volume on a single-disk VPS: create, open, close, and what it does and does not protect.

A VPS has one disk and our images cannot be installed with full-disk encryption. What you can do is keep your sensitive data inside an encrypted LUKS volume stored in a file. It is closed (unreadable) until you open it with a passphrase.

What it protects#

  • Copies of the disk image, or a disk that leaves the data center.
  • Backups of the volume file.

It does not protect data while the volume is open: root on the running server, and anyone with access to the machine's memory, can read it. Open the volume only while you work, and close it afterwards. Treat it as a lock on a drawer, not a vault.

Create it#

sudo apt install -y cryptsetup
sudo fallocate -l 5G /root/secure.img
sudo cryptsetup luksFormat /root/secure.img

Type YES in capitals and choose a long passphrase. Without it the data cannot be recovered. Then create the filesystem:

sudo cryptsetup open /root/secure.img secure
sudo mkfs.ext4 /dev/mapper/secure
sudo mkdir -p /mnt/secure
sudo mount /dev/mapper/secure /mnt/secure

Use it#

Open it when you need it:

sudo cryptsetup open /root/secure.img secure
sudo mount /dev/mapper/secure /mnt/secure

Close it when you are done:

sudo umount /mnt/secure
sudo cryptsetup close secure

Do not mount it at boot#

An automatic unlock needs the key on the same disk, which defeats the point. Open it by hand after each reboot. Services that use the volume must be started after you open it.

Back up the header#

Damage to the LUKS header makes the data unrecoverable. Save a copy off the server:

sudo cryptsetup luksHeaderBackup /root/secure.img --header-backup-file /root/secure.header

Move that file to your own computer, and keep it as safe as the passphrase: with the header and an old passphrase, someone can open the volume.

Make it bigger#

The volume does not grow by itself. Create a bigger one and copy the files across, or close it and extend the file:

sudo cryptsetup close secure
sudo truncate -s +2G /root/secure.img
sudo cryptsetup open /root/secure.img secure
sudo cryptsetup resize secure
sudo e2fsck -f /dev/mapper/secure
sudo resize2fs /dev/mapper/secure

Check you have the space with df -h first, and make a copy before resizing.

Related: back up your server with restic.

More in this section