From ArchWiki
Revision as of 14:38, 16 February 2010 by Buergi (talk | contribs) (→‎Quick method: added note)
Jump to navigation Jump to search


Why Encryption?

Encryption is useful for two (related) reasons. Firstly, it prevents anyone with physical access to your computer, and your hard drive in particular, from getting the data from it (unless they have your passphrase/key). Secondly, it allows you to wipe the data on your hard drive with far more confidence in the event of you selling or discarding your drive.

Basically, it supplements the access control mechanisms of the operating system (like file permissions) by making it harder to bypass the operating system by inserting a boot CD, for example. Encrypting the root partition prevents anyone from using this method to insert viruses or trojans onto your computer.

Note that we're not encrypting the boot partition - the bootloader needs to read that one!

ATTENTION: Having encrypted partitions does not protect you from all possible attacks. The encryption is only as good as your key management, and there are other ways to break into computers while they are running. Read the CAVEATS section below!

Why LUKS for dm-crypt?

There are either 3 or 4 rival disk encryption standards in Linux, depending on how you count them.

The old cryptoloop is deprecated: it's old, insecure and unreliable.

A much better version, loop-AES (, was created but, due to politics, never became favorable with the kernel developers. It's far more secure than either cryptoloop or straight device-mapper encryptions (and probably faster than any of the other 3 options), but is not user-friendly. It also requires non-standard kernel support, which ARCH's kernel26 doesn't have.

The standard device-mapper encryption (dm-crypt) is another choice.

LUKS essentially makes management of encrypted partitions easier. Without going into the hairy details (check out the LUKS home page if you're interested), it stores all the needed setup information on the disk itself. All you need then is the password, which can be in a separate file if you like. The Linux implementation uses dm-crypt and it can have up to eight different passwords, which can be changed or revoked easily. It is also supported by mkinitcpio in ARCH linux, which is nice.


Security (encryption)

Disk encryption is not the be-all and end-all of security. Why not? Well, for a start, it won't prevent people from hacking into a running computer (either over the network or at a console) if there is a security hole to exploited (and there invariably is). There are a dozen and one things you can (and should) do to secure your computer against this type of attack, but they are all outside the scope of this document.

What's more, even in situations this type of encryption is useful for (physical access to storage media), it isn't worth a thing if someone has your key. In other words, if someone finds out or guesses your passphrase, or gets access to your external key file if you're using one, they can unlock the encryption on the hard drive in exactly the same way that you can.

What does this mean for you? Well, if you use an external key file, keep the device it is on SAFE. Attach it to your keyring or whatever. If you use a passphrase, make it hard to guess. There are hundreds of documents all over the internet telling you how to come up with a secure passphrase; we're not going to go over it here. Note, however, that we use the term "passphrase": it doesn't have to be a single word.

Getting started

If you're not starting from an unused hard drive, BACK UP YOUR DATA! I cannot stress this enough. Ideally, you should be doing this regularly anyway, and it's particularly important with an encrypted hard drive. But beware: if you have unencrypted backups, is there any point in having an encrypted hard drive? Think about where you store your backups.

Note: if you want to have encrypted swap, read the section below about Encrypted Swap and decide how you want to set it up before you start the rest of this HOWTO.

Since Arch Linux 2009.08 the Arch installer provides a comfortable and easy way to configure dm_crypt (also in combination with LVM). Of course you can also do all the work manually. In either case it's recommended to overwrite the disk to wipe out former unencrypted content.



Repartitioning and formatting your drive will only remove the filesystem metadata and will mostly leave the actual data intact, allowing determined attackers to recover data using tools like Foremost. If your harddisk contained sensitive data from previous use, you might want to overwrite this data. Contrary to popular believe overwriting several times or using random data as source serves no purpose. Data won't be recoverable after being overwritten by zeros. [1]

To overwrite your disk with zeros you can use

# dd if=/dev/zero of=/dev/sda bs=1M

If you want to check for bad blocks while writing you can use badblocks. The badblocks command will check your disk for bad blocks while writing random data. The pseudorandom algorithm used by this command is faster (although "less random") than /dev/urandom, so it can be useful for large disks. frandom is a fast random generator you might want to use for large disk.

# badblocks -c 10240 -w -t random -s -v /dev/sda

This will test blocks in groups of 10240 (i.e. 10MB) at a time, writing over them with random data and showing progress as it goes.

However it should be noted that the pseudo random data generated by badblocks does not serve any other purpose than slowing down the wiping of your drive.

Arch Linux Installer (>2009.08)

Since Arch Linux 2009.08 the installer supports dm_crypt and LVM (and combination of both) out of the box.

Just run the installer as usual, i.e. follow the Official Arch Linux Install Guide or the Beginners' Guide. When you reach the "Prepare Hard Drive(s)" don't use "Auto-Prepare" but set up your partitions manually. Beware that you have to create a separate unencrypted /boot partition, or GRUB/LILO has no chance to load the operating system afterwards. The most important step towards an encrypted system is done in the "Manually Configure ..." step.

Configuring filesystems and mountpoints

At first select the device corresponding to your unencrypted /boot partition, choose e.g. ext2 as filesystem and select /boot as the mountpoint. For all other partitions you created and which you want to be encrypted select dm_crypt in the filesystem dialog. You should enter a label for the encrypted device, e.g. 'sda2crypt', or simply 'root'.

Here is an example listing how it may look like:

/dev/sda1   raw->ext2;yes;/boot;no_opts;no_label;no_params
/dev/sda2   raw->dm_crypt;yes;no_mountpoint;no_opts;sda2crypt
/dev/sda3   raw->dm_crypt;yes;no_mountpoint;no_opts;sda3crypt
/dev/mapper/sda2crypt   dm_crypt->ext3;yes;/;no_opts;no_label;no_params
/dev/mapper/sda3crypt   dm_crypt->ext3;yes;/home;no_opts;no_label;no_params

Note: you can also put a LVM inside the dm_crypt partition, or vice versa a dm_crypt partition inside a LVM volume. See Encrypting a LVM setup for details.

When you press 'DONE' the installer will create and mount the filesystem configuration automatically. You will be prompted for a LUKS passphrase 3 times (2x to set a new passphrase, 1x to unlock the device).

That's it with the dm_crypt specific part for so far. Select your desired packages and install the system. The installer should perform all steps necessary for configuring the boot and mount process of your new system. You can check the configuration afterwards and compare them to the one in the section about manual configuration. Especially the HOOKS section in mkinitcpio.conf is important for an encrypted root partition.

Further tweaks for USB keyfile authentication

When you're planning to use a keyfile on an USB stick instead of passphrase authentication you have to do some further tweaks in mkinitcpio.conf: To mount the USB device with your keyfile in the boot process add usb somewhere before encrypt in the HOOKS variable e.g.

HOOKS=" ... sata usb usbinput keymap encrypt filesystems ... "

And for a FAT formated USB stick add the following to the MODULES variable

MODULES=" ... nls_cp437 vfat ... "

After exiting the installer you can now create a keyfile onto USB stick your for authentication. This is for example done with the following commands. Check out section Generating the keyfile for further details.

# mkdir /mnt/usbstick
# mount -t vfat /dev/sdb1 /mnt/usbstick
# cd /mnt/usbstick
# dd if=/dev/urandom of=mykeyfile bs=512 count=4
# cryptsetup luksAddKey /dev/sdaX /mnt/usbstick/mykeyfile

Manually configuring LUKS

As noted above it's recommended for security reasons to overwrite the partition before going any further.


At first set up your partitions as you want. Make sure you have a separate partition for /boot. If you think about it, this is absolutely necessary. If your /boot partition is encrypted, then your bootloader would not be able to read the kernel image and you would not get far.

# cfdisk /dev/sda

The following - indicative - partition layout will be used:

/dev/sda1 -> /boot
/dev/sda2 -> swap
/dev/sda3 -> /
/dev/sda4 -> /home
/dev/sda5 -> /tmp    # especially useful if you don't want to encrypt the entire root (/) partition

Loading kernel modules

Note: this article will use XTS-AES as encryption algorithm because it was standardized as IEEE P1619 Standard for Cryptographic Protection of Data on Block-Oriented Storage Devices and it is quite secure, however the XTS mode is still flagged as "experimental" in the Linux kernel, so if you want something less secure but more proven, you should go with the CBC-ESSIV mode. The XTS mode is supported by Linux 2.6.24 upwards (ISO of Arch 2008.06 upwards).

Note: The XTS mode uses two keys of the same size, therefore available sizes (using XTS-AES) are 256 (128 * 2), 384 (192 * 2) and 512 (256 * 2).

Load the dm-crypt and the optimized AES module:

# modprobe dm-crypt
# modprobe aes-i586

Note: x86_64 users can also try the "aes-x86_64" optimized module instead of "aes-i586".

Mapping partitions


Use this to create a password to unlock your encrypted partions with:

Create your new LUKS encrypted partitions:

# cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/sda3
Enter passphrase: mypassword
Verify passphrase: mypassword
# cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/sda4
Enter passphrase: myotherpassword
Verify passphrase: myotherpassword
# cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/sda5
Enter passphrase: myotherpassword
Verify passphrase: myotherpassword

Then open the newly created LUKS partitions:

# cryptsetup luksOpen /dev/sda3 root
Enter any LUKS passphrase: mypassword
key slot 0 unlocked.
Command successful.
# cryptsetup luksOpen /dev/sda4 home
Enter any LUKS passphrase: myotherpassword
key slot 0 unlocked.
Command successful.
# cryptsetup luksOpen /dev/sda5 tmp
Enter any LUKS passphrase: myotherpassword
key slot 0 unlocked.
Command successful.


You can also do the following to create a keyfile instead of a passphrase. Of course you could put the keyfile everywhere you like, but most probably you'll want to put it onto an USB stick to unlock your encrypted partions. See the corresponding section below for further details on this.

To store the keyfile on an USB stick mount it and change to the directory

# mkdir /mnt/usbstick
# mount -t vfat /dev/sdb1 /mnt/usbstick
# cd /mnt/usbstick

As said above the keyfile can be of any content and size. We'll generate a random keyfile of 2048 bytes onto the USB stick:

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

Create your new LUKS encrypted partitions:

# cryptsetup -c aes-xts-plain -s 512 -v luksFormat /dev/sda3 /mnt/usbstick/mykeyfile
# cryptsetup -c aes-xts-plain -s 512 -v luksFormat /dev/sda4 /mnt/usbstick/mykeyfile
# cryptsetup -c aes-xts-plain -s 512 -v luksFormat /dev/sda5 /mnt/usbstick/mykeyfile

Note: if you've already created the LUKS partitions e.g. with passphrase authentication, you can add a keyfile as further authentication method by using

# cryptsetup luksAddKey /dev/sdaX /mnt/usbstick/mykeyfile # replace X by 3,4,5

Then open the newly created LUKS partitions:

# cryptsetup -d /mnt/usbstick/mykeyfile luksOpen /dev/sda3 root
key slot 0 unlocked.
Command successful.
# cryptsetup -d /mnt/usbstick/mykeyfile luksOpen /dev/sda4 home
key slot 0 unlocked.
Command successful.
# cryptsetup -d /mnt/usbstick/mykeyfile luksOpen /dev/sda5 tmp
key slot 0 unlocked.
Command successful.


Now you should have a device called /dev/mapper/root, another one called /dev/mapper/home and another one called /dev/mapper/tmp. These are block devices like any other, but with a neat twist: whenever you write to them, the data is actually written to /dev/sda3, /dev/sda4 or /dev/sda5 respectively, but it is encrypted first! The only way to access the data on this encrypted partition is to re-create that /dev/mapper/root, /dev/mapper/home etc. device with cryptsetup each time you boot. With LUKS, you can use cryptsetup luksAddKey /dev/sda3 to add a new password or cryptsetup luksDelKey /dev/sda3 to revoke a password. Type cryptsetup -? or man cryptsetup (once you've booted your new Arch installation) for more info.

Note: With LUKS, if you enter the wrong password, it will reject it. You don't have to worry about it possibly destroying your data.

Note: You might also want to replace /var/tmp/ with a symbolic link to /tmp.

Note: If you've decided to go for option two for encrypted swap (see Encrypted Swap below), you should set up /dev/mapper/swap in a similar way as you've just set up /dev/mapper/home. See Encrypted Swap below for details.

Installing the system

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

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

Skip the Partitioning and Auto-Prepare business and go straight to manually 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.

Configure System

Note: encrypt hook is only needed if your root partition is a LUKS partition (or for a LUKS partition that needs to be mounted before root). If it is a swap or any other partition, all is taken care by rc.sysinit and /etc/crypttab file

Afterwards you can check the files presented to you by the installer, the most important one being /etc/mkinitcpio.conf. For detailed info on mkinitcpio (and its configuration) refer to Mkinitcpio.You have to make sure that your HOOKS looks somehow like this:

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

It is important that the encrypt hook comes before the filesystems one. If you store your key on an external USB device (e.g. a USB stick), you need to add the USB hook too:

HOOKS="... usb encrypt ... filesystems ..."

For safety, add in usb before encrypt; not sure if they're run in the order they appear in mkinitcpio.conf or not. If you need support for foreign keymaps for your encryption password you have to specify the hook 'keyboard' as well. I suggest to put this in mkinitcpio.conf right before 'encrypt'.

If you have USB keyboard you need the "usbinput" hook in mkinitcpio.conf. Without it, no USB keyboard will work in early userspace.

Install Bootloader

GRUB: You have to make some small changes to the entries generated by the installer by replacing /dev/mapper/root with /dev/sda3. The corrected config looks like this:

# (0) Arch Linux
title Arch Linux
root (hd0,0)
kernel /vmlinuz26 root=/dev/sda3 ro
initrd /kernel26.img

For kernel >= 2.6.30:

# (0) Arch Linux
title Arch Linux
root (hd0,0)
kernel /vmlinuz26 cryptdevice=/dev/sda3:root root=/dev/mapper/root ro
initrd /kernel26.img

LILO: On Lilo, edit the Arch Linux section on /etc/lilo.conf and include a line for append option, over the initrd, with the "root=/dev/sda3" param. The append section make the same kernel line on grub. Also, you can ommit the root option, over the image option. The section look like this:

# Arch Linux lilo section
image = /vmlinuz26
# root = /dev/sda3
 label = Arch
 initrd = /kernel26.img
 append = "root=/dev/sda3"

Note if you want to use a USB stick with a keyfile you have to append the cryptkey option. See the corresponding section below.

Exit Install

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

# vi /mnt/etc/crypttab

Add the following line for the /home partition

home    /dev/sda4    "myotherpassword"

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/sda4    /path/of/your/keyfile

After rebooting you should now be presented with the text

A password is required to access the root filesystem:

followed by a prompt for any LUKS password. Type it in and everything should boot. Once you've 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 isn't, simply enter your password and press return.

Encrypting swap partition

Sensitive data stored in memory may be written to swap at any time. If you've gone to the trouble of encrypting your root and home partitions, you should encrypt your swap as well. There are two options here: random encryption on each boot (better security), or the same encryption each time. We won't cover the second option here, as it is pretty much identical to how you set up the /home partition above. Just replace all references to home with swap, and sda4 with sda2.

Arch Linux provides a convenient way for the first option, which uses dm-crypt directly without LUKS. If you're still in the archsetup process, just switch to a different virtual console (ALT+F2). If you've exited already, the new root will have been unmounted. Use mount /dev/mapper/root /mnt to mount it again.

Now add an entry to the cryptsetup file:

# echo swap /dev/sda2 SWAP "-c aes-xts-plain -h whirlpool -s 512" >> /mnt/etc/crypttab

Note: Recommended hash algorithms are "whirlpool" (patent free), "sha256", "sha384" or "sha512". Default is "ripemd160" (not recommended).

[why is it not recommended? only RIPEMD (128bit) was hacked RIPEMD-160 is still safe[2], isn't it? I heard wirlpool is at least twice as slow. ]

Note: Please take extra care to put the right partition here. The startup script won't ask before overwriting the provided device, destroying all data on it, unless it has a LUKS header, then it simply won't work. If you have been following these instructions closely, then in the section "Mapping Partitions" above you put a LUKS header on your swap partition. Erase it with something like the command below, replacing /dev/sda2 with the appropriate swap device:

# dd if=/dev/zero of=/dev/sda2

From now on, each time you boot, the partition will be encrypted automatically with a random key, and will then be formated with mkswap.

Now all you have to do is adjust the corresponding entry in /etc/fstab:

/dev/mapper/swap swap swap defaults 0 0

And you're done! Carry on with installation or, if you've already finished, umount /mnt.

Encrypted swap 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 LUKS swap partition with a persistent key, which can be stored on the disk or input manually at startup. Because the resume takes place before the crypttab can be used, it is required to create a hook in 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>

To create the swap partition, follow steps similar to those described in mapping partitions above. Omit steps 1 and 2 if you don't intend to use a saved key file.

1. Generate a random key file in a safe place - encrypted root partition like my examples or secure USB stick.

# dd if=/dev/urandom bs=1 count=512 of=/etc/keys/swap.key

2. For security reasons, no user except root should have read-access to this file.

# chown root:root /etc/keys/swap.key
# chmod go-rwx /etc/keys/swap.key

3. Format the partition you want to use as swap with cryptsetup, using the key stored previously. For performance reasons, you might want to use different ciphers with different key sizes. A benchmark can be found here.

# cryptsetup -c aes-xts-plain -s 256 -v luksFormat /dev/<device> /etc/keys/swap.key
* as stated in discussion: the -h parameter to specify hash function is (in this case) ignored, also the default hash - ripemd - is not recommended (citation needed). use aes-xts-plain:whirlpool , or aes-xts-sha256 instead. 
* check result with # cryptsetup luksDump /dev/<device>(sda3)

If you don't use a saved key file, use this command:

# cryptsetup -c aes-xts-plain -s 256 -v luksFormat /dev/<device>

4. Open the partition in /dev/mapper using the key:

# cryptsetup luksOpen /dev/<device> swapDevice -d /etc/keys/swap.key

If you don't use a saved key file, use this command:

# cryptsetup luksOpen /dev/<device> swapDevice

5. Create a swap filesystem inside the mapped partition:

# mkswap /dev/mapper/swapDevice

Now you should have a LUKS swap partition which uses the key file stored in /etc/keys/swap.key or asks for the passphrase before mounting, depending on your choice. Make sure you remove any line in /etc/crypttab which uses this device. Now you have to create a hook to open the swap at boot time.

6. Create a file /lib/initcpio/hooks/openswap containing the open command:

# vim: set ft=sh:
run_hook ()
    cryptsetup luksOpen /dev/<device> swapDevice -d /etc/keys/swap.key

If you don't use a saved key file, openswap should instead contain:

# vim: set ft=sh:
run_hook ()
    cryptsetup luksOpen /dev/<device> swapDevice

7. Then create and edit the hook setup file /lib/initcpio/install/openswap as:

# vim: set ft=sh:

install ()
    add_file "/etc/keys/swap.key"

help ()
  This opens the swap encrypted partition /dev/<device> in /dev/mapper/swapDevice

If you don't use a saved key file, remove unnecessary line add_file "/etc/keys/swap.key" from the file above.

8. Add the hook openswap in the HOOKS array in /etc/mkinitcpio.conf, before filesystem, but after encrypt which is mandatory as well.

9. Regenerate the boot image:

# mkinitcpio -p kernel26

10. Add the mapped partition to /etc/fstab:

/dev/mapper/swapDevice swap swap defaults 0 0

11. 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:

kernel /vmlinuz26 cryptdevice=/dev/sda2:rootDevice root=/dev/mapper/rootDevice resume=/dev/mapper/swapDevice ro

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 stand after openswap 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.

Storing the key externally (USB stick)

Preparation for permanent device names

For reading the file from an USB stick it's important to access it through a permanent device name. The numbering of the normal device names e.g. /dev/sdb1 is somewhat arbitrary and depends on how many storage devices are attached and in what order etc. So in order to assure that the encrypt HOOK in the initcpio finds your keyfile you have to use a permanent device name.

Quick method

A quick method (as opposed to setting up a udev rule) for doing so involves referencing your removable device by its label (or UUID). To find your label or UUID, plug in your USB drive and run

# ls -l /dev/disk/by-label/
lrwxrwxrwx 1 root root 10 12. Feb 10:11 Keys -> ../../sdb1


# ls -l /dev/disk/by-uuid/
lrwxrwxrwx 1 root root 10 12. Feb 10:11 4803-8A7B -> ../../sdb1

In this case I labeled the vfat partition on my USB drive as "Keys" so my device is always symlinked in /dev/disk/by-label/Keys, or If I had wanted to use the UUID I would find /dev/disk/by-uuid/4803-8A7B. This allows me to have a consistent naming of my USB devices regardless of the order they are plugged into the system. These device names can be used in the "cryptkey" kernel option or any where else. 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.

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. Create a UDEV rule instead as described in the following section.

Using UDEV

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

Get the serial number from your USB stick:

lsusb -v | grep -A 5 Vendor

Create a udev-rule for it:

echo 'KERNEL=="sd*", ATTRS{serial}=="$SERIAL", SYMLINK+="$SYMLINK%n"' > /etc/udev/rules.d/8-usbstick.rules

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

Optionally you can mount a tmpfs for storing the temporary keyfile.

# mkdir ./mytmpfs
# mount tmpfs ./mytmpfs -t tmpfs -o size=32m
# cd ./mytmpfs

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'll 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, 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. (due to journaling filesystems etc this is also not 100% secure)

Add the temporary keyfile with cryptsetup:

# 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 stick's file system and one for the codepage. Further if you created a udev-rule you should tell mkinitcpio about it:

MODULES="ata_generic ata_piix nls_cp437 vfat"

In this example it's assumed, that you use a FAT formated stick. 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.

In addition insert the usb hook somewhere before the encrypt hook.

HOOKS="... usb encrypt ... filesystems ..."

Generate a new image (maybe you should take a copy of your old kernel26.img before):

mkinitcpio -g /boot/kernel26.img

Storing the key as plain (visible) file

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

You have to add a kernel parameter in your menu.lst (grub), it should look something like this:

kernel /vmlinuz26 root=/dev/hda3 ro vga=791 cryptkey=/dev/usbstick:vfat:/secretkey

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

That's all, reboot and have fun!

Storing the key between MBR and 1st partition

We'll write the key directly between MBR and 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!

If you have a bootloader installed on your drive you have to adjust the values. E.g. Grub needs the first 16 sectors, 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 don't know if you've got enough free space before the first partition you can do

dd if=/dev/usbstick of=64sectors bs=512 count=64   # gives you copy of your first 64 sectors
hexcurse 64sectors                                 # determine free space
xxd 64sectors | less                               # alternative hex viewer

Write your key to the disk:

dd if=secretkey of=/dev/usbstick bs=512 seek=4

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 menu.lst (Grub), it should look something like this:

kernel /vmlinuz26 root=/dev/hda3 ro vga=791 cryptkey=/dev/usbstick:2048:2048

Format for the cryptkey option:


OFFSET and SIZE match in this example, but this is coincidence - they can differ (and often will). An other possible example could be

kernel /vmlinuz26 root=/dev/hda3 ro vga=791 cryptkey=/dev/usbstick:8192:2048

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

Backup the cryptheader

When the header of your crypted partition was destroyed, you will not be able to decrypt your data. So creating a backup of the headers and storing them on another disk might be a good idea.

Attention: Many people recommend NOT to backup the cryptheader, even so it's a single point failure! In short, the problem is, that LUKS isn't aware of the duplicated cryptheader, which contains the masterkey which is used to encrypt all files on your partition. Of course this masterkey 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 masterkey 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 [3] for further details on this.


First you have to find out the payload offset of the crypted partition (replace sdaX with the corresponding partition)

cryptsetup luksDump /dev/sdaX | grep "Payload offset"
Payload offset:	4040

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

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

Note: you can also backup the header into a tmpfs/ramfs and encrypt it with gpg or whatever before writing it to a physical disk. Of course you can wrap your encrypted backup into another encryption layer and so on until you feel safe enough :-)


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.

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

So, let's start by creating an encrypted container!

dd if=/dev/zero of=/bigsecret bs=1M count=10 # you can also use if=/dev/urandom, if you're really paranoid

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)

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 devicefile /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:

umount /mnt/secret
cryptsetup luksClose secret
losetup -d /dev/loop0 # free the loopdevice.

so, if you want to mount the container again, you just apply the following commands:

losetup /dev/loop0 /bigsecret
cryptsetup luksOpen /dev/loop0 secret
mount -t ext2 /dev/mapper/secret /mnt/secret

Pretty easy, huh?

Encrypt using a key-file

Let's first generate a 2048 Byte random keyfile :

dd if=/dev/urandom of=keyfile bs=1k count=2

We can now format our container using this key

cryptsetup luksFormat /dev/loop0 keyfile

or our partition :

cryptsetup luksFormat /dev/hda2 keyfile

Once formatted, we can now open the luks device using the key:

cryptsetup -d keyfile luksOpen /dev/loop0 container

You can now like before format the device /dev/mapper/container with your favorite filesystem and then mount it just as easily.

The keyfile is now the only key to your file. I personally advise to encrypt your keyfile using your private GPG key and storing an offsite secured copy of the file.

Resizing the loopback filesystem

First we should unmount the encrypted container:

umount /mnt/secret
cryptsetup luksClose secret
losetup -d /dev/loop0 # free the loopdevice.

After this we need to create a second file with the size of the data we want to add:

dd if=/dev/zero of=zeros bs=1M count=1024

You could use /dev/urandom instead of /dev/zero if you're paranoid, but /dev/zero should be faster on older computers. Next we need to add the created file to our container. Be careful to really use TWO ">", or you will override your current container!

cat zeros >> /bigsecret

Now we have to map the container to the loopdevice:

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:

e2fsck -f /dev/mapper/secret # Just doing a filesystem check, because it's a bad idea to resize a broken fs
resize2fs /dev/mapper/secret

You can now mount your container again:

mount /dev/mapper/secret /mnt/secret

Encrypting a LVM setup

It's really easy to use encryption together with LVM. We are not going to cover the process of setting up LVM here as there is already a guide for that (Installing_with_Software_RAID_or_LVM).

The best method and easier method to follow for a laptop is to set up the LVM on top of the encrypted partition instead of the other way around. This link here is easy to follow and explains everything: Arch Linux: LVM on top of an encrypted partition

To use encryption on top of LVM, you have to first setup your lvm volumes and then use them as base for the encrypted partitions. That means in short that you have to setup lvm at first. Then follow this guide, but replace all occurrences of /dev/sdXy in the guide with its lvm counterpart. (eg: /dev/sda4 -> /dev/<volume group name>/home).

Don't forget to add the "lvm2" hook in /etc/mkinitcpio.conf before the "encrypt" hook. And you will have to change USELVM in /etc/rc.conf to yes.

LVM with Arch Linux Installer (>2009.08)

Since Arch Linux images 2009.08 LVM and dm_crypt is supported by the installer out of the box. This makes it very easy to configure your 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 partion 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:

/dev/sda1   raw->ext2;yes;/boot;no_opts;no_label;no_params
/dev/sda2   raw->dm_crypt;yes;no_mountpoint;no_opts;sda2crypt;-c_aes-xts-plain_-y_-s_512
/dev/mapper/sda2crypt   dm_crypt->lvm-vg;yes;no_mountpoint;no_opts;no_label;no_params
/dev/mapper/sda2crypt+  lvm-pv->lvm-vg;yes;no_mountpoint;no_opts;cryptpool;no_params
/dev/mapper/cryptpool   lvm-vg(cryptpool)->lvm-lv;yes;no_mountpoint;no_opts;cryptroot;10000M|lvm-lv;yes;no_mountpoint;no_opts;crypthome;20000M
/dev/mapper/cryptpool-cryptroot   lvm-lv(cryptroot)->ext3;yes;/;no_opts;cryptroot;no_params
/dev/mapper/cryptpool-crypthome   lvm-lv(crypthome)->ext3;yes;/home;no_opts;cryptroot;no_params

The configuration stage

In /etc/rc.conf set USELVM="yes" In /etc/mkinitcpio.conf add lvm2 before encrypt in the HOOKS variable.

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

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. not on any internal HD 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 fstab order (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 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's 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 aren't 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/vmlinuz26 md=1,/dev/hda5,/dev/hdb5

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

kernel /boot/vmlinuz26 root=/dev/md0 ro md=0,/dev/sda1,/dev/sdb1 md=1,/dev/sda5,/dev/sdb5,/dev/sdc5

LVM&dm-crypt manually (short version)


If you're enough smart enough for this, you'll be smart enough to ignore/replace LVM-specific things if you don't want to use LVM.

Partitioning scheme

/dev/sda1 -> /boot
/dev/sda2 -> LVM

The commands =

cryptsetup -d /dev/random -c aes-xts-plain -s 512 create lvm /dev/sda2
dd if=/dev/urandom of=/dev/mapper/lvm
cryptsetup remove lvm
lvm pvcreate /dev/sda2
lvm vgcreate lvm /dev/sda2
lvm lvcreate -L 10G -n root lvm
lvm lvcreate -L 500M -n swap lvm
lvm lvcreate -L 500M -n tmp lvm
lvm lvcreate -l 100%FREE -n home lvm
cryptsetup luksFormat -c aes-xts-plain -s 512 /dev/lvm/root
cryptsetup luksOpen /dev/lvm/root root
mkreiserfs /dev/mapper/root
mount /dev/mapper/root /mnt
dd if=/dev/zero of=/dev/sda1 bs=1M
mkreiserfs /dev/sda1
mkdir /mnt/boot
mount /dev/sda1 /mnt/boot
mkdir -p -m 700 /mnt/etc/luks-keys
dd if=/dev/random of=/mnt/etc/luks-keys/home bs=1 count=256

Install Arch Linux




Change USELVM="no" to USELVM="yes".


Put lvm2 encrypt before filesystems.


Change root=/dev/hda3 to root=/dev/lvm/root.
For kernel >= 2.6.30, you should change root=/dev/hda3 to:

cryptdevice=/dev/lvm/root:root root=/dev/mapper/root
/dev/mapper/root        /       reiserfs        defaults        0       1
/dev/sda1               /boot   reiserfs        defaults        0       2
/dev/mapper/tmp         /tmp    tmpfs           defaults        0       0
/dev/mapper/swap        none    swap            sw              0       0
swap	/dev/lvm/swap	SWAP		-c aes-xts-plain -h whirlpool -s 512
tmp	/dev/lvm/tmp	/dev/urandom	-c aes-xts-plain -s 512

After reboot

The commands
cryptsetup luksFormat -c aes-xts-plain -s 512 /dev/lvm/home /etc/luks-keys/home
cryptsetup luksOpen -d /etc/luks-keys/home /dev/lvm/home home
mkreiserfs /dev/mapper/home
mount /dev/mapper/home /home
home	/dev/lvm/home   /etc/luks-keys/home
/dev/mapper/home        /home   reiserfs        defaults        0       0

/ on lvm on luks

Make sure your kernel commandline looks like this:

root=/dev/mapper/<volume-group>-<logical-volume> cryptdevice=/dev/<luks-part>:<volume-group>

for example:

root=/dev/mapper/vg-arch cryptdevice=/dev/sda4:vg

Or like this:

cryptdevice=/dev/<volume-group>/<logical-volume>:root root=/dev/mapper/root