How to encrypt swap on Ubuntu 12.04

Without going into particulars, it suffices to say that Ubuntu 12.04 has the following script that sets up encrypted swap:

ecryptfs-setup-swap

The normal output of this script:

WARNING:
An encrypted swap is required to help ensure that encrypted files are not leaked to disk in an unencrypted format.

HOWEVER, THE SWAP ENCRYPTION CONFIGURATION PRODUCED BY THIS PROGRAM WILL BREAK HIBERNATE/RESUME ON THIS SYSTEM!

NOTE: Your suspend/resume capabilities will not be affected.

Do you want to proceed with encrypting your swap? [y/N]: y

INFO: Setting up swap: [/dev/sda5]
WARNING: Commented out your unencrypted swap from /etc/fstab
 * Stopping remaining crypto disks...                                                                                         * cryptswap1 (stopped)...                                                                                            [ OK ]
 * Starting remaining crypto disks...                                                                                         * cryptswap1 (starting)..
 * cryptswap1 (started)...                                                                                            [ OK ]
INFO: Successfully setup encrypted swap!

To ensure that swap is working properly we can do the following:

fdisk -l

It should show something like /dev/mapper/cryptswap1:

Disk /dev/sda: 21.5 GB, 21474836480 bytes
255 heads, 63 sectors/track, 2610 cylinders, total 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00041a2a

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048    40105983    20051968   83  Linux
/dev/sda2        40108030    41940991      916481    5  Extended
/dev/sda5        40108032    41940991      916480   82  Linux swap / Solaris

Disk /dev/mapper/cryptswap1: 938 MB, 938475520 bytes
255 heads, 63 sectors/track, 114 cylinders, total 1832960 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x6943c31d

Disk /dev/mapper/cryptswap1 doesn't contain a valid partition table

Then we can check that changes are automatically applied to /etc/fstab configurations file. It also should contain this /dev/mapper/cryptswap1:

# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    nodev,noexec,nosuid 0       0
# / was on /dev/sda1 during installation
UUID=fcc47f97-2a8a-45e6-a389-15cff216f652 /               ext4    errors=remount-ro 0       1
# swap was on /dev/sda5 during installation
#UUID=4a885082-3ce6-4725-b536-97706162f6b9 none            swap    sw              0       0
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0
/dev/mapper/cryptswap1 none swap sw 0 0

and unencrypted swap should be commented out.

The same situation with /etc/crypttab:

# <target name> <source device>         <key file>      <options>
cryptswap1 /dev/sda5 /dev/urandom swap,cipher=aes-cbc-essiv:sha256

And finally

free -m

should show corresponding swap size:

             total       used       free     shared    buffers     cached
Mem:           495        320        175          0        125        111
-/+ buffers/cache:         82        413
Swap:          894          0        894

below I provided the source code of /usr/bin/ecryptfs-setup-swap script:

#!/bin/sh -e
#    ecryptfs-setup-swap
#    Copyright (C) 2008 Canonical Ltd.
#
#    Authors: Dustin Kirkland <kirkland@ubuntu.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; version 2 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# The cryptswap setup used here follows a guide published at:
#  * http://ubuntumagnet.com/2007/11/creating-encrypted-swap-file-ubuntu-using-cryptsetup

TEXTDOMAIN="ecryptfs-utils"

error() {
    echo `gettext "ERROR:"` "$@" 1>&2
    exit 1
}

info() {
    echo `gettext "INFO:"` "$@"
}

warn() {
    echo `gettext "WARNING:"` "$@" 1>&2
}

usage() {
    echo
    echo `gettext "Usage:"`
    echo "  $0 [-f|--force] [-n|--no-reload]"
    echo
    exit 1
}

# Handle command line options
FORCE=0
while [ ! -z "$1" ]; do
    case "$1" in
        -f|--force)
            FORCE=1
            shift 1
        ;;
        -n|--no-reload)
            NO_RELOAD=1
            shift 1
        ;;
        *)
            usage
        ;;
    esac
done

# Ensure that cryptsetup is available
[ -x /sbin/cryptsetup ] || error `gettext "Please install"` "'cryptsetup'"

# Ensure that we're running with root privileges
[ -w /etc/passwd ] || error `gettext "This program must be run with 'sudo', or as root"`

