Encrypt a swap partition

Last edited on 2023-12-22 Tagged under  #linux   #encrypt 

An encrypted Linux system that include an unencrypted swap partition may experience all sorts of sensitive information that gets passed to swap that survives a reboot. Best practice is to encrypt the swap partition as well.

The /etc/crypttab file can be configured to set up swap with a randomly generated password with plain dm-crypt at boot. Any Linux partition can be used for swap and there is no need to run mkswap to configure it beforehand. Upon shutdown, the password is discarded and the contents of the partition remain encrypted and inaccessible.

This is how I do it...

1. PARTLABEL

Disk sda in this example uses a GPT partition table.

All contents of the encrypted swap will be deleted.

When identifying the partition to be used as encrypted swap, avoid using simple partition names (e.g /dev/sda2, /dev/nvme0p3) because their order can change. UUIDs cannot be used, because they change with every recreation and re-encryption of swap on every boot.

Instead, I use GPT partition labels (PARTLABEL) to identify the swap partition to the system. A PARTLABEL is set in the header of the partition entry on GPT disks and is unaffected when the file system on the partition is changed.

All partitions that have partition labels are listed in the /dev/disk/by-partlabel directory:

$ ls -al /dev/disk/by-partlabel/
total 0
drwxr-xr-x 2 root root 100 Dec 21 15:29 .
drwxr-xr-x 8 root root 160 Dec 21 15:29 ..
lrwxrwxrwx 1 root root  10 Dec 21 15:29 esp -> ../../sda1
lrwxrwxrwx 1 root root  10 Dec 21 15:29 swap -> ../../sda2
lrwxrwxrwx 1 root root  10 Dec 21 15:29 root -> ../../sda3

In this example partition sda2 has the PARTLABEL swap.

If the labels do not currently exit - or to change a label name - a new label can be set using the sgdisk command as root with the syntax...

sgdisk -c <partition_number>:<partlabel> <disk>

Example: Change the second partition on /dev/sda to swap:

# sgdisk -c 2:swap /dev/sda

2. Crypttab

Using the above swap as swap partition PARTLABEL, add to /etc/crypttab:

# echo "swap PARTLABEL=swap /dev/urandom swap,offset=2048,cipher=aes-xts-plain64,size=512" >> /etc/crypttab

This will map /dev/disk/by-partlabel/swap to /dev/mapper/swap as a swap partition that can be added in /etc/fstab like a normal swap.

3. Fstab

Either modify an existing swap entry, or add the new entry in /etc/fstab:

/dev/mapper/swap    none    swap    defaults    0 0

4. Resources

You can like, share, or comment on this post on Mastodon 💬

Thanks for reading! Read other posts?

» Next: Roll your own Linux desktop using Sway

« Previous: 8 things I do after installing FreeBSD