User:dimadenisjuk/Dm-crypt (Русский)/Device encryption (Русский)

From ArchWiki

Эта статья рассказывает, как использовать dm-crypt из командной строки для шифрования системы.

This article or section needs expansion.

Reason: Перевод неполный. Переведены только пункты 1, 2, частично 3, частично 5, частично 7. Остались пока нетронутыми 4, 6 (Discuss in User talk:Dimadenisjuk/Dm-crypt (Русский)/Device encryption (Русский))

Подготовка

Перед использованием cryptsetup, убедитесь, что загружен модуль ядра dm_crypt.

Использование cryptsetup

Cryptsetup — это инструмент для взаимодействия с dm-crypt, необходимый для создания, доступа и управления зашифрованными устройствами. Позже этот инструмент был расширен для поддержки различных типов шифрования, которые зависят от device-mapper и криптографических (cryptographic) модулей ядра Linux. Наиболее заметным расширением стало расширение Linux Unified Key Setup (LUKS), которое хранит всю необходимую информацию о настройке dm-crypt на самом диске, абстрагирует раздел и управление ключами для большего удобства в использовании. Устройства, доступ к которым осуществляется через device-mapper считаются блочными. Для получения дополнительной информации см. Data-at-rest encryption#Block device encryption.


Cryptsetup используется следующим образом:

# cryptsetup <OPTIONS> <action> <action-specific-options> <device> <dmname>

Предустановленные параметры используются, если другие не были указаны из командной строки. Изучите

$ cryptsetup --help 

что покажет опции, действия и параметры по умолчанию для различных режимов шифрования. Полный список опция перечислен в странице man. Поскольку различные параметры необходимы или необязательны в зависимости от действия и метода шифрования, в следующих разделах подробно расписаны различия. Шифрование блочных устройств недолгое, но его скорость имеет большое значение. После смены шифра важно заранее проверить производительность dm-crypt с вашими параметрами:

$ cryptsetup benchmark 

может дать рекомендации по выбору алгоритма и размера ключа до установки. Шифры AES, имеющие более высокую пропускную способность, вероятно, имеют аппаратную поддержку процессором.

Совет: Вы можете попрактиковаться в шифровании диска виртуальной машины для тренировки.

Пароли и ключи cryptsetup

Зашифрованное устройство защищено ключом. Ключ может быть:

Оба типа ключей имеют стандартный максимальный размер: максимальная длина пароля — 512 символов, файла — 8192kiB.

Важным отличием LUKS, которое стоит отметить, является то, что пользовательский ключ используется для разблокировки мастер-ключа от зашифрованного устройства и может быть сменён с root-доступом. Другие методы шифрования не поддерживают изменение ключа, поскольку не используют мастер-ключ для шифрования. См. Data-at-rest encryption#Block device encryption.

Опции шифрования dm-crypt

Cryptsetup поддерживает различные режимы шифрования для использования с dm-crypt:

  • --type luks для использования стандартной версии формата LUKS (LUKS1 для cryptsetup < 2.1.0, LUKS2 для cryptsetup ≥ 2.1.0),
  • --type luks1 для использования LUKS1, стандартной версии LUKS (полезно для загрузки шифрованного /boot из GRUB),
  • --type luks2 для использования LUKS2, последней доступной версии LUKS с дополнительными возможностями,
  • --type plain для использования простого (plain) режима dm-crypt,
  • --type loopaes для использования устаревшего (legacy) режима loopaes,
  • --type tcrypt для совместимости с TrueCrypt.

Базовые опции шифра и хешей доступны для использования во всех режимах и зависят от опций ядра. Все загруженные и доступные для использования опции можно посмотреть с помощью:

$ less /proc/crypto 
Совет: Если данный список слишком короткий, выполните $ cryptsetup benchmark, что вызовет загрузку доступных модулей ядра.

Ниже представлены опции шифрования для режимов luks, luks1, luks2 и plain. Учтите, что в таблицах перечислены не все доступные параметры, а только используемые в соответствующих примерах в этой статье.

Опции шифрования для режима LUKS

Команда cryptsetup luksFormat используется для создания нового устройства dm-crypt в режиме шифрования LUKS. Несмотря на название, она не форматирует раздел, а настраивает заголовок LUKS и шифрует мастер-ключ с указанными криптографическими параметрами.

Для создания нового контейнера LUKS с опциями по умолчанию, перечисленными в cryptsetup --help, просто выполните:

# cryptsetup luksFormat device

Для cryptsetup 2.3.4 эта команда эквивалентна:

# cryptsetup --type luks2 --cipher aes-xts-plain64 --hash sha256 --iter-time 2000 --key-size 256 --pbkdf argon2i --sector-size 512 --use-urandom --verify-passphrase luksFormat device

Сравнение стандартных опций с криптографически более высоким примером представлено в таблице ниже с сопровождающими комментариями:

Параметры Значения по умолчанию (cryptsetup 2.1.0) Значения, используемые в примерах Комментарий
--cipher

-c

aes-xts-plain64 aes-xts-plain64 Release 1.6.0 changed the defaults to an AES cipher in XTS mode (see item 5.16 of the FAQ). It is advised against using the previous default --cipher aes-cbc-essiv because of its known issues and practical attacks against them.
--key-size

-s

256 (512 for XTS) 512 By default a 512 bit key-size is used for XTS ciphers. Note however that XTS splits the supplied key in half, so this results in AES-256 being used.
--hash

-h

sha256 sha512 Hash algorithm used for key derivation. Release 1.7.0 changed defaults from sha1 to sha256 "not for security reasons [but] mainly to prevent compatibility problems on hardened systems where SHA1 is already [being] phased out"[1]. The former default of sha1 can still be used for compatibility with older versions of cryptsetup since it is considered secure (see item 5.20).
--iter-time

-i

2000 5000 Number of milliseconds to spend with PBKDF2 passphrase processing. Release 1.7.0 changed defaults from 1000 to 2000 to "try to keep PBKDF2 iteration count still high enough and also still acceptable for users."[2]. 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..
--use-urandom --use-urandom --use-random Выбирает, какой генератор случайных чисел использовать. Учтите, что пул блокировок /dev/random был удалён. Следовательно, флаг --use-random теперь эквивалентен --use-urandom.
--verify-passphrase

-y

Yes - Включён по умолчанию в Arch Linux для luksFormat и luksAddKey.

Свойства стандартных функций и опций LUKS подробно описаны в спецификациях LUKS1 (pdf) и LUKS2 (pdf).

Совет: В презентации разработчика проекта devconfcz2016 (pdf) излагается мотивация для крупного обновления спецификации LUKS2.

Выбор варианта argon2 для PBKDF

Хотя argon2id для большинства случаев является предпочтительным вариантом семейства Argon2, в цитируемом RFC сказано, что:

Argon2i использует независимый от данных (data-independent) доступ к памяти, который более предпочтителен для хеширования паролей и получения ключей.

Мы также можем видеть, как это отражается в ответе от Milan Broz, сопровождающего проект cryptsetup:

Однако вы можете использовать Argon2id (комбинация зависимого и независимого от данных доступа). Я для получения ключей предпочитаю Argon2i, но мнения могут расходиться.

Поэтому рекомендуется оставить значение по умолчанию, чтобы ненароком не снизить уровень безопасности.

Время итерации

From cryptsetup FAQ§2.1 and §3.4:

The unlock time for a key-slot [...] is calculated when setting a passphrase. By default it is 1 second (2 seconds for LUKS2). [...]
Passphrase iteration count is based on time and hence security level depends on CPU power of the system the LUKS container is created on. [...]
If you set a passphrase on a fast machine and then unlock it on a slow machine, the unlocking time can be much longer.

As such, it is better to always create a container on the machine where it will be most often accessed.

Read the rest of those sections for advice on how to correctly adjust the iteration count should the need arise.

Размер сектора

Важно: The filesystem to be used inside the LUKS container must also be formatted with the same sector size.

For drives with Advanced Format (also known as AF, 4K, 4096 byte sector drives) sectors it is recommended to use the appropriate physical sector size. In particular shingled magnetic recording (SMR) drives that are firmware-managed are negatively impacted if using a logical sector size of 512 bytes if their physical sector size is of 4096 bytes.

cryptsetup(8) § OPTIONS description for --sector-size indicates that: "Increasing sector size from 512 bytes to 4096 bytes can provide better performance on most of the modern storage devices and also with some hw encryption accelerators" (see the rest of the description for caveats to be aware of).

In a comment from 2019[3], the following reason is given for why the default was not switched over to 4K sector:

  1. Compatibility with old kernels and cryptsetup versions. The 4K encryption sector support is still fairly new, after all.
  2. It’s not guaranteed safe on disks with 512-byte sectors, as it can break atomicity guarantees that might be assumed by software. I don’t believe this is a problem on modern disks or flash storage, nor on ext4 or f2fs. But the cryptsetup default needs to be more conservative.

To create a LUKS2 container with a 4K sector size and otherwise default options:

# cryptsetup luksFormat --sector-size 4096 device

Выполнение данной команды прервётся с ошибкой, если запрошенный размер сектора не совпадает с размером сектора вашего устройства:

# cryptsetup luksFormat --sector-size 4096 device
(...)
Verify passphrase: 
Device size is not aligned to requested sector size.
Примечание: См. [4] информацию о том, почему команда может завершиться ошибкой, если базовый диск использует физические сектора по 4K.

Впоследствии отформатируйте размеченный контейнер, используя тот же размер сектора, например, для btrfs выполните:

# mkfs.btrfs -s 4096 /dev/mapper/mapped_device

Опции шифрования для простого (plain) режима

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.

Чтобы создать разметку простого (plain) режима со стандартными параметрами, выполните:

# cryptsetup <options> open --type plain <device> <dmname>

Будет запрошен пароль, который должен обладать очень высокой энтропией.

Ниже приведено сравнение стандартных параметров с примером из dm-crypt/Encrypting an entire system#Plain dm-crypt:

Параметры Значения по умолчанию (cryptsetup 2.1.0) Значения, используемые в примерах Комментарий
--hash

-h

ripemd160 - Хеш используется для генерации ключа из пароля; он не используется в случае файла-ключа.
--cipher

-c

aes-cbc-essiv:sha256 aes-xts-plain64 The cipher consists of three parts: cipher-chainmode-IV generator. Please see Data-at-rest encryption#Ciphers and modes of operation for an explanation of these settings, and the DMCrypt documentation for some of the options available.
--key-size

-s

256 512 Размер ключа (в битах). Размер будет зависеть от используемого шифра, а также от используемого режима (chainmode). Режим Xts требует вдвое большего размера ключа по сравнению с cbc.
--size

-b

действительный размер целевого диска 2048 (mapped device will be 512B×2048=1MiB) Ограничивает максимальный размер устройства (в секторах по 512 байт).
--offset

-o

0 0 Смещение (в секторах по 512 байт) от начала целевого диска, с которого начинается разметка.
--skip

-p

0 2048 (512B×2048=1MiB будет пропущен) Количество секторов по 512 байт, которые будут пропущены в начале.
--key-file

-d

по умолчанию используется пароль /dev/sdZ (или, например, /boot/keyfile.enc) Устройство или файл, используемый в качестве ключа. См. #Keyfiles для подробной информации.
--keyfile-offset 0 0 Смещение (в байтах) от начала файла до места, где начинается ключ. Опция поддерживается, начиная с cryptsetup 1.6.7.
--keyfile-size

-l

8192kB - (значение по умолчанию) Ограничивает число байт, читаемое из файла-ключа. Опция поддерживается, начиная с cryptsetup 1.6.7.

При использовании устройства /dev/sdX пример команды в соответствии с правой колонкой таблицы выглядит так:

# cryptsetup --cipher=aes-xts-plain64 --offset=0 --key-file=/dev/sdZ --key-size=512 open --type=plain /dev/sdX enc

В отличие от шифрования LUKS, команда выше должна выполняться со всеми аргументами всякий раз, когда необходимо получить доступ к контейнеру, поэтому важно помнить данную информацию о шифре, хеше и файле-ключе. Вы можете проверить, что разметка была создана:

# fdisk -l

Теперь должна существовать запись для /dev/mapper/enc.

Шифрование устройств при помощи cryptsetup

This section shows how to employ the options for creating new encrypted blockdevices and accessing them manually.

Важно: GRUB не поддерживает заголовки LUKS2; см. GRUB bug #55093. Поэтому, если вы планируете загружаться с зашифрованного раздела /boot из GRUB, укажите опцию --type luks1 для зашифрованного устройства, к которому нужен доступ из GRUB.

Encrypting devices with LUKS mode

Formatting LUKS partitions

In order to setup a partition as an encrypted LUKS partition execute:

# cryptsetup luksFormat device

You will then be prompted to enter a password and verify it.

See #Encryption options for LUKS mode for command line options.

You can check the results with:

# cryptsetup luksDump device

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 following example will create an encrypted root partition on /dev/sda1 using the default AES cipher in XTS mode with an effective 256-bit encryption

# cryptsetup -s 512 luksFormat /dev/sda1
Using LUKS to format partitions with a keyfile

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

# cryptsetup luksFormat device /path/to/mykeyfile

See #Keyfiles for instructions on how to generate and manage keyfiles.

Unlocking/Mapping LUKS partitions with the device mapper

Once the LUKS partitions have been created, they can then be unlocked.

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

In order to open an encrypted LUKS partition execute:

# cryptsetup open device dm_name

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 /dev/sda1 and maps it to device mapper named cryptroot:

# cryptsetup open /dev/sda1 cryptroot 

Once opened, the root partition device address would be /dev/mapper/cryptroot instead of the partition (e.g. /dev/sda1).

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

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 create a filesystem. For example:

# mkfs -t ext4 /dev/mapper/cryptroot

The device /dev/mapper/cryptroot can then be mounted like any other partition.

To close the LUKS container, unmount the partition and do:

# cryptsetup close cryptroot

Using a TPM to store keys

See Trusted Platform Module#Data-at-rest encryption with LUKS.

Encrypting devices with plain mode

The creation and subsequent access of a dm-crypt plain mode encryption both require not more than using the cryptsetup open action with correct 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.

A first mapper is created with cryptsetup's plain-mode defaults, as described in the table's left column above

# cryptsetup --type plain -v open /dev/sdaX plain1
Enter passphrase: 
Command successful.

Now we add the second blockdevice inside it, using different encryption parameters and with an (optional) offset, create a filesystem and mount it

# cryptsetup --type plain --cipher=serpent-xts-plain64 --hash=sha256 --key-size=256 --offset=10  open /dev/mapper/plain1 plain2
Enter passphrase:
# lsblk -p
 NAME                                                     
 /dev/sda                                     
 ├─/dev/sdaX          
 │ └─/dev/mapper/plain1     
 │   └─/dev/mapper/plain2              
 ...
# mkfs -t ext2 /dev/mapper/plain2
# mount -t ext2 /dev/mapper/plain2 /mnt
# echo "This is stacked. one passphrase per foot to shoot." > /mnt/stacked.txt

We close the stack to check access works

# cryptsetup close plain2
# cryptsetup close plain1

First, let us try to open the filesystem directly:

# cryptsetup --type plain --cipher=serpent-xts-plain64 --hash=sha256 --key-size=256 --offset=10 open /dev/sdaX plain2
# mount -t ext2 /dev/mapper/plain2 /mnt
mount: wrong fs type, bad option, bad superblock on /dev/mapper/plain2,
      missing codepage or helper program, or other error

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 open action will not error out itself.

Trying again in correct order:

# cryptsetup close plain2    # dysfunctional mapper from previous try
# cryptsetup --type plain open /dev/sdaX plain1
Enter passphrase:
# cryptsetup --type plain --cipher=serpent-xts-plain64 --hash=sha256 --key-size=256 --offset=10 open /dev/mapper/plain1 plain2
Enter passphrase:
# mount /dev/mapper/plain2 /mnt && cat /mnt/stacked.txt
This is stacked. one passphrase per foot to shoot.

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.

Available for plain mode only is the option --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:

# cryptsetup --type plain --offset 0 --size 1000 open /dev/sdaX plain1
Enter passphrase:
# cryptsetup --type plain --offset 1000 --size 1000 --shared --cipher=aes-cbc-lmk --hash=sha256 open /dev/sdaX plain2
Enter passphrase:
# lsblk -p
NAME                    
dev/sdaX                    
├─/dev/sdaX               
│ ├─/dev/mapper/plain1     
│ └─/dev/mapper/plain2     
...

As the devicetree shows both reside on the same level, i.e. are not stacked and "plain2" can be opened individually.

Действия cryptsetup, специфичные для LUKS

Управление ключами

It is possible to define addition keys for the LUKS partition. This enables the user to create access keys for safe backup storage In 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. A different key-slot could also be used to grant access to a partition to a user by issuing a second key and later revoking it again.

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

# cryptsetup luksDump /dev/<device>

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.

Добавление ключей LUKS

Добавление новых ключей производится с помощью cryptsetup командой luksAddKey. Для обеспечения безопасности оно всегда (даже в случае, если том уже расшифрован) запросит любой существующий ключ ("any passphrase") перед вводом нового:

# cryptsetup luksAddKey /dev/<device> (/path/to/<additionalkeyfile>)
Enter any passphrase:
Enter new passphrase for key slot:
Verify passphrase: 

If /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 --key-file or -d option followed by the "old" <keyfile> will try to unlock all available keyfile keyslots:

# cryptsetup luksAddKey /dev/<device> (/path/to/<additionalkeyfile>) -d /path/to/<keyfile>

If it is intended to use multiple keys and change or revoke them, the --key-slot or -S option may be used to specify the slot:

# cryptsetup luksAddKey /dev/<device> -S 6
Enter any passphrase: 
Enter new passphrase for key slot: 
Verify passphrase:
# cryptsetup luksDump /dev/sda8 | grep 'Slot 6'
Key Slot 6: ENABLED

To show an associated action in this example, we decide to change the key right away:

# cryptsetup luksChangeKey /dev/<device> -S 6
Enter LUKS passphrase to be changed: 
Enter new LUKS passphrase:

before continuing to remove it.

Removing LUKS keys

There are three different actions to remove keys from the header:

  • luksRemoveKey is used to remove a key by specifying its passphrase/key-file.
  • 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.
  • luksErase is used to quickly remove all active keys.
Важно:
  • All above actions can be used to irrevocably delete the last active key for an encrypted device!
  • The 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 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.

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 -v option, which will specify which slot it occupies:

# cryptsetup -v open /dev/<device> testcrypt
Enter passphrase for /dev/<device>: 
Key slot 1 unlocked.
Command successful.

Now we can remove the key added in the previous subsection using its passphrase:

# cryptsetup luksRemoveKey /dev/<device>
Enter LUKS passphrase to be deleted:

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.

Alternatively, we can specify the key slot:

# cryptsetup luksKillSlot /dev/<device> 6
Enter any remaining LUKS passphrase:

Note that in both cases, no confirmation was required.

# cryptsetup luksDump /dev/sda8 | grep 'Slot 6'
Key Slot 6: DISABLED

To re-iterate the warning above: If the same passphrase had been used for key slots 1 and 6, both would be gone now.

Резервное копирование и восстановление

Если заголовок зашифрованного раздела LUKS будет уничтожен, вы не сможете расшифровать ваши данные. Повреждение заголовка равносильно забыванию пароля или потере файла-ключа от зашифрованного контейнера. Такой урон может быть нанесён вашей ошибкой при последующей разметке диска или сторонними программами, неправильно интерпретирующими таблицу разделов. Поэтому бывает полезно хранить резервную копию заголовка LUKS на другом носителе.

Примечание: Если один из паролей был скомпрометирован, вам придётся отозвать его на каждой копии заголовка LUKS, сохранённой вами. Иначе резервная копия заголовка вкупе со скомпрометированным паролем может быть использована, чтобы узнать мастер-ключ, который, в свою очередь, может быть использован, чтобы расшифровать связанный с ним раздел (даже ваш настоящий раздел, а не только его резервную копию). С другой стороны, если был скомпрометирован мастер-ключ, вам придётся выполнять повторное шифрование всего раздела. См. LUKS FAQ для подробной информации.

Резервное копирование с помощью cryptsetup

Cryptsetup's 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.

You can also back up the plaintext header into ramfs and encrypt it with e.g. GPG before writing it to persistent storage:

# 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>
Важно: Tmpfs может записывать данные на жёсткий диск, если остаётся мало памяти, поэтому его использование не рекомендуется.

Восстановление с помощью cryptsetup

Важно: Восстановление неправильного заголовка LUKS или его восстановление на незашифрованный раздел приведёт к потере данных! Это действие не проверяет, действительно ли заголовок подходит к определённому устройству.

Для того, чтобы избежать восстановления неправильного заголовка, сначала убедитесь, что он работает, открыв контейнер внешним заголовком с опцией --header:

# cryptsetup -v --header /mnt/<backup>/<file>.img open /dev/<device> test
Key slot 0 unlocked.
Command successful.
# mount /dev/mapper/test /mnt/test && ls /mnt/test 
# umount /mnt/test 
# cryptsetup close test 

Теперь, после успешной проверки восстановление можно выполнить командой:

# cryptsetup luksHeaderRestore /dev/<device> --header-backup-file ./mnt/<backup>/<file>.img

Now that all the keyslot areas are overwritten; only active keyslots from the backup file are available after issuing the command.

Ручное резервное копирование и восстановление

Заголовок LUKS всегда находится в начале устройства, и его резервное копирование может быть произведено без использования cryptsetup. Во-первых, вы должны найти смещение заголовка (payload offset) зашифрованного раздела:

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

Во-вторых, необходимо знать размер сектора на диске:

# fdisk -l /dev/<device> | grep "Sector size"
Sector size (logical/physical): 512 bytes / 512 bytes

Теперь, зная эти значения, вы можете сохранить резервную копию заголовка с помощью простой команды dd:

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

и хранить его в надёжном месте.

Восстановление может быть выполнено с использованием тех же значений, что и резервное копирование:

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

Re-encrypting devices

This article or section needs expansion.

Reason: cryptsetup 2.2 using LUKS2 (with a 16 MiB header) supports online encryption/decryption/reencryption.[5] (Discuss in User talk:Dimadenisjuk/Dm-crypt (Русский)/Device encryption (Русский))

The cryptsetup package features two options for re-encryption.

cryptsetup reencrypt
Argument to cryptsetup itself: Preferred method. Currently LUKS2 devices only. Actions can be performed online. Supports multiple parallel re-encryption jobs. Resilient to system failures. See cryptsetup(8) for more information.
cryptsetup-reencrypt
Legacy tool, supports LUKS1 in addition to LUKS2. Actions can be performed on unmounted devices only. Single process at a time. Sensitive to system failures. See cryptsetup-reencrypt(8) for more information.

Both can be used to convert an existing unencrypted filesystem to a LUKS encrypted one or permanently remove LUKS encryption from a device (using --decrypt). 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.

One application of re-encryption may be to secure the data again after a passphrase or 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).

Важно: Always make sure a reliable backup is available and double-check options you specify before using the tool!

The following shows an example to encrypt an unencrypted filesystem partition and a re-encryption of an existing LUKS device.

Encrypt an existing unencrypted filesystem

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.

This article or section needs expansion.

Reason: cryptsetup man pages suggest using twice the LUKS2 header size. That implies 32MiB and using --reduce-device-size 32M (Discuss in User talk:Dimadenisjuk/Dm-crypt (Русский)/Device encryption (Русский))

The default LUKS2 header requires 16 MiB. If the current filesystem occupies all the available space, we will have to shrink it at least that much. To shrink an existing ext4 filesystem on /dev/sdaX to its current possible minimum:

# umount /mnt
# e2fsck -f /dev/sdaX
e2fsck 1.43-WIP (18-May-2015)
Pass 1: Checking inodes, blocks, and sizes
...
/dev/sda6: 12/166320 files (0.0% non-contiguous), 28783/665062 blocks
# resize2fs -p -M /dev/sdaX
resize2fs 1.43-WIP (18-May-2015)
Resizing the filesystem on /dev/sdaX to 26347 (4k) blocks.
The filesystem on /dev/sdaX is now 26347 (4k) blocks long.
Совет: Shrinking to the minimum size with -M might take very long. You might want to calculate a size just 32MiB smaller than the current size instead of using -M, or use a graphical tool like gparted.

Now we encrypt it, using the default cipher we do not have to specify it explicitly:

# cryptsetup reencrypt --encrypt --reduce-device-size 16M /dev/sdaX

WARNING!

========

This will overwrite data on LUKS2-temp-12345678-9012-3456-7890-123456789012.new irrevocably.

Are you sure? (Type 'yes' in capital letters): YES
Enter passphrase for LUKS2-temp-12345678-9012-3456-7890-123456789012.new: 
Verify passphrase: 

After it finished, the whole /dev/sdaX partition is encrypted, not only the space the filesystem was shrunk to. As a final step we extend the original ext4 filesystem to occupy all available space again, on the now encrypted partition:

# cryptsetup open /dev/sdaX recrypt
Enter passphrase for /dev/sdaX: 
...
# resize2fs /dev/mapper/recrypt
resize2fs 1.43-WIP (18-May-2015)
Resizing the filesystem on /dev/mapper/recrypt to 664807 (4k) blocks.
The filesystem on /dev/mapper/recrypt is now 664807 (4k) blocks long.
# mount /dev/mapper/recrypt /mnt

The filesystem is now ready to use. You may want to add it to your crypttab.

Повторное шифрование существующего раздела LUKS

В данном примере существующее устройство LUKS шифруется повторно.

Важно: Double-check you specify encryption options for correctly and never re-encrypt without a reliable backup!

Если устройство шифруется повторно с сохранением старых параметров шифрования, их можно не указывать:

# cryptsetup reencrypt /dev/sdaX
Примечание: Для LUKS1 необходимо использовать устаревший инструмент:
# cryptsetup-reencrypt /dev/sdaX

Existing keys are retained when re-encrypting a device with a different cipher and/or hash. Another use case 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 4096 sectors:

# cryptsetup luksDump /dev/sdaX |grep -e "mode" -e "Payload" -e "MK bits"
Cipher mode:   	cbc-essiv:sha256
Payload offset:	2048
MK bits:       	128

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

Преобразование из LUKS1 в LUKS2 и обратно

Пакет cryptsetup поддерживает опцию convert, необходимую для преобразования контейнера между форматами LUKS1 и LUKS2. Необходим аргумент --type.

Миграция из LUKS1 в LUKS2:

# cryptsetup convert --type luks2 /dev/sdaX

Откат к LUKS1 (например, для загрузки зашифрованного /boot из GRUB):

# cryptsetup convert --type luks1 /dev/sdaX
Примечание: Преобразование из LUKS2 в LUKS1 не всегда возможно.

Иногда вы можете получить следующую ошибку:

Cannot convert to LUKS1 format - keyslot 0 is not LUKS1 compatible.


Resizing encrypted devices

This article or section needs expansion.

Reason: This section should be rewritten to introduce resizing more generically. Perhaps work on it together with Resizing LVM-on-LUKS. (Discuss in User talk:Dimadenisjuk/Dm-crypt (Русский)/Device encryption (Русский))

If a storage device encrypted with dm-crypt is being cloned (with a tool like dd) to another larger device, the underlying dm-crypt device must be resized to use the whole space.

The destination device is /dev/sdX2 in this example, the whole available space adjacent to the partition will be used:

# cryptsetup luksOpen /dev/sdX2 sdX2
# cryptsetup resize sdX2

Then the underlying filesystem must be resized.

Loopback filesystem

Assume that an encrypted loopback filesystem is stored in a file /bigsecret, looped to /dev/loop0, mapped to secret and mounted on /mnt/secret, as in the example at dm-crypt/Encrypting a non-root file system#File container.

If the container file is currently mapped and/or mounted, unmount and/or close it:

# umount /mnt/secret
# cryptsetup close secret
# losetup -d /dev/loop0

Next, expand the container file with the size of the data you want to add. In this example, the file will be expanded with 1M * 1024, which is 1G.

Важно: Make absolutely sure to use two >, instead of just one, or else you will overwrite the file instead of appending to it. Making a backup before this step is strongly recommended.
# dd if=/dev/urandom bs=1M count=1024 | cat - >> /bigsecret

Now map the container to the loop device:

# losetup /dev/loop0 /bigsecret
# cryptsetup open /dev/loop0 secret

After this, resize the encrypted part of the container to the new maximum size of the container file:

# cryptsetup resize secret

Finally, perform a filesystem check and, if it is ok, resize it (example for ext2/3/4):

# e2fsck -f /dev/mapper/secret
# resize2fs /dev/mapper/secret

You can now mount the container again:

# mount /dev/mapper/secret /mnt/secret

Integrity protected device

If the device was formatted with integrity support (e.g., --integrity hmac-sha256) and the backing block device is shrinked, it cannot be opened with this error: device-mapper: reload ioctl on failed: Invalid argument.

To fix this issue without wiping the device again, it can be formatted with the previous master key (keeping the per-sector tags valid).

# cryptsetup luksDump /dev/sdX2 --dump-master-key --master-key-file=/tmp/masterkey-in-tmpfs.key
# cryptsetup luksFormat /dev/sdX2 --type luks2 --integrity hmac-sha256 --master-key-file=/tmp/masterkey-in-tmpfs.key --integrity-no-wipe
# rm /tmp/masterkey-in-tmpfs.key

Файлы-ключи (keyfiles)

Примечание: This section describes using a plaintext keyfile. If you want to encrypt your keyfile giving you two factor authentication see Using GPG or OpenSSL Encrypted Keyfiles for details, but please still read this section.

Что такое файл-ключ?

Файл-ключ — это файл, содержимое которого используется в качестве пароля для разблокировки зашифрованного раздела. Это значит, что, если такой файл был потерян или изменён, расшифровка раздела может стать невозможной.

Совет: Задайте пароль в добавление к файлу-ключу для расшифровки раздела на случай, если последний будет утерян или изменён.

Зачем использовать файл-ключ?

Существует множество типов ключей. Каждый из них имеет свои преимущества и недостатки, изложенные ниже:

Типы файлов-ключей

пароль

Файл-ключ может содержать простой пароль. Преимущества данного типа ключа в том, что, даже если файл был утерян, его содержимое известно и легко вспоминается владельцем зашифрованного тома. Тем не менее недостатком является то, что безопасность системы в данном случае будет не выше, чем при использовании обычного пароля.

Пример ключа: 1234

Примечание: В конце файла, содержащего пароль не должно быть символа новой строки. Такой файл можно создать командой
# echo -n 'ваш_пароль' > /path/to/<keyfile>
# chown root:root /path/to/<keyfile>; chmod 400 /path/to/<keyfile>

Если файл содержит специальные символы (например, обратный слеш), лучше вместо их экранирования просто редактировать файл-ключ напрямую, введя или вставив пароль, и затем удалить символ новой строки с помощью простой однострочной команды perl:

# perl -pi -e 'chomp if eof' /path/to/<keyfile>

случайный текст

Этот тип ключа-файла содержит последовательность случайных символов. Его основное преимущество заключается в том, что он гораздо более устойчив к атакам с использованием словарей, чем простой пароль. Дополнительная прочность такого ключа может быть достигнута за счет большей длины файла. Так как он не предназначен для запоминания человеком для ввода, обычно создаются файлы, которые содержат тысячи случайных символов в качестве ключа. Основной недостаток: если файл был утерян или изменён, то скорее всего не получится вернуть доступ к зашифрованным данным без запасного ключа.

Пример ключа: fjqweifj830149-57 819y4my1-38t1934yt8-91m 34co3;t8y;9p3y-

двоичный файл

Это бинарный файл, который был определён как ключ. При выборе файла для использования в качестве ключа желательно искать файлы, которые обычно остаются неизменными (фотографии, музыка, видеофайлы). Преимущество данных файлов в том, что они выполняют двойную функцию, что делает более сложной их идентификацию в качестве ключей. Вместо текстового файла с большим количеством символов для случайного наблюдателя ключ может выглядить как обычная картинка или аудиофайл. Недостаток данного типа ключа: если файл был утерян или изменён, то скорее всего не получится вернуть доступ к зашифрованным данным без запасного ключа. Кроме того, такой файл содержит меньше энтропии (случайности) по сравнению со специально сгенерированным текстовым файлом из случайных символов. Это происходит из-за наличия некоторой связи между соседними битами в изображениях, музыке и видеофайлах, хотя это спорно и никогда не использовалось публично.

Пример ключа: изображения, документы, видео, ...

Создание файла-ключа со случайными символами

Хранение файла-ключа в файловой системе

Ключ может быть произвольного содержания и размера.

Например, для генерации ключа из 2048 случайных байт может использоваться команда dd, сохраняющая ключ в /etc/mykeyfile:

# dd bs=512 count=4 if=/dev/random of=/etc/mykeyfile iflag=fullblock

Если вы собираетесь хранить ключ на внешнем устройстве, вы можете указать файл назначения в соответствующей директории:

# dd bs=512 count=4 if=/dev/random of=/media/usbstick/mykeyfile iflag=fullblock

Необходимо запретить доступ к файлу другим пользователям, кроме root:

# chmod 600 /etc/mykeyfile
Надёжная перезапись временного файла-ключа

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

# shred --remove --zero mykeyfile

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

Хранение файла-ключа в ramfs

В качестве альтернативы, вы можете смонтировать ramfs для временного хранения файла-ключа:

# mkdir /root/myramfs
# mount ramfs /root/myramfs/ -t ramfs
# cd /root/myramfs

Преимущество заключается в том, что он хранится в ОЗУ, а не на диске, поэтому он не может быть восстановлен после отключения ramfs. После копирования файла в другое надёжное постоянное хранилище можно отключить ramfs командой

# umount /root/myramfs

Настройка LUKS для использования файла-ключа

Добавление слота для файла-ключа в загововок LUKS:

# cryptsetup luksAddKey /dev/sda2 /etc/mykeyfile
Enter any LUKS passphrase:
key slot 0 unlocked.
Command successful.

Ручная разблокировка с использованием файла-ключа

Используйте опцию --key-file при открытии устройства LUKS:

# cryptsetup open /dev/sda2 dm_name --key-file /etc/mykeyfile

Расшифровка раздела root при загрузке

Для автоматического открытия зашифрованного контейнера при загрузке системы необходимо включить необходимые модули и файлы в mkinitcpio и настроить параметр ядра cryptkey, чтобы ядро знало, где искать файл-ключ.

Ниже рассматриваются два случая:

  1. С использованием файла-ключа на внешнем носителе (например, USB-флешке)
  2. С использованием ключа, встроенного в initramfs

С файлом-ключом на внешнем носителе

Настройка mkinitcpio

Вы должны добавить модуль файловой системы носителя с ключом в массив MODULES в /etc/mkinitcpio.conf. Например, модуль ext4, если используется файловая система Ext4 или vfat, если используется FAT:

MODULES=(vfat)

При появлении при загрузке сообщеня bad superblock либо bad codepage необходимо загрузить модуль ядра с дополнительной кодировкой. К примеру, вам может пригодиться модуль nls_iso8859-1 для кодировки iso8859-1.

Обновление initramfs.

Настройка параметров ядра

С файлом-ключом,зашитым в initramfs

This article or section needs expansion.

Важно: Use an embedded keyfile only if you protect the keyfile sufficiently by:
  • Using some form of authentication earlier in the boot process. Otherwise auto-decryption will occur, defeating completely the purpose of block device encryption.
  • /boot is encrypted. Otherwise root on a different installation (including the live environment) can extract your key from the initramfs, and unlock the device without any other authentication.

This method allows to use a specially named keyfile that will be embedded in the initramfs and picked up by the encrypt hook to unlock the root filesystem (cryptdevice) automatically. It may be useful to apply when using the GRUB early cryptodisk feature, in order to avoid entering two passphrases during boot.

The encrypt hook lets the user specify a keyfile with the cryptkey kernel parameter: in the case of initramfs, the syntax is rootfs:path. See dm-crypt/System configuration#cryptkey. Besides, this kernel parameter defaults to use /crypto_keyfile.bin, and if the initramfs contains a valid key with this name, decryption will occur automatically without the need to configure the cryptkey parameter.

При использовании sd-encrypt вместо encrypt, укажите местоположение файла-ключа в параметре ядра rd.luks.key. См. dm-crypt/System configuration#rd.luks.key.

Генерируя файл-ключ, присвойте ему подходящие права доступа и добавьте его в список ключей LUKS:

# dd bs=512 count=4 if=/dev/random of=/crypto_keyfile.bin iflag=fullblock
# chmod 600 /crypto_keyfile.bin
# chmod 600 /boot/initramfs-linux*
# cryptsetup luksAddKey /dev/sdX# /crypto_keyfile.bin
Важно: Когда права доступа initramfs установлены в 644 (по умолчанию), пользователи имеют доступ к дампу файла-ключа. Убедитесь, что права установлены в 600 перед добавлением нового ядра.

Включите ключ в массив FILES mkinitcpio:

/etc/mkinitcpio.conf
FILES=(/crypto_keyfile.bin)

Наконец, запустите генерацию initramfs:

# mkinitcpio -p linux

При последующей перезагрузке вам нужно будет ввести пароль контейнера один раз.

(source)