How to Set Up an Encrypted Swap File in Linux Using dm-crypt and crypttab

In modern Linux workstation and server environments, swap space plays an indispensable role in maintaining system responsiveness by paging out inactive memory blocks when physical RAM nears exhaustion. However, unencrypted swap spaces pose a severe security vulnerability. Whenever confidential credentials, private cryptographic keys, or sensitive browser data residing in volatile memory are swapped to disk, they are stored in plaintext on non-volatile storage. Configuring an encrypted swap space using the native Linux device-mapper cryptographic target (dm-crypt) ensures that every data block written to swap is encrypted on the fly with a fresh, volatile cipher key generated at boot.

Why Ephemeral Key Encryption Is Ideal for Swap

Unlike standard persistent partitions or home directories that require a passphrase or keyfile to decrypt data across reboots, swap space does not require data retention across power cycles (unless you utilise disk-based hibernation/suspend-to-disk). By using an ephemeral random key derived from the kernel random number generator (/dev/urandom), the encryption key is discarded upon shutdown. Even if an attacker physically extracts the storage drive or creates a block-level forensic clone, the contents of the swap file remain mathematically indecipherable.

Step 1: Create an Unformatted Raw Swap File

To begin, allocate a dedicated contiguous file on your root filesystem using the fallocate or dd utility. For example, to provision an 8 GB swap file:

sudo fallocate -l 8G /var/swapcrypt

If your underlying filesystem does not support fallocate (such as older ext3 or specific non-allocating btrfs subvolumes), use dd instead:

sudo dd if=/dev/zero of=/var/swapcrypt bs=1M count=8192 status=progress

Next, restrict access permissions so that only the root superuser can read or modify the raw container:

sudo chmod 600 /var/swapcrypt

Step 2: Attach the File to a Loopback Device

Because dm-crypt operates at the block-device layer rather than directly on virtual file nodes, you must associate the allocated file with a loop device:

sudo losetup -fP /var/swapcrypt

To confirm the assigned loop device name, run:

losetup -a

You will see output indicating your swap file is attached to a node such as /dev/loop0.

Step 3: Configure Automated Encryption via /etc/crypttab

The Linux system initialization daemon reads /etc/crypttab during early boot to construct encrypted virtual devices. Open the configuration file in your preferred terminal editor:

sudo nano /etc/crypttab

Append the following entry at the bottom of the file (replace /var/swapcrypt with your actual file path):

cryptswap /var/swapcrypt /dev/urandom cipher=aes-xts-plain64,size=512,swap,discard

Parameter breakdown:

  • cryptswap: The target mapping name that will appear under /dev/mapper/cryptswap.
  • /var/swapcrypt: The backing source file or block device.
  • /dev/urandom: Specifies that a newly randomised 512-bit AES key is generated on every system boot.
  • cipher=aes-xts-plain64: Uses the industry-standard AES cipher in XTS mode.
  • swap: Instructs the systemd-cryptsetup generator to format the decrypted container as a valid swap space automatically using mkswap.
  • discard: Enables TRIM commands for solid-state drives (SSDs).

Step 4: Mount Encrypted Swap via /etc/fstab

Once crypttab creates the mapped device, the operating system must mount it as active swap. Open your filesystem table:

sudo nano /etc/fstab

Add the following line:

/dev/mapper/cryptswap none swap defaults 0 0

Save the file and exit the editor.

Step 5: Initialise and Verify the Encrypted Swap Device

You can activate the encrypted mapping immediately without rebooting your machine:

sudo systemctl daemon-reload
sudo cryptdisks_start cryptswap || sudo systemctl restart [email protected]
sudo swapon /dev/mapper/cryptswap

To verify that your encrypted swap partition is active and properly mapped, run the swapon summary command:

swapon --show

The output will display /dev/dm-X or /dev/mapper/cryptswap listed as an active swap device with your configured partition size. You can also inspect the encryption parameters in detail using:

sudo cryptsetup status cryptswap

This command outputs the cipher type, key size, and active read/write sectors, confirming your memory paging is fully shielded against physical data extraction.

Frequently Asked Questions

Does encrypted swap reduce system performance?

Modern x86_64 and ARM processors include dedicated AES-NI hardware instruction sets. Because cryptographic calculations are executed directly within CPU registers with negligible overhead, throughput differences between plaintext and encrypted swap are virtually imperceptible in daily usage.

Can I use hibernation (suspend-to-disk) with an ephemeral encrypted swap?

No. When using /dev/urandom, the encryption key changes on every boot. Because the key generated during shutdown is discarded from RAM, the system cannot decrypt the hibernation image upon powering back on. If hibernation is required, you must configure a persistent keyfile stored inside an existing encrypted LUKS root container.

How do I safely disable and remove the encrypted swap file?

To decommission the encrypted swap, run sudo swapoff /dev/mapper/cryptswap, comment out or remove the corresponding lines from /etc/fstab and /etc/crypttab, and delete the backing file using sudo rm /var/swapcrypt.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.