How to Setup Encrypted Filesystems and Swap Space Using ‘Cryptsetup’ Tool in Linux – Part 3

A LFCE (short for Linux Foundation Certified Engineer​) is trained and has the expertise to install, manage, and troubleshoot network services in Linux systems, and is in charge of the design, implementation and ongoing maintenance of the system architecture.

Linux Hard Disk Encryption
Linux Filesystem Encryption

Introducing The Linux Foundation Certification Program (LFCE).

The idea behind encryption is to allow only trusted persons to access your sensitive data and to protect it from falling into the wrong hands in case of loss or theft of your machine / hard disk.

In simple terms, a key is used to “lock” access to your information, so that it becomes available when the system is running and unlocked by an authorized user. This implies that if a person tries to examine the disk contents (plugging it to his own system or by booting the machine with a LiveCD/DVD/USB), he will only find unreadable data instead of the actual files.

In this article we will discuss how to set up encrypted file systems with dm-crypt (short for device mapper and cryptographic), the standard kernel-level encryption tool. Please note that since dm-crypt is a block-level tool, it can only be used to encrypt full devices, partitions, or loop devices (will not work on regular files or directories).

Preparing A Drive / Partition / Loop Device for Encryption

Since we will wipe all data present in our chosen drive (/dev/sdb), first of all, we need to perform a backup of any important files contained in that partition BEFORE proceeding further.

Wipe all data from /dev/sdb. We are going to use dd command here, but you could also do it with other tools such as shred. Next, we will create a partition on this device, /dev/sdb1, following the explanation in Part 4 – Create Partitions and Filesystems in Linux of the LFCS series.

# dd if=/dev/urandom of=/dev/sdb bs=4096 
Testing for Encryption Support

Before we proceed further, we need to make sure that our kernel has been compiled with encryption support:

# grep -i config_dm_crypt /boot/config-$(uname -r)
Check  Encryption Support in Linux
Check Encryption Support

As outlined in the image above, the dm-crypt kernel module needs to be loaded in order to set up encryption.

Installing Cryptsetup

Cryptsetup is a frontend interface for creating, configuring, accessing, and managing encrypted file systems using dm-crypt.

# aptitude update && aptitude install cryptsetup 		[On Ubuntu]
# yum update && yum install cryptsetup 				[On CentOS] 
# zypper refresh && zypper install cryptsetup 			[On openSUSE]

Setting Up an Encrypted Partition

The default operating mode for cryptsetup is LUKS (Linux Unified Key Setup) so we’ll stick with it. We will begin by setting the LUKS partition and the passphrase:

# cryptsetup -y luksFormat /dev/sdb1
Creating an Encrypted Partition
Creating an Encrypted Partition

The command above runs cryptsetup with default parameters, which can be listed with,

# cryptsetup --version
Cryptsetup Parameters
Cryptsetup Parameters

Should you want to change the cipher, hash, or key parameters, you can use the –cipher, –hash, and –key-size flags, respectively, with the values taken from /proc/crypto.

Next, we need to open the LUKS partition (we will be prompted for the passphrase that we entered earlier). If the authentication succeeds, our encrypted partition will be available inside /dev/mapper with the specified name:

# cryptsetup luksOpen /dev/sdb1 my_encrypted_partition
Encrypted Partition
Encrypted Partition

Now, we’ll format out partition as ext4.

# mkfs.ext4 /dev/mapper/my_encrypted_partition

and create a mount point to mount the encrypted partition. Finally, we may want to confirm whether the mount operation succeeded.

# mkdir /mnt/enc
# mount /dev/mapper/my_encrypted_partition /mnt/enc
# mount | grep partition
Mount Encrypted Partition in Linux
Mount Encrypted Partition

When you are done writing to or reading from your encrypted file system, simply unmount it

# umount /mnt/enc

and close the LUKS partition using,

# cryptesetup luksClose my_encrypted_partition
Testing Encryption

Finally, we will check whether our encrypted partition is safe:

1. Open the LUKS partition

# cryptsetup luksOpen /dev/sdb1 my_encrypted_partition

2. Enter your passphrase

3. Mount the partition

# mount /dev/mapper/my_encrypted_partition /mnt/enc

4. Create a dummy file inside the mount point.

# echo “This is Part 3 of a 12-article series about the LFCE certification” > /mnt/enc/testfile.txt

5. Verify that you can access the file that you just created.

# cat /mnt/enc/testfile.txt

6. Unmount the file system.

# umount /mnt/enc

7. Close the LUKS partition.

# cryptsetup luksClose my_encrypted_partition

8. Try to mount the partition as a regular file system. It should indicate an error.

# mount /dev/sdb1 /mnt/enc
Test Encryption on Partition
Test Encryption on Partition

Encryptin the Swap Space for Further Security

The passphrase you entered earlier to use the encrypted partition is stored in RAM memory while it’s open. If someone can get his hands on this key, he will be able to decrypt the data. This is especially easy to do in the case of a laptop, since while hibernating the contents of RAM are kept on the swap partition.

