Creating an encrypted swap file for Ubuntu using cryptsetup

Encrypting the swap space on any computer makes a lot of sense for anyone interested in security. The swap area always has a chance of containing sensitive user information that could easily be recovered from the disk. Furthermore, since swap storage does not need to be preserved across reboots it is trivial to use a random key, thus greatly decreasing the odds that any information can be recovered. The only downside that I’ve found on Ubuntu and other GNU/Linux operating systems is that there are too many ways to do encryption in general and swap in particular. But here is a relatively simple way to setup an encrypted swap file.

Of course, most Ubuntu users will have a swap partition instead so I’ll cover that as well. But for me I think the swap partition is a waste of space unless it is created with lvm so that it can be resized easily. The Linux kernel did have performance issues with using swap files at one point but those issues have long since been remedied. I have argued that at the point that the performance difference between a swap file and a swap partition are significant the system is already in trouble.

So here’s a simple formula for an encrypted swap file.

  • sudo apt-get install cryptsetup
  • dd bs=1M count=256 if=/dev/urandom of=/swapfile
    • This creates a 256MB file filled with pseudo-random data as /swapfile.
    • For improved security one could use /dev/random instead of /dev/urandom.
  • edit /etc/crypttab and add the line:
    cswap /swapfile /dev/urandom swap,cipher=aes-cbc-essiv:sha256

    • Using /dev/random instead of /dev/urandom will provide greater security.
  • edit /etc/fstab and add the line:
    /dev/mapper/cswap none swap sw 0 0
  • /etc/init.d/cryptdisks start
    • This will create the device /dev/mapper/cswap.
  • swapon -a
    • This will activate all swap entries in the /etc/fstab file including the one for dev/mapper/cswap
  • swapon -s
    • This shows a summary of all the swap devices. cat /proc/swaps would also work.

If one wanted to use a swap partition instead of a file all that would change is that there would be no reason to use dd to create a new file (though one may still want to use it to fill the swap partition with random data) and the column /swapfile in the /etc/crypttab file would need to be changed to the swap device name.

Creative Commons License Except where otherwise noted, content on this site is licensed under a Creative Commons by-nc-sa 3.0 License