# Count swap spaces available
if [ $(grep -c "^/" /proc/swaps) -eq 0 ]; then
    mem=$(grep "^MemTotal:" /proc/meminfo | awk '{print $2}')
    swapsize=$((4*$mem))
    info "You do not currently have any swap space defined."
    echo
    echo `gettext "You can create a swap file by doing:"`
    echo " $ sudo dd if=/dev/zero of=/swapfile count=$swapsize"
    echo " $ sudo mkswap /swapfile"
    echo " $ sudo swapon /swapfile"
    echo
    echo `gettext "And then re-run"` "$0"
    echo
    exit 0
fi

swaps=$(grep "^/" /proc/swaps | awk '{print $1}')

filtered_swaps=$(
for swap in $swaps; do
    # Make sure this is swap space
    if [ "$(blkid -o value -s TYPE $swap)" != "swap" ]; then
        warn "[$swap]" `gettext "does not appear to be swap space, skipping."`
        continue
    fi
    
    if [ "${swap#/dev/ram}" != "$swap" ] || [ "${swap#/dev/zram}" != "$swap" ]; then
        warn "[$swap]" `gettext "is a RAM device, skipping."`
        continue
    fi

    # Check if this swap space is already setup for encryption
    if /sbin/dmsetup table "$swap" 2>/dev/null | grep -qs " crypt "; then
        warn "[$swap]" `gettext "already appears to be encrypted, skipping."`
        continue
    fi

    base=$(basename "$swap")
    if grep -qs "^$base.*swap.*cipher" /etc/crypttab 2>/dev/null; then
        warn "[$swap]" `gettext "already has an entry in /etc/crypttab, skipping."`
        continue
    fi
    if grep -qs "$swap" /etc/initramfs-tools/conf.d/cryptroot 2>/dev/null; then
        warn "[$swap]" `gettext "already has an entry in /etc/crypttab, skipping."`
        continue
    fi

    echo $swap
done
)
swaps="$filtered_swaps"
if [ -z "$swaps" ]; then
    warn "There were no usable swap devices to be encrypted.  Exiting."
    exit 0
fi
##########################################################################
# Warn the user about breaking hibernate mode
if [ "$FORCE" != 1 ]; then
    echo
    echo `gettext "WARNING:"`
    echo `gettext "An encrypted swap is required to help ensure that encrypted files are not leaked to disk in an unencrypted format."`
    echo
    echo `gettext "HOWEVER, THE SWAP ENCRYPTION CONFIGURATION PRODUCED BY THIS PROGRAM WILL BREAK HIBERNATE/RESUME ON THIS SYSTEM!"`
    echo
    echo `gettext "NOTE: Your suspend/resume capabilities will not be affected."`
    echo
    echo -n `gettext "Do you want to proceed with encrypting your swap?"` "[y/N]: "
    CONFIRM=`head -n1`
    echo
    if [ "$CONFIRM" != "y" -a "$CONFIRM" != "Y" ]; then
        echo
        info `gettext "Aborting."`
        echo
        exit 0
    fi
fi
##########################################################################


i=0
for swap in $swaps; do
    info `gettext "Setting up swap:"` "[$swap]"
    uuid=$(blkid -o value -s UUID $swap)
    for target in "UUID=$uuid" $swap; do
        if [ -n "$target" ] && grep -qs "^$target " /etc/fstab; then
            sed -i "s:^$target :\#$target :" /etc/fstab
            warn "Commented out your unencrypted swap from /etc/fstab"
        fi
    done

    while :; do
        i=$((i+1))
        [ -e "/dev/mapper/cryptswap$i" ] || break
    done
    # Add crypttab entry
    echo "cryptswap$i $swap /dev/urandom swap,cipher=aes-cbc-essiv:sha256" >> /etc/crypttab

    # Add fstab entry
    echo "/dev/mapper/cryptswap$i none swap sw 0 0" >> /etc/fstab
done

if [ "$NO_RELOAD" != 1 ]; then
    # Turn swap off
    swapoff -a

    # Restart cryptdisks
    /etc/init.d/cryptdisks restart

    # Turn the swap on
    swapon -a
fi

info `gettext "Successfully setup encrypted swap!"`

Leave a Reply

Your email address will not be published. Required fields are marked *