Securing swap space content
In this lesson, you will learn how to protect the data stored in your virtual memory by implementing an encrypted swap file.
When your system runs low on RAM, the kernel "swaps" inactive memory pages to your storage drive. If that drive isn't encrypted, sensitive data—like passwords, encryption keys, or private documents—could be written to your disk in plain text. Even after a reboot, that data might persist in the swap file, creating a security vulnerability.
How encrypted swap works
To secure this, we use a mapping layer that encrypts data on the fly before it hits the disk. Instead of swapping directly to a static file or partition, we create a device mapper entry that uses a temporary, randomly generated key stored only in your volatile RAM. Because this key is discarded when the system powers off, any data remaining in the swap file becomes completely unreadable junk.
Implementation steps
If you are using a swap file, you can secure it by configuring dm-crypt (the Linux disk encryption framework) to handle the swap device. You typically do this via the /etc/crypttab file.
To set up an encrypted swap, you assign the swap partition or file a mapping name, point it to the device, use /dev/urandom as the key source, and specify the swap option:
# Example entry in /etc/crypttab
# <target name> <source device> <key file> <options>
swap_encrypted /dev/sdb1 /dev/urandom swap,cipher=aes-xts-plain64,size=256
Once this is defined, the system treats swap_encrypted as a secure block device. You then update your /etc/fstab to point to the mapped device (e.g., /dev/mapper/swap_encrypted) instead of the raw physical partition.
By using /dev/urandom, you ensure that the encryption key is unique to every single boot. This renders the swap content useless to anyone who might try to analyze the disk after the machine is turned off, providing a critical layer of defense for your system’s volatile memory footprint.
Key Takeaway: By mapping your swap space through an encrypted layer with a transient key, you ensure that sensitive virtual memory data is never stored in plain text on your physical disk.