1=====================================
2Filesystem-level encryption (fscrypt)
3=====================================
4
5Introduction
6============
7
8fscrypt is a library which filesystems can hook into to support
9transparent encryption of files and directories.
10
11Note: "fscrypt" in this document refers to the kernel-level portion,
12implemented in ``fs/crypto/``, as opposed to the userspace tool
13`fscrypt <https://github.com/google/fscrypt>`_.  This document only
14covers the kernel-level portion.  For command-line examples of how to
15use encryption, see the documentation for the userspace tool `fscrypt
16<https://github.com/google/fscrypt>`_.  Also, it is recommended to use
17the fscrypt userspace tool, or other existing userspace tools such as
18`fscryptctl <https://github.com/google/fscryptctl>`_ or `Android's key
19management system
20<https://source.android.com/security/encryption/file-based>`_, over
21using the kernel's API directly.  Using existing tools reduces the
22chance of introducing your own security bugs.  (Nevertheless, for
23completeness this documentation covers the kernel's API anyway.)
24
25Unlike dm-crypt, fscrypt operates at the filesystem level rather than
26at the block device level.  This allows it to encrypt different files
27with different keys and to have unencrypted files on the same
28filesystem.  This is useful for multi-user systems where each user's
29data-at-rest needs to be cryptographically isolated from the others.
30However, except for filenames, fscrypt does not encrypt filesystem
31metadata.
32
33Unlike eCryptfs, which is a stacked filesystem, fscrypt is integrated
34directly into supported filesystems --- currently ext4, F2FS, UBIFS,
35and CephFS.  This allows encrypted files to be read and written
36without caching both the decrypted and encrypted pages in the
37pagecache, thereby nearly halving the memory used and bringing it in
38line with unencrypted files.  Similarly, half as many dentries and
39inodes are needed.  eCryptfs also limits encrypted filenames to 143
40bytes, causing application compatibility issues; fscrypt allows the
41full 255 bytes (NAME_MAX).  Finally, unlike eCryptfs, the fscrypt API
42can be used by unprivileged users, with no need to mount anything.
43
44fscrypt does not support encrypting files in-place.  Instead, it
45supports marking an empty directory as encrypted.  Then, after
46userspace provides the key, all regular files, directories, and
47symbolic links created in that directory tree are transparently
48encrypted.
49
50Threat model
51============
52
53Offline attacks
54---------------
55
56Provided that userspace chooses a strong encryption key, fscrypt
57protects the confidentiality of file contents and filenames in the
58event of a single point-in-time permanent offline compromise of the
59block device content.  fscrypt does not protect the confidentiality of
60non-filename metadata, e.g. file sizes, file permissions, file
61timestamps, and extended attributes.  Also, the existence and location
62of holes (unallocated blocks which logically contain all zeroes) in
63files is not protected.
64
65fscrypt is not guaranteed to protect confidentiality or authenticity
66if an attacker is able to manipulate the filesystem offline prior to
67an authorized user later accessing the filesystem.
68
69Online attacks
70--------------
71
72fscrypt (and storage encryption in general) can only provide limited
73protection, if any at all, against online attacks.  In detail:
74
75Side-channel attacks
76~~~~~~~~~~~~~~~~~~~~
77
78fscrypt is only resistant to side-channel attacks, such as timing or
79electromagnetic attacks, to the extent that the underlying Linux
80Cryptographic API algorithms or inline encryption hardware are.  If a
81vulnerable algorithm is used, such as a table-based implementation of
82AES, it may be possible for an attacker to mount a side channel attack
83against the online system.  Side channel attacks may also be mounted
84against applications consuming decrypted data.
85
86Unauthorized file access
87~~~~~~~~~~~~~~~~~~~~~~~~
88
89After an encryption key has been added, fscrypt does not hide the
90plaintext file contents or filenames from other users on the same
91system.  Instead, existing access control mechanisms such as file mode
92bits, POSIX ACLs, LSMs, or namespaces should be used for this purpose.
93
94(For the reasoning behind this, understand that while the key is
95added, the confidentiality of the data, from the perspective of the
96system itself, is *not* protected by the mathematical properties of
97encryption but rather only by the correctness of the kernel.
98Therefore, any encryption-specific access control checks would merely
99be enforced by kernel *code* and therefore would be largely redundant
100with the wide variety of access control mechanisms already available.)
101
102Kernel memory compromise
103~~~~~~~~~~~~~~~~~~~~~~~~
104
105An attacker who compromises the system enough to read from arbitrary
106memory, e.g. by mounting a physical attack or by exploiting a kernel
107security vulnerability, can compromise all encryption keys that are
108currently in use.
109
110However, fscrypt allows encryption keys to be removed from the kernel,
111which may protect them from later compromise.
112
113In more detail, the FS_IOC_REMOVE_ENCRYPTION_KEY ioctl (or the
114FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS ioctl) can wipe a master
115encryption key from kernel memory.  If it does so, it will also try to
116evict all cached inodes which had been "unlocked" using the key,
117thereby wiping their per-file keys and making them once again appear
118"locked", i.e. in ciphertext or encrypted form.
119
120However, these ioctls have some limitations:
121
122- Per-file keys for in-use files will *not* be removed or wiped.
123  Therefore, for maximum effect, userspace should close the relevant
124  encrypted files and directories before removing a master key, as
125  well as kill any processes whose working directory is in an affected
126  encrypted directory.
127
128- The kernel cannot magically wipe copies of the master key(s) that
129  userspace might have as well.  Therefore, userspace must wipe all
130  copies of the master key(s) it makes as well; normally this should
131  be done immediately after FS_IOC_ADD_ENCRYPTION_KEY, without waiting
132  for FS_IOC_REMOVE_ENCRYPTION_KEY.  Naturally, the same also applies
133  to all higher levels in the key hierarchy.  Userspace should also
134  follow other security precautions such as mlock()ing memory
135  containing keys to prevent it from being swapped out.
136
137- In general, decrypted contents and filenames in the kernel VFS
138  caches are freed but not wiped.  Therefore, portions thereof may be
139  recoverable from freed memory, even after the corresponding key(s)
140  were wiped.  To partially solve this, you can add init_on_free=1 to
141  your kernel command line.  However, this has a performance cost.
142
143- Secret keys might still exist in CPU registers, in crypto
144  accelerator hardware (if used by the crypto API to implement any of
145  the algorithms), or in other places not explicitly considered here.
146
147Limitations of v1 policies
148~~~~~~~~~~~~~~~~~~~~~~~~~~
149
150v1 encryption policies have some weaknesses with respect to online
151attacks:
152
153- There is no verification that the provided master key is correct.
154  Therefore, a malicious user can temporarily associate the wrong key
155  with another user's encrypted files to which they have read-only
156  access.  Because of filesystem caching, the wrong key will then be
157  used by the other user's accesses to those files, even if the other
158  user has the correct key in their own keyring.  This violates the
159  meaning of "read-only access".
160
161- A compromise of a per-file key also compromises the master key from
162  which it was derived.
163
164- Non-root users cannot securely remove encryption keys.
165
166All the above problems are fixed with v2 encryption policies.  For
167this reason among others, it is recommended to use v2 encryption
168policies on all new encrypted directories.
169
170Key hierarchy
171=============
172
173Master Keys
174-----------
175
176Each encrypted directory tree is protected by a *master key*.  Master
177keys can be up to 64 bytes long, and must be at least as long as the
178greater of the security strength of the contents and filenames
179encryption modes being used.  For example, if any AES-256 mode is
180used, the master key must be at least 256 bits, i.e. 32 bytes.  A
181stricter requirement applies if the key is used by a v1 encryption
182policy and AES-256-XTS is used; such keys must be 64 bytes.
183
184To "unlock" an encrypted directory tree, userspace must provide the
185appropriate master key.  There can be any number of master keys, each
186of which protects any number of directory trees on any number of
187filesystems.
188
189Master keys must be real cryptographic keys, i.e. indistinguishable
190from random bytestrings of the same length.  This implies that users
191**must not** directly use a password as a master key, zero-pad a
192shorter key, or repeat a shorter key.  Security cannot be guaranteed
193if userspace makes any such error, as the cryptographic proofs and
194analysis would no longer apply.
195
196Instead, users should generate master keys either using a
197cryptographically secure random number generator, or by using a KDF
198(Key Derivation Function).  The kernel does not do any key stretching;
199therefore, if userspace derives the key from a low-entropy secret such
200as a passphrase, it is critical that a KDF designed for this purpose
201be used, such as scrypt, PBKDF2, or Argon2.
202
203Key derivation function
204-----------------------
205
206With one exception, fscrypt never uses the master key(s) for
207encryption directly.  Instead, they are only used as input to a KDF
208(Key Derivation Function) to derive the actual keys.
209
210The KDF used for a particular master key differs depending on whether
211the key is used for v1 encryption policies or for v2 encryption
212policies.  Users **must not** use the same key for both v1 and v2
213encryption policies.  (No real-world attack is currently known on this
214specific case of key reuse, but its security cannot be guaranteed
215since the cryptographic proofs and analysis would no longer apply.)
216
217For v1 encryption policies, the KDF only supports deriving per-file
218encryption keys.  It works by encrypting the master key with
219AES-128-ECB, using the file's 16-byte nonce as the AES key.  The
220resulting ciphertext is used as the derived key.  If the ciphertext is
221longer than needed, then it is truncated to the needed length.
222
223For v2 encryption policies, the KDF is HKDF-SHA512.  The master key is
224passed as the "input keying material", no salt is used, and a distinct
225"application-specific information string" is used for each distinct
226key to be derived.  For example, when a per-file encryption key is
227derived, the application-specific information string is the file's
228nonce prefixed with "fscrypt\\0" and a context byte.  Different
229context bytes are used for other types of derived keys.
230
231HKDF-SHA512 is preferred to the original AES-128-ECB based KDF because
232HKDF is more flexible, is nonreversible, and evenly distributes
233entropy from the master key.  HKDF is also standardized and widely
234used by other software, whereas the AES-128-ECB based KDF is ad-hoc.
235
236Per-file encryption keys
237------------------------
238
239Since each master key can protect many files, it is necessary to
240"tweak" the encryption of each file so that the same plaintext in two
241files doesn't map to the same ciphertext, or vice versa.  In most
242cases, fscrypt does this by deriving per-file keys.  When a new
243encrypted inode (regular file, directory, or symlink) is created,
244fscrypt randomly generates a 16-byte nonce and stores it in the
245inode's encryption xattr.  Then, it uses a KDF (as described in `Key
246derivation function`_) to derive the file's key from the master key
247and nonce.
248
249Key derivation was chosen over key wrapping because wrapped keys would
250require larger xattrs which would be less likely to fit in-line in the
251filesystem's inode table, and there didn't appear to be any
252significant advantages to key wrapping.  In particular, currently
253there is no requirement to support unlocking a file with multiple
254alternative master keys or to support rotating master keys.  Instead,
255the master keys may be wrapped in userspace, e.g. as is done by the
256`fscrypt <https://github.com/google/fscrypt>`_ tool.
257
258DIRECT_KEY policies
259-------------------
260
261The Adiantum encryption mode (see `Encryption modes and usage`_) is
262suitable for both contents and filenames encryption, and it accepts
263long IVs --- long enough to hold both an 8-byte data unit index and a
26416-byte per-file nonce.  Also, the overhead of each Adiantum key is
265greater than that of an AES-256-XTS key.
266
267Therefore, to improve performance and save memory, for Adiantum a
268"direct key" configuration is supported.  When the user has enabled
269this by setting FSCRYPT_POLICY_FLAG_DIRECT_KEY in the fscrypt policy,
270per-file encryption keys are not used.  Instead, whenever any data
271(contents or filenames) is encrypted, the file's 16-byte nonce is
272included in the IV.  Moreover:
273
274- For v1 encryption policies, the encryption is done directly with the
275  master key.  Because of this, users **must not** use the same master
276  key for any other purpose, even for other v1 policies.
277
278- For v2 encryption policies, the encryption is done with a per-mode
279  key derived using the KDF.  Users may use the same master key for
280  other v2 encryption policies.
281
282IV_INO_LBLK_64 policies
283-----------------------
284
285When FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 is set in the fscrypt policy,
286the encryption keys are derived from the master key, encryption mode
287number, and filesystem UUID.  This normally results in all files
288protected by the same master key sharing a single contents encryption
289key and a single filenames encryption key.  To still encrypt different
290files' data differently, inode numbers are included in the IVs.
291Consequently, shrinking the filesystem may not be allowed.
292
293This format is optimized for use with inline encryption hardware
294compliant with the UFS standard, which supports only 64 IV bits per
295I/O request and may have only a small number of keyslots.
296
297IV_INO_LBLK_32 policies
298-----------------------
299
300IV_INO_LBLK_32 policies work like IV_INO_LBLK_64, except that for
301IV_INO_LBLK_32, the inode number is hashed with SipHash-2-4 (where the
302SipHash key is derived from the master key) and added to the file data
303unit index mod 2^32 to produce a 32-bit IV.
304
305This format is optimized for use with inline encryption hardware
306compliant with the eMMC v5.2 standard, which supports only 32 IV bits
307per I/O request and may have only a small number of keyslots.  This
308format results in some level of IV reuse, so it should only be used
309when necessary due to hardware limitations.
310
311Key identifiers
312---------------
313
314For master keys used for v2 encryption policies, a unique 16-byte "key
315identifier" is also derived using the KDF.  This value is stored in
316the clear, since it is needed to reliably identify the key itself.
317
318Dirhash keys
319------------
320
321For directories that are indexed using a secret-keyed dirhash over the
322plaintext filenames, the KDF is also used to derive a 128-bit
323SipHash-2-4 key per directory in order to hash filenames.  This works
324just like deriving a per-file encryption key, except that a different
325KDF context is used.  Currently, only casefolded ("case-insensitive")
326encrypted directories use this style of hashing.
327
328Encryption modes and usage
329==========================
330
331fscrypt allows one encryption mode to be specified for file contents
332and one encryption mode to be specified for filenames.  Different
333directory trees are permitted to use different encryption modes.
334
335Supported modes
336---------------
337
338Currently, the following pairs of encryption modes are supported:
339
340- AES-256-XTS for contents and AES-256-CBC-CTS for filenames
341- AES-256-XTS for contents and AES-256-HCTR2 for filenames
342- Adiantum for both contents and filenames
343- AES-128-CBC-ESSIV for contents and AES-128-CBC-CTS for filenames
344- SM4-XTS for contents and SM4-CBC-CTS for filenames
345
346Note: in the API, "CBC" means CBC-ESSIV, and "CTS" means CBC-CTS.
347So, for example, FSCRYPT_MODE_AES_256_CTS means AES-256-CBC-CTS.
348
349Authenticated encryption modes are not currently supported because of
350the difficulty of dealing with ciphertext expansion.  Therefore,
351contents encryption uses a block cipher in `XTS mode
352<https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS>`_ or
353`CBC-ESSIV mode
354<https://en.wikipedia.org/wiki/Disk_encryption_theory#Encrypted_salt-sector_initialization_vector_(ESSIV)>`_,
355or a wide-block cipher.  Filenames encryption uses a
356block cipher in `CBC-CTS mode
357<https://en.wikipedia.org/wiki/Ciphertext_stealing>`_ or a wide-block
358cipher.
359
360The (AES-256-XTS, AES-256-CBC-CTS) pair is the recommended default.
361It is also the only option that is *guaranteed* to always be supported
362if the kernel supports fscrypt at all; see `Kernel config options`_.
363
364The (AES-256-XTS, AES-256-HCTR2) pair is also a good choice that
365upgrades the filenames encryption to use a wide-block cipher.  (A
366*wide-block cipher*, also called a tweakable super-pseudorandom
367permutation, has the property that changing one bit scrambles the
368entire result.)  As described in `Filenames encryption`_, a wide-block
369cipher is the ideal mode for the problem domain, though CBC-CTS is the
370"least bad" choice among the alternatives.  For more information about
371HCTR2, see `the HCTR2 paper <https://eprint.iacr.org/2021/1441.pdf>`_.
372
373Adiantum is recommended on systems where AES is too slow due to lack
374of hardware acceleration for AES.  Adiantum is a wide-block cipher
375that uses XChaCha12 and AES-256 as its underlying components.  Most of
376the work is done by XChaCha12, which is much faster than AES when AES
377acceleration is unavailable.  For more information about Adiantum, see
378`the Adiantum paper <https://eprint.iacr.org/2018/720.pdf>`_.
379
380The (AES-128-CBC-ESSIV, AES-128-CBC-CTS) pair exists only to support
381systems whose only form of AES acceleration is an off-CPU crypto
382accelerator such as CAAM or CESA that does not support XTS.
383
384The remaining mode pairs are the "national pride ciphers":
385
386- (SM4-XTS, SM4-CBC-CTS)
387
388Generally speaking, these ciphers aren't "bad" per se, but they
389receive limited security review compared to the usual choices such as
390AES and ChaCha.  They also don't bring much new to the table.  It is
391suggested to only use these ciphers where their use is mandated.
392
393Kernel config options
394---------------------
395
396Enabling fscrypt support (CONFIG_FS_ENCRYPTION) automatically pulls in
397only the basic support from the crypto API needed to use AES-256-XTS
398and AES-256-CBC-CTS encryption.  For optimal performance, it is
399strongly recommended to also enable any available platform-specific
400kconfig options that provide acceleration for the algorithm(s) you
401wish to use.  Support for any "non-default" encryption modes typically
402requires extra kconfig options as well.
403
404Below, some relevant options are listed by encryption mode.  Note,
405acceleration options not listed below may be available for your
406platform; refer to the kconfig menus.  File contents encryption can
407also be configured to use inline encryption hardware instead of the
408kernel crypto API (see `Inline encryption support`_); in that case,
409the file contents mode doesn't need to supported in the kernel crypto
410API, but the filenames mode still does.
411
412- AES-256-XTS and AES-256-CBC-CTS
413    - Recommended:
414        - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
415        - x86: CONFIG_CRYPTO_AES_NI_INTEL
416
417- AES-256-HCTR2
418    - Mandatory:
419        - CONFIG_CRYPTO_HCTR2
420    - Recommended:
421        - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
422        - arm64: CONFIG_CRYPTO_POLYVAL_ARM64_CE
423        - x86: CONFIG_CRYPTO_AES_NI_INTEL
424        - x86: CONFIG_CRYPTO_POLYVAL_CLMUL_NI
425
426- Adiantum
427    - Mandatory:
428        - CONFIG_CRYPTO_ADIANTUM
429    - Recommended:
430        - arm32: CONFIG_CRYPTO_NHPOLY1305_NEON
431        - arm64: CONFIG_CRYPTO_NHPOLY1305_NEON
432        - x86: CONFIG_CRYPTO_NHPOLY1305_SSE2
433        - x86: CONFIG_CRYPTO_NHPOLY1305_AVX2
434
435- AES-128-CBC-ESSIV and AES-128-CBC-CTS:
436    - Mandatory:
437        - CONFIG_CRYPTO_ESSIV
438        - CONFIG_CRYPTO_SHA256 or another SHA-256 implementation
439    - Recommended:
440        - AES-CBC acceleration
441
442fscrypt also uses HMAC-SHA512 for key derivation, so enabling SHA-512
443acceleration is recommended:
444
445- SHA-512
446    - Recommended:
447        - arm64: CONFIG_CRYPTO_SHA512_ARM64_CE
448        - x86: CONFIG_CRYPTO_SHA512_SSSE3
449
450Contents encryption
451-------------------
452
453For contents encryption, each file's contents is divided into "data
454units".  Each data unit is encrypted independently.  The IV for each
455data unit incorporates the zero-based index of the data unit within
456the file.  This ensures that each data unit within a file is encrypted
457differently, which is essential to prevent leaking information.
458
459Note: the encryption depending on the offset into the file means that
460operations like "collapse range" and "insert range" that rearrange the
461extent mapping of files are not supported on encrypted files.
462
463There are two cases for the sizes of the data units:
464
465* Fixed-size data units.  This is how all filesystems other than UBIFS
466  work.  A file's data units are all the same size; the last data unit
467  is zero-padded if needed.  By default, the data unit size is equal
468  to the filesystem block size.  On some filesystems, users can select
469  a sub-block data unit size via the ``log2_data_unit_size`` field of
470  the encryption policy; see `FS_IOC_SET_ENCRYPTION_POLICY`_.
471
472* Variable-size data units.  This is what UBIFS does.  Each "UBIFS
473  data node" is treated as a crypto data unit.  Each contains variable
474  length, possibly compressed data, zero-padded to the next 16-byte
475  boundary.  Users cannot select a sub-block data unit size on UBIFS.
476
477In the case of compression + encryption, the compressed data is
478encrypted.  UBIFS compression works as described above.  f2fs
479compression works a bit differently; it compresses a number of
480filesystem blocks into a smaller number of filesystem blocks.
481Therefore a f2fs-compressed file still uses fixed-size data units, and
482it is encrypted in a similar way to a file containing holes.
483
484As mentioned in `Key hierarchy`_, the default encryption setting uses
485per-file keys.  In this case, the IV for each data unit is simply the
486index of the data unit in the file.  However, users can select an
487encryption setting that does not use per-file keys.  For these, some
488kind of file identifier is incorporated into the IVs as follows:
489
490- With `DIRECT_KEY policies`_, the data unit index is placed in bits
491  0-63 of the IV, and the file's nonce is placed in bits 64-191.
492
493- With `IV_INO_LBLK_64 policies`_, the data unit index is placed in
494  bits 0-31 of the IV, and the file's inode number is placed in bits
495  32-63.  This setting is only allowed when data unit indices and
496  inode numbers fit in 32 bits.
497
498- With `IV_INO_LBLK_32 policies`_, the file's inode number is hashed
499  and added to the data unit index.  The resulting value is truncated
500  to 32 bits and placed in bits 0-31 of the IV.  This setting is only
501  allowed when data unit indices and inode numbers fit in 32 bits.
502
503The byte order of the IV is always little endian.
504
505If the user selects FSCRYPT_MODE_AES_128_CBC for the contents mode, an
506ESSIV layer is automatically included.  In this case, before the IV is
507passed to AES-128-CBC, it is encrypted with AES-256 where the AES-256
508key is the SHA-256 hash of the file's contents encryption key.
509
510Filenames encryption
511--------------------
512
513For filenames, each full filename is encrypted at once.  Because of
514the requirements to retain support for efficient directory lookups and
515filenames of up to 255 bytes, the same IV is used for every filename
516in a directory.
517
518However, each encrypted directory still uses a unique key, or
519alternatively has the file's nonce (for `DIRECT_KEY policies`_) or
520inode number (for `IV_INO_LBLK_64 policies`_) included in the IVs.
521Thus, IV reuse is limited to within a single directory.
522
523With CBC-CTS, the IV reuse means that when the plaintext filenames share a
524common prefix at least as long as the cipher block size (16 bytes for AES), the
525corresponding encrypted filenames will also share a common prefix.  This is
526undesirable.  Adiantum and HCTR2 do not have this weakness, as they are
527wide-block encryption modes.
528
529All supported filenames encryption modes accept any plaintext length
530>= 16 bytes; cipher block alignment is not required.  However,
531filenames shorter than 16 bytes are NUL-padded to 16 bytes before
532being encrypted.  In addition, to reduce leakage of filename lengths
533via their ciphertexts, all filenames are NUL-padded to the next 4, 8,
53416, or 32-byte boundary (configurable).  32 is recommended since this
535provides the best confidentiality, at the cost of making directory
536entries consume slightly more space.  Note that since NUL (``\0``) is
537not otherwise a valid character in filenames, the padding will never
538produce duplicate plaintexts.
539
540Symbolic link targets are considered a type of filename and are
541encrypted in the same way as filenames in directory entries, except
542that IV reuse is not a problem as each symlink has its own inode.
543
544User API
545========
546
547Setting an encryption policy
548----------------------------
549
550FS_IOC_SET_ENCRYPTION_POLICY
551~~~~~~~~~~~~~~~~~~~~~~~~~~~~
552
553The FS_IOC_SET_ENCRYPTION_POLICY ioctl sets an encryption policy on an
554empty directory or verifies that a directory or regular file already
555has the specified encryption policy.  It takes in a pointer to
556struct fscrypt_policy_v1 or struct fscrypt_policy_v2, defined as
557follows::
558
559    #define FSCRYPT_POLICY_V1               0
560    #define FSCRYPT_KEY_DESCRIPTOR_SIZE     8
561    struct fscrypt_policy_v1 {
562            __u8 version;
563            __u8 contents_encryption_mode;
564            __u8 filenames_encryption_mode;
565            __u8 flags;
566            __u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
567    };
568    #define fscrypt_policy  fscrypt_policy_v1
569
570    #define FSCRYPT_POLICY_V2               2
571    #define FSCRYPT_KEY_IDENTIFIER_SIZE     16
572    struct fscrypt_policy_v2 {
573            __u8 version;
574            __u8 contents_encryption_mode;
575            __u8 filenames_encryption_mode;
576            __u8 flags;
577            __u8 log2_data_unit_size;
578            __u8 __reserved[3];
579            __u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
580    };
581
582This structure must be initialized as follows:
583
584- ``version`` must be FSCRYPT_POLICY_V1 (0) if
585  struct fscrypt_policy_v1 is used or FSCRYPT_POLICY_V2 (2) if
586  struct fscrypt_policy_v2 is used. (Note: we refer to the original
587  policy version as "v1", though its version code is really 0.)
588  For new encrypted directories, use v2 policies.
589
590- ``contents_encryption_mode`` and ``filenames_encryption_mode`` must
591  be set to constants from ``<linux/fscrypt.h>`` which identify the
592  encryption modes to use.  If unsure, use FSCRYPT_MODE_AES_256_XTS
593  (1) for ``contents_encryption_mode`` and FSCRYPT_MODE_AES_256_CTS
594  (4) for ``filenames_encryption_mode``.  For details, see `Encryption
595  modes and usage`_.
596
597  v1 encryption policies only support three combinations of modes:
598  (FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS),
599  (FSCRYPT_MODE_AES_128_CBC, FSCRYPT_MODE_AES_128_CTS), and
600  (FSCRYPT_MODE_ADIANTUM, FSCRYPT_MODE_ADIANTUM).  v2 policies support
601  all combinations documented in `Supported modes`_.
602
603- ``flags`` contains optional flags from ``<linux/fscrypt.h>``:
604
605  - FSCRYPT_POLICY_FLAGS_PAD_*: The amount of NUL padding to use when
606    encrypting filenames.  If unsure, use FSCRYPT_POLICY_FLAGS_PAD_32
607    (0x3).
608  - FSCRYPT_POLICY_FLAG_DIRECT_KEY: See `DIRECT_KEY policies`_.
609  - FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64: See `IV_INO_LBLK_64
610    policies`_.
611  - FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32: See `IV_INO_LBLK_32
612    policies`_.
613
614  v1 encryption policies only support the PAD_* and DIRECT_KEY flags.
615  The other flags are only supported by v2 encryption policies.
616
617  The DIRECT_KEY, IV_INO_LBLK_64, and IV_INO_LBLK_32 flags are
618  mutually exclusive.
619
620- ``log2_data_unit_size`` is the log2 of the data unit size in bytes,
621  or 0 to select the default data unit size.  The data unit size is
622  the granularity of file contents encryption.  For example, setting
623  ``log2_data_unit_size`` to 12 causes file contents be passed to the
624  underlying encryption algorithm (such as AES-256-XTS) in 4096-byte
625  data units, each with its own IV.
626
627  Not all filesystems support setting ``log2_data_unit_size``.  ext4
628  and f2fs support it since Linux v6.7.  On filesystems that support
629  it, the supported nonzero values are 9 through the log2 of the
630  filesystem block size, inclusively.  The default value of 0 selects
631  the filesystem block size.
632
633  The main use case for ``log2_data_unit_size`` is for selecting a
634  data unit size smaller than the filesystem block size for
635  compatibility with inline encryption hardware that only supports
636  smaller data unit sizes.  ``/sys/block/$disk/queue/crypto/`` may be
637  useful for checking which data unit sizes are supported by a
638  particular system's inline encryption hardware.
639
640  Leave this field zeroed unless you are certain you need it.  Using
641  an unnecessarily small data unit size reduces performance.
642
643- For v2 encryption policies, ``__reserved`` must be zeroed.
644
645- For v1 encryption policies, ``master_key_descriptor`` specifies how
646  to find the master key in a keyring; see `Adding keys`_.  It is up
647  to userspace to choose a unique ``master_key_descriptor`` for each
648  master key.  The e4crypt and fscrypt tools use the first 8 bytes of
649  ``SHA-512(SHA-512(master_key))``, but this particular scheme is not
650  required.  Also, the master key need not be in the keyring yet when
651  FS_IOC_SET_ENCRYPTION_POLICY is executed.  However, it must be added
652  before any files can be created in the encrypted directory.
653
654  For v2 encryption policies, ``master_key_descriptor`` has been
655  replaced with ``master_key_identifier``, which is longer and cannot
656  be arbitrarily chosen.  Instead, the key must first be added using
657  `FS_IOC_ADD_ENCRYPTION_KEY`_.  Then, the ``key_spec.u.identifier``
658  the kernel returned in the struct fscrypt_add_key_arg must
659  be used as the ``master_key_identifier`` in
660  struct fscrypt_policy_v2.
661
662If the file is not yet encrypted, then FS_IOC_SET_ENCRYPTION_POLICY
663verifies that the file is an empty directory.  If so, the specified
664encryption policy is assigned to the directory, turning it into an
665encrypted directory.  After that, and after providing the
666corresponding master key as described in `Adding keys`_, all regular
667files, directories (recursively), and symlinks created in the
668directory will be encrypted, inheriting the same encryption policy.
669The filenames in the directory's entries will be encrypted as well.
670
671Alternatively, if the file is already encrypted, then
672FS_IOC_SET_ENCRYPTION_POLICY validates that the specified encryption
673policy exactly matches the actual one.  If they match, then the ioctl
674returns 0.  Otherwise, it fails with EEXIST.  This works on both
675regular files and directories, including nonempty directories.
676
677When a v2 encryption policy is assigned to a directory, it is also
678required that either the specified key has been added by the current
679user or that the caller has CAP_FOWNER in the initial user namespace.
680(This is needed to prevent a user from encrypting their data with
681another user's key.)  The key must remain added while
682FS_IOC_SET_ENCRYPTION_POLICY is executing.  However, if the new
683encrypted directory does not need to be accessed immediately, then the
684key can be removed right away afterwards.
685
686Note that the ext4 filesystem does not allow the root directory to be
687encrypted, even if it is empty.  Users who want to encrypt an entire
688filesystem with one key should consider using dm-crypt instead.
689
690FS_IOC_SET_ENCRYPTION_POLICY can fail with the following errors:
691
692- ``EACCES``: the file is not owned by the process's uid, nor does the
693  process have the CAP_FOWNER capability in a namespace with the file
694  owner's uid mapped
695- ``EEXIST``: the file is already encrypted with an encryption policy
696  different from the one specified
697- ``EINVAL``: an invalid encryption policy was specified (invalid
698  version, mode(s), or flags; or reserved bits were set); or a v1
699  encryption policy was specified but the directory has the casefold
700  flag enabled (casefolding is incompatible with v1 policies).
701- ``ENOKEY``: a v2 encryption policy was specified, but the key with
702  the specified ``master_key_identifier`` has not been added, nor does
703  the process have the CAP_FOWNER capability in the initial user
704  namespace
705- ``ENOTDIR``: the file is unencrypted and is a regular file, not a
706  directory
707- ``ENOTEMPTY``: the file is unencrypted and is a nonempty directory
708- ``ENOTTY``: this type of filesystem does not implement encryption
709- ``EOPNOTSUPP``: the kernel was not configured with encryption
710  support for filesystems, or the filesystem superblock has not
711  had encryption enabled on it.  (For example, to use encryption on an
712  ext4 filesystem, CONFIG_FS_ENCRYPTION must be enabled in the
713  kernel config, and the superblock must have had the "encrypt"
714  feature flag enabled using ``tune2fs -O encrypt`` or ``mkfs.ext4 -O
715  encrypt``.)
716- ``EPERM``: this directory may not be encrypted, e.g. because it is
717  the root directory of an ext4 filesystem
718- ``EROFS``: the filesystem is readonly
719
720Getting an encryption policy
721----------------------------
722
723Two ioctls are available to get a file's encryption policy:
724
725- `FS_IOC_GET_ENCRYPTION_POLICY_EX`_
726- `FS_IOC_GET_ENCRYPTION_POLICY`_
727
728The extended (_EX) version of the ioctl is more general and is
729recommended to use when possible.  However, on older kernels only the
730original ioctl is available.  Applications should try the extended
731version, and if it fails with ENOTTY fall back to the original
732version.
733
734FS_IOC_GET_ENCRYPTION_POLICY_EX
735~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
736
737The FS_IOC_GET_ENCRYPTION_POLICY_EX ioctl retrieves the encryption
738policy, if any, for a directory or regular file.  No additional
739permissions are required beyond the ability to open the file.  It
740takes in a pointer to struct fscrypt_get_policy_ex_arg,
741defined as follows::
742
743    struct fscrypt_get_policy_ex_arg {
744            __u64 policy_size; /* input/output */
745            union {
746                    __u8 version;
747                    struct fscrypt_policy_v1 v1;
748                    struct fscrypt_policy_v2 v2;
749            } policy; /* output */
750    };
751
752The caller must initialize ``policy_size`` to the size available for
753the policy struct, i.e. ``sizeof(arg.policy)``.
754
755On success, the policy struct is returned in ``policy``, and its
756actual size is returned in ``policy_size``.  ``policy.version`` should
757be checked to determine the version of policy returned.  Note that the
758version code for the "v1" policy is actually 0 (FSCRYPT_POLICY_V1).
759
760FS_IOC_GET_ENCRYPTION_POLICY_EX can fail with the following errors:
761
762- ``EINVAL``: the file is encrypted, but it uses an unrecognized
763  encryption policy version
764- ``ENODATA``: the file is not encrypted
765- ``ENOTTY``: this type of filesystem does not implement encryption,
766  or this kernel is too old to support FS_IOC_GET_ENCRYPTION_POLICY_EX
767  (try FS_IOC_GET_ENCRYPTION_POLICY instead)
768- ``EOPNOTSUPP``: the kernel was not configured with encryption
769  support for this filesystem, or the filesystem superblock has not
770  had encryption enabled on it
771- ``EOVERFLOW``: the file is encrypted and uses a recognized
772  encryption policy version, but the policy struct does not fit into
773  the provided buffer
774
775Note: if you only need to know whether a file is encrypted or not, on
776most filesystems it is also possible to use the FS_IOC_GETFLAGS ioctl
777and check for FS_ENCRYPT_FL, or to use the statx() system call and
778check for STATX_ATTR_ENCRYPTED in stx_attributes.
779
780FS_IOC_GET_ENCRYPTION_POLICY
781~~~~~~~~~~~~~~~~~~~~~~~~~~~~
782
783The FS_IOC_GET_ENCRYPTION_POLICY ioctl can also retrieve the
784encryption policy, if any, for a directory or regular file.  However,
785unlike `FS_IOC_GET_ENCRYPTION_POLICY_EX`_,
786FS_IOC_GET_ENCRYPTION_POLICY only supports the original policy
787version.  It takes in a pointer directly to struct fscrypt_policy_v1
788rather than struct fscrypt_get_policy_ex_arg.
789
790The error codes for FS_IOC_GET_ENCRYPTION_POLICY are the same as those
791for FS_IOC_GET_ENCRYPTION_POLICY_EX, except that
792FS_IOC_GET_ENCRYPTION_POLICY also returns ``EINVAL`` if the file is
793encrypted using a newer encryption policy version.
794
795Getting the per-filesystem salt
796-------------------------------
797
798Some filesystems, such as ext4 and F2FS, also support the deprecated
799ioctl FS_IOC_GET_ENCRYPTION_PWSALT.  This ioctl retrieves a randomly
800generated 16-byte value stored in the filesystem superblock.  This
801value is intended to used as a salt when deriving an encryption key
802from a passphrase or other low-entropy user credential.
803
804FS_IOC_GET_ENCRYPTION_PWSALT is deprecated.  Instead, prefer to
805generate and manage any needed salt(s) in userspace.
806
807Getting a file's encryption nonce
808---------------------------------
809
810Since Linux v5.7, the ioctl FS_IOC_GET_ENCRYPTION_NONCE is supported.
811On encrypted files and directories it gets the inode's 16-byte nonce.
812On unencrypted files and directories, it fails with ENODATA.
813
814This ioctl can be useful for automated tests which verify that the
815encryption is being done correctly.  It is not needed for normal use
816of fscrypt.
817
818Adding keys
819-----------
820
821FS_IOC_ADD_ENCRYPTION_KEY
822~~~~~~~~~~~~~~~~~~~~~~~~~
823
824The FS_IOC_ADD_ENCRYPTION_KEY ioctl adds a master encryption key to
825the filesystem, making all files on the filesystem which were
826encrypted using that key appear "unlocked", i.e. in plaintext form.
827It can be executed on any file or directory on the target filesystem,
828but using the filesystem's root directory is recommended.  It takes in
829a pointer to struct fscrypt_add_key_arg, defined as follows::
830
831    struct fscrypt_add_key_arg {
832            struct fscrypt_key_specifier key_spec;
833            __u32 raw_size;
834            __u32 key_id;
835            __u32 __reserved[8];
836            __u8 raw[];
837    };
838
839    #define FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR        1
840    #define FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER        2
841
842    struct fscrypt_key_specifier {
843            __u32 type;     /* one of FSCRYPT_KEY_SPEC_TYPE_* */
844            __u32 __reserved;
845            union {
846                    __u8 __reserved[32]; /* reserve some extra space */
847                    __u8 descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
848                    __u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
849            } u;
850    };
851
852    struct fscrypt_provisioning_key_payload {
853            __u32 type;
854            __u32 __reserved;
855            __u8 raw[];
856    };
857
858struct fscrypt_add_key_arg must be zeroed, then initialized
859as follows:
860
861- If the key is being added for use by v1 encryption policies, then
862  ``key_spec.type`` must contain FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR, and
863  ``key_spec.u.descriptor`` must contain the descriptor of the key
864  being added, corresponding to the value in the
865  ``master_key_descriptor`` field of struct fscrypt_policy_v1.
866  To add this type of key, the calling process must have the
867  CAP_SYS_ADMIN capability in the initial user namespace.
868
869  Alternatively, if the key is being added for use by v2 encryption
870  policies, then ``key_spec.type`` must contain
871  FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER, and ``key_spec.u.identifier`` is
872  an *output* field which the kernel fills in with a cryptographic
873  hash of the key.  To add this type of key, the calling process does
874  not need any privileges.  However, the number of keys that can be
875  added is limited by the user's quota for the keyrings service (see
876  ``Documentation/security/keys/core.rst``).
877
878- ``raw_size`` must be the size of the ``raw`` key provided, in bytes.
879  Alternatively, if ``key_id`` is nonzero, this field must be 0, since
880  in that case the size is implied by the specified Linux keyring key.
881
882- ``key_id`` is 0 if the raw key is given directly in the ``raw``
883  field.  Otherwise ``key_id`` is the ID of a Linux keyring key of
884  type "fscrypt-provisioning" whose payload is
885  struct fscrypt_provisioning_key_payload whose ``raw`` field contains
886  the raw key and whose ``type`` field matches ``key_spec.type``.
887  Since ``raw`` is variable-length, the total size of this key's
888  payload must be ``sizeof(struct fscrypt_provisioning_key_payload)``
889  plus the raw key size.  The process must have Search permission on
890  this key.
891
892  Most users should leave this 0 and specify the raw key directly.
893  The support for specifying a Linux keyring key is intended mainly to
894  allow re-adding keys after a filesystem is unmounted and re-mounted,
895  without having to store the raw keys in userspace memory.
896
897- ``raw`` is a variable-length field which must contain the actual
898  key, ``raw_size`` bytes long.  Alternatively, if ``key_id`` is
899  nonzero, then this field is unused.
900
901For v2 policy keys, the kernel keeps track of which user (identified
902by effective user ID) added the key, and only allows the key to be
903removed by that user --- or by "root", if they use
904`FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`_.
905
906However, if another user has added the key, it may be desirable to
907prevent that other user from unexpectedly removing it.  Therefore,
908FS_IOC_ADD_ENCRYPTION_KEY may also be used to add a v2 policy key
909*again*, even if it's already added by other user(s).  In this case,
910FS_IOC_ADD_ENCRYPTION_KEY will just install a claim to the key for the
911current user, rather than actually add the key again (but the raw key
912must still be provided, as a proof of knowledge).
913
914FS_IOC_ADD_ENCRYPTION_KEY returns 0 if either the key or a claim to
915the key was either added or already exists.
916
917FS_IOC_ADD_ENCRYPTION_KEY can fail with the following errors:
918
919- ``EACCES``: FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR was specified, but the
920  caller does not have the CAP_SYS_ADMIN capability in the initial
921  user namespace; or the raw key was specified by Linux key ID but the
922  process lacks Search permission on the key.
923- ``EDQUOT``: the key quota for this user would be exceeded by adding
924  the key
925- ``EINVAL``: invalid key size or key specifier type, or reserved bits
926  were set
927- ``EKEYREJECTED``: the raw key was specified by Linux key ID, but the
928  key has the wrong type
929- ``ENOKEY``: the raw key was specified by Linux key ID, but no key
930  exists with that ID
931- ``ENOTTY``: this type of filesystem does not implement encryption
932- ``EOPNOTSUPP``: the kernel was not configured with encryption
933  support for this filesystem, or the filesystem superblock has not
934  had encryption enabled on it
935
936Legacy method
937~~~~~~~~~~~~~
938
939For v1 encryption policies, a master encryption key can also be
940provided by adding it to a process-subscribed keyring, e.g. to a
941session keyring, or to a user keyring if the user keyring is linked
942into the session keyring.
943
944This method is deprecated (and not supported for v2 encryption
945policies) for several reasons.  First, it cannot be used in
946combination with FS_IOC_REMOVE_ENCRYPTION_KEY (see `Removing keys`_),
947so for removing a key a workaround such as keyctl_unlink() in
948combination with ``sync; echo 2 > /proc/sys/vm/drop_caches`` would
949have to be used.  Second, it doesn't match the fact that the
950locked/unlocked status of encrypted files (i.e. whether they appear to
951be in plaintext form or in ciphertext form) is global.  This mismatch
952has caused much confusion as well as real problems when processes
953running under different UIDs, such as a ``sudo`` command, need to
954access encrypted files.
955
956Nevertheless, to add a key to one of the process-subscribed keyrings,
957the add_key() system call can be used (see:
958``Documentation/security/keys/core.rst``).  The key type must be
959"logon"; keys of this type are kept in kernel memory and cannot be
960read back by userspace.  The key description must be "fscrypt:"
961followed by the 16-character lower case hex representation of the
962``master_key_descriptor`` that was set in the encryption policy.  The
963key payload must conform to the following structure::
964
965    #define FSCRYPT_MAX_KEY_SIZE            64
966
967    struct fscrypt_key {
968            __u32 mode;
969            __u8 raw[FSCRYPT_MAX_KEY_SIZE];
970            __u32 size;
971    };
972
973``mode`` is ignored; just set it to 0.  The actual key is provided in
974``raw`` with ``size`` indicating its size in bytes.  That is, the
975bytes ``raw[0..size-1]`` (inclusive) are the actual key.
976
977The key description prefix "fscrypt:" may alternatively be replaced
978with a filesystem-specific prefix such as "ext4:".  However, the
979filesystem-specific prefixes are deprecated and should not be used in
980new programs.
981
982Removing keys
983-------------
984
985Two ioctls are available for removing a key that was added by
986`FS_IOC_ADD_ENCRYPTION_KEY`_:
987
988- `FS_IOC_REMOVE_ENCRYPTION_KEY`_
989- `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`_
990
991These two ioctls differ only in cases where v2 policy keys are added
992or removed by non-root users.
993
994These ioctls don't work on keys that were added via the legacy
995process-subscribed keyrings mechanism.
996
997Before using these ioctls, read the `Kernel memory compromise`_
998section for a discussion of the security goals and limitations of
999these ioctls.
1000
1001FS_IOC_REMOVE_ENCRYPTION_KEY
1002~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1003
1004The FS_IOC_REMOVE_ENCRYPTION_KEY ioctl removes a claim to a master
1005encryption key from the filesystem, and possibly removes the key
1006itself.  It can be executed on any file or directory on the target
1007filesystem, but using the filesystem's root directory is recommended.
1008It takes in a pointer to struct fscrypt_remove_key_arg, defined
1009as follows::
1010
1011    struct fscrypt_remove_key_arg {
1012            struct fscrypt_key_specifier key_spec;
1013    #define FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY      0x00000001
1014    #define FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS     0x00000002
1015            __u32 removal_status_flags;     /* output */
1016            __u32 __reserved[5];
1017    };
1018
1019This structure must be zeroed, then initialized as follows:
1020
1021- The key to remove is specified by ``key_spec``:
1022
1023    - To remove a key used by v1 encryption policies, set
1024      ``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill
1025      in ``key_spec.u.descriptor``.  To remove this type of key, the
1026      calling process must have the CAP_SYS_ADMIN capability in the
1027      initial user namespace.
1028
1029    - To remove a key used by v2 encryption policies, set
1030      ``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill
1031      in ``key_spec.u.identifier``.
1032
1033For v2 policy keys, this ioctl is usable by non-root users.  However,
1034to make this possible, it actually just removes the current user's
1035claim to the key, undoing a single call to FS_IOC_ADD_ENCRYPTION_KEY.
1036Only after all claims are removed is the key really removed.
1037
1038For example, if FS_IOC_ADD_ENCRYPTION_KEY was called with uid 1000,
1039then the key will be "claimed" by uid 1000, and
1040FS_IOC_REMOVE_ENCRYPTION_KEY will only succeed as uid 1000.  Or, if
1041both uids 1000 and 2000 added the key, then for each uid
1042FS_IOC_REMOVE_ENCRYPTION_KEY will only remove their own claim.  Only
1043once *both* are removed is the key really removed.  (Think of it like
1044unlinking a file that may have hard links.)
1045
1046If FS_IOC_REMOVE_ENCRYPTION_KEY really removes the key, it will also
1047try to "lock" all files that had been unlocked with the key.  It won't
1048lock files that are still in-use, so this ioctl is expected to be used
1049in cooperation with userspace ensuring that none of the files are
1050still open.  However, if necessary, this ioctl can be executed again
1051later to retry locking any remaining files.
1052
1053FS_IOC_REMOVE_ENCRYPTION_KEY returns 0 if either the key was removed
1054(but may still have files remaining to be locked), the user's claim to
1055the key was removed, or the key was already removed but had files
1056remaining to be the locked so the ioctl retried locking them.  In any
1057of these cases, ``removal_status_flags`` is filled in with the
1058following informational status flags:
1059
1060- ``FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY``: set if some file(s)
1061  are still in-use.  Not guaranteed to be set in the case where only
1062  the user's claim to the key was removed.
1063- ``FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS``: set if only the
1064  user's claim to the key was removed, not the key itself
1065
1066FS_IOC_REMOVE_ENCRYPTION_KEY can fail with the following errors:
1067
1068- ``EACCES``: The FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR key specifier type
1069  was specified, but the caller does not have the CAP_SYS_ADMIN
1070  capability in the initial user namespace
1071- ``EINVAL``: invalid key specifier type, or reserved bits were set
1072- ``ENOKEY``: the key object was not found at all, i.e. it was never
1073  added in the first place or was already fully removed including all
1074  files locked; or, the user does not have a claim to the key (but
1075  someone else does).
1076- ``ENOTTY``: this type of filesystem does not implement encryption
1077- ``EOPNOTSUPP``: the kernel was not configured with encryption
1078  support for this filesystem, or the filesystem superblock has not
1079  had encryption enabled on it
1080
1081FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS
1082~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1083
1084FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS is exactly the same as
1085`FS_IOC_REMOVE_ENCRYPTION_KEY`_, except that for v2 policy keys, the
1086ALL_USERS version of the ioctl will remove all users' claims to the
1087key, not just the current user's.  I.e., the key itself will always be
1088removed, no matter how many users have added it.  This difference is
1089only meaningful if non-root users are adding and removing keys.
1090
1091Because of this, FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS also requires
1092"root", namely the CAP_SYS_ADMIN capability in the initial user
1093namespace.  Otherwise it will fail with EACCES.
1094
1095Getting key status
1096------------------
1097
1098FS_IOC_GET_ENCRYPTION_KEY_STATUS
1099~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1100
1101The FS_IOC_GET_ENCRYPTION_KEY_STATUS ioctl retrieves the status of a
1102master encryption key.  It can be executed on any file or directory on
1103the target filesystem, but using the filesystem's root directory is
1104recommended.  It takes in a pointer to
1105struct fscrypt_get_key_status_arg, defined as follows::
1106
1107    struct fscrypt_get_key_status_arg {
1108            /* input */
1109            struct fscrypt_key_specifier key_spec;
1110            __u32 __reserved[6];
1111
1112            /* output */
1113    #define FSCRYPT_KEY_STATUS_ABSENT               1
1114    #define FSCRYPT_KEY_STATUS_PRESENT              2
1115    #define FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED 3
1116            __u32 status;
1117    #define FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF   0x00000001
1118            __u32 status_flags;
1119            __u32 user_count;
1120            __u32 __out_reserved[13];
1121    };
1122
1123The caller must zero all input fields, then fill in ``key_spec``:
1124
1125    - To get the status of a key for v1 encryption policies, set
1126      ``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill
1127      in ``key_spec.u.descriptor``.
1128
1129    - To get the status of a key for v2 encryption policies, set
1130      ``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill
1131      in ``key_spec.u.identifier``.
1132
1133On success, 0 is returned and the kernel fills in the output fields:
1134
1135- ``status`` indicates whether the key is absent, present, or
1136  incompletely removed.  Incompletely removed means that removal has
1137  been initiated, but some files are still in use; i.e.,
1138  `FS_IOC_REMOVE_ENCRYPTION_KEY`_ returned 0 but set the informational
1139  status flag FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY.
1140
1141- ``status_flags`` can contain the following flags:
1142
1143    - ``FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF`` indicates that the key
1144      has added by the current user.  This is only set for keys
1145      identified by ``identifier`` rather than by ``descriptor``.
1146
1147- ``user_count`` specifies the number of users who have added the key.
1148  This is only set for keys identified by ``identifier`` rather than
1149  by ``descriptor``.
1150
1151FS_IOC_GET_ENCRYPTION_KEY_STATUS can fail with the following errors:
1152
1153- ``EINVAL``: invalid key specifier type, or reserved bits were set
1154- ``ENOTTY``: this type of filesystem does not implement encryption
1155- ``EOPNOTSUPP``: the kernel was not configured with encryption
1156  support for this filesystem, or the filesystem superblock has not
1157  had encryption enabled on it
1158
1159Among other use cases, FS_IOC_GET_ENCRYPTION_KEY_STATUS can be useful
1160for determining whether the key for a given encrypted directory needs
1161to be added before prompting the user for the passphrase needed to
1162derive the key.
1163
1164FS_IOC_GET_ENCRYPTION_KEY_STATUS can only get the status of keys in
1165the filesystem-level keyring, i.e. the keyring managed by
1166`FS_IOC_ADD_ENCRYPTION_KEY`_ and `FS_IOC_REMOVE_ENCRYPTION_KEY`_.  It
1167cannot get the status of a key that has only been added for use by v1
1168encryption policies using the legacy mechanism involving
1169process-subscribed keyrings.
1170
1171Access semantics
1172================
1173
1174With the key
1175------------
1176
1177With the encryption key, encrypted regular files, directories, and
1178symlinks behave very similarly to their unencrypted counterparts ---
1179after all, the encryption is intended to be transparent.  However,
1180astute users may notice some differences in behavior:
1181
1182- Unencrypted files, or files encrypted with a different encryption
1183  policy (i.e. different key, modes, or flags), cannot be renamed or
1184  linked into an encrypted directory; see `Encryption policy
1185  enforcement`_.  Attempts to do so will fail with EXDEV.  However,
1186  encrypted files can be renamed within an encrypted directory, or
1187  into an unencrypted directory.
1188
1189  Note: "moving" an unencrypted file into an encrypted directory, e.g.
1190  with the `mv` program, is implemented in userspace by a copy
1191  followed by a delete.  Be aware that the original unencrypted data
1192  may remain recoverable from free space on the disk; prefer to keep
1193  all files encrypted from the very beginning.  The `shred` program
1194  may be used to overwrite the source files but isn't guaranteed to be
1195  effective on all filesystems and storage devices.
1196
1197- Direct I/O is supported on encrypted files only under some
1198  circumstances.  For details, see `Direct I/O support`_.
1199
1200- The fallocate operations FALLOC_FL_COLLAPSE_RANGE and
1201  FALLOC_FL_INSERT_RANGE are not supported on encrypted files and will
1202  fail with EOPNOTSUPP.
1203
1204- Online defragmentation of encrypted files is not supported.  The
1205  EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail with
1206  EOPNOTSUPP.
1207
1208- The ext4 filesystem does not support data journaling with encrypted
1209  regular files.  It will fall back to ordered data mode instead.
1210
1211- DAX (Direct Access) is not supported on encrypted files.
1212
1213- The maximum length of an encrypted symlink is 2 bytes shorter than
1214  the maximum length of an unencrypted symlink.  For example, on an
1215  EXT4 filesystem with a 4K block size, unencrypted symlinks can be up
1216  to 4095 bytes long, while encrypted symlinks can only be up to 4093
1217  bytes long (both lengths excluding the terminating null).
1218
1219Note that mmap *is* supported.  This is possible because the pagecache
1220for an encrypted file contains the plaintext, not the ciphertext.
1221
1222Without the key
1223---------------
1224
1225Some filesystem operations may be performed on encrypted regular
1226files, directories, and symlinks even before their encryption key has
1227been added, or after their encryption key has been removed:
1228
1229- File metadata may be read, e.g. using stat().
1230
1231- Directories may be listed, in which case the filenames will be
1232  listed in an encoded form derived from their ciphertext.  The
1233  current encoding algorithm is described in `Filename hashing and
1234  encoding`_.  The algorithm is subject to change, but it is
1235  guaranteed that the presented filenames will be no longer than
1236  NAME_MAX bytes, will not contain the ``/`` or ``\0`` characters, and
1237  will uniquely identify directory entries.
1238
1239  The ``.`` and ``..`` directory entries are special.  They are always
1240  present and are not encrypted or encoded.
1241
1242- Files may be deleted.  That is, nondirectory files may be deleted
1243  with unlink() as usual, and empty directories may be deleted with
1244  rmdir() as usual.  Therefore, ``rm`` and ``rm -r`` will work as
1245  expected.
1246
1247- Symlink targets may be read and followed, but they will be presented
1248  in encrypted form, similar to filenames in directories.  Hence, they
1249  are unlikely to point to anywhere useful.
1250
1251Without the key, regular files cannot be opened or truncated.
1252Attempts to do so will fail with ENOKEY.  This implies that any
1253regular file operations that require a file descriptor, such as
1254read(), write(), mmap(), fallocate(), and ioctl(), are also forbidden.
1255
1256Also without the key, files of any type (including directories) cannot
1257be created or linked into an encrypted directory, nor can a name in an
1258encrypted directory be the source or target of a rename, nor can an
1259O_TMPFILE temporary file be created in an encrypted directory.  All
1260such operations will fail with ENOKEY.
1261
1262It is not currently possible to backup and restore encrypted files
1263without the encryption key.  This would require special APIs which
1264have not yet been implemented.
1265
1266Encryption policy enforcement
1267=============================
1268
1269After an encryption policy has been set on a directory, all regular
1270files, directories, and symbolic links created in that directory
1271(recursively) will inherit that encryption policy.  Special files ---
1272that is, named pipes, device nodes, and UNIX domain sockets --- will
1273not be encrypted.
1274
1275Except for those special files, it is forbidden to have unencrypted
1276files, or files encrypted with a different encryption policy, in an
1277encrypted directory tree.  Attempts to link or rename such a file into
1278an encrypted directory will fail with EXDEV.  This is also enforced
1279during ->lookup() to provide limited protection against offline
1280attacks that try to disable or downgrade encryption in known locations
1281where applications may later write sensitive data.  It is recommended
1282that systems implementing a form of "verified boot" take advantage of
1283this by validating all top-level encryption policies prior to access.
1284
1285Inline encryption support
1286=========================
1287
1288By default, fscrypt uses the kernel crypto API for all cryptographic
1289operations (other than HKDF, which fscrypt partially implements
1290itself).  The kernel crypto API supports hardware crypto accelerators,
1291but only ones that work in the traditional way where all inputs and
1292outputs (e.g. plaintexts and ciphertexts) are in memory.  fscrypt can
1293take advantage of such hardware, but the traditional acceleration
1294model isn't particularly efficient and fscrypt hasn't been optimized
1295for it.
1296
1297Instead, many newer systems (especially mobile SoCs) have *inline
1298encryption hardware* that can encrypt/decrypt data while it is on its
1299way to/from the storage device.  Linux supports inline encryption
1300through a set of extensions to the block layer called *blk-crypto*.
1301blk-crypto allows filesystems to attach encryption contexts to bios
1302(I/O requests) to specify how the data will be encrypted or decrypted
1303in-line.  For more information about blk-crypto, see
1304:ref:`Documentation/block/inline-encryption.rst <inline_encryption>`.
1305
1306On supported filesystems (currently ext4 and f2fs), fscrypt can use
1307blk-crypto instead of the kernel crypto API to encrypt/decrypt file
1308contents.  To enable this, set CONFIG_FS_ENCRYPTION_INLINE_CRYPT=y in
1309the kernel configuration, and specify the "inlinecrypt" mount option
1310when mounting the filesystem.
1311
1312Note that the "inlinecrypt" mount option just specifies to use inline
1313encryption when possible; it doesn't force its use.  fscrypt will
1314still fall back to using the kernel crypto API on files where the
1315inline encryption hardware doesn't have the needed crypto capabilities
1316(e.g. support for the needed encryption algorithm and data unit size)
1317and where blk-crypto-fallback is unusable.  (For blk-crypto-fallback
1318to be usable, it must be enabled in the kernel configuration with
1319CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK=y.)
1320
1321Currently fscrypt always uses the filesystem block size (which is
1322usually 4096 bytes) as the data unit size.  Therefore, it can only use
1323inline encryption hardware that supports that data unit size.
1324
1325Inline encryption doesn't affect the ciphertext or other aspects of
1326the on-disk format, so users may freely switch back and forth between
1327using "inlinecrypt" and not using "inlinecrypt".
1328
1329Direct I/O support
1330==================
1331
1332For direct I/O on an encrypted file to work, the following conditions
1333must be met (in addition to the conditions for direct I/O on an
1334unencrypted file):
1335
1336* The file must be using inline encryption.  Usually this means that
1337  the filesystem must be mounted with ``-o inlinecrypt`` and inline
1338  encryption hardware must be present.  However, a software fallback
1339  is also available.  For details, see `Inline encryption support`_.
1340
1341* The I/O request must be fully aligned to the filesystem block size.
1342  This means that the file position the I/O is targeting, the lengths
1343  of all I/O segments, and the memory addresses of all I/O buffers
1344  must be multiples of this value.  Note that the filesystem block
1345  size may be greater than the logical block size of the block device.
1346
1347If either of the above conditions is not met, then direct I/O on the
1348encrypted file will fall back to buffered I/O.
1349
1350Implementation details
1351======================
1352
1353Encryption context
1354------------------
1355
1356An encryption policy is represented on-disk by
1357struct fscrypt_context_v1 or struct fscrypt_context_v2.  It is up to
1358individual filesystems to decide where to store it, but normally it
1359would be stored in a hidden extended attribute.  It should *not* be
1360exposed by the xattr-related system calls such as getxattr() and
1361setxattr() because of the special semantics of the encryption xattr.
1362(In particular, there would be much confusion if an encryption policy
1363were to be added to or removed from anything other than an empty
1364directory.)  These structs are defined as follows::
1365
1366    #define FSCRYPT_FILE_NONCE_SIZE 16
1367
1368    #define FSCRYPT_KEY_DESCRIPTOR_SIZE  8
1369    struct fscrypt_context_v1 {
1370            u8 version;
1371            u8 contents_encryption_mode;
1372            u8 filenames_encryption_mode;
1373            u8 flags;
1374            u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
1375            u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
1376    };
1377
1378    #define FSCRYPT_KEY_IDENTIFIER_SIZE  16
1379    struct fscrypt_context_v2 {
1380            u8 version;
1381            u8 contents_encryption_mode;
1382            u8 filenames_encryption_mode;
1383            u8 flags;
1384            u8 log2_data_unit_size;
1385            u8 __reserved[3];
1386            u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
1387            u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
1388    };
1389
1390The context structs contain the same information as the corresponding
1391policy structs (see `Setting an encryption policy`_), except that the
1392context structs also contain a nonce.  The nonce is randomly generated
1393by the kernel and is used as KDF input or as a tweak to cause
1394different files to be encrypted differently; see `Per-file encryption
1395keys`_ and `DIRECT_KEY policies`_.
1396
1397Data path changes
1398-----------------
1399
1400When inline encryption is used, filesystems just need to associate
1401encryption contexts with bios to specify how the block layer or the
1402inline encryption hardware will encrypt/decrypt the file contents.
1403
1404When inline encryption isn't used, filesystems must encrypt/decrypt
1405the file contents themselves, as described below:
1406
1407For the read path (->read_folio()) of regular files, filesystems can
1408read the ciphertext into the page cache and decrypt it in-place.  The
1409folio lock must be held until decryption has finished, to prevent the
1410folio from becoming visible to userspace prematurely.
1411
1412For the write path (->writepage()) of regular files, filesystems
1413cannot encrypt data in-place in the page cache, since the cached
1414plaintext must be preserved.  Instead, filesystems must encrypt into a
1415temporary buffer or "bounce page", then write out the temporary
1416buffer.  Some filesystems, such as UBIFS, already use temporary
1417buffers regardless of encryption.  Other filesystems, such as ext4 and
1418F2FS, have to allocate bounce pages specially for encryption.
1419
1420Filename hashing and encoding
1421-----------------------------
1422
1423Modern filesystems accelerate directory lookups by using indexed
1424directories.  An indexed directory is organized as a tree keyed by
1425filename hashes.  When a ->lookup() is requested, the filesystem
1426normally hashes the filename being looked up so that it can quickly
1427find the corresponding directory entry, if any.
1428
1429With encryption, lookups must be supported and efficient both with and
1430without the encryption key.  Clearly, it would not work to hash the
1431plaintext filenames, since the plaintext filenames are unavailable
1432without the key.  (Hashing the plaintext filenames would also make it
1433impossible for the filesystem's fsck tool to optimize encrypted
1434directories.)  Instead, filesystems hash the ciphertext filenames,
1435i.e. the bytes actually stored on-disk in the directory entries.  When
1436asked to do a ->lookup() with the key, the filesystem just encrypts
1437the user-supplied name to get the ciphertext.
1438
1439Lookups without the key are more complicated.  The raw ciphertext may
1440contain the ``\0`` and ``/`` characters, which are illegal in
1441filenames.  Therefore, readdir() must base64url-encode the ciphertext
1442for presentation.  For most filenames, this works fine; on ->lookup(),
1443the filesystem just base64url-decodes the user-supplied name to get
1444back to the raw ciphertext.
1445
1446However, for very long filenames, base64url encoding would cause the
1447filename length to exceed NAME_MAX.  To prevent this, readdir()
1448actually presents long filenames in an abbreviated form which encodes
1449a strong "hash" of the ciphertext filename, along with the optional
1450filesystem-specific hash(es) needed for directory lookups.  This
1451allows the filesystem to still, with a high degree of confidence, map
1452the filename given in ->lookup() back to a particular directory entry
1453that was previously listed by readdir().  See
1454struct fscrypt_nokey_name in the source for more details.
1455
1456Note that the precise way that filenames are presented to userspace
1457without the key is subject to change in the future.  It is only meant
1458as a way to temporarily present valid filenames so that commands like
1459``rm -r`` work as expected on encrypted directories.
1460
1461Tests
1462=====
1463
1464To test fscrypt, use xfstests, which is Linux's de facto standard
1465filesystem test suite.  First, run all the tests in the "encrypt"
1466group on the relevant filesystem(s).  One can also run the tests
1467with the 'inlinecrypt' mount option to test the implementation for
1468inline encryption support.  For example, to test ext4 and
1469f2fs encryption using `kvm-xfstests
1470<https://github.com/tytso/xfstests-bld/blob/master/Documentation/kvm-quickstart.md>`_::
1471
1472    kvm-xfstests -c ext4,f2fs -g encrypt
1473    kvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt
1474
1475UBIFS encryption can also be tested this way, but it should be done in
1476a separate command, and it takes some time for kvm-xfstests to set up
1477emulated UBI volumes::
1478
1479    kvm-xfstests -c ubifs -g encrypt
1480
1481No tests should fail.  However, tests that use non-default encryption
1482modes (e.g. generic/549 and generic/550) will be skipped if the needed
1483algorithms were not built into the kernel's crypto API.  Also, tests
1484that access the raw block device (e.g. generic/399, generic/548,
1485generic/549, generic/550) will be skipped on UBIFS.
1486
1487Besides running the "encrypt" group tests, for ext4 and f2fs it's also
1488possible to run most xfstests with the "test_dummy_encryption" mount
1489option.  This option causes all new files to be automatically
1490encrypted with a dummy key, without having to make any API calls.
1491This tests the encrypted I/O paths more thoroughly.  To do this with
1492kvm-xfstests, use the "encrypt" filesystem configuration::
1493
1494    kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
1495    kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
1496
1497Because this runs many more tests than "-g encrypt" does, it takes
1498much longer to run; so also consider using `gce-xfstests
1499<https://github.com/tytso/xfstests-bld/blob/master/Documentation/gce-xfstests.md>`_
1500instead of kvm-xfstests::
1501
1502    gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
1503    gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
1504