blob: 3a7b60521b94ab38654dcbaa8380a8a5bcc9d85e [file] [log] [blame]
Eric Biggerse33fa312018-11-26 11:27:37 -08001=====================================
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, and
35UBIFS. This allows encrypted files to be read and written without
36caching both the decrypted and encrypted pages in the pagecache,
37thereby nearly halving the memory used and bringing it in line with
38unencrypted files. Similarly, half as many dentries and inodes are
39needed. eCryptfs also limits encrypted filenames to 143 bytes,
40causing application compatibility issues; fscrypt allows the full 255
41bytes (NAME_MAX). Finally, unlike eCryptfs, the fscrypt API can be
42used 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
75fscrypt is only resistant to side-channel attacks, such as timing or
76electromagnetic attacks, to the extent that the underlying Linux
77Cryptographic API algorithms are. If a vulnerable algorithm is used,
78such as a table-based implementation of AES, it may be possible for an
79attacker to mount a side channel attack against the online system.
80Side channel attacks may also be mounted against applications
81consuming decrypted data.
82
83After an encryption key has been provided, fscrypt is not designed to
84hide the plaintext file contents or filenames from other users on the
85same system, regardless of the visibility of the keyring key.
86Instead, existing access control mechanisms such as file mode bits,
87POSIX ACLs, LSMs, or mount namespaces should be used for this purpose.
88Also note that as long as the encryption keys are *anywhere* in
89memory, an online attacker can necessarily compromise them by mounting
90a physical attack or by exploiting any kernel security vulnerability
91which provides an arbitrary memory read primitive.
92
93While it is ostensibly possible to "evict" keys from the system,
94recently accessed encrypted files will remain accessible at least
95until the filesystem is unmounted or the VFS caches are dropped, e.g.
96using ``echo 2 > /proc/sys/vm/drop_caches``. Even after that, if the
97RAM is compromised before being powered off, it will likely still be
98possible to recover portions of the plaintext file contents, if not
99some of the encryption keys as well. (Since Linux v4.12, all
100in-kernel keys related to fscrypt are sanitized before being freed.
101However, userspace would need to do its part as well.)
102
103Currently, fscrypt does not prevent a user from maliciously providing
104an incorrect key for another user's existing encrypted files. A
105protection against this is planned.
106
107Key hierarchy
108=============
109
110Master Keys
111-----------
112
113Each encrypted directory tree is protected by a *master key*. Master
114keys can be up to 64 bytes long, and must be at least as long as the
115greater of the key length needed by the contents and filenames
116encryption modes being used. For example, if AES-256-XTS is used for
117contents encryption, the master key must be 64 bytes (512 bits). Note
118that the XTS mode is defined to require a key twice as long as that
119required by the underlying block cipher.
120
121To "unlock" an encrypted directory tree, userspace must provide the
122appropriate master key. There can be any number of master keys, each
123of which protects any number of directory trees on any number of
124filesystems.
125
126Userspace should generate master keys either using a cryptographically
127secure random number generator, or by using a KDF (Key Derivation
128Function). Note that whenever a KDF is used to "stretch" a
129lower-entropy secret such as a passphrase, it is critical that a KDF
130designed for this purpose be used, such as scrypt, PBKDF2, or Argon2.
131
132Per-file keys
133-------------
134
135Since each master key can protect many files, it is necessary to
136"tweak" the encryption of each file so that the same plaintext in two
137files doesn't map to the same ciphertext, or vice versa. In most
138cases, fscrypt does this by deriving per-file keys. When a new
139encrypted inode (regular file, directory, or symlink) is created,
140fscrypt randomly generates a 16-byte nonce and stores it in the
141inode's encryption xattr. Then, it uses a KDF (Key Derivation
142Function) to derive the file's key from the master key and nonce.
143
144The Adiantum encryption mode (see `Encryption modes and usage`_) is
145special, since it accepts longer IVs and is suitable for both contents
146and filenames encryption. For it, a "direct key" option is offered
147where the file's nonce is included in the IVs and the master key is
148used for encryption directly. This improves performance; however,
149users must not use the same master key for any other encryption mode.
150
151Below, the KDF and design considerations are described in more detail.
152
153The current KDF works by encrypting the master key with AES-128-ECB,
154using the file's nonce as the AES key. The output is used as the
155derived key. If the output is longer than needed, then it is
156truncated to the needed length.
157
158Note: this KDF meets the primary security requirement, which is to
159produce unique derived keys that preserve the entropy of the master
160key, assuming that the master key is already a good pseudorandom key.
161However, it is nonstandard and has some problems such as being
162reversible, so it is generally considered to be a mistake! It may be
163replaced with HKDF or another more standard KDF in the future.
164
165Key derivation was chosen over key wrapping because wrapped keys would
166require larger xattrs which would be less likely to fit in-line in the
167filesystem's inode table, and there didn't appear to be any
168significant advantages to key wrapping. In particular, currently
169there is no requirement to support unlocking a file with multiple
170alternative master keys or to support rotating master keys. Instead,
171the master keys may be wrapped in userspace, e.g. as is done by the
172`fscrypt <https://github.com/google/fscrypt>`_ tool.
173
174Including the inode number in the IVs was considered. However, it was
175rejected as it would have prevented ext4 filesystems from being
176resized, and by itself still wouldn't have been sufficient to prevent
177the same key from being directly reused for both XTS and CTS-CBC.
178
179Encryption modes and usage
180==========================
181
182fscrypt allows one encryption mode to be specified for file contents
183and one encryption mode to be specified for filenames. Different
184directory trees are permitted to use different encryption modes.
185Currently, the following pairs of encryption modes are supported:
186
187- AES-256-XTS for contents and AES-256-CTS-CBC for filenames
188- AES-128-CBC for contents and AES-128-CTS-CBC for filenames
189- Adiantum for both contents and filenames
190
191If unsure, you should use the (AES-256-XTS, AES-256-CTS-CBC) pair.
192
193AES-128-CBC was added only for low-powered embedded devices with
194crypto accelerators such as CAAM or CESA that do not support XTS.
195
196Adiantum is a (primarily) stream cipher-based mode that is fast even
197on CPUs without dedicated crypto instructions. It's also a true
198wide-block mode, unlike XTS. It can also eliminate the need to derive
199per-file keys. However, it depends on the security of two primitives,
200XChaCha12 and AES-256, rather than just one. See the paper
201"Adiantum: length-preserving encryption for entry-level processors"
202(https://eprint.iacr.org/2018/720.pdf) for more details. To use
203Adiantum, CONFIG_CRYPTO_ADIANTUM must be enabled. Also, fast
204implementations of ChaCha and NHPoly1305 should be enabled, e.g.
205CONFIG_CRYPTO_CHACHA20_NEON and CONFIG_CRYPTO_NHPOLY1305_NEON for ARM.
206
207New encryption modes can be added relatively easily, without changes
208to individual filesystems. However, authenticated encryption (AE)
209modes are not currently supported because of the difficulty of dealing
210with ciphertext expansion.
211
212Contents encryption
213-------------------
214
215For file contents, each filesystem block is encrypted independently.
216Currently, only the case where the filesystem block size is equal to
217the system's page size (usually 4096 bytes) is supported.
218
219Each block's IV is set to the logical block number within the file as
220a little endian number, except that:
221
222- With CBC mode encryption, ESSIV is also used. Specifically, each IV
223 is encrypted with AES-256 where the AES-256 key is the SHA-256 hash
224 of the file's data encryption key.
225
226- In the "direct key" configuration (FS_POLICY_FLAG_DIRECT_KEY set in
227 the fscrypt_policy), the file's nonce is also appended to the IV.
228 Currently this is only allowed with the Adiantum encryption mode.
229
230Filenames encryption
231--------------------
232
233For filenames, each full filename is encrypted at once. Because of
234the requirements to retain support for efficient directory lookups and
235filenames of up to 255 bytes, the same IV is used for every filename
236in a directory.
237
238However, each encrypted directory still uses a unique key; or
239alternatively (for the "direct key" configuration) has the file's
240nonce included in the IVs. Thus, IV reuse is limited to within a
241single directory.
242
243With CTS-CBC, the IV reuse means that when the plaintext filenames
244share a common prefix at least as long as the cipher block size (16
245bytes for AES), the corresponding encrypted filenames will also share
246a common prefix. This is undesirable. Adiantum does not have this
247weakness, as it is a wide-block encryption mode.
248
249All supported filenames encryption modes accept any plaintext length
250>= 16 bytes; cipher block alignment is not required. However,
251filenames shorter than 16 bytes are NUL-padded to 16 bytes before
252being encrypted. In addition, to reduce leakage of filename lengths
253via their ciphertexts, all filenames are NUL-padded to the next 4, 8,
25416, or 32-byte boundary (configurable). 32 is recommended since this
255provides the best confidentiality, at the cost of making directory
256entries consume slightly more space. Note that since NUL (``\0``) is
257not otherwise a valid character in filenames, the padding will never
258produce duplicate plaintexts.
259
260Symbolic link targets are considered a type of filename and are
261encrypted in the same way as filenames in directory entries, except
262that IV reuse is not a problem as each symlink has its own inode.
263
264User API
265========
266
267Setting an encryption policy
268----------------------------
269
270The FS_IOC_SET_ENCRYPTION_POLICY ioctl sets an encryption policy on an
271empty directory or verifies that a directory or regular file already
272has the specified encryption policy. It takes in a pointer to a
273:c:type:`struct fscrypt_policy`, defined as follows::
274
275 #define FS_KEY_DESCRIPTOR_SIZE 8
276
277 struct fscrypt_policy {
278 __u8 version;
279 __u8 contents_encryption_mode;
280 __u8 filenames_encryption_mode;
281 __u8 flags;
282 __u8 master_key_descriptor[FS_KEY_DESCRIPTOR_SIZE];
283 };
284
285This structure must be initialized as follows:
286
287- ``version`` must be 0.
288
289- ``contents_encryption_mode`` and ``filenames_encryption_mode`` must
290 be set to constants from ``<linux/fs.h>`` which identify the
291 encryption modes to use. If unsure, use
292 FS_ENCRYPTION_MODE_AES_256_XTS (1) for ``contents_encryption_mode``
293 and FS_ENCRYPTION_MODE_AES_256_CTS (4) for
294 ``filenames_encryption_mode``.
295
296- ``flags`` must contain a value from ``<linux/fs.h>`` which
297 identifies the amount of NUL-padding to use when encrypting
298 filenames. If unsure, use FS_POLICY_FLAGS_PAD_32 (0x3).
299 In addition, if the chosen encryption modes are both
300 FS_ENCRYPTION_MODE_ADIANTUM, this can contain
301 FS_POLICY_FLAG_DIRECT_KEY to specify that the master key should be
302 used directly, without key derivation.
303
304- ``master_key_descriptor`` specifies how to find the master key in
305 the keyring; see `Adding keys`_. It is up to userspace to choose a
306 unique ``master_key_descriptor`` for each master key. The e4crypt
307 and fscrypt tools use the first 8 bytes of
308 ``SHA-512(SHA-512(master_key))``, but this particular scheme is not
309 required. Also, the master key need not be in the keyring yet when
310 FS_IOC_SET_ENCRYPTION_POLICY is executed. However, it must be added
311 before any files can be created in the encrypted directory.
312
313If the file is not yet encrypted, then FS_IOC_SET_ENCRYPTION_POLICY
314verifies that the file is an empty directory. If so, the specified
315encryption policy is assigned to the directory, turning it into an
316encrypted directory. After that, and after providing the
317corresponding master key as described in `Adding keys`_, all regular
318files, directories (recursively), and symlinks created in the
319directory will be encrypted, inheriting the same encryption policy.
320The filenames in the directory's entries will be encrypted as well.
321
322Alternatively, if the file is already encrypted, then
323FS_IOC_SET_ENCRYPTION_POLICY validates that the specified encryption
324policy exactly matches the actual one. If they match, then the ioctl
325returns 0. Otherwise, it fails with EEXIST. This works on both
326regular files and directories, including nonempty directories.
327
328Note that the ext4 filesystem does not allow the root directory to be
329encrypted, even if it is empty. Users who want to encrypt an entire
330filesystem with one key should consider using dm-crypt instead.
331
332FS_IOC_SET_ENCRYPTION_POLICY can fail with the following errors:
333
334- ``EACCES``: the file is not owned by the process's uid, nor does the
335 process have the CAP_FOWNER capability in a namespace with the file
336 owner's uid mapped
337- ``EEXIST``: the file is already encrypted with an encryption policy
338 different from the one specified
339- ``EINVAL``: an invalid encryption policy was specified (invalid
340 version, mode(s), or flags)
341- ``ENOTDIR``: the file is unencrypted and is a regular file, not a
342 directory
343- ``ENOTEMPTY``: the file is unencrypted and is a nonempty directory
344- ``ENOTTY``: this type of filesystem does not implement encryption
345- ``EOPNOTSUPP``: the kernel was not configured with encryption
346 support for this filesystem, or the filesystem superblock has not
347 had encryption enabled on it. (For example, to use encryption on an
348 ext4 filesystem, CONFIG_EXT4_ENCRYPTION must be enabled in the
349 kernel config, and the superblock must have had the "encrypt"
350 feature flag enabled using ``tune2fs -O encrypt`` or ``mkfs.ext4 -O
351 encrypt``.)
352- ``EPERM``: this directory may not be encrypted, e.g. because it is
353 the root directory of an ext4 filesystem
354- ``EROFS``: the filesystem is readonly
355
356Getting an encryption policy
357----------------------------
358
359The FS_IOC_GET_ENCRYPTION_POLICY ioctl retrieves the :c:type:`struct
360fscrypt_policy`, if any, for a directory or regular file. See above
361for the struct definition. No additional permissions are required
362beyond the ability to open the file.
363
364FS_IOC_GET_ENCRYPTION_POLICY can fail with the following errors:
365
366- ``EINVAL``: the file is encrypted, but it uses an unrecognized
367 encryption context format
368- ``ENODATA``: the file is not encrypted
369- ``ENOTTY``: this type of filesystem does not implement encryption
370- ``EOPNOTSUPP``: the kernel was not configured with encryption
371 support for this filesystem
372
373Note: if you only need to know whether a file is encrypted or not, on
374most filesystems it is also possible to use the FS_IOC_GETFLAGS ioctl
375and check for FS_ENCRYPT_FL, or to use the statx() system call and
376check for STATX_ATTR_ENCRYPTED in stx_attributes.
377
378Getting the per-filesystem salt
379-------------------------------
380
381Some filesystems, such as ext4 and F2FS, also support the deprecated
382ioctl FS_IOC_GET_ENCRYPTION_PWSALT. This ioctl retrieves a randomly
383generated 16-byte value stored in the filesystem superblock. This
384value is intended to used as a salt when deriving an encryption key
385from a passphrase or other low-entropy user credential.
386
387FS_IOC_GET_ENCRYPTION_PWSALT is deprecated. Instead, prefer to
388generate and manage any needed salt(s) in userspace.
389
390Adding keys
391-----------
392
393To provide a master key, userspace must add it to an appropriate
394keyring using the add_key() system call (see:
395``Documentation/security/keys/core.rst``). The key type must be
396"logon"; keys of this type are kept in kernel memory and cannot be
397read back by userspace. The key description must be "fscrypt:"
398followed by the 16-character lower case hex representation of the
399``master_key_descriptor`` that was set in the encryption policy. The
400key payload must conform to the following structure::
401
402 #define FS_MAX_KEY_SIZE 64
403
404 struct fscrypt_key {
405 u32 mode;
406 u8 raw[FS_MAX_KEY_SIZE];
407 u32 size;
408 };
409
410``mode`` is ignored; just set it to 0. The actual key is provided in
411``raw`` with ``size`` indicating its size in bytes. That is, the
412bytes ``raw[0..size-1]`` (inclusive) are the actual key.
413
414The key description prefix "fscrypt:" may alternatively be replaced
415with a filesystem-specific prefix such as "ext4:". However, the
416filesystem-specific prefixes are deprecated and should not be used in
417new programs.
418
419There are several different types of keyrings in which encryption keys
420may be placed, such as a session keyring, a user session keyring, or a
421user keyring. Each key must be placed in a keyring that is "attached"
422to all processes that might need to access files encrypted with it, in
423the sense that request_key() will find the key. Generally, if only
424processes belonging to a specific user need to access a given
425encrypted directory and no session keyring has been installed, then
426that directory's key should be placed in that user's user session
427keyring or user keyring. Otherwise, a session keyring should be
428installed if needed, and the key should be linked into that session
429keyring, or in a keyring linked into that session keyring.
430
431Note: introducing the complex visibility semantics of keyrings here
432was arguably a mistake --- especially given that by design, after any
433process successfully opens an encrypted file (thereby setting up the
434per-file key), possessing the keyring key is not actually required for
435any process to read/write the file until its in-memory inode is
436evicted. In the future there probably should be a way to provide keys
437directly to the filesystem instead, which would make the intended
438semantics clearer.
439
440Access semantics
441================
442
443With the key
444------------
445
446With the encryption key, encrypted regular files, directories, and
447symlinks behave very similarly to their unencrypted counterparts ---
448after all, the encryption is intended to be transparent. However,
449astute users may notice some differences in behavior:
450
451- Unencrypted files, or files encrypted with a different encryption
452 policy (i.e. different key, modes, or flags), cannot be renamed or
453 linked into an encrypted directory; see `Encryption policy
454 enforcement`_. Attempts to do so will fail with EPERM. However,
455 encrypted files can be renamed within an encrypted directory, or
456 into an unencrypted directory.
457
458- Direct I/O is not supported on encrypted files. Attempts to use
459 direct I/O on such files will fall back to buffered I/O.
460
461- The fallocate operations FALLOC_FL_COLLAPSE_RANGE,
462 FALLOC_FL_INSERT_RANGE, and FALLOC_FL_ZERO_RANGE are not supported
463 on encrypted files and will fail with EOPNOTSUPP.
464
465- Online defragmentation of encrypted files is not supported. The
466 EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail with
467 EOPNOTSUPP.
468
469- The ext4 filesystem does not support data journaling with encrypted
470 regular files. It will fall back to ordered data mode instead.
471
472- DAX (Direct Access) is not supported on encrypted files.
473
474- The st_size of an encrypted symlink will not necessarily give the
475 length of the symlink target as required by POSIX. It will actually
476 give the length of the ciphertext, which will be slightly longer
477 than the plaintext due to NUL-padding and an extra 2-byte overhead.
478
479- The maximum length of an encrypted symlink is 2 bytes shorter than
480 the maximum length of an unencrypted symlink. For example, on an
481 EXT4 filesystem with a 4K block size, unencrypted symlinks can be up
482 to 4095 bytes long, while encrypted symlinks can only be up to 4093
483 bytes long (both lengths excluding the terminating null).
484
485Note that mmap *is* supported. This is possible because the pagecache
486for an encrypted file contains the plaintext, not the ciphertext.
487
488Without the key
489---------------
490
491Some filesystem operations may be performed on encrypted regular
492files, directories, and symlinks even before their encryption key has
493been provided:
494
495- File metadata may be read, e.g. using stat().
496
497- Directories may be listed, in which case the filenames will be
498 listed in an encoded form derived from their ciphertext. The
499 current encoding algorithm is described in `Filename hashing and
500 encoding`_. The algorithm is subject to change, but it is
501 guaranteed that the presented filenames will be no longer than
502 NAME_MAX bytes, will not contain the ``/`` or ``\0`` characters, and
503 will uniquely identify directory entries.
504
505 The ``.`` and ``..`` directory entries are special. They are always
506 present and are not encrypted or encoded.
507
508- Files may be deleted. That is, nondirectory files may be deleted
509 with unlink() as usual, and empty directories may be deleted with
510 rmdir() as usual. Therefore, ``rm`` and ``rm -r`` will work as
511 expected.
512
513- Symlink targets may be read and followed, but they will be presented
514 in encrypted form, similar to filenames in directories. Hence, they
515 are unlikely to point to anywhere useful.
516
517Without the key, regular files cannot be opened or truncated.
518Attempts to do so will fail with ENOKEY. This implies that any
519regular file operations that require a file descriptor, such as
520read(), write(), mmap(), fallocate(), and ioctl(), are also forbidden.
521
522Also without the key, files of any type (including directories) cannot
523be created or linked into an encrypted directory, nor can a name in an
524encrypted directory be the source or target of a rename, nor can an
525O_TMPFILE temporary file be created in an encrypted directory. All
526such operations will fail with ENOKEY.
527
528It is not currently possible to backup and restore encrypted files
529without the encryption key. This would require special APIs which
530have not yet been implemented.
531
532Encryption policy enforcement
533=============================
534
535After an encryption policy has been set on a directory, all regular
536files, directories, and symbolic links created in that directory
537(recursively) will inherit that encryption policy. Special files ---
538that is, named pipes, device nodes, and UNIX domain sockets --- will
539not be encrypted.
540
541Except for those special files, it is forbidden to have unencrypted
542files, or files encrypted with a different encryption policy, in an
543encrypted directory tree. Attempts to link or rename such a file into
544an encrypted directory will fail with EPERM. This is also enforced
545during ->lookup() to provide limited protection against offline
546attacks that try to disable or downgrade encryption in known locations
547where applications may later write sensitive data. It is recommended
548that systems implementing a form of "verified boot" take advantage of
549this by validating all top-level encryption policies prior to access.
550
551Implementation details
552======================
553
554Encryption context
555------------------
556
557An encryption policy is represented on-disk by a :c:type:`struct
558fscrypt_context`. It is up to individual filesystems to decide where
559to store it, but normally it would be stored in a hidden extended
560attribute. It should *not* be exposed by the xattr-related system
561calls such as getxattr() and setxattr() because of the special
562semantics of the encryption xattr. (In particular, there would be
563much confusion if an encryption policy were to be added to or removed
564from anything other than an empty directory.) The struct is defined
565as follows::
566
567 #define FS_KEY_DESCRIPTOR_SIZE 8
568 #define FS_KEY_DERIVATION_NONCE_SIZE 16
569
570 struct fscrypt_context {
571 u8 format;
572 u8 contents_encryption_mode;
573 u8 filenames_encryption_mode;
574 u8 flags;
575 u8 master_key_descriptor[FS_KEY_DESCRIPTOR_SIZE];
576 u8 nonce[FS_KEY_DERIVATION_NONCE_SIZE];
577 };
578
579Note that :c:type:`struct fscrypt_context` contains the same
580information as :c:type:`struct fscrypt_policy` (see `Setting an
581encryption policy`_), except that :c:type:`struct fscrypt_context`
582also contains a nonce. The nonce is randomly generated by the kernel
583and is used to derive the inode's encryption key as described in
584`Per-file keys`_.
585
586Data path changes
587-----------------
588
589For the read path (->readpage()) of regular files, filesystems can
590read the ciphertext into the page cache and decrypt it in-place. The
591page lock must be held until decryption has finished, to prevent the
592page from becoming visible to userspace prematurely.
593
594For the write path (->writepage()) of regular files, filesystems
595cannot encrypt data in-place in the page cache, since the cached
596plaintext must be preserved. Instead, filesystems must encrypt into a
597temporary buffer or "bounce page", then write out the temporary
598buffer. Some filesystems, such as UBIFS, already use temporary
599buffers regardless of encryption. Other filesystems, such as ext4 and
600F2FS, have to allocate bounce pages specially for encryption.
601
602Filename hashing and encoding
603-----------------------------
604
605Modern filesystems accelerate directory lookups by using indexed
606directories. An indexed directory is organized as a tree keyed by
607filename hashes. When a ->lookup() is requested, the filesystem
608normally hashes the filename being looked up so that it can quickly
609find the corresponding directory entry, if any.
610
611With encryption, lookups must be supported and efficient both with and
612without the encryption key. Clearly, it would not work to hash the
613plaintext filenames, since the plaintext filenames are unavailable
614without the key. (Hashing the plaintext filenames would also make it
615impossible for the filesystem's fsck tool to optimize encrypted
616directories.) Instead, filesystems hash the ciphertext filenames,
617i.e. the bytes actually stored on-disk in the directory entries. When
618asked to do a ->lookup() with the key, the filesystem just encrypts
619the user-supplied name to get the ciphertext.
620
621Lookups without the key are more complicated. The raw ciphertext may
622contain the ``\0`` and ``/`` characters, which are illegal in
623filenames. Therefore, readdir() must base64-encode the ciphertext for
624presentation. For most filenames, this works fine; on ->lookup(), the
625filesystem just base64-decodes the user-supplied name to get back to
626the raw ciphertext.
627
628However, for very long filenames, base64 encoding would cause the
629filename length to exceed NAME_MAX. To prevent this, readdir()
630actually presents long filenames in an abbreviated form which encodes
631a strong "hash" of the ciphertext filename, along with the optional
632filesystem-specific hash(es) needed for directory lookups. This
633allows the filesystem to still, with a high degree of confidence, map
634the filename given in ->lookup() back to a particular directory entry
635that was previously listed by readdir(). See :c:type:`struct
636fscrypt_digested_name` in the source for more details.
637
638Note that the precise way that filenames are presented to userspace
639without the key is subject to change in the future. It is only meant
640as a way to temporarily present valid filenames so that commands like
641``rm -r`` work as expected on encrypted directories.