To avoid leaving a copy of your key accessible to a thief, encrypt the swap partition following these steps:

1 Create a partition to be used as swap with the appropriate size (/dev/sdd1 in our case) and encrypt it as explained earlier. Name it just “swap” for convenience.’

2.Set it as swap and activate it.

# mkswap /dev/mapper/swap
# swapon /dev/mapper/swap

3. Next, change the corresponding entry in /etc/fstab.

/dev/mapper/swap none        	swap	sw          	0   	0

4. Finally, edit /etc/crypttab and reboot.

swap               /dev/sdd1         /dev/urandom swap

Once the system has finished booting, you can verify the status of the swap space:

# cryptsetup status swap
Check Swap Encryption Status
Check Swap Encryption Status

Summary

In this article we have explored how to encrypt a partition and swap space. With this setup, your data should be considerably safe. Feel free to experiment and do not hesitate to get back to us if you have questions or comments. Just use the form below – we’ll be more than glad to hear from you!

Gabriel Cánepa
Gabriel Cánepa is a GNU/Linux sysadmin and web developer from Villa Mercedes, San Luis, Argentina. He works for a worldwide leading consumer product company and takes great pleasure in using FOSS tools to increase productivity in all areas of his daily work.

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

16 thoughts on “How to Setup Encrypted Filesystems and Swap Space Using ‘Cryptsetup’ Tool in Linux – Part 3”

    • Who said they were the same? Doing a yum update before installing a package in a CentOS system is a matter of personal preference. I also use to do aptitude update for a different reason, yes – but again it’s also a personal preference.

      Reply
  1. Hi
    I tried to execute the command cryptsetup –version but it only results in
    cryptsetup 1.6.6. I am using Ubuntu 16.0.4 Server version. Did I miss anything>?

    Reply
  2. Hi ,

    I’ve managed to get the encrypted swap auto mounted in OpenSuSE 13.2 (not secure as we use a key from from local system.Prefer to use interactive setup at boot )

    * cruptsetup luksFormat /dev/
    * dd if=/dev/urandom of=/etc/en_key bs=1024 count=4
    * cryptsetup luksAddKey /dev/ /etc/en_key
    * en_swap /dev/ /etc/en_key swap # in /etc/crypttab
    * /dev/mapper/en_swap swap swap sw,pri=1 0 0 # in /etc/fstab
    * Enable verbose logging at boot (/etc/default/grub – GRUB_CMDLINE_LINUX_DEFAULT=”….. splash=verbose loglevel=3″)

    Reply
  3. Did you test what you wrote on a real server? The instructions to setup a encrypted swap partition don’t work at all (at least in Ubuntu). Also, it’s not clear how do you create the encrypted device in the case of the swap partition, do you use a passphrase? what happens when you use /dev/urandom in /etc/crypttab?

    Reply
    • @toshiro,
      Yes, I did test what I wrote on a real server. As you can see in the screenshots, I used a box named dev2 which was a Debian Wheezy 7.5 system. You use a passphrase to encrypt / decrypt a partition, as explained in this article. Such passphrase is not used to encrypt / decrypt the swap partition, but you need to create a separate one for that (or you can make it the same – it’s entirely up to you). As for the use of /dev/urandom in /etc/crypttab, you can refer to man crypttab here: http://linux.die.net/man/5/crypttab.

      Reply
  4. Please is “Encryptin the Swap Space” part of the LFCE blueprint? The blueprint seems a bit loose or did you just decided to add swap aspect?

    Thanks!!

    Reply
  5. There is an an area I found to be unclear that caused me hours of headache. In item one of the swap file encryption section the instructions indicate “and encrypt it as explained earlier'” I was never able to get the swap file to mount on reboot because of the luks format pass phrase. A helpful addition to the article may be to explain the difference between a plain dm_crypt and luks format. It took some trial and error once I figured out that difference, but instructions 2-4 in the swap file setup work flawlessly once the concept of plain encryption is understood.

    Reply
  6. Great series of articles, wish I’d found them earlier :)
    “Configure systems to mount standard, encrypted and network file systems on demand” is one of the listed competencies on the LF’s website but I’m a little confused about what is meant by that and I notice you don’t show an fstab entry for the newly created encrypted partition. Is this intentional?

    Reply
  7. @Pim,
    Thank you for your comment. You are correct in that you mention yet another setup alternative for file sustem encryption but please note that LVM is out of the scope of the LFCE requirents.

    Reply
  8. I personally prefer LVM v2 under LUKS encrypted disk space. I have used this for may years now.

    The thing to be carefull about is the partion ids being used. Particularly x’85’ for your extended partion – keeps Windows away – and x’FC’ – as stated on the man page – for your encrypted data.

    Something else, I regularly trip over is the diferences between implementations of LVM. particularly, -M or fixed node numbers. The same is true with extfs(4). NB: The man page has dropped the description of –major, but it is still required with -M, but is ignored.

    Reply

Got something to say? Join the discussion.

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.