Difference between revisions of "Dm-crypt"

From ArchWiki
Jump to: navigation, search
m (Securing the unencrypted boot partition: -- fix spelling error)
(Undo revision 458633 by Nucleos (talk) there are so many ways to ruin an encrypted volume, this is only an overview page; also added in Special:Diff/457412/458635)
 
(155 intermediate revisions by 24 users not shown)
Line 1: Line 1:
 
{{Lowercase title}}
 
{{Lowercase title}}
[[Category:Security]]
+
[[Category:Encryption]]
 
[[Category:File systems]]
 
[[Category:File systems]]
[[de:ArchLinux mit verschlüsseltem LVM und Systemd]]
+
[[de:dm-crypt]]
 +
[[es:Dm-crypt]]
 
[[fr:LUKS]]
 
[[fr:LUKS]]
 +
[[it:Dm-crypt with LUKS]]
 +
[[ja:Dm-crypt]]
 
[[ru:System Encryption with LUKS]]
 
[[ru:System Encryption with LUKS]]
[[zh-CN:System Encryption with LUKS]]
+
[[zh-CN:Dm-crypt]]
{{Article summary start}}
+
{{Related articles start}}
{{Article summary text|This tutorial will show you how to set up system encryption with LUKS for dm-crypt.}}
+
{{Related|Disk encryption}}
{{Article summary heading|Related}}
+
{{Related|Removing System Encryption}}
{{Article summary wiki|Disk Encryption}}
+
{{Related articles end}}
{{Article summary wiki|Removing System Encryption}}
+
{{Article summary end}}
+
  
This article focuses on how to set up full system encryption on Arch Linux, using dm-crypt with LUKS.
+
From the cryptsetup project's [https://gitlab.com/cryptsetup/cryptsetup/wikis/DMCrypt wiki]:
  
'''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.
+
:Device-mapper is infrastructure in the Linux 2.6 and 3.x kernel that provides a generic way to create virtual layers of block devices. Device-mapper crypt target provides transparent encryption of block devices using the kernel crypto API. The user can basically specify one of the symmetric ciphers, an encryption mode, a key (of any allowed size), an iv generation mode and then the user can create a new block device in /dev. Writes to this device will be encrypted and reads decrypted. You can mount your filesystem on it as usual or stack dm-crypt device with another device like RAID or LVM volume. Basic documentation of dm-crypt mapping table comes with kernel source and the latest version is available in git repository.
  
'''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.
+
==Common scenarios==
 +
This part introduces common scenarios to employ ''dm-crypt'' to encrypt a system or individual filesystem mount points. It is meant as starting point to familiarize with different practical encryption procedures. The scenarios cross-link to the other subpages where needed.  
  
