Linux swap file and encrypted volumes

encrypted

As with the last post, this seems like two pretty different subjects, a swap file and encrypted volumes, but for me it makes sense, because it’s all in preparation for the LFCS exam as mentioned here and here.

First I want to make a small addendum on the creation of swap space; this time a swap file instead of a whole partition. Next I want to describe how to make an encrypted volume with standard Linux tools.

As part of the exam, we need to be able to create a swap file as well, in contrast to a swap partition. This of course uses a lot of the same tools, but to create the file itself, needs some extra attention.

We can use the simple ‘fallocate’ command:

# fallocate -l 2G /swap

But while writing this post, I discovered that this is not recommended in many cases. You can read this in the man page of ‘swapon’, at ‘Notes’.

This is why we’re using the bit more cumbersome ‘dd’ command. Let’s create a 2GB swap file in root named simply ‘swap’:

# dd if=/dev/zero of=/swap bs=1024 count=2097152

As you can see it is a bit more difficult because we have to specify the block size and count and have to calculate how to get to 2GB. You can use this awesome tool though to do so.

Prepare the file for swapping:

# chmod 600 /swap 
# mkswap -L swapfile /swap

Enable it and check:

# swapon /swap
# swapon
# free -h
# cat /proc/swaps

Set it on boot by adding it to the /etc/fstab file:

/swap	none	swap	defaults	0	0

When you have defined your swap space in the fstab file, you can also use these commands to turn swap on and off:

# swapon -a
# swapoff -a

That’s a lot of text for something pretty simple.

On with encrypted volumes. I’m again using a small 1GB drive that is on /dev/sdg for me.

Let’s prep the device with the ‘cryptsetup’ utility that is standard in my Ubuntu 18.04 installation:

# cryptsetup -y luksFormat /dev/sdg

Like the warning says, contents will be lost so use a clean drive:

WARNING!
========
This will overwrite data on /dev/sdg irrevocably.

Are you sure? (Type uppercase yes): YES

Type in your passphrase twice. Next is to create a mapping (I’m naming it ‘secret’) in /dev/mapper:

# cryptsetup luksOpen /dev/sdg secret

Finally we can low level the mapping, create a filesystem and mount it:

# dd if=/dev/urandom of=/dev/mapper/secret status=progress
# mkfs.ext4 /dev/mapper/secret
# mkdir -p /mnt/secret
# mount /dev/mapper/secret /mnt/secret/

This ‘warning’ after the above ‘dd’ command is normal:

dd: writing to '/dev/mapper/secret': No space left on device

Checks:

# df -h
# mount

Unmount:

# umount /mnt/secret
# cryptsetup luksClose secret

Remount:

# cryptsetup luksOpen /dev/sdg secret
# mount /dev/mapper/secret /mnt/secret/

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.