Imported Upstream version 2.3.7
[platform/upstream/cryptsetup.git] / FAQ.md
1 # Frequently Asked Questions Cryptsetup/LUKS
2
3 # Sections
4 [1. General Questions](#1-general-questions)  
5 [2. Setup](#2-setup)  
6 [3. Common Problems](#3-common-problems)  
7 [4. Troubleshooting](#4-troubleshooting)  
8 [5. Security Aspects](#5-security-aspects)  
9 [6. Backup and Data Recovery](#6-backup-and-data-recovery)  
10 [7. Interoperability with other Disk Encryption Tools](#7-interoperability-with-other-disk-encryption-tools)  
11 [8. Issues with Specific Versions of cryptsetup](#8-issues-with-specific-versions-of-cryptsetup)  
12 [9. The Initrd question](#9-the-initrd-question)  
13 [10. LUKS2 Questions](#10-luks2-questions)  
14 [11. References and Further Reading](#11-references-and-further-reading)  
15 [A. Contributors](#a-contributors)  
16
17 # 1. General Questions
18
19
20   * **1.1 What is this?**
21
22   This is the FAQ (Frequently Asked Questions) for cryptsetup.  It covers
23   Linux disk encryption with plain dm-crypt (one passphrase, no
24   management, no metadata on disk) and LUKS (multiple user keys with one
25   volume key, anti-forensic features, metadata block at start of device,
26   ...).  The latest version of this FAQ should usually be available at
27   https://gitlab.com/cryptsetup/cryptsetup/wikis/FrequentlyAskedQuestions
28
29
30   * **1.2 WARNINGS**
31
32   LUKS2 COMPATIBILITY: This FAQ was originally written for LUKS1, not
33   LUKS2.  Hence regarding LUKS2, some of the answers found here may not
34   apply.  Updates for LUKS2 have been done and anything not applying to
35   LUKS2 should clearly say LUKS1.  However, this is a Frequently Asked
36   Questions, and questions for LUKS2 are limited at this time or at least
37   those that have reached me are.  In the following, "LUKS" refers to both
38   LUKS1 and LUKS2.
39  
40   The LUKS1 on-disk format specification is at  
41   https://www.kernel.org/pub/linux/utils/cryptsetup/LUKS_docs/on-disk-format.pdf  
42   The LUKS2 on-disk format specification is at  
43   https://gitlab.com/cryptsetup/LUKS2-docs
44
45   ATTENTION: If you are going to read just one thing, make it the section
46   on Backup and Data Recovery.  By far the most questions on the
47   cryptsetup mailing list are from people that managed to damage the start
48   of their LUKS partitions, i.e.  the LUKS header.  In most cases, there
49   is nothing that can be done to help these poor souls recover their data. 
50   Make sure you understand the problem and limitations imposed by the LUKS
51   security model BEFORE you face such a disaster!  In particular, make
52   sure you have a current header backup before doing any potentially
53   dangerous operations.  The LUKS2 header should be a bit more resilient
54   as critical data starts later and is stored twice, but you can decidedly
55   still destroy it or a keyslot permanently by accident.
56
57   DEBUG COMMANDS: While the --debug and --debug-json options should not
58   leak secret data, "strace" and the like can leak your full passphrase. 
59   Do not post an strace output with the correct passphrase to a
60   mailing-list or online!  See Item 4.5 for more explanation.
61
62   SSDs/FLASH DRIVES: SSDs and Flash are different.  Currently it is
63   unclear how to get LUKS or plain dm-crypt to run on them with the full
64   set of security assurances intact.  This may or may not be a problem,
65   depending on the attacker model.  See Section 5.19.
66
67   BACKUP: Yes, encrypted disks die, just as normal ones do.  A full backup
68   is mandatory, see Section "6.  Backup and Data Recovery" on options for
69   doing encrypted backup.
70
71   CLONING/IMAGING: If you clone or image a LUKS container, you make a copy
72   of the LUKS header and the volume key will stay the same!  That means
73   that if you distribute an image to several machines, the same volume key
74   will be used on all of them, regardless of whether you change the
75   passphrases.  Do NOT do this!  If you do, a root-user on any of the
76   machines with a mapped (decrypted) container or a passphrase on that
77   machine can decrypt all other copies, breaking security.  See also Item
78   6.15.
79
80   DISTRIBUTION INSTALLERS: Some distribution installers offer to create
81   LUKS containers in a way that can be mistaken as activation of an
82   existing container.  Creating a new LUKS container on top of an existing
83   one leads to permanent, complete and irreversible data loss.  It is
84   strongly recommended to only use distribution installers after a
85   complete backup of all LUKS containers has been made.
86
87   UBUNTU INSTALLER: In particular the Ubuntu installer seems to be quite
88   willing to kill LUKS containers in several different ways.  Those
89   responsible at Ubuntu seem not to care very much (it is very easy to
90   recognize a LUKS container), so treat the process of installing Ubuntu
91   as a severe hazard to any LUKS container you may have.
92
93   NO WARNING ON NON-INTERACTIVE FORMAT: If you feed cryptsetup from STDIN
94   (e.g.  via GnuPG) on LUKS format, it does not give you the warning that
95   you are about to format (and e.g.  will lose any pre-existing LUKS
96   container on the target), as it assumes it is used from a script.  In
97   this scenario, the responsibility for warning the user and possibly
98   checking for an existing LUKS header is shifted to the script.  This is
99   a more general form of the previous item.
100
101   LUKS PASSPHRASE IS NOT THE VOLUME KEY: The LUKS passphrase is not used
102   in deriving the volume key.  It is used in decrypting a volume key that
103   is randomly selected on header creation.  This means that if you create
104   a new LUKS header on top of an old one with exactly the same parameters
105   and exactly the same passphrase as the old one, it will still have a
106   different volume key and your data will be permanently lost.
107
108   PASSPHRASE CHARACTER SET: Some people have had difficulties with this
109   when upgrading distributions.  It is highly advisable to only use the 95
110   printable characters from the first 128 characters of the ASCII table,
111   as they will always have the same binary representation.  Other
112   characters may have different encoding depending on system configuration
113   and your passphrase will not work with a different encoding.  A table of
114   the standardized first 128 ASCII characters can, e.g.  be found on
115   https://en.wikipedia.org/wiki/ASCII
116
117   KEYBOARD NUM-PAD: Apparently some pre-boot authentication environments
118   (these are done by the distro, not by cryptsetup, so complain there)
119   treat digits entered on the num-pad and ones entered regularly
120   different.  This may be because the BIOS USB keyboard driver is used and
121   that one may have bugs on some computers.  If you cannot open your
122   device in pre-boot, try entering the digits over the regular digit keys.
123
124
125   * **1.3 System specific warnings**
126
127   - The Ubuntu Natty uinstaller has a "won't fix" defect that may destroy
128   LUKS containers.  This is quite old an not relevant for most people. 
129   Reference:
130   https://bugs.launchpad.net/ubuntu/+source/partman-crypto/+bug/420080
131
132
133   * **1.4 My LUKS-device is broken! Help!**
134
135   First: Do not panic! In many cases the data is still recoverable.
136   Do not do anything hasty! Steps:
137
138   - Take some deep breaths. Maybe add some relaxing music.  This may
139   sound funny, but I am completely serious.  Often, critical damage is
140   done only after the initial problem.
141
142   - Do not reboot. The keys may still be in the kernel if the device is
143   mapped.
144
145   - Make sure others do not reboot the system.
146
147   - Do not write to your disk without a clear understanding why this will
148   not make matters worse.  Do a sector-level backup before any writes. 
149   Often you do not need to write at all to get enough access to make a
150   backup of the data.
151
152   - Relax some more.
153
154   - Read section 6 of this FAQ.
155
156   - Ask on the mailing-list if you need more help.
157
158
159   * **1.5 Who wrote this?**
160
161   Current FAQ maintainer is Arno Wagner <arno@wagner.name>.  If you want
162   to send me encrypted email, my current PGP key is DSA key CB5D9718,
163   fingerprint 12D6 C03B 1B30 33BB 13CF B774 E35C 5FA1 CB5D 9718.
164
165   Other contributors are listed at the end.  If you want to contribute,
166   send your article, including a descriptive headline, to the maintainer,
167   or the dm-crypt mailing list with something like "FAQ ..." 
168   in the subject.  You can also send more raw information and have
169   me write the section.  Please note that by contributing to this FAQ,
170   you accept the license described below.
171
172   This work is under the "Attribution-Share Alike 3.0 Unported" license,
173   which means distribution is unlimited, you may create derived works, but
174   attributions to original authors and this license statement must be
175   retained and the derived work must be under the same license.  See
176   https://creativecommons.org/licenses/by-sa/3.0/ for more details of the
177   license.
178
179   Side note: I did text license research some time ago and I think this
180   license is best suited for the purpose at hand and creates the least
181   problems.
182
183
184   * **1.6 Where is the project website?**
185
186   There is the project website at
187   https://gitlab.com/cryptsetup/cryptsetup/ Please do not post
188   questions there, nobody will read them.  Use the mailing-list
189   instead.
190
191
192   * **1.7 Is there a mailing-list?**
193
194   Instructions on how to subscribe to the mailing-list are on the
195   project website.  People are generally helpful and friendly on the
196   list.
197
198   The question of how to unsubscribe from the list does crop up sometimes. 
199   For this you need your list management URL 
200   https://subspace.kernel.org/lists.linux.dev.html. Go to the URL mentioned 
201   in the email and select "unsubscribe".
202
203   Alternatively, you can send an empty Email to cryptsetup+help@lists.linux.dev. 
204   Make sure to send it from your list address.
205
206   The mailing list archive is here:
207   https://lore.kernel.org/cryptsetup/
208
209   The legacy dm-crypt mailing list archive is here:
210   https://lore.kernel.org/dm-crypt/
211
212
213   * **1.8 Unsubscribe from the mailing-list**
214
215   Send mail to cryptsetup+unsubscribe@lists.linux.dev from the subscribed account. 
216   You will get an email with instructions.
217
218   Basically, you just have to respond to it unmodified to get
219   unsubscribed.  The listserver admin functions are not very fast.  It can
220   take 15 minutes or longer for a reply to arrive (I suspect greylisting
221   is in use), so be patient.
222
223   Also note that nobody on the list can unsubscribe you, sending demands
224   to be unsubscribed to the list just annoys people that are entirely
225   blameless for you being subscribed.
226
227   If you are subscribed, a subscription confirmation email was sent to
228   your email account and it had to be answered before the subscription
229   went active.  The confirmation emails from the listserver have subjects
230   like these (with other numbers):
231 ```
232     Subject: Confirm subscription to cryptsetup@lists.linux.dev
233 ```
234   and are sent from cryptsetup+help@lists.linux.dev.  You should check whether
235   you have anything like it in your sent email folder.  If you find
236   nothing and are sure you did not confirm, then you should look into a
237   possible compromise of your email account.
238
239   * **1.9 What can I do if cryptsetup is running out of memory?**
240
241   Memory issues are generally related to the key derivation function.  You may
242   be able to tune usage with the options --pbkdf-memory or --pbkdf pbkdf2.
243
244
245   * **1.10 Can cryptsetup be run without root access?**
246
247   Elevated privileges are required to use cryptsetup and LUKS.  Some operations
248   require root access.  There are a few features which will work without root 
249   access with the right switches but there are caveats.
250
251
252   * **1.11 What are the problems with running as non root?**
253
254   The first issue is one of permissions to devices.  Generally, root or a group
255   such as disk has ownership of the storage devices.  The non root user will
256   need write access to the block device used for LUKS.
257
258   Next, file locking is managed in /run/cryptsetup.  You may use 
259   --disable-locks but cryptsetup will no longer protect you from race 
260   conditions and problems with concurrent access to the same devices.
261
262   Also, device mapper requires root access.  cryptsetup uses device mapper to 
263   manage the decrypted container.
264
265   * **1.12 How can I report an issue in the cryptsetup project?**
266
267   Before reporting any issue, please be sure you are using the latest
268   upstream version and that you read the documentation (and this FAQ).
269
270   If you think you have discovered an issue, please report it through
271   the project issue tracker [New issue](https://gitlab.com/cryptsetup/cryptsetup/issues).
272   For a possible security issue, please use the confidential checkbox.
273
274   Please fill in all information requested in the report template
275   (specifically add debug output with all run environment data).
276   Do not trim the output; debug output does not include private data.
277
278
279 # 2. Setup
280
281   * **2.1 LUKS Container Setup mini-HOWTO**
282
283   This item tries to give you a very brief list of all the steps you
284   should go through when creating a new LUKS encrypted container, i.e.
285   encrypted disk, partition or loop-file.
286
287   01) All data will be lost, if there is data on the target, make a
288   backup.
289
290   02) Make very sure you use the right target disk, partition or
291   loop-file.
292
293   03) If the target was in use previously, it is a good idea to wipe it
294   before creating the LUKS container in order to remove any trace of old
295   file systems and data.  For example, some users have managed to run
296   e2fsck on a partition containing a LUKS container, possibly because of
297   residual ext2 superblocks from an earlier use.  This can do arbitrary
298   damage up to complete and permanent loss of all data in the LUKS
299   container.
300
301   To just quickly wipe file systems (old data may remain), use
302 ```
303     wipefs -a <target device>
304 ```
305   To wipe file system and data, use something like
306 ```
307     cat /dev/zero > <target device>
308 ```
309   This can take a while.  To get a progress indicator, you can use the
310   tool dd_rescue (->google) instead or use my stream meter "wcs" (source
311   here: https://www.tansi.org/tools/index.html) in the following fashion:
312 ```
313     cat /dev/zero | wcs > <target device>
314 ```
315   Plain "dd" also gives you the progress on a SIGUSR1, see its man-page.
316   The GNU "dd" command supports the "status=progress" operand that gives you
317   the progress without having to send it any signal.
318
319   Be very sure you have the right target, all data will be lost!
320
321   Note that automatic wiping is on the TODO list for cryptsetup, so at
322   some time in the future this will become unnecessary.
323
324   Alternatively, plain dm-crypt can be used for a very fast wipe with
325   crypto-grade randomness, see Item 2.19
326
327   04) Create the LUKS container.  
328
329   LUKS1:
330 ```
331     cryptsetup luksFormat --type luks1 <target device>
332 ```   
333   LUKS2:
334 ```
335     cryptsetup luksFormat --type luks2 <target device>
336 ```
337
338   Just follow the on-screen instructions.
339
340   Note: Passphrase iteration count is based on time and hence security
341   level depends on CPU power of the system the LUKS container is created
342   on.  For example on a Raspberry Pi and LUKS1, I found some time ago that
343   the iteration count is 15 times lower than for a regular PC (well, for
344   my old one).  Depending on security requirements, this may need
345   adjustment.  For LUKS1, you can just look at the iteration count on
346   different systems and select one you like.  You can also change the
347   benchmark time with the -i parameter to create a header for a slower
348   system.
349
350   For LUKS2, the parameters are more complex.  ARGON2 has iteration,
351   parallelism and memory parameter.  cryptsetup actually may adjust the
352   memory parameter for time scaling.  Hence to use -i is the easiest way
353   to get slower or faster opening (default: 2000 = 2sec).  Just make sure
354   to not drop this too low or you may get a memory parameter that is to
355   small to be secure.  The luksDump command lists the memory parameter of
356   a created LUKS2 keyslot in kB.  That parameter should probably be not
357   much lower than 100000, i.e.  100MB, but don't take my word for it.
358
359   05) Map the container. Here it will be mapped to /dev/mapper/c1:
360 ```
361     cryptsetup luksOpen <target device> c1
362 ```
363   06) (Optionally) wipe the container (make sure you have the right
364       target!): 
365 ```
366     cat /dev/zero > /dev/mapper/c1
367 ```
368   This will take a while.  Note that this creates a small information
369   leak, as an attacker can determine whether a 512 byte block is zero if
370   the attacker has access to the encrypted container multiple times. 
371   Typically a competent attacker that has access multiple times can
372   install a passphrase sniffer anyways, so this leakage is not very
373   significant.  For getting a progress indicator, see step 03.
374
375   07) Create a file system in the mapped container, for example an
376   ext3 file system (any other file system is possible):
377 ```
378     mke2fs -j /dev/mapper/c1
379 ```
380   08) Mount your encrypted file system, here on /mnt:
381 ```
382     mount /dev/mapper/c1 /mnt
383 ```
384   09) Make a LUKS header backup and plan for a container backup.
385       See Section 6 for details.
386
387   Done.  You can now use the encrypted file system to store data.  Be sure
388   to read through the rest of the FAQ, these are just the very basics.  In
389   particular, there are a number of mistakes that are easy to make, but
390   will compromise your security.
391
392
393   * **2.2 LUKS on partitions or raw disks? What about RAID?**
394
395   Also see Item 2.8.  
396   This is a complicated question, and made more so by the availability of
397   RAID and LVM.  I will try to give some scenarios and discuss advantages
398   and disadvantages.  Note that I say LUKS for simplicity, but you can do
399   all the things described with plain dm-crypt as well.  Also note that
400   your specific scenario may be so special that most or even all things I
401   say below do not apply.
402
403   Be aware that if you add LVM into the mix, things can get very
404   complicated.  Same with RAID but less so.  In particular, data recovery
405   can get exceedingly difficult.  Only add LVM if you have a really good
406   reason and always remember KISS is what separates an engineer from an
407   amateur.  Of course, if you really need the added complexity, KISS is
408   satisfied.  But be very sure as there is a price to pay for it.  In
409   engineering, complexity is always the enemy and needs to be fought
410   without mercy when encountered.
411
412   Also consider using RAID instead of LVM, as at least with the old
413   superblock format 0.90, the RAID superblock is in the place (end of
414   disk) where the risk of it damaging the LUKS header is smallest and you
415   can have your array assembled by the RAID controller (i.e.  the kernel),
416   as it should be.  Use partition type 0xfd for that.  I recommend staying
417   away from superblock formats 1.0, 1.1 and 1.2 unless you really need
418   them.
419
420   Scenarios:
421
422   (1) Encrypted partition: Just make a partition to your liking, and put
423   LUKS on top of it and a filesystem into the LUKS container.  This gives
424   you isolation of differently-tasked data areas, just as ordinary
425   partitioning does.  You can have confidential data, non-confidential
426   data, data for some specific applications, user-homes, root, etc. 
427   Advantages are simplicity as there is a 1:1 mapping between partitions
428   and filesystems, clear security functionality and the ability to
429   separate data into different, independent (!) containers.
430
431   Note that you cannot do this for encrypted root, that requires an
432   initrd.  On the other hand, an initrd is about as vulnerable to a
433   competent attacker as a non-encrypted root, so there really is no
434   security advantage to doing it that way.  An attacker that wants to
435   compromise your system will just compromise the initrd or the kernel
436   itself.  The better way to deal with this is to make sure the root
437   partition does not store any critical data and to move that to
438   additional encrypted partitions.  If you really are concerned your root
439   partition may be sabotaged by somebody with physical access (who would
440   however strangely not, say, sabotage your BIOS, keyboard, etc.), protect
441   it in some other way.  The PC is just not set-up for a really secure
442   boot-chain (whatever some people may claim).
443
444   That said, if you want an encrypted root partition, you have to store 
445   an initrd with cryptsetup somewhere else. The traditional approach is
446   to have a separate partition under /boot for that. You can also put that 
447   initrd on a bootable memory stick, bootable CD or bootable external
448   drive as well. The kernel and Grub typically go to the same location 
449   as that initrd. A minimal example what such an initrd can look like is 
450   given in Section 9.
451   
452   (2) Fully encrypted raw block device: For this, put LUKS on the raw
453   device (e.g.  /dev/sdb) and put a filesystem into the LUKS container, no
454   partitioning whatsoever involved.  This is very suitable for things like
455   external USB disks used for backups or offline data-storage.
456
457   (3) Encrypted RAID: Create your RAID from partitions and/or full
458   devices.  Put LUKS on top of the RAID device, just if it were an
459   ordinary block device.  Applications are just the same as above, but you
460   get redundancy.  (Side note as many people seem to be unaware of it: You
461   can do RAID1 with an arbitrary number of components in Linux.) See also
462   Item 2.8.
463
464   (4) Now, some people advocate doing the encryption below the RAID layer. 
465   That has several serious problems.  One is that suddenly debugging RAID
466   issues becomes much harder.  You cannot do automatic RAID assembly
467   anymore.  You need to keep the encryption keys for the different RAID
468   components in sync or manage them somehow.  The only possible advantage
469   is that things may run a little faster as more CPUs do the encryption,
470   but if speed is a priority over security and simplicity, you are doing
471   this wrong anyways.  A good way to mitigate a speed issue is to get a
472   CPU that does hardware AES as most do today.
473
474
475   * **2.3 How do I set up encrypted swap?**
476
477   As things that are confidential can end up in swap (keys, passphrases,
478   etc.  are usually protected against being swapped to disk, but other
479   things may not be), it may be advisable to do something about the issue. 
480   One option is to run without swap, which generally works well in a
481   desktop-context.  It may cause problems in a server-setting or under
482   special circumstances.  The solution to that is to encrypt swap with a
483   random key at boot-time.
484
485   NOTE: This is for Debian, and should work for Debian-derived
486   distributions.  For others you may have to write your own startup script
487   or use other mechanisms.
488
489   01) Add the swap partition to /etc/crypttab. A line like the
490   following should do it:
491 ```
492     swap  /dev/<partition>  /dev/urandom   swap,noearly
493 ```
494   Warning: While Debian refuses to overwrite partitions with a filesystem
495   or RAID signature on it, as your disk IDs may change (adding or removing
496   disks, failure of disk during boot, etc.), you may want to take
497   additional precautions.  Yes, this means that your kernel device names
498   like sda, sdb, ...  can change between reboots!  This is not a concern
499   if you have only one disk.  One possibility is to make sure the
500   partition number is not present on additional disks or also swap there. 
501   Another is to encapsulate the swap partition (by making it a 1-partition
502   RAID1 or by using LVM), as that gets a persistent identifier. 
503   Specifying it directly by UUID does not work, unfortunately, as the UUID
504   is part of the swap signature and that is not visible from the outside
505   due to the encryption and in addition changes on each reboot with this
506   setup.
507
508   Note: Use /dev/random if you are paranoid or in a potential low-entropy
509   situation (embedded system, etc.).  This may cause the operation to take
510   a long time during boot however.  If you are in a "no entropy"
511   situation, you cannot encrypt swap securely.  In this situation you
512   should find some entropy, also because nothing else using crypto will be
513   secure, like ssh, ssl or GnuPG.
514
515   Note: The "noearly" option makes sure things like LVM, RAID, etc.  are
516   running.  As swap is non-critical for boot, it is fine to start it late.
517
518   02) Add the swap partition to /etc/fstab. A line like the following
519   should do it:
520 ```
521     /dev/mapper/swap none swap sw 0 0
522 ```
523   That is it. Reboot or start it manually to activate encrypted swap. 
524   Manual start would look like this:
525 ```
526     /etc/init.d/cryptdisks start
527     swapon /dev/mapper/swap
528 ```
529
530   * **2.4 What is the difference between "plain" and LUKS format?**
531
532   First, unless you happen to understand the cryptographic background
533   well, you should use LUKS.  It does protect the user from a lot of
534   common mistakes.  Plain dm-crypt is for experts.
535
536   Plain format is just that: It has no metadata on disk, reads all
537   parameters from the commandline (or the defaults), derives a volume-key
538   from the passphrase and then uses that to de-/encrypt the sectors of the
539   device, with a direct 1:1 mapping between encrypted and decrypted
540   sectors.
541
542   Primary advantage is high resilience to damage, as one damaged encrypted
543   sector results in exactly one damaged decrypted sector.  Also, it is not
544   readily apparent that there even is encrypted data on the device, as an
545   overwrite with crypto-grade randomness (e.g.  from
546   /dev/urandom) looks exactly the same on disk.
547
548   Side-note: That has limited value against the authorities.  In civilized
549   countries, they cannot force you to give up a crypto-key anyways.  In
550   quite a few countries around the world, they can force you to give up
551   the keys (using imprisonment or worse to pressure you, sometimes without
552   due process), and in the worst case, they only need a nebulous
553   "suspicion" about the presence of encrypted data.  Sometimes this
554   applies to everybody, sometimes only when you are suspected of having
555   "illicit data" (definition subject to change) and sometimes specifically
556   when crossing a border.  Note that this is going on in countries like
557   the US and the UK to different degrees and sometimes with courts
558   restricting what the authorities can actually demand.
559
560   My advice is to either be ready to give up the keys or to not have
561   encrypted data when traveling to those countries, especially when
562   crossing the borders.  The latter also means not having any high-entropy
563   (random) data areas on your disk, unless you can explain them and
564   demonstrate that explanation.  Hence doing a zero-wipe of all free
565   space, including unused space, may be a good idea.
566
567   Disadvantages are that you do not have all the nice features that the
568   LUKS metadata offers, like multiple passphrases that can be changed, the
569   cipher being stored in the metadata, anti-forensic properties like
570   key-slot diffusion and salts, etc..
571
572   LUKS format uses a metadata header and 8 key-slot areas that are being
573   placed at the beginning of the disk, see below under "What does the LUKS
574   on-disk format looks like?".  The passphrases are used to decrypt a
575   single volume key that is stored in the anti-forensic stripes.  LUKS2
576   adds some more flexibility.
577
578   Advantages are a higher usability, automatic configuration of
579   non-default crypto parameters, defenses against low-entropy passphrases
580   like salting and iterated PBKDF2 or ARGON 2 passphrase hashing, the
581   ability to change passphrases, and others.
582
583   Disadvantages are that it is readily obvious there is encrypted data on
584   disk (but see side note above) and that damage to the header or
585   key-slots usually results in permanent data-loss.  See below under "6. 
586   Backup and Data Recovery" on how to reduce that risk.  Also the sector
587   numbers get shifted by the length of the header and key-slots and there
588   is a loss of that size in capacity.  Unless you have a specific need,
589   use LUKS2.
590
591
592   * **2.5 Can I encrypt an existing, non-empty partition to use LUKS?**
593
594   There is no converter, and it is not really needed.  The way to do this
595   is to make a backup of the device in question, securely wipe the device
596   (as LUKS device initialization does not clear away old data), do a
597   luksFormat, optionally overwrite the encrypted device, create a new
598   filesystem and restore your backup on the now encrypted device.  Also
599   refer to sections "Security Aspects" and "Backup and Data Recovery".
600
601   For backup, plain GNU tar works well and backs up anything likely to be
602   in a filesystem.
603
604
605   * **2.6 How do I use LUKS with a loop-device?**
606
607   This can be very handy for experiments.  Setup is just the same as with
608   any block device.  If you want, for example, to use a 100MiB file as
609   LUKS container, do something like this:
610 ```
611     head -c 100M /dev/zero > luksfile               # create empty file
612     losetup /dev/loop0 luksfile                     # map file to /dev/loop0
613     cryptsetup luksFormat --type luks2 /dev/loop0   # create LUKS2 container
614 ```
615   Afterwards just use /dev/loop0 as a you would use a LUKS partition.
616   To unmap the file when done, use "losetup -d /dev/loop0".
617
618
619   * **2.7 When I add a new key-slot to LUKS, it asks for a passphrase but then complains about there not being a key-slot with that passphrase?**
620
621   That is as intended.  You are asked a passphrase of an existing key-slot
622   first, before you can enter the passphrase for the new key-slot. 
623   Otherwise you could break the encryption by just adding a new key-slot. 
624   This way, you have to know the passphrase of one of the already
625   configured key-slots in order to be able to configure a new key-slot.
626
627
628   * **2.8 Encryption on top of RAID or the other way round?**
629
630   Also see Item 2.2.  
631   Unless you have special needs, place encryption between RAID and
632   filesystem, i.e.  encryption on top of RAID.  You can do it the other
633   way round, but you have to be aware that you then need to give the
634   passphrase for each individual disk and RAID auto-detection will not
635   work anymore.  Therefore it is better to encrypt the RAID device, e.g. 
636   /dev/dm0 .
637
638   This means that the typical layering looks like this:
639 ```
640   Filesystem     <- top
641   |
642   Encryption (LUKS)
643   |
644   RAID
645   |
646   Raw partitions (optional)
647   |
648   Raw disks      <- bottom
649 ```
650   The big advantage of this is that you can manage the RAID container just
651   like any other regular RAID container, it does not care that its content
652   is encrypted.  This strongly cuts down on complexity, something very
653   valuable with storage encryption.
654
655   Try to avoid so-called fake RAID (RAID configured from BIOS but handled
656   by proprietary drivers). Note that some fake RAID firmware automatically
657   writes signature on disks if enabled. This causes corruption of LUKS
658   metadata. Be sure to switch the RAID option off in BIOS if you do not
659   use it.
660
661   Another data corruption can happen if you resize (enlarge) the underlying
662   device and some remnant metadata appear near the end of the resized device
663   (like a secondary copy of the GPT table). You can use wipefs command to
664   detect and wipe such signatures.
665
666
667   * **2.9 How do I read a dm-crypt key from file?**
668
669   Use the --key-file option, like this:
670 ```
671     cryptsetup create --key-file keyfile e1 /dev/loop0
672 ```
673   This will read the binary key from file, i.e.  no hashing or
674   transformation will be applied to the keyfile before its bits are used
675   as key.  Extra bits (beyond the length of the key) at the end are
676   ignored.  Note that if you read from STDIN, the data will be hashed,
677   just as a key read interactively from the terminal.  See the man-page
678   sections "NOTES ON PASSPHRASE PROCESSING..." for more detail.
679
680
681   * **2.10 How do I read a LUKS slot key from file?**
682
683   What you really do here is to read a passphrase from file, just as you
684   would with manual entry of a passphrase for a key-slot.  You can add a
685   new passphrase to a free key-slot, set the passphrase of an specific
686   key-slot or put an already configured passphrase into a file.  Make sure
687   no trailing newline (0x0a) is contained in the input key file, or the
688   passphrase will not work because the whole file is used as input.
689
690   To add a new passphrase to a free key slot from file, use something
691   like this:
692 ```
693     cryptsetup luksAddKey /dev/loop0 keyfile
694 ```   
695   To add a new passphrase to a specific key-slot, use something
696   like this:
697 ```
698     cryptsetup luksAddKey --key-slot 7 /dev/loop0 keyfile
699 ```   
700   To supply a key from file to any LUKS command, use the --key-file
701   option, e.g. like this:
702 ```
703     cryptsetup luksOpen --key-file keyfile /dev/loop0 e1
704 ```   
705
706
707   * **2.11 How do I read the LUKS volume key from file?**
708
709   The question you should ask yourself first is why you would want to do
710   this.  The only legitimate reason I can think of is if you want to have
711   two LUKS devices with the same volume key.  Even then, I think it would
712   be preferable to just use key-slots with the same passphrase, or to use
713   plain dm-crypt instead.  If you really have a good reason, please tell
714   me.  If I am convinced, I will add how to do this here.
715
716
717   * **2.12 What are the security requirements for a key read from file?**
718
719   A file-stored key or passphrase has the same security requirements as
720   one entered interactively, however you can use random bytes and thereby
721   use bytes you cannot type on the keyboard.  You can use any file you
722   like as key file, for example a plain text file with a human readable
723   passphrase.  To generate a file with random bytes, use something like
724   this:
725 ```
726     head -c 256 /dev/random > keyfile
727 ```
728
729
730   * **2.13 If I map a journaled file system using dm-crypt/LUKS, does it still provide its usual transactional guarantees?**
731
732   Yes, it does, unless a very old kernel is used.  The required flags come
733   from the filesystem layer and are processed and passed onward by
734   dm-crypt (regardless of direct key management or LUKS key management). 
735   A bit more information on the process by which transactional guarantees
736   are implemented can be found here:
737
738   https://lwn.net/Articles/400541/
739
740   Please note that these "guarantees" are weaker than they appear to be. 
741   One problem is that quite a few disks lie to the OS about having flushed
742   their buffers.  This is likely still true with SSDs.  Some other things
743   can go wrong as well.  The filesystem developers are aware of these
744   problems and typically can make it work anyways.  That said,
745   dm-crypt/LUKS will not make things worse.
746
747   One specific problem you can run into is that you can get short freezes
748   and other slowdowns due to the encryption layer.  Encryption takes time
749   and forced flushes will block for that time.  For example, I did run
750   into frequent small freezes (1-2 sec) when putting a vmware image on
751   ext3 over dm-crypt.  When I went back to ext2, the problem went away. 
752   This seems to have gotten better with kernel 2.6.36 and the reworking of
753   filesystem flush locking mechanism (less blocking of CPU activity during
754   flushes).  This should improve further and eventually the problem should
755   go away.
756
757
758   * **2.14 Can I use LUKS or cryptsetup with a more secure (external) medium for key storage, e.g. TPM or a smartcard?**
759
760   Yes, see the answers on using a file-supplied key.  You do have to write
761   the glue-logic yourself though.  Basically you can have cryptsetup read
762   the key from STDIN and write it there with your own tool that in turn
763   gets the key from the more secure key storage.
764
765
766   * **2.15 Can I resize a dm-crypt or LUKS container?**
767
768   Yes, you can, as neither dm-crypt nor LUKS1 stores partition size and
769   LUKS2 uses a generic "whole device" size as default.  Note that LUKS2
770   can use specified data-area sizes as a non-standard case and that these
771   may cause issues when resizing a LUKS2 container if set to a specific
772   value.
773
774   Whether you should do this is a different question.  Personally I
775   recommend backup, recreation of the dm-crypt or LUKS container with new
776   size, recreation of the filesystem and restore.  This gets around the
777   tricky business of resizing the filesystem.  Resizing a dm-crypt or LUKS
778   container does not resize the filesystem in it.  A backup is really
779   non-optional here, as a lot can go wrong, resulting in partial or
780   complete data loss.  But if you have that backup, you can also just
781   recreate everything.
782
783   You also need to be aware of size-based limitations.  The one currently
784   relevant is that aes-xts-plain should not be used for encrypted
785   container sizes larger than 2TiB.  Use aes-xts-plain64 for that.
786
787
788   * **2.16 How do I Benchmark the Ciphers, Hashes and Modes?**
789
790   Since version 1.60 cryptsetup supports the "benchmark" command. 
791   Simply run as root:
792 ```
793     cryptsetup benchmark
794 ```
795   You can get more than the default benchmarks, see the man-page for the
796   relevant parameters.  Note that XTS mode takes two keys, hence the
797   listed key sizes are double that for other modes and half of it is the
798   cipher key, the other half is the XTS key.
799
800
801   * **2.17 How do I Verify I have an Authentic cryptsetup Source Package?**
802
803   Current maintainer is Milan Broz and he signs the release packages with
804   his PGP key.  The key he currently uses is the "RSA key ID D93E98FC",
805   fingerprint 2A29 1824 3FDE 4664 8D06 86F9 D9B0 577B D93E 98FC.  While I
806   have every confidence this really is his key and that he is who he
807   claims to be, don't depend on it if your life is at stake.  For that
808   matter, if your life is at stake, don't depend on me being who I claim
809   to be either.
810
811   That said, as cryptsetup is under good version control and a malicious
812   change should be noticed sooner or later, but it may take a while. 
813   Also, the attacker model makes compromising the sources in a non-obvious
814   way pretty hard.  Sure, you could put the volume-key somewhere on disk,
815   but that is rather obvious as soon as somebody looks as there would be
816   data in an empty LUKS container in a place it should not be.  Doing this
817   in a more nefarious way, for example hiding the volume-key in the salts,
818   would need a look at the sources to be discovered, but I think that
819   somebody would find that sooner or later as well.
820
821   That said, this discussion is really a lot more complicated and longer
822   as an FAQ can sustain.  If in doubt, ask on the mailing list.
823
824
825   * **2.18 Is there a concern with 4k Sectors?**
826
827   Not from dm-crypt itself.  Encryption will be done in 512B blocks, but
828   if the partition and filesystem are aligned correctly and the filesystem
829   uses multiples of 4kiB as block size, the dm-crypt layer will just
830   process 8 x 512B = 4096B at a time with negligible overhead.  LUKS does
831   place data at an offset, which is 2MiB per default and will not break
832   alignment.  See also Item 6.12 of this FAQ for more details.  Note that
833   if your partition or filesystem is misaligned, dm-crypt can make the
834   effect worse though.  Also note that SSDs typically have much larger
835   blocks internally (e.g.  128kB or even larger).
836
837
838   * **2.19 How can I wipe a device with crypto-grade randomness?**
839
840   The conventional recommendation if you want to do more than just a
841   zero-wipe is to use something like
842 ```
843     cat /dev/urandom >  <target-device>
844 ```
845   That used to very slow and painful at 10-20MB/s on a fast computer, but
846   newer kernels can give you > 200MB/s (depending on hardware).  An
847   alternative is using cryptsetup and a plain dm-crypt device with a
848   random key, which is fast and on the same level of security.  The
849   defaults are quite enough.
850
851   For device set-up, do the following:
852 ```
853     cryptsetup open --type plain -d /dev/urandom /dev/<device> target
854 ```
855   This maps the container as plain under /dev/mapper/target with a random
856   password.  For the actual wipe you have several options.  Basically, you
857   pipe zeroes into the opened container that then get encrypted.  Simple
858   wipe without progress-indicator:
859 ```
860     cat /dev/zero > /dev/mapper/to_be_wiped
861 ```
862   Progress-indicator by dd_rescue:
863 ```
864     dd_rescue -w /dev/zero /dev/mapper/to_be_wiped
865 ```
866   Progress-indicator by my "wcs" stream meter (available from
867   https://www.tansi.org/tools/index.html ):
868 ```
869     cat /dev/zero | wcs > /dev/mapper/to_be_wiped
870 ```
871   Or use plain "dd", which gives you the progress when sent a SIGUSR1, see
872   the dd man page. The GNU "dd" command supports the "status=progress"
873   operand that gives you the progress without having to send it any signal.
874
875   Remove the mapping at the end and you are done.
876
877
878   * **2.20 How do I wipe only the LUKS header?**
879  
880   This does _not_ describe an emergency wipe procedure, see Item 5.4 for
881   that.  This procedure here is intended to be used when the data should
882   stay intact, e.g.  when you change your LUKS container to use a detached
883   header and want to remove the old one.  Please only do this if you have
884   a current backup.
885
886   LUKS1:  
887   01) Determine header size in 512 Byte sectors with luksDump:
888 ```
889      cryptsetup luksDump <device with LUKS container>
890
891 ->   ...
892      Payload offset: <number> [of 512 byte sectors]
893      ...
894 ```
895   02) Take the result number, multiply by 512 zeros and write to 
896       the start of the device, e.g. using one of the following alternatives:
897 ```
898      dd bs=512 count=<number> if=/dev/zero of=<device>
899 ```        
900 ```  
901      head -c <number * 512> /dev/zero > /dev/<device>
902 ```
903
904   LUKS2:  
905   (warning, untested!  Remember that backup?) This assumes the
906   LUKS2 container uses the defaults, in particular there is only one data
907   segment.  
908   01) Determine the data-segment offset using luksDump, same
909       as above for LUKS1:
910 ```
911      cryptsetup luksDump <device with LUKS container>
912 ->   ...  
913      Data segments:
914         0: crypt
915            offset: <number> [bytes]
916      ...
917 ```
918   02) Overwrite the stated number of bytes from the start of the device.
919       Just to give yet another way to get a defined number of zeros:
920 ```
921      head -c <number> /dev/zero > /dev/<device>
922 ```
923
924 # 3. Common Problems
925
926
927   * **3.1 My dm-crypt/LUKS mapping does not work! What general steps are there to investigate the problem?**
928
929   If you get a specific error message, investigate what it claims first. 
930   If not, you may want to check the following things.
931
932   - Check that "/dev", including "/dev/mapper/control" is there.  If it is
933   missing, you may have a problem with the "/dev" tree itself or you may
934   have broken udev rules.
935
936   - Check that you have the device mapper and the crypt target in your
937   kernel.  The output of "dmsetup targets" should list a "crypt" target. 
938   If it is not there or the command fails, add device mapper and
939   crypt-target to the kernel.
940
941   - Check that the hash-functions and ciphers you want to use are in the
942   kernel.  The output of "cat /proc/crypto" needs to list them.
943
944
945   * **3.2 My dm-crypt mapping suddenly stopped when upgrading cryptsetup.**
946
947   The default cipher, hash or mode may have changed (the mode changed from
948   1.0.x to 1.1.x).  See under "Issues With Specific Versions of
949   cryptsetup".
950
951
952   * **3.3 When I call cryptsetup from cron/CGI, I get errors about unknown features?**
953
954   If you get errors about unknown parameters or the like that are not
955   present when cryptsetup is called from the shell, make sure you have no
956   older version of cryptsetup on your system that then gets called by
957   cron/CGI.  For example some distributions install cryptsetup into
958   /usr/sbin, while a manual install could go to /usr/local/sbin.  As a
959   debugging aid, call "cryptsetup --version" from cron/CGI or the
960   non-shell mechanism to be sure the right version gets called.
961
962
963   * **3.4 Unlocking a LUKS device takes very long. Why?**
964
965   The unlock time for a key-slot (see Section 5 for an explanation what
966   iteration does) is calculated when setting a passphrase.  By default it
967   is 1 second (2 seconds for LUKS2).  If you set a passphrase on a fast
968   machine and then unlock it on a slow machine, the unlocking time can be
969   much longer.  Also take into account that up to 8 key-slots (LUKS2: up
970   to 32 key-slots) have to be tried in order to find the right one.
971
972   If this is the problem, you can add another key-slot using the slow
973   machine with the same passphrase and then remove the old key-slot.  The
974   new key-slot will have the unlock time adjusted to the slow machine.
975   Use luksKeyAdd and then luksKillSlot or luksRemoveKey.  You can also use
976   the -i option to reduce iteration time (and security level) when setting 
977   a passphrase.  Default is 1000 (1 sec) for LUKS1 and 2000 (2sec) for
978   LUKS2.
979
980   However, this operation will not change volume key iteration count ("MK
981   iterations" for LUKS1, "Iterations" under "Digests" for LUKS2).  In
982   order to change that, you will have to backup the data in the LUKS
983   container (i.e.  your encrypted data), luksFormat on the slow machine
984   and restore the data.  Note that MK iterations are not very security
985   relevant.
986
987
988   * **3.5 "blkid" sees a LUKS UUID and an ext2/swap UUID on the same device. What is wrong?**
989
990   Some old versions of cryptsetup have a bug where the header does not get
991   completely wiped during LUKS format and an older ext2/swap signature
992   remains on the device.  This confuses blkid.
993
994   Fix: Wipe the unused header areas by doing a backup and restore of
995   the header with cryptsetup 1.1.x or later:
996 ```
997     cryptsetup luksHeaderBackup --header-backup-file <file> <device>
998     cryptsetup luksHeaderRestore --header-backup-file <file> <device>
999 ```
1000
1001   * **3.6 I see a data corruption with the Intel QAT kernel driver; why?**
1002
1003   Intel QAT crypto API drivers have severe bugs that are not fixed for years.
1004
1005   If you see data corruption, please disable the QAT in the BIOS or avoid loading
1006   kernel Intel QAT drivers (switch to software crypto implementation or AES-NI).
1007
1008   For more info, see posts in dm-devel list https://lore.kernel.org/dm-devel/?q=intel+qat
1009
1010
1011 # 4. Troubleshooting
1012
1013
1014   * **4.1 I get the error "LUKS keyslot x is invalid." What does that mean?**
1015
1016   For LUKS1, this means that the given keyslot has an offset that points
1017   outside the valid keyslot area.  Typically, the reason is a corrupted
1018   LUKS1 header because something was written to the start of the device
1019   the LUKS1 container is on.  For LUKS2, I do not know when this error can
1020   happen, but I expect it will be something similar.  Refer to Section
1021   "Backup and Data Recovery" and ask on the mailing list if you have
1022   trouble diagnosing and (if still possible) repairing this.
1023
1024
1025   * **4.2 I cannot unlock my LUKS container! What could be the problem?**
1026
1027   First, make sure you have a correct passphrase.  Then make sure you have
1028   the correct key-map and correct keyboard.  And then make sure you have
1029   the correct character set and encoding, see also "PASSPHRASE CHARACTER
1030   SET" under Section 1.2.
1031
1032   If you are sure you are entering the passphrase right, there is the
1033   possibility that the respective key-slot has been damaged.  There is no
1034   way to recover a damaged key-slot, except from a header backup (see
1035   Section 6).  For security reasons, there is also no checksum in the
1036   key-slots that could tell you whether a key-slot has been damaged.  The
1037   only checksum present allows recognition of a correct passphrase, but
1038   that only works with that correct passphrase and a respective key-slot
1039   that is intact.
1040
1041   In order to find out whether a key-slot is damaged one has to look for
1042   "non-random looking" data in it.  There is a tool that automates this
1043   for LUKS1 in the cryptsetup distribution from version 1.6.0 onwards.  It
1044   is located in misc/keyslot_checker/.  Instructions how to use and how to
1045   interpret results are in the README file.  Note that this tool requires
1046   a libcryptsetup from cryptsetup 1.6.0 or later (which means
1047   libcryptsetup.so.4.5.0 or later).  If the tool complains about missing
1048   functions in libcryptsetup, you likely have an earlier version from your
1049   distribution still installed.  You can either point the symbolic link(s)
1050   from libcryptsetup.so.4 to the new version manually, or you can
1051   uninstall the distribution version of cryptsetup and re-install that
1052   from cryptsetup >= 1.6.0 again to fix this.
1053
1054
1055   * **4.3 Can a bad RAM module cause problems?**
1056
1057   LUKS and dm-crypt can give the RAM quite a workout, especially when
1058   combined with software RAID.  In particular the combination RAID5 +
1059   LUKS1 + XFS seems to uncover RAM problems that do not cause obvious
1060   problems otherwise.  Symptoms vary, but often the problem manifests
1061   itself when copying large amounts of data, typically several times
1062   larger than your main memory.
1063
1064   Note: One thing you should always do on large data copying or movements
1065   is to run a verify, for example with the "-d" option of "tar" or by
1066   doing a set of MD5 checksums on the source or target with
1067 ```
1068     find . -type f -exec md5sum \{\} \; > checksum-file
1069 ```
1070   and then a "md5sum -c checksum-file" on the other side.  If you get
1071   mismatches here, RAM is the primary suspect.  A lesser suspect is an
1072   overclocked CPU.  I have found countless hardware problems in verify
1073   runs after copying data or making backups.  Bit errors are much more
1074   common than most people think.
1075
1076   Some RAM issues are even worse and corrupt structures in one of the
1077   layers.  This typically results in lockups, CPU state dumps in the
1078   system logs, kernel panic or other things.  It is quite possible to have
1079   a problem with an encrypted device, but not with an otherwise the same
1080   unencrypted device.  The reason for that is that encryption has an error
1081   amplification property: If you flip one bit in an encrypted data block,
1082   the decrypted version has half of its bits flipped.  This is actually an
1083   important security property for modern ciphers.  With the usual modes in
1084   cryptsetup (CBC, ESSIV, XTS), you can get a completely changed 512 byte
1085   block for a bit error.  A corrupt block causes a lot more havoc than the
1086   occasionally flipped single bit and can result in various obscure
1087   errors.
1088
1089   Note that a verify run on copying between encrypted or unencrypted
1090   devices will reliably detect corruption, even when the copying itself
1091   did not report any problems.  If you find defect RAM, assume all backups
1092   and copied data to be suspect, unless you did a verify.
1093
1094
1095   * **4.4 How do I test RAM?**
1096
1097   First you should know that overclocking often makes memory problems
1098   worse.  So if you overclock (which I strongly recommend against in a
1099   system holding data that has any worth), run the tests with the
1100   overclocking active.
1101
1102   There are two good options.  One is Memtest86+ and the other is
1103   "memtester" by Charles Cazabon.  Memtest86+ requires a reboot and then
1104   takes over the machine, while memtester runs from a root-shell.  Both
1105   use different testing methods and I have found problems fast with either
1106   one that the other needed long to find.  I recommend running the
1107   following procedure until the first error is found:
1108
1109   - Run Memtest86+ for one cycle
1110
1111   - Run memtester for one cycle (shut down as many other applications
1112     as possible and use the largest memory area you can get)
1113
1114   - Run Memtest86+ for 24h or more
1115
1116   - Run memtester for 24h or more
1117
1118   If all that does not produce error messages, your RAM may be sound,
1119   but I have had one weak bit in the past that Memtest86+ needed around 
1120   60 hours to find.  If you can reproduce the original problem reliably, 
1121   a good additional test may be to remove half of the RAM (if you have 
1122   more than one module) and try whether the problem is still there and if
1123   so, try with the other half.  If you just have one module, get a
1124   different one and try with that.  If you do overclocking, reduce the
1125   settings to the most conservative ones available and try with that.
1126
1127
1128   * **4.5 Is there a risk using debugging tools like strace?**
1129
1130   There most definitely is. A dump from strace and friends can contain
1131   all data entered, including the full passphrase.  Example with strace
1132   and passphrase "test":
1133 ```
1134     > strace cryptsetup luksOpen /dev/sda10 c1
1135     ...
1136     read(6, "test\n", 512)                  = 5
1137     ...
1138 ```
1139   Depending on different factors and the tool used, the passphrase may
1140   also be encoded and not plainly visible.  Hence it is never a good idea
1141   to give such a trace from a live container to anybody.  Recreate the
1142   problem with a test container or set a temporary passphrase like "test"
1143   and use that for the trace generation.  Item 2.6 explains how to create
1144   a loop-file backed LUKS container that may come in handy for this
1145   purpose.
1146
1147   See also Item 6.10 for another set of data you should not give to
1148   others.
1149
1150
1151 # 5. Security Aspects
1152
1153
1154   * **5.1 How long is a secure passphrase?**
1155
1156   This is just the short answer.  For more info and explanation of some of
1157   the terms used in this item, read the rest of Section 5.  The actual
1158   recommendation is at the end of this item.
1159
1160   First, passphrase length is not really the right measure, passphrase
1161   entropy is.  If your passphrase is 200 times the letter "a", it is long
1162   but has very low entropy and is pretty insecure.
1163
1164   For example, a random lowercase letter (a-z) gives you 4.7 bit of
1165   entropy, one element of a-z0-9 gives you 5.2 bits of entropy, an element
1166   of a-zA-Z0-9 gives you 5.9 bits and a-zA-Z0-9!@#$%\^&:-+ gives you 6.2
1167   bits.  On the other hand, a random English word only gives you 0.6...1.3
1168   bits of entropy per character.  Using sentences that make sense gives
1169   lower entropy, series of random words gives higher entropy.  Do not use
1170   sentences that can be tied to you or found on your computer.  This type
1171   of attack is done routinely today.
1172
1173   That said, it does not matter too much what scheme you use, but it does
1174   matter how much entropy your passphrase contains, because an attacker
1175   has to try on average
1176 ```
1177     1/2 * 2^(bits of entropy in passphrase)
1178 ```
1179   different passphrases to guess correctly.
1180
1181   Historically, estimations tended to use computing time estimates, but
1182   more modern approaches try to estimate cost of guessing a passphrase.
1183
1184   As an example, I will try to get an estimate from the numbers in
1185   https://gist.github.com/epixoip/a83d38f412b4737e99bbef804a270c40 This
1186   thing costs 23kUSD and does 68Ghashes/sec for SHA1.  This is in 2017.
1187  
1188   Incidentally, my older calculation for a machine around 1000 times
1189   slower was off by a factor of about 1000, but in the right direction,
1190   i.e.  I estimated the attack to be too easy.  Nobody noticed ;-) On the
1191   plus side, the tables are now (2017) pretty much accurate.
1192
1193   More references can be found at the end of this document.  Note that
1194   these are estimates from the defender side, so assuming something is
1195   easier than it actually is fine.  An attacker may still have
1196   significantly higher cost than estimated here.
1197
1198   LUKS1 used SHA1 (since version 1.7.0 it uses SHA256) for hashing per
1199   default.  We will leave aside the check whether a try actually decrypts 
1200   a key-slot.  I will assume a useful lifetime of the hardware of 2 years. 
1201   (This is on the low side.) Disregarding downtime, the machine can then
1202   break
1203 ```
1204      N = 68*10^9 * 3600 * 24 * 365 * 2 ~ 4*10^18
1205 ```
1206   passphrases for EUR/USD 23k.  That is one 62 bit passphrase hashed once
1207   with SHA1 for EUR/USD 23k.  This can be parallelized, it can be done
1208   faster than 2 years with several of these machines.
1209
1210   For LUKS2, things look a bit better, as the advantage of using graphics
1211   cards is massively reduced.  Using the recommendations below should
1212   hence be fine for LUKS2 as well and give a better security margin.
1213
1214   For plain dm-crypt (no hash iteration) this is it.  This gives (with
1215   SHA1, plain dm-crypt default is ripemd160 which seems to be slightly
1216   slower than SHA1):
1217 ```
1218     Passphrase entropy  Cost to break
1219     60 bit              EUR/USD     6k
1220     65 bit              EUR/USD   200K
1221     70 bit              EUR/USD     6M
1222     75 bit              EUR/USD   200M
1223     80 bit              EUR/USD     6B
1224     85 bit              EUR/USD   200B
1225     ...                      ...
1226 ```
1227
1228   For LUKS1, you have to take into account hash iteration in PBKDF2. 
1229   For a current CPU, there are about 100k iterations (as can be queried
1230   with ''cryptsetup luksDump''. 
1231
1232   The table above then becomes:
1233 ```
1234     Passphrase entropy  Cost to break
1235     50 bit              EUR/USD   600k
1236     55 bit              EUR/USD    20M
1237     60 bit              EUR/USD   600M
1238     65 bit              EUR/USD    20B
1239     70 bit              EUR/USD   600B
1240     75 bit              EUR/USD    20T
1241     ...                      ...
1242 ```
1243
1244   Recommendation:
1245
1246   To get reasonable security for the  next 10 years, it is a good idea
1247   to overestimate by a factor of at least 1000.
1248
1249   Then there is the question of how much the attacker is willing to spend. 
1250   That is up to your own security evaluation.  For general use, I will
1251   assume the attacker is willing to spend up to 1 million EUR/USD.  Then
1252   we get the following recommendations:
1253
1254   Plain dm-crypt: Use > 80 bit. That is e.g. 17 random chars from a-z
1255   or a random English sentence of > 135 characters length.
1256
1257   LUKS1 and LUKS2: Use > 65 bit. That is e.g. 14 random chars from a-z 
1258   or a random English sentence of > 108 characters length.
1259
1260   If paranoid, add at least 20 bit. That is roughly four additional
1261   characters for random passphrases and roughly 32 characters for a
1262   random English sentence. 
1263
1264
1265   * **5.2 Is LUKS insecure? Everybody can see I have encrypted data!**
1266
1267   In practice it does not really matter.  In most civilized countries you
1268   can just refuse to hand over the keys, no harm done.  In some countries
1269   they can force you to hand over the keys if they suspect encryption. 
1270   The suspicion is enough, they do not have to prove anything.  This is
1271   for practical reasons, as even the presence of a header (like the LUKS
1272   header) is not enough to prove that you have any keys.  It might have
1273   been an experiment, for example.  Or it was used as encrypted swap with
1274   a key from /dev/random.  So they make you prove you do not have
1275   encrypted data.  Of course, if true, that is impossible and hence the
1276   whole idea is not compatible with fair laws.  Note that in this context,
1277   countries like the US or the UK are not civilized and do not have fair
1278   laws.
1279
1280   As a side-note, standards for biometrics (fingerprint, retina, 
1281   vein-pattern, etc.) are often different and much lower. If you put
1282   your LUKS passphrase into a device that can be unlocked using biometrics,
1283   they may force a biometric sample in many countries where they could not
1284   force you to give them a passphrase you solely have in your memory and
1285   can claim to have forgotten if needed (it happens). If you need protection
1286   on this level, make sure you know what the respective legal situation is,
1287   also while traveling, and make sure you decide beforehand what you
1288   will do if push comes to shove as they will definitely put you under
1289   as much pressure as they can legally apply. 
1290
1291   This means that if you have a large set of random-looking data, they can
1292   already lock you up.  Hidden containers (encryption hidden within
1293   encryption), as possible with Truecrypt, do not help either.  They will
1294   just assume the hidden container is there and unless you hand over the
1295   key, you will stay locked up.  Don't have a hidden container?  Tough
1296   luck.  Anybody could claim that.
1297
1298   Still, if you are concerned about the LUKS header, use plain dm-crypt
1299   with a good passphrase.  See also Section 2, "What is the difference
1300   between "plain" and LUKS format?"
1301
1302
1303   * **5.3 Should I initialize (overwrite) a new LUKS/dm-crypt partition?**
1304
1305   If you just create a filesystem on it, most of the old data will still
1306   be there.  If the old data is sensitive, you should overwrite it before
1307   encrypting.  In any case, not initializing will leave the old data there
1308   until the specific sector gets written.  That may enable an attacker to
1309   determine how much and where on the partition data was written.  If you
1310   think this is a risk, you can prevent this by overwriting the encrypted
1311   device (here assumed to be named "e1") with zeros like this:
1312 ```
1313     dd_rescue -w /dev/zero /dev/mapper/e1
1314 ```
1315   or alternatively with one of the following more standard commands:
1316 ```
1317     cat /dev/zero > /dev/mapper/e1
1318     dd if=/dev/zero of=/dev/mapper/e1
1319 ```
1320
1321
1322   * **5.4 How do I securely erase a LUKS container?**
1323
1324   For LUKS, if you are in a desperate hurry, overwrite the LUKS header and
1325   key-slot area.  For LUKS1 and LUKS2, just be generous and overwrite the
1326   first 100MB.  A single overwrite with zeros should be enough.  If you
1327   anticipate being in a desperate hurry, prepare the command beforehand. 
1328   Example with /dev/sde1 as the LUKS partition and default parameters:
1329 ```
1330     head -c 100000000 /dev/zero > /dev/sde1; sync
1331 ```
1332   A LUKS header backup or full backup will still grant access to most or
1333   all data, so make sure that an attacker does not have access to backups
1334   or destroy them as well.
1335
1336   Also note that SSDs and also some HDDs (SMR and hybrid HDDs, for
1337   example) may not actually overwrite the header and only do that an
1338   unspecified and possibly very long time later.  The only way to be sure
1339   there is physical destruction.  If the situation permits, do both
1340   overwrite and physical destruction.
1341
1342   If you have time, overwrite the whole drive with a single pass of random
1343   data.  This is enough for most HDDs.  For SSDs or FLASH (USB sticks) or
1344   SMR or hybrid drives, you may want to overwrite the whole drive several
1345   times to be sure data is not retained.  This is possibly still insecure
1346   as the respective technologies are not fully understood in this regard. 
1347   Still, due to the anti-forensic properties of the LUKS key-slots, a
1348   single overwrite could be enough.  If in doubt, use physical destruction
1349   in addition.  Here is a link to some current research results on erasing
1350   SSDs and FLASH drives:
1351   https://www.usenix.org/events/fast11/tech/full_papers/Wei.pdf
1352
1353   Keep in mind to also erase all backups.
1354
1355   Example for a random-overwrite erase of partition sde1 done with
1356   dd_rescue:
1357 ```
1358     dd_rescue -w /dev/urandom /dev/sde1
1359 ```
1360
1361
1362   * **5.5 How do I securely erase a backup of a LUKS partition or header?**
1363
1364   That depends on the medium it is stored on.  For HDD and SSD, use
1365   overwrite with random data.  For an SSD, FLASH drive (USB stick) hybrid
1366   HDD or SMR HDD, you may want to overwrite the complete drive several
1367   times and use physical destruction in addition, see last item.  For
1368   re-writable CD/DVD, a single overwrite should be enough, due to the
1369   anti-forensic properties of the LUKS keyslots.  For write-once media,
1370   use physical destruction.  For low security requirements, just cut the
1371   CD/DVD into several parts.  For high security needs, shred or burn the
1372   medium.
1373
1374   If your backup is on magnetic tape, I advise physical destruction by
1375   shredding or burning, after (!) overwriting.  The problem with magnetic
1376   tape is that it has a higher dynamic range than HDDs and older data may
1377   well be recoverable after overwrites.  Also write-head alignment issues
1378   can lead to data not actually being deleted during overwrites.
1379
1380   The best option is to actually encrypt the backup, for example with
1381   PGP/GnuPG and then just destroy all copies of the encryption key if
1382   needed.  Best keep them on paper, as that has excellent durability and
1383   secure destruction is easy, for example by burning and then crushing the
1384   ashes to a fine powder.  A blender and water also works nicely.
1385
1386
1387   * **5.6 What about backup? Does it compromise security?**
1388
1389   That depends. See item 6.7.
1390
1391
1392   * **5.7 Why is all my data permanently gone if I overwrite the LUKS header?**
1393
1394   Overwriting the LUKS header in part or in full is the most common reason
1395   why access to LUKS containers is lost permanently.  Overwriting can be
1396   done in a number of fashions, like creating a new filesystem on the raw
1397   LUKS partition, making the raw partition part of a RAID array and just
1398   writing to the raw partition.
1399
1400   The LUKS1 header contains a 256 bit "salt" per key-slot and without that
1401   no decryption is possible.  While the salts are not secret, they are
1402   key-grade material and cannot be reconstructed.  This is a
1403   cryptographically strong "cannot".  From observations on the cryptsetup
1404   mailing-list, people typically go though the usual stages of grief
1405   (Denial, Anger, Bargaining, Depression, Acceptance) when this happens to
1406   them.  Observed times vary between 1 day and 2 weeks to complete the
1407   cycle.  Seeking help on the mailing-list is fine.  Even if we usually
1408   cannot help with getting back your data, most people found the feedback
1409   comforting.
1410
1411   If your header does not contain an intact key-slot salt, best go
1412   directly to the last stage ("Acceptance") and think about what to do
1413   now.  There is one exception that I know of: If your LUKS1 container is
1414   still open, then it may be possible to extract the volume key from the
1415   running system.  See Item "How do I recover the volume key from a mapped
1416   LUKS1 container?" in Section "Backup and Data Recovery".
1417
1418   For LUKS2, things are both better and worse.  First, the salts are in a
1419   less vulnerable position now.  But, on the other hand, the keys of a
1420   mapped (open) container are now stored in the kernel key-store, and
1421   while there probably is some way to get them out of there, I am not sure
1422   how much effort that needs.
1423
1424
1425   * **5.8 What is a "salt"?**
1426
1427   A salt is a random key-grade value added to the passphrase before it is
1428   processed.  It is not kept secret.  The reason for using salts is as
1429   follows: If an attacker wants to crack the password for a single LUKS
1430   container, then every possible passphrase has to be tried.  Typically an
1431   attacker will not try every binary value, but will try words and
1432   sentences from a dictionary.
1433
1434   If an attacker wants to attack several LUKS containers with the same
1435   dictionary, then a different approach makes sense: Compute the resulting
1436   slot-key for each dictionary element and store it on disk.  Then the
1437   test for each entry is just the slow unlocking with the slot key (say
1438   0.00001 sec) instead of calculating the slot-key first (1 sec).  For a
1439   single attack, this does not help.  But if you have more than one
1440   container to attack, this helps tremendously, also because you can
1441   prepare your table before you even have the container to attack!  The
1442   calculation is also very simple to parallelize.  You could, for example,
1443   use the night-time unused CPU power of your desktop PCs for this.
1444
1445   This is where the salt comes in.  If the salt is combined with the
1446   passphrase (in the simplest form, just appended to it), you suddenly
1447   need a separate table for each salt value.  With a reasonably-sized salt
1448   value (256 bit, e.g.) this is quite infeasible.
1449
1450
1451   * **5.9 Is LUKS secure with a low-entropy (bad) passphrase?**
1452
1453   Short answer: yes. Do not use a low-entropy passphrase.
1454
1455   Note: For LUKS2, protection for bad passphrases is a bit better
1456   due to the use of Argon2, but that is only a gradual improvement.
1457
1458   Longer answer:  
1459   This needs a bit of theory.  The quality of your passphrase is directly
1460   related to its entropy (information theoretic, not thermodynamic).  The
1461   entropy says how many bits of "uncertainty" or "randomness" are in you
1462   passphrase.  In other words, that is how difficult guessing the
1463   passphrase is.
1464
1465   Example: A random English sentence has about 1 bit of entropy per
1466   character.  A random lowercase (or uppercase) character has about 4.7
1467   bit of entropy.
1468
1469   Now, if n is the number of bits of entropy in your passphrase and t
1470   is the time it takes to process a passphrase in order to open the
1471   LUKS container, then an attacker has to spend at maximum
1472 ```
1473     attack_time_max = 2^n * t
1474 ```
1475   time for a successful attack and on average half that.  There is no way
1476   getting around that relationship.  However, there is one thing that does
1477   help, namely increasing t, the time it takes to use a passphrase, see
1478   next FAQ item.
1479
1480   Still, if you want good security, a high-entropy passphrase is the only
1481   option.  For example, a low-entropy passphrase can never be considered
1482   secure against a TLA-level (Three Letter Agency level, i.e. 
1483   government-level) attacker, no matter what tricks are used in the
1484   key-derivation function.  Use at least 64 bits for secret stuff.  That
1485   is 64 characters of English text (but only if randomly chosen) or a
1486   combination of 12 truly random letters and digits.
1487
1488   For passphrase generation, do not use lines from very well-known texts
1489   (religious texts, Harry Potter, etc.) as they are too easy to guess.
1490   For example, the total Harry Potter has about 1'500'000 words (my
1491   estimation).  Trying every 64 character sequence starting and ending at
1492   a word boundary would take only something like 20 days on a single CPU
1493   and is entirely feasible.  To put that into perspective, using a number
1494   of Amazon EC2 High-CPU Extra Large instances (each gives about 8 real
1495   cores), this test costs currently about 50USD/EUR, but can be made to
1496   run arbitrarily fast.
1497
1498   On the other hand, choosing 1.5 lines from, say, the Wheel of Time, is
1499   in itself not more secure, but the book selection adds quite a bit of
1500   entropy.  (Now that I have mentioned it here, don't use tWoT either!) If
1501   you add 2 or 3 typos and switch some words around, then this is good
1502   passphrase material.
1503
1504
1505   * **5.10 What is "iteration count" and why is decreasing it a bad idea?**
1506
1507   LUKS1:  
1508   Iteration count is the number of PBKDF2 iterations a passphrase is put
1509   through before it is used to unlock a key-slot.  Iterations are done
1510   with the explicit purpose to increase the time that it takes to unlock a
1511   key-slot.  This provides some protection against use of low-entropy
1512   passphrases.
1513
1514   The idea is that an attacker has to try all possible passphrases.  Even
1515   if the attacker knows the passphrase is low-entropy (see last item), it
1516   is possible to make each individual try take longer.  The way to do this
1517   is to repeatedly hash the passphrase for a certain time.  The attacker
1518   then has to spend the same time (given the same computing power) as the
1519   user per try.  With LUKS1, the default is 1 second of PBKDF2 hashing.
1520
1521   Example 1: Lets assume we have a really bad passphrase (e.g.  a
1522   girlfriends name) with 10 bits of entropy.  With the same CPU, an
1523   attacker would need to spend around 500 seconds on average to break that
1524   passphrase.  Without iteration, it would be more like 0.0001 seconds on
1525   a modern CPU.
1526
1527   Example 2: The user did a bit better and has 32 chars of English text. 
1528   That would be about 32 bits of entropy.  With 1 second iteration, that
1529   means an attacker on the same CPU needs around 136 years.  That is
1530   pretty impressive for such a weak passphrase.  Without the iterations,
1531   it would be more like 50 days on a modern CPU, and possibly far less.
1532
1533   In addition, the attacker can both parallelize and use special hardware
1534   like GPUs or FPGAs to speed up the attack.  The attack can also happen
1535   quite some time after the luksFormat operation and CPUs can have become
1536   faster and cheaper.  For that reason you want a bit of extra security. 
1537   Anyways, in Example 1 your are screwed.  In example 2, not necessarily. 
1538   Even if the attack is faster, it still has a certain cost associated
1539   with it, say 10000 EUR/USD with iteration and 1 EUR/USD without
1540   iteration.  The first can be prohibitively expensive, while the second
1541   is something you try even without solid proof that the decryption will
1542   yield something useful.
1543
1544   The numbers above are mostly made up, but show the idea.  Of course the
1545   best thing is to have a high-entropy passphrase.
1546
1547   Would a 100 sec iteration time be even better?  Yes and no. 
1548   Cryptographically it would be a lot better, namely 100 times better. 
1549   However, usability is a very important factor for security technology
1550   and one that gets overlooked surprisingly often.  For LUKS, if you have
1551   to wait 2 minutes to unlock the LUKS container, most people will not
1552   bother and use less secure storage instead.  It is better to have less
1553   protection against low-entropy passphrases and people actually use LUKS,
1554   than having them do without encryption altogether.
1555
1556   Now, what about decreasing the iteration time?  This is generally a very
1557   bad idea, unless you know and can enforce that the users only use
1558   high-entropy passphrases.  If you decrease the iteration time without
1559   ensuring that, then you put your users at increased risk, and
1560   considering how rarely LUKS containers are unlocked in a typical
1561   work-flow, you do so without a good reason.  Don't do it.  The iteration
1562   time is already low enough that users with low entropy passphrases are
1563   vulnerable.  Lowering it even further increases this danger
1564   significantly.
1565
1566   LUKS2: Pretty much the same reasoning applies. The advantages of using
1567   GPUs or FPGAs in an attack have been significantly reduced, but that 
1568   is the only main difference.
1569
1570
1571   * **5.11 Some people say PBKDF2 is insecure?**
1572
1573   There is some discussion that a hash-function should have a "large
1574   memory" property, i.e.  that it should require a lot of memory to be
1575   computed.  This serves to prevent attacks using special programmable
1576   circuits, like FPGAs, and attacks using graphics cards.  PBKDF2 does not
1577   need a lot of memory and is vulnerable to these attacks.  However, the
1578   publication usually referred in these discussions is not very convincing
1579   in proving that the presented hash really is "large memory" (that may
1580   change, email the FAQ maintainer when it does) and it is of limited
1581   usefulness anyways.  Attackers that use clusters of normal PCs will not
1582   be affected at all by a "large memory" property.  For example the US
1583   Secret Service is known to use the off-hour time of all the office PCs
1584   of the Treasury for password breaking.  The Treasury has about 110'000
1585   employees.  Assuming every one has an office PC, that is significant
1586   computing power, all of it with plenty of memory for computing "large
1587   memory" hashes.  Bot-net operators also have all the memory they want. 
1588   The only protection against a resourceful attacker is a high-entropy
1589   passphrase, see items 5.9 and 5.10.
1590
1591   That said, LUKS2 defaults to Argon2, which has a large-memory property
1592   and massively reduces the advantages of GPUs and FPGAs.
1593
1594
1595   * **5.12 What about iteration count with plain dm-crypt?**
1596
1597   Simple: There is none.  There is also no salting.  If you use plain
1598   dm-crypt, the only way to be secure is to use a high entropy passphrase. 
1599   If in doubt, use LUKS instead.
1600
1601
1602   * **5.13 Is LUKS with default parameters less secure on a slow CPU?**
1603
1604   Unfortunately, yes.  However the only aspect affected is the protection
1605   for low-entropy passphrase or volume-key.  All other security aspects
1606   are independent of CPU speed.
1607
1608   The volume key is less critical, as you really have to work at it to
1609   give it low entropy.  One possibility to mess this up is to supply the
1610   volume key yourself.  If that key is low-entropy, then you get what you
1611   deserve.  The other known possibility to create a LUKS container with a
1612   bad volume key is to use /dev/urandom for key generation in an
1613   entropy-starved situation (e.g.  automatic installation on an embedded
1614   device without network and other entropy sources or installation in a VM
1615   under certain circumstances).
1616
1617   For the passphrase, don't use a low-entropy passphrase.  If your
1618   passphrase is good, then a slow CPU will not matter.  If you insist on a
1619   low-entropy passphrase on a slow CPU, use something like
1620   "--iter-time=10000" or higher and wait a long time on each LUKS unlock
1621   and pray that the attacker does not find out in which way exactly your
1622   passphrase is low entropy.  This also applies to low-entropy passphrases
1623   on fast CPUs.  Technology can do only so much to compensate for problems
1624   in front of the keyboard.
1625
1626   Also note that power-saving modes will make your CPU slower.  This will
1627   reduce iteration count on LUKS container creation.  It will keep unlock
1628   times at the expected values though at this CPU speed.
1629
1630
1631   * **5.14 Why was the default aes-cbc-plain replaced with aes-cbc-essiv?**
1632
1633   Note: This item applies both to plain dm-crypt and to LUKS
1634
1635   The problem is that cbc-plain has a fingerprint vulnerability, where a
1636   specially crafted file placed into the crypto-container can be
1637   recognized from the outside.  The issue here is that for cbc-plain the
1638   initialization vector (IV) is the sector number.  The IV gets XORed to
1639   the first data chunk of the sector to be encrypted.  If you make sure
1640   that the first data block to be stored in a sector contains the sector
1641   number as well, the first data block to be encrypted is all zeros and
1642   always encrypted to the same ciphertext.  This also works if the first
1643   data chunk just has a constant XOR with the sector number.  By having
1644   several shifted patterns you can take care of the case of a
1645   non-power-of-two start sector number of the file.
1646
1647   This mechanism allows you to create a pattern of sectors that have the
1648   same first ciphertext block and signal one bit per sector to the
1649   outside, allowing you to e.g.  mark media files that way for recognition
1650   without decryption.  For large files this is a practical attack.  For
1651   small ones, you do not have enough blocks to signal and take care of
1652   different file starting offsets.
1653
1654   In order to prevent this attack, the default was changed to cbc-essiv. 
1655   ESSIV uses a keyed hash of the sector number, with the encryption key as
1656   key.  This makes the IV unpredictable without knowing the encryption key
1657   and the watermarking attack fails.
1658
1659
1660   * **5.15 Are there any problems with "plain" IV? What is "plain64"?**
1661
1662   First, "plain" and "plain64" are both not secure to use with CBC, see
1663   previous FAQ item.
1664
1665   However there are modes, like XTS, that are secure with "plain" IV.  The
1666   next limit is that "plain" is 64 bit, with the upper 32 bit set to zero. 
1667   This means that on volumes larger than 2TiB, the IV repeats, creating a
1668   vulnerability that potentially leaks some data.  To avoid this, use
1669   "plain64", which uses the full sector number up to 64 bit.  Note that
1670   "plain64" requires a kernel 2.6.33 or more recent.  Also note that
1671   "plain64" is backwards compatible for volume sizes of maximum size 2TiB,
1672   but not for those > 2TiB.  Finally, "plain64" does not cause any
1673   performance penalty compared to "plain".
1674
1675
1676   * **5.16 What about XTS mode?**
1677
1678   XTS mode is potentially even more secure than cbc-essiv (but only if
1679   cbc-essiv is insecure in your scenario).  It is a NIST standard and
1680   used, e.g.  in Truecrypt.  From version 1.6.0 of cryptsetup onwards,
1681   aes-xts-plain64 is the default for LUKS.  If you want to use it with a
1682   cryptsetup before version 1.6.0 or with plain dm-crypt, you have to
1683   specify it manually as "aes-xts-plain", i.e.
1684 ```
1685     cryptsetup -c aes-xts-plain luksFormat <device>
1686 ```
1687   For volumes >2TiB and kernels >= 2.6.33 use "plain64" (see FAQ item
1688   on "plain" and "plain64"):
1689 ```
1690     cryptsetup -c aes-xts-plain64 luksFormat <device>
1691 ```
1692   There is a potential security issue with XTS mode and large blocks. 
1693   LUKS and dm-crypt always use 512B blocks and the issue does not apply.
1694
1695
1696   * **5.17 Is LUKS FIPS-140-2 certified?**
1697
1698   No.  But that is more a problem of FIPS-140-2 than of LUKS.  From a
1699   technical point-of-view, LUKS with the right parameters would be
1700   FIPS-140-2 compliant, but in order to make it certified, somebody has to
1701   pay real money for that.  And then, whenever cryptsetup is changed or
1702   extended, the certification lapses and has to be obtained again.
1703
1704   From the aspect of actual security, LUKS with default parameters should
1705   be as good as most things that are FIPS-140-2 certified, although you
1706   may want to make sure to use /dev/random (by specifying --use-random on
1707   luksFormat) as randomness source for the volume key to avoid being
1708   potentially insecure in an entropy-starved situation.
1709
1710
1711   * **5.18 What about Plausible Deniability?**
1712
1713   First let me attempt a definition for the case of encrypted filesystems:
1714   Plausible deniability is when you store data inside an encrypted
1715   container and it is not possible to prove it is there without having a
1716   special passphrase.  And at the same time it must be "plausible" that
1717   there actually is no hidden data there.
1718
1719   As a simple entropy-analysis will show that here may be data there, the
1720   second part is what makes it tricky.
1721
1722   There seem to  be a lot of misunderstandings about this idea, so let me
1723   make it clear that this refers to the situation where the attackers can
1724   prove that there is data that either may be random or may be part of a
1725   plausible-deniability scheme, they just cannot prove which one it is. 
1726   Hence a plausible-deniability scheme must hold up when the attackers
1727   know there is something potentially fishy.  If you just hide data and
1728   rely on it not being found, that is just simple deniability, not
1729   "plausible" deniability and I am not talking about that in the
1730   following.  Simple deniability against a low-competence attacker may be
1731   as simple as renaming a file or putting data into an unused part of a
1732   disk.  Simple deniability against a high-skill attacker with time to
1733   invest is usually pointless unless you go for advanced steganographic
1734   techniques, which have their own drawbacks, such as low data capacity.
1735
1736   Now, the idea of plausible deniability is compelling and on a first
1737   glance it seems possible to do it.  And from a cryptographic point of
1738   view, it actually is possible.
1739
1740   So, does the idea work in practice?  No, unfortunately.  The reasoning
1741   used by its proponents is fundamentally flawed in several ways and the
1742   cryptographic properties fail fatally when colliding with the real
1743   world.
1744
1745   First, why should "I do not have a hidden partition" be any more
1746   plausible than "I forgot my crypto key" or "I wiped that partition with
1747   random data, nothing in there"?  I do not see any reason.
1748
1749   Second, there are two types of situations: Either they cannot force you
1750   to give them the key (then you simply do not) or they can.  In the
1751   second case, they can always do bad things to you, because they cannot
1752   prove that you have the key in the first place!  This means they do not
1753   have to prove you have the key, or that this random looking data on your
1754   disk is actually encrypted data.  So the situation will allow them to
1755   waterboard/lock-up/deport you anyways, regardless of how "plausible"
1756   your deniability is.  Do not have a hidden partition you could show to
1757   them, but there are indications you may?  Too bad for you. 
1758   Unfortunately "plausible deniability" also means you cannot prove there
1759   is no hidden data.
1760
1761   Third, hidden partitions are not that hidden.  There are basically just
1762   two possibilities: a) Make a large crypto container, but put a smaller
1763   filesystem in there and put the hidden partition into the free space. 
1764   Unfortunately this is glaringly obvious and can be detected in an
1765   automated fashion.  This means that the initial suspicion to put you
1766   under duress in order to make you reveal your hidden data is given.  b)
1767   Make a filesystem that spans the whole encrypted partition, and put the
1768   hidden partition into space not currently used by that filesystem. 
1769   Unfortunately that is also glaringly obvious, as you then cannot write
1770   to the filesystem without a high risk of destroying data in the hidden
1771   container.  Have not written anything to the encrypted filesystem in a
1772   while?  Too bad, they have the suspicion they need to do unpleasant
1773   things to you.
1774
1775   To be fair, if you prepare option b) carefully and directly before going
1776   into danger, it may work.  But then, the mere presence of encrypted data
1777   may already be enough to get you into trouble in those places were they
1778   can demand encryption keys.
1779
1780   Here is an additional reference for some problems with plausible
1781   deniability:
1782   https://www.schneier.com/academic/paperfiles/paper-truecrypt-dfs.pdf
1783   I strongly suggest you read it.
1784
1785   So, no, I will not provide any instructions on how to do it with plain
1786   dm-crypt or LUKS.  If you insist on shooting yourself in the foot, you
1787   can figure out how to do it yourself.
1788
1789
1790  * **5.19 What about SSDs, Flash, Hybrid and SMR Drives?**
1791
1792   The problem is that you cannot reliably erase parts of these devices,
1793   mainly due to wear-leveling and possibly defect management and delayed
1794   writes to the main data area.
1795
1796   For example for SSDs, when overwriting a sector, what the device does is
1797   to move an internal sector (may be 128kB or even larger) to some pool of
1798   discarded, not-yet erased unused sectors, take a fresh empty sector from
1799   the empty-sector pool and copy the old sector over with the changes to
1800   the small part you wrote.  This is done in some fashion so that larger
1801   writes do not cause a lot of small internal updates.
1802
1803   The thing is that the mappings between outside-addressable sectors and
1804   inside sectors is arbitrary (and the vendors are not talking).  Also the
1805   discarded sectors are not necessarily erased immediately.  They may
1806   linger a long time.
1807
1808   For plain dm-crypt, the consequences are that older encrypted data may
1809   be lying around in some internal pools of the device.  Thus may or may
1810   not be a problem and depends on the application.  Remember the same can
1811   happen with a filesystem if consecutive writes to the same area of a
1812   file can go to different sectors.
1813
1814   However, for LUKS, the worst case is that key-slots and LUKS header may
1815   end up in these internal pools.  This means that password management
1816   functionality is compromised (the old passwords may still be around,
1817   potentially for a very long time) and that fast erase by overwriting the
1818   header and key-slot area is insecure.
1819
1820   Also keep in mind that the discarded/used pool may be large.  For
1821   example, a 240GB SSD has about 16GB of spare area in the chips that it
1822   is free to do with as it likes.  You would need to make each individual
1823   key-slot larger than that to allow reliable overwriting.  And that
1824   assumes the disk thinks all other space is in use.  Reading the internal
1825   pools using forensic tools is not that hard, but may involve some
1826   soldering.
1827
1828   What to do?
1829
1830   If you trust the device vendor (you probably should not...) you can try
1831   an ATA "secure erase" command.  That is not present in USB keys though
1832   and may or may not be secure for a hybrid drive.
1833
1834   If you can do without password management and are fine with doing
1835   physical destruction for permanently deleting data (always after one or
1836   several full overwrites!), you can use plain dm-crypt.
1837
1838   If you want or need all the original LUKS security features to work, you
1839   can use a detached LUKS header and put that on a conventional, magnetic
1840   disk.  That leaves potentially old encrypted data in the pools on the
1841   main disk, but otherwise you get LUKS with the same security as on a
1842   traditional magnetic disk.  Note however that storage vendors are prone
1843   to lying to their customers.  For example, it recently came out that
1844   HDDs sold without any warning or mentioning in the data-sheets were
1845   actually using SMR and that will write data first to a faster area and
1846   only overwrite the original data area some time later when things are
1847   quiet.
1848
1849   If you are concerned about your laptop being stolen, you are likely fine
1850   using LUKS on an SSD or hybrid drive.  An attacker would need to have
1851   access to an old passphrase (and the key-slot for this old passphrase
1852   would actually need to still be somewhere in the SSD) for your data to
1853   be at risk.  So unless you pasted your old passphrase all over the
1854   Internet or the attacker has knowledge of it from some other source and
1855   does a targeted laptop theft to get at your data, you should be fine.
1856
1857
1858  * **5.20 LUKS1 is broken! It uses SHA-1!**
1859
1860   No, it is not.  SHA-1 is (academically) broken for finding collisions,
1861   but not for using it in a key-derivation function.  And that collision
1862   vulnerability is for non-iterated use only.  And you need the hash-value
1863   in verbatim.
1864
1865   This basically means that if you already have a slot-key, and you have
1866   set the PBKDF2 iteration count to 1 (it is > 10'000 normally), you could
1867   (maybe) derive a different passphrase that gives you the same slot-key.
1868   But if you have the slot-key, you can already unlock the key-slot and
1869   get the volume key, breaking everything.  So basically, this SHA-1
1870   vulnerability allows you to open a LUKS1 container with high effort when
1871   you already have it open.
1872
1873   The real problem here is people that do not understand crypto and claim
1874   things are broken just because some mechanism is used that has been
1875   broken for a specific different use.  The way the mechanism is used
1876   matters very much.  A hash that is broken for one use can be completely
1877   secure for other uses and here it is.
1878
1879   Since version 1.7.0, cryptsetup uses SHA-256 as default to ensure that
1880   it will be compatible in the future. There are already some systems 
1881   where SHA-1 is completely phased out or disabled by a security policy.
1882
1883
1884  * **5.21 Why is there no "Nuke-Option"?**
1885
1886   A "Nuke-Option" or "Kill-switch" is a password that when entered upon
1887   unlocking instead wipes the header and all passwords.  So when somebody
1888   forces you to enter your password, you can destroy the data instead.
1889
1890   While this sounds attractive at first glance, it does not make sense
1891   once a real security analysis is done.  One problem is that you have to
1892   have some kind of HSM (Hardware Security Module) in order to implement
1893   it securely.  In the movies, a HSM starts to smoke and melt once the
1894   Nuke-Option has been activated.  In actual reality, it just wipes some
1895   battery-backed RAM cells.  A proper HSM costs something like
1896   20'000...100'000 EUR/USD and there a Nuke-Option may make some sense. 
1897   BTW, a chipcard or a TPM is not a HSM, although some vendors are
1898   promoting that myth.
1899
1900   Now, a proper HSMs will have a wipe option but not a Nuke-Option, i.e. 
1901   you can explicitly wipe the HSM, but by a different process than
1902   unlocking it takes.  Why is that?  Simple: If somebody can force you to
1903   reveal passwords, then they can also do bad things to you if you do not
1904   or if you enter a nuke password instead.  Think locking you up for a few
1905   years for "destroying evidence" or for far longer and without trial for
1906   being a "terrorist suspect".  No HSM maker will want to expose its
1907   customers to that risk.
1908
1909   Now think of the typical LUKS application scenario, i.e.  disk
1910   encryption.  Usually the ones forcing you to hand over your password
1911   will have access to the disk as well, and, if they have any real
1912   suspicion, they will mirror your disk before entering anything supplied
1913   by you.  This neatly negates any Nuke-Option.  If they have no suspicion
1914   (just harassing people that cross some border for example), the
1915   Nuke-Option would work, but see above about likely negative consequences
1916   and remember that a Nuke-Option may not work reliably on SSD and hybrid
1917   drives anyways.
1918
1919   Hence my advice is to never take data that you do not want to reveal
1920   into any such situation in the first place.  There is no need to
1921   transfer data on physical carriers today.  The Internet makes it quite
1922   possible to transfer data between arbitrary places and modern encryption
1923   makes it secure.  If you do it right, nobody will even be able to
1924   identify source or destination.  (How to do that is out of scope of this
1925   document.  It does require advanced skills in this age of pervasive
1926   surveillance.)
1927
1928   Hence, LUKS has no kill option because it would do much more harm than
1929   good.
1930
1931   Still, if you have a good use-case (i.e.  non-abstract real-world
1932   situation) where a Nuke-Option would actually be beneficial, please let
1933   me know.
1934
1935
1936  * **5.22 Does cryptsetup open network connections to websites, etc. ?**
1937
1938   This question seems not to make much sense at first glance, but here is
1939   an example form the real world: The TrueCrypt GUI has a "Donation"
1940   button.  Press it, and a web-connection to the TrueCrypt website is
1941   opened via the default browser, telling everybody that listens that you
1942   use TrueCrypt.  In the worst case, things like this can get people
1943   tortured or killed.
1944
1945   So: Cryptsetup will never open any network connections except the
1946   local netlink socket it needs to talk to the kernel crypto API.
1947
1948   In addition, the installation package should contain all documentation,
1949   including this FAQ, so that you do not have to go to a web-site to read
1950   it.  (If your distro cuts the docu, please complain to them.) In
1951   security software, any connection initiated to anywhere outside your
1952   machine should always be the result of an explicit request for such a
1953   connection by the user and cryptsetup will stay true to that principle.
1954
1955
1956  * **5.23 What is cryptsetup CVE-2021-4122?**
1957
1958   CVE-2021-4122 describes a possible attack against data confidentiality
1959   through LUKS2 online reencryption extension crash recovery.
1960
1961   An attacker can modify on-disk metadata to simulate decryption in
1962   progress with crashed (unfinished) reencryption step and persistently
1963   decrypt part of the LUKS device.
1964
1965   This attack requires repeated physical access to the LUKS device but
1966   no knowledge of user passphrases.
1967
1968   The decryption step is performed after a valid user activates
1969   the device with a correct passphrase and modified metadata.
1970   There are no visible warnings for the user that such recovery happened
1971   (except using the luksDump command). The attack can also be reversed
1972   afterward (simulating crashed encryption from a plaintext) with
1973   possible modification of revealed plaintext.
1974
1975   The problem was fixed in cryptsetup version 2.4.3 and 2.3.7.
1976
1977   For more info, please see the report here:
1978   https://seclists.org/oss-sec/2022/q1/34
1979
1980
1981 # 6. Backup and Data Recovery
1982
1983
1984  * **6.1 Why do I need Backup?**
1985
1986   First, disks die.  The rate for well-treated (!) disk is about 5% per
1987   year, which is high enough to worry about.  There is some indication
1988   that this may be even worse for some SSDs.  This applies both to LUKS
1989   and plain dm-crypt partitions.
1990
1991   Second, for LUKS, if anything damages the LUKS header or the key-stripe
1992   area then decrypting the LUKS device can become impossible.  This is a
1993   frequent occurrence.  For example an accidental format as FAT or some
1994   software overwriting the first sector where it suspects a partition boot
1995   sector typically makes a LUKS1 partition permanently inaccessible.  See
1996   more below on LUKS header damage.
1997
1998   So, data-backup in some form is non-optional.  For LUKS, you may also
1999   want to store a header backup in some secure location.  This only needs
2000   an update if you change passphrases.
2001
2002
2003  * **6.2 How do I backup a LUKS header?**
2004
2005   While you could just copy the appropriate number of bytes from the start
2006   of the LUKS partition, the best way is to use command option
2007   "luksHeaderBackup" of cryptsetup.  This protects also against errors
2008   when non-standard parameters have been used in LUKS partition creation.  
2009   Example:
2010 ```
2011     cryptsetup luksHeaderBackup --header-backup-file <file> <device>
2012 ```
2013   To restore, use the inverse command, i.e.
2014 ```
2015     cryptsetup luksHeaderRestore --header-backup-file <file> <device>
2016 ```
2017   If you are unsure about a header to be restored, make a backup of the
2018   current one first!  You can also test the header-file without restoring
2019   it by using the --header option for a detached header like this:
2020 ```
2021     cryptsetup --header <file> luksOpen <device> </dev/mapper/name>
2022 ```
2023   If that unlocks your key-slot, you are good. Do not forget to close
2024   the device again.
2025
2026   Under some circumstances (damaged header), this fails.  Then use the
2027   following steps in case it is LUKS1:
2028
2029   First determine the volume (volume) key size:
2030 ```
2031     cryptsetup luksDump <device>
2032 ```
2033   gives a line of the form
2034 ```
2035     MK bits:        <bits>
2036 ```
2037   with bits equal to 256 for the old defaults and 512 for the new
2038   defaults.  256 bits equals a total header size of 1'052'672 Bytes and
2039   512 bits one of 2MiB.  (See also Item 6.12) If luksDump fails, assume
2040   2MiB, but be aware that if you restore that, you may also restore the
2041   first 1M or so of the filesystem.  Do not change the filesystem if you
2042   were unable to determine the header size!  With that, restoring a
2043   too-large header backup is still safe.
2044
2045   Second, dump the header to file. There are many ways to do it, I
2046   prefer the following:
2047 ```
2048     head -c 1052672 <device>  >  header_backup.dmp
2049 ```
2050   or
2051 ```
2052     head -c 2M <device>  >  header_backup.dmp
2053 ```
2054   for a 2MiB header. Verify the size of the dump-file to be sure.
2055
2056   To restore such a backup, you can try luksHeaderRestore or do a more
2057   basic
2058 ```
2059     cat header_backup.dmp  >  <device>
2060 ```
2061
2062
2063   * **6.3 How do I test for a LUKS header?**
2064
2065   Use
2066 ```
2067     cryptsetup -v isLuks <device>
2068 ```
2069   on the device.  Without the "-v" it just signals its result via
2070   exit-status.  You can also use the more general test
2071 ```
2072     blkid -p <device>
2073 ```
2074   which will also detect other types and give some more info.  Omit
2075   "-p" for old versions of blkid that do not support it.
2076
2077
2078   * **6.4 How do I backup a LUKS or dm-crypt partition?**
2079
2080   There are two options, a sector-image and a plain file or filesystem
2081   backup of the contents of the partition.  The sector image is already
2082   encrypted, but cannot be compressed and contains all empty space.  The
2083   filesystem backup can be compressed, can contain only part of the
2084   encrypted device, but needs to be encrypted separately if so desired.
2085
2086   A sector-image will contain the whole partition in encrypted form, for
2087   LUKS the LUKS header, the keys-slots and the data area.  It can be done
2088   under Linux e.g.  with dd_rescue (for a direct image copy) and with
2089   "cat" or "dd".  Examples:
2090 ```
2091     cat /dev/sda10 > sda10.img
2092     dd_rescue /dev/sda10 sda10.img
2093 ```
2094   You can also use any other backup software that is capable of making a
2095   sector image of a partition.  Note that compression is ineffective for
2096   encrypted data, hence it does not make sense to use it.
2097
2098   For a filesystem backup, you decrypt and mount the encrypted partition
2099   and back it up as you would a normal filesystem.  In this case the
2100   backup is not encrypted, unless your encryption method does that.  For
2101   example you can encrypt a backup with "tar" as follows with GnuPG:
2102 ```
2103     tar cjf - <path> | gpg --cipher-algo AES -c - > backup.tbz2.gpg
2104 ```
2105   And verify the backup like this if you are at "path":
2106 ```
2107     cat backup.tbz2.gpg | gpg - | tar djf -
2108 ```
2109   Note: Always verify backups, especially encrypted ones!
2110
2111   There is one problem with verifying like this: The kernel may still have
2112   some files cached and in fact verify them against RAM or may even verify
2113   RAM against RAM, which defeats the purpose of the exercise.  The
2114   following command empties the kernel caches:
2115 ```
2116     echo 3 > /proc/sys/vm/drop_caches
2117 ```
2118   Run it after backup and before verify.
2119
2120   In both cases GnuPG will ask you interactively for your symmetric key. 
2121   The verify will only output errors.  Use "tar dvjf -" to get all
2122   comparison results.  To make sure no data is written to disk
2123   unencrypted, turn off swap if it is not encrypted before doing the
2124   backup.
2125
2126   Restore works like certification with the 'd' ('difference') replaced 
2127   by 'x' ('eXtract').  Refer to the man-page of tar for more explanations 
2128   and instructions.  Note that with default options tar will overwrite 
2129   already existing files without warning.  If you are unsure about how 
2130   to use tar, experiment with it in a location where you cannot do damage.
2131
2132   You can of course use different or no compression and you can use an
2133   asymmetric key if you have one and have a backup of the secret key that
2134   belongs to it.
2135
2136   A second option for a filesystem-level backup that can be used when the
2137   backup is also on local disk (e.g.  an external USB drive) is to use a
2138   LUKS container there and copy the files to be backed up between both
2139   mounted containers.  Also see next item.
2140
2141
2142   * **6.5 Do I need a backup of the full partition? Would the header and key-slots not be enough?**
2143
2144   Backup protects you against two things: Disk loss or corruption and user
2145   error.  By far the most questions on the dm-crypt mailing list about how
2146   to recover a damaged LUKS partition are related to user error.  For
2147   example, if you create a new filesystem on a non-mapped LUKS container,
2148   chances are good that all data is lost permanently.
2149
2150   For this case, a header+key-slot backup would often be enough.  But keep
2151   in mind that a well-treated (!) HDD has roughly a failure risk of 5% per
2152   year.  It is highly advisable to have a complete backup to protect
2153   against this case.
2154
2155
2156   * **6.6 What do I need to backup if I use "decrypt_derived"?**
2157
2158   This is a script in Debian, intended for mounting /tmp or swap with a
2159   key derived from the volume key of an already decrypted device.  If you
2160   use this for an device with data that should be persistent, you need to
2161   make sure you either do not lose access to that volume key or have a
2162   backup of the data.  If you derive from a LUKS device, a header backup
2163   of that device would cover backing up the volume key.  Keep in mind that
2164   this does not protect against disk loss.
2165
2166   Note: If you recreate the LUKS header of the device you derive from
2167   (using luksFormat), the volume key changes even if you use the same
2168   passphrase(s) and you will not be able to decrypt the derived device
2169   with the new LUKS header.
2170
2171
2172   * **6.7 Does a backup compromise security?**
2173
2174   Depends on how you do it.  However if you do not have one, you are going
2175   to eventually lose your encrypted data.
2176
2177   There are risks introduced by backups.  For example if you
2178   change/disable a key-slot in LUKS, a binary backup of the partition will
2179   still have the old key-slot.  To deal with this, you have to be able to
2180   change the key-slot on the backup as well, securely erase the backup or
2181   do a filesystem-level backup instead of a binary one.
2182
2183   If you use dm-crypt, backup is simpler: As there is no key management,
2184   the main risk is that you cannot wipe the backup when wiping the
2185   original.  However wiping the original for dm-crypt should consist of
2186   forgetting the passphrase and that you can do without actual access to
2187   the backup.
2188
2189   In both cases, there is an additional (usually small) risk with binary
2190   backups: An attacker can see how many sectors and which ones have been
2191   changed since the backup.  To prevent this, use a filesystem level
2192   backup method that encrypts the whole backup in one go, e.g.  as
2193   described above with tar and GnuPG.
2194
2195   My personal advice is to use one USB disk (low value data) or three
2196   disks (high value data) in rotating order for backups, and either use
2197   independent LUKS partitions on them, or use encrypted backup with tar
2198   and GnuPG.
2199
2200   If you do network-backup or tape-backup, I strongly recommend to go
2201   the filesystem backup path with independent encryption, as you
2202   typically cannot reliably delete data in these scenarios, especially
2203   in a cloud setting.  (Well, you can burn the tape if it is under your
2204   control...)
2205
2206
2207   * **6.8 What happens if I overwrite the start of a LUKS partition or damage the LUKS header or key-slots?**
2208
2209   There are two critical components for decryption: The salt values in the
2210   key-slot descriptors of the header and the key-slots.  For LUKS2 they
2211   are a bit better protected.  but for LUKS1, these are right in the first
2212   sector.  If the salt values are overwritten or changed, nothing (in the
2213   cryptographically strong sense) can be done to access the data, unless
2214   there is a backup of the LUKS header.  If a key-slot is damaged, the
2215   data can still be read with a different key-slot, if there is a
2216   remaining undamaged and used key-slot.  Note that in order to make a
2217   key-slot completely unrecoverable, changing about 4-6 bits in random
2218   locations of its 128kiB size is quite enough.
2219
2220
2221   * **6.9 What happens if I (quick) format a LUKS partition?**
2222
2223   I have not tried the different ways to do this, but very likely you will
2224   have written a new boot-sector, which in turn overwrites the LUKS
2225   header, including the salts, making your data permanently irretrievable,
2226   unless you have a LUKS header backup.  For LUKS2 this may still be
2227   recoverable without that header backup, for LUKS1 it is not.  You may
2228   also damage the key-slots in part or in full.  See also last item.
2229
2230
2231   * **6.10 How do I recover the volume key from a mapped LUKS1 container?**
2232
2233   Note: LUKS2 uses the kernel keyring to store keys and hence this
2234   procedure does not work unless you have explicitly disabled the use of
2235   the keyring with "--disable-keyring" on opening.
2236  
2237   This is typically only needed if you managed to damage your LUKS1
2238   header, but the container is still mapped, i.e.  "luksOpen"ed.  It also
2239   helps if you have a mapped container that you forgot or do not know a
2240   passphrase for (e.g.  on a long running server.)
2241
2242   WARNING: Things go wrong, do a full backup before trying this!
2243
2244   WARNING: This exposes the volume key of the LUKS1 container.  Note that
2245   both ways to recreate a LUKS header with the old volume key described
2246   below will write the volume key to disk.  Unless you are sure you have
2247   securely erased it afterwards, e.g.  by writing it to an encrypted
2248   partition, RAM disk or by erasing the filesystem you wrote it to by a
2249   complete overwrite, you should change the volume key afterwards. 
2250   Changing the volume key requires a full data backup, luksFormat and then
2251   restore of the backup.  Alternatively the tool cryptsetup-reencrypt from
2252   the cryptsetup package can be used to change the volume key (see its
2253   man-page), but a full backup is still highly recommended.
2254
2255   First, there is a script by Milan that automates the whole process,
2256   except generating a new LUKS1 header with the old volume key (it prints
2257   the command for that though):
2258
2259   https://gitlab.com/cryptsetup/cryptsetup/blob/main/misc/luks-header-from-active
2260
2261   You can also do this manually. Here is how:
2262
2263   - Get the volume key from the device mapper.  This is done by the
2264   following command.  Substitute c5 for whatever you mapped to:
2265 ```
2266     # dmsetup table --target crypt --showkey /dev/mapper/c5
2267
2268     Result:
2269     0 200704 crypt aes-cbc-essiv:sha256
2270     a1704d9715f73a1bb4db581dcacadaf405e700d591e93e2eaade13ba653d0d09
2271     0 7:0 4096
2272 ```
2273   The result is actually one line, wrapped here for clarity.  The long
2274   hex string is the volume key.
2275
2276   - Convert the volume key to a binary file representation.  You can do
2277   this manually, e.g.  with hexedit.  You can also use the tool "xxd"
2278   from vim like this:
2279 ```
2280     echo "a1704d9....53d0d09" | xxd -r -p > <volume-key-file>
2281 ```
2282
2283   - Do a luksFormat to create a new LUKS1 header.
2284
2285     NOTE: If your header is intact and you just forgot the passphrase,
2286     you can just set a new passphrase, see next sub-item.
2287
2288   Unmap the device before you do that (luksClose). Then do
2289 ```
2290     cryptsetup luksFormat --volume-key-file=<volume-key-file> <luks device>
2291 ```
2292   Note that if the container was created with other than the default
2293   settings of the cryptsetup version you are using, you need to give
2294   additional parameters specifying the deviations.  If in doubt, try the
2295   script by Milan.  It does recover the other parameters as well.
2296
2297   Side note: This is the way the decrypt_derived script gets at the volume
2298   key.  It just omits the conversion and hashes the volume key string.
2299
2300   - If the header is intact and you just forgot the passphrase, just
2301   set a new passphrase like this:
2302 ```
2303       cryptsetup luksAddKey --volume-key-file=<volume-key-file> <luks device>
2304 ```
2305   You may want to disable the old one afterwards.
2306
2307
2308   * **6.11 What does the on-disk structure of dm-crypt look like?**
2309
2310   There is none.  dm-crypt takes a block device and gives encrypted access
2311   to each of its blocks with a key derived from the passphrase given.  If
2312   you use a cipher different than the default, you have to specify that as
2313   a parameter to cryptsetup too.  If you want to change the password, you
2314   basically have to create a second encrypted device with the new
2315   passphrase and copy your data over.  On the plus side, if you
2316   accidentally overwrite any part of a dm-crypt device, the damage will be
2317   limited to the area you overwrote.
2318
2319
2320   * **6.12 What does the on-disk structure of LUKS1 look like?**
2321
2322   Note: For LUKS2, refer to the LUKS2 document referenced in Item 1.2
2323
2324   A LUKS1 partition consists of a header, followed by 8 key-slot
2325   descriptors, followed by 8 key slots, followed by the encrypted data
2326   area.
2327
2328   Header and key-slot descriptors fill the first 592 bytes.  The key-slot
2329   size depends on the creation parameters, namely on the number of
2330   anti-forensic stripes, key material offset and volume key size.
2331
2332   With the default parameters, each key-slot is a bit less than 128kiB in
2333   size.  Due to sector alignment of the key-slot start, that means the key
2334   block 0 is at offset 0x1000-0x20400, key block 1 at offset
2335   0x21000-0x40400, and key block 7 at offset 0xc1000-0xe0400.  The space
2336   to the next full sector address is padded with zeros.  Never used
2337   key-slots are filled with what the disk originally contained there, a
2338   key-slot removed with "luksRemoveKey" or "luksKillSlot" gets filled with
2339   0xff.  Due to 2MiB default alignment, start of the data area for
2340   cryptsetup 1.3 and later is at 2MiB, i.e.  at 0x200000.  For older
2341   versions, it is at 0x101000, i.e.  at 1'052'672 bytes, i.e.  at 1MiB +
2342   4096 bytes from the start of the partition.  Incidentally,
2343   "luksHeaderBackup" for a LUKS container created with default parameters
2344   dumps exactly the first 2MiB (or 1'052'672 bytes for headers created
2345   with cryptsetup versions < 1.3) to file and "luksHeaderRestore" restores
2346   them.
2347
2348   For non-default parameters, you have to figure out placement yourself. 
2349   "luksDump" helps.  See also next item.  For the most common non-default
2350   settings, namely aes-xts-plain with 512 bit key, the offsets are: 1st
2351   keyslot 0x1000-0x3f800, 2nd keyslot 0x40000-0x7e000, 3rd keyslot
2352   0x7e000-0xbd800, ..., and start of bulk data at 0x200000.
2353
2354   The exact specification of the format is here:
2355      https://gitlab.com/cryptsetup/cryptsetup/wikis/Specification
2356
2357   For your convenience, here is the LUKS1 header with hex offsets.  
2358   NOTE:
2359   The spec counts key-slots from 1 to 8, but the cryptsetup tool counts
2360   from 0 to 7.  The numbers here refer to the cryptsetup numbers.
2361
2362 ```
2363 Refers to LUKS1 On-Disk Format Specification Version 1.2.3
2364
2365 LUKS1 header:
2366
2367 offset  length  name             data type  description
2368 -----------------------------------------------------------------------
2369 0x0000   0x06   magic            byte[]     'L','U','K','S', 0xba, 0xbe
2370      0      6
2371 0x0006   0x02   version          uint16_t   LUKS version
2372      6      3
2373 0x0008   0x20   cipher-name      char[]     cipher name spec.
2374      8     32
2375 0x0028   0x20   cipher-mode      char[]     cipher mode spec.
2376     40     32
2377 0x0048   0x20   hash-spec        char[]     hash spec.
2378     72     32
2379 0x0068   0x04   payload-offset   uint32_t   bulk data offset in sectors
2380    104      4                               (512 bytes per sector)
2381 0x006c   0x04   key-bytes        uint32_t   number of bytes in key
2382    108      4
2383 0x0070   0x14   mk-digest        byte[]     volume key checksum
2384    112     20                               calculated with PBKDF2
2385 0x0084   0x20   mk-digest-salt   byte[]     salt for PBKDF2 when
2386    132     32                               calculating mk-digest
2387 0x00a4   0x04   mk-digest-iter   uint32_t   iteration count for PBKDF2
2388    164      4                               when calculating mk-digest
2389 0x00a8   0x28   uuid             char[]     partition UUID
2390    168     40
2391 0x00d0   0x30   key-slot-0       key slot   key slot 0
2392    208     48
2393 0x0100   0x30   key-slot-1       key slot   key slot 1
2394    256     48
2395 0x0130   0x30   key-slot-2       key slot   key slot 2
2396    304     48
2397 0x0160   0x30   key-slot-3       key slot   key slot 3
2398    352     48
2399 0x0190   0x30   key-slot-4       key slot   key slot 4
2400    400     48
2401 0x01c0   0x30   key-slot-5       key slot   key slot 5
2402    448     48
2403 0x01f0   0x30   key-slot-6       key slot   key slot 6
2404    496     48
2405 0x0220   0x30   key-slot-7       key slot   key slot 7
2406    544     48
2407
2408
2409 Key slot:
2410
2411 offset  length  name                  data type  description
2412 -------------------------------------------------------------------------
2413 0x0000   0x04   active                uint32_t   key slot enabled/disabled
2414      0      4
2415 0x0004   0x04   iterations            uint32_t   PBKDF2 iteration count
2416      4      4
2417 0x0008   0x20   salt                  byte[]     PBKDF2 salt
2418      8     32
2419 0x0028   0x04   key-material-offset   uint32_t   key start sector
2420     40      4                                    (512 bytes/sector)
2421 0x002c   0x04   stripes               uint32_t   number of anti-forensic
2422     44      4                                    stripes
2423 ```
2424
2425
2426   * **6.13 What is the smallest possible LUKS1 container?**
2427
2428   Note: From cryptsetup 1.3 onwards, alignment is set to 1MB.  With modern
2429   Linux partitioning tools that also align to 1MB, this will result in
2430   alignment to 2k sectors and typical Flash/SSD sectors, which is highly
2431   desirable for a number of reasons.  Changing the alignment is not
2432   recommended.
2433
2434   That said, with default parameters, the data area starts at exactly 2MB
2435   offset (at 0x101000 for cryptsetup versions before 1.3).  The smallest
2436   data area you can have is one sector of 512 bytes.  Data areas of 0
2437   bytes can be created, but fail on mapping.
2438
2439   While you cannot put a filesystem into something this small, it may
2440   still be used to contain, for example, key.  Note that with current
2441   formatting tools, a partition for a container this size will be 3MiB
2442   anyways.  If you put the LUKS container into a file (via losetup and a
2443   loopback device), the file needs to be 2097664 bytes in size, i.e.  2MiB
2444   + 512B.
2445
2446   The two ways to influence the start of the data area are key-size and
2447   alignment.
2448
2449   For alignment, you can go down to 1 on the parameter.  This will still
2450   leave you with a data-area starting at 0x101000, i.e.  1MiB+4096B
2451   (default parameters) as alignment will be rounded up to the next
2452   multiple of 8 (i.e.  4096 bytes) If in doubt, do a dry-run on a larger
2453   file and dump the LUKS header to get actual information.
2454
2455   For key-size, you can use 128 bit (e.g.  AES-128 with CBC), 256 bit
2456   (e.g.  AES-256 with CBC) or 512 bit (e.g.  AES-256 with XTS mode).  You
2457   can do 64 bit (e.g.  blowfish-64 with CBC), but anything below 128 bit
2458   has to be considered insecure today.
2459
2460   Example 1 - AES 128 bit with CBC:
2461 ```
2462       cryptsetup luksFormat -s 128 --align-payload=8 <device>
2463 ```
2464   This results in a data offset of 0x81000, i.e. 516KiB or 528384
2465   bytes.  Add one 512 byte sector and the smallest LUKS container size
2466   with these parameters is 516KiB + 512B or 528896 bytes.
2467
2468   Example 2 - Blowfish 64 bit with CBC (WARNING: insecure):
2469 ```
2470       cryptsetup luksFormat -c blowfish -s 64 --align-payload=8 /dev/loop0
2471 ```
2472   This results in a data offset of 0x41000, i.e. 260kiB or 266240
2473   bytes, with a minimal LUKS1 container size of 260kiB + 512B or 266752
2474   bytes.
2475
2476
2477   * **6.14 I think this is overly complicated. Is there an alternative?**
2478
2479   Not really.  Encryption comes at a price.  You can use plain dm-crypt to
2480   simplify things a bit.  It does not allow multiple passphrases, but on
2481   the plus side, it has zero on disk description and if you overwrite some
2482   part of a plain dm-crypt partition, exactly the overwritten parts are
2483   lost (rounded up to full sectors).
2484
2485   * **6.15 Can I clone a LUKS container?**
2486
2487   You can, but it breaks security, because the cloned container has the
2488   same header and hence the same volume key.  Even if you change the 
2489   passphrase(s), the volume key stays the same.  That means whoever has 
2490   access to one of the clones can decrypt them all, completely bypassing 
2491   the passphrases. 
2492
2493   While you can use cryptsetup-reencrypt to change the volume key, 
2494   this is probably more effort than to create separate LUKS containers
2495   in the first place.
2496
2497   The right way to do this is to first luksFormat the target container,
2498   then to clone the contents of the source container, with both containers
2499   mapped, i.e.  decrypted.  You can clone the decrypted contents of a LUKS
2500   container in binary mode, although you may run into secondary issues
2501   with GUIDs in filesystems, partition tables, RAID-components and the
2502   like.  These are just the normal problems binary cloning causes.
2503
2504   Note that if you need to ship (e.g.) cloned LUKS containers with a
2505   default passphrase, that is fine as long as each container was
2506   individually created (and hence has its own volume key).  In this case,
2507   changing the default passphrase will make it secure again.
2508
2509   * **6.16 How to convert the printed volume key to a raw one?**
2510   A volume key printed via something like:
2511 ```
2512       cryptsetup --dump-volume-key luksDump /dev/<device> >volume-key
2513 ```
2514 (i.e. without using `--volume-key-file`), which gives something like:
2515 ```
2516 LUKS header information for /dev/<device>
2517 Cipher name:    aes
2518 Cipher mode:    xts-plain64
2519 Payload offset: 32768
2520 UUID:           6e914442-e8b5-4eb5-98c4-5bf0cf17ecad
2521 MK bits:        512
2522 MK dump:        e0 3f 15 c2 0f e5 80 ab 35 b4 10 03 ae 30 b9 5d 
2523                 4c 0d 28 9e 1b 0f e3 b0 50 57 ef d4 4d 53 a0 12 
2524                 b7 4e 43 a1 20 7e c5 02 1f f1 f5 08 04 3c f5 20 
2525                 a6 0b 23 f6 7b 53 55 aa 22 d8 aa 02 e0 2f d5 04 
2526 ```
2527 can be converted to the raw volume key for example via:
2528 ```
2529       sed -E -n '/^MK dump:\t/,/^[^\t]/{0,/^MK dump:\t/s/^MK dump://; /^([^\t].*)?$/q; s/\t+//p;};' volume-key  |  xxd -r -p
2530 ```
2531
2532
2533
2534
2535 # 7. Interoperability with other Disk Encryption Tools
2536
2537
2538   * **7.1 What is this section about?**
2539
2540   Cryptsetup for plain dm-crypt can be used to access a number of on-disk
2541   formats created by tools like loop-aes patched into losetup.  This
2542   sometimes works and sometimes does not.  This section collects insights
2543   into what works, what does not and where more information is required.
2544
2545   Additional information may be found in the mailing-list archives,
2546   mentioned at the start of this FAQ document.  If you have a solution
2547   working that is not yet documented here and think a wider audience may
2548   be interested, please email the FAQ maintainer.
2549
2550
2551   * **7.2 loop-aes: General observations.**
2552
2553   One problem is that there are different versions of losetup around. 
2554   loop-aes is a patch for losetup.  Possible problems and deviations
2555   from cryptsetup option syntax include:
2556
2557   - Offsets specified in bytes (cryptsetup: 512 byte sectors)
2558
2559   - The need to specify an IV offset
2560
2561   - Encryption mode needs specifying (e.g. "-c twofish-cbc-plain")
2562
2563   - Key size needs specifying (e.g. "-s 128" for 128 bit keys)
2564
2565   - Passphrase hash algorithm needs specifying
2566
2567   Also note that because plain dm-crypt and loop-aes format does not have
2568   metadata, and while the loopAES extension for cryptsetup tries
2569   autodetection (see command loopaesOpen), it may not always work.  If you
2570   still have the old set-up, using a verbosity option (-v) on mapping with
2571   the old tool or having a look into the system logs after setup could
2572   give you the information you need.  Below, there are also some things
2573   that worked for somebody.
2574
2575
2576   * **7.3 loop-aes patched into losetup on Debian 5.x, kernel 2.6.32**
2577
2578   In this case, the main problem seems to be that this variant of
2579   losetup takes the offset (-o option) in bytes, while cryptsetup takes
2580   it in sectors of 512 bytes each.  
2581
2582   Example: The losetup command
2583 ```
2584     losetup -e twofish -o 2560 /dev/loop0 /dev/sdb1
2585     mount /dev/loop0 mount-point
2586 ```
2587   translates to
2588 ```
2589     cryptsetup create -c twofish -o 5 --skip 5 e1 /dev/sdb1
2590     mount /dev/mapper/e1 mount-point
2591 ```
2592
2593
2594   * **7.4 loop-aes with 160 bit key**
2595
2596   This seems to be sometimes used with twofish and blowfish and represents
2597   a 160 bit ripemed160 hash output padded to 196 bit key length.  It seems
2598   the corresponding options for cryptsetup are
2599 ```
2600     --cipher twofish-cbc-null -s 192 -h ripemd160:20
2601 ```
2602
2603
2604   * **7.5 loop-aes v1 format OpenSUSE**
2605
2606   Apparently this is done by older OpenSUSE distros and stopped working
2607   from OpenSUSE 12.1 to 12.2.  One user had success with the following:
2608 ```
2609     cryptsetup create <target> <device> -c aes -s 128 -h sha256
2610 ```
2611
2612
2613   * **7.6 Kernel encrypted loop device (cryptoloop)**
2614
2615   There are a number of different losetup implementations for using
2616   encrypted loop devices so getting this to work may need a bit of
2617   experimentation.
2618
2619   NOTE: Do NOT use this for new containers! Some of the existing
2620   implementations are insecure and future support is uncertain.
2621
2622   Example for a compatible mapping:
2623 ```
2624     losetup -e twofish -N /dev/loop0 /image.img
2625 ```
2626   translates to
2627 ```
2628     cryptsetup create image_plain /image.img -c twofish-cbc-plain -H plain
2629 ```
2630   with the mapping being done to /dev/mapper/image_plain instead of
2631   to /dev/loop0.
2632
2633   More details:
2634
2635   Cipher, mode and password hash (or no hash):
2636 ```
2637   -e cipher [-N]        => -c cipher-cbc-plain -H plain [-s 256]
2638   -e cipher             => -c cipher-cbc-plain -H ripemd160 [-s 256]
2639 ```
2640
2641   Key size and offsets (losetup: bytes, cryptsetuop: sectors of 512 bytes):
2642 ```
2643   -k 128                 => -s 128
2644   -o 2560                => -o 5 -p 5       # 2560/512 = 5
2645 ```
2646
2647   There is no replacement for --pass-fd, it has to be emulated using
2648   keyfiles, see the cryptsetup man-page.
2649
2650
2651 # 8. Issues with Specific Versions of cryptsetup
2652
2653
2654   * **8.1 When using the create command for plain dm-crypt with cryptsetup 1.1.x, the mapping is incompatible and my data is not accessible anymore!**
2655
2656   With cryptsetup 1.1.x, the distro maintainer can define different
2657   default encryption modes.  You can check the compiled-in defaults using
2658   "cryptsetup --help".  Moreover, the plain device default changed because
2659   the old IV mode was vulnerable to a watermarking attack.
2660
2661   If you are using a plain device and you need a compatible mode, just
2662   specify cipher, key size and hash algorithm explicitly.  For
2663   compatibility with cryptsetup 1.0.x defaults, simple use the following:
2664 ```
2665     cryptsetup create -c aes-cbc-plain -s 256 -h ripemd160 <name> <dev>
2666 ```
2667   LUKS stores cipher and mode in the metadata on disk, avoiding this
2668   problem.
2669
2670
2671   * **8.2 cryptsetup on SLED 10 has problems...**
2672
2673   SLED 10 is missing an essential kernel patch for dm-crypt, which is
2674   broken in its kernel as a result.  There may be a very old version of
2675   cryptsetup (1.0.x) provided by SLED, which should also not be used
2676   anymore as well.  My advice would be to drop SLED 10.
2677
2678
2679   * **8.3 Gcrypt 1.6.x and later break Whirlpool**
2680
2681   It is the other way round: In gcrypt 1.5.x, Whirlpool is broken and it
2682   was fixed in 1.6.0 and later.  If you selected whirlpool as hash on
2683   creation of a LUKS container, it does not work anymore with the fixed
2684   library.  This shows one serious risk of using rarely used settings.
2685
2686   Note that at the time this FAQ item was written, 1.5.4 was the latest
2687   1.5.x version and it has the flaw, i.e.  works with the old Whirlpool
2688   version.  Possibly later 1.5.x versions will work as well.  If not,
2689   please let me know.
2690
2691   The only two ways to access older LUKS containers created with Whirlpool
2692   are to either decrypt with an old gcrypt version that has the flaw or to
2693   use a compatibility feature introduced in cryptsetup 1.6.4 and gcrypt
2694   1.6.1 or later.  Version 1.6.0 cannot be used.
2695
2696   Steps:
2697
2698   - Make at least a header backup or better, refresh your full backup. 
2699   (You have a full backup, right?  See Item 6.1 and following.)
2700
2701   - Make sure you have cryptsetup 1.6.4 or later and check the gcrypt
2702     version:
2703 ```
2704      cryptsetup luksDump <your luks device> --debug | grep backend
2705 ```
2706   If gcrypt is at version 1.5.x or before:
2707
2708   - Reencrypt the LUKS header with a different hash. (Requires entering
2709   all keyslot passphrases.  If you do not have all, remove the ones you
2710   do not have before.):
2711 ```
2712      cryptsetup-reencrypt --keep-key --hash sha256 <your luks device>
2713 ```
2714   If gcrypt is at version 1.6.1 or later:
2715
2716   - Patch the hash name in the LUKS header from "whirlpool" to
2717   "whirlpool_gcryptbug".  This activates the broken implementation. 
2718   The detailed header layout is in Item 6.12 of this FAQ and in the
2719   LUKS on-disk format specification.  One way to change the hash is
2720   with the following command:
2721 ```
2722      echo -n -e 'whirlpool_gcryptbug\0' | dd of=<luks device> bs=1 seek=72 conv=notrunc
2723 ```
2724   - You can now open the device again. It is highly advisable to change
2725   the hash now with cryptsetup-reencrypt as described above.  While you
2726   can reencrypt to use the fixed whirlpool, that may not be a good idea
2727   as almost nobody seems to use it and hence the long time until the
2728   bug was discovered.
2729
2730
2731 # 9. The Initrd question
2732
2733
2734   * **9.1 My initrd is broken with cryptsetup**
2735
2736   That is not nice!  However the initrd is supplied by your distribution,
2737   not by the cryptsetup project and hence you should complain to them.  We
2738   cannot really do anything about it.
2739
2740
2741   * **9.2 CVE-2016-4484 says cryptsetup is broken!**
2742
2743   Not really. It says the initrd in some Debian versions have a behavior 
2744   that under some very special and unusual conditions may be considered
2745   a vulnerability. 
2746
2747   What happens is that you can trick the initrd to go to a rescue-shell if
2748   you enter the LUKS password wrongly in a specific way.  But falling back
2749   to a rescue shell on initrd errors is a sensible default behavior in the
2750   first place.  It gives you about as much access as booting a rescue
2751   system from CD or USB-Stick or as removing the disk would give you.  So
2752   this only applies when an attacker has physical access, but cannot boot
2753   anything else or remove the disk.  These will be rare circumstances
2754   indeed, and if you rely on the default distribution initrd to keep you
2755   safe under these circumstances, then you have bigger problems than this
2756   somewhat expected behavior.
2757
2758   The CVE was exaggerated and should not be assigned to upstream
2759   cryptsetup in the first place (it is a distro specific initrd issue). 
2760   It was driven more by a try to make a splash for self-aggrandizement,
2761   than by any actual security concerns.  Ignore it.
2762
2763
2764   * **9.3 How do I do my own initrd with cryptsetup?**
2765
2766   Note: The instructions here apply to an initrd in initramfs format, not
2767   to an initrd in initrd format.  The latter is a filesystem image, not a
2768   cpio-archive, and seems to not be widely used anymore.
2769  
2770   It depends on the distribution.  Below, I give a very simple example and
2771   step-by-step instructions for Debian.  With a bit of work, it should be
2772   possible to adapt this to other distributions.  Note that the
2773   description is pretty general, so if you want to do other things with an
2774   initrd it provides a useful starting point for that too.
2775
2776   01) Unpacking an existing initrd to use as template
2777
2778   A Linux initrd is in gzip'ed cpio format. To unpack it, use something
2779   like this: 
2780 ``` 
2781      mkdir tmp; cd tmp; cat ../initrd | gunzip | cpio -id
2782 ```
2783   After this, you have the full initrd content in tmp/
2784
2785   02) Inspecting the init-script
2786
2787   The init-script is the only thing the kernel cares about.  All activity
2788   starts there.  Its traditional location is /sbin/init on disk, but /init
2789   in an initrd.  In an initrd unpacked as above it is tmp/init.
2790
2791   While init can be a binary despite usually being called "init script",
2792   in Debian the main init on the root partition is a binary, but the init
2793   in the initrd (and only that one is called by the kernel) is a script
2794   and starts like this:
2795 ```
2796     #!/bin/sh
2797     ....
2798 ```
2799   The "sh" used here is in tmp/bin/sh as just unpacked, and in Debian it
2800   currently is a busybox.
2801
2802   03) Creating your own initrd
2803
2804   The two examples below should give you most of what is needed.  This is
2805   tested with LUKS1 and should work with LUKS2 as well.  If not, please
2806   let me know.
2807
2808   Here is a really minimal example.  It does nothing but set up some
2809   things and then drop to an interactive shell.  It is perfect to try out
2810   things that you want to go into the init-script.
2811 ```
2812    #!/bin/sh
2813    export PATH=/sbin:/bin  
2814    [ -d /sys ] || mkdir /sys
2815    [ -d /proc ] || mkdir /proc
2816    [ -d /tmp ] || mkdir /tmp
2817    mount -t sysfs -o nodev,noexec,nosuid sysfs /sys
2818    mount -t proc -o nodev,noexec,nosuid proc /proc
2819    echo "initrd is running, starting BusyBox..."
2820    exec /bin/sh --login
2821 ```
2822
2823   Here is an example that opens the first LUKS-partition it finds with the
2824   hard-coded password "test2" and then mounts it as root-filesystem.  This
2825   is intended to be used on an USB-stick that after boot goes into a safe,
2826   as it contains the LUKS-passphrase in plain text and is not secure to be
2827   left in the system.  The script contains debug-output that should make it
2828   easier to see what is going on.  Note that the final hand-over to the init
2829   on the encrypted root-partition is done by "exec switch_root /mnt/root
2830   /sbin/init", after mounting the decrypted LUKS container with "mount
2831   /dev/mapper/c1 /mnt/root".  The second argument of switch_root is relative
2832   to the first argument, i.e.  the init started with this command is really
2833   /mnt/sbin/init before switch_root runs.
2834 ```
2835    #!/bin/sh
2836    export PATH=/sbin:/bin
2837    [ -d /sys ] || mkdir /sys
2838    [ -d /proc ] || mkdir /proc
2839    [ -d /tmp ] || mkdir /tmp
2840    mount -t sysfs -o nodev,noexec,nosuid sysfs /sys
2841    mount -t proc -o nodev,noexec,nosuid proc /proc
2842    echo "detecting LUKS containers in sda1-10, sdb1-10"; sleep 1
2843    for i in a b
2844    do
2845      for j in 1 2 3 4 5 6 7 8 9 10
2846      do
2847        sleep 0.5
2848        d="/dev/sd"$i""$j
2849        echo -n $d
2850        cryptsetup isLuks $d >/dev/null 2>&1
2851        r=$?
2852        echo -n "  result: "$r""
2853        # 0 = is LUKS, 1 = is not LUKS, 4 = other error
2854        if expr $r = 0 > /dev/null
2855        then
2856          echo "  is LUKS, attempting unlock"
2857          echo -n "test2" | cryptsetup luksOpen --key-file=- $d c1
2858          r=$?
2859          echo "  result of unlock attempt: "$r""
2860          sleep 2
2861          if expr $r = 0 > /dev/null
2862          then
2863            echo "*** LUKS partition unlocked, switching root *** 
2864            echo "    (waiting 30 seconds before doing that)"
2865            mount /dev/mapper/c1 /mnt/root
2866            sleep 30
2867            exec switch_root /mnt/root /sbin/init
2868          fi
2869        else
2870          echo "  is not LUKS"
2871        fi
2872      done
2873    done
2874    echo "FAIL finding root on LUKS, loading BusyBox..."; sleep 5
2875    exec /bin/sh --login
2876 ```
2877
2878   04) What if I want a binary in the initrd, but libraries are missing?
2879
2880   That is a bit tricky.  One option is to compile statically, but that
2881   does not work for everything.  Debian puts some libraries into lib/ and
2882   lib64/ which are usually enough.  If you need more, you can add the
2883   libraries you need there.  That may or may not need a configuration
2884   change for the dynamic linker "ld" as well.  Refer to standard Linux
2885   documentation on how to add a library to a Linux system.  A running
2886   initrd is just a running Linux system after all, it is not special in
2887   any way.
2888
2889   05) How do I repack the initrd?
2890
2891   Simply repack the changed directory. While in tmp/, do
2892   the following:
2893   ```
2894   find . | cpio --create --format='newc' | gzip > ../new_initrd
2895   ```
2896   Rename "new_initrd" to however you want it called (the name of
2897   the initrd is a kernel-parameter) and move to /boot. That is it.
2898
2899
2900 # 10. LUKS2 Questions
2901
2902
2903   * **10.1 Is the cryptography of LUKS2 different?**
2904
2905   Mostly not.  The header has changed in its structure, but the
2906   cryptography is the same.  The one exception is that PBKDF2 has been
2907   replaced by Argon2 to give better resilience against attacks by
2908   graphics cards and other hardware with lots of computing power but
2909   limited local memory per computing element.
2910
2911
2912   * **10.2 What new features does LUKS2 have?**
2913   
2914   There are quite a few.  I recommend reading the man-page and the on-disk
2915   format specification, see Item 1.2.
2916
2917   To list just some:
2918   - A lot of the metadata is JSON, allowing for easier extension
2919   - Max 32 key-slots per default
2920   - Better protection for bad passphrases now available with Argon2
2921   - Authenticated encryption 
2922   - The LUKS2 header is less vulnerable to corruption and has a 2nd copy
2923   
2924   
2925   * **10.3 Why does LUKS2 need so much memory?**
2926
2927   LUKS2 uses Argon2 instead of PBKDF2.  That causes the increase in memory. 
2928   See next item.
2929
2930
2931   * **10.4  Why use Argon2 in LUKS 2 instead of PBKDF2?**
2932
2933   LUKS tries to be secure with not-so-good passwords.  Bad passwords need to
2934   be protected in some way against an attacker that just tries all possible
2935   combinations.  (For good passwords, you can just wait for the attacker to
2936   die of old age...) The situation with LUKS is not quite the same as with a
2937   password stored in a database, but there are similarities.
2938
2939   LUKS does not store passwords on disk.  Instead, the passwords are used to
2940   decrypt the volume-key with it and that one is stored on disk in encrypted
2941   form.  If you have a good password, with, say, more than 80 bits of
2942   entropy, you could just put the password through a single crypto-hash (to
2943   turn it into something that can be used as a key) and that would be secure. 
2944   This is what plain dm-crypt does.
2945
2946   If the password has lower entropy, you want to make this process cost some
2947   effort, so that each try takes time and resources and slows the attacker
2948   down.  LUKS1 uses PBKDF2 for that, adding an iteration count and a salt. 
2949   The iteration count is per default set to that it takes 1 second per try on
2950   the CPU of the device where the respective passphrase was set.  The salt is
2951   there to prevent precomputation.
2952
2953   The problem with that is that if you use a graphics card, you can massively
2954   speed up these computations as PBKDF2 needs very little memory to compute
2955   it.  A graphics card is (grossly simplified) a mass of small CPUs with some
2956   small very fast local memory per CPU and a large slow memory (the 4/6/8 GB
2957   a current card may have).  If you can keep a computation in the small,
2958   CPU-local memory, you can gain a speed factor of 1000 or more when trying
2959   passwords with PBKDF2.
2960
2961   Argon2 was created to address this problem.  It adds a "large memory
2962   property" where computing the result with less memory than the memory
2963   parameter requires is massively (exponentially) slowed down.  That means,
2964   if you set, for example, 4GB of memory, computing Argon2 on a graphics card
2965   with around 100kB of memory per "CPU" makes no sense at all because it is
2966   far too slow.  An attacker has hence to use real CPUs and furthermore is
2967   limited by main memory bandwidth.
2968
2969   Hence the large amount of memory used is a security feature and should not
2970   be turned off or reduced.  If you really (!) understand what you are doing
2971   and can assure good passwords, you can either go back to PBKDF2 or set a
2972   low amount of memory used for Argon2 when creating the header.
2973
2974
2975   * **10.5 LUKS2 is insecure! It uses less memory than the Argon2 RFC say!**
2976
2977   Well, not really.  The RFC recommends 6GiB of memory for use with disk
2978   encryption.  That is a bit insane and something clearly went wrong in the
2979   standardization process here.  First, that makes Argon2 unusable on any 32
2980   bit Linux and that is clearly a bad thing.  Second, there are many small
2981   Linux devices around that do not have 6GiB of RAM in the first place.  For
2982   example, the current Raspberry Pi has 1GB, 2GB or 4GB of RAM, and with the
2983   RFC recommendations, none of these could compute Argon2 hashes.
2984
2985   Hence LUKS2 uses a more real-world approach.  Iteration is set to a
2986   minimum of 4 because there are some theoretical attacks that work up to an
2987   iteration count of 3.  The thread parameter is set to 4.  To achieve 2
2988   second/slot unlock time, LUKS2 adjusts the memory parameter down if
2989   needed.  In the other direction, it will respect available memory and not
2990   exceed it.  On a current PC, the memory parameter will be somewhere around
2991   1GB, which should be quite generous.  The minimum I was able to set in an
2992   experiment with "-i 1" was 400kB of memory and that is too low to be
2993   secure.  A Raspberry Pi would probably end up somewhere around 50MB (have
2994   not tried it) and that should still be plenty.
2995
2996   That said, if you have a good, high-entropy passphrase, LUKS2 is secure
2997   with any memory parameter.
2998
2999
3000   * **10.6 How does re-encryption store data while it is running?**
3001
3002   All metadata necessary to perform a recovery of said segment (in case of 
3003   crash) is stored in the LUKS2 metadata area. No matter if the LUKS2 
3004   reencryption was run in online or offline mode.
3005
3006   
3007   * **10.7 What do I do if re-encryption crashes?**
3008   
3009   In case of a reencryption application crash, try to close the original
3010   device via following command first: 
3011 ```
3012     cryptsetup close <my_crypt_device>. 
3013 ```
3014   Cryptsetup assesses if it's safe to teardown the reencryption device stack
3015   or not.  It will also cut off I/O (via dm-error mapping) to current
3016   hotzone segment (to make later recovery possible).  If it can't be torn
3017   down, i.e.  due to a mounted fs, you must unmount the filesystem first. 
3018   Never try to tear down reencryption dm devices manually using e.g. 
3019   dmsetup tool, at least not unless cryptsetup says it's safe to do so.  It
3020   could damage the data beyond repair.
3021
3022
3023   * **10.8 Do I need to enter two passphrases to recover a crashed re-encryption?** 
3024
3025   Cryptsetup (command line utility) expects the passphrases to be identical
3026   for the keyslot containing old volume key and for the keyslot containing
3027   new one.  So the recovery happens during normal the "cryptsetup open" 
3028   operation or the equivalent during boot.
3029
3030   Re-encryption recovery can be also performed in offline mode by 
3031   the "cryptsetup repair" command.
3032
3033
3034   * **10.9 What is an unbound keyslot and what is it used for?**
3035
3036   Quite simply, an 'unbound key' is an independent 'key' stored in a luks2 
3037   keyslot that cannot be used to unlock a LUKS2 data device. More specifically, 
3038   an 'unbound key' or 'unbound luks2 keyslot' contains a secret that is not
3039   currently associated with any data/crypt segment (encrypted area) in the 
3040   LUKS2 'Segments' section (displayed by luksDump).
3041
3042   This is a bit of a more general idea. It basically allows one to use a
3043   keyslot as a container for a key to be used in other things than decrypting
3044   a data segment.
3045
3046   As of April 2020, the following uses are defined:
3047
3048   1) LUKS2 re-encryption. The new volume key is stored in an unbound keyslot 
3049      which becomes a regular LUKS2 keyslot later when re-encryption is 
3050      finished.
3051   
3052   2) Somewhat similar is the use with a wrapped key scheme (e.g. with the 
3053      paes cipher). In this case, the VK (Volume Key) stored in a keyslot 
3054      is an encrypted binary binary blob. The KEK (Key Encryption Key) for 
3055      that blob may be refreshed (Note that this KEK is not managed by 
3056      cryptsetup!) and the binary blob gets changed. The KEK refresh process 
3057      uses an 'unbound keyslot'. First the future effective VK is placed 
3058      in the unbound keyslot and later it gets turned into the new real VK 
3059      (and bound to the respective crypt segment).
3060
3061
3062   * **10.10 What about the size of the LUKS2 header**?
3063
3064   While the LUKS1 header has a fixed size that is determined by the cipher
3065   spec (see Item 6.12), LUKS2 is more variable. The default size is 16MB,
3066   but it can be adjusted on creation by using the --luks2-metadata-size 
3067   and --luks2-keyslots-size options. Refer to the man-page for details.
3068   While adjusting the size in an existing LUKS2 container is possible,
3069   it is somewhat complicated and risky. My advice is to do a backup, 
3070   recreate the container with changed parameters and restore that backup.
3071
3072
3073   * **10.11 Does LUKS2 store metadata anywhere except in the header?**
3074  
3075   It does not. But note that if you use the experimental integrity support,
3076   there will be an integrity header as well at the start of the data area 
3077   and things  get a bit more complicated. All metadata will still be at the 
3078   start of the device, nothing gets stored somewhere in the middle or at 
3079   the end. 
3080   
3081   * **10.12 What is a LUKS2 Token?**
3082
3083   A LUKS2 token is an object that describes "how to get a passphrase or 
3084   key" to unlock particular keyslot. A LUKS2 token is stored as json data 
3085   in the LUKS2 header. The token can be related to all keyslots or a 
3086   specific one. As the token is stored in JSON formay it is text by 
3087   default but binary data can be encoded into it according to the JSON 
3088   conventions.
3089  
3090   Documentation on the last changes to LUKS2 tokens can be found in the 
3091   release notes. As of version 2.4 of cryptsetup, there are significant 
3092   features. The standard documentation for working with tokens is 
3093   in the luks2 reference available as PDF on the project page.
3094
3095
3096 # 11. References and Further Reading
3097
3098
3099   * **Purpose of this Section**
3100
3101   The purpose of this section is to collect references to all materials
3102   that do not fit the FAQ but are relevant in some fashion.  This can be
3103   core topics like the LUKS spec or disk encryption, but it can also be
3104   more tangential, like secure storage management or cryptography used in
3105   LUKS.  It should still have relevance to cryptsetup and its
3106   applications.
3107
3108   If you want to see something added here, send email to the maintainer
3109   (or the cryptsetup mailing list) giving an URL, a description (1-3 lines
3110   preferred) and a section to put it in.  You can also propose new
3111   sections.
3112
3113   At this time I would like to limit the references to things that are
3114   available on the web.
3115
3116   * **Specifications**
3117
3118   - LUKS on-disk format spec: See Item 1.2
3119
3120   * **Other Documentation**
3121   
3122   - Arch Linux on LUKS, LVM and full-disk encryption: 
3123     https://wiki.archlinux.org/index.php/Dm-crypt/Encrypting_an_entire_system
3124
3125   * **Code Examples**
3126
3127   - Some code examples are in the source package under docs/examples
3128
3129   - LUKS AF Splitter in Ruby by John Lane: https://rubygems.org/gems/afsplitter
3130
3131   * **Brute-forcing passphrases**
3132
3133   - http://news.electricalchemy.net/2009/10/password-cracking-in-cloud-part-5.html
3134
3135   - https://it.slashdot.org/story/12/12/05/0623215/new-25-gpu-monster-devours-strong-passwords-in-minutes
3136
3137   * **Tools**
3138
3139   * **SSD and Flash Disk Related**
3140
3141   * **Disk Encryption**
3142
3143   * **Attacks Against Disk Encryption**
3144
3145   * **Risk Management as Relevant for Disk Encryption**
3146
3147   * **Cryptography**
3148
3149   * **Secure Storage**
3150
3151
3152 # A. Contributors
3153 In no particular order:
3154
3155   - Arno Wagner
3156
3157   - Milan Broz
3158
3159 ___