dm-crypt with LUKS (Italiano)

From ArchWiki
Revision as of 20:35, 22 September 2012 by Maveloth (Talk | contribs) (alligned)

Jump to: navigation, search

Template:Article summary start Template:Article summary text Template:Article summary heading Template:Article summary wiki Template:Article summary wiki Template:Article summary end

Tango-preferences-desktop-locale.pngThis article or section needs to be translated.Tango-preferences-desktop-locale.png

Notes: Questo articolo è in fase di traduzione. Seguite per ora le istruzioni della versione inglese. (Discuss in Talk:ArchWiki Translation Team (Italiano)#Pagine Marcate come "out of date" e "Traslateme")

Questo articolo si concentra su come configurare un sistema completamente crittografato su Arch Linux, usando dm-crypt con LUKS.

dm-crypt è il device-mapper standard per le funzionalità di crittografia fornito dal kernel Linux. Può essere utilizzato direttamente da chi desidera avere un completo controllo degli aspetti del partizionamento e della gestione delle chiavi.

LUKS è un comodo strato aggiuntivo il quale archivia tutte le informazioni necessarie alla configurazione di dm-crypt sul disco stesso e si occupa anche della gestione delle partizioni e delle chiavi nel tentativo di facilitarne l’uso.

Per maggiori dettagli sui paragoni tra dm-crypt+LUKS e gli altri metodi di crittografia, consultare Disk Encryption#Comparison table.

Contents

Avvertenze

Tango-view-refresh-red.pngThis article or section is out of date.Tango-view-refresh-red.png

Reason: As of the 2012.07.15 installation media release, AIF (the Arch Installation Framework) is no longer included but instead Arch Install Scripts are provided to aid in the installation process. A lot of content still has to get updated all over the page. Many external Links are so old they might confuse users not aware of all noticeable changes in Arch Linux configs. Just keep that in mind while reading. (Discuss in Talk:Dm-crypt with LUKS (Italiano)#)

Configurazione iniziale

Panoramica e preparazione

Il supporto di installazione di Arch comprende i tool necessari per la crittografia del sistema. L’installazione di un sistema crittografato è in gran parte simile ad una normale installazione, sarà quindi possibile seguire la Guida all’installazione di Arch Linux oppure la Beginners' Guide dopo aver configurato le partizioni crittografate. Sarà necessario sistemare la configurazione del sistema per si che possa avviarsi dai volumi Luks.

La routine di creazione di un sistema criptato segue questi passaggi generali:

  • Cancellazione sicura del/degli hard disk
  • Partizionamento e configurazione della crittografia (LVM è opzionale)
  • Selezione ed installazione dei pacchetti
  • Configurazione del sistema
Attenzione: Crittografare una partizione cancellerà tutto il suo contenuto. Si consiglia di effettuare i backup necessari prima di iniziare.

Cancellazione sicura del/degli hard disk

Si consiglia di cancellare in modo sicuro i dati accessibili nelle partizioni o dischi utilizzando dati casuali. I dati casuali saranno scritti per motivi di sicurezza perché sono indistinguibili dai dati successivamente da dm-crypt. La cancellazione sicura dei dischi implica la sovrascrittura dell’intero disco con dati casuali.

Entrambi i dischi sia nuovi che usati dovrebbero essere sovrascritti in maniera sicura. Questo aiuta ad assicurare la privacy dei dati che si trovano sulle partizioni criptate. Il contenuto dei dischi comprati dal produttore non è assicurato. Se il disco è stato riempito con bit di valore zero e successivamente usato per dati criptati, allora sarà relativamente semplice identificare dove finiscono i dati criptati e dove iniziano gli zeri. Dato che una partizione criptata si suppone essere indistinguibile da dati casuali, la mancanza di dati casuali su di un disco sovrascritto con degli zeri rende il disco criptato un facile bersaglio per la cripto analisi.

Ripartizionare o riformattare un disco usato rimuove la struttura del file system che serve per sapere dove sono collocati i dati, ma lascia i dati intatti sul disco. Sarà relativamente semplice utilizzando strumenti come Foremost accedere ai dati rimasti. Quindi i dischi dovrebbero essere sovrascritti in modo sicuro con dati casuali prima di effettuare la cifratura per evitare il recupero di dati non intenzionale.

Nel decidere quale metodo utilizzare per la cancellazione sicura del disco, notare che non sarà necessario eseguirlo più di una volta fintanto che il disco viene utilizzato come disco criptato. Per maggiori informazioni consultare: Securely wipe disk

Cancellare il disco con un file criptato(alternativo)

In alternativa, il solito effetto può essere ottenuto se viene creato su tutte le partizioni un file che le riempia completamente dopo che il sistema è stato installato ed avviato con le partizioni criptate montate. Questo perché i dati criptati sono indistinguibili dai dati casuali.

#dd if=/dev/zero of=/path/to/the/output/file
#rm /path/to/the/input/file

Ripetere il processo precedente per ogni partizione sul filesystem.

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; if TRIM support were enabled, an attacker may be able to tell which blocks have been used, how many blocks have been used, and other information that is exposed directly to the device when a TRIM is issued.

It may be possible to determine the filesystem utilized by your encrypted device through the data that is leaked by TRIM. Furthermore, any information that may be derived by a profile of block usage may be exposed by enabling TRIM support on an encrypted device.

As of linux version 3.1, support for dm-crypt TRIM pass-through can be toggled upon device creation or mount with dmsetup. Support for this option also exists in cryptsetup version 1.4.0 and up. To add support during boot, you will need to add :allow-discards to the cryptdevice option. The TRIM option may look like this:

cryptdevice=/dev/mapper/root:root:allow-discards

For the main cryptdevice configuration options before the :allow-discards please refer to the sections following.

For more information, including specific commands and details on dm-crypt TRIM pass-through, see these mailing list threads:

* http://article.gmane.org/gmane.linux.kernel.device-mapper.devel/14134
* http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/5166

Partizionamento

Dopo che il disco è stato sovrascritto in modo sicuro, è il momento di creare le partizioni e iniziare la configurazione del sistema criptato.

Ci sono diversi modi di creare partizioni sul disco:

LUKS è compatibile con sistemi che necessitano di LVM e/o RAID come con le partizioni standard che siano primarie, estese, e logiche.

Partizioni standard

Queste sono le partizioni con cui la maggior parte degli utenti avrà maggiore familiarità. Esse possono essere di tre tipi: partizioni primarie, partizioni estese e partizioni logiche.

Partizioni primarie
Sono le normali partizioni riconosciute dal BIOS. Possono esserne presenti fino a quattro in un partizionamento MBR.
Partizioni estese
Sono partizioni primarie che definiscono al loro interno altre partizioni. Le partizioni estese sono state create per ovviare il limite delle quattro partizioni primarie.
Partizioni logiche
Sono le partizioni definite nelle partizioni estese.

LVM: Logical Volume Manager

The LVM allows for creation of volume groups for systems that require complex combinations of multiple hard disk drives and partitions that are not possible with standard partitions. LVM is covered in detail in the Arch Linux LVM Wiki Article which is recommended reading prior to continuing with the instructions on setting up LUKS with LVM located below.

How does LVM fit into the overall system?

There is a growing preference towards logical volume management of LUKS encrypted physical media (LVM on LUKS). It is possible there may exist usage scenarios where encrypting logical volumes rather than physical disks is required (LUKS on LVM). However, the deployment of LVM on LUKS is considered much more generalizable. One reason for this is that using LUKS as the lowest level of infrastructure most closely approximates the deployment of physical disks with built-in hardware encryption. In this case, logical volume management would be layered on top of the hardware encryption – usage of LUKS would be superfluous.

Creating Disk Partitions

Disk partitions are created using:

# cfdisk

This will display a graphical interface for creating disk partitions.

There are two required partitions for any encrypted system:

A root file system
  • /
  • Will be encrypted and store all system and user files (/usr, /bin, /var, /home, etc.)
An initial boot partition
  • /boot
  • Will not be encrypted; the bootloader needs to access the /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, /boot needs to reside on its own, unencrypted partition.
Note: A swap partition is optional; it can be encrypted with dm-crypt/LUKS. See Encrypting the Swap Partition for details.
Single Disk Systems

Depending on the system demands, there may be additional partitions desired. These partitions can be individually created at this level by defining separate primary or extended/logical partitions. However, if LVM is to be used, the space unoccupied by /boot and swap should be defined as single large partition which will be divided up later at the LVM level.

Multiple Disk Systems

In systems that will have multiple hard disk drives, the same options exist as a single disk system. After the creation of the /boot and swap partitions, the remaining free space on physical disks can divided up into their respective partitions at this level, or large partitions can define all free space per physical disk with intent to partition them within the LVM.

Configuring LUKS

Creating LUKS partitions with a passphrase is supported by the /arch/setup program.

This section of the Wiki will cover how to manually utilize LUKS from the command line to encrypt a system.

The steps for accomplishing this through the graphical installer are very similar and can be located in the dialogue for manual configuration of the hard drive.

Mapping Physical Partitions to LUKS

Once the desired partitions are created it is time to format them as LUKS partitions and then mount them through the device mapper.

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.

Using LUKS to Format Partitions with a Passphrase

Note: Using a passphrase to decrypt LUKS partitions automatically from /etc/crypttab is deprecated: see http://www.mail-archive.com/arch-projects@archlinux.org/msg02115.html

Cryptsetup is used to interface with LUKS for formatting, mounting and unmounting encrypted partitions.

A full list of options cryptsetup accepts can be found in the [Cryptsetup Manpage]

The options used here are:

  • -c defines the cipher type
  • -y prompts for password confirmation on password creation
  • -s defines the key size
luksFormat addresses the LUKS extensions built into cryptsetup.

In the following examples for creating LUKS partitions, we will use the AES cipher in XTS mode; at present this is most generally used preferred cipher. Other ciphers can be used with cryptsetup, and details about them 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: # modprobe dm_mod

In order to format a desired partition as an encrypted LUKS partition execute:

# cryptsetup -c <cipher> -y -s <key size> luksFormat /dev/<partition name>
Enter passphrase: <password>
Verify passphrase: <password>

This should be repeated for all partitions except for /boot and possibly swap.

The example below will create an encrypted root partition using the AES cipher in XTS mode (generally referred to as XTS-AES).

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 /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 /dev/<partition name> is actually an encrypted device and should be addressed through LUKS using the /dev/mapper/<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 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 /dev/mapper/swap instead of /dev/sda2.
  • cryptsetup luksOpen /dev/sda3 root
Once opened, the root partition device address would be /dev/mapper/root instead of /dev/sda3.
Note: Since /boot is not encrypted, it does not need a device mapped name and will be addressed as /dev/sda1.
Warning: In order to write encrypted data into the partition it must be accessed through the device mapped name.

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 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 dd is used to generate a keyfile of 2048 bits of random characters.

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

The usage of 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 keys with any single encrypted volume. Keys can be either keyfiles or passphrases.

Once an encrytped partition has been created, the initial key is associated at slot 0. Additional keys will occupy slots 1–7.

The addition of new keys to an encrypted partition is accomplished using cryptsetup with the luksAddKey extension.

# cryptsetup luksAddKey /dev/<encrypted volume> /path/to/mykeyfile

Where /dev/<encrypted volume> is the volume that is to have the new key associated with it.

If the bolded area is present, cryptsetup will look for the keyfile defined at that location to associate with the encrypted volume specified.

Storing the Key File

External Storage on a USB Drive

Preparation for permanent device names

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

Quick method

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

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

or

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

In this case, I labeled the vfat partition on my USB drive as "Keys" so my device is always symlinked in /dev/disk/by-label/Keys, or if I had wanted to use the UUID I would find /dev/disk/by-uuid/4803-8A7B. This allows me to have a consistent naming of my USB devices regardless of the order they are plugged into the system. These device names can be used in the "cryptkey" kernel option or any where else. Filesystem UUIDs are stored in the filesystem itself, meaning that the UUID will be the same if you plug it into any other computer, and that a dd backup of it will always have the same UUID since dd does a bitwise copy.

Note: If you plan to store the keyfile between MBR and the 1st partition you cannot use this method, since it only allows access to the partitions (sdb1, sdb2, ...) but not to the USB device (sdb) itself. Create a udev rule instead as described in the following section.

Using udev

Optionally you may choose to set up your 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 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 /etc/udev/rules.d/, such as 8-usbstick.rules:

KERNEL=="sd*", ATTRS{serial}=="$SERIAL", SYMLINK+="$SYMLINK%n"

Replace $SYMLINK and $SERIAL with their respective values. %n will expand to the partition (just like sda is subdivided into sda1, sda2, ...). You do not need to go with the 'serial' attribute. If you have a custom rule of your own, you can put it in as well (e.g. using the vendor name).

Rescan your sysfs:

udevadm trigger

Now check the contents of /dev:

ls /dev

It should show your device with your desired name.

Generating the keyfile

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

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

The advantage is that it resides in RAM and not on a physical disk, so after unmounting your keyfile is securly gone. So copy your keyfile to some place you consider as secure before unmounting. If you are planning to store the keyfile as a plain file on your USB device, you can also simply execute the following command in the corresponding directory, e.g. /media/sdb1

The keyfile can be of arbitrary content and size. We 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. (However due to journaling filesystems this is also not 100% secure.)

Add the temporary keyfile with cryptsetup:

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

Storing the keyfile

To store the key file, you have two options. The first is less risky than the other, but perhaps a bit more secure (if you consider security by obscurity as more secure). In any case you have to do some further configuration, if not already done above.

Configuration of initcpio

You have to add two extra modules in your /etc/mkinitcpio.conf, one for the drive's file system and one for the codepage. Further if you created a udev rule, you should tell mkinitcpio about it:

MODULES="ata_generic ata_piix nls_cp437 vfat"
FILES="/etc/udev/rules.d/8-usbstick.rules"

In this example it 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.

Additionally, insert the usb hook somewhere before the encrypt hook.

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

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 keymap hook before encrypt.

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

mkinitcpio -g /boot/initramfs-linux.img

Storing the key as a plain (visible) file

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

You have to add a kernel parameter in your /boot/grub/menu.lst (GRUB). It should look something like this:

kernel /vmlinuz-linux cryptdevice=/dev/sda3:root root=/dev/mapper/root ro cryptkey=/dev/usbstick:vfat:/secretkey

This assumes /dev/usbstick is the FAT partition of your choice. Replace it with /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!

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 seek=4 with seek=16; otherwise you would overwrite parts of your GRUB installation. When in doubt, take a look at the first 64 sectors of your drive and decide on your own where to place your key.

Optional If you 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 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 /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 cryptkey option:

cryptkey=BLOCKDEVICE:OFFSET:SIZE

OFFSET and 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

Without suspend-to-disk support

Note: The /etc/crypttab is now well commented and you can basically just uncomment the swap line and change the drive number.


In systems where suspend to disk is not a desired feature, it is possible to create a swap file that will have a random passphrase with each boot.

This is accomplished by using dm-crypt directly without LUKS extensions.

Append a similar line to /etc/crypttab to set up a randomly encrypted swap partition:

<device-mapper name> <swap physical partition> /dev/urandom swap

Where:

  • <device-mapper name> represents the name you want to use as label in /etc/fstab
  • <swap physical partition> should be the ID of the actual partition.
    Warning: You should use IDs here 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. ls -l /dev/disk/*/* | grep sdl7 should help you to find the desired partition.
  • /dev/urandom set the partition's password
  • swap identifies the partition as a swap partition

Example line (where /dev/sdl7 is the physical partition and LABEL=swap the desired label):

swap /dev/disk/by-id/scsi-SATA_Hitachi_HDS7220_JK1130YAGX0R1T-part7 /dev/urandom swap
Maps /dev/sdl7 to /dev/mapper/swap as a swap partition which we can now add in /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 LUKS header must be removed. This can be accomplished with:

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

With suspend-to-disk support

Warning: Do not use this setup with a key file. Please read about the issue reported here

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 /etc/crypttab can be used, it is required to create a hook in /etc/mkinitcpio.conf to open the swap LUKS device before resuming. The following setup has the disadvantage of having to insert a key manually for the swap partition.

If you want to use a partition which is currently used by the system, you have to disable it first:

# swapoff /dev/<device>

To create the swap partition, follow steps similar to those described in mapping partitions above.

  • Format the partition you want to use as swap with the cryptsetup command. For performance reasons, you might want to use different ciphers with different key sizes.
# cryptsetup -c aes-xts-plain -s 512 -h sha512 -v luksFormat /dev/<device>

Check the result with:

# cryptsetup luksDump /dev/<device>
  • Open the partition in /dev/mapper:
# cryptsetup luksOpen /dev/<device> swapDevice
  • Create a swap filesystem inside the mapped partition:
# mkswap /dev/mapper/swapDevice

Now you should have a LUKS swap partition which asks for the passphrase before mounting. Make sure you remove any line in /etc/crypttab which uses this device. Now you have to create a hook to open the swap at boot time.

  • Create a hook file containing the open command:
/lib/initcpio/hooks/openswap
 # vim: set ft=sh:
 run_hook ()
 {
     cryptsetup luksOpen /dev/<device> swapDevice
 }
Note: If you use a Solid State Disk (SSD) for your swap and you consider using discard also on swap you have to add the option '--allow-discards' to the cryptsetup line above. See 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:
/lib/initcpio/install/openswap
 # vim: set ft=sh:
 build ()
 {
     MODULES=""
     BINARIES=""
     FILES=""
     SCRIPT="openswap"
 }
 help ()
 {
 cat<<HELPEOF
   This opens the swap encrypted partition /dev/<device> in /dev/mapper/swapDevice
 HELPEOF
 }
  • Add the hook openswap in the HOOKS array in /etc/mkinitcpio.conf, before filesystem but after encrypt. Do not forget to add the resume hook after openswap.
HOOKS="... encrypt openswap resume filesystems ..."
  • Regenerate the boot image:
# mkinitcpio -p linux
  • Add the mapped partition to /etc/fstab by adding the following line:
/dev/mapper/swapDevice swap swap defaults 0 0
  • Set up your system to resume from /dev/mapper/swapDevice. For example, if you use GRUB with kernel hibernation support, add resume=/dev/mapper/swapDevice to the kernel line in /boot/grub/menu.lst. A line with encrypted root and swap partitions can look like this:
kernel /vmlinuz-linux cryptdevice=/dev/sda2:rootDevice root=/dev/mapper/rootDevice resume=/dev/mapper/swapDevice ro

At boot time, the openswap hook will open the swap partition so the kernel resume may use it. If you use special hooks for resuming from hibernation, make sure they are placed after openswap in the HOOKS array. Please note that because of initrd opening swap, there is no entry for swapDevice in /etc/crypttab needed in this case.

Using a swap file for suspend-to-disk support

  • Choose a mapped partition (e.g. /dev/mapper/rootDevice) whose mounted filesystem (e.g. /) contains enough free space to hold the entire contents of your system's RAM. For example, if your system has 4 GiB RAM, then you need at least that much free space on the mounted filesystem of your chosen mapped partition for the swap file.
  • Create the swap file (e.g. /swapfile) inside the mounted filesystem of your chosen mapped partition. Be sure to activate it with swapon and also add it to your /etc/fstab file afterward.
  • Set up your system to resume from your chosen mapped partition. For example, if you use GRUB with kernel hibernation support, add resume=your chosen mapped partition and resume_offset=see calculation command below to the kernel line in /boot/grub/menu.lst. 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

You can calculate the resume_offset of your swap file like this:

# filefrag -v /swapfile | awk '{if($1==0){print $3}}'
  • Add the resume hook to your etc/mkinitcpio.conf file and rebuild the image afterward:
HOOKS="... encrypt resume ... filesystems ..."
  • If you use a USB keyboard to enter your decryption password, then the usbinput module must appear in front of the 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!
HOOKS="... usbinput encrypt ..."

Installing the system

Tango-view-refresh-red.pngThis article or section is out of date.Tango-view-refresh-red.png

Reason: AIF does not exist anymore, GRUB Legacy is not available anymore (Discuss in Talk:Dm-crypt with LUKS (Italiano)#)

Now that /dev/mapper/root and /dev/mapper/home are in place, we can enter the regular Arch setup script to install the system into the encrypted volumes.

# /arch/setup
Note: Most of the installation can be carried out normally. However, there are a few areas where it is important to make certain selections. These are marked below.

Prepare hard drive

Skip the Partitioning and Auto-Prepare steps and go straight to manual configuration. Instead of choosing the hardware devices (/dev/sdaX) directly, you have to select the mapper devices created above. Choose /dev/mapper/root for your root and /dev/mapper/home as /home partition respectively and format them with any filesystem you like. The same is valid for a swap partition which is set up like the /home partition. Make sure you mount /dev/sda1 as the /boot partition, or else the installer will not properly set up the bootloader.

Select and Install packages

Select and install the packages as usual: the base package contains all required programs.

Configure System

Note: The 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 encrypt hook is not needed if any other partition (swap, for example) is encrypted. System initialization scripts (/etc/rc.sysinit and /etc/crypttab among others) take care of those.

Afterwards you can check the files presented to you by the installer, the most important one being /etc/mkinitcpio.conf. For detailed information about mkinitcpio and its configuration refer to Mkinitcpio. You have to make sure that your HOOKS array in /etc/mkinitcpio.conf looks something like this:

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

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

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

For safety, add usb before encrypt because the hooks are run in the order they appear. If you need support for foreign keymaps for your encryption password, you have to specify the hook keymap as well. I suggest putting this in /etc/mkinitcpio.conf immediately before encrypt.

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

If your root partition is a LUKS partition, add the used filesystem to the MODULES section.

MODULES="... ext3 ext4 xfs ..."

Install Bootloader

GRUB2: As with GRUB Legacy you have to specify your cryptdevice with the same name to map it to as your bootloader expects it. The default boot menu can receive its kernel command line from editing /etc/default/grub. Extend GRUB_CMDLINE_LINUX="" by the following parameter (assume your root device lies within /dev/sda3 and it should be mapped to cryptroot:

GRUB_CMDLINE_LINUX="cryptdevice=/dev/sda3:cryptroot"
Note: The device name your harddrive should be mapped to depends on your setup and configuration. If you are directly decrypting your root partition, the parameter root=/dev/mapper/cryptroot will indicate the expected name. In case of LVM this name can be any arbitrary name, as LVM will parse all available devices if specified as the next hook.


GRUB Legacy: You have to make some small changes to the entries generated by the installer by replacing /dev/mapper/root with /dev/sda3. The important point to remember here is to use the same cryptdevice name you assigned when you initially unlocked your device. In this example, the device name is cryptroot; customize yours accordingly:

# (0) Arch Linux
title Arch Linux
root (hd0,0)
kernel /vmlinuz-linux cryptdevice=/dev/sda3:cryptroot root=/dev/mapper/cryptroot ro
initrd /initramfs-linux.img

For kernels older than 2.6.37, the syntax is:

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

LILO: Edit the Arch Linux section in /etc/lilo.conf and include a line for the append option, over the initrd, with the root=/dev/sda3 parameter. The append section makes the same kernel line as in GRUB. Also, you can omit the root option above the image option. The section looks like this:

# Arch Linux lilo section
image = /vmlinuz-linux
# root = /dev/sda3
 label = Arch
 initrd = /initramfs-linux.img
 append = "root=/dev/sda3"
 read-only
Note: If you want to use a USB flash drive with a keyfile, you have to append the cryptkey option. See the corresponding section below.

Exit Install

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

# vi /mnt/etc/crypttab

Add the following line for the /home partition

Note: Using a passphrase to decrypt LUKS partitions automatically from /etc/crypttab is deprecated: see http://www.mail-archive.com/arch-projects@archlinux.org/msg02115.html
home    /dev/sda5    "myotherpassword"

You can also use a keyfile instead of a passphrase. If not already done, create a keyfile and add the key to the corresponding LUKS partition as described above. Then add the following information to the /etc/crypttab file for automounting:

home    /dev/sda5    /path/of/your/keyfile

If you used a USB device to store your keyfile, you should have something like this:

home    /dev/sda5    /dev/sd*1/keyfile

Or if the keyfile was stored in the MBR, it should be like this:

home    /dev/sda5    /dev/sd*:2048:2048
Note: When reading the keyfile from the MBR it should be /dev/sdb not /dev/sdb1 but if the key is in the filesystem it should still be /dev/sdb1.

After rebooting you should now be presented with the text

A password is required to access the root filesystem:

followed by a prompt for a LUKS password. Type it in and everything should boot. Once you have logged in, have a look at your mounted partitions by typing mount. You should have /dev/mapper/root mounted at / and, if you set up a separate encrypted home partition, /dev/mapper/home mounted at /home. If you set up encrypted swap, swapon -s should have /dev/mapper/swap listed as your swap partition.

Note: Eventually the text prompting for the password is mixed up with other boot messages. So the boot process may seem frozen at first glance, but it is not, simply enter your password and press Template:Keypress.

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 net hook along with an SSH server in initrd. Install the dropbear_initrd_encryptAUR package from the AUR and follow the post-installation instructions. Replace the encrypt hook with dropbear encryptssh in /etc/mkinitcpio.conf. Put the 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 /home)remotely, you may want to look at this forum thread.

Note: Acutally trim will not work with this script because it is not yet updated to the latest encrypt hook, so it is not able to parse -–allow-discards from /boot/grub/menu.lst. (Version: dropbear_initrd_encrypt 0.8-16). You won't notice any error when using online discard, but you see an error when you try to use fstrim.For a temporary solution just add -–allow-discards to every cryptsetup line of /lib/initcpio/install/dropbear(1 line) and /lib/initcpio/hooks/encryptssh(3 lines)

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 LUKS FAQ for further details on this.

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

Backup

Manually

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

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

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

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

Using cryptsetup

You can also use the luksHeaderBackup command instead:

cryptsetup luksHeaderBackup /dev/sdaX --header-backup-file ./backup.img

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.

Manually

Again, you will need to the same values as when backing up:

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

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.

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 bigsecret with a size of 10 megabytes.

losetup /dev/loop0 /bigsecret

This will create the device node /dev/loop0, so that we can mount/use our container.

Note: If it gives you the error /dev/loop0: No such file or directory, you need to first load the kernel module with modprobe loop. These days (Kernel 3.2) loop devices are created on demand. Ask for a new loop device with 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 Command failed: Failed to setup dm-crypt key mapping. Check kernel for support for the aes-cbc-essiv:sha256 cipher spec and verify that /dev/loop0 contains at least 133 sectors, then run modprobe dm-mod.
cryptsetup luksOpen /dev/loop0 secret

The encrypted container is now available through the device file /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 /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 >, or you will override your current container!

You could use /dev/zero instead of /dev/urandom to significantly speed up the process, but with /dev/zero your encrypted filesystems will not be as secure. (A better option to create random data quicker than /dev/urandom is frandom [1], available from the AUR).

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's really easy to use encryption with LVM. If you do not know how to set up LVM, then read Installing_with_Software_RAID_or_LVM.

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

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

To use encryption on top of LVM, you have to first set up your LVM volumes and then use them as the base for the encrypted partitions. That means, in short, that you have to set up LVM first. Then follow this guide, but replace all occurrences of /dev/sdXy in the guide with its LVM counterpart. (E.g.: /dev/sda5 -> /dev/<volume group name>/home). This is used to setup partitions (inside the LVM) which can be unlocked separately or a mixture of encrypted and non-encrypted partitions.

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 encrypt hook in /etc/mkinitcpio.conf after the lvm2 hook, if you chose to set up encrypted partitions on top of LVM. Also remember to change USELVM in /etc/rc.conf to "yes".

LVM with Arch Linux Installer (>2009.08 <2012.07.15)

Note: As on 2012.07.15, the AIF was removed so these steps are now obsolote. They still give the backbones to understanding what to do however with btrfs avaliable; It'll be easier to use btrfs instead of lvm with several ext partitions.

Since Arch Linux images 2009.08, LVM and dm_crypt is supported by the installer out of the box. This makes it very easy to configure your system for LVM on dm-crypt or vice versa. Actually the configuration is done exactly as without LVM: see the corresponding section above. It differs only in two aspects.

The partition and filesystem choice

Create a small, unencrypted boot partition and use the remaining space for a single partition which can later be split up into multiple logic volumes by LVM.

For a LVM-on-dm-crypt system set up the filesystems and mounting points for example like this:

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

The configuration stage

  • In /etc/rc.conf set USELVM to "yes"
  • In /etc/mkinitcpio.conf add the encrypt hook before the lvm2 hook in the HOOKS array, if you set up LVM on top of the encrypted partition.

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

Applying this to a non-root partition

You might get tempted to apply all this fancy stuff to a non-root partition. Arch does not support this out of the box, however, you can easily change the cryptdev and cryptname values in /lib/initcpio/hooks/encrypt (the first one to your /dev/sd* partition, the second to the name you want to attribute). That should be enough.

The big advantage is you can have everything automated, while setting up /etc/crypttab with an external key file (i.e. 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 /etc/fstab (at least).

Of course, if the cryptsetup package gets upgraded, you will have to change this script again. However, this solution is to be preferred over hacking /etc/rc.sysinit or similar files. Unlike /etc/crypttab, only one partition is supported, but with some further hacking one should be able to have multiple partitions unlocked.

If you want to do this on a software RAID partition, there is one more thing you need to do. Just setting the /dev/mdX device in /lib/initcpio/hooks/encrypt is not enough; the encrypt hook will fail to find the key for some reason, and not prompt for a passphrase either. It looks like the RAID devices are not brought up until after the encrypt hook is run. You can solve this by putting the RAID array in /boot/grub/menu.lst, like

kernel /boot/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

LVM and dm-crypt manually (short version)

Notes

If you are smart enough for this, you will be smart enough to ignore/replace LVM-specific things if you do not want to use LVM.

Note: This brief uses reiserfs for some of the partitions, so change this accordingly if you want to use a more "normal" file system, like ext4.

Partitioning scheme

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

The commands

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

Install Arch Linux

Run /arch/setup

Configuration

/etc/rc.conf

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

/etc/mkinitcpio.conf

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

if you want install the system on a usb stick, you need to put usb just after udev.

/boot/grub/menu.lst

Change root=/dev/hda3 to root=/dev/lvm/root.

For kernel >= 2.6.30, you should change root=/dev/hda3 to the following:

cryptdevice=/dev/lvm/root:root root=/dev/mapper/root

if you want install the system on a usb stick, you need to add lvmdelay=/dev/mapper/lvm-root

/etc/fstab
/dev/mapper/root        /       reiserfs        defaults        0       1
/dev/sda1               /boot   reiserfs        defaults        0       2
/dev/mapper/tmp         /tmp    tmpfs           defaults        0       0
/dev/mapper/swap        none    swap            sw              0       0
/etc/crypttab

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

Reason: /dev/urandom needs dd count and skip paramters. (Discuss in Talk:Dm-crypt with LUKS (Italiano)#Specifying_skip_and_count_in_.2Fetc.2Fcrypttab_for_.2Ftmp)
swap	/dev/lvm/swap	SWAP		-c aes-xts-plain -h whirlpool -s 512
tmp	/dev/lvm/tmp	/dev/urandom	-c aes-xts-plain -s 512

After rebooting

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

/ on LVM on LUKS

Make sure your kernel command line looks like this:

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

For example:

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

Or like this:

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

Using GPG or OpenSSL Encrypted Keyfiles

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 System Encryption using LUKS with GPG encrypted keys:

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 /etc/mkinitcpio.conf should look like HOOKS=" ... usb usbinput (etwo or ssldec) encrypt(if using openssl) lvm2 resume ... " and you should add to your kernel line(if using grub, /boot/grub/menu.lst) or GRUB_CMD_LINE(if using grub2, /etc/default/grub): "resume=/dev/mapper/<VolumeGroupName>-<LVNameOfSwap>"

  • If you need to temporarily store the unecrypted keyfile somewhere, do not store them on an

unencrytped disk. Even better make sure to store them to RAM such as /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 gnupg1
  • It is possible that an update to OpenSSL could break the custom ssldec mentioned in the second forum post.

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 all files under /boot for changes of SHA-1 hash, inode and occupied blocks on the hard drive. It also checks the MBR.

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

After installation:

  • For classical sysvinit: add /usr/local/bin/chkboot.sh & to your /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

[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 chkboot.sh script provided contains an empty space at the beginning of #!/bin/bash which has to be removed for the service to start successfully.

As /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 /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