13.4. Encrypting Storage with LUKS

LUKS protects data at rest: without a key, the container's contents are indistinguishable from noise. The kernel's device-mapper dm-crypt target does the encryption; cryptsetup formats containers and opens them into mappings. This section builds an encrypted data volume on /dev/vdg, manages its credentials, and wires it to unlock automatically - the confidentiality layer from Section 13.1.2, with its single point of failure made explicit and backed up.

13.4.1. LUKS Containers, Device Mappings, and Filesystems

A LUKS container is a header followed by encrypted data. The header is plaintext metadata: the container's UUID and parameters, the data segment description, and the keyslots. Each keyslot wraps a copy of the same volume key - the actual AES key the kernel uses - under a passphrase or key file, so several different credentials can open one container without re-encrypting anything. Opening the container unwraps the volume key into the kernel keyring and creates a device-mapper node; the filesystem lives on that node and never knows it is encrypted.

The LUKS2 device layout: a 16 MiB header holding two metadata areas and keyslots, followed by the encrypted data area, with the passphrase-to-volume-key unlock flow below.

Figure 13.6. Inside a LUKS2 container, with the practice volume's captured geometry: two 16 KiB metadata areas (a primary and a backup copy of the header), a keyslots area for up to 32 slots, and data starting at offset 16 MiB. luksHeaderBackup copies exactly the first 16 MiB.

The header is small and critical: it is the only part of the device that records how to reach the data. Destroy it and the data still exists on the platters, unreachable by any means but a backup of the header - the property Section 13.4.3 demonstrates both ways. LUKS2 is the current format; LUKS1 remains supported for existing volumes:

Property LUKS2 LUKS1
Metadata JSON, two copies, extensible Binary blob, single copy
Keyslots Up to 32, argon2id PBKDF by default Up to 8, PBKDF2 only
Header backup First 16 MiB, luksHeaderBackup First 2 MiB
Created by Default for --type luks2 --type luks1, or any pre-2018 volume

On the practice volume the default parameters are AES in XTS mode with a 512-bit key - aes-xts-plain64 - and argon2id as the passphrase-derivation function. XTS is the standard wide-block encryption mode for disk sectors, and argon2id is deliberately memory-hard: a wrong passphrase costs the attacker a large amount of memory per guess, not just a fast hash computation, which is what makes offline guessing on a stolen disk expensive.

13.4.2. Creating and Opening an Encrypted Data Volume

The target is /dev/vdg, blank from the chapter's start. Wipe any residue first:

# wipefs -a /dev/vdg

Silent. cryptsetup's subcommands share a set of options; the ones this chapter uses:

Option Description
--type luks2 State the LUKS version explicitly when formatting or opening
--label NAME Record a label in the header for recognition in listings
--key-file FILE Take the credential from FILE instead of prompting
--header-backup-file FILE Name the file luksHeaderBackup writes and luksHeaderRestore reads

Format the container - the exact command, with the type stated and a label for recognition in listings:

# cryptsetup luksFormat --type luks2 --label handbook-crypt /dev/vdg

The command asks two things interactively and prints no other output. First it warns that the operation is irreversible and asks for confirmation - Are you sure? (Type 'yes' in capital letters): - so only YES in capitals proceeds. Then it asks for the new passphrase twice (Enter passphrase, then Verify passphrase), with typing hidden. When it returns silently, the container exists.

Inspect what was written:

# cryptsetup luksDump /dev/vdg
LUKS header information
Version:        2
Metadata area:  16384 [bytes]
Keyslots area:  16744448 [bytes]
UUID:           809b56a1-bde7-4dd2-b3d3-23b826853806
Label:          handbook-crypt

Data segments:
  0: crypt
    offset: 16777216 [bytes]
    length: (whole device)
    cipher: aes-xts-plain64
    sector: 512 [bytes]

Keyslots:
  0: luks2
    Key:        512 bits
    Priority:   normal
    Cipher:     aes-xts-plain64
    PBKDF:      argon2id
    Time cost:  4
    Memory:     617396
    Threads:    1
    Area offset:32768 [bytes]
    Area length:258048 [bytes]
    Digest ID:  0

Selected output; the epoch, subsystem, and flags header lines, the keyslot's cipher-key, salt, and anti-forensic parameters, and the trailing tokens and digests section are omitted.