For more details on how dm-crypt+LUKS compares to other disk encryption solution, see [[Disk Encryption#Comparison table]].
+
See [[Dm-crypt/Encrypting a non-root file system]] if you need to encrypt a device that is not used for booting a system, like a [[Dm-crypt/Encrypting a non-root file system#Partition|partition]] or a [[Dm-crypt/Encrypting a non-root file system#Loop device|loop device]].
  
== Caveats ==
+
See [[Dm-crypt/Encrypting an entire system]] if you want to encrypt an entire system, in particular a root partition. Several scenarios are covered, including the use of ''dm-crypt'' with the ''LUKS'' extension, ''plain'' mode encryption and encryption and ''LVM''.
{{Warning|Encrypting a disk or partition will erase everything currently on that disk or partition:
+
* Please make appropriate data backups prior to starting
+
Also be aware that encrypting a system might not only make the life of laptop thieves more miserable, but also yours if you don't plan ahead on
+
* how to make secure backups of the encrypted system/-setup/data and
+
* how to access the encrypted system manually for maintenance.
+
Keeping those points in mind while deciding on how to use encryption may help to decide on method and tools as well.}}
+
  
== Initial Setup ==
+
==Drive preparation==
=== Overview and Preparation ===
+
[[Dm-crypt/Drive preparation]] deals with operations like [[Dm-crypt/Drive preparation#Secure erasure of the hard disk drive|securely erasing the drive]] and ''dm-crypt'' specific points for [[Dm-crypt/Drive preparation#Partitioning|partitioning it]].  
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:
+
  
::* Secure erasure of the hard disk drive(s)
+
==Device encryption==
::* Partitioning and setup of encryption ([[LVM]] optional)
+
[[Dm-crypt/Device encryption]] covers how to manually utilize dm-crypt to encrypt a system through the [[dm-crypt/Device encryption#Cryptsetup usage|cryptsetup]] command. It covers examples of the [[Dm-crypt/Device encryption#Encryption options with dm-crypt|Encryption options with dm-crypt]], deals with the creation of [[dm-crypt/Device encryption#Keyfiles|keyfiles]], LUKS specific commands for [[Dm-crypt/Device_encryption#Key_management|key management]] as well as for  [[Dm-crypt/Device_encryption#Backup_and_restore|Backup and restore]].
::* Routine package selection and installation
+
::* System configuration to handle the encryption
+
  
This page covers the first two points in a general way for different configuration options available with LUKS.  
+
==System configuration==
 +
[[Dm-crypt/System configuration]] illustrates how to configure [[Dm-crypt/System configuration#mkinitcpio|mkinitcpio]], the [[Dm-crypt/System configuration#Boot loader|boot loader]] and the [[Dm-crypt/System configuration#crypttab|crypttab]] file when encrypting a system.
  
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, which is also covered in setup examples in the later sections.
+
==Swap device encryption==
 
+
[[Dm-crypt/Swap encryption]] covers how to add a swap partition to an encrypted system, if required. The swap partition must be encrypted as well to protect any data swapped out by the system. This part details methods [[Dm-crypt_with_LUKS/Swap_Encryption#Without_suspend-to-disk_support|without]] and [[Dm-crypt_with_LUKS/Swap_Encryption#With_suspend-to-disk_support|with]] suspend-to-disk support.
=== Secure erasure of the hard disk drive ===
+
 
+
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 needs only to be performed once for as long as the drive is used as an encrypted drive. For detailed instructions on how to erase and prepare a drive consult [[Securely wipe disk]]. The following methods are specific for dm-crypt/LUKS and are mentioned complementary, because they can be performed after a partition setup too.
+
 
+
==== Use LUKS container as pseudorandom number generator (alternate) ====
+
 
+
The [http://code.google.com/p/cryptsetup/wiki/FrequentlyAskedQuestions#5._Security_Aspects 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.
+
 
+
{{bc|1=
+
# 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.
+
 
+
{{bc|1=
+
# dd if=/dev/zero of=/file/in/luks-container
+
# rm /file/in/luks-container}}
+
 
+
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 {{ic|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 ({{ic|/dev/sda'''1'''}} 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 {{ic|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 everything left on the device is encrypted data. An exception to this may occur for an SSD, because of cache blocks SSDs employ. In theory it may happen that the header was cached in these some time before and that copy may consequently be still available after wiping the original header. For strong security concerns, a secure ATA erase of the SSD should be done (procedure please see the cryptsetup [http://code.google.com/p/cryptsetup/wiki/FrequentlyAskedQuestions#5._Security_Aspects FAQ 5.19]).
+
 
+
====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 [http://asalor.blogspot.de/2011/08/trim-dm-crypt-problems.html blog] of a {{ic|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 {{Pkg|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 {{Pkg|cryptsetup}} version 1.4.0 and up. To add support during boot, you will need to add {{ic|:allow-discards}} to the {{ic|cryptdevice}} option. The TRIM option may look like this:
+
cryptdevice=/dev/mapper/root:root:allow-discards
+
 
+
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.
+
 
+
===Partitioning===
+
 
+
After the drive has been securely overwritten, it is time to create partitions and begin setting up an encrypted system.
+
 
+
There are multiple ways to create disk partitions:
+
 
+
::*[[Partitioning|Standard partitions]]
+
::*[[#LVM:_Logical_Volume_Manager|LVM]]
+
::*[[RAID]]
+
 
+
LUKS can be used with systems that require LVM and/or RAID and is compatible with all regular partitioning standards in Linux.
+
 
+
====Creating Disk Partitions====
+
 
+
There are two required partitions for a basic encrypted system setup:
+
 
+
; root file system: {{ic|'''/'''}} Will be encrypted and store all system and user files ({{ic|/usr}}, {{ic|/bin}}, {{ic|/var}}, {{ic|/home}}, etc.)
+
 
+
; initial boot partition: {{ic|'''/boot'''}} Will ''not'' be encrypted; the bootloader needs to access the {{ic|/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, {{ic|/boot}} needs to reside on its own, unencrypted partition.
+
 
+
This partition layout is encrypted in [[Dm-crypt_with_LUKS#Encrypting_a_system_partition|this example]] and can be refined according to needs, e.g. by separating partitions or adding an encrypted swap-partition.
+
 
+
=====Single Disk Systems=====
+
 
+
If there are additional partitions desired, these can be individually created by defining separate primary or extended/logical partitions. It is possible to encrypt separate partitions (e.g. /home, /var) while leaving others (e.g. /usr) unencrypted as required. However, a standard install would also require separate passphrases or keys to open each encrypted partition during boot.
+
 
+
=====Multiple Disk Systems=====
+
 
+
In systems with multiple hard disk drives, the same options exist as a single disk system. After the creation of the {{ic|/boot}} partition, the remaining free space on the physical disks can be divided up into their respective partitions at this level. For encrypted partitions that span multiple disks, LUKS must be used with RAID or LVM.
+
 
+
====LVM: Logical Volume Manager====
+
 
+
The LVM allows for systems that require complex hard disk configurations. [[LVM|Knowledge of using LVM]] is a requisite to continue with [[Dm-crypt_with_LUKS#Encrypting_a_LVM_setup|setting up LUKS with LVM]] later in this article.
+
 
+
{{Tip|Btrfs has a built-in [[Btrfs#Subvolumes|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 [https://btrfs.wiki.kernel.org/index.php/FAQ#Does_btrfs_support_swap_files.3F not supported] by btrfs up to now.}}
+
 
+
=====LVM on LUKS=====
+
 
+
There is a growing preference towards logical volume management of LUKS encrypted physical media (LVM on LUKS). A reason for this is LVM's flexibility, e.g. for resizing volumes as needed. In a LVM on LUKS scenario, the LUKS-partition has to be opened and mapped before LVM can access the underlaying setup volumes. But once LVM has activated the volumes, the encryption is transparent and LVM tools can be used to change volumes without affecting the LUKS-blockdevice.
+
 
+
This setup is using LUKS as the lowest level of infrastructure most closely approximating 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 may be superfluous depending on requirements (e.g. open-source).
+
 
+
=====LUKS on LVM=====
+
 
+
Other usage scenarios exist where encrypting logical volumes rather than a physical disk is required (LUKS on LVM). One may be a requirement for utmost flexibility of assigning available diskspace across multiple disks, which is not possible with LVM on LUKS. Another scenario may be a mix of unencrypted and encrypted volumes.
+
 
+
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 layers' setup have to be taken into account, i.e. shrinking or expanding an encrypted volume has to include the resizing of the filesystem, which is hidden for LVM inside the encrypted LUKS blockdevice, to ensure filesystem integrity.
+
 
+
== 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 {{ic|/etc/crypttab}} is [http://www.mail-archive.com/arch-projects@archlinux.org/msg02115.html deprecated.]}}
+
 
+
Cryptsetup is used to interface with LUKS for formatting, mounting and unmounting encrypted partitions.
+
 
+
Usage:
+
# cryptsetup [OPTION...] <action> <action-specific>
+
 
+
Example:
+
# cryptsetup --cipher aes-xts-plain64 --key-size 512 --hash sha512 --iter-time 5000 --use-random --verify-passphrase luksFormat <device>
+
 
+
Common options used with luksFormat:
+
 
+
{| class="wikitable" style="margin:0 5em 0.5em 0.5em 0.5em;"
+
! scope="col" style="text-align:left" | Available&nbsp;options
+
! scope="col" style="text-align:left" | Cryptsetup (<1.6.0) defaults
+
! scope="col" style="text-align:left" | Comment
+
! scope="col" style="text-align:left" | Example
+
! scope="col" style="text-align:left" | Comment
+
|-
+
! scope="row" style="text-align:right" | --cipher, -c
+
| {{ic|aes-cbc-essiv:sha256}}
+
| Use the AES-[[Disk_Encryption#Ciphers_and_modes_of_operation|cipher]] with [http://en.wikipedia.org/wiki/Disk_encryption_theory#Cipher-block_chaining_.28CBC.29 CBC/ESSIV].
+
| {{ic|aes-xts-plain64}}
+
| [http://en.wikipedia.org/wiki/Disk_encryption_theory#XEX-based_tweaked-codebook_mode_with_ciphertext_stealing_.28XTS.29 XTS]. For volumes >2TiB use {{ic|aes-xts-plain64}} (requires kernel >= 2.6.33).
+
|-
+
! scope="row" style="text-align:right" | --key-size, -s
+
| {{ic|256}}
+
| The cipher is used with 256 bit key-size.
+
| {{ic|512}}
+
| [http://en.wikipedia.org/wiki/XEX-TCB-CTS#Issues_with_XTS XTS splits the supplied key] into fraternal twins. For an effective AES-256 the XTS key-size must be {{ic|512}}.
+
|-
+
! scope="row" style="text-align:right" | --hash, -h
+
| {{ic|sha1}}
+
| Hash algorithm used for [[Disk_Encryption#Keys.2C_keyfiles_and_passphrases|PBKDF2]].
+
| {{ic|sha512}}
+
|
+
|-
+
! scope="row" style="text-align:right" | --iter-time, -i
+
| {{ic|1000}}
+
| Number of milliseconds to spend with PBKDF2 passphrase processing.
+
| {{ic|5000}}
+
| Using a hash stronger than sha1 results in less iterations if iter-time is not increased.
+
|-
+
! scope="row" style="text-align:right" | --use-random
+
| {{ic|--use-'''u'''random}}
+
| /dev/u[[Random|random]] is used as randomness source for the (long-term) volume master key.
+
| {{ic|--use-random}}
+
| Avoid generating an insecure master key if low on entropy. Will block if the entropy pool is used up.
+
|-
+
! scope="row" style="text-align:right" | --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 {{ic|cryptsetup}} accepts can be found in the [http://www.dsm.fordham.edu/cgi-bin/man-cgi.pl?topic=cryptsetup manpage]. Furthermore,  {{ic|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: {{ic|# modprobe dm_mod}}
+
 
+
In order to format a desired partition as an encrypted LUKS partition execute:
+
{{hc|# cryptsetup -c <cipher> -y -s <key size> luksFormat /dev/<partition name>|
+
Enter passphrase: <password>
+
Verify passphrase: <password>}}
+
 
+
Check results:
+
# cryptsetup luksDump /dev/<drive>
+
 
+
This should be repeated for all partitions except for {{ic|/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'').
+
{{bc|# 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 {{ic|/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 {{ic|/dev/<partition name>}} is actually an encrypted device and should be addressed through LUKS using the {{ic|/dev/mapper/<name>}} so as not to overwrite the encrypted data. To guard against accidental overwriting, read about the possibilities to [[LUKS#Backup_the_cryptheader|backup the cryptheader]] after finishing setup.
+
 
+
In order to open an encrypted LUKS partition execute:
+
{{hc|# cryptsetup luksOpen /dev/<partition name> <device-mapper name>|
+
Enter any LUKS passphrase: <password>
+
key slot 0 unlocked.
+
Command successful.}}
+
 
+
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 {{ic|/dev/mapper/swap}} instead of {{ic|/dev/sda2}}.
+
 
+
; cryptsetup luksOpen /dev/sda3 root: Once opened, the root partition device address would be {{ic|/dev/mapper/root}} instead of {{ic|/dev/sda3}}.
+
 
+
; cryptsetup luksOpen /dev/sda3 lvmpool (alternate): For setting up [[#LVM:_Logical_Volume_Manager|LVM]] ontop the encryption layer the device file  for the decrypted volume group would be anything like {{ic|/dev/mapper/lvmpool}} instead of {{ic|/dev/sda3}}. LVM will then give additional names to all logical volumes created, e.g. {{ic|/dev/mapper/lvmpool-root}} and {{ic|/dev/mapper/lvmpool-swap}}.
+
 
+
In order to write encrypted data into the partition it must be accessed through the device mapped name.
+
 
+
{{Note|Since {{ic|/boot}} is not encrypted, it does not need a device mapped name and will be addressed as {{ic|/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 [https://wiki.archlinux.org/index.php/System_Encryption_with_LUKS#Using_GPG_or_OpenSSL_Encrypted_Keyfiles 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 {{ic|dd}} is used to generate a keyfile of 2048 random bytes.
+
 
+
# dd if=/dev/urandom of=mykeyfile bs=512 count=4
+
 
+
The usage of {{ic|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:
+
 
+
# cryptsetup -c <desired cipher> -s <key size> luksFormat /dev/<volume to encrypt> '''/path/to/mykeyfile'''
+
 
+
This is accomplished by appending the bold area to the standard cryptsetup command which defines where the keyfile is located.
+
 
+
==== Adding Additional Passphrases or Keyfiles to a LUKS Encrypted Partition ====
+
 
+
LUKS supports the association of up to 8 keyslots with any single encrypted volume.
+
Keyslots can be either keyfiles or passphrases.
+
 
+
Once an encrypted partition has been created, the initial keyslot 0 is created. Additional keyslots are numbered from 1 to 7.
+
 
+
Adding new keyslots is accomplished using cryptsetup with the {{ic|luksAddKey}} action.
+
 
+
Don't forget wiping unused keyslots with {{ic|luksKillSlot}} as described in [[#Wipe LUKS keyslots]].)
+
 
+
{{hc|# cryptsetup luksAddKey /dev/<volume> (/path/to/<additionalkeyfile>)|
+
Enter any passphrase:
+
Enter new passphrase for key slot:
+
Verify passphrase:}}
+
 
+
Where <device> is the volume containing the LUKS header to wich the new keyslot is added. This works on header backup files as well.
+
 
+
If {{ic|/path/to/<additionalkeyfile>}} is given, cryptsetup will add a new keyslot for <additionalkeyfile>. Otherwise a new passphrase will be prompted for twice.
+
 
+
For adding keyslots cryptsetup has to decrypt the master key from an existing keyslot so it first asks for "any passphrase" (of an existing keyslot).
+
 
+
For getting the master key from an existing keyfile keyslot the {{ic|--key-file}} or {{ic|-d}} option followed by the "old" <keyfile> will try to unlock all available keyfile keyslots.
+
 
+
# cryptsetup luksAddKey /dev/mapper/<device> (/path/to/<additionalkeyfile>) -d /path/to/<keyfile>
+
 
+
=== 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 {{ic|/dev/sdb1}} whose naming depends on the order in which devices are plugged in. So in order to assure that the {{ic|encrypt}} HOOK in the initcpio finds your keyfile, you must use a permanent device name.
+
 
+
=====Persistent symlinks=====
+
 
+
{{Merge|Persistent block device naming|Anything not specific to storing LUKS keyfiles should get merged there.}}
+
 
+
A quick method (as opposed to setting up a [[udev]] rule) for doing so involves referencing the right partition by its UUID, id (based on hardware info and serial number) or filesystem label.
+
 
+
Plug the device in and print every file name under /dev/disk:
+
 
+
{{hc|#ls -lR /dev/disk/|
+
/dev/disk/:
+
total 0
+
drwxr-xr-x 2 root root 180 Feb 12 10:11 by-id
+
drwxr-xr-x 2 root root  60 Feb 12 10:11 by-label
+
drwxr-xr-x 2 root root 100 Feb 12 10:11 by-path
+
drwxr-xr-x 2 root root 180 Feb 12 10:11 by-uuid
+
 
+
/dev/disk/by-id:
+
total 0
+
lrwxrwxrwx 1 root root  9 Feb 12 10:11 usb-Generic_STORAGE_DEVICE_000000014583-0:0 -> ../../sdb
+
lrwxrwxrwx 1 root root 10 Feb 12 10:11 usb-Generic_STORAGE_DEVICE_000000014583-0:0-part1 -> ../../sdb1
+
 
+
/dev/disk/by-label:
+
total 0
+
lrwxrwxrwx 1 root root 10 Feb 12 10:11 Keys -> ../../sdb1
+
 
+
/dev/disk/by-path:
+
total 0
+
lrwxrwxrwx 1 root root  9 Feb 12 10:11 pci-0000:00:1d.7-usb-0:1:1.0-scsi-0:0:0:0 -> ../../sdb
+
lrwxrwxrwx 1 root root 10 Feb 12 10:11 pci-0000:00:1d.7-usb-0:1:1.0-scsi-0:0:0:0-part1 -> ../../sdb1
+
 
+
/dev/disk/by-uuid:
+
total 0
+
lrwxrwxrwx 1 root root 10 Feb 12 10:11 baa07781-2a10-43a7-b876-c1715aba9d54 -> ../../sdb1}}
+
 
+
'''UUID'''
+
 
+
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 {{ic|/dev/sdb1}} will always get symlinked by {{ic|/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 {{ic|/dev/disk/by-label/Keys}}:
+
 
+
#mkdosfs -n >volume-name< /dev/sdb1
+
 
+
{{hc|#blkid -o list|
+
device    fs_type label    mount point    UUID
+
<nowiki>-------------------------------------------------------</nowiki>
+
/dev/sdb1  vfat    Keys    (not mounted)  221E-09C0}}
+
 
+
{{Note|If you plan to store the keyfile between [[#Storing_the_key_between_MBR_and_1st_partition|MBR and the 1st partition]] you '''cannot use this method''', since it only allows access to the partitions ({{ic|sdb1}}, {{ic|sdb2}}, ...) but not to the USB device ({{ic|sdb}}) itself. Use something like {{ic|/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 [http://reactivated.net/writing_udev_rules.html 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 {{ic|/etc/udev/rules.d/}}, such as {{ic|8-usbstick.rules}}:
+
KERNEL=="sd*", ATTRS{serial}=="$SERIAL", SYMLINK+="$SYMLINK%n"
+
 
+
Replace {{ic|$SYMLINK}} and {{ic|$SERIAL}} with their respective values. {{ic|%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 {{ic|/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. {{ic|/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 [[Securely wipe disk|wipe the entire device]] or at least the keyfiles partition.
+
 
+
Add a keyslot for the temporary keyfile to the LUKS header:
+
{{hc|# 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 {{ic|/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 {{ic|mkinitcpio}} about it:
+
MODULES="ata_generic ata_piix nls_cp437 vfat"
+
FILES="/etc/udev/rules.d/8-usbstick.rules"
+
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 {{ic|keymap}} hook before {{ic|encrypt}}.
+
 
+
Generate a new image (maybe you should backup a copy of your old {{ic|/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 &ndash; a bit of 'security through obscurity' is always nice ;-). Avoid using dotfiles (hidden files) &ndash; the {{ic|encrypt}} hook will fail to find the keyfile during the boot process.
+
 
+
You have to add {{ic|1=cryptdevice=/dev/sda3:root cryptkey=/dev/usbstick:vfat:/secretkey}} to your [[kernel parameters]]. This assumes {{ic|/dev/usbstick}} is the FAT partition of your choice. Replace it with {{ic|/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!'''}}
+
 
+
{{Out of date|[[GRUB Legacy]] is not available anymore and for [[GRUB]] a 1-2MB gap between MBR and the beginning of other written data (e.g. first partition or LUKS-key) is needed for embedding GRUB's {{ic|core.img}}. Information regarding GPT and/or UEFI combinations are required. GRUB has changed parsing configuration.}}
+
 
+
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 {{ic|seek<nowiki>=</nowiki>4}} with {{ic|seek<nowiki>=</nowiki>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
+
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 {{ic|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 {{ic|/boot/grub/menu.lst}} file (GRUB); it should look something like this:
+
  kernel /vmlinuz-linux cryptdevice=/dev/sda3:root root=/dev/mapper/root ro cryptkey=/dev/usb:2048:2048
+
Format for the {{ic|cryptkey}} option:
+
cryptkey=BLOCKDEVICE:OFFSET:SIZE
+
{{ic|OFFSET}} and {{ic|SIZE}} match in this example, but this is just coincidence - they can differ (and often will). An other possible example could be
+
kernel /vmlinuz-linux cryptdevice=/dev/sda3:root root=/dev/mapper/root ro cryptkey=/dev/usb:8192:2048
+
That is all, reboot and have fun! And look if your partitions still work after that ;-).
+
 
+
=== Encrypting the Swap partition ===
+
A swap partition may be added to an encrypted system, if required. Obviously, the swap partition must be encrypted as well to protect any data swapped out by the system. Depending on the requirements, different methods may be used which are described in the following. A setup where the swap encryption is re-initialised on reboot (with a new encryption) provides higher data protection. However, re-encrypting swap also forbids using a suspend-to-disk feature generally.
+
 
+
==== 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 {{ic|/etc/crypttab}} is well commented and you can basically just uncomment the swap line and change <device> to a persistent symlink.
+
 
+
{{hc|/etc/crypttab|# <name>      <device>        <password>              <options>
+
# swap        /dev/hdx4        /dev/urandom            <nowiki>swap,cipher=aes-cbc-essiv:sha256,size=256</nowiki>}}
+
 
+
Where:
+
; <name>: Represents the name ({{ic|/dev/mapper/<name>}}) to list in /etc/fstab.
+
; <device>: Should be the symlink to the actual partition's device file.
+
; <password>: {{ic|/dev/urandom}} sets the dm-crypt master key to be randomized on every volume recreation.
+
; <options>: The {{ic|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 {{ic|/dev/disk/}} read on in the section on [[#Preparation for Persistent block device naming]]
+
 
+
{{hc|#ls -l <nowiki>/dev/disk/*/* |</nowiki> grep sda2|
+
lrwxrwxrwx 1 root root 10 Oct 12 16:54 /dev/disk/by-id/ata-WDC_WD2500BEVT-22ZCT0_WD-WXE908VF0470-part2 -> ../../sda2}}
+
 
+
Example line for the {{ic|/dev/sda2}} symlink from above:
+
 
+
{{hc|/etc/crypttab|# <name>                      <device>                                  <password>    <options>
+
  swap  /dev/disk/by-id/ata-WDC_WD2500BEVT-22ZCT0_WD-WXE908VF0470-part2  /dev/urandom  <nowiki>swap,cipher=aes-cbc-essiv:sha256,size=256</nowiki>}}
+
 
+
This will map {{ic|/dev/sda2}} to {{ic|/dev/mapper/swap}} as a swap partition that can be added in {{ic|/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 [[#Wipe_LUKS_header|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 {{ic|/etc/crypttab}} can be used, it is required to create a hook in {{ic|/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 {{ic|/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 [[Talk:System Encryption with LUKS for dm-crypt#Suspend to disk instructions are insecure|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.
+
 
+
Open the partition in {{ic|/dev/mapper}}:
+
# cryptsetup luksOpen /dev/<device> swapDevice
+
 
+
Create a swap filesystem inside the mapped partition:
+
# mkswap /dev/mapper/swapDevice
+
 
+
Now you have to create a hook to open the swap at boot time.
+
 
+
* Create a hook file containing the open command:
+
 
+
{{hc|/lib/initcpio/hooks/openswap|<nowiki>
+
# vim: set ft=sh:
+
run_hook ()
+
{
+
    cryptsetup luksOpen /dev/<device> swapDevice
+
}
+
</nowiki>}}
+
 
+
for opening the swap device by typing your password or
+
 
+
{{hc|/lib/initcpio/hooks/openswap|<nowiki>
+
# vim: set ft=sh:
+
run_hook ()
+
{
+
    mkdir crypto_key_device
+
    mount /dev/mapper/<root-device> crypto_key_device
+
    cryptsetup luksOpen --key-file crypto_key_device/<path-to-the-key> /dev/<device> swapDevice
+
    umount crypto_key_device
+
}
+
</nowiki>}}
+
 
+
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 {{ic|--allow-discards}} has to get added to the cryptsetup line in the openswap hook above. See [[#Discard.2FTRIM_support_for_solid_state_disks_.28SSD.29|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.''}}
+
 
+
* Then create and edit the hook setup file:
+
{{hc|/lib/initcpio/install/openswap|<nowiki>
+
# vim: set ft=sh:
+
build ()
+
{
+
  add_runscript
+
}
+
help ()
+
{
+
cat<<HELPEOF
+
  This opens the swap encrypted partition /dev/<device> in /dev/mapper/swapDevice
+
HELPEOF
+
}
+
</nowiki>}}
+
 
+
* Add the hook {{ic|openswap}} in the {{ic|HOOKS}} array in {{ic|/etc/mkinitcpio.conf}}, before {{ic|filesystem}} but after {{ic|encrypt}}. Do not forget to add the {{ic|resume}} hook after {{ic|openswap}}.
+
<nowiki>HOOKS="... encrypt openswap resume filesystems ..."</nowiki>
+
* Regenerate the boot image:
+
 
+
# mkinitcpio -p linux
+
 
+
* Add the mapped partition to {{ic|/etc/fstab}} by adding the following line:
+
/dev/mapper/swapDevice swap swap defaults 0 0
+
 
+
* Set up your system to resume from {{ic|/dev/mapper/swapDevice}}. For example, if you use [[GRUB]] with kernel hibernation support, add {{ic|resume<nowiki>=</nowiki>/dev/mapper/swapDevice}} to the kernel line in {{ic|/boot/grub/grub.cfg}}. A line with encrypted root and swap partitions can look like this:
+
 
+
kernel /vmlinuz-linux cryptdevice=/dev/sda2:rootDevice root=/dev/mapper/rootDevice resume=/dev/mapper/swapDevice ro
+
 
+
To make the parameter persistent on kernel updates, add it to {{ic|/etc/default/grub}}.
+
 
+
At boot time, the {{ic|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 '''after''' {{ic|openswap}} in the {{ic|HOOKS}} array. Please note that because of initrd opening swap, there is no entry for swapDevice in {{ic|/etc/crypttab}} needed in this case.
+
 
+
==== Using a swap file for suspend-to-disk support ====
+
A swap file can be used to reserve swap-space within an existing partition and may also be setup inside an encrypted blockdevice's partition. When resuming from a swapfile the {{ic|resume}} hook must be supplied with the passphrase to unlock the device where the swap file is located. To create it: 
+
* Choose a mapped partition (e.g. {{ic|/dev/mapper/rootDevice}}) whose mounted filesystem (e.g. {{ic|/}}) contains enough free space to create a swapfile with the desired size.
+
 
+
* [[HOW_TO:_Create_swap_file#Swap_file_creation | Create the swap file]] (e.g. {{ic|/swapfile}}) inside the mounted filesystem of your chosen mapped partition.  Be sure to activate it with {{ic|swapon}} and also add it to your {{ic|/etc/fstab}} file afterward. Note that the swapfile's previous contents remain transparent over reboots.
+
 
+
* Set up your system to resume from your chosen mapped partition. For example, if you use [[GRUB]] with kernel hibernation support, add {{ic|resume<nowiki>=</nowiki>}}''your chosen mapped partition'' and {{ic|resume_offset<nowiki>=</nowiki>}}''see calculation command below'' to the kernel line in {{ic|/boot/grub/grub.cfg}}. A line with encrypted root partition can look like this:
+
 
+
kernel /vmlinuz-linux cryptdevice=/dev/sda2:rootDevice root=/dev/mapper/rootDevice resume=/dev/mapper/rootDevice resume_offset=123456789 ro
+
 
+
The {{ic|resume_offset}} of the swap-file points to the start (extent zero) of the file and can be identified like this:
+
 
+
# filefrag -v /swapfile | awk '{if($1==0){print $3}}'
+
 
+
* Add the {{ic|resume}} hook to your {{ic|etc/mkinitcpio.conf}} file and [[Mkinitcpio#Image_creation_and_activation|rebuild the image]] afterward:
+
 
+
HOOKS="... encrypt '''resume''' ... filesystems ..."
+
 
+
* If you use a USB keyboard to enter your decryption password, then the {{ic|keyboard}} module '''must''' appear in front of the {{ic|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! (If you still have this problem after adding {{ic|keyboard}}, try {{ic|usbinput}}, though this is deprecated.)
+
 
+
HOOKS="... '''keyboard''' encrypt ..."
+
 
+
== 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 [http://code.google.com/p/cryptsetup/wiki/FrequentlyAskedQuestions#6._Backup_and_Data_Recovery| LUKS FAQ] for further details on this.
+
 
+
=== Backup ===
+
==== Using cryptsetup ====
+
Cryptsetups {{ic|luksHeaderBackup}} action stores a binary backup of the LUKS header and keyslot area:
+
# cryptsetup luksHeaderBackup /dev/<device> --header-backup-file /mnt/<backup>/<file>.img
+
where <device> is the partition containing the LUKS volume.
+
 
+
{{Note|Using {{ic|-}} as header backup file writes to a file named {{ic|-}}.}}
+
 
+
{{Tip|You can also back up the plaintext header into ramfs and encrypt it in example with gpg before writing to persistent backup storage by executing the following commands.}}
+
{{bc|# mkdir /root/<tmp>/
+
# mount ramfs /root/<tmp>/ -t ramfs
+
# cryptsetup luksHeaderBackup /dev/<device> --header-backup-file /root/<tmp>/<file>.img
+
# gpg2 --recipient <User ID> --encrypt /root/<tmp>/<file>.img
+
# cp /root/<tmp>/<file>.img.gpg /mnt/<backup>/
+
# umount /root/<tmp>}}
+
{{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:
+
{{hc|# cryptsetup luksDump /dev/<device> <nowiki>|</nowiki> grep "Payload offset"|
+
Payload offset: 4040}}
+
Second check the sector size of the drive
+
{{hc|# fdisk -l /dev/<device> <nowiki>|</nowiki>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 ====
+
Or you can use the luksHeaderRestore command:
+
cryptsetup luksHeaderRestore /dev/sdaX --header-backup-file ./backup.img
+
 
+
'''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 system partition ==
+
 
+
{{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 {{ic|/}} (e.g. {{ic|/dev/sdaX}}) and {{ic|/boot}} ({{ic|/dev/sdaY}}) at least, following the [[Installation_Guide|Installation Guide]] and deciding against [[LUKS#Encrypting a LVM setup|using LVM]]. Prior to creating the partitions you have done a [[LUKS#Secure_erasure_of_the_hard_disk_drive|preparation]] of the disk for encryption according to your necessities (the necessary tools are on the installation-ISO).
+
 
+
First check, if the blockdevice mapper {{ic|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 [[LUKS#Using_LUKS_to_Format_Partitions_with_a_Passphrase|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 {{ic|/home}} partition, the steps have to be adapted and repeated for that. However, this may be inconvenient, because it would result in a separate passphrase to be input as well. An alternative is to use a key-file stored in the system partition to unlock the separate partition via {{ic|crypttab}}. How that is done may be derived from the [[Dm-crypt_with_LUKS#Encrypting_.2Fhome_after_reboot|LVM example]] below. If you leave unpartitioned disk space, the necessary configuration may be done later too along with migration data.
+
+
What you do have to setup is a non-encrypted {{ic|/boot}} partition, which is needed for a crypted root. For a standard [[EFI|MBR/non-EFI]] {{ic|/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 [[Installation_Guide#Mount_the_partitions|Arch Install Scripts]]. Take care to install the bootloader to {{ic|/mnt/boot}} with the {{ic|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 {{ic|/etc/mkinitcpio.conf}}. The one you ''have'' to add when encrypting the root filesystem is {{ic|encrypt}}. A recommended hook for LUKS encrypted blockdevices is {{ic|shutdown}} to ensure controlled unmounting during system shutdown. Others needed, e.g. {{ic|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 {{ic|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 {{ic|encrypt}} hook is not needed for any other encrypted partitions (swap, for example). System initialization scripts ({{ic|/etc/rc.sysinit}} and {{ic|/etc/crypttab}} among others) take care of those.}}
+
 
+
It is important that the {{ic|encrypt}} hook comes ''before'' the {{ic|filesystems}} hook (in case you are using '''LVM on LUKS''', the order should be: {{ic|encrypt lvm2 filesystems}}), so make sure that your {{ic|HOOKS}} array looks something like this:
+
{{hc|etc/mkinitcpio.conf|HOOKS<nowiki>=</nowiki>"(base udev) ... '''encrypt''' ... filesystems ..."}}
+
 
+
If you need support for foreign keymaps for your encryption password, you have to specify the hook {{ic|keymap}} as well before {{ic|encrypt}}.
+
 
+
If you have a USB keyboard, you will need the {{ic|keyboard}} hook. Without it, no USB keyboard will work in early userspace. If you still have this problem after adding {{ic|keyboard}}, try {{ic|usbinput}}, though this is deprecated.
+
 
+
In the same file, you may want to add to "MODULES" '''dm_mod''' and the filesystem types used, e.g: {{ic|MODULES<nowiki>=</nowiki>"dm_mod ext4"}}
+
 
+
After you are done don't forget:
+
mkinitcpio -p linux
+
 
+
=== Kernel parameter configuration of the bootloader ===
+
In order to enable booting an encrypted root partition, it is passed to the {{ic|encrypt}} hook with [[kernel parameters]] to be set up in the bootloader.
+
The main parameter is '''cryptdevice''', with the following syntax:
+
cryptdevice=<device>:<dmname>
+
; <device>: The path to the raw encrypted device. Usage of [[Persistent block device naming]] is advisable.
+
; <dmname>: The name given to the device after decryption, will be available as {{ic|/dev/mapper/<dmname>}}. (<dmname> '''MUST NOT''' be set to a name already used for LVM partitions!)
+
 
+
So if the encrypted root device in the example is {{ic|/dev/sda2}} and the decrypted one should be mapped to {{ic|/dev/mapper/cryptroot}}, the kernel parameter would be:
+
cryptdevice=/dev/sda2:cryptroot
+
This will make the system prompt for the passphrase to unlock the root device on a cold boot.
+
 
+
Depending on the setup other parameters are required as well:
+
cryptdevice=<device>:<dmname> root=<device> resume=<device> cryptkey=<device>:<fstype>:<path>
+
 
+
; root=<device>: The device file of the actual (decrypted) root filesystem. If the filesystem is formatted directly on the decrypted device file this will be {{ic|/dev/mapper/<dmname>}}. If LVM is used, the device must be addressed like {{ic|/dev/mapper/<volgroup>-<pvol>}} or {{ic|/dev/<volgroup>/<pvol>}}.
+
; resume=<device>: The device file of the decrypted (swap) filesystem used for suspend2disk.
+
; cryptkey=<nowiki><device>:<fstype>:<path></nowiki>: Required for reading a [[#Storing_the_Key_File|keyfile]] from a filesystem.
+
 
+
The syntax for the optional '''cryptkey''' parameter is:
+
 
+
cryptkey=<device>:<fstype>:<path>
+
 
+
; <device>: The raw block device where the key exists.
+
; <fstype>: The filesystem type of <device> (or auto).
+
; <path>: The absolute path of the keyfile within the device.
+
 
+
Examples on configuration for [[GRUB#Root encryption|GRUB]] and [[Syslinux#Basic Config|Syslinux]] are available on the respective pages.
+
 
+
=== Fstab ===
+
Further, double-check the {{ic|gen[[fstab]]}} scripts result for your {{ic|/dev/mapper/cryptroot}} and other mounts.
+
 
+
== 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 {{ic|bigsecret}} with a size of 10 megabytes.
+
 
+
losetup /dev/loop0 /bigsecret
+
 
+
This will create the device node {{ic|/dev/loop0}}, so that we can mount/use our container.
+
 
+
{{Note|If it gives you the error {{ic|/dev/loop0: No such file or directory}}, you need to first load the kernel module with {{ic|modprobe loop}}. These days (Kernel 3.2) loop devices are created on demand. Ask for a new loop device with {{ic|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 {{ic|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 {{ic|modprobe dm-mod}}.}}
+
 
+
cryptsetup luksOpen /dev/loop0 secret
+
 
+
The encrypted container is now available through the device file {{ic|/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
+
 
+
=== Encrypt using a key-file ===
+
Let us 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 {{ic|/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 encrypting your keyfile using your private GPG key and storing an off-site 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 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 {{ic|>}}, or you will override your current container!
+
 
+
You could use {{ic|/dev/zero}} instead of {{ic|/dev/urandom}} to significantly speed up the process, but with {{ic|/dev/zero}} your encrypted filesystems will ''not be as secure''. (A better option to create random data quicker than {{ic|/dev/urandom}} is {{ic|frandom}} [https://aur.archlinux.org/packages.php?ID=9869], available from the [[AUR]]).
+
A faster (almost instant) method than dd is {{ic|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:
+
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 is easy to use encryption with [[LVM]]. This section describes specific aspects of setting up an encrypted LVM setup and has a mini-howto for users with experiences of using both, cryptsetup and LVM. If you are looking for verbose installation instructions of such a setup, you might want to read [[Encrypted_LVM]] first.
+
 
+
If you do not know how to set up LVM, then read [[Installing with Software RAID or LVM]]. Using LVM is particularly helpful when a system with multiple partitions is planned. While there are a number of alternatives for unlocking multiple partitions with the same passphrase/key, the default Arch {{ic|mkinitcpio}} hooks do not implement non-standard ways. A combination of the {{ic|encrypt}} and {{ic|lvm2}} hooks, however, enables to setup a system with numerous logical volumes as partitions while using one passphrase/key to unlock them.
+
 
+
'''LVM on LUKS'''
+
 
+
The straight-forward method is to set up LVM on top of the encrypted partition instead of the other way round. Technically the LVM is setup inside one big encrypted blockdevice. Hence, the LVM is not transparent until the blockdevice is unlocked and the underlying volume structure is scanned and mounted during boot.
+
 
+
The most important thing in setting LVM on '''top''' of encryption is to [[#Configure initramfs|configure the initramfs]] for running '''both''' the {{ic|encrypt}} hook '''and''' the {{ic|lvm2}} hook (and those two before the {{ic|filesystems}} hook). In the past, it was necessary to ensure the correct ordering of these hooks in {{ic|/etc/mkinitcpio.conf}} but the order no longer matters with the current implementation of {{ic|lvm2}}.
+
 
+
'''LUKS on LVM'''
+
 
+
To use encryption on top of LVM, the LVM volumes are set up first and then used as the base for the encrypted partitions. This way around a mixture of encrypted and non-encrypted volumes/partitions is possible as well.
+
 
+
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 {{ic|encrypt}} hook in {{ic|/etc/mkinitcpio.conf}} '''after''' the {{ic|lvm2}} hook, if you chose to set up encrypted partitions on '''top''' of LVM.
+
 
+
Both these options are described in more detail in [[Encrypted_LVM]]. The following represents the historic guide from before the verbose page.
+
 
+
=== LVM and dm-crypt manually (short version) ===
+
 
+
The following short example creates a LUKS on LVM setup and mixes in the use of a key-file for the /home partition and temporary crypt volumes for /tmp and /swap. The latter is considered desirable from a security perspective, because no potentially sensitive temporary data survives the reboot, when the encryption is re-initialised. If you are experienced with LVM, you will be able to ignore/replace LVM- and other specifics according to your plan. For {{ic|cryptsetup}} options, please see [[Dm-crypt_with_LUKS#Configuring_LUKS|above]].
+
 
+
==== Partitioning scheme ====
+
{{ic|/dev/sda1}} -> {{ic|/boot}}
+
{{ic|/dev/sda2}} -> LVM
+
 
+
==== Setting up the encrypted system ====
+
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 ====
+
Now after setup of the encrypted LVM partitioning, it would be time to install: [[Installation_Guide#Mount_the_partitions|Arch Install Scripts]].
+
 
+
==== Configuration ====
+
 
+
===== /etc/mkinitcpio.conf =====
+
Put {{ic|lvm2}} and {{ic|encrypt}} (in that order) before {{ic|filesystems}} in the {{ic|HOOKS}} array. Again, note that this is setting encryption on '''top''' of LVM.
+
 
+
If you want install the system on a usb stick, you need to put {{ic|usb}} just after {{ic|udev}}.
+
 
+
===== Boot options for LUKS-LVM =====
+
For the above example, change the kernel options for the root-device auto-configured in the bootloader installation from {{ic|root<nowiki>=</nowiki>/dev/hda3}} to
+
cryptdevice=/dev/lvm/root:root root=/dev/mapper/root
+
 
+
More general, the kernel command line for LUKS <-> LVM is constructed 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
+
 
+
If you want install the system on a usb stick, you need to add {{ic|lvmdelay<nowiki>=</nowiki>/dev/mapper/lvm-root}}
+
 
+
===== Filesystem mounts system =====
+
{{hc|/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}}
+
 
+
{{hc|/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}}
+
 
+
===== Encrypting /home after reboot =====
+
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
+
 
+
===== Filesystem mounts home =====
+
{{hc|/etc/crypttab|
+
home /dev/lvm/home  /etc/luks-keys/home}}
+
 
+
{{hc|/etc/fstab|
+
/dev/mapper/home        /home  reiserfs        defaults        0      0}}
+
  
 
==Specialties==
 
==Specialties==
===Using GPG or OpenSSL Encrypted Keyfiles===
+
[[Dm-crypt/Specialties]] deals with special operations like [[Dm-crypt/Specialties#Securing the unencrypted boot partition|securing the unencrypted boot partition]], [[Dm-crypt/Specialties#Using GPG or OpenSSL Encrypted Keyfiles|using GPG or OpenSSL encrypted keyfiles]], a method to [[Dm-crypt/Specialties#Remote_unlocking_of_the_root_.28or_other.29_partition|boot and unlock via the network]], another for [[Dm-crypt/Specialties#Discard.2FTRIM_support_for_solid_state_drives_.28SSD.29|setting up discard/TRIM for a SSD]], and sections dealing with [[Dm-crypt/Specialties#The_encrypt_hook_and_multiple_disks|the encrypt hook and multiple disks]].  
The following forum posts give instructions to use two factor authentication, gpg or openssl encrypted keyfiles, instead of a plaintext keyfile described earlier in this wiki article [https://bbs.archlinux.org/viewtopic.php?id=120243 System Encryption using LUKS with GPG encrypted keys]:
+
* GnuPG: [https://bbs.archlinux.org/viewtopic.php?pid=943338#p943338 Post regarding GPG encrypted keys] This post has the generic instructions.
+
* OpenSSL: [https://bbs.archlinux.org/viewtopic.php?pid=947805#p947805 Post regarding OpenSSL encrypted keys] This post only has the {{ic|ssldec}} hooks.
+
* OpenSSL: [https://bbs.archlinux.org/viewtopic.php?id=155393 Post regarding OpenSSL salted bf-cbc encrypted keys] This post has the {{ic|bfkf}} initcpio hooks, install, and encrypted keyfile generator scripts.
+
 
+
Note that:
+
* 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 {{ic|/etc/mkinitcpio.conf}}
+
should look like
+
{{ic|HOOKS&#61;" ... usb usbinput (etwo or ssldec) encrypt(if using openssl) lvm2 resume ... "}}
+
and you should add {{ic|"resume&#61;/dev/mapper/<VolumeGroupName>-<LVNameOfSwap>"}} to your [[kernel parameters]].
+
* If you need to temporarily store the unecrypted keyfile somewhere, do not store them on an unencrypted disk. Even better make sure to store them to RAM such as {{ic|/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 [https://aur.archlinux.org/packages.php?ID=58030 gnupg1]
+
* It is possible that an update to OpenSSL could break the custom {{ic|ssldec}} mentioned in the second forum post.
+
 
+
===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 {{ic|net}} hook along with an [[SSH]] server in initrd. Install the {{AUR|dropbear_initrd_encrypt}} package from the [[Arch User Repository|AUR]] and follow the post-installation instructions. Replace the {{ic|encrypt}} hook with {{ic|dropbear encryptssh}} in {{ic|/etc/mkinitcpio.conf}}. Put the {{ic|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 {{ic|/home}})remotely, you may want to look at [https://bbs.archlinux.org/viewtopic.php?pid=880484 this forum thread].
+
 
+
===Modifying the encrypt hook for a non-root partition===
+
Maybe you have a requirement for using the {{ic|encrypt}} hook on a non-root partition. Arch does not support this out of the box, however, you can easily change the cryptdev and cryptname values in {{ic|/lib/initcpio/hooks/encrypt}} (the first one to your {{ic|/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 {{ic|/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 {{ic|/etc/fstab}} (at least).
+
 
+
Of course, if the {{pkg|cryptsetup}} package gets upgraded, you will have to change this script again. Unlike {{ic|/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 {{ic|/dev/mdX}} device in {{ic|/lib/initcpio/hooks/encrypt}} is not enough; the {{ic|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 {{ic|encrypt}} hook is run. You can solve this by putting the RAID array in {{ic|/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:
+
kernel /boot/vmlinuz-linux root=/dev/md0 ro md=0,/dev/sda1,/dev/sdb1 md=1,/dev/sda5,/dev/sdb5,/dev/sdc5
+
 
+
===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 files under {{ic|/boot}} for changes of SHA-1 hash, inode and occupied blocks on the hard drive. It also checks the MBR. The script cannot prevent certain type of attacks, but a lot are made harder. No configuration of the script itself is stored in unencrypted {{ic|/boot}}. With a locked/powered-off crypted system this makes it infeasible for an attacker to recognize that an automatic checksum comparison of the partition is done upon boot.
+
 
+
The script with installation instructions is available here: ftp://ftp.heise.de/pub/ct/listings/1203-146.zip (Author: Juergen Schmidt, ju at heisec.de; License: GPLv2). There is also an AUR package: {{AUR|chkboot}}
+
 
+
After installation:
+
* For classical sysvinit: add {{ic|/usr/local/bin/chkboot.sh &}} to your {{ic|/etc/rc.local}}
+
* For systemd: add a service file and enable the service: [[systemd]]. The service file might look like:
+
[Unit]
+
Description=Check that boot is what we want
+
Requires=basic.target
+
After=basic.target
+
+
[Service]
+
Type=oneshot
+
ExecStart=/usr/local/bin/chkboot.sh
+
+
[Install]
+
WantedBy=multi-user.target
+
 
+
There is a small caveat for systemd: At the time of writing the original {{ic|chkboot.sh}} script provided contains an empty space at the beginning of {{ic|<u> </u>#!/bin/bash}} which has to be removed for the service to start successfully.
+
 
+
As {{ic|/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 {{ic|/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:
+
 
+
#!/bin/bash
+
#
+
# Note: Insert your <user>  and execute it with sudo for pacman & chkboot to work automagically
+
#
+
echo "Pacman update [1] Quickcheck before updating" &
+
sudo -u <user> /usr/local/bin/chkboot_user.sh # insert your logged on <user>
+
/usr/local/bin/chkboot.sh
+
sync # sync disks with any results
+
sudo -u <user> /usr/local/bin/chkboot_user.sh # insert your logged on <user>
+
echo "Pacman update [2] Syncing repos for pacman"
+
pacman -Syu
+
/usr/local/bin/chkboot.sh
+
sync
+
sudo -u <user> /usr/local/bin/chkboot_user.sh # insert your logged on <user>
+
echo "Pacman update [3] All done, let's roll on ..."
+
 
+
===Automount user homes on login===
+
See [[Pam mount]].
+
  
== Resources ==
+
== See also ==
* [http://code.google.com/p/cryptsetup/wiki/FrequentlyAskedQuestions cryptsetup FAQ] - The main and foremost help resource, directly from the developers.
+
* [https://gitlab.com/cryptsetup/cryptsetup/wikis/DMCrypt dm-crypt] - The project homepage
* [http://www.freeotfe.org/ FreeOTFE] - Supports unlocking LUKS encrypted volumes in Microsoft Windows.
+
* [https://gitlab.com/cryptsetup/cryptsetup cryptsetup] - The LUKS homepage and [https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions FAQ] - the main and foremost help resource.  
 +
* [https://git.kernel.org/cgit/utils/cryptsetup/cryptsetup.git/ cryptsetup repository] and [https://www.kernel.org/pub/linux/utils/cryptsetup/ release] archive.
 +
* [https://github.com/t-d-k/doxbox DOXBOX] - Supports unlocking LUKS encrypted volumes in Microsoft Windows.

Latest revision as of 14:30, 7 December 2016

From the cryptsetup project's wiki:

Device-mapper is infrastructure in the Linux 2.6 and 3.x kernel that provides a generic way to create virtual layers of block devices. Device-mapper crypt target provides transparent encryption of block devices using the kernel crypto API. The user can basically specify one of the symmetric ciphers, an encryption mode, a key (of any allowed size), an iv generation mode and then the user can create a new block device in /dev. Writes to this device will be encrypted and reads decrypted. You can mount your filesystem on it as usual or stack dm-crypt device with another device like RAID or LVM volume. Basic documentation of dm-crypt mapping table comes with kernel source and the latest version is available in git repository.

Common scenarios

This part introduces common scenarios to employ dm-crypt to encrypt a system or individual filesystem mount points. It is meant as starting point to familiarize with different practical encryption procedures. The scenarios cross-link to the other subpages where needed.

See Dm-crypt/Encrypting a non-root file system if you need to encrypt a device that is not used for booting a system, like a partition or a loop device.

See Dm-crypt/Encrypting an entire system if you want to encrypt an entire system, in particular a root partition. Several scenarios are covered, including the use of dm-crypt with the LUKS extension, plain mode encryption and encryption and LVM.

Drive preparation

Dm-crypt/Drive preparation deals with operations like securely erasing the drive and dm-crypt specific points for partitioning it.

Device encryption

Dm-crypt/Device encryption covers how to manually utilize dm-crypt to encrypt a system through the cryptsetup command. It covers examples of the Encryption options with dm-crypt, deals with the creation of keyfiles, LUKS specific commands for key management as well as for Backup and restore.

System configuration

Dm-crypt/System configuration illustrates how to configure mkinitcpio, the boot loader and the crypttab file when encrypting a system.

Swap device encryption

Dm-crypt/Swap encryption covers how to add a swap partition to an encrypted system, if required. The swap partition must be encrypted as well to protect any data swapped out by the system. This part details methods without and with suspend-to-disk support.

Specialties

Dm-crypt/Specialties deals with special operations like securing the unencrypted boot partition, using GPG or OpenSSL encrypted keyfiles, a method to boot and unlock via the network, another for setting up discard/TRIM for a SSD, and sections dealing with the encrypt hook and multiple disks.

See also