For the main {{ic|cryptdevice}} configuration options before the {{ic|:allow-discards}} please refer to the sections following.

+

For the main {{ic|cryptdevice}} configuration options before the {{ic|:allow-discards}} please refer to the sections following. Besides the kernel option, it is also required to mount the filesystem (e.g. {{ic|/dev/mapper/root}} in this example) with the {{ic|discard}} option in {{ic|/etc/fstab}}. For details, please refer to the [[SSD#TRIM|SSD]] page.

This article focuses on how to set up full system encryption on Arch Linux, using dm-crypt with LUKS.

dm-crypt is the standard device-mapper encryption functionality provided by the Linux kernel. It can be used directly by those who like to have full control over all aspects of partition and key management.

LUKS is an additional convenience layer which stores all of the needed setup information for dm-crypt on the disk itself and abstracts partition and key management in an attempt to improve ease of use.

Caveats

This article or section is out of date.

Reason: As of the 2012.07.15 installation media release, AIF (the Arch Installation Framework) is no longer included but instead Arch Install Scripts are provided to aid in the installation process. A lot of content still has to get updated all over this page. Many external links are old so that they may not include all noticeable changes in Arch Linux configs. Just keep that in mind while reading. (Discuss in Talk:Dm-crypt#)

Initial Setup

Overview and Preparation

The installation of a LUKS-encrypted system is largely the same as installing an unencrypted system. Routine creation of an encrypted system follows these general steps:

This page covers the first two points in a general way for different configuration options available with LUKS.

The third and fourth point are covered in the later sections. Since the Arch installation media comes with all the tools required for system encryption, you can follow the Installation Guide or the Beginners' Guide after the encrypted partitions are set up. You will have to adjust the system configuration to be able to boot from your LUKS-volumes though.

Warning: Encrypting a partition will erase everything currently on that partition. Please make appropriate data backups prior to starting.

Secure erasure of the hard disk drive

Note: The following methods are specifically to dm-crypt/LUKS. For detailed instructions on how to erase and prepare a drive consult: Securely wipe disk

Before encrypting a drive, you should perform a secure erase of the disk by overwriting the entire drive with random data. To prevent cryptographic attacks or unwanted File Recovery, this data should be completely indistinguishable from all data later written by dm-crypt.

In deciding which method to use for secure erasure of a hard disk drive, remember that this will not need to be performed more than once for as long as the drive is used as an encrypted drive.

Use LUKS container as pseudorandom number generator (alternate)

The cryptsetup FAQ mentions a very simple procedure to use an existing dm-crypt-volume to wipe all free space accessible on the underlying block device with random data by acting as a simple pseudorandom number generator. It is also claimed to protect against disclosure of usage patterns.

# dd if=/dev/zero of=/dev/mapper/luks-container

Wipe free space with encrypted file after Installation

The same effect can be achieved if a file is created on each encrypted partition that fills the partition completely after the system is installed, booted and filesystems mounted. That is because encrypted data is indistinguishable from random.

Obviously the above process has to be repeated for every container created.

Wipe LUKS keyslots

#cryptsetup luksKillSlot <device> <key slot number>

This will only wipe a single keyslot.

Wipe LUKS header

The partitions formatted with dm-crypt/LUKS contain a header with the cipher and crypt-options used, which is referred to dm-mod when opening the blockdevice. After the header the actual random data partition starts. Hence, when de-commissioning a drive (e.g. sale of PC, switch of drives, etc.) it may be just enough to wipe the header of the partition, rather than overwriting the whole drive - which can be a lengthy process.

Wiping the LUKS header will delete the PBKDF2-encrypted (AES) master key, salts and so on.

Note: It is crucial to write to the LUKS encrypted partition (/dev/sda1 in this example) and not directly to the disks device node. If you did set up encryption as a device-mapper layer on top of others, e.g. LVM on LUKS on RAID then write to RAID respectively.

A header with one single default 256 bit size keyslot is 1024KB in size. It is advised to also overwrite the first 4KB written by dm-crypt, so 1028KB have to be wiped. That is 1052672 Byte.

For zero offset use:

#head -c 1052672 /dev/zero > /dev/sda1; sync

For 512 bit key length (e.g. for aes-xts-plain with 512 bit key) the header is 2MB.

If in doubt, just be generous and overwrite the first 10MB or so.

#dd if=/dev/zero of=/dev/sda1 bs=512 count=20480

Note: With a backup-copy of the header data can get rescued but the filesystem was likely damaged as the first encrypted sectors were overwritten. See further sections on how to make a backup of the crucial header blocks.

When wiping the header with random data and the header is followed by encrypted data written ontop random data everything left is random data.

Discard/TRIM support for solid state disks (SSD)

Solid state disk users should be aware that by default, Linux's full-disk encryption mechanisms will not forward TRIM commands from the filesystem to the underlying disk. The device-mapper maintainers have made it clear that TRIM support will never be enabled by default on dm-crypt devices because of the potential security implications.

Most users will still want to use TRIM on their encrypted SSDs. Minimal data leakage in the form of freed block information, perhaps sufficient to determine the filesystem in use, may occur on devices with TRIM enabled. An illustration and discussion of the issues arising from activating TRIM is available in the blog of a cryptsetup developer.

As a semi-tangential caveat, it is worth noting that because TRIM provides information to the disk firmware about which blocks contain data, encryption schemes that rely on plausible deniability, like TrueCrypt's hidden volumes, should never be used on a device that utilizes TRIM. This is probably also valid for TC containers within a LUKS encrypted device that uses TRIM.

TrueCrypt's developers also recommend against using any TC volume on a device that performs wear-leveling techniques to extend the life of the disk; most flash devices, including SSDs and USB flash drives, use mandatory wear-leveling at the firmware level. LUKS devices are probably not vulnerable to problems with wear-leveling if the entire device is blanked before the LUKS partition is initialized. See http://www.truecrypt.org/docs/?s=trim-operation and http://www.truecrypt.org/docs/?s=wear-leveling for more information.

In linux 3.1 and up, support for dm-crypt TRIM pass-through can be toggled upon device creation or mount with dmsetup. Support for this option also exists in cryptsetup version 1.4.0 and up. To add support during boot, you will need to add :allow-discards to the cryptdevice option. The TRIM option may look like this:

cryptdevice=/dev/mapper/root:root:allow-discards

For the main cryptdevice configuration options before the :allow-discards please refer to the sections following. Besides the kernel option, it is also required to mount the filesystem (e.g. /dev/mapper/root in this example) with the discard option in /etc/fstab. For details, please refer to the SSD page.

Partitioning

After the drive has been securely overwritten, it is time to create partitions and begin setting up an encrypted system.

LUKS is compatible with systems that require LVM and/or RAID as well as with with standard primary, extended, and logical partitions.

Standard Partitions

These are the partitions that most people are familiar with. They come in three flavors: primary partitions, extended partitions, and logical partitions.

Primary Partitions

These are the normal partitions recognized by the system BIOS. There can be up to four of these stored in the MBR.

Extended Partitions

These are primary partitions that also define another partition within themselves. Extended partitions were created to work around the original limit of four primary partitions.

Logical Partitions

These are the partitions that are defined within extended partitions.

LVM: Logical Volume Manager

The LVM allows for creation of volume groups for systems that require complex combinations of multiple hard disk drives and partitions that are not possible with standard partitions. LVM is covered in detail in the Article on LVM which is recommended reading prior to continuing with the instructions on setting up LUKS with LVM located below.

Tip: Btrfs has a built-in Subvolume-Feature that fully replaces the need for LVM if no other filesystems are required. An encrypted swap is not possible this way and swap files are not supported by btrfs up to now.

Reason: Due to uncomprehensible disarrangement this small section on stacking of device-mapper layers was overcomplicated to read. Now different setups are seperated by subsection-headings, nevertheless language and content still need improvement and duplicates should get deleted. (Discuss in Talk:Dm-crypt#)

LVM on LUKS

There is a growing preference towards logical volume management of LUKS encrypted physical media (LVM on LUKS). The deployment of LVM on LUKS is considered much more generalizable. In a LVM on LUKS scenario, the LUKS-partition has to be opened and mapped before LVM can access the underlaying setup volumes.

One reason for this is that using LUKS as the lowest level of infrastructure most closely approximates the deployment of physical disks with built-in hardware encryption. In that case, logical volume management would be layered on top of the hardware encryption - usage of LUKS would be superfluous.

LUKS on LVM

It is possible there may exist usage scenarios where encrypting logical volumes rather than physical disks is required (LUKS on LVM).
A usage scenario for LUKS on LVM exists where utmost flexibility for assigning available diskspace or a mix of unencrypted and encrypted volumes is desired. Upon boot the LVM is setup and assigned before the LUKS-encrypted volumes are opened. In order to manage changes of volumes in a LUKS on LVM setup, both module layers' setup have to be taken into account, i.e. shrinking or expanding an encrypted volume has to include the resizing of the encrypted LUKS blockdevice to ensure integrity of it and the filesystem. That said, in simpler scenarios the usage of LVM may be superfluous.

Creating Disk Partitions

Disk partitions are created using:

# cfdisk

This will display a graphical interface for creating disk partitions.

There are two required partitions for any encrypted system:

root file system

/ Will be encrypted and store all system and user files (/usr, /bin, /var, /home, etc.)

initial boot partition

/boot Will not be encrypted; the bootloader needs to access the /boot directory where it will load the initramfs/encryption modules needed to load the rest of the system which is encrypted (see Mkinitcpio for details). For this reason, /boot needs to reside on its own, unencrypted partition.

Single Disk Systems

Depending on the system demands, there may be additional partitions desired. These partitions can be individually created at this level by defining separate primary or extended/logical partitions. However, if LVM is to be used, the space unoccupied by /boot and swap should be defined as single large partition which will be divided up later at the LVM level.

Multiple Disk Systems

In systems that will have multiple hard disk drives, the same options exist as a single disk system. After the creation of the /boot and swap partitions, the remaining free space on physical disks can divided up into their respective partitions at this level, or large partitions can define all free space per physical disk with intent to partition them within the LVM.

Configuring LUKS

This section covers how to manually utilize LUKS from the command line to encrypt a system.

Mapping Physical Partitions to LUKS

After writing the partition table to the MBR (optionally set up LVM thereafter) the next step is to create the LUKS and dm-crypt magic and make device mapper mount it to the filesystem of the installation system.

When creating LUKS partitions they must be associated with a key. The key is used to unlock the header of the LUKS-encrypted partitions.

A key is either a:

Passphrase

Keyfile

It is possible to define up to 8 different keys per LUKS partition. This enables the user to create access keys for save backup storage. Also a different key-slot could be used to grant access to a partition to a user by issuing a second key and later revoking it again without the need to re-encrypt the partition. Having in mind that further passphrases or keyfiles can be added later easily at any time might make the choice for the initial key easier.

Using LUKS to Format Partitions with a Passphrase

Note: Using a passphrase to decrypt LUKS partitions automatically from /etc/crypttab is deprecated.

Cryptsetup is used to interface with LUKS for formatting, mounting and unmounting encrypted partitions.

Using a hash stronger than sha1 results in less iterations if iter-time is not increased.

--use-random

--use-urandom

/dev/urandom is used as randomness source for the (long-term) volume master key.

--use-random

Avoid generating an insecure master key if low on entropy. Will block if the entropy pool is used up.

--verify-passphrase, -y

Yes

Default only for luksFormat and luksAddKey.

-

No need to type for archlinux at the moment.

Please note that the above compares historic cryptsetup defaults in the left column. With release 1.6.0 the defaults have changed to an AES cipher in XTS mode, but with other options than the right column example (e.g. an effective key-size of 128-bit). The defaults can be checked with the tail output of

# cryptsetup --help

When deciding on the encryption cipher to use during blockdevice creation, it has to be taken into account that a number of the options stated affect system performance just for creating the initial crypt-blockdevice or opening it, but not the crypto and disk-io operations when the system is running. The throughput and security of the crypted data itself depends on the cipher and key-size. The used hash, iteration-time and random source options affect the cryptographic security of the master-key creation and processing time needed to unlock it in the future.

A full list of options cryptsetup accepts can be found in the manpage. Furthermore, cryptsetup now has a feature to benchmark the crypto performance of the processor:

# cryptsetup benchmark

can give guidance on deciding for a cipher to use prior to installation.

In the following examples for creating LUKS partitions, we will use the AES cipher in XTS mode; at present this is not only the default, but also a most generally used preferred cipher.
More information this and other ciphers used with cryptsetup can be found here: Wikipedia:Block_cipher

Formatting LUKS Partitions

First of all make sure the device mapper kernel module is loaded by executing the following: # modprobe dm_mod

In order to format a desired partition as an encrypted LUKS partition execute:

This should be repeated for all partitions except for /boot and possibly swap. You will note that the dump not only shows the cipher header information, but also the key-slots in use for the LUKS partition.

The example below will create an encrypted root partition using the AES cipher in XTS mode (generally referred to as XTS-AES).

# cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/sda2

Note: If hibernation usage is planned, swap must be encrypted in this fashion; otherwise, if hibernation is not a planned feature for the system, encrypting the swap file will be performed in a alternative manner.

Warning: Irrespective of the chosen partitioning method, the /boot partition must remain separate and unencrypted in order to load the kernel and boot the system.

Unlocking/Mapping LUKS Partitions with the Device Mapper

Once the LUKS partitions have been created it is time to unlock them.

The unlocking process will map the partitions to a new device name using the device mapper. This alerts the kernel that /dev/<partition name> is actually an encrypted device and should be addressed through LUKS using the /dev/mapper/<name> so as not to overwrite the encrypted data. To guard against accidental overwriting, read about the possibilities to backup the cryptheader after finishing setup.

Usually the device mapped name is descriptive of the function of the partition that is mapped, example:

cryptsetup luksOpen /dev/sda2 swap

Once opened, the swap partition device address would be /dev/mapper/swap instead of /dev/sda2.

cryptsetup luksOpen /dev/sda3 root

Once opened, the root partition device address would be /dev/mapper/root instead of /dev/sda3.

cryptsetup luksOpen /dev/sda3 lvmpool (alternate)

For setting up LVM ontop the encryption layer the device file for the decrypted volume group would be anything like /dev/mapper/lvmpool instead of /dev/sda3. LVM will then give additional names to all logical volumes created, e.g. /dev/mapper/lvmpool-root and /dev/mapper/lvmpool-swap.

In order to write encrypted data into the partition it must be accessed through the device mapped name.

Note: Since /boot is not encrypted, it does not need a device mapped name and will be addressed as /dev/sda1.

Using LUKS to Format Partitions with a Keyfile

Note: This section describes using a plaintext keyfile. If you want to encrypt your keyfile giving you two factor authentication see Section 9 for details, but please still read this section.

What is a Keyfile?

A keyfile is any file in which the data contained within it is used as the passphrase to unlock an encrypted volume.
Therefore if these files are lost or changed, decrypting the volume will no longer be possible.

Tip: Define a passphrase in addition to the keyfile for backup access to encrypted volumes in the event the defined keyfile is lost or changed.

Why use a Keyfile?

There are many kinds of keyfile. Each type of keyfile used has benefits and disadvantages summarized below:

keyfile.passphrase:

this is my passphrase I would have typed during boot but I have placed it in a file instead

This is a keyfile containing a simple passphrase. The benefit of this type of keyfile is that if the file is lost the data it contained is known and hopefully easily remembered by the owner of the encrypted volume. However the disadvantage is that this does not add any security over entering a passphrase during the initial system start.

keyfile.randomtext:

fjqweifj830149-57 819y4my1- 38t1934yt8-91m 34co3;t8y;9p3y-

This is a keyfile containing a block of random characters. The benefit of this type of keyfile is that it is much more resistant to dictionary attacks than a simple passphrase. An additional strength of keyfiles can be utilized in this situation which is the length of data used. Since this is not a string meant to be memorized by a person for entry, it is trivial to create files containing thousands of random characters as the key. The disadvantage is that if this file is lost or changed, it will most likely not be possible to access the encrypted volume without a backup passphrase.

keyfile.binary:

where any binary file, images, text, video could be chosen as the keyfile

This is a binary file that has been defined as a keyfile. When identifying files as candidates for a keyfile, it is recommended to choose files that are relatively static such as photos, music, video clips. The benefit of these files is that they serve a dual function which can make them harder to identify as keyfiles. Instead of having a text file with a large amount of random text, the keyfile would look like a regular image file or music clip to the casual observer. The disadvantage is that if this file is lost or changed, it will most likely not be possible to access the encrypted volume without a backup passphrase. Additionally, there is a theoretical loss of randomness when compared to a randomly generated text file. This is due to the fact that images, videos and music have some intrinsic relationship between neighboring bits of data that does not exist for a text file. However this is controversial and has never been exploited publicly.

Creating a Keyfile with Random Characters

Here dd is used to generate a keyfile of 2048 random bytes.

# dd if=/dev/urandom of=mykeyfile bs=512 count=4

The usage of dd is similar to initially wiping the volume with random data prior to encryption.

Warning: Do not use badblocks here. It only generate a random pattern which just repeats its randomness over and over again.

Creating a new LUKS encrypted partition with a Keyfile

When creating a new LUKS encrypted partition, a keyfile may be associated with the partition on its creation using:

Storing the Key File

External Storage on a USB Drive

Preparation for Persistent block device naming

For reading the file from an external storage device it is very convenient to access it through udev's Persistent block device naming features and not by ordinary device nodes like /dev/sdb1 whose naming depends on the order in which devices are plugged in. So in order to assure that the encrypt HOOK in the initcpio finds your keyfile, you must use a permanent device name.

Using the filesystem UUID for persistent block device naming is considered very reliable. Filesystem UUIDs are stored in the filesystem itself, meaning that the UUID will be the same if you plug it into any other computer, and that a dd backup of it will always have the same UUID since dd does a bitwise copy.

The right device node for what is now /dev/sdb1 will always get symlinked by /dev/disk/by-uuid/baa07781-2a10-43a7-b876-c1715aba9d54. Symlinks can be used in the bootloaders "cryptkey" kernel option or anywhere else.

For legacy filesystems like FAT the UUID will be much shorter but collision is still unlikely to happen if not mounting many different FAT filesystems at once.

Label

In the following example a FAT partition is labeled as "Keys" and will always get symlinked by /dev/disk/by-label/Keys:

Note: If you plan to store the keyfile between MBR and the 1st partition you cannot use this method, since it only allows access to the partitions (sdb1, sdb2, ...) but not to the USB device (sdb) itself. Use something like /dev/disk/by-id/* or alternatively create a udev rule as described in the following section.

Persistent udev rule

Optionally you may choose to set up your flash drive with a udev rule. There is some documentation in the Arch wiki about that already; if you want more in-depth, structural info, read this guide. Here is quickly how it goes.

Get the serial number from your USB flash drive:

lsusb -v | grep -A 5 Vendor

Create a udev rule for it by adding the following to a file in /etc/udev/rules.d/, such as 8-usbstick.rules:

KERNEL=="sd*", ATTRS{serial}=="$SERIAL", SYMLINK+="$SYMLINK%n"

Replace $SYMLINK and $SERIAL with their respective values. %n will expand to the partition (just like sda is subdivided into sda1, sda2, ...). You do not need to go with the 'serial' attribute. If you have a custom rule of your own, you can put it in as well (e.g. using the vendor name).

Rescan your sysfs:

udevadm trigger

Now check the contents of /dev:

ls /dev

It should show your device with your desired name.

Generating the keyfile

The advantage is that it resides in RAM and not on a physical disk, so after unmounting your keyfile is securly gone.
So copy your keyfile to some place you consider as secure before unmounting.
If you are planning to store the keyfile as a plain file on your USB device, you can also simply execute the following command in the corresponding directory, e.g. /media/sdb1

The keyfile can be of arbitrary content and size. We will generate a random temporary keyfile of 2048 bytes:

# dd if=/dev/urandom of=secretkey bs=512 count=4

If you stored your temporary keyfile on a physical storage device, remember to not just (re)move the keyfile later on, but use something like

cp secretkey /destination/path
shred --remove --zero secretkey

to securely overwrite it. For overaged filesystems like FAT or ext2 this will suffice while in the case of journaling filesystems, flash memory hardware and other cases it is highly recommended to wipe the entire device or at least the keyfiles partition.

Add a keyslot for the temporary keyfile to the LUKS header:

# cryptsetup luksAddKey /dev/sda2 secretkey

Enter any LUKS passphrase:
key slot 0 unlocked.
Command successful.

Storing the keyfile

To store the key file, you have two options. The first is less risky than the other, but perhaps a bit more secure (if you consider security by obscurity as more secure).
In any case you have to do some further configuration, if not already done above.

Configuration of initcpio

You have to add two extra modules in your /etc/mkinitcpio.conf, one for the drive's file system and one for the codepage. Further if you created a udev rule, you should tell mkinitcpio about it:

In this example it is assumed that you use a FAT formatted USB drive. Replace those module names if you use another file system on your USB stick (e.g. ext2) or another codepage. Users running the stock Arch kernel should stick to the codepage mentioned here.

If you have a non-US keyboard, it might prove useful to load your keyboard layout before you are prompted to enter the password to unlock the root partition at boot. For this, you will need the keymap hook before encrypt.

Generate a new image (maybe you should backup a copy of your old /boot/initramfs-linux.img first):

# mkinitcpio -p linux

Storing the key as a plain (visible) file

Be sure to choose a plain name for your key – a bit of 'security through obscurity' is always nice ;-). Avoid using dotfiles (hidden files) – the encrypt hook will fail to find the keyfile during the boot process.

You have to add a kernel parameter in your /boot/grub/menu.lst (GRUB). It should look something like this:

This assumes /dev/usbstick is the FAT partition of your choice. Replace it with /dev/disk/by-... or whatever your device is.

That is all, reboot and have fun!

Storing the key between MBR and 1st partition

We will write the key directly between the Master Boot Record (MBR) and the first partition.

Warning: You should only follow this step if you know what you are doing -- it can cause data loss and damage your partitions or MBR on the stick!

This article or section is out of date.

Reason: Grub-legacy is not available anymore and for GRUB2 a 1-2MB gap between MBR and the beginning of other written data (e.g. first partition or LUKS-key) is needed for embedding GRUB2's core.img. Information regarding GPT and/or UEFI combinations are required. GRUB2 has changed parsing configuration. (Discuss in Talk:Dm-crypt#)

If you have a bootloader installed on your drive you have to adjust the values. E.g. GRUB needs the first 16 sectors (actually, it depends on the type of the file system, so do not rely on this too much), so you would have to replace seek=4 with seek=16; otherwise you would overwrite parts of your GRUB installation. When in doubt, take a look at the first 64 sectors of your drive and decide on your own where to place your key.

Optional
If you do not know if you have enough free space before the first partition, you can do

If everything went fine you can now overwrite and delete your temporary secretkey as noted above.
You should not simply use rm as the keyfile would only be unlinked from your filesystem and be left physically intact.

Now you have to add a kernel parameter in your /boot/grub/menu.lst file (GRUB); it should look something like this:

That is all, reboot and have fun! And look if your partitions still work after that ;-).

Encrypting the Swap partition

Without suspend-to-disk support

In systems where suspend to disk is not a desired feature, it is possible to create a swap file that will have a random master key with each boot. This is accomplished by using dm-crypt directly without LUKS extensions.

The /etc/crypttab is well commented and you can basically just uncomment the swap line and change <device> to a persistent symlink.

/dev/urandom sets the dm-crypt master key to be randomized on every volume recreation.

<options>

The swap option runs mkswap after cryptographic's are setup.

Warning: You should use persistent block device naming (in example ID's) for <device> because if there are multiple hard drives installed in the system, their naming order (sda, sdb,...) can occasionally be scrambled upon boot and thus the swap would be created over a valuable file system, destroying its content.

Persistent block device naming is implemented with simple symlinks. Using UUID's or filesystem-labels is not possible as plain dm-crypt writes only encrypted data without a persistent header like LUKS. If you are not familar with one of the directories under /dev/disk/ read on in the section on #Preparation for Persistent block device naming

This will map /dev/sda2 to /dev/mapper/swap as a swap partition that can be added in /etc/fstab like a normal swap.

If the partition chosen for swap was previously a LUKS partition, crypttab will not overwrite the partition to create a swap partition. This is a safety measure to prevent data loss from accidental mis-identification of the swap partition in crypttab. In order to use such a partition the LUKS header must be overwritten once.

With suspend-to-disk support

To be able to resume after suspending the computer to disk (hibernate), it is required to keep the swap filesystem intact. Therefore, it is required to have a pre-existent LUKS swap partition, which can be stored on the disk or input manually at startup. Because the resume takes place before /etc/crypttab can be used, it is required to create a hook in /etc/mkinitcpio.conf to open the swap LUKS device before resuming.

If you want to use a partition which is currently used by the system, you have to disable it first:

# swapoff /dev/<device>

Also make sure you remove any line in /etc/crypttab pointing to this device.

A simple way to realize encrypted swap with suspend-to-disk support is by using LVM ontop the encryption layer, so one encrypted partition can contain infinite filesystems (root, swap, home, ...). Follow the instructions on #Encrypting a LVM setup.

The following setup has the disadvantage of having to insert an additional passphrase for the swap partition manually on every boot.

Warning: Do not use this setup with a key file. Please read about the issue reported here

To format the encrypted container for the swap partition, follow steps similar to those described in #Configuring LUKS above and create keyslot for a user-memorizable passphrase.

for opening the swap device by loading a keyfile from a crypted root device

Note: If swap is on a Solid State Disk (SSD) and Discard/TRIM is desired the option --allow-discards has to get added to the cryptsetup line in the openswap hook above. See Discard/TRIM support for solid state disks (SSD) or SSD for more information on discard. Additionally you have to add the mount option 'discard' to your fstab entry for the swap device.

Add the hook openswap in the HOOKS array in /etc/mkinitcpio.conf, before filesystem but after encrypt. Do not forget to add the resume hook after openswap.

HOOKS="... encrypt openswap resume filesystems ..."

Regenerate the boot image:

# mkinitcpio -p linux

Add the mapped partition to /etc/fstab by adding the following line:

/dev/mapper/swapDevice swap swap defaults 0 0

Set up your system to resume from /dev/mapper/swapDevice. For example, if you use GRUB with kernel hibernation support, add resume=/dev/mapper/swapDevice to the kernel line in /boot/grub/menu.lst. A line with encrypted root and swap partitions can look like this:

At boot time, the openswap hook will open the swap partition so the kernel resume may use it. If you use special hooks for resuming from hibernation, make sure they are placed afteropenswap in the HOOKS array. Please note that because of initrd opening swap, there is no entry for swapDevice in /etc/crypttab needed in this case.

Using a swap file for suspend-to-disk support

Choose a mapped partition (e.g. /dev/mapper/rootDevice) whose mounted filesystem (e.g. /) contains enough free space to hold the entire contents of your system's RAM. For example, if your system has 4 GiB RAM, then you need at least that much free space on the mounted filesystem of your chosen mapped partition for the swap file.

Create the swap file (e.g. /swapfile) inside the mounted filesystem of your chosen mapped partition. Be sure to activate it with swapon and also add it to your /etc/fstab file afterward.

Set up your system to resume from your chosen mapped partition. For example, if you use GRUB with kernel hibernation support, add resume=your chosen mapped partition and resume_offset=see calculation command below to the kernel line in /boot/grub/menu.lst. A line with encrypted root partition can look like this:

Add the resume hook to your etc/mkinitcpio.conf file and rebuild the image afterward:

HOOKS="... encrypt resume ... filesystems ..."

If you use a USB keyboard to enter your decryption password, then the keyboard module must appear in front of the encrypt hook, as shown below. Otherwise, you will not be able to boot your computer because you couldn't enter your decryption password to decrypt your Linux root partition!

HOOKS="... keyboard encrypt ..."

Installing the system

Note: Most of the installation can be carried out normally. However, there are a few areas where it is important to make certain selections. These are marked below.

Prepare hard drive for Arch Install Scripts

This assumes you want to install an encrypted system with the Arch Install Scripts, have created partitions for / (e.g. /dev/sdaX) and /boot (/dev/sdaY) at least, following the Installation Guide and deciding against using LVM. Prior to creating the partitions you have done a preparation of the disk for encryption according to your necessities (the necessary tools are on the installation-ISO).

First check, if the blockdevice mapper dm_mod is loaded with

# lsmod | grep mod

If one wants to use the default LUKS-cipher algorithm, there is no need to specify one for the luksFormat. You may want to check the defaults used by the cryptsetup version at time of installation and decide yourself. With defaults a dm-crypt/LUKS blockdevice for the crypted root can be created

# cryptsetup -y -v luksFormat /dev/sdaX

opened

# cryptsetup open /dev/sdaX cryptroot

formatted with your desired filesystem

# mkfs -t ext4 /dev/mapper/cryptroot

and mounted

# mount -t ext4 /dev/mapper/cryptroot /mnt

At this point, just before installing the base system, it might be useful to check the mapping works as intended:

# umount /mnt
# cryptsetup close cryptroot

and mount it again to check.

If you created a separate /home partition, the steps have to be adapted and repeated for that.
What you do have to setup is a non-encrypted /boot partition, which is needed for a crypted root. For a standard MBR/non-EFI/boot partition that may be achieved by formatting

# mkfs -t ext2 /dev/sdaY

creating a mount-point for installation

# mkdir /mnt/boot

and mounting it

# mount -t ext2 /dev/sdaY /mnt/boot

That is basically what is necessary at this point before installing the base system with the Arch Install Scripts. Take care to install the bootloader to /mnt/boot with the pacstrap script. Additional configuration steps must be followed before booting the installed system.

Configure initramfs

One important point is to add the hooks relevant for your particular install in the correct order to /etc/mkinitcpio.conf. The one you have to add when encrypting the root filesystem is encrypt. A recommended hook for LUKS encrypted blockdevices is shutdown to ensure controlled unmounting during system shutdown. Others needed, e.g. keymap, should be clear from other manual steps you follow during the installation and further details in the following. For detailed information about initramfs configuration and available Hooks refer to Mkinitcpio#HOOKS.

Note: The encrypt hook is only needed if your root partition is a LUKS partition (or a LUKS partition that needs to be mounted before root). The encrypt hook is not needed for any other encrypted partitions (swap, for example). System initialization scripts (/etc/rc.sysinit and /etc/crypttab among others) take care of those.

It is important that the encrypt hook comes before the filesystems hook (in case you are using LVM on LUKS, the order should be: encrypt lvm2 filesystems), so make sure that your HOOKS array looks something like this:

etc/mkinitcpio.conf

HOOKS="(base udev) ... encrypt ... filesystems ..."

If you need support for foreign keymaps for your encryption password, you have to specify the hook keymap as well before encrypt.

If you have a USB keyboard, you will need the keyboard hook. Without it, no USB keyboard will work in early userspace.

In the same file, you may want to add to "MODULES" dm_mod and the filesystem types used, e.g: MODULES="dm_mod ext4"

The device file of the actual (decrypted) root filesystem. If the filesystem is formatted directly on the decrypted device file this will be /dev/mapper/<dmname>. If LVM is in between sth. like /dev/mapper/<volgroup>-<pvol> or /dev/<volgroup>/<pvol> does the trick.

resume=<device>

The device file of the decrypted (swap) filesystem used for suspend2disk.

Fstab

AIF Instructions

Reason: AIF (Arch Installation Framework; referenced below also as /arch/setup) does not exist anymore, GRUB Legacy is not available anymore (Discuss in Talk:Dm-crypt#)

Prepare hard drive for AIF

Now that /dev/mapper/root and /dev/mapper/home are in place, we can enter the regular Arch setup script to install the system into the encrypted volumes.

# /arch/setup

Skip the Partitioning and Auto-Prepare steps and go straight to manual configuration.
Instead of choosing the hardware devices (/dev/sdaX) directly, you have to select the mapper devices created above.
Choose /dev/mapper/root for your root and /dev/mapper/home as /home partition respectively and format them with any filesystem you like.
The same is valid for a swap partition which is set up like the /home partition. Make sure you mount /dev/sda1 as the /boot partition, or else the installer will not properly set up the bootloader.

Select and Install packages

Select and install the packages as usual: the base package contains all required programs.

Exit Install

Now that the install is finished the only thing left to do is add entries to the /etc/crypttab file so you do not have to enter the passphrase for all encrypted partitions. This works only for non-root partitions e.g. /home, swap, etc.

You can also use a keyfile instead of a passphrase. If not already done, create a keyfile and add the key to the corresponding LUKS partition as described above.
Then add the following information to the /etc/crypttab file for automounting:

home /dev/sda5 /path/of/your/keyfile

If you used a USB device to store your keyfile, you should have something like this:

home /dev/sda5 /dev/sd*1/keyfile

Or if the keyfile was stored in the MBR, it should be like this:

home /dev/sda5 /dev/sd*:2048:2048

Note: When reading the keyfile from the MBR it should be /dev/sdb not /dev/sdb1 but if the key is in the filesystem it should still be /dev/sdb1.

After rebooting you should now be presented with the text

A password is required to access the root filesystem:

followed by a prompt for a LUKS password. Type it in and everything should boot.
Once you have logged in, have a look at your mounted partitions by typing mount. You should have /dev/mapper/root mounted at / and, if you set up a separate encrypted home partition, /dev/mapper/home mounted at /home. If you set up encrypted swap, swapon -s should have /dev/mapper/swap listed as your swap partition.

Note: Eventually the text prompting for the password is mixed up with other boot messages. So the boot process may seem frozen at first glance, but it is not, simply enter your password and press Template:Keypress.

GRUB Legacy

This article or section is out of date.

Reason: Like AIF in this section, GRUB Legacy and LILO are dropped. (Discuss in Talk:Dm-crypt#)

GRUB Legacy: You have to make some small changes to the entries generated by the installer by replacing /dev/mapper/root with /dev/sda3. The important point to remember here is to use the same cryptdevice name you assigned when you initially unlocked your device. In this example, the device name is cryptroot; customize yours accordingly:

LILO

LILO: Edit the Arch Linux section in /etc/lilo.conf and include a line for the append option, over the initrd, with the root=/dev/sda3 parameter. The append section makes the same kernel line as in GRUB. Also, you can omit the root option above the image option. The section looks like this:

If you want to use a USB flash drive with a keyfile, you have to append the cryptkey option. See the corresponding section above.

Remote unlocking of the root (or other) partition

If you want to be able to reboot a fully LUKS-encrypted system remotely, or start it with a Wake-on-LAN service, you will need a way to enter a passphrase for the root partition/volume at startup. This can be achieved by running the net hook along with an SSH server in initrd. Install the dropbear_initrd_encryptAUR package from the AUR and follow the post-installation instructions. Replace the encrypt hook with dropbear encryptssh in /etc/mkinitcpio.conf. Put the net hook early in the HOOKS array if your DHCP server takes a long time to lease IP addresses.

If you would simply like a nice solution to mount other encrypted partitions (such as /home)remotely, you may want to look at this forum thread.

Note: Acutally trim will not work with this script because it is not yet updated to the latest encrypt hook, so it is not able to parse -–allow-discards from /boot/grub/menu.lst. (Version: dropbear_initrd_encrypt 0.8-16). You won't notice any error when using online discard, but you see an error when you try to use fstrim.For a temporary solution just add -–allow-discards to every cryptsetup line of /lib/initcpio/install/dropbear(1 line) and /lib/initcpio/hooks/encryptssh(3 lines)

Backup the cryptheader

If the header of your encrypted partition gets destroyed, you will not be able to decrypt your data. It is just as much as a dilemma as forgetting the passphrase or damaging a key-file used to unlock the partition. A damage may occur by your own fault while re-partitioning the disk later or by third-party programs misinterpreting the partition table.

Therefore, having a backup of the headers and storing them on another disk might be a good idea.

Attention: Many people recommend NOT backing up the cryptheader, but even so it's a single point of failure!
In short, the problem is that LUKS is not aware of the duplicated cryptheader, which contains the master key which is used to encrypt all files on your partition. Of course this master key is encrypted with your passphrases or keyfiles.
But if one of those gets compromised and you want to revoke it you have to do this on all copies of the cryptheader!
I.e. if someone has got your cryptheader and one of your keys he can decrypt the master key and access all your data.
Of course the same is true for all backups you create of your partions.
So you decide if you are one of those paranoids brave enough to go without a backup for the sake of security or not.
See also the LUKS FAQ for further details on this.

Warning: Tmpfs can swap to harddisk if low on memory so it is not recommended here.

Manually

First you have to find out the payload offset of the crypted partition:

# cryptsetup luksDump /dev/<device> | grep "Payload offset"

Payload offset: 4040

Second check the sector size of the drive

# fdisk -l /dev/<device> |grep "Sector size"

Sector size (logical/physical): 512 bytes / 512 bytes

Now that you know the values, you can backup the header with a simple dd command:

# dd if=/dev/<device> of=/path/to/<file>.img bs=512 count=4040

and store it safely.

Restore

Be careful before restore: make sure that you chose the right partition (again replace sdaX with the corresponding partition).
Restoring the wrong header or restoring to an unencrypted partition will cause data loss.

Using cryptsetup

Note: All the keyslot areas are overwritten; only active keyslots from the backup file are available after issuing this command.

Manually

Again, you will need to the same values as when backing up:

dd if=./backup.img of=/dev/sdX bs=512 count=4040

Encrypting a loopback filesystem

[This paragraph has been merged from another page; its consistency with the other paragraphs should be improved]

Preparation and mapping

First, start by creating an encrypted container!

dd if=/dev/urandom of=/bigsecret bs=1M count=10

This will create the file bigsecret with a size of 10 megabytes.

losetup /dev/loop0 /bigsecret

This will create the device node /dev/loop0, so that we can mount/use our container.

Note: If it gives you the error /dev/loop0: No such file or directory, you need to first load the kernel module with modprobe loop. These days (Kernel 3.2) loop devices are created on demand. Ask for a new loop device with losetup -f.

cryptsetup luksFormat /dev/loop0

This will ask you for a password for your new container file.

Note: If you get an error like Command failed: Failed to setup dm-crypt key mapping. Check kernel for support for the aes-cbc-essiv:sha256 cipher spec and verify that /dev/loop0 contains at least 133 sectors, then run modprobe dm-mod.

cryptsetup luksOpen /dev/loop0 secret

The encrypted container is now available through the device file /dev/mapper/secret.
Now we are able to create a partition in the container:

mkfs.ext2 /dev/mapper/secret

and mount it...

mkdir /mnt/secret
mount -t ext2 /dev/mapper/secret /mnt/secret

We can now use the container as if it was a normal partition!
To unmount the container:

Resizing the loopback filesystem

After this we need to expand our container file with the size of the data we want to add:

dd if=/dev/urandom bs=1M count=1024 | cat - >> /bigsecret

Be careful to really use TWO >, or you will override your current container!

You could use /dev/zero instead of /dev/urandom to significantly speed up the process, but with /dev/zero your encrypted filesystems will not be as secure. (A better option to create random data quicker than /dev/urandom is frandom[1], available from the AUR).
A faster (almost instant) method than dd is truncate , but its use has the same security implications as using /dev/zero. The size passed to truncate is the final size to make the file, so don't use a value less than that of the current file or you will lose data. e.g. to increase a 20G file by 10G: truncate -s 30G filename.

Now we have to map the container to the loop device:

losetup /dev/loop0 /bigsecret
cryptsetup luksOpen /dev/loop0 secret

After this we will resize the encrypted part of the container to the maximum size of the container file:

cryptsetup resize secret

Finally, we can resize the filesystem. Here is an example for ext2/3/4:

The most important thing in setting LVM on top of encryption is to configure the initramfs for running the encrypt hook before the lvm2 hook (and those two before the filesystems hook).

LUKS on LVM

To use encryption on top of LVM, you have to first set up your LVM volumes and then use them as the base for the encrypted partitions. That means, in short, that you have to set up LVM first. Then follow this guide, but replace all occurrences of /dev/sdXy in the guide with its LVM counterpart. (E.g.: /dev/sda5 -> /dev/<volume group name>/home). This is used to setup partitions (inside the LVM) which can be unlocked separately or a mixture of encrypted and non-encrypted partitions.

For encrypted partitions inside an LVM, the LVM-hook has to run first, before the respective encrypted logical volumes can be unlocked. So for this add the encrypt hook in /etc/mkinitcpio.confafter the lvm2 hook, if you chose to set up encrypted partitions on top of LVM. Also remember to change USELVM in /etc/rc.conf to "yes".

In between Arch Linux installation media release 2009.08 and 2012.07.15 LVM and dm_crypt had been supported by the installer out of the box.
This made it very easy to configure a system for LVM on dm-crypt or vice versa.
Actually the configuration is done exactly as without LVM: see the corresponding section above. It differs only in two aspects.

The partition and filesystem choice

Create a small, unencrypted boot partition and use the remaining space for a single partition which can later be split up into multiple logic volumes by LVM.

For a LVM-on-dm-crypt system set up the filesystems and mounting points for example like this:

The configuration stage

In /etc/mkinitcpio.conf add the encrypt hook before the lvm2 hook in the HOOKS array, if you set up LVM on top of the encrypted partition.

That is it for the LVM & dm_crypt specific part. The rest is done as usual.

The factual accuracy of this article or section is disputed.

Reason: The lvm2 hook activates the (encrypted) root volume group long before sysvinit (or systemd) can run from there. Letting sysvinit later run a second LVM activation in addition serves no purpose. Read LVM#Configure system. However this error is duplicated within the #Encrypting a LVM setup section. (Discuss in Talk:Dm-crypt#)

In /etc/rc.conf set USELVM to "yes".

Applying this to a non-root partition

You might get tempted to apply all this fancy stuff to a non-root partition. Arch does not support this out of the box, however, you can easily change the cryptdev and cryptname values in /lib/initcpio/hooks/encrypt (the first one to your /dev/sd* partition, the second to the name you want to attribute). That should be enough.

The big advantage is you can have everything automated, while setting up /etc/crypttab with an external key file (i.e. the keyfile is not on any internal hard drive partition) can be a pain - you need to make sure the USB/FireWire/... device gets mounted before the encrypted partition, which means you have to change the order of /etc/fstab (at least).

Of course, if the cryptsetup package gets upgraded, you will have to change this script again. However, this solution is to be preferred over hacking /etc/rc.sysinit or similar files. Unlike /etc/crypttab, only one partition is supported, but with some further hacking one should be able to have multiple partitions unlocked.

If you want to do this on a software RAID partition, there is one more thing you need to do. Just setting the /dev/mdX device in /lib/initcpio/hooks/encrypt is not enough; the encrypt hook will fail to find the key for some reason, and not prompt for a passphrase either. It looks like the RAID devices are not brought up until after the encrypt hook is run. You can solve this by putting the RAID array in /boot/grub/menu.lst, like

kernel /boot/vmlinuz-linux md=1,/dev/hda5,/dev/hdb5

If you set up your root partition as a RAID, you will notice the similarities with that setup ;-). GRUB can handle multiple array definitions just fine:

You can follow the above instructions with only two primary partitions one boot partition

(required because of LVM), and one primary LVM partition. Within the LVM partition you can have
as many partitions as you need, but most importantly it should contain at least root, swap, and
home logical volume partitions. This has the added benefit of having only one keyfile for all
your partitions, and having the ability to hibernate your computer (suspend to disk) where the
swap partition is encrypted. If you decide to do so your hooks in /etc/mkinitcpio.conf
should look like
HOOKS=" ... usb usbinput (etwo or ssldec) encrypt(if using openssl) lvm2 resume ... "
and you should add to your kernel line(if using grub, /boot/grub/menu.lst) or
GRUB_CMD_LINE(if using grub2, /etc/default/grub):
"resume=/dev/mapper/<VolumeGroupName>-<LVNameOfSwap>"

If you need to temporarily store the unecrypted keyfile somewhere, do not store them on an

unencrytped disk. Even better make sure to store them to RAM such as /dev/shm.

If you want to use a GPG encrypted keyfile, you need to use a statically compiled GnuPG version 1.4 or you could edit the hooks and use this AUR package gnupg1

It is possible that an update to OpenSSL could break the custom ssldec mentioned in the second forum post.

Securing the unencrypted boot partition

Referring to an article from the ct-magazine (Issue 3/12, page 146, 01.16.2012 http://www.heise.de/ct/inhalt/2012/03/6/) the following script checks all files under /boot for changes of SHA-1 hash, inode and occupied blocks on the hard drive. It also checks the MBR.

There is a small caveat for systemd: At the time of writing the original chkboot.sh script provided contains an empty space at the beginning of #!/bin/bash which has to be removed for the service to start successfully.

As /usr/local/bin/chkboot_user.sh need to be excuted after login, add it to the autostart (e.g. under KDE -> System Settings -> Startup and Shutdown -> Autostart; Gnome3: gnome-session-properties).

With Arch Linux changes to /boot are pretty frequent, for example by new kernels rolling-in. Therefore it may be helpful to use the scripts with every full system update. One way to do so:

Resources

Reason: Explained separately for each link beneath. (Discuss in Talk:Dm-crypt#)

Arch cryptsetup example video - A HowTo video on setting up an encrypted Arch system from scratch. The video still shows an installation with AIF, which is at the time of writing deprecated / not developed further. The important partitioning and cryptsetup are shown outside AIF though.