Encrypt a swap partition

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

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 ...


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 cryptswap ...

# sgdisk -c 2:cryptswap /dev/sda

2. Crypttab

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

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

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

3. Fstab

Either modify an existing sway entry, or add the cryptswap entry in /etc/fstab ...

/dev/mapper/cryptswap 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: Install Debian 12 with encrypted Root-on-ZFS

« Previous: 8 things I do after installing FreeBSD