Last Updated:

Encrypting your swap file on recent Debian or Ubuntu 18.04 based systems.

This quick guide is subject to the usual disclaimer. Use it at your own risk. :)

Why do it?

Depending on your system's configuration and utilization memory pages may get swapped out to disk by the kernel. This virtual memory has the potential to leak sensitive data or at least leave sensitive information behind on your drive(s) for a while. Swap does not get wiped upon shutdown. Now, if you encrypt the rest of your system but leave your swap file unencrypted then this becomes even more egregious. But by default most Linux distributions still don't encrypt their swap space.

So this post shows you how to change that.

Do you even swap (bro)?

How eagerly the Linux kernel moves pages to the swap space is controlled by the swappiness parameter. This can take a value between 0 (never swap) to 100 (swap as much as possible). The default is 60.

To set it permanently:

sudo vi /etc/sysctl.conf# add the line below to the file, 20 is an example value for little swappingvm.swappiness = 20

How do it?

First let's check whether you already have any swap partitions active.

cat /proc/swaps

If the command returns entries, consider taking note which partition or raid set they are located on. Then turn them off.

sudo swapoff -acat /proc/swaps

Should now return empty.

Going forward we assume you are starting from scratch but if you already have existing raid sets or fstab entries just update them accordingly.

  • For an encrypted single-disk swap:

# become root, then:apt install --yes cryptsetupecho swap ${DISK}-part2 /dev/urandom swap,cipher=aes-xts-plain64:sha256,size=512 >> /etc/crypttabecho /dev/mapper/swap none swap defaults 0 0 >> /etc/fstabswapon -a

  • For an encrypted mirror or raid topology:

# become root, then:apt install --yes cryptsetup mdadm# for e.g. a 2 drive /dev/disk/by-id/ata-HGST_HUS724020ALA640_PN000004440001ata-HGST_HUS724020ALA640_PN00000444DER3# so you don't have to deal with long path names in your commands# set up variables for the drive pathsDISK1=/dev/disk/by-id/ata-HGST_HUS724020ALA640_PN000004440001DISK2=/dev/disk/by-id/ata-HGST_HUS724020ALA640_PN00000444DER3# Adjust the level e.g. stripe, mirror, raid5, raid6, etc.. and# raid-devices as necessary and specify the actual devices.# assuming swap will be on partition 2 on each drive:mdadm --create /dev/md0 --metadata=1.2 --level=mirror --raid-devices=2 ${DISK1}-part2 ${DISK2}-part2echo swap /dev/md0 /dev/urandom swap,cipher=aes-xts-plain64:sha256,size=512 >> /etc/crypttabecho /dev/mapper/swap none swap defaults 0 0 >> /etc/fstabswapon -a

There you go, enjoy!