The geometry matches Figure 13.6: two 16 KiB metadata areas (the dump's Metadata area: 16384 [bytes] is the size of each one), a keyslots area of 16,744,448 bytes inside the first 16 MiB, and data starting at offset 16,777,216.

Keyslot 0 holds a 512-bit key wrapped with argon2id; the Memory: 617396 figure is the kilobytes of memory one passphrase attempt consumes. blkid now recognizes the device by its new signature:

# blkid /dev/vdg
/dev/vdg: UUID="809b56a1-bde7-4dd2-b3d3-23b826853806" LABEL="handbook-crypt" TYPE="crypto_LUKS"

That UUID= with TYPE="crypto_LUKS" is what /etc/crypttab will reference in Section 13.4.4. Open the container under a chosen name - the name becomes the mapping:

# cryptsetup open --type luks2 /dev/vdg cryptdata

The command prompts once for the passphrase, again with typing hidden, and on success prints nothing. The mapping exists:

# cryptsetup status cryptdata
/dev/mapper/cryptdata is active.
  type:    LUKS2
  cipher:  aes-xts-plain64
  keysize: 512 bits
  key location: keyring
  device:  /dev/vdg
  sector size:  512
  offset:  32768 sectors
  size:    4161536 sectors
  mode:    read/write

status reports the mapping's essentials: which device it decrypts, the cipher and key size in use, the offset - 32,768 sectors of 512 bytes is the 16 MiB header again - and the access mode the mapping currently allows. The tree view shows the new layer:

# lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT /dev/vdg
NAME        SIZE TYPE  FSTYPE      MOUNTPOINT
vdg           2G disk  crypto_LUKS 
└─cryptdata   2G crypt             

/dev/vdg is now a two-level tree: the disk carrying the signature, and the crypt device under /dev/mapper. Filesystem, mount point, and john's file, exactly as before - each step silent:

# mkfs.ext4 -q -L handbook-crypt /dev/mapper/cryptdata
# mkdir -p /srv/luks
# chown john:john /srv/luks
# mount /dev/mapper/cryptdata /srv/luks
# chown john:john /srv/luks

As john, in /srv/luks:

$ printf "%s\n" "encrypted payload" > readme.txt
$ cat readme.txt
encrypted payload

One capacity observation in the root shell:

# df -h /srv/luks
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/cryptdata  2.0G  536K  1.9G   1% /srv/luks

The 2 GiB disk yields a 2.0 GiB filesystem; the 16 MiB header is barely visible at this scale. The volume is now a working encrypted data store: locked with a passphrase, readable through the mapping, and - per Section 13.1.2 - protected against nothing but the physical disclosure of the disk.

13.4.3. Keyslots, Passphrases, Key Files, and Header Backups

A keyslot is a credential: passphrase or key file, wrapped around the volume key, occupying one slot. Slot 0 holds the passphrase set at format time. This section adds a key file as a second slot - the form automation can use - then exercises the failure modes: a wrong passphrase, and a destroyed header with its recovery.

Generate a 32-byte random key file in john's workspace, then make it readable only by root:

# dd if=/dev/urandom of=/home/john/debian-handbook/storage-layers/luks-key.bin bs=32 count=1 status=none

bs=32 count=1 reads one 32-byte piece of the kernel's random source into the named file; status=none suppresses dd's transfer summary, so the command is silent. Take ownership and permissions:

# chown root:root /home/john/debian-handbook/storage-layers/luks-key.bin
# chmod 400 /home/john/debian-handbook/storage-layers/luks-key.bin
# ls -l /home/john/debian-handbook/storage-layers/luks-key.bin
-r-------- 1 root root 32 Nov 20 11:17 /home/john/debian-handbook/storage-layers/luks-key.bin

Mode 0400, owned by root: any process that can read this file can open the container, so the file's permissions are the container's lock. Note the absolute path - in the root shell, ~ expands to root's home, not john's, so the path under /home/john is spelled out (Chapter 3 Section 3.2.1 covered tilde expansion). Install it as a new keyslot:

# cryptsetup luksAddKey /dev/vdg /home/john/debian-handbook/storage-layers/luks-key.bin

The command prompts for any existing passphrase - the proof of authority to add a credential - then reads the named file as the new key. It prints nothing on success. The dump shows two slots:

# cryptsetup luksDump /dev/vdg
LUKS header information
Version:        2
Metadata area:  16384 [bytes]
Keyslots area:  16744448 [bytes]
UUID:           809b56a1-bde7-4dd2-b3d3-23b826853806
Label:          handbook-crypt

Data segments:
  0: crypt
    offset: 16777216 [bytes]
    cipher: aes-xts-plain64
    sector: 512 [bytes]

Keyslots:
  0: luks2
    Key:        512 bits
    PBKDF:      argon2id
    Time cost:  4
    Memory:     617396
    Area offset:32768 [bytes]
    Area length:258048 [bytes]
    Digest ID:  0
  1: luks2
    Key:        512 bits
    PBKDF:      argon2id
    Time cost:  4
    Memory:     499001
    Area offset:290816 [bytes]
    Area length:258048 [bytes]
    Digest ID:  0

Selected output; the epoch, subsystem, and flags header lines, the data segment's length line, both keyslots' priority, cipher, and thread lines, the keyslots' cipher-key, salt, and anti-forensic parameters, and the trailing tokens and digests section are omitted.

Keyslot 1 now exists with its own area offset, its own salt, and its own argon2id parameters - each slot is derived independently, which is why the memory figures differ. Both slots carry the same Digest ID: both wrap the same volume key, so either one opens the container. Close and reopen with the key file to prove it. The unmount and close are silent:

# umount /srv/luks
# cryptsetup close cryptdata

Now open with the key file instead of a prompt:

# cryptsetup open --type luks2 --key-file /home/john/debian-handbook/storage-layers/luks-key.bin /dev/vdg cryptdata

Silent - no prompt, because the credential came from the file. The mapping is up:

# cryptsetup status cryptdata
/dev/mapper/cryptdata is active.
  type:    LUKS2
  cipher:  aes-xts-plain64
  keysize: 512 bits
  key location: keyring
  device:  /dev/vdg
  sector size:  512
  offset:  32768 sectors
  size:    4161536 sectors
  mode:    read/write

Close it again for the failure exercises:

# cryptsetup close cryptdata

Silent. First, the wrong-credential failure. Attempt to open with a mistyped passphrase:

# cryptsetup open --type luks2 /dev/vdg cryptdata
No key available with this passphrase.

The attempt fails; cryptsetup documents exit status 2 as the bad-passphrase result. Nothing was created - check:

# cryptsetup status cryptdata
/dev/mapper/cryptdata is inactive.

status on a nonexistent mapping reports it inactive (exit status 4, the documented code for a wrong device). The container is untouched; a wrong passphrase costs nothing but the argon2id attempt.

Now the header. Back it up before anything threatens it:

# rm -f /home/john/debian-handbook/storage-layers/luks-header.img

Silent - removing any earlier copy so the exercise cannot confuse a stale backup with a fresh one.

# cryptsetup luksHeaderBackup /dev/vdg --header-backup-file /home/john/debian-handbook/storage-layers/luks-header.img

Silent. The file:

# ls -lh /home/john/debian-handbook/storage-layers/luks-header.img
-r-------- 1 root root 16M Nov 20 11:18 /home/john/debian-handbook/storage-layers/luks-header.img

16 MiB, matching the dump's geometry, created by cryptsetup readable only by root. It contains both keyslots as they are now - a header backup is a snapshot, and restoring it returns the keyslots to this moment, discarding any slot added or changed afterward. Keep the backup off the encrypted disk itself, and somewhere a lost machine does not take with it (Chapter 15 Section 15.1.2 includes it in backup selection). Chapter 2 Section 2.3.3's advice applies verbatim: keep a header backup, and test that it unlocks the volume.

Now destroy the header deliberately, to see both the loss and the recovery.

Warning: The next command overwrites the first 16 MiB of /dev/vdg with zeros. That is the entire LUKS header - both metadata areas and every keyslot. On the practice volume this is deliberate and recoverable from the backup just taken; on a real volume without a backup it makes the data permanently unreachable.

# dd if=/dev/zero of=/dev/vdg bs=1M count=16 conv=fsync status=none

bs=1M count=16 writes the 16 MiB; conv=fsync makes dd flush the writes to the device before exiting; status=none suppresses the transfer summary. The command is silent. Try to open what is left:

# cryptsetup open --type luks2 /dev/vdg cryptdata
Device /dev/vdg is not a valid LUKS device.

No passphrase is even asked for: the magic bytes that identify a LUKS container are gone, and cryptsetup exits with status 1. The data area still holds the encrypted filesystem - nothing overwrote it - but no keyslot exists to unwrap the volume key. Restore the header:

# cryptsetup luksHeaderRestore /dev/vdg --header-backup-file /home/john/debian-handbook/storage-layers/luks-header.img

Silent - the 16 MiB from the backup file is written back over the zeroed region. Open again, with the passphrase:

# cryptsetup open --type luks2 /dev/vdg cryptdata

The prompt appears as in Section 13.4.2; on the correct passphrase the command is silent. Mount the filesystem again in the root shell:

# mount /dev/mapper/cryptdata /srv/luks

Silent. As john, in /srv/luks:

$ cat readme.txt
encrypted payload

The file is intact - the header loss never touched the data area, and the restored header still wraps the same volume key. That asymmetry is the whole lesson of the exercise: the header is simultaneously critical (nothing opens without it) and small enough to back up in one file. The same backup discipline covers the other loss mode of this section: losing all credentials - every passphrase forgotten, every key file destroyed - leaves a healthy container with no usable slot, and the header backup is then the only remaining credential, not a violation of the encryption. cryptsetup luksKillSlot removes a single slot when rotating credentials, as cryptsetup(8) documents.

13.4.4. Persistent Unlocking with /etc/crypttab

So far the mapping has been opened and closed by hand. A volume that should be present after every boot is declared in /etc/crypttab, one line per container:

Field Meaning This volume's value
name Mapping name, appears under /dev/mapper/ cryptdata
source Device or UUID= of the LUKS container UUID=809b56a1-…
key file Path to a key file, or none to prompt at the console the key file from Section 13.4.3
options Comma-separated; luks selects LUKS unlocking luks

Close the mapping first, so the activation that follows is visibly the crypttab's doing. Both commands are silent:

# umount /srv/luks
# cryptsetup close cryptdata

Get the container UUID - the identifier Section 13.1.3's table listed:

# cryptsetup luksUUID /dev/vdg
809b56a1-bde7-4dd2-b3d3-23b826853806

Write the entry. Whether the file already exists depends on how the system was built: the Debian installer creates /etc/crypttab when it configures encrypted volumes - Chapter 2 Section 2.3.3's guided layout does - while the cryptsetup package, for its part, ships the format's manual page rather than the file. On the example system the file holds nothing but comments, so this example replaces it with its single active line; on a system that already holds entries, append instead of overwriting, and on a system where the file is absent the redirection creates it:

cryptdata UUID=809b56a1-bde7-4dd2-b3d3-23b826853806 /home/john/debian-handbook/storage-layers/luks-key.bin luks
# printf 'cryptdata UUID=809b56a1-bde7-4dd2-b3d3-23b826853806 /home/john/debian-handbook/storage-layers/luks-key.bin luks\n' > /etc/crypttab

The redirection writes the file rather than printing to the terminal. Read it back:

# cat /etc/crypttab
cryptdata UUID=809b56a1-bde7-4dd2-b3d3-23b826853806 /home/john/debian-handbook/storage-layers/luks-key.bin luks

Activate the entry by name with the helper Debian's cryptsetup package provides:

# cryptdisks_start cryptdata
Starting crypto disk...cryptdata (starting)...cryptdata (started)...done.

cryptdisks_start runs, on demand, the same unlock steps boot-time crypttab processing performs for each entry: find the source by UUID, unlock with the named key file, create the mapping. The helper also checks the key file's ownership and permissions - a key file readable by other users draws a warning, which the root-only 0400 file from Section 13.4.3 avoids. Verify:

# cryptsetup status cryptdata
/dev/mapper/cryptdata is active.
  type:    LUKS2
  cipher:  aes-xts-plain64
  keysize: 512 bits
  key location: keyring
  device:  /dev/vdg
  sector size:  512
  offset:  32768 sectors
  size:    4161536 sectors
  mode:    read/write

With the mapping up, finish the persistence chain in /etc/fstab, exactly as Chapter 11 Section 11.3.3 did for a plain partition. Get the filesystem's UUID - a different identifier from the container's, read from the mapping:

# blkid -s UUID -o value /dev/mapper/cryptdata
a50ad955-f4b9-4778-8c62-1e22caac3236

Back up the fstab before editing - Chapter 11 Section 11.3.3's rule for a file whose errors can block a boot:

# cp -p /etc/fstab /etc/fstab.ch13backup

Silent. The new entry:

UUID=a50ad955-f4b9-4778-8c62-1e22caac3236 /srv/luks ext4 defaults,nofail 0 2
# printf 'UUID=a50ad955-f4b9-4778-8c62-1e22caac3236 /srv/luks ext4 defaults,nofail 0 2\n' >> /etc/fstab

The >> operator appends the line to the file without printing it; read the entry back to confirm what landed:

# grep /srv/luks /etc/fstab
UUID=a50ad955-f4b9-4778-8c62-1e22caac3236 /srv/luks ext4 defaults,nofail 0 2

grep prints the matching lines - here the one line the append added, with the system's own entries left out of the view. The nofail option matters more here than it did in Chapter 11: this filesystem depends on the crypttab activation succeeding first, and an encrypted volume that fails to unlock (a missing key file, a detached disk) should not hold the rest of the boot hostage - the mount is skipped with a journal message instead. Mount everything in the file that is not yet mounted:

# mount -a

Silent. Confirm the mount and its source:

# findmnt /srv/luks
TARGET    SOURCE                FSTYPE OPTIONS
/srv/luks /dev/mapper/cryptdata ext4   rw,relatime

As john, in /srv/luks, the data is where it was left:

$ cat readme.txt
encrypted payload

Reverse the whole chain to close down: unmount the filesystem, then deactivate the mapping by name:

# umount /srv/luks
# cryptdisks_stop cryptdata
Stopping crypto disk...cryptdata (stopping)...done.

cryptdisks_stop closes the mapping, and a mapping cannot close while its filesystem is still mounted - the same top-down order Section 13.5.4 formalizes, demonstrated there with cryptsetup close. Restore the fstab, since this entry was for demonstration:

# mv /etc/fstab.ch13backup /etc/fstab

Silent. The crypttab entry is left in place for now; Section 13.5.4 removes it with the rest of the practice configuration.

Two behaviors of this configuration complete the picture. The first is what happens at boot, and on a Debian 13 systemd system that job is systemd's: the systemd-cryptsetup package - present on ordinary installations because the systemd package recommends it - supplies systemd-cryptsetup-generator, which reads /etc/crypttab whenever systemd loads its configuration and turns each entry into a systemd-cryptsetup@<name>.service unit ordered before the mounts that need the mapping. The entry just written has not reached systemd yet, so make it run the generator now:

# systemctl daemon-reload

Silent - daemon-reload makes systemd re-read its configuration, generators included. The generated unit can be read by name:

# systemctl cat systemd-cryptsetup@cryptdata.service
# /run/systemd/generator/systemd-cryptsetup@cryptdata.service
# Automatically generated by systemd-cryptsetup-generator

[Unit]
SourcePath=/etc/crypttab
RequiresMountsFor=/home/john/debian-handbook/storage-layers/luks-key.bin

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/systemd-cryptsetup attach 'cryptdata' '/dev/disk/by-uuid/809b56a1-bde7-4dd2-b3d3-23b826853806' '/home/john/debian-handbook/storage-layers/luks-key.bin' 'luks'
ExecStop=/usr/bin/systemd-cryptsetup detach 'cryptdata'

Selected output; the unit's description, documentation, and remaining dependency and service lines are omitted. SourcePath records where the entry came from; RequiresMountsFor ensures the key file's filesystem is mounted before the unlock; and ExecStart is the crypttab line translated into a unit - systemd-cryptsetup attach, with the mapping name, the /dev/disk/by-uuid/ source, the key file, and the luks option. At boot the generator creates this unit automatically, so the data volume unlocks and mounts without a console prompt; the prompt-based alternative is the third field none, which makes the unit ask at the console instead. The legacy cryptdisks init script is masked on systemd systems in favor of this path - the cryptsetup package's README.Debian notes it - leaving cryptdisks_start and cryptdisks_stop, used earlier in this section, as the manual on-demand forms. Figure 13.7 in Section 13.5.1 shows where both paths sit in the boot sequence. Second, the layer interacts with SSD TRIM: the kernel does not forward filesystem discard requests through a LUKS mapping unless the mapping opts in, because discarded-sector bookkeeping can leak which blocks are unused; adding discard to the crypttab options enables it. A complete stack needs each layer's answer: plain partitions pass discards, LVM's linear mappings pass them by default, md forwards them for RAID0 and RAID1 (parity levels have changed support across kernel versions, so verify before relying on it), and LUKS requires the explicit opt-in just described. LVM separately consults its issue_discards setting when volume space is removed, deciding whether deletions send discards down; Chapter 11 Section 11.5.1 covered the filesystem's half of the arrangement.