Difference between revisions of "Dm-crypt"

From ArchWiki
Jump to: navigation, search
(Configuring filesystems and mountpoints)
(Loading kernel modules)
Line 131: Line 131:
  
 
===  Loading kernel modules ===
 
===  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 | 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).
+
{{ 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:
 
Load the dm-crypt and the optimized AES module:
Line 139: Line 139:
 
  # modprobe aes-i586
 
  # modprobe aes-i586
  
'''Note:''' x86_64 users can also try the "aes-x86_64" optimized module instead of "aes-i586".
+
{{ Tip | x86_64 users can also try the "aes-x86_64" optimized module instead of "aes-i586".}}
  
 
=== Mapping partitions ===
 
=== Mapping partitions ===

Revision as of 16:52, 21 August 2010

This template has only maintenance purposes. For linking to local translations please use interlanguage links, see Help:i18n#Interlanguage links.


Local languages: Català – Dansk – English – Español – Esperanto – Hrvatski – Indonesia – Italiano – Lietuviškai – Magyar – Nederlands – Norsk Bokmål – Polski – Português – Slovenský – Česky – Ελληνικά – Български – Русский – Српски – Українська – עברית – العربية – ไทย – 日本語 – 正體中文 – 简体中文 – 한국어


External languages (all articles in these languages should be moved to the external wiki): Deutsch – Français – Română – Suomi – Svenska – Tiếng Việt – Türkçe – فارسی

Summary help replacing me
This tutorial will show you how to set up system encryption with LUKS for dm-crypt.

Contents

Introduction

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!

Warning: 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 (http://loop-aes.sourceforge.net/), 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.

Caveats

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.

Security (encrypted home)

If you install mlocate, it will scan all your currently mounted filesystems regularly, in updatedb. Then it will write the list of filenames to /var/lib/mlocate/mlocate.db, which is in the (less-encrypted) root or /var partition. There might be other packages similar to mlocate. Thus an attacker will have a list of all your filenames, including the ones you illegally downloaded or perhaps you named a file after your secret lover (or your chat client did, somewhere under ~/.chat-client/...). Thus your security would be reduced to the level of eCryptfs. If you're interested in encryption, think twice before sabotaging its potential.

Likewise, it is essential to have all swap be encrypted and /tmp to either be tmpfs or also an encrypted partition; otherwise it is all too easy for information to leak and you not even to realize it is leaking unencrypted onto the disk.

Installation

Warning: 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.
Tip: 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.

Overwriting

Repartitioning and formatting your drive will only remove the filesystem metadata and will mostly leave the actual data intact, allowing determined attackers to recover your data using tools like Foremost. If your harddisk contained sensitive data from previous use, you might want to overwrite that data. And contrary to popular belief, overwriting your data using a random source or overwriting it several times serves no purpose; the original data cannot be recovered once it has been overwritten with 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.

Tip: It is advantageous to subsequently fill the disk from a cryptographically-secure random number generator such as /dev/urandom, so that attackers who get access to your disk (the only people that disk-encryption defends against) cannot tell which blocks of the disk have yet been filled with encrypted data. If they get this information, it both tells them directly something about how much you've used your disk, and also might make the encryption easier to crack, (learning which parts of the disk are used might potentially help them guess which filesystem is inside, and maybe even what size files you've got...). Yes, /dev/urandom takes hours to generate enough data to fill up a modern hard disk, but you only have to do it once.

To overwrite your disk with random information use:

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

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.

Partitioning

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 (extended partition)
/dev/sda5 -> /home
/dev/sda6 -> /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
Tip: x86_64 users can also try the "aes-x86_64" optimized module instead of "aes-i586".

Mapping partitions

Passphrase

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/sda5
Enter passphrase: myotherpassword
Verify passphrase: myotherpassword
# cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/sda6
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/sda5 home
Enter any LUKS passphrase: myotherpassword
key slot 0 unlocked.
Command successful.
# cryptsetup luksOpen /dev/sda6 tmp
Enter any LUKS passphrase: myotherpassword
key slot 0 unlocked.
Command successful.

Keyfile

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/sda5 /mnt/usbstick/mykeyfile
# cryptsetup -c aes-xts-plain -s 512 -v luksFormat /dev/sda6 /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,5,6

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/sda5 home
key slot 0 unlocked.
Command successful.
# cryptsetup -d /mnt/usbstick/mykeyfile luksOpen /dev/sda6 tmp
key slot 0 unlocked.
Command successful.


Explanation

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/sda5 or /dev/sda6 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). Encrypt hook is not needed in case any other partition (swap, for example) is encrypted. System initialization scripts (rc.sysinit and /etc/crypttab among others) take care of those.

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 'keymap' 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"
 read-only

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/sda5    "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/sda5    /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 sda5 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

Warning: don't use this setup with a key file, please read about the issue reported here: http://wiki.archlinux.org/index.php/Talk:System_Encryption_with_LUKS_for_dm-crypt#Suspend_to_disk_instructions_are_insecure

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 presistent LUKS swap partition, 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. The following setup has the disadvantage of having to insert a key manually for the swap partition.

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.

1. Format the partition you want to use as swap with cryptsetup. 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 512 -h sha512 -v luksFormat /dev/<device>

Check result with:

# cryptsetup luksDump /dev/<device>

2. Open the partition in /dev/mapper:

# cryptsetup luksOpen /dev/<device> swapDevice

3. Create a swap filesystem inside the mapped partition:

# mkswap /dev/mapper/swapDevice

Now you should have a LUKS swap partition which asks for the passphrase before mounting. 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.

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

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

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

# vim: set ft=sh:

install ()
{
    MODULES=""
    BINARIES=""
    FILES=""
    SCRIPT="openswap"
}

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

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

7. Regenerate the boot image:

# mkinitcpio -p kernel26

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

/dev/mapper/swapDevice swap swap defaults 0 0

9. 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

or

# 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. (However due to journaling filesystems 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"
FILES="/etc/udev/rules.d/8-usbstick.rules"

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 (actually, it depends on the type of the file system, so don't rely on this too much), 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:

cryptkey=BLOCKDEVICE:OFFSET:SIZE

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.

Backup

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 :-)

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.

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

The most important this in setting LVM on top of encryption is, that you need to have encrypt hook before lvm2 hook (and those two before filesystems hook, but that's repeating). Because they are processed in order.

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/sda5 -> /dev/<volume group name>/home).

Don't forget to add the "lvm2" hook in /etc/mkinitcpio.conf before the "encrypt" hook, if you chose to set up encrypted partition on top of LVM. Also remember 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 if you set up LVM on top of the encrypted partition.

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)

Notes

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

/arch/setup

Configuration

/etc/rc.conf

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

/etc/mkinitcpio.conf

Put lvm2 and encrypt (in that order) before filesystems in the HOOKS variable. Again, note that you are setting encryption on top of LVM.)

/boot/grub/menu.lst

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
/etc/fstab
/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
/etc/crypttab
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
/etc/crypttab
home	/dev/lvm/home   /etc/luks-keys/home
/etc/fstab
/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

Resources