https://wiki.archlinux.org/api.php?action=feedcontributions&user=Zkosfonn&feedformat=atomArchWiki - User contributions [en]2024-03-29T13:06:24ZUser contributionsMediaWiki 1.41.0https://wiki.archlinux.org/index.php?title=Dm-crypt/Device_encryption&diff=457957Dm-crypt/Device encryption2016-11-28T17:03:30Z<p>Zkosfonn: iflag=fullblock is not needed for non-blocking /dev/urandom</p>
<hr />
<div>{{Lowercase title}}<br />
[[Category:Encryption]]<br />
[[Category:File systems]]<br />
[[ja:Dm-crypt/デバイスの暗号化]]<br />
Back to [[Dm-crypt]].<br />
<br />
This section covers how to manually utilize ''dm-crypt'' from the command line to encrypt a system. <br />
<br />
== Preparation ==<br />
Before using {{pkg|cryptsetup}}, always make sure the {{ic|dm-crypt}} [[kernel module]] is loaded.<br />
<br />
== Cryptsetup usage ==<br />
''Cryptsetup'' is the command line tool to interface with ''dm-crypt'' for creating, accessing and managing encrypted devices. The tool was later expanded to support different encryption types that rely on the Linux kernel '''d'''evice-'''m'''apper and the '''crypt'''ographic modules. The most notable expansion was for the Linux Unified Key Setup (LUKS) extension, 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. Devices accessed via the device-mapper are called blockdevices. For further information see [[Disk encryption#Block device encryption]]. <br />
<br />
The tool is used as follows: <br />
<br />
# cryptsetup <OPTIONS> <action> <action-specific-options> <device> <dmname><br />
<br />
It has compiled-in defaults for the options and the encryption mode, which will be used if no others are specified on the command line. Have a look at <br />
<br />
$ cryptsetup --help <br />
<br />
which lists options, actions and the default parameters for the encryption modes in that order. A full list of options can be found on the man page.<br />
Since different parameters are required or optional, depending on encryption mode and action, the following sections point out differences further. Blockdevice encryption is fast, but speed matters a lot too. Since changing an encryption cipher of a blockdevice after setup is difficult, it is important to check ''dm-crypt'' performance for the individual parameters in advance: <br />
<br />
$ cryptsetup benchmark <br />
<br />
can give guidance on deciding for an algorithm and key-size prior to installation. If certain AES ciphers excel with a considerable higher throughput, these are probably the ones with hardware support in the CPU.<br />
<br />
{{Tip|You may want to practise encrypting a virtual hard drive in a [[:Category:Virtualization|virtual machine]] when learning.}}<br />
<br />
=== Cryptsetup passphrases and keys ===<br />
An encrypted blockdevice is protected by a key. A key is either: <br />
<br />
* a passphrase: see [[Disk encryption#Choosing a strong passphrase]].<br />
* a keyfile, see [[#Keyfiles]].<br />
<br />
Both key types have default maximum sizes: passphrases can be up to 512 characters and keyfiles up to 8192kiB. <br />
<br />
An important distinction of ''LUKS'' to note at this point is that the key is used to unlock the master-key of a LUKS-encrypted device and can be changed with root access. Other encryption modes do not support changing the key after setup, because they do not employ a master-key for the encryption. See [[Disk encryption#Block device encryption]] for details.<br />
<br />
== Encryption options with dm-crypt ==<br />
''Cryptsetup'' supports different encryption operating modes to use with ''dm-crypt''. The most common (and default) is <br />
*{{ic|--type LUKS}} <br />
The other ones are <br />
*{{ic|--type plain}} for using dm-crypt plain mode, <br />
*{{ic|--type loopaes}} for a loopaes legacy mode, and <br />
*{{ic|--type tcrypt}} for a [[Truecrypt]] compatibility mode. <br />
<br />
The basic cryptographic options for encryption cipher and hashes available can be used for all modes and rely on the kernel cryptographic backend features. All that are loaded at runtime can be viewed with <br />
$ less /proc/crypto <br />
and are available to use as options. If the list is short, execute {{ic|cryptsetup benchmark}} which will trigger loading available modules. <br />
<br />
The following introduces encryption options for the first two modes. Note that the tables list options used in the respective examples in this article and not all available ones. <br />
<br />
=== Encryption options for LUKS mode ===<br />
<br />
The ''cryptsetup'' action to set up a new dm-crypt device in LUKS encryption mode is ''luksFormat''. Unlike the name implies, it does not format the device, but sets up the LUKS device header and encrypts the master-key with the desired cryptographic options. <br />
<br />
As LUKS is the default encryption mode,<br />
<br />
# cryptsetup -v luksFormat ''device''<br />
<br />
is all that is needed to create a new LUKS device with default parameters ({{ic|-v}} is optional). For comparison, we can specify the default options manually too: <br />
<br />
# cryptsetup -v --cipher aes-xts-plain64 --key-size 256 --hash sha256 --iter-time 2000 --use-urandom --verify-passphrase luksFormat ''device''<br />
<br />
Defaults are compared with a cryptographically higher specification example in the table below, with accompanying comments: <br />
<br />
{| class="wikitable"<br />
! scope="col" style="text-align:left" | Options<br />
! scope="col" style="text-align:left" | Cryptsetup 1.7.0 defaults <br />
! scope="col" style="text-align:left" | Example<br />
! scope="col" style="text-align:left" | Comment<br />
|-<br />
! scope="row" style="text-align:right" | --cipher, -c<br />
| {{ic|aes-xts-plain64}}<br />
| {{ic|aes-xts-plain64}}<br />
| [https://www.kernel.org/pub/linux/utils/cryptsetup/v1.6/v1.6.0-ReleaseNotes Release 1.6.0] changed the defaults to an AES [[Disk encryption#Ciphers_and_modes_of_operation|cipher]] in [[wikipedia:Disk_encryption_theory#XEX-based_tweaked-codebook_mode_with_ciphertext_stealing_.28XTS.29|XTS]] mode (see item 5.16 [https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions#5-security-aspects of the FAQ]). It is advised against using the previous default {{ic|--cipher aes-cbc-essiv}} because of its known [https://en.wikipedia.org/wiki/Disk_encryption_theory#Cipher-block_chaining_.28CBC.29 issues] and practical [http://www.jakoblell.com/blog/2013/12/22/practical-malleability-attack-against-cbc-encrypted-luks-partitions/ attacks] against them.<br />
|-<br />
! scope="row" style="text-align:right" | --key-size, -s<br />
| {{ic|256}}<br />
| {{ic|512}}<br />
| By default a 256 bit key-size is used. Note however that [[wikipedia:Disk_encryption_theory#XEX-based_tweaked-codebook_mode_with_ciphertext_stealing_.28XTS.29|XTS splits the supplied key in half]], so to use AES-256 instead of AES-128 you have to set the XTS key-size to {{ic|512}}.<br />
|-<br />
! scope="row" style="text-align:right" | --hash, -h<br />
| {{ic|sha256}}<br />
| {{ic|sha512}}<br />
| Hash algorithm used for [[Disk_encryption#Cryptographic_metadata|key derivation]]. Release 1.7.0 changed defaults from {{ic|sha1}} to {{ic|sha256}} "''not for security reasons [but] mainly to prevent compatibility problems on hardened systems where SHA1 is already [being] phased out''"[https://www.kernel.org/pub/linux/utils/cryptsetup/v1.7/v1.7.0-ReleaseNotes]. The former default of {{ic|sha1}} can still be used for compatibility with older versions of ''cryptsetup'' since it is [https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions#5-security-aspects considered secure] (see item 5.20). <br />
|-<br />
! scope="row" style="text-align:right" | --iter-time, -i<br />
| {{ic|2000}}<br />
| {{ic|5000}}<br />
| Number of milliseconds to spend with PBKDF2 passphrase processing. Release 1.7.0 changed defaults from {{ic|1000}} to {{ic|2000}} to "''try to keep PBKDF2 iteration count still high enough and also still acceptable for users.''"[https://www.kernel.org/pub/linux/utils/cryptsetup/v1.7/v1.7.0-ReleaseNotes]. This option is only relevant for LUKS operations that set or change passphrases, such as ''luksFormat'' or ''luksAddKey''. Specifying 0 as parameter selects the compiled-in default..<br />
|-<br />
! scope="row" style="text-align:right" | --use-{u,}random<br />
| {{ic|--use-urandom}}<br />
| {{ic|--use-random}}<br />
| Selects which [[random number generator]] to use. Quoting the cryptsetup manual page: "In a low-entropy situation (e.g. in an embedded system), both selections are problematic. Using /dev/urandom can lead to weak keys. Using /dev/random can block a long time, potentially forever, if not enough entropy can be harvested by the kernel."<br />
|-<br />
! scope="row" style="text-align:right" | --verify-passphrase, -y<br />
| Yes<br />
| -<br />
| Default only for luksFormat and luksAddKey. No need to type for Arch Linux with LUKS mode at the moment. <br />
|}<br />
<br />
If you want to deep-dive into cryptographic features of LUKS, the [https://gitlab.com/cryptsetup/cryptsetup/wikis/Specification LUKS specification] (e.g. its appendices) is a resource. <br />
{{Tip|It is anticipated that the LUKS header receives another major revision in due course. If you are interested in the plans, the developers' [https://mbroz.fedorapeople.org/talks/DevConf2016/devconf2016-luks2.pdf devconfcz2016] (pdf) presentation summarizes.}}<br />
<br />
=== Encryption options for plain mode ===<br />
In dm-crypt ''plain'' mode, there is no master-key on the device, hence, there is no need to set it up. Instead the encryption options to be employed are used directly to create the mapping between an encrypted disk and a named device. The mapping can be created against a partition or a full device. In the latter case not even a partition table is needed. <br />
<br />
To create a ''plain'' mode mapping with cryptsetup's default parameters: <br />
# cryptsetup <options> open --type plain <device> <dmname><br />
Executing it will prompt for a password, which should have very high entropy. <br />
Below a comparison of default parameters with the example in [[Dm-crypt/Encrypting an entire system#Plain dm-crypt]]<br />
<br />
{| class="wikitable"<br />
! Option !! Cryptsetup 1.7.0 defaults !! Example !! Comment<br />
|-<br />
| '''--hash''' || {{ic|ripemd160}} || - || The hash is used to create the key from the passphrase; it is not used on a keyfile. <br />
|-<br />
| '''--cipher'''|| {{ic|aes-cbc-essiv:sha256}}|| {{ic|twofish-xts-plain64}} || The cipher consists of three parts: cipher-chainmode-IV generator. Please see [[Disk encryption#Ciphers and modes of operation]] for an explanation of these settings, and the [https://gitlab.com/cryptsetup/cryptsetup/wikis/DMCrypt DMCrypt documentation] for some of the options available. <br />
|-<br />
| '''--key-size'''||{{ic|256}}||{{ic|512}}||The key size (in bits). The size will depend on the cipher being used and also the chainmode in use. Xts mode requires twice the key size of cbc. <br />
|-<br />
| '''--offset'''||{{ic|0}}||{{ic|0}}||The offset from the beginning of the target disk (in bytes) from which to start the mapping<br />
|-<br />
| '''--key-file'''||default uses a passphrase||{{ic|/dev/sd''Z''}} (or e.g. /boot/keyfile.enc)||The device or file to be used as a key. See [[#Keyfiles]] for further details.<br />
|-<br />
| '''--keyfile-offset'''||{{ic|0}}||{{ic|0}}||Offset from the beginning of the file where the key starts (in bytes). This option is supported from ''cryptsetup'' 1.6.7 onwards. <br />
|-<br />
| '''--keyfile-size'''||{{ic|8192kB}}||- (default applies)||Limits the bytes read from the key file. This option is supported from ''cryptsetup'' 1.6.7 onwards. <br />
|}<br />
<br />
Using the device {{ic|/dev/sd''X''}}, the above right column example results in:<br />
{{bc|<nowiki># cryptsetup --cipher=twofish-xts-plain64 --offset=0 --key-file=</nowiki>/dev/sd''Z'' <nowiki>--key-size=512 open --type=plain /dev/sdX enc</nowiki>}}<br />
Unlike encrypting with LUKS, the above command must be executed ''in full'' whenever the mapping needs to be re-established, so it is important to remember the cipher, hash and key file details.<br />
We can now check that the mapping has been made:<br />
# fdisk -l<br />
An entry should now exist for {{ic|/dev/mapper/enc}}.<br />
<br />
== Encrypting devices with cryptsetup ==<br />
This section shows how to employ the options for creating new encrypted blockdevices and accessing them manually. <br />
<br />
=== Encrypting devices with LUKS mode ===<br />
==== Formatting LUKS partitions ====<br />
<br />
In order to setup a partition as an encrypted LUKS partition execute:<br />
<br />
# cryptsetup luksFormat ''device''<br />
<br />
You will then be prompted to enter a password and verify it.<br />
<br />
See [[#Encryption options for LUKS mode]] for command line options.<br />
<br />
You can check the results with:<br />
<br />
# cryptsetup luksDump ''device''<br />
<br />
You will note that the dump not only shows the cipher header information, but also the key-slots in use for the LUKS partition. <br />
<br />
The following example will create an encrypted root partition on {{ic|/dev/sda1}} using the default AES cipher in XTS mode with an effective 256-bit encryption <br />
{{bc|# cryptsetup -s 512 luksFormat /dev/sda1}}<br />
<br />
=====Using LUKS to format partitions with a keyfile=====<br />
<br />
When creating a new LUKS encrypted partition, a keyfile may be associated with the partition on its creation using:<br />
<br />
# cryptsetup luksFormat ''device'' ''/path/to/mykeyfile''<br />
<br />
This is accomplished by appending the bold area to the standard cryptsetup command which defines where the keyfile is located.<br />
<br />
See [[#Keyfiles]] for instructions on how to generate and manage keyfiles.<br />
<br />
====Unlocking/Mapping LUKS partitions with the device mapper ====<br />
<br />
Once the LUKS partitions have been created, they can then be unlocked.<br />
<br />
The unlocking process will map the partitions to a new device name using the device mapper. This alerts the kernel that {{ic|''device''}} is actually an encrypted device and should be addressed through LUKS using the {{ic|/dev/mapper/''dm_name''}} so as not to overwrite the encrypted data. To guard against accidental overwriting, read about the possibilities to [[Dm-crypt/Device encryption#Backup_and_restore|backup the cryptheader]] after finishing setup.<br />
<br />
In order to open an encrypted LUKS partition execute:<br />
<br />
# cryptsetup open --type luks ''device'' ''dm_name''<br />
<br />
You will then be prompted for the password to unlock the partition. Usually the device mapped name is descriptive of the function of the partition that is mapped. For example the following unlocks a luks partition {{ic|/dev/sda1}} and maps it to device mapper named {{ic|cryptroot}}:<br />
<br />
# cryptsetup open --type luks /dev/sda1 cryptroot <br />
<br />
Once opened, the root partition device address would be {{ic|/dev/mapper/cryptroot}} instead of the partition (e.g. {{ic|/dev/sda1}}). <br />
<br />
For setting up LVM ontop the encryption layer the device file for the decrypted volume group would be anything like {{ic|/dev/mapper/cryptroot}} instead of {{ic|/dev/sda1}}. LVM will then give additional names to all logical volumes created, e.g. {{ic|/dev/mapper/lvmpool-root}} and {{ic|/dev/mapper/lvmpool-swap}}.<br />
<br />
In order to write encrypted data into the partition it must be accessed through the device mapped name. The first step of access will typically be to [[File_systems#Formatting|create a filesystem]]. For example:<br />
<br />
# mkfs -t ext4 /dev/mapper/cryptroot<br />
<br />
The device {{ic|/dev/mapper/cryptroot}} can then be [[mount]]ed like any other partition.<br />
<br />
To close the luks container, unmount the partition and do:<br />
<br />
# cryptsetup close cryptroot<br />
<br />
=== Encrypting devices with plain mode ===<br />
<br />
The creation and subsequent access of a ''dm-crypt'' plain mode encryption both require not more than using the ''cryptsetup'' {{ic|open}} action with correct [[Dm-crypt/Device encryption#Encryption_options_for_plain_mode|parameters]]. The following shows that with two examples of non-root devices, but adds a quirk by stacking both (i.e. the second is created inside the first). Obviously, stacking the encryption doubles overhead. The usecase here is simply to illustrate another example of the cipher option usage. <br />
<br />
A first mapper is created with ''cryptsetup's'' plain-mode defaults, as described in the table's left column above <br />
# cryptsetup --type plain -v open /dev/sdaX plain1 <br />
Enter passphrase: <br />
Command successful.<br />
# <br />
Now we add the second blockdevice inside it, using different encryption parameters and with an (optional) offset, create a filesystem and mount it <br />
# cryptsetup --type plain --cipher=serpent-xts-plain64 --hash=sha256 --key-size=256 --offset=10 open /dev/mapper/plain1 plain2<br />
Enter passphrase: <br />
# lsblk -p <br />
NAME <br />
/dev/sda <br />
├─/dev/sdaX <br />
│ └─/dev/mapper/plain1 <br />
│ └─/dev/mapper/plain2 <br />
...<br />
# mkfs -t ext2 /dev/mapper/plain2<br />
# mount -t ext2 /dev/mapper/plain2 /mnt<br />
# echo "This is stacked. one passphrase per foot to shoot." > /mnt/stacked.txt<br />
We close the stack to check access works<br />
# cryptsetup close plain2<br />
# cryptsetup close plain1<br />
First, let's try to open the filesystem directly: <br />
# cryptsetup --type plain --cipher=serpent-xts-plain64 --hash=sha256 --key-size=256 --offset=10 open /dev/sdaX plain2<br />
# mount -t ext2 /dev/mapper/plain2 /mnt<br />
mount: wrong fs type, bad option, bad superblock on /dev/mapper/plain2,<br />
missing codepage or helper program, or other error<br />
Why that did not work? Because the "plain2" starting block (10) is still encrypted with the cipher from "plain1". It can only be accessed via the stacked mapper. The error is arbitrary though, trying a wrong passphrase or wrong options will yield the same. For ''dm-crypt'' plain mode, the {{ic|open}} action will not error out itself. <br />
<br />
Trying again in correct order: <br />
# cryptsetup close plain2 # dysfunctional mapper from previous try<br />
# cryptsetup --type plain open /dev/sdaX plain1<br />
Enter passphrase: <br />
# cryptsetup --type plain --cipher=serpent-xts-plain64 --hash=sha256 --key-size=256 --offset=10 open /dev/mapper/plain1 plain2 <br />
Enter passphrase: <br />
# mount /dev/mapper/plain2 /mnt && cat /mnt/stacked.txt<br />
This is stacked. one passphrase per foot to shoot.<br />
# exit<br />
''dm-crypt'' will handle stacked encryption with some mixed modes too. For example LUKS mode could be stacked on the "plain1" mapper. Its header would then be encrypted inside "plain1" when that is closed.<br />
<br />
Available for plain mode only is the option {{ic|--shared}}. With it a single device can be segmented into different non-overlapping mappers. We do that in the next example, using a ''loopaes'' compatible cipher mode for "plain2" this time: <br />
# cryptsetup --type plain --offset 0 --size 1000 open /dev/sdaX plain1 <br />
Enter passphrase: <br />
# cryptsetup --type plain --offset 1000 --size 1000 --shared --cipher=aes-cbc-lmk --hash=sha256 open /dev/sdaX plain2<br />
Enter passphrase: <br />
# lsblk -p<br />
NAME <br />
dev/sdaX <br />
├─/dev/sdaX <br />
│ ├─/dev/mapper/plain1 <br />
│ └─/dev/mapper/plain2 <br />
...<br />
As the devicetree shows both reside on the same level, i.e. are not stacked and "plain2" can be opened individually.<br />
<br />
== Cryptsetup actions specific for LUKS ==<br />
=== Key management ===<br />
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: In a so-called key escrow, one key is used for daily usage, another kept in escrow to gain access to the partition in case the daily passphrase is forgotten or a keyfile is lost/damaged. 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. <br />
<br />
Once an encrypted partition has been created, the initial keyslot 0 is created (if no other was specified manually). Additional keyslots are numbered from 1 to 7. Which keyslots are used can be seen by issuing <br />
{{hc|# cryptsetup luksDump /dev/<device> <nowiki>|</nowiki>grep BLED|<br />
Key Slot 0: ENABLED<br />
Key Slot 1: ENABLED<br />
Key Slot 2: ENABLED<br />
Key Slot 3: DISABLED<br />
Key Slot 4: DISABLED<br />
Key Slot 5: DISABLED<br />
Key Slot 6: DISABLED<br />
Key Slot 7: DISABLED}}<br />
<br />
Where <device> is the volume containing the LUKS header. This and all the following commands in this section work on header backup files as well. <br />
<br />
==== Adding LUKS keys ====<br />
<br />
Adding new keyslots is accomplished using cryptsetup with the {{ic|luksAddKey}} action. For safety it will always, i.e. also for already unlocked devices, ask for a valid existing key ("any passphrase") before a new one may be entered:<br />
<br />
# cryptsetup luksAddKey /dev/<device> (/path/to/<additionalkeyfile>) <br />
Enter any passphrase:<br />
Enter new passphrase for key slot:<br />
Verify passphrase: <br />
<br />
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 using an existing ''keyfile'' to authorize the action, the {{ic|--key-file}} or {{ic|-d}} option followed by the "old" <keyfile> will try to unlock all available keyfile keyslots:<br />
<br />
# cryptsetup luksAddKey /dev/<device> (/path/to/<additionalkeyfile>) -d /path/to/<keyfile><br />
<br />
If it is intended to use multiple keys and change or revoke them, the {{ic|--key-slot}} or {{ic|-S}} option may be used to specify the slot: <br />
# cryptsetup luksAddKey /dev/<device> -S 6 <br />
Enter any passphrase: <br />
Enter new passphrase for key slot: <br />
Verify passphrase:<br />
# cryptsetup luksDump /dev/sda8 |grep 'Slot 6'<br />
Key Slot 6: ENABLED<br />
<br />
To show an associated action in this example, we decide to change the key right away: <br />
# cryptsetup luksChangeKey /dev/<device> -S 6 <br />
Enter LUKS passphrase to be changed: <br />
Enter new LUKS passphrase: <br />
<br />
before continuing to remove it.<br />
<br />
==== Removing LUKS keys ====<br />
<br />
There are three different actions to remove keys from the header: <br />
*{{ic|luksRemoveKey}} is used to remove a key by specifying its passphrase/key-file. <br />
*{{ic|luksKillSlot}} may be used to remove a key from a specific key slot (using another key). Obviously, this is extremely useful if you have forgotten a passphrase, lost a key-file, or have no access to it. <br />
*{{ic|luksErase}} is used to quickly remove '''all''' active keys. <br />
{{warning|<br />
*All above actions can be used to irrevocably delete the last active key for an encrypted device! <br />
*The {{ic|luksErase}} command was added in version 1.6.4 to quickly nuke access to the device. This action '''will not''' prompt for a valid passphrase! It will not [[Dm-crypt/Drive_preparation#Wipe_LUKS_header|wipe the LUKS header]], but all keyslots at once and you will, therefore, not be able to regain access unless you have a valid backup of the LUKS header.}} <br />
<br />
For above warning it is good to know the key we want to '''keep''' is valid. An easy check is to unlock the device with the {{ic|-v}} option, which will specify which slot it occupies: <br />
{{bc|# cryptsetup -v open /dev/<device> testcrypt<br />
Enter passphrase for /dev/<device>: <br />
Key slot 1 unlocked.<br />
Command successful.}}<br />
<br />
Now we can remove the key added in the previous subsection using its passphrase: <br />
# cryptsetup luksRemoveKey /dev/<device><br />
Enter LUKS passphrase to be deleted: <br />
If we had used the same passphrase for two keyslots, the first slot would be wiped now. Only executing it again would remove the second one. <br />
<br />
Alternatively, we can specify the key slot: <br />
# cryptsetup luksKillSlot /dev/<device> 6<br />
Enter any remaining LUKS passphrase:<br />
<br />
Note that in both cases, no confirmation was required.<br />
# cryptsetup luksDump /dev/sda8 |grep 'Slot 6'<br />
Key Slot 6: DISABLED<br />
To re-iterate the warning above: If the same passphrase had been used for key slots 1 and 6, both would be gone now.<br />
<br />
=== Backup and restore ===<br />
If the header of a LUKS encrypted partition gets destroyed, you will not be able to decrypt your data. It is just as much of a dilemma as forgetting the passphrase or damaging a key-file used to unlock the partition. 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 header and storing it on another disk might be a good idea.<br />
<br />
{{Note|If the LUKS-encrypted partitions' master passphrase becomes compromised, you must revoke it on ''every'' copy of the cryptheader, even those you have backed up. Otherwise, a copy of the backed-up cryptheader that uses the compromised passphrase can be used to decrypt the associated partition. See [https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions#6-backup-and-data-recovery LUKS FAQ] for further details.}}<br />
<br />
==== Backup using cryptsetup ====<br />
Cryptsetup's {{ic|luksHeaderBackup}} action stores a binary backup of the LUKS header and keyslot area:<br />
# cryptsetup luksHeaderBackup /dev/<device> --header-backup-file /mnt/<backup>/<file>.img<br />
where <device> is the partition containing the LUKS volume.<br />
<br />
{{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.}}<br />
{{bc|# mkdir /root/<tmp>/<br />
# mount ramfs /root/<tmp>/ -t ramfs<br />
# cryptsetup luksHeaderBackup /dev/<device> --header-backup-file /root/<tmp>/<file>.img<br />
# gpg2 --recipient <User ID> --encrypt /root/<tmp>/<file>.img <br />
# cp /root/<tmp>/<file>.img.gpg /mnt/<backup>/<br />
# umount /root/<tmp>}}<br />
{{Warning|Tmpfs can swap to harddisk if low on memory so it is not recommended here.}}<br />
<br />
==== Restore using cryptsetup ====<br />
<br />
{{Warning|Restoring the wrong header or restoring to an unencrypted partition will cause data loss! The action can not perform a check whether the header is actually the ''correct'' one for that particular device.}} <br />
<br />
In order to evade restoring a wrong header, you can ensure it does work by using it as a remote {{ic|--header}} first: <br />
<br />
# cryptsetup -v --header /mnt/<backup>/<file>.img open /dev/<device> test <br />
Key slot 0 unlocked.<br />
Command successful.<br />
# mount /dev/mapper/test /mnt/test && ls /mnt/test <br />
# umount /mnt/test <br />
# cryptsetup close test <br />
<br />
Now that the check succeeded, the restore may be performed: <br />
# cryptsetup luksHeaderRestore /dev/<device> --header-backup-file ./mnt/<backup>/<file>.img<br />
<br />
Now that all the keyslot areas are overwritten; only active keyslots from the backup file are available after issuing the command.<br />
<br />
==== Manual backup and restore ====<br />
The header always resides at the beginning of the device and a backup can be performed without access to ''cryptsetup'' as well. First you have to find out the payload offset of the crypted partition:<br />
{{hc|# cryptsetup luksDump /dev/<device> <nowiki>|</nowiki> grep "Payload offset"|<br />
Payload offset: 4040}}<br />
Second check the sector size of the drive<br />
{{hc|# fdisk -l /dev/<device> <nowiki>|</nowiki>grep "Sector size"|Sector size (logical/physical): 512 bytes / 512 bytes}}<br />
<br />
Now that you know the values, you can backup the header with a simple dd command:<br />
# dd if=/dev/<device> of=/path/to/<file>.img bs=512 count=4040<br />
and store it safely.<br />
<br />
A restore can then be performed using the same values as when backing up:<br />
# dd if=./<file>.img of=/dev/<device> bs=512 count=4040<br />
<br />
=== Re-encrypting devices ===<br />
<br />
The {{Pkg|cryptsetup}} package features the ''cryptsetup-reencrypt'' tool. It can be used to convert an existing unencrypted filesystem to a LUKS encrypted one (option {{ic|--new}}) and permanently remove LUKS encryption ({{ic|--decrypt}}) from a device. As its name suggests it can also be used to re-encrypt an existing LUKS encrypted device, though, re-encryption is not possible for a detached LUKS header or other encryption modes (e.g. plain-mode). For re-encryption it is possible to change the [[#Encryption options for LUKS mode]]. ''cryptsetup-reencrypt'' actions can be performed to unmounted devices only. See {{ic|man cryptsetup-reencrypt}} for more information. <br />
<br />
One application of re-encryption may be to secure the data again after a passphrase or [[#Keyfiles|keyfile]] has been compromised ''and'' one cannot be certain that no copy of the LUKS header has been obtained. For example, if only a passphrase has been shoulder-surfed but no physical/logical access to the device happened, it would be enough to change the respective passphrase/key only ([[#Key management]]). <br />
<br />
{{Warning|Always make sure a '''reliable backup''' is available and double-check options you specify before using the tool!}}<br />
<br />
The following shows an example to encrypt an unencrypted filesystem partition and a re-encryption of an existing LUKS device. <br />
<br />
==== Encrypt an unencrypted filesystem ====<br />
<br />
A LUKS encryption header is always stored at the beginning of the device. Since an existing filesystem will usually be allocated all partition sectors, the first step is to shrink it to make space for the LUKS header. <br />
<br />
The [[#Encryption_options_for_LUKS_mode|default]] LUKS header encryption cipher requires {{ic|4096}} 512-byte sectors. We already checked space and keep it simple by shrinking the existing {{ic|ext4}} filesystem on {{ic|/dev/sdaX}} to its current possible minimum: <br />
<br />
{{bc|# umount /mnt<br />
# e2fsck -f /dev/sdaX <br />
e2fsck 1.43-WIP (18-May-2015)<br />
Pass 1: Checking inodes, blocks, and sizes<br />
...<br />
/dev/sda6: 12/166320 files (0.0% non-contiguous), 28783/665062 blocks<br />
# resize2fs -M /dev/sdaX<br />
resize2fs 1.43-WIP (18-May-2015)<br />
Resizing the filesystem on /dev/sdaX to 26347 (4k) blocks.<br />
The filesystem on /dev/sdaX is now 26347 (4k) blocks long.}}<br />
<br />
Now we encrypt it, using the default cipher we do not have to specify it explicitly. Note there is no option (yet) to double-check the passphrase before encryption starts, be careful not to mistype: <br />
<br />
{{hc|# cryptsetup-reencrypt /dev/sdaX --new --reduce-device-size 4096S|<br />
WARNING: this is experimental code, it can completely break your data.<br />
Enter new passphrase: <br />
Progress: 100,0%, ETA 00:00, 2596 MiB written, speed 37,6 MiB/s}}<br />
<br />
After it finished, the encryption was performed to the full partition, i.e. not only the space the filesystem was shrunk to ({{ic|sdaX}} has {{ic|2.6GiB}} and the CPU used in the example has no hardware AES instructions). As a final step we extend the filesystem of the now encrypted device again to occupy available space: <br />
<br />
{{bc|# cryptsetup open /dev/sdaX recrypt <br />
Enter passphrase for /dev/sdaX: <br />
...<br />
# resize2fs /dev/mapper/recrypt <br />
resize2fs 1.43-WIP (18-May-2015)<br />
Resizing the filesystem on /dev/mapper/recrypt to 664807 (4k) blocks.<br />
The filesystem on /dev/mapper/recrypt is now 664807 (4k) blocks long.<br />
# mount /dev/mapper/recrypt /mnt}}<br />
<br />
and are done.<br />
<br />
==== Re-encrypting an existing LUKS partition ====<br />
<br />
In this example an existing LUKS device is re-encrypted. <br />
<br />
{{Warning|Double-check you specify encryption options for ''cryptsetup-reencrypt'' correctly and ''never'' re-encrypt without a '''reliable backup'''! As of September 2015 the tool '''does''' accept invalid options and damage the LUKS header, if not used correctly!}}<br />
<br />
In order to re-encrypt a device with its existing encryption options, they do not need to be specified. A simple: <br />
<br />
{{hc|# cryptsetup-reencrypt /dev/sdaX| <br />
WARNING: this is experimental code, it can completely break your data.<br />
Enter passphrase for key slot 0: <br />
Progress: 100,0%, ETA 00:00, 2596 MiB written, speed 36,5 MiB/s}}<br />
<br />
performs it. <br />
<br />
A possible usecase is to re-encrypt LUKS devices which have non-current encryption options. Apart from above warning on specifying options correctly, the ability to change the LUKS header may also be limited by its size. For example, if the device was initially encrypted using a CBC mode cipher and 128 bit key-size, the LUKS header will be half the size of above mentioned {{ic|4096}} sectors: <br />
{{hc|# cryptsetup luksDump /dev/sdaX <nowiki>|</nowiki>grep -e "mode" -e "Payload" -e "MK bits"|<br />
Cipher mode: cbc-essiv:sha256<br />
Payload offset: '''2048'''<br />
MK bits: 128}}<br />
While it is possible to upgrade the encryption of such a device, it is currently only feasible in two steps. First, re-encrypting with the same encryption options, but using the {{ic|--reduce-device-size}} option to make further space for the larger LUKS header. Second, re-encypt the whole device again with the desired cipher. For this reason and the fact that a backup should be created in any case, creating a new, fresh encrypted device to restore into is always the faster option.<br />
<br />
== Keyfiles ==<br />
<br />
{{Note|This section describes using a plaintext keyfile. If you want to encrypt your keyfile giving you two factor authentication see [[Dm-crypt/Specialties#Using_GPG_or_OpenSSL_Encrypted_Keyfiles|Using GPG or OpenSSL Encrypted Keyfiles]] for details, but please still read this section.}}<br />
<br />
'''What is a keyfile?'''<br />
<br />
A keyfile is a file whose data is used as the passphrase to unlock an encrypted volume.<br />
That means if such a file is lost or changed, decrypting the volume may no longer be possible.<br />
<br />
{{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.}}<br />
<br />
'''Why use a keyfile?'''<br />
<br />
There are many kinds of keyfiles. Each type of keyfile used has benefits and disadvantages summarized below:<br />
<br />
=== Types of keyfiles ===<br />
==== passphrase ====<br />
<br />
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.<br />
<br />
Example: 1234<br />
<br />
==== randomtext ====<br />
<br />
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.<br />
<br />
Example: fjqweifj830149-57 819y4my1-38t1934yt8-91m 34co3;t8y;9p3y-<br />
<br />
==== binary ====<br />
<br />
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.<br />
<br />
Example: images, text, video, ...<br />
<br />
=== Creating a keyfile with random characters ===<br />
<br />
==== Storing the keyfile on a filesystem ====<br />
<br />
A keyfile can be of arbitrary content and size. <br />
<br />
Here {{ic|dd}} is used to generate a keyfile of 2048 random bytes, storing it in the file {{ic|/etc/mykeyfile}}:<br />
<br />
# dd bs=512 count=4 if=/dev/urandom of=/etc/mykeyfile<br />
<br />
If you are planning to store the keyfile on an external device, you can also simply change the outputfile to the corresponding directory:<br />
<br />
# dd bs=512 count=4 if=/dev/urandom of=/media/usbstick/mykeyfile<br />
<br />
===== Securely overwriting stored keyfiles =====<br />
<br />
If you stored your temporary keyfile on a physical storage device, and want to delete it, remember to not just remove the keyfile later on, but use something like<br />
<br />
# shred --remove --zero mykeyfile<br />
<br />
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.<br />
<br />
==== Storing the keyfile in tmpfs ====<br />
<br />
Alternatively, you can mount a tmpfs for storing the keyfile temporarily:<br />
<br />
# mkdir mytmpfs<br />
# mount tmpfs mytmpfs -t tmpfs -o size=32m<br />
# cd mytmpfs<br />
<br />
The advantage is that it resides in RAM and not on a physical disk, therefore it can not be recovered after unmounting the tmpfs. On the other hand this requires you to copy the keyfile to another filesystem you consider secure before unmounting.<br />
<br />
=== Configuring LUKS to make use of the keyfile ===<br />
<br />
Add a keyslot for the keyfile to the LUKS header:<br />
<br />
{{hc|# cryptsetup luksAddKey /dev/sda2 /etc/mykeyfile|<br />
Enter any LUKS passphrase:<br />
key slot 0 unlocked.<br />
Command successful.}}<br />
<br />
=== Unlocking a secondary partition at boot ===<br />
<br />
If the keyfile for a secondary file system is itself stored inside an encrypted root, it is safe while the system is powered off but can be sourced to automatically unlock the mount during with boot via [[Dm-crypt/System configuration#crypttab|crypttab]]. Following on from the first example above<br />
{{hc|/etc/crypttab|home /dev/sda2 /etc/mykeyfile}}<br />
is all needed for unlocking, and <br />
{{hc|/etc/fstab|/dev/mapper/home /home ext4 defaults 0 2}} for mounting the LUKS blockdevice with the generated keyfile.<br />
{{Tip|If you prefer to use a {{ic|--plain}} mode blockdevice, the encryption options necessary to unlock it are specified in {{ic|/etc/crypttab}}. Take care to apply the systemd workaround mentioned in [[Dm-crypt/System configuration#crypttab|crypttab]] in this case.}}<br />
<br />
=== Unlocking the root partition at boot ===<br />
<br />
This is simply a matter of configuring [[mkinitcpio]] to include the necessary modules or files and configuring the [[Dm-crypt/System_configuration#cryptkey|cryptkey]] [[Kernel_parameters|kernel parameter]] to know where to find the keyfile.<br />
<br />
Two cases will be covered:<br />
<br />
# Using a keyfile stored on an external media (here a USB stick)<br />
# Using a keyfile embedded in the initramfs <br />
<br />
==== With a keyfile stored on an external media ====<br />
<br />
===== Configuring mkinitcpio =====<br />
<br />
You have to add two extra modules in your {{ic|/etc/mkinitcpio.conf}}, one for the drive's file system ({{ic|vfat}} module in the example below) and one for the codepage ({{ic|nls_cp437}} module) :<br />
MODULES="nls_cp437 vfat"<br />
<br />
In this example it is assumed that you use a FAT formatted USB drive ({{ic|vfat}} module). Replace those module names if you use another file system on your USB stick (e.g. {{ic|ext2}}) or another codepage. Users running the stock Arch kernel should stick to the codepage mentioned here. If it complains of bad superblock and bad codepage at boot, then you need an extra codepage module to be loaded. For instance, you may need {{ic|nls_iso8859-1}} module for {{ic|iso8859-1}} codepage.<br />
<br />
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}}.<br />
<br />
Generate a new initramfs image:<br />
<br />
# mkinitcpio -p linux<br />
<br />
===== Configuring the kernel parameters =====<br />
<br />
Add the following options to the [[kernel parameters]] if using the {{ic|encrypt}} hook. If using {{ic|sd-encrypt}} see [[Dm-crypt/System configuration#cryptkey]].<br />
<br />
cryptdevice=/dev/''<partition1>'':root cryptkey=/dev/''<partition2>'':<fstype>:<path><br />
<br />
For example:<br />
<br />
cryptdevice=/dev/sda3:root cryptkey=/dev/sdb1:vfat:/keys/secretkey<br />
<br />
Choosing a plain filename for your key provides a bit of 'security through obscurity', but be aware the kernel command line is recorded in the kernel's log (''dmesg''). The keyfile can not be a hidden file, that means the filename must not start with a dot, or the {{ic|encrypt}} hook will fail to find the keyfile during the boot process. Alternatively, one could hide the keyfile between the partitions and use:<br />
<br />
cryptkey=/dev/sdb1:offset:size<br />
<br />
As an advantage, it is harder to accidentally delete the key.<br />
<br />
The naming of device nodes like {{ic|/dev/sdb1}} is not guaranteed to stay the same across reboots. It is more reliable to access the device with udev's [[persistent block device naming]] instead. To assure that the {{ic|encrypt}} hook finds your keyfile when reading it from an external storage device, persistent block device names must be used. See the article [[persistent block device naming]].<br />
<br />
==== With a keyfile embedded in the initramfs ====<br />
<br />
{{Warning|Use an embedded keyfile '''only''' if you have some form of authentication mechanism beforehand that protects the keyfile sufficiently. Otherwise auto-decryption will occur, defeating completely the purpose of block device encryption.}}<br />
<br />
This method allows to use a specially named keyfile that will be embedded in the [[initramfs]] and picked up by the {{ic|encrypt}} [[Mkinitcpio#HOOKS|hook]] to unlock the root filesystem ({{ic|cryptdevice}}) automatically. It may be useful to apply when using the [[GRUB#Boot partition|GRUB early cryptodisk]] feature, in order to avoid entering two passphrases during boot.<br />
<br />
The {{ic|encrypt}} hook lets the user specify a keyfile with the {{ic|cryptkey}} kernel parameter: in the case of initramfs, the syntax is {{ic|rootfs:''path''}}. See [[Dm-crypt/System configuration#cryptkey]]. Besides, this kernel parameter defaults to use {{ic|/crypto_keyfile.bin}}, and if the initramfs contains a valid key with this name, decryption will occur automatically without the need to configure the {{ic|cryptkey}} parameter.<br />
<br />
If using {{ic|sd-encrypt}} instead of {{ic|encrypt}}, specify the location of the keyfile with the {{ic|luks.cryptkey}} kernel parameter. See [[Dm-crypt/System configuration#luks.key]].<br />
<br />
[[#Creating_a_keyfile_with_random_characters|Generate the keyfile]], give it suitable permissions and [[#Adding_LUKS_keys|add it as a LUKS key]]:<br />
<br />
# dd bs=512 count=4 if=/dev/urandom of=/crypto_keyfile.bin<br />
# chmod 000 /crypto_keyfile.bin<br />
# chmod 600 /boot/initramfs-linux*<br />
# cryptsetup luksAddKey /dev/sdX# /crypto_keyfile.bin<br />
<br />
{{Warning|When initramfs' permissions are set to 644 (by default), then all users will be able to dump the keyfile. Make sure the permissions are still 600 if you install a new kernel.}}<br />
<br />
Include the key in [[Mkinitcpio#BINARIES_and_FILES|mkinitcpio FILES array]]:<br />
<br />
{{hc|/etc/mkinitcpio.conf|2=FILES="/crypto_keyfile.bin"}}<br />
<br />
Finally [[Mkinitcpio#Image_creation_and_activation|Regenerate your initramfs]].<br />
<br />
On the next reboot you should only have to enter your container decryption passphrase once.<br />
<br />
([http://www.pavelkogan.com/2014/05/23/luks-full-disk-encryption/#bonus-login-once source])</div>Zkosfonn