← Documents Documentation/filesystems/fscrypt.rst GitHub 원문 ↗

Linux 6.18.37 · Filesystems

Filesystem-level encryption (fscrypt)

fscrypt의 위협 모델, 키 계층, 암호화 모드, 정책·키 ioctl, 접근 의미, 인라인·hardware-wrapped key와 테스트를 다루는 전문 번역입니다.

Source pathDocumentation/filesystems/fscrypt.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

fscrypt.rst:1-1599

fscrypt는 ext4, F2FS, UBIFS, CephFS에 통합되는 파일시스템 수준 암호화 계층입니다. 디렉터리 트리별 master key와 정책을 사용해 파일 내용과 파일 이름을 보호하고, 파일 크기·권한·시간 같은 비이름 메타데이터는 보호 범위 밖에 둡니다.

새 배포에서는 v2 정책, 강한 무작위 master key, AES-256-XTS/AES-256-CBC-CTS 또는 HCTR2 조합을 기본으로 검토해야 합니다. AES 가속이 없는 장치는 Adiantum이 적합합니다. 키 제거는 열린 파일, 사용자 공간 복사본, VFS 잔여 메모리까지 자동으로 해결하지 않으므로 운영 절차가 암호화 알고리즘만큼 중요합니다.

API 사용자는 정책 구조체의 reserved 필드를 0으로 초기화하고, ADD·REMOVE·STATUS ioctl의 claim 모델과 반환 status flags를 정확히 처리해야 합니다. hardware-wrapped key는 내용 키의 커널 메모리 노출을 줄이지만 인라인 하드웨어와 IV_INO_LBLK 정책에 종속되며 파일 이름 하위 키까지 보호하지는 않습니다.

fscrypt 전체 수명 주기
강한 master key 생성 또는 저엔트로피 비밀에 전용 KDF 적용빈 디렉터리에 v2 policy 설정ADD_KEY로 파일시스템 keyring과 사용자 claim 생성inode nonce·정책 flag에 따라 내용·이름 하위 키 파생VFS 평문과 디스크 암호문 사이에서 software 또는 inline 암복호화파일을 닫고 REMOVE_KEY의 status flags가 사라질 때까지 제거xfstests encrypt·inlinecrypt·dummy encryption 매트릭스로 검증

정책 생성부터 잠금·제거·검증까지의 핵심 흐름입니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

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

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

파일시스템 수준 암호화의 역할과 적용 범위

1-49

fscrypt는 파일시스템이 연결해 파일과 디렉터리의 투명 암호화를 제공할 수 있게 하는 커널 라이브러리입니다. 이 문서에서 `fscrypt`는 사용자 공간 도구가 아니라 `fs/crypto/`에 구현된 커널 부분을 뜻합니다. 명령행 사용법은 사용자 공간 `fscrypt` 문서를 참고해야 합니다.

커널 API를 직접 호출하기보다는 `fscrypt`, `fscryptctl`, Android 키 관리 시스템 같은 검증된 사용자 공간 도구를 사용하는 것이 권장됩니다. 기존 도구는 자체 키 관리 코드를 작성하면서 보안 결함을 만들 가능성을 줄입니다. 다만 완전성을 위해 이 문서는 커널 API도 모두 설명합니다.

dm-crypt가 블록 장치 전체를 암호화하는 것과 달리 fscrypt는 파일시스템 계층에서 동작합니다. 따라서 파일마다 다른 키를 쓸 수 있고 같은 파일시스템 안에 평문 파일과 암호화 파일을 함께 둘 수 있습니다. 사용자별 저장 데이터를 암호학적으로 분리해야 하는 다중 사용자 시스템에 유용하지만, 파일 이름을 제외한 파일 크기·권한·시간 같은 파일시스템 메타데이터는 암호화하지 않습니다.

스택형 파일시스템인 eCryptfs와 달리 fscrypt는 ext4, F2FS, UBIFS, CephFS에 직접 통합됩니다. 평문 페이지와 암호문 페이지를 페이지 캐시에 이중 보관하지 않으므로 메모리 사용량을 거의 절반으로 줄이고, dentry와 inode도 절반만 필요합니다. eCryptfs의 암호화 파일 이름 한도는 143바이트이지만 fscrypt는 `NAME_MAX`인 255바이트를 허용합니다. 권한 없는 사용자도 별도 마운트 없이 API를 사용할 수 있습니다.

fscrypt는 기존 파일의 제자리 암호화를 지원하지 않습니다. 먼저 비어 있는 디렉터리에 암호화 정책을 설정하고 사용자 공간이 키를 제공해야 합니다. 그 뒤 해당 트리에 새로 생성되는 일반 파일, 디렉터리, 심볼릭 링크가 투명하게 암호화됩니다.

fscrypt 적용 흐름
지원 파일시스템에서 빈 디렉터리 준비디렉터리에 fscrypt 암호화 정책 설정사용자 공간이 올바른 master key 추가새 일반 파일·디렉터리·심볼릭 링크가 정책 상속VFS에서는 평문처럼 접근하고 디스크에는 암호문 저장

빈 디렉터리에 정책과 키를 결합해 새 객체부터 암호화하는 흐름입니다.

=====================================
Filesystem-level encryption (fscrypt)
=====================================

Introduction
============

fscrypt is a library which filesystems can hook into to support
transparent encryption of files and directories.

Note: "fscrypt" in this document refers to the kernel-level portion,
implemented in ``fs/crypto/``, as opposed to the userspace tool
`fscrypt <https://github.com/google/fscrypt>`_.  This document only
covers the kernel-level portion.  For command-line examples of how to
use encryption, see the documentation for the userspace tool `fscrypt
<https://github.com/google/fscrypt>`_.  Also, it is recommended to use
the fscrypt userspace tool, or other existing userspace tools such as
`fscryptctl <https://github.com/google/fscryptctl>`_ or `Android's key
management system
<https://source.android.com/security/encryption/file-based>`_, over
using the kernel's API directly.  Using existing tools reduces the
chance of introducing your own security bugs.  (Nevertheless, for
completeness this documentation covers the kernel's API anyway.)

Unlike dm-crypt, fscrypt operates at the filesystem level rather than
at the block device level.  This allows it to encrypt different files
with different keys and to have unencrypted files on the same
filesystem.  This is useful for multi-user systems where each user's
data-at-rest needs to be cryptographically isolated from the others.
However, except for filenames, fscrypt does not encrypt filesystem
metadata.

Unlike eCryptfs, which is a stacked filesystem, fscrypt is integrated
directly into supported filesystems --- currently ext4, F2FS, UBIFS,
and CephFS.  This allows encrypted files to be read and written
without caching both the decrypted and encrypted pages in the
pagecache, thereby nearly halving the memory used and bringing it in
line with unencrypted files.  Similarly, half as many dentries and
inodes are needed.  eCryptfs also limits encrypted filenames to 143
bytes, causing application compatibility issues; fscrypt allows the
full 255 bytes (NAME_MAX).  Finally, unlike eCryptfs, the fscrypt API
can be used by unprivileged users, with no need to mount anything.

fscrypt does not support encrypting files in-place.  Instead, it
supports marking an empty directory as encrypted.  Then, after
userspace provides the key, all regular files, directories, and
symbolic links created in that directory tree are transparently
encrypted.

위협 모델과 v1 정책의 한계

50-193

강한 암호화 키를 선택했다는 전제에서 fscrypt는 블록 장치 내용이 특정 한 시점에 영구적으로 오프라인 유출되었을 때 파일 내용과 파일 이름의 기밀성을 보호합니다. 파일 크기, 권한, 타임스탬프, 확장 속성 같은 파일 이름 외 메타데이터와 파일의 hole 위치·존재는 숨기지 않습니다.

공격자가 파일시스템을 오프라인으로 조작한 뒤 권한 있는 사용자가 나중에 그 파일시스템에 접근하게 만들 수 있다면 기밀성이나 무결성을 보장하지 않습니다. 저장장치 암호화 전반과 마찬가지로 온라인 공격에 대한 보호도 제한적입니다.

타이밍·전자기파 같은 부채널 공격 저항성은 Linux Crypto API 구현이나 인라인 암호화 하드웨어의 저항성만큼만 강합니다. 테이블 기반 AES처럼 취약한 구현을 쓰면 온라인 시스템을 상대로 부채널 공격이 가능할 수 있고, 복호화 데이터를 소비하는 애플리케이션도 공격 대상이 됩니다.

키가 추가된 뒤에는 같은 시스템의 다른 사용자에게 평문 파일 내용이나 이름을 fscrypt 자체가 숨기지 않습니다. 파일 모드 비트, POSIX ACL, LSM, namespace 같은 기존 접근 제어를 사용해야 합니다. 키가 있는 동안 시스템 관점의 기밀성은 암호 수학이 아니라 커널의 정확성에 의존하므로, 별도의 암호화 전용 접근 검사는 기존 커널 접근 제어와 대부분 중복됩니다.

hardware-wrapped key를 쓰지 않는다면 임의 커널 메모리를 읽을 수 있는 공격자는 현재 사용 중인 모든 fscrypt 키를 탈취할 수 있습니다. 갑작스러운 전원 차단 뒤 메모리에 키가 잠시 남을 수 있는 cold boot 공격도 포함됩니다. hardware-wrapped key는 master key와 파일 내용 암호화 키를 보호하지만 파일 이름 키 같은 다른 하위 키까지 보호하지는 않습니다.

`FS_IOC_REMOVE_ENCRYPTION_KEY` 또는 `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`는 커널 메모리의 master key를 지우고, 그 키로 잠금 해제된 캐시 inode를 퇴거시켜 per-file key도 지우려 합니다. 그러나 사용 중인 파일의 per-file key는 제거되지 않으므로 파일과 디렉터리를 닫고, 영향을 받는 암호화 디렉터리를 작업 디렉터리로 쓰는 프로세스도 종료해야 효과가 가장 큽니다.

커널은 사용자 공간이 가진 master key 복사본을 지울 수 없습니다. 사용자 공간은 `FS_IOC_ADD_ENCRYPTION_KEY` 직후 자체 복사본을 지우고, 더 상위 키 계층의 비밀도 같은 방식으로 처리해야 합니다. 키가 swap으로 나가지 않도록 `mlock()` 같은 방어도 적용해야 합니다.

VFS 캐시에 있던 복호화 내용과 파일 이름은 해제되지만 일반적으로 덮어쓰지는 않으므로, 키를 지운 뒤에도 해제 메모리에서 일부를 복구할 수 있습니다. 커널 명령행의 `init_on_free=1`로 일부 완화할 수 있지만 성능 비용이 있습니다. 비밀 키가 CPU 레지스터나 여기서 명시하지 않은 다른 위치에 남을 가능성도 있습니다.

root 권한 또는 임의 커널 코드 실행 권한을 얻은 공격자는 사용 중인 fscrypt 키로 보호되는 데이터를 자유롭게 유출할 수 있으므로 일반적으로 전체 시스템 침해 상황에서는 의미 있는 보호를 제공하지 못합니다. 공격 내내 키가 없었던 데이터는 키 제거의 한계를 제외하면 계속 보호됩니다.

hardware-wrapped key를 쓰면 전체 시스템을 침해한 공격자도 전원을 끈 뒤 사용할 수 있는 형태로 master key나 파일 내용 키를 반출할 수 없습니다. 공격자의 시간이나 대역폭이 크게 제한되어 일부 데이터만 온라인으로 빼내고 나머지는 나중의 오프라인 공격에 의존해야 하는 상황에서 유용할 수 있습니다.

v1 정책은 제공된 master key가 올바른지 검증하지 않습니다. 악의적 사용자가 읽기 전용으로 접근 가능한 다른 사용자의 암호화 파일에 잠시 잘못된 키를 연결하면 파일시스템 캐시 때문에 실제 사용자의 올바른 keyring보다 잘못된 키가 계속 사용될 수 있어 읽기 전용 접근 의미를 깨뜨립니다. 또한 per-file key 하나가 노출되면 그 기반 master key도 노출되고, 비root 사용자는 키를 안전하게 제거할 수 없습니다. v2 정책은 이 문제를 모두 해결하므로 새 암호화 디렉터리에는 v2를 권장합니다.

fscrypt 위협 경계
공격·노출보호 범위남는 한계
단일 시점 오프라인 장치 유출강한 키로 내용·파일 이름 보호비이름 메타데이터와 hole은 노출
온라인 부채널Crypto API·하드웨어 구현 수준애플리케이션도 공격 가능
임의 커널 메모리 읽기hardware-wrapped key가 일부 키 보호파일 이름 등 소프트웨어 하위 키는 노출
root·임의 커널 코드 실행공격 내내 부재한 키의 데이터사용 중 키의 데이터는 유출 가능
키 제거 뒤master key와 가능한 per-file key 삭제사용 중 파일·VFS 잔여·사용자 공간 복사본

공격 유형별 보호 범위와 운영상 주의점입니다.

Threat model
============

Offline attacks
---------------

Provided that userspace chooses a strong encryption key, fscrypt
protects the confidentiality of file contents and filenames in the
event of a single point-in-time permanent offline compromise of the
block device content.  fscrypt does not protect the confidentiality of
non-filename metadata, e.g. file sizes, file permissions, file
timestamps, and extended attributes.  Also, the existence and location
of holes (unallocated blocks which logically contain all zeroes) in
files is not protected.

fscrypt is not guaranteed to protect confidentiality or authenticity
if an attacker is able to manipulate the filesystem offline prior to
an authorized user later accessing the filesystem.

Online attacks
--------------

fscrypt (and storage encryption in general) can only provide limited
protection against online attacks.  In detail:

Side-channel attacks
~~~~~~~~~~~~~~~~~~~~

fscrypt is only resistant to side-channel attacks, such as timing or
electromagnetic attacks, to the extent that the underlying Linux
Cryptographic API algorithms or inline encryption hardware are.  If a
vulnerable algorithm is used, such as a table-based implementation of
AES, it may be possible for an attacker to mount a side channel attack
against the online system.  Side channel attacks may also be mounted
against applications consuming decrypted data.

Unauthorized file access
~~~~~~~~~~~~~~~~~~~~~~~~

After an encryption key has been added, fscrypt does not hide the
plaintext file contents or filenames from other users on the same
system.  Instead, existing access control mechanisms such as file mode
bits, POSIX ACLs, LSMs, or namespaces should be used for this purpose.

(For the reasoning behind this, understand that while the key is
added, the confidentiality of the data, from the perspective of the
system itself, is *not* protected by the mathematical properties of
encryption but rather only by the correctness of the kernel.
Therefore, any encryption-specific access control checks would merely
be enforced by kernel *code* and therefore would be largely redundant
with the wide variety of access control mechanisms already available.)

Read-only kernel memory compromise
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Unless `hardware-wrapped keys`_ are used, an attacker who gains the
ability to read from arbitrary kernel memory, e.g. by mounting a
physical attack or by exploiting a kernel security vulnerability, can
compromise all fscrypt keys that are currently in-use.  This also
extends to cold boot attacks; if the system is suddenly powered off,
keys the system was using may remain in memory for a short time.

However, if hardware-wrapped keys are used, then the fscrypt master
keys and file contents encryption keys (but not other types of fscrypt
subkeys such as filenames encryption keys) are protected from
compromises of arbitrary kernel memory.

In addition, fscrypt allows encryption keys to be removed from the
kernel, which may protect them from later compromise.

In more detail, the FS_IOC_REMOVE_ENCRYPTION_KEY ioctl (or the
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS ioctl) can wipe a master
encryption key from kernel memory.  If it does so, it will also try to
evict all cached inodes which had been "unlocked" using the key,
thereby wiping their per-file keys and making them once again appear
"locked", i.e. in ciphertext or encrypted form.

However, these ioctls have some limitations:

- Per-file keys for in-use files will *not* be removed or wiped.
  Therefore, for maximum effect, userspace should close the relevant
  encrypted files and directories before removing a master key, as
  well as kill any processes whose working directory is in an affected
  encrypted directory.

- The kernel cannot magically wipe copies of the master key(s) that
  userspace might have as well.  Therefore, userspace must wipe all
  copies of the master key(s) it makes as well; normally this should
  be done immediately after FS_IOC_ADD_ENCRYPTION_KEY, without waiting
  for FS_IOC_REMOVE_ENCRYPTION_KEY.  Naturally, the same also applies
  to all higher levels in the key hierarchy.  Userspace should also
  follow other security precautions such as mlock()ing memory
  containing keys to prevent it from being swapped out.

- In general, decrypted contents and filenames in the kernel VFS
  caches are freed but not wiped.  Therefore, portions thereof may be
  recoverable from freed memory, even after the corresponding key(s)
  were wiped.  To partially solve this, you can add init_on_free=1 to
  your kernel command line.  However, this has a performance cost.

- Secret keys might still exist in CPU registers or in other places
  not explicitly considered here.

Full system compromise
~~~~~~~~~~~~~~~~~~~~~~

An attacker who gains "root" access and/or the ability to execute
arbitrary kernel code can freely exfiltrate data that is protected by
any in-use fscrypt keys.  Thus, usually fscrypt provides no meaningful
protection in this scenario.  (Data that is protected by a key that is
absent throughout the entire attack remains protected, modulo the
limitations of key removal mentioned above in the case where the key
was removed prior to the attack.)

However, if `hardware-wrapped keys`_ are used, such attackers will be
unable to exfiltrate the master keys or file contents keys in a form
that will be usable after the system is powered off.  This may be
useful if the attacker is significantly time-limited and/or
bandwidth-limited, so they can only exfiltrate some data and need to
rely on a later offline attack to exfiltrate the rest of it.

Limitations of v1 policies
~~~~~~~~~~~~~~~~~~~~~~~~~~

v1 encryption policies have some weaknesses with respect to online
attacks:

- There is no verification that the provided master key is correct.
  Therefore, a malicious user can temporarily associate the wrong key
  with another user's encrypted files to which they have read-only
  access.  Because of filesystem caching, the wrong key will then be
  used by the other user's accesses to those files, even if the other
  user has the correct key in their own keyring.  This violates the
  meaning of "read-only access".

- A compromise of a per-file key also compromises the master key from
  which it was derived.

- Non-root users cannot securely remove encryption keys.

All the above problems are fixed with v2 encryption policies.  For
this reason among others, it is recommended to use v2 encryption
policies on all new encrypted directories.

Master key, KDF, per-file key와 IV 정책

194-355

이 절은 raw key 사용을 전제로 합니다. hardware-wrapped key를 쓰면 키 계층이 일부 달라집니다. 각 암호화 디렉터리 트리는 하나의 master key로 보호되며 master key는 최대 64바이트입니다. 내용 모드와 파일 이름 모드 중 더 강한 보안 강도 이상이어야 하므로 AES-256 모드가 하나라도 있으면 최소 32바이트가 필요합니다. v1 정책에서 AES-256-XTS를 쓰는 경우에는 64바이트가 필요합니다.

사용자 공간은 디렉터리 트리를 잠금 해제할 올바른 master key를 제공합니다. master key 수에는 제한이 없고, 하나의 키가 여러 파일시스템에 걸친 여러 디렉터리 트리를 보호할 수 있습니다.

master key는 같은 길이의 무작위 바이트열과 구별할 수 없는 실제 암호 키여야 합니다. 암호를 그대로 사용하거나 짧은 키를 0으로 채우거나 반복해서는 안 됩니다. CSPRNG로 생성하거나 KDF로 만들어야 합니다. 커널은 key stretching을 하지 않으므로 passphrase 같은 저엔트로피 비밀에서 만들 때는 `scrypt`, `PBKDF2`, `Argon2`처럼 그 목적에 맞는 KDF가 필수입니다.

한 가지 예외를 제외하면 fscrypt는 master key를 직접 암호화에 쓰지 않고 KDF 입력으로만 씁니다. v1과 v2는 KDF가 다르므로 같은 키를 두 정책 버전에 재사용해서는 안 됩니다. 이 특정 재사용에 알려진 현실 공격이 없더라도 암호학적 증명과 분석이 더 이상 적용되지 않습니다.

v1 KDF는 per-file encryption key만 파생합니다. 파일의 16바이트 nonce를 AES 키로 삼아 AES-128-ECB로 master key를 암호화하고, 결과 암호문이 필요한 길이보다 길면 잘라 사용합니다. 이 방식은 임의 설계이고 가역적입니다.

v2는 HKDF-SHA512를 사용합니다. master key를 input keying material로 넣고 salt는 쓰지 않으며, 파생할 키 종류마다 다른 application-specific information string을 사용합니다. per-file key의 정보 문자열은 `fscrypt\0`, context byte, 파일 nonce로 구성되고 다른 하위 키에는 다른 context byte를 씁니다. HKDF는 더 유연하고 비가역적이며 master key 엔트로피를 고르게 분배하고 표준화되어 있어 v1 방식보다 선호됩니다.

새 암호화 inode가 생성되면 커널은 무작위 16바이트 nonce를 만들어 inode의 암호화 xattr에 저장하고 master key와 nonce에서 파일 키를 파생합니다. 같은 평문이 서로 다른 파일에서 같은 암호문이 되는 것을 막는 tweak 역할을 합니다. 키 래핑보다 파생을 택한 이유는 wrapped key가 xattr을 키워 inode table에 inline으로 들어갈 가능성을 낮추는 반면, 현재 여러 master key로 같은 파일을 열거나 master key를 회전할 요구는 없기 때문입니다. master key 자체는 사용자 공간에서 래핑할 수 있습니다.

Adiantum은 내용과 파일 이름 모두에 쓸 수 있고 8바이트 data unit index와 16바이트 per-file nonce를 함께 담는 긴 IV를 받습니다. 키 하나의 오버헤드도 AES-256-XTS보다 큽니다. `FSCRYPT_POLICY_FLAG_DIRECT_KEY`를 설정하면 per-file key를 만들지 않고 파일 nonce를 모든 내용·이름 암호화 IV에 포함합니다.

DIRECT_KEY를 v1에서 사용하면 master key 자체로 암호화하므로 그 키를 다른 v1 정책을 포함한 어떤 용도로도 재사용하면 안 됩니다. v2에서는 KDF로 파생한 per-mode key를 쓰므로 같은 master key를 다른 v2 정책에 재사용할 수 있습니다.

`FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64`에서는 master key, 암호화 모드 번호, 파일시스템 UUID로 키를 파생합니다. 보통 같은 master key의 모든 파일이 하나의 내용 키와 하나의 이름 키를 공유하고, 파일별 차이는 IV에 inode 번호를 넣어 확보합니다. 이 때문에 파일시스템 축소가 허용되지 않을 수 있습니다. UFS 표준처럼 요청당 IV가 64비트뿐이고 keyslot이 적은 인라인 암호화 하드웨어에 최적화된 형식입니다.

`IV_INO_LBLK_32`도 같은 계열이지만 master key에서 파생한 SipHash 키로 inode 번호를 SipHash-2-4 해시한 뒤 파일 data unit index를 더하고 mod 2^32를 취해 32비트 IV를 만듭니다. eMMC v5.2처럼 요청당 IV 32비트와 적은 keyslot만 지원하는 하드웨어용입니다. 어느 정도 IV 재사용이 발생하므로 하드웨어 제약 때문에 필요할 때만 사용해야 합니다.

v2 master key에는 KDF로 고유한 16바이트 key identifier도 파생하며, 키를 안정적으로 식별해야 하므로 평문으로 저장합니다. 평문 파일 이름에 secret-keyed dirhash를 쓰는 디렉터리는 디렉터리마다 128비트 SipHash-2-4 키를 다른 KDF context로 파생합니다. 현재 이 방식은 casefolded, 즉 대소문자를 구분하지 않는 암호화 디렉터리만 사용합니다.

fscrypt 키 계층
CSPRNG 또는 강한 사용자 공간 KDF로 master key 생성v1 AES-128-ECB 또는 v2 HKDF-SHA512 선택기본 정책: inode의 16바이트 nonce로 per-file key 파생DIRECT_KEY: nonce를 IV에 넣고 v2는 per-mode key 사용IV_INO_LBLK 정책: 모드·UUID 기반 공유 키와 inode 기반 IV 사용별도 context로 key identifier·dirhash·파일 이름 키 파생

master key에서 정책과 inode별 하위 키가 갈라지는 관계입니다.

정책별 키·IV 구성
정책내용 키파일 구분주요 목적
기본per-file key16바이트 inode nonce일반적인 안전한 기본값
DIRECT_KEYv1 master / v2 per-modenonce를 긴 IV에 포함Adiantum 메모리·성능 최적화
IV_INO_LBLK_64master·mode·UUID 공유 키32비트 inode + 32비트 indexUFS 64비트 IV
IV_INO_LBLK_32공유 키SipHash(inode)+index mod 2^32eMMC 5.2 32비트 IV

파일별 분리 방법과 하드웨어 목적을 비교합니다.

Key hierarchy
=============

Note: this section assumes the use of raw keys rather than
hardware-wrapped keys.  The use of hardware-wrapped keys modifies the
key hierarchy slightly.  For details, see `Hardware-wrapped keys`_.

Master Keys
-----------

Each encrypted directory tree is protected by a *master key*.  Master
keys can be up to 64 bytes long, and must be at least as long as the
greater of the security strength of the contents and filenames
encryption modes being used.  For example, if any AES-256 mode is
used, the master key must be at least 256 bits, i.e. 32 bytes.  A
stricter requirement applies if the key is used by a v1 encryption
policy and AES-256-XTS is used; such keys must be 64 bytes.

To "unlock" an encrypted directory tree, userspace must provide the
appropriate master key.  There can be any number of master keys, each
of which protects any number of directory trees on any number of
filesystems.

Master keys must be real cryptographic keys, i.e. indistinguishable
from random bytestrings of the same length.  This implies that users
**must not** directly use a password as a master key, zero-pad a
shorter key, or repeat a shorter key.  Security cannot be guaranteed
if userspace makes any such error, as the cryptographic proofs and
analysis would no longer apply.

Instead, users should generate master keys either using a
cryptographically secure random number generator, or by using a KDF
(Key Derivation Function).  The kernel does not do any key stretching;
therefore, if userspace derives the key from a low-entropy secret such
as a passphrase, it is critical that a KDF designed for this purpose
be used, such as scrypt, PBKDF2, or Argon2.

Key derivation function
-----------------------

With one exception, fscrypt never uses the master key(s) for
encryption directly.  Instead, they are only used as input to a KDF
(Key Derivation Function) to derive the actual keys.

The KDF used for a particular master key differs depending on whether
the key is used for v1 encryption policies or for v2 encryption
policies.  Users **must not** use the same key for both v1 and v2
encryption policies.  (No real-world attack is currently known on this
specific case of key reuse, but its security cannot be guaranteed
since the cryptographic proofs and analysis would no longer apply.)

For v1 encryption policies, the KDF only supports deriving per-file
encryption keys.  It works by encrypting the master key with
AES-128-ECB, using the file's 16-byte nonce as the AES key.  The
resulting ciphertext is used as the derived key.  If the ciphertext is
longer than needed, then it is truncated to the needed length.

For v2 encryption policies, the KDF is HKDF-SHA512.  The master key is
passed as the "input keying material", no salt is used, and a distinct
"application-specific information string" is used for each distinct
key to be derived.  For example, when a per-file encryption key is
derived, the application-specific information string is the file's
nonce prefixed with "fscrypt\\0" and a context byte.  Different
context bytes are used for other types of derived keys.

HKDF-SHA512 is preferred to the original AES-128-ECB based KDF because
HKDF is more flexible, is nonreversible, and evenly distributes
entropy from the master key.  HKDF is also standardized and widely
used by other software, whereas the AES-128-ECB based KDF is ad-hoc.

Per-file encryption keys
------------------------

Since each master key can protect many files, it is necessary to
"tweak" the encryption of each file so that the same plaintext in two
files doesn't map to the same ciphertext, or vice versa.  In most
cases, fscrypt does this by deriving per-file keys.  When a new
encrypted inode (regular file, directory, or symlink) is created,
fscrypt randomly generates a 16-byte nonce and stores it in the
inode's encryption xattr.  Then, it uses a KDF (as described in `Key
derivation function`_) to derive the file's key from the master key
and nonce.

Key derivation was chosen over key wrapping because wrapped keys would
require larger xattrs which would be less likely to fit in-line in the
filesystem's inode table, and there didn't appear to be any
significant advantages to key wrapping.  In particular, currently
there is no requirement to support unlocking a file with multiple
alternative master keys or to support rotating master keys.  Instead,
the master keys may be wrapped in userspace, e.g. as is done by the
`fscrypt <https://github.com/google/fscrypt>`_ tool.

DIRECT_KEY policies
-------------------

The Adiantum encryption mode (see `Encryption modes and usage`_) is
suitable for both contents and filenames encryption, and it accepts
long IVs --- long enough to hold both an 8-byte data unit index and a
16-byte per-file nonce.  Also, the overhead of each Adiantum key is
greater than that of an AES-256-XTS key.

Therefore, to improve performance and save memory, for Adiantum a
"direct key" configuration is supported.  When the user has enabled
this by setting FSCRYPT_POLICY_FLAG_DIRECT_KEY in the fscrypt policy,
per-file encryption keys are not used.  Instead, whenever any data
(contents or filenames) is encrypted, the file's 16-byte nonce is
included in the IV.  Moreover:

- For v1 encryption policies, the encryption is done directly with the
  master key.  Because of this, users **must not** use the same master
  key for any other purpose, even for other v1 policies.

- For v2 encryption policies, the encryption is done with a per-mode
  key derived using the KDF.  Users may use the same master key for
  other v2 encryption policies.

IV_INO_LBLK_64 policies
-----------------------

When FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 is set in the fscrypt policy,
the encryption keys are derived from the master key, encryption mode
number, and filesystem UUID.  This normally results in all files
protected by the same master key sharing a single contents encryption
key and a single filenames encryption key.  To still encrypt different
files' data differently, inode numbers are included in the IVs.
Consequently, shrinking the filesystem may not be allowed.

This format is optimized for use with inline encryption hardware
compliant with the UFS standard, which supports only 64 IV bits per
I/O request and may have only a small number of keyslots.

IV_INO_LBLK_32 policies
-----------------------

IV_INO_LBLK_32 policies work like IV_INO_LBLK_64, except that for
IV_INO_LBLK_32, the inode number is hashed with SipHash-2-4 (where the
SipHash key is derived from the master key) and added to the file data
unit index mod 2^32 to produce a 32-bit IV.

This format is optimized for use with inline encryption hardware
compliant with the eMMC v5.2 standard, which supports only 32 IV bits
per I/O request and may have only a small number of keyslots.  This
format results in some level of IV reuse, so it should only be used
when necessary due to hardware limitations.

Key identifiers
---------------

For master keys used for v2 encryption policies, a unique 16-byte "key
identifier" is also derived using the KDF.  This value is stored in
the clear, since it is needed to reliably identify the key itself.

Dirhash keys
------------

For directories that are indexed using a secret-keyed dirhash over the
plaintext filenames, the KDF is also used to derive a 128-bit
SipHash-2-4 key per directory in order to hash filenames.  This works
just like deriving a per-file encryption key, except that a different
KDF context is used.  Currently, only casefolded ("case-insensitive")
encrypted directories use this style of hashing.

지원 암호화 모드와 커널 구성

356-472

fscrypt는 파일 내용용 모드 하나와 파일 이름용 모드 하나를 정책에 지정하며 디렉터리 트리마다 다른 조합을 쓸 수 있습니다. 지원 조합은 AES-256-XTS/AES-256-CBC-CTS, AES-256-XTS/AES-256-HCTR2, 내용·이름 모두 Adiantum, AES-128-CBC-ESSIV/AES-128-CBC-CTS, SM4-XTS/SM4-CBC-CTS입니다. API 이름에서 `CBC`는 CBC-ESSIV, `CTS`는 CBC-CTS를 뜻하므로 `FSCRYPT_MODE_AES_256_CTS`는 AES-256-CBC-CTS입니다.

암호문 길이 증가를 다루기 어려워 authenticated encryption mode는 현재 지원하지 않습니다. 내용은 XTS, CBC-ESSIV 또는 wide-block cipher를 사용하고, 파일 이름은 CBC-CTS 또는 wide-block cipher를 사용합니다.

권장 기본 조합은 AES-256-XTS/AES-256-CBC-CTS입니다. 커널이 fscrypt를 지원한다면 항상 지원된다고 보장되는 유일한 선택입니다. AES-256-XTS/AES-256-HCTR2는 파일 이름을 wide-block cipher로 업그레이드하는 좋은 선택입니다. wide-block cipher는 한 비트가 바뀌면 결과 전체가 뒤섞이는 tweakable super-pseudorandom permutation이므로 파일 이름 문제에 이상적이고, CBC-CTS는 대안 중 덜 나쁜 선택입니다.

AES 하드웨어 가속이 없어 AES가 느린 시스템에는 Adiantum을 권장합니다. Adiantum은 XChaCha12와 AES-256을 구성 요소로 사용하는 wide-block cipher이며 대부분의 작업을 XChaCha12가 수행하므로 AES 가속이 없을 때 훨씬 빠릅니다.

AES-128-CBC-ESSIV/AES-128-CBC-CTS 조합은 CPU AES 명령은 없지만 AES-CBC를 지원하고 AES-XTS는 지원하지 않는 CAAM·CESA 같은 비인라인 crypto engine을 위해 추가되었습니다. 그러나 CPU에서 AES를 직접 수행하는 편이 더 빠르고 Adiantum은 더 빠르다는 것이 확인되어 폐기 예정입니다.

SM4 조합은 국가 표준 준수가 요구되는 용도를 위한 선택이며, 다른 선택보다 암호 분석 검토가 제한적이므로 SM4가 의무인 경우에만 사용해야 합니다.

`CONFIG_FS_ENCRYPTION`은 AES-256-XTS와 AES-256-CBC-CTS를 포함한 기본 fscrypt 지원을 선택합니다. 최적 성능을 위해 CPU별 암호 가속을 켜야 합니다. 내용 암호화가 인라인 하드웨어에서 처리된다면 그 내용 모드가 Crypto API에 없어도 되지만, 파일 이름 모드는 여전히 Crypto API 구현이 필요합니다.

AES 기본 조합은 arm64에서 `CONFIG_CRYPTO_AES_ARM64_CE_BLK`, x86에서 `CONFIG_CRYPTO_AES_NI_INTEL`을 권장합니다. HCTR2에는 `CONFIG_CRYPTO_HCTR2`가 필수이며 플랫폼 AES와 POLYVAL 가속을 권장합니다. Adiantum에는 `CONFIG_CRYPTO_ADIANTUM`이 필수이고 NHPOLY1305의 NEON, SSE2, AVX2 구현을 플랫폼에 맞게 권장합니다. AES-128-CBC-ESSIV에는 `CONFIG_CRYPTO_ESSIV`, SHA-256과 AES-CBC 가속이 필요합니다.

지원 모드 조합
내용파일 이름판단
AES-256-XTSAES-256-CBC-CTS보장되는 권장 기본값
AES-256-XTSAES-256-HCTR2wide-block 파일 이름 권장 업그레이드
AdiantumAdiantumAES 가속이 없는 장치
AES-128-CBC-ESSIVAES-128-CBC-CTS폐기 예정
SM4-XTSSM4-CBC-CTS표준 준수가 의무일 때만

내용과 파일 이름에 허용되는 짝과 권장 용도입니다.

커널 구성 점검
대상필수·권장 구성
fscrypt 기본`CONFIG_FS_ENCRYPTION`
arm64 AES`CONFIG_CRYPTO_AES_ARM64_CE_BLK` 권장
x86 AES`CONFIG_CRYPTO_AES_NI_INTEL` 권장
HCTR2`CONFIG_CRYPTO_HCTR2`, AES·POLYVAL 가속
Adiantum`CONFIG_CRYPTO_ADIANTUM`, NHPOLY1305 플랫폼 가속
AES-128 ESSIV`CONFIG_CRYPTO_ESSIV`, SHA-256, AES-CBC

모드별 필수·권장 구성입니다.

Encryption modes and usage
==========================

fscrypt allows one encryption mode to be specified for file contents
and one encryption mode to be specified for filenames.  Different
directory trees are permitted to use different encryption modes.

Supported modes
---------------

Currently, the following pairs of encryption modes are supported:

- AES-256-XTS for contents and AES-256-CBC-CTS for filenames
- AES-256-XTS for contents and AES-256-HCTR2 for filenames
- Adiantum for both contents and filenames
- AES-128-CBC-ESSIV for contents and AES-128-CBC-CTS for filenames
- SM4-XTS for contents and SM4-CBC-CTS for filenames

Note: in the API, "CBC" means CBC-ESSIV, and "CTS" means CBC-CTS.
So, for example, FSCRYPT_MODE_AES_256_CTS means AES-256-CBC-CTS.

Authenticated encryption modes are not currently supported because of
the difficulty of dealing with ciphertext expansion.  Therefore,
contents encryption uses a block cipher in `XTS mode
<https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS>`_ or
`CBC-ESSIV mode
<https://en.wikipedia.org/wiki/Disk_encryption_theory#Encrypted_salt-sector_initialization_vector_(ESSIV)>`_,
or a wide-block cipher.  Filenames encryption uses a
block cipher in `CBC-CTS mode
<https://en.wikipedia.org/wiki/Ciphertext_stealing>`_ or a wide-block
cipher.

The (AES-256-XTS, AES-256-CBC-CTS) pair is the recommended default.
It is also the only option that is *guaranteed* to always be supported
if the kernel supports fscrypt at all; see `Kernel config options`_.

The (AES-256-XTS, AES-256-HCTR2) pair is also a good choice that
upgrades the filenames encryption to use a wide-block cipher.  (A
*wide-block cipher*, also called a tweakable super-pseudorandom
permutation, has the property that changing one bit scrambles the
entire result.)  As described in `Filenames encryption`_, a wide-block
cipher is the ideal mode for the problem domain, though CBC-CTS is the
"least bad" choice among the alternatives.  For more information about
HCTR2, see `the HCTR2 paper <https://eprint.iacr.org/2021/1441.pdf>`_.

Adiantum is recommended on systems where AES is too slow due to lack
of hardware acceleration for AES.  Adiantum is a wide-block cipher
that uses XChaCha12 and AES-256 as its underlying components.  Most of
the work is done by XChaCha12, which is much faster than AES when AES
acceleration is unavailable.  For more information about Adiantum, see
`the Adiantum paper <https://eprint.iacr.org/2018/720.pdf>`_.

The (AES-128-CBC-ESSIV, AES-128-CBC-CTS) pair was added to try to
provide a more efficient option for systems that lack AES instructions
in the CPU but do have a non-inline crypto engine such as CAAM or CESA
that supports AES-CBC (and not AES-XTS).  This is deprecated.  It has
been shown that just doing AES on the CPU is actually faster.
Moreover, Adiantum is faster still and is recommended on such systems.

The remaining mode pairs are the "national pride ciphers":

- (SM4-XTS, SM4-CBC-CTS)

Generally speaking, these ciphers aren't "bad" per se, but they
receive limited security review compared to the usual choices such as
AES and ChaCha.  They also don't bring much new to the table.  It is
suggested to only use these ciphers where their use is mandated.

Kernel config options
---------------------

Enabling fscrypt support (CONFIG_FS_ENCRYPTION) automatically pulls in
only the basic support from the crypto API needed to use AES-256-XTS
and AES-256-CBC-CTS encryption.  For optimal performance, it is
strongly recommended to also enable any available platform-specific
kconfig options that provide acceleration for the algorithm(s) you
wish to use.  Support for any "non-default" encryption modes typically
requires extra kconfig options as well.

Below, some relevant options are listed by encryption mode.  Note,
acceleration options not listed below may be available for your
platform; refer to the kconfig menus.  File contents encryption can
also be configured to use inline encryption hardware instead of the
kernel crypto API (see `Inline encryption support`_); in that case,
the file contents mode doesn't need to supported in the kernel crypto
API, but the filenames mode still does.

- AES-256-XTS and AES-256-CBC-CTS
    - Recommended:
        - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
        - x86: CONFIG_CRYPTO_AES_NI_INTEL

- AES-256-HCTR2
    - Mandatory:
        - CONFIG_CRYPTO_HCTR2
    - Recommended:
        - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
        - arm64: CONFIG_CRYPTO_POLYVAL_ARM64_CE
        - x86: CONFIG_CRYPTO_AES_NI_INTEL
        - x86: CONFIG_CRYPTO_POLYVAL_CLMUL_NI

- Adiantum
    - Mandatory:
        - CONFIG_CRYPTO_ADIANTUM
    - Recommended:
        - arm32: CONFIG_CRYPTO_NHPOLY1305_NEON
        - arm64: CONFIG_CRYPTO_NHPOLY1305_NEON
        - x86: CONFIG_CRYPTO_NHPOLY1305_SSE2
        - x86: CONFIG_CRYPTO_NHPOLY1305_AVX2

- AES-128-CBC-ESSIV and AES-128-CBC-CTS:
    - Mandatory:
        - CONFIG_CRYPTO_ESSIV
        - CONFIG_CRYPTO_SHA256 or another SHA-256 implementation
    - Recommended:
        - AES-CBC acceleration

파일 내용과 파일 이름 암호화 방식

473-566

파일 내용은 독립적으로 암복호화되는 data unit으로 나뉘며 IV에는 파일 안에서 0부터 시작하는 data unit index가 포함됩니다. 따라서 암호화 파일에서 `FALLOC_FL_COLLAPSE_RANGE`와 `FALLOC_FL_INSERT_RANGE`처럼 data unit 위치를 바꾸는 연산은 지원하지 않습니다.

UBIFS를 제외한 파일시스템은 고정 크기 data unit을 사용합니다. 기본 크기는 파일시스템 블록 크기이고 v2 정책의 `log2_data_unit_size`로 더 작은 지원 크기를 선택할 수 있습니다. 마지막 unit은 0으로 채웁니다. UBIFS는 압축될 수 있는 가변 크기 data node를 단위로 쓰고 16바이트 배수로 패딩하며 sub-block data unit은 쓰지 않습니다.

압축을 지원하는 파일시스템에서는 압축 뒤 암호화합니다. F2FS 압축 파일도 고정 크기 data unit을 사용하며 압축되지 않은 범위나 hole과 일관되게 다룹니다.

기본 정책의 IV는 per-file key와 data unit index로 구성됩니다. DIRECT_KEY에서는 IV 비트 0~63에 index, 비트 64~191에 16바이트 nonce를 둡니다. IV_INO_LBLK_64에서는 비트 0~31에 index, 비트 32~63에 inode 번호를 넣으며 둘 다 32비트에 맞아야 합니다. IV_INO_LBLK_32에서는 해시된 inode 값과 index의 합을 32비트로 줄여 비트 0~31에 둡니다. 모든 정수는 little-endian으로 인코딩합니다.

AES-128-CBC 내용 모드는 ESSIV를 자동으로 적용합니다. contents key의 SHA-256 해시를 AES-256 키로 사용해 data unit index를 암호화한 값이 CBC IV가 됩니다.

파일 이름은 이름 전체를 하나의 암호화 단위로 처리합니다. 디렉터리 조회가 가능하고 `NAME_MAX` 255바이트를 지키기 위해 같은 디렉터리의 모든 이름에 같은 IV를 쓰지만, 기본 정책은 디렉터리별 키를 쓰고 DIRECT_KEY·inode IV 정책은 nonce나 inode를 IV에 포함해 파일 간 재사용을 제한합니다.

CBC-CTS는 16바이트 이상 공통 접두사를 가진 파일 이름에서 그 접두사를 누설합니다. HCTR2와 Adiantum 같은 wide-block 모드는 이 문제가 없습니다. 입력 길이는 최소 16바이트가 되도록 NUL로 채우며, 파일 이름은 정책에 따라 4·8·16·32바이트 배수로 패딩합니다. 32바이트 패딩을 권장합니다. 실제 파일 이름에는 NUL이 허용되지 않으므로 패딩 뒤에도 매핑은 고유합니다.

심볼릭 링크 대상은 파일 이름과 같은 방식으로 암호화하지만 심볼릭 링크 자체 inode의 키·nonce를 사용하므로 파일 이름과 IV가 재사용되지 않습니다.

내용 암호화 IV 배치
정책IV 구성제약
기본per-file key + data unit indexindex는 파일 내 0부터 시작
DIRECT_KEYbits 0-63 index, bits 64-191 nonceAdiantum 긴 IV
IV_INO_LBLK_64bits 0-31 index, bits 32-63 inode두 값 모두 32비트
IV_INO_LBLK_32bits 0-31 (SipHash(inode)+index) mod 2^32일부 IV 재사용

정책별 IV 비트 구성을 구조화한 표입니다.

파일 이름 암호화
이름을 16바이트 이상, 정책의 4·8·16·32바이트 배수로 NUL 패딩디렉터리 키·nonce·inode 정책에 맞는 IV 선택CBC-CTS 또는 wide-block cipher로 이름 전체 암호화암호문을 directory entry에 저장하고 암호문 해시로 인덱싱키가 있으면 조회 이름을 암호화해 비교

조회 가능성과 길이 제한을 함께 만족하는 처리 순서입니다.

Contents encryption
-------------------

For contents encryption, each file's contents is divided into "data
units".  Each data unit is encrypted independently.  The IV for each
data unit incorporates the zero-based index of the data unit within
the file.  This ensures that each data unit within a file is encrypted
differently, which is essential to prevent leaking information.

Note: the encryption depending on the offset into the file means that
operations like "collapse range" and "insert range" that rearrange the
extent mapping of files are not supported on encrypted files.

There are two cases for the sizes of the data units:

* Fixed-size data units.  This is how all filesystems other than UBIFS
  work.  A file's data units are all the same size; the last data unit
  is zero-padded if needed.  By default, the data unit size is equal
  to the filesystem block size.  On some filesystems, users can select
  a sub-block data unit size via the ``log2_data_unit_size`` field of
  the encryption policy; see `FS_IOC_SET_ENCRYPTION_POLICY`_.

* Variable-size data units.  This is what UBIFS does.  Each "UBIFS
  data node" is treated as a crypto data unit.  Each contains variable
  length, possibly compressed data, zero-padded to the next 16-byte
  boundary.  Users cannot select a sub-block data unit size on UBIFS.

In the case of compression + encryption, the compressed data is
encrypted.  UBIFS compression works as described above.  f2fs
compression works a bit differently; it compresses a number of
filesystem blocks into a smaller number of filesystem blocks.
Therefore a f2fs-compressed file still uses fixed-size data units, and
it is encrypted in a similar way to a file containing holes.

As mentioned in `Key hierarchy`_, the default encryption setting uses
per-file keys.  In this case, the IV for each data unit is simply the
index of the data unit in the file.  However, users can select an
encryption setting that does not use per-file keys.  For these, some
kind of file identifier is incorporated into the IVs as follows:

- With `DIRECT_KEY policies`_, the data unit index is placed in bits
  0-63 of the IV, and the file's nonce is placed in bits 64-191.

- With `IV_INO_LBLK_64 policies`_, the data unit index is placed in
  bits 0-31 of the IV, and the file's inode number is placed in bits
  32-63.  This setting is only allowed when data unit indices and
  inode numbers fit in 32 bits.

- With `IV_INO_LBLK_32 policies`_, the file's inode number is hashed
  and added to the data unit index.  The resulting value is truncated
  to 32 bits and placed in bits 0-31 of the IV.  This setting is only
  allowed when data unit indices and inode numbers fit in 32 bits.

The byte order of the IV is always little endian.

If the user selects FSCRYPT_MODE_AES_128_CBC for the contents mode, an
ESSIV layer is automatically included.  In this case, before the IV is
passed to AES-128-CBC, it is encrypted with AES-256 where the AES-256
key is the SHA-256 hash of the file's contents encryption key.

Filenames encryption
--------------------

For filenames, each full filename is encrypted at once.  Because of
the requirements to retain support for efficient directory lookups and
filenames of up to 255 bytes, the same IV is used for every filename
in a directory.

However, each encrypted directory still uses a unique key, or
alternatively has the file's nonce (for `DIRECT_KEY policies`_) or
inode number (for `IV_INO_LBLK_64 policies`_) included in the IVs.
Thus, IV reuse is limited to within a single directory.

With CBC-CTS, the IV reuse means that when the plaintext filenames share a
common prefix at least as long as the cipher block size (16 bytes for AES), the
corresponding encrypted filenames will also share a common prefix.  This is
undesirable.  Adiantum and HCTR2 do not have this weakness, as they are
wide-block encryption modes.

All supported filenames encryption modes accept any plaintext length
>= 16 bytes; cipher block alignment is not required.  However,
filenames shorter than 16 bytes are NUL-padded to 16 bytes before
being encrypted.  In addition, to reduce leakage of filename lengths
via their ciphertexts, all filenames are NUL-padded to the next 4, 8,
16, or 32-byte boundary (configurable).  32 is recommended since this
provides the best confidentiality, at the cost of making directory
entries consume slightly more space.  Note that since NUL (``\0``) is
not otherwise a valid character in filenames, the padding will never
produce duplicate plaintexts.

Symbolic link targets are considered a type of filename and are
encrypted in the same way as filenames in directory entries, except
that IV reuse is not a problem as each symlink has its own inode.

암호화 정책 설정 API

567-742

정책은 `FS_IOC_SET_ENCRYPTION_POLICY` ioctl로 비어 있는 디렉터리에 설정합니다. v1 구조체의 버전 값은 역사적 이유로 `FSCRYPT_POLICY_V1`인 0이고, v2 값은 `FSCRYPT_POLICY_V2`인 2입니다. 새 암호화 디렉터리에는 v2를 사용해야 합니다.

#define FSCRYPT_POLICY_V1 0
#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8
struct fscrypt_policy_v1 {
        __u8 version;
        __u8 contents_encryption_mode;
        __u8 filenames_encryption_mode;
        __u8 flags;
        __u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
};

#define FSCRYPT_POLICY_V2 2
#define FSCRYPT_KEY_IDENTIFIER_SIZE 16
struct fscrypt_policy_v2 {
        __u8 version;
        __u8 contents_encryption_mode;
        __u8 filenames_encryption_mode;
        __u8 flags;
        __u8 log2_data_unit_size;
        __u8 __reserved[3];
        __u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
};

`contents_encryption_mode`와 `filenames_encryption_mode`에는 지원되는 모드 짝을 지정합니다. 일반 기본값은 내용 `FSCRYPT_MODE_AES_256_XTS`(1), 이름 `FSCRYPT_MODE_AES_256_CTS`(4)입니다. v1은 역사적으로 지원된 세 조합만 허용하고 v2는 현재 지원 조합 전체를 허용합니다.

`flags`의 `FSCRYPT_POLICY_FLAGS_PAD_4`, `_PAD_8`, `_PAD_16`, `_PAD_32`는 파일 이름 패딩을 선택하며 PAD_32를 권장합니다. `FSCRYPT_POLICY_FLAG_DIRECT_KEY`, `FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64`, `FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32`는 키·IV 구성을 선택하고 서로 동시에 사용할 수 없습니다. v1은 패딩과 DIRECT_KEY만 지원합니다.

v2의 `log2_data_unit_size`가 0이면 파일시스템 기본값을 사용하고, 예를 들어 12는 4096바이트를 뜻합니다. ext4와 F2FS는 Linux 6.7부터 기본값이 아닌 값을 지원합니다. 0이 아니라면 9 이상이고 파일시스템 블록 크기의 log2 이하여야 합니다. 인라인 하드웨어가 특정 단위를 요구할 때 사용할 수 있으며 sysfs의 crypto capability를 확인해야 합니다. 더 작은 단위는 성능을 낮출 수 있습니다. `__reserved`는 0이어야 합니다.

v1의 8바이트 `master_key_descriptor`는 사용자 공간이 키를 식별하도록 선택한 값입니다. e4crypt와 fscrypt 도구는 보통 master key에 SHA-512를 두 번 적용한 결과의 첫 8바이트를 사용하지만 커널이 강제하지는 않습니다. 정책 설정 시 키가 없어도 되지만 파일을 만들기 전에는 키가 필요합니다.

v2의 16바이트 `master_key_identifier`는 `FS_IOC_ADD_ENCRYPTION_KEY`가 반환한 값을 그대로 사용해야 하며 임의 값을 넣으면 안 됩니다. 정책을 설정하는 사용자가 현재 해당 키를 추가한 사용자이거나 초기 user namespace에서 `CAP_FOWNER`를 가져야 합니다. ioctl이 실행되는 동안 키는 제거되지 않도록 유지됩니다.

대상은 암호화되지 않은 빈 디렉터리여야 하며 이후 생성되는 자손이 정책을 상속합니다. 이미 암호화된 디렉터리에 같은 정책을 다시 설정하면 성공하고 다른 정책이면 `EEXIST`입니다. ext4 루트 디렉터리는 암호화할 수 없으므로 파일시스템 전체 보호가 필요하면 dm-crypt를 사용합니다.

오류는 접근·소유권 실패 `EACCES`, 기존 다른 정책 `EEXIST`, 구조체·버전·모드·플래그 오류 `EINVAL`, v2 키 부재 `ENOKEY`, 대상이 디렉터리가 아님 `ENOTDIR`, 비어 있지 않음 `ENOTEMPTY`, ioctl 미지원 `ENOTTY`, 파일시스템 암호화 미지원 `EOPNOTSUPP`, 권한 부족 `EPERM`, 읽기 전용 파일시스템 `EROFS` 등으로 구분됩니다.

정책 구조체 핵심 필드
필드v1v2
`version`02
키 참조8바이트 descriptorADD_KEY가 반환한 16바이트 identifier
IV flagsDIRECT_KEY만DIRECT_KEY·IV64·IV32
`log2_data_unit_size`없음0 또는 9..log2(block size)
reserved없음3바이트 모두 0
권장 여부호환용새 디렉터리 권장

v1과 v2의 차이와 초기화 규칙입니다.

SET_POLICY 주요 오류
errno의미
`EACCES` / `EPERM`소유권·capability·접근 조건 불충족
`EEXIST`이미 다른 정책 존재
`EINVAL`버전·모드·flag·reserved·data unit 오류
`ENOKEY`v2 identifier에 해당하는 키가 사용자에게 없음
`ENOTDIR` / `ENOTEMPTY`대상이 디렉터리가 아니거나 비어 있지 않음
`ENOTTY` / `EOPNOTSUPP`ioctl 또는 파일시스템 암호화 미지원
`EROFS`읽기 전용 파일시스템

실패 원인을 운영자가 구분할 수 있게 정리했습니다.

User API
========

Setting an encryption policy
----------------------------

FS_IOC_SET_ENCRYPTION_POLICY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The FS_IOC_SET_ENCRYPTION_POLICY ioctl sets an encryption policy on an
empty directory or verifies that a directory or regular file already
has the specified encryption policy.  It takes in a pointer to
struct fscrypt_policy_v1 or struct fscrypt_policy_v2, defined as
follows::

    #define FSCRYPT_POLICY_V1               0
    #define FSCRYPT_KEY_DESCRIPTOR_SIZE     8
    struct fscrypt_policy_v1 {
            __u8 version;
            __u8 contents_encryption_mode;
            __u8 filenames_encryption_mode;
            __u8 flags;
            __u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
    };
    #define fscrypt_policy  fscrypt_policy_v1

    #define FSCRYPT_POLICY_V2               2
    #define FSCRYPT_KEY_IDENTIFIER_SIZE     16
    struct fscrypt_policy_v2 {
            __u8 version;
            __u8 contents_encryption_mode;
            __u8 filenames_encryption_mode;
            __u8 flags;
            __u8 log2_data_unit_size;
            __u8 __reserved[3];
            __u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
    };

This structure must be initialized as follows:

- ``version`` must be FSCRYPT_POLICY_V1 (0) if
  struct fscrypt_policy_v1 is used or FSCRYPT_POLICY_V2 (2) if
  struct fscrypt_policy_v2 is used. (Note: we refer to the original
  policy version as "v1", though its version code is really 0.)
  For new encrypted directories, use v2 policies.

- ``contents_encryption_mode`` and ``filenames_encryption_mode`` must
  be set to constants from ``<linux/fscrypt.h>`` which identify the
  encryption modes to use.  If unsure, use FSCRYPT_MODE_AES_256_XTS
  (1) for ``contents_encryption_mode`` and FSCRYPT_MODE_AES_256_CTS
  (4) for ``filenames_encryption_mode``.  For details, see `Encryption
  modes and usage`_.

  v1 encryption policies only support three combinations of modes:
  (FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS),
  (FSCRYPT_MODE_AES_128_CBC, FSCRYPT_MODE_AES_128_CTS), and
  (FSCRYPT_MODE_ADIANTUM, FSCRYPT_MODE_ADIANTUM).  v2 policies support
  all combinations documented in `Supported modes`_.

- ``flags`` contains optional flags from ``<linux/fscrypt.h>``:

  - FSCRYPT_POLICY_FLAGS_PAD_*: The amount of NUL padding to use when
    encrypting filenames.  If unsure, use FSCRYPT_POLICY_FLAGS_PAD_32
    (0x3).
  - FSCRYPT_POLICY_FLAG_DIRECT_KEY: See `DIRECT_KEY policies`_.
  - FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64: See `IV_INO_LBLK_64
    policies`_.
  - FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32: See `IV_INO_LBLK_32
    policies`_.

  v1 encryption policies only support the PAD_* and DIRECT_KEY flags.
  The other flags are only supported by v2 encryption policies.

  The DIRECT_KEY, IV_INO_LBLK_64, and IV_INO_LBLK_32 flags are
  mutually exclusive.

- ``log2_data_unit_size`` is the log2 of the data unit size in bytes,
  or 0 to select the default data unit size.  The data unit size is
  the granularity of file contents encryption.  For example, setting
  ``log2_data_unit_size`` to 12 causes file contents be passed to the
  underlying encryption algorithm (such as AES-256-XTS) in 4096-byte
  data units, each with its own IV.

  Not all filesystems support setting ``log2_data_unit_size``.  ext4
  and f2fs support it since Linux v6.7.  On filesystems that support
  it, the supported nonzero values are 9 through the log2 of the
  filesystem block size, inclusively.  The default value of 0 selects
  the filesystem block size.

  The main use case for ``log2_data_unit_size`` is for selecting a
  data unit size smaller than the filesystem block size for
  compatibility with inline encryption hardware that only supports
  smaller data unit sizes.  ``/sys/block/$disk/queue/crypto/`` may be
  useful for checking which data unit sizes are supported by a
  particular system's inline encryption hardware.

  Leave this field zeroed unless you are certain you need it.  Using
  an unnecessarily small data unit size reduces performance.

- For v2 encryption policies, ``__reserved`` must be zeroed.

- For v1 encryption policies, ``master_key_descriptor`` specifies how
  to find the master key in a keyring; see `Adding keys`_.  It is up
  to userspace to choose a unique ``master_key_descriptor`` for each
  master key.  The e4crypt and fscrypt tools use the first 8 bytes of
  ``SHA-512(SHA-512(master_key))``, but this particular scheme is not
  required.  Also, the master key need not be in the keyring yet when
  FS_IOC_SET_ENCRYPTION_POLICY is executed.  However, it must be added
  before any files can be created in the encrypted directory.

  For v2 encryption policies, ``master_key_descriptor`` has been
  replaced with ``master_key_identifier``, which is longer and cannot
  be arbitrarily chosen.  Instead, the key must first be added using
  `FS_IOC_ADD_ENCRYPTION_KEY`_.  Then, the ``key_spec.u.identifier``
  the kernel returned in the struct fscrypt_add_key_arg must
  be used as the ``master_key_identifier`` in
  struct fscrypt_policy_v2.

If the file is not yet encrypted, then FS_IOC_SET_ENCRYPTION_POLICY
verifies that the file is an empty directory.  If so, the specified
encryption policy is assigned to the directory, turning it into an
encrypted directory.  After that, and after providing the
corresponding master key as described in `Adding keys`_, all regular
files, directories (recursively), and symlinks created in the
directory will be encrypted, inheriting the same encryption policy.
The filenames in the directory's entries will be encrypted as well.

Alternatively, if the file is already encrypted, then
FS_IOC_SET_ENCRYPTION_POLICY validates that the specified encryption
policy exactly matches the actual one.  If they match, then the ioctl
returns 0.  Otherwise, it fails with EEXIST.  This works on both
regular files and directories, including nonempty directories.

When a v2 encryption policy is assigned to a directory, it is also
required that either the specified key has been added by the current
user or that the caller has CAP_FOWNER in the initial user namespace.
(This is needed to prevent a user from encrypting their data with
another user's key.)  The key must remain added while
FS_IOC_SET_ENCRYPTION_POLICY is executing.  However, if the new
encrypted directory does not need to be accessed immediately, then the
key can be removed right away afterwards.

Note that the ext4 filesystem does not allow the root directory to be
encrypted, even if it is empty.  Users who want to encrypt an entire
filesystem with one key should consider using dm-crypt instead.

FS_IOC_SET_ENCRYPTION_POLICY can fail with the following errors:

- ``EACCES``: the file is not owned by the process's uid, nor does the
  process have the CAP_FOWNER capability in a namespace with the file
  owner's uid mapped
- ``EEXIST``: the file is already encrypted with an encryption policy
  different from the one specified
- ``EINVAL``: an invalid encryption policy was specified (invalid
  version, mode(s), or flags; or reserved bits were set); or a v1
  encryption policy was specified but the directory has the casefold
  flag enabled (casefolding is incompatible with v1 policies).
- ``ENOKEY``: a v2 encryption policy was specified, but the key with
  the specified ``master_key_identifier`` has not been added, nor does
  the process have the CAP_FOWNER capability in the initial user
  namespace
- ``ENOTDIR``: the file is unencrypted and is a regular file, not a
  directory
- ``ENOTEMPTY``: the file is unencrypted and is a nonempty directory
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
  support for filesystems, or the filesystem superblock has not
  had encryption enabled on it.  (For example, to use encryption on an
  ext4 filesystem, CONFIG_FS_ENCRYPTION must be enabled in the
  kernel config, and the superblock must have had the "encrypt"
  feature flag enabled using ``tune2fs -O encrypt`` or ``mkfs.ext4 -O
  encrypt``.)
- ``EPERM``: this directory may not be encrypted, e.g. because it is
  the root directory of an ext4 filesystem
- ``EROFS``: the filesystem is readonly

정책 조회, salt와 nonce 조회

743-840

정책 조회에는 `FS_IOC_GET_ENCRYPTION_POLICY_EX`를 우선 사용하고 `ENOTTY`일 때만 구형 `FS_IOC_GET_ENCRYPTION_POLICY`로 폴백해야 합니다. 확장 ioctl의 인수는 `policy_size`와 version·v1·v2 union을 가지며, 호출 전 `policy_size`를 union의 수용 크기로 초기화합니다. 성공하면 실제 정책 크기와 버전별 구조체가 반환됩니다.

확장 조회의 `EINVAL`은 알 수 없는 정책 버전, `ENODATA`는 정책 없음, `ENOTTY`는 ioctl 미지원, `EOPNOTSUPP`는 파일시스템 암호화 미지원, `EOVERFLOW`는 제공한 버퍼가 정책보다 작음을 뜻합니다.

디렉터리가 암호화되었는지만 확인하려면 `FS_IOC_GETFLAGS`의 `FS_ENCRYPT_FL` 또는 `statx()`의 `STATX_ATTR_ENCRYPTED`도 사용할 수 있습니다.

구형 `FS_IOC_GET_ENCRYPTION_POLICY`는 v1만 반환합니다. 새 커널에서 v2 정책에 호출하면 `EINVAL`이므로 확장 ioctl을 먼저 시도해야 합니다.

`FS_IOC_GET_ENCRYPTION_PWSALT`는 파일시스템 superblock의 무작위 16바이트 salt를 반환하는 폐기 예정 API입니다. passphrase에서 암호 키를 파생하는 데 사용되었지만 사용자 공간이 자체 salt를 관리하는 것이 권장됩니다.

Linux 5.7부터 `FS_IOC_GET_ENCRYPTION_NONCE`는 암호화 inode의 16바이트 nonce를 반환합니다. 암호화되지 않은 inode에는 `ENODATA`를 반환하며 일반 애플리케이션용이 아니라 fscrypt 테스트용입니다.

정책·보조 정보 조회 API
ioctl·API용도주의
`FS_IOC_GET_ENCRYPTION_POLICY_EX`v1·v2 정책 조회항상 먼저 시도
`FS_IOC_GET_ENCRYPTION_POLICY`v1 정책 조회EX가 `ENOTTY`일 때 폴백
`FS_IOC_GETFLAGS` / `statx()`암호화 여부만 확인`FS_ENCRYPT_FL` / `STATX_ATTR_ENCRYPTED`
`FS_IOC_GET_ENCRYPTION_PWSALT`16바이트 superblock salt폐기 예정
`FS_IOC_GET_ENCRYPTION_NONCE`16바이트 inode nonceLinux 5.7+, 테스트 전용

선호 순서와 반환값을 비교합니다.

Getting an encryption policy
----------------------------

Two ioctls are available to get a file's encryption policy:

- `FS_IOC_GET_ENCRYPTION_POLICY_EX`_
- `FS_IOC_GET_ENCRYPTION_POLICY`_

The extended (_EX) version of the ioctl is more general and is
recommended to use when possible.  However, on older kernels only the
original ioctl is available.  Applications should try the extended
version, and if it fails with ENOTTY fall back to the original
version.

FS_IOC_GET_ENCRYPTION_POLICY_EX
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The FS_IOC_GET_ENCRYPTION_POLICY_EX ioctl retrieves the encryption
policy, if any, for a directory or regular file.  No additional
permissions are required beyond the ability to open the file.  It
takes in a pointer to struct fscrypt_get_policy_ex_arg,
defined as follows::

    struct fscrypt_get_policy_ex_arg {
            __u64 policy_size; /* input/output */
            union {
                    __u8 version;
                    struct fscrypt_policy_v1 v1;
                    struct fscrypt_policy_v2 v2;
            } policy; /* output */
    };

The caller must initialize ``policy_size`` to the size available for
the policy struct, i.e. ``sizeof(arg.policy)``.

On success, the policy struct is returned in ``policy``, and its
actual size is returned in ``policy_size``.  ``policy.version`` should
be checked to determine the version of policy returned.  Note that the
version code for the "v1" policy is actually 0 (FSCRYPT_POLICY_V1).

FS_IOC_GET_ENCRYPTION_POLICY_EX can fail with the following errors:

- ``EINVAL``: the file is encrypted, but it uses an unrecognized
  encryption policy version
- ``ENODATA``: the file is not encrypted
- ``ENOTTY``: this type of filesystem does not implement encryption,
  or this kernel is too old to support FS_IOC_GET_ENCRYPTION_POLICY_EX
  (try FS_IOC_GET_ENCRYPTION_POLICY instead)
- ``EOPNOTSUPP``: the kernel was not configured with encryption
  support for this filesystem, or the filesystem superblock has not
  had encryption enabled on it
- ``EOVERFLOW``: the file is encrypted and uses a recognized
  encryption policy version, but the policy struct does not fit into
  the provided buffer

Note: if you only need to know whether a file is encrypted or not, on
most filesystems it is also possible to use the FS_IOC_GETFLAGS ioctl
and check for FS_ENCRYPT_FL, or to use the statx() system call and
check for STATX_ATTR_ENCRYPTED in stx_attributes.

FS_IOC_GET_ENCRYPTION_POLICY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The FS_IOC_GET_ENCRYPTION_POLICY ioctl can also retrieve the
encryption policy, if any, for a directory or regular file.  However,
unlike `FS_IOC_GET_ENCRYPTION_POLICY_EX`_,
FS_IOC_GET_ENCRYPTION_POLICY only supports the original policy
version.  It takes in a pointer directly to struct fscrypt_policy_v1
rather than struct fscrypt_get_policy_ex_arg.

The error codes for FS_IOC_GET_ENCRYPTION_POLICY are the same as those
for FS_IOC_GET_ENCRYPTION_POLICY_EX, except that
FS_IOC_GET_ENCRYPTION_POLICY also returns ``EINVAL`` if the file is
encrypted using a newer encryption policy version.

Getting the per-filesystem salt
-------------------------------

Some filesystems, such as ext4 and F2FS, also support the deprecated
ioctl FS_IOC_GET_ENCRYPTION_PWSALT.  This ioctl retrieves a randomly
generated 16-byte value stored in the filesystem superblock.  This
value is intended to used as a salt when deriving an encryption key
from a passphrase or other low-entropy user credential.

FS_IOC_GET_ENCRYPTION_PWSALT is deprecated.  Instead, prefer to
generate and manage any needed salt(s) in userspace.

Getting a file's encryption nonce
---------------------------------

Since Linux v5.7, the ioctl FS_IOC_GET_ENCRYPTION_NONCE is supported.
On encrypted files and directories it gets the inode's 16-byte nonce.
On unencrypted files and directories, it fails with ENODATA.

This ioctl can be useful for automated tests which verify that the
encryption is being done correctly.  It is not needed for normal use
of fscrypt.

Master key 추가와 legacy keyring

841-1017

새 API에서는 `FS_IOC_ADD_ENCRYPTION_KEY`로 파일시스템별 keyring에 master key를 추가합니다. `struct fscrypt_add_key_arg`는 `key_spec`, `raw_size`, `key_id`, `flags`, reserved 영역, 가변 길이 `raw[]`로 구성됩니다. `key_spec`은 v1용 descriptor 또는 v2용 identifier 형식입니다.

구조체 전체와 reserved 영역은 0으로 초기화해야 합니다. v1 descriptor 형식의 키를 추가하려면 초기 user namespace의 `CAP_SYS_ADMIN`이 필요합니다. v2 identifier는 커널이 raw key의 암호학적 해시로 계산해 출력하므로 권한 없는 사용자도 추가할 수 있지만 keyring quota의 적용을 받습니다.

`key_id`가 0이면 `raw_size`만큼의 키 바이트를 `raw[]`에 직접 넣습니다. `key_id`가 0이 아니면 `raw_size`는 0이어야 하고 Linux keyring의 `fscrypt-provisioning` 키를 참조합니다. 해당 키 payload는 type, flags, raw key size와 바이트를 담고 호출자는 그 키에 Search 권한이 있어야 합니다. 직접 raw key 전달이 보통 더 단순하지만, provisioning key는 재마운트 등에서 키를 다시 공급하는 데 유용합니다.

hardware-wrapped key는 `FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED`를 add 인수와 provisioning payload 양쪽에 필요할 때 모두 설정합니다. wrapped key는 descriptor 형식과 함께 사용할 수 없습니다.

v2 키는 effective UID별 사용자의 claim을 추적합니다. 같은 키를 다른 사용자가 다시 추가하면 키 자체를 중복 저장하지 않고 그 사용자의 claim을 만들며, raw key를 알고 있음을 증명해야 합니다. 이미 자신이 추가한 키를 다시 추가해도 성공 0을 반환합니다.

주요 오류는 provisioning key Search 권한 부족 `EACCES`, payload 형식 오류 `EBADMSG`, keyring quota 초과 `EDQUOT`, 구조체·specifier·크기·flag 오류 `EINVAL`, 제공 키가 기존 identifier와 불일치 `EKEYREJECTED`, provisioning key 부재 `ENOKEY`, ioctl 미지원 `ENOTTY`, 파일시스템 암호화 미지원 `EOPNOTSUPP`입니다.

v1의 legacy 방식은 process-subscribed keyring에 type `logon`, description `fscrypt:` 뒤에 16자리 소문자 16진 descriptor를 붙여 키를 추가합니다. payload는 최대 64바이트 raw key와 size, mode 0을 담는 구조체입니다. 파일시스템별 prefix도 과거에 사용됐지만 폐기 예정입니다.

legacy keyring 방식은 안전한 remove ioctl이 없고 전역 keyring 상태가 파일시스템별 상태 API와 맞지 않으므로 새 코드에서 사용해서는 안 됩니다. `FS_IOC_ADD_ENCRYPTION_KEY`와 v2 정책을 사용해야 합니다.

ADD_KEY 처리
인수와 reserved 영역을 0으로 초기화descriptor(v1) 또는 identifier(v2) specifier 선택`key_id=0`이면 raw[] 전달, 아니면 fscrypt-provisioning key 조회wrapped key라면 양쪽 flags에 HW_WRAPPED 설정커널이 v2 identifier 계산·검증effective UID의 claim과 파일시스템별 keyring 상태 갱신

직접 키와 provisioning key가 파일시스템 keyring에 합류하는 흐름입니다.

ADD_KEY 오류
errno원인
`EACCES`provisioning key Search 권한 또는 v1 capability 부족
`EBADMSG`provisioning payload 손상·형식 불일치
`EDQUOT`keyring quota 초과
`EINVAL`specifier·크기·flag·reserved 조합 오류
`EKEYREJECTED`키가 기존 v2 identifier와 불일치
`ENOKEY`지정한 provisioning key 없음
`ENOTTY` / `EOPNOTSUPP`ioctl·파일시스템 암호화 미지원

키 공급 경로별 실패 의미입니다.

Adding keys
-----------

FS_IOC_ADD_ENCRYPTION_KEY
~~~~~~~~~~~~~~~~~~~~~~~~~

The FS_IOC_ADD_ENCRYPTION_KEY ioctl adds a master encryption key to
the filesystem, making all files on the filesystem which were
encrypted using that key appear "unlocked", i.e. in plaintext form.
It can be executed on any file or directory on the target filesystem,
but using the filesystem's root directory is recommended.  It takes in
a pointer to struct fscrypt_add_key_arg, defined as follows::

    struct fscrypt_add_key_arg {
            struct fscrypt_key_specifier key_spec;
            __u32 raw_size;
            __u32 key_id;
    #define FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED 0x00000001
            __u32 flags;
            __u32 __reserved[7];
            __u8 raw[];
    };

    #define FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR        1
    #define FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER        2

    struct fscrypt_key_specifier {
            __u32 type;     /* one of FSCRYPT_KEY_SPEC_TYPE_* */
            __u32 __reserved;
            union {
                    __u8 __reserved[32]; /* reserve some extra space */
                    __u8 descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
                    __u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
            } u;
    };

    struct fscrypt_provisioning_key_payload {
            __u32 type;
            __u32 flags;
            __u8 raw[];
    };

struct fscrypt_add_key_arg must be zeroed, then initialized
as follows:

- If the key is being added for use by v1 encryption policies, then
  ``key_spec.type`` must contain FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR, and
  ``key_spec.u.descriptor`` must contain the descriptor of the key
  being added, corresponding to the value in the
  ``master_key_descriptor`` field of struct fscrypt_policy_v1.
  To add this type of key, the calling process must have the
  CAP_SYS_ADMIN capability in the initial user namespace.

  Alternatively, if the key is being added for use by v2 encryption
  policies, then ``key_spec.type`` must contain
  FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER, and ``key_spec.u.identifier`` is
  an *output* field which the kernel fills in with a cryptographic
  hash of the key.  To add this type of key, the calling process does
  not need any privileges.  However, the number of keys that can be
  added is limited by the user's quota for the keyrings service (see
  ``Documentation/security/keys/core.rst``).

- ``raw_size`` must be the size of the ``raw`` key provided, in bytes.
  Alternatively, if ``key_id`` is nonzero, this field must be 0, since
  in that case the size is implied by the specified Linux keyring key.

- ``key_id`` is 0 if the key is given directly in the ``raw`` field.
  Otherwise ``key_id`` is the ID of a Linux keyring key of type
  "fscrypt-provisioning" whose payload is struct
  fscrypt_provisioning_key_payload whose ``raw`` field contains the
  key, whose ``type`` field matches ``key_spec.type``, and whose
  ``flags`` field matches ``flags``.  Since ``raw`` is
  variable-length, the total size of this key's payload must be
  ``sizeof(struct fscrypt_provisioning_key_payload)`` plus the number
  of key bytes.  The process must have Search permission on this key.

  Most users should leave this 0 and specify the key directly.  The
  support for specifying a Linux keyring key is intended mainly to
  allow re-adding keys after a filesystem is unmounted and re-mounted,
  without having to store the keys in userspace memory.

- ``flags`` contains optional flags from ``<linux/fscrypt.h>``:

  - FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED: This denotes that the key is a
    hardware-wrapped key.  See `Hardware-wrapped keys`_.  This flag
    can't be used if FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR is used.

- ``raw`` is a variable-length field which must contain the actual
  key, ``raw_size`` bytes long.  Alternatively, if ``key_id`` is
  nonzero, then this field is unused.  Note that despite being named
  ``raw``, if FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED is specified then it
  will contain a wrapped key, not a raw key.

For v2 policy keys, the kernel keeps track of which user (identified
by effective user ID) added the key, and only allows the key to be
removed by that user --- or by "root", if they use
`FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`_.

However, if another user has added the key, it may be desirable to
prevent that other user from unexpectedly removing it.  Therefore,
FS_IOC_ADD_ENCRYPTION_KEY may also be used to add a v2 policy key
*again*, even if it's already added by other user(s).  In this case,
FS_IOC_ADD_ENCRYPTION_KEY will just install a claim to the key for the
current user, rather than actually add the key again (but the key must
still be provided, as a proof of knowledge).

FS_IOC_ADD_ENCRYPTION_KEY returns 0 if either the key or a claim to
the key was either added or already exists.

FS_IOC_ADD_ENCRYPTION_KEY can fail with the following errors:

- ``EACCES``: FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR was specified, but the
  caller does not have the CAP_SYS_ADMIN capability in the initial
  user namespace; or the key was specified by Linux key ID but the
  process lacks Search permission on the key.
- ``EBADMSG``: invalid hardware-wrapped key
- ``EDQUOT``: the key quota for this user would be exceeded by adding
  the key
- ``EINVAL``: invalid key size or key specifier type, or reserved bits
  were set
- ``EKEYREJECTED``: the key was specified by Linux key ID, but the key
  has the wrong type
- ``ENOKEY``: the key was specified by Linux key ID, but no key exists
  with that ID
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
  support for this filesystem, or the filesystem superblock has not
  had encryption enabled on it; or a hardware wrapped key was specified
  but the filesystem does not support inline encryption or the hardware
  does not support hardware-wrapped keys

Legacy method
~~~~~~~~~~~~~

For v1 encryption policies, a master encryption key can also be
provided by adding it to a process-subscribed keyring, e.g. to a
session keyring, or to a user keyring if the user keyring is linked
into the session keyring.

This method is deprecated (and not supported for v2 encryption
policies) for several reasons.  First, it cannot be used in
combination with FS_IOC_REMOVE_ENCRYPTION_KEY (see `Removing keys`_),
so for removing a key a workaround such as keyctl_unlink() in
combination with ``sync; echo 2 > /proc/sys/vm/drop_caches`` would
have to be used.  Second, it doesn't match the fact that the
locked/unlocked status of encrypted files (i.e. whether they appear to
be in plaintext form or in ciphertext form) is global.  This mismatch
has caused much confusion as well as real problems when processes
running under different UIDs, such as a ``sudo`` command, need to
access encrypted files.

Nevertheless, to add a key to one of the process-subscribed keyrings,
the add_key() system call can be used (see:
``Documentation/security/keys/core.rst``).  The key type must be
"logon"; keys of this type are kept in kernel memory and cannot be
read back by userspace.  The key description must be "fscrypt:"
followed by the 16-character lower case hex representation of the
``master_key_descriptor`` that was set in the encryption policy.  The
key payload must conform to the following structure::

    #define FSCRYPT_MAX_KEY_SIZE            64

    struct fscrypt_key {
            __u32 mode;
            __u8 raw[FSCRYPT_MAX_KEY_SIZE];
            __u32 size;
    };

``mode`` is ignored; just set it to 0.  The actual key is provided in
``raw`` with ``size`` indicating its size in bytes.  That is, the
bytes ``raw[0..size-1]`` (inclusive) are the actual key.

The key description prefix "fscrypt:" may alternatively be replaced
with a filesystem-specific prefix such as "ext4:".  However, the
filesystem-specific prefixes are deprecated and should not be used in
new programs.

키 제거, 사용자 claim과 상태 조회

1018-1205

`FS_IOC_REMOVE_ENCRYPTION_KEY`와 `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`는 `FS_IOC_ADD_ENCRYPTION_KEY`로 관리되는 파일시스템별 keyring의 키만 제거합니다. v1 descriptor 제거에는 초기 user namespace의 `CAP_SYS_ADMIN`이 필요하고 v2는 identifier를 사용합니다.

일반 REMOVE ioctl은 v2에서 호출자의 claim을 먼저 제거합니다. 여러 사용자가 같은 키를 추가했다면 hard link와 비슷하게 모든 claim이 없어져야 실제 키가 제거됩니다. 마지막 claim이 사라지면 커널은 키를 지우고 잠금 해제 inode를 퇴거하려 합니다.

키가 실제로 지워져도 사용 중 inode의 per-file key는 남을 수 있습니다. 반환 구조체의 `FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY`는 이러한 파일이 남았음을 뜻하며 파일을 닫은 뒤 ioctl을 재시도해야 합니다. `FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS`는 다른 사용자의 claim 때문에 키가 남았음을 뜻합니다.

`FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`는 모든 사용자 claim과 키를 한 번에 제거하며 초기 user namespace의 `CAP_SYS_ADMIN`이 필요합니다. 권한이 없으면 `EACCES`입니다.

제거 ioctl의 오류는 접근 권한 부족 `EACCES`, 구조체·specifier·reserved 오류 `EINVAL`, 자신이 claim하지 않았거나 키가 없음 `ENOKEY`, ioctl 미지원 `ENOTTY`, 파일시스템 암호화 미지원 `EOPNOTSUPP`입니다. 성공 0만으로 완전 제거를 단정하지 말고 반환 status flags를 반드시 확인해야 합니다.

`FS_IOC_GET_ENCRYPTION_KEY_STATUS`는 `FSCRYPT_KEY_STATUS_ABSENT`, `PRESENT`, `INCOMPLETELY_REMOVED` 중 하나를 반환합니다. `PRESENT`는 키가 있고 사용할 수 있음을, `INCOMPLETELY_REMOVED`는 master key는 제거됐지만 사용 중 파일 때문에 일부 per-file key가 남았음을 뜻합니다.

v2에서는 `FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF`로 현재 effective UID가 claim을 보유하는지 알 수 있고 `user_count`로 전체 claim 수를 확인합니다. v1에는 이 정보가 없습니다. 이 API는 암호화 디렉터리의 키가 없는지 확인한 뒤 passphrase를 묻는 용도에 유용합니다.

상태 조회는 파일시스템별 keyring만 보며 legacy process-subscribed keyring에만 추가된 v1 키는 볼 수 없습니다. 상태 조회 오류는 인수 오류 `EINVAL`, ioctl 미지원 `ENOTTY`, 파일시스템 암호화 미지원 또는 superblock에서 암호화가 켜지지 않은 `EOPNOTSUPP`입니다.

v2 claim 제거 모델
사용자 A와 B가 같은 v2 key identifier를 claimA의 REMOVE는 A claim만 제거OTHER_USERS flag가 남은 B claim을 알림마지막 claim 제거 시 master key 삭제 시도사용 중 inode가 있으면 FILES_BUSY와 INCOMPLETELY_REMOVED파일을 닫고 재시도해 완전한 ABSENT 상태 도달

여러 사용자가 같은 키를 추가했을 때 실제 제거 조건입니다.

키 상태와 조치
상태·flag의미조치
`ABSENT`파일시스템 keyring에 키 없음필요하면 ADD_KEY
`PRESENT`키 사용 가능user_count·ADDED_BY_SELF 확인
`INCOMPLETELY_REMOVED`master는 제거됐으나 per-file key 잔류열린 파일 종료 후 REMOVE 재시도
`FILES_BUSY`사용 중 inode 때문에 잔류fd·cwd 정리
`OTHER_USERS`다른 UID claim 존재각 사용자 제거 또는 ALL_USERS

status와 removal flag를 함께 해석해야 합니다.

Removing keys
-------------

Two ioctls are available for removing a key that was added by
`FS_IOC_ADD_ENCRYPTION_KEY`_:

- `FS_IOC_REMOVE_ENCRYPTION_KEY`_
- `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`_

These two ioctls differ only in cases where v2 policy keys are added
or removed by non-root users.

These ioctls don't work on keys that were added via the legacy
process-subscribed keyrings mechanism.

Before using these ioctls, read the `Online attacks`_ section for a
discussion of the security goals and limitations of these ioctls.

FS_IOC_REMOVE_ENCRYPTION_KEY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The FS_IOC_REMOVE_ENCRYPTION_KEY ioctl removes a claim to a master
encryption key from the filesystem, and possibly removes the key
itself.  It can be executed on any file or directory on the target
filesystem, but using the filesystem's root directory is recommended.
It takes in a pointer to struct fscrypt_remove_key_arg, defined
as follows::

    struct fscrypt_remove_key_arg {
            struct fscrypt_key_specifier key_spec;
    #define FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY      0x00000001
    #define FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS     0x00000002
            __u32 removal_status_flags;     /* output */
            __u32 __reserved[5];
    };

This structure must be zeroed, then initialized as follows:

- The key to remove is specified by ``key_spec``:

    - To remove a key used by v1 encryption policies, set
      ``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill
      in ``key_spec.u.descriptor``.  To remove this type of key, the
      calling process must have the CAP_SYS_ADMIN capability in the
      initial user namespace.

    - To remove a key used by v2 encryption policies, set
      ``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill
      in ``key_spec.u.identifier``.

For v2 policy keys, this ioctl is usable by non-root users.  However,
to make this possible, it actually just removes the current user's
claim to the key, undoing a single call to FS_IOC_ADD_ENCRYPTION_KEY.
Only after all claims are removed is the key really removed.

For example, if FS_IOC_ADD_ENCRYPTION_KEY was called with uid 1000,
then the key will be "claimed" by uid 1000, and
FS_IOC_REMOVE_ENCRYPTION_KEY will only succeed as uid 1000.  Or, if
both uids 1000 and 2000 added the key, then for each uid
FS_IOC_REMOVE_ENCRYPTION_KEY will only remove their own claim.  Only
once *both* are removed is the key really removed.  (Think of it like
unlinking a file that may have hard links.)

If FS_IOC_REMOVE_ENCRYPTION_KEY really removes the key, it will also
try to "lock" all files that had been unlocked with the key.  It won't
lock files that are still in-use, so this ioctl is expected to be used
in cooperation with userspace ensuring that none of the files are
still open.  However, if necessary, this ioctl can be executed again
later to retry locking any remaining files.

FS_IOC_REMOVE_ENCRYPTION_KEY returns 0 if either the key was removed
(but may still have files remaining to be locked), the user's claim to
the key was removed, or the key was already removed but had files
remaining to be the locked so the ioctl retried locking them.  In any
of these cases, ``removal_status_flags`` is filled in with the
following informational status flags:

- ``FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY``: set if some file(s)
  are still in-use.  Not guaranteed to be set in the case where only
  the user's claim to the key was removed.
- ``FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS``: set if only the
  user's claim to the key was removed, not the key itself

FS_IOC_REMOVE_ENCRYPTION_KEY can fail with the following errors:

- ``EACCES``: The FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR key specifier type
  was specified, but the caller does not have the CAP_SYS_ADMIN
  capability in the initial user namespace
- ``EINVAL``: invalid key specifier type, or reserved bits were set
- ``ENOKEY``: the key object was not found at all, i.e. it was never
  added in the first place or was already fully removed including all
  files locked; or, the user does not have a claim to the key (but
  someone else does).
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
  support for this filesystem, or the filesystem superblock has not
  had encryption enabled on it

FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS is exactly the same as
`FS_IOC_REMOVE_ENCRYPTION_KEY`_, except that for v2 policy keys, the
ALL_USERS version of the ioctl will remove all users' claims to the
key, not just the current user's.  I.e., the key itself will always be
removed, no matter how many users have added it.  This difference is
only meaningful if non-root users are adding and removing keys.

Because of this, FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS also requires
"root", namely the CAP_SYS_ADMIN capability in the initial user
namespace.  Otherwise it will fail with EACCES.

Getting key status
------------------

FS_IOC_GET_ENCRYPTION_KEY_STATUS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The FS_IOC_GET_ENCRYPTION_KEY_STATUS ioctl retrieves the status of a
master encryption key.  It can be executed on any file or directory on
the target filesystem, but using the filesystem's root directory is
recommended.  It takes in a pointer to
struct fscrypt_get_key_status_arg, defined as follows::

    struct fscrypt_get_key_status_arg {
            /* input */
            struct fscrypt_key_specifier key_spec;
            __u32 __reserved[6];

            /* output */
    #define FSCRYPT_KEY_STATUS_ABSENT               1
    #define FSCRYPT_KEY_STATUS_PRESENT              2
    #define FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED 3
            __u32 status;
    #define FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF   0x00000001
            __u32 status_flags;
            __u32 user_count;
            __u32 __out_reserved[13];
    };

The caller must zero all input fields, then fill in ``key_spec``:

    - To get the status of a key for v1 encryption policies, set
      ``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill
      in ``key_spec.u.descriptor``.

    - To get the status of a key for v2 encryption policies, set
      ``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill
      in ``key_spec.u.identifier``.

On success, 0 is returned and the kernel fills in the output fields:

- ``status`` indicates whether the key is absent, present, or
  incompletely removed.  Incompletely removed means that removal has
  been initiated, but some files are still in use; i.e.,
  `FS_IOC_REMOVE_ENCRYPTION_KEY`_ returned 0 but set the informational
  status flag FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY.

- ``status_flags`` can contain the following flags:

    - ``FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF`` indicates that the key
      has added by the current user.  This is only set for keys
      identified by ``identifier`` rather than by ``descriptor``.

- ``user_count`` specifies the number of users who have added the key.
  This is only set for keys identified by ``identifier`` rather than
  by ``descriptor``.

FS_IOC_GET_ENCRYPTION_KEY_STATUS can fail with the following errors:

- ``EINVAL``: invalid key specifier type, or reserved bits were set
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
  support for this filesystem, or the filesystem superblock has not
  had encryption enabled on it

Among other use cases, FS_IOC_GET_ENCRYPTION_KEY_STATUS can be useful
for determining whether the key for a given encrypted directory needs
to be added before prompting the user for the passphrase needed to
derive the key.

FS_IOC_GET_ENCRYPTION_KEY_STATUS can only get the status of keys in
the filesystem-level keyring, i.e. the keyring managed by
`FS_IOC_ADD_ENCRYPTION_KEY`_ and `FS_IOC_REMOVE_ENCRYPTION_KEY`_.  It
cannot get the status of a key that has only been added for use by v1
encryption policies using the legacy mechanism involving
process-subscribed keyrings.

키 유무에 따른 접근 의미와 정책 강제

1206-1319

키가 있으면 암호화 일반 파일, 디렉터리, 심볼릭 링크는 대부분 평문 객체처럼 동작합니다. 다만 암호화되지 않았거나 키·모드·flag가 다른 정책의 파일을 암호화 디렉터리로 rename하거나 link할 수 없고 `EXDEV`가 납니다. 같은 암호화 디렉터리 안이나 암호화 디렉터리에서 평문 디렉터리로 이동하는 것은 가능합니다.

`mv`가 평문 파일을 암호화 디렉터리로 옮길 때는 사용자 공간에서 복사 후 삭제로 구현됩니다. 원래 평문 데이터가 디스크 여유 공간에 남을 수 있으므로 처음부터 암호화 상태로 파일을 만드는 편이 안전합니다. `shred`도 모든 파일시스템과 저장장치에서 효과가 보장되지 않습니다.

암호화 파일의 direct I/O는 특정 조건에서만 지원합니다. `FALLOC_FL_COLLAPSE_RANGE`, `FALLOC_FL_INSERT_RANGE`, ext4 `EXT4_IOC_MOVE_EXT`, F2FS `F2FS_IOC_MOVE_RANGE`는 `EOPNOTSUPP`입니다. ext4 data journaling은 암호화 일반 파일에서 지원되지 않아 ordered data mode로 폴백합니다. DAX도 지원하지 않습니다.

암호화 심볼릭 링크의 최대 길이는 평문보다 2바이트 짧습니다. 예를 들어 4K 블록 ext4에서 종료 NUL을 제외한 평문 링크는 4095바이트, 암호화 링크는 4093바이트입니다. `mmap`은 페이지 캐시에 암호문이 아니라 평문을 보관하므로 지원됩니다.

키가 없어도 `stat()`으로 메타데이터를 읽고 디렉터리를 나열하며 파일을 삭제할 수 있습니다. 파일 이름은 암호문에서 파생한 인코딩 형태로 보이고 `NAME_MAX` 이내이며 `/`와 NUL을 포함하지 않고 각 directory entry를 고유하게 식별합니다. `.`과 `..`는 항상 평문입니다. `unlink()`, 빈 디렉터리 `rmdir()`, `rm -r`도 동작합니다.

키 없이 심볼릭 링크 대상을 읽거나 따라갈 수는 있지만 암호화 표현으로 보이므로 유용한 위치를 가리킬 가능성은 낮습니다. 일반 파일 open·truncate는 `ENOKEY`이며 fd가 필요한 `read()`, `write()`, `mmap()`, `fallocate()`, `ioctl()`도 불가능합니다.

키가 없으면 암호화 디렉터리 안에 어떤 형식의 파일도 만들거나 link할 수 없고, 그 안의 이름을 rename의 source 또는 target으로 쓸 수 없으며 `O_TMPFILE`도 만들 수 없습니다. 모두 `ENOKEY`입니다. 키 없이 암호화 파일을 백업·복원하는 전용 API는 아직 구현되지 않았습니다.

정책을 설정한 디렉터리에서 새로 만들어지는 일반 파일, 디렉터리, 심볼릭 링크는 재귀적으로 정책을 상속합니다. named pipe, device node, UNIX domain socket 같은 특수 파일은 암호화하지 않습니다.

특수 파일을 제외하면 평문 파일이나 다른 정책의 파일이 암호화 트리에 들어가는 것을 금지하고 link·rename에 `EXDEV`를 반환합니다. `->lookup()`에서도 이를 검사해 공격자가 오프라인으로 알려진 위치의 암호화를 비활성화하거나 낮춘 뒤 애플리케이션이 민감 데이터를 쓰게 하는 공격을 제한합니다. verified boot 시스템은 접근 전에 최상위 암호화 정책을 검증해야 합니다.

키 유무별 동작
연산키 있음키 없음
`stat()`메타데이터메타데이터
`readdir()`평문 이름암호문 파생 인코딩 이름
`open()` 일반 파일허용`ENOKEY`
`unlink()` / `rmdir()`허용허용
create·link·rename·`O_TMPFILE`정책 일치 시 허용`ENOKEY`
`mmap()`평문 pagecache로 허용fd를 열 수 없어 불가

같은 inode가 key state에 따라 제공하는 인터페이스입니다.

Access semantics
================

With the key
------------

With the encryption key, encrypted regular files, directories, and
symlinks behave very similarly to their unencrypted counterparts ---
after all, the encryption is intended to be transparent.  However,
astute users may notice some differences in behavior:

- Unencrypted files, or files encrypted with a different encryption
  policy (i.e. different key, modes, or flags), cannot be renamed or
  linked into an encrypted directory; see `Encryption policy
  enforcement`_.  Attempts to do so will fail with EXDEV.  However,
  encrypted files can be renamed within an encrypted directory, or
  into an unencrypted directory.

  Note: "moving" an unencrypted file into an encrypted directory, e.g.
  with the `mv` program, is implemented in userspace by a copy
  followed by a delete.  Be aware that the original unencrypted data
  may remain recoverable from free space on the disk; prefer to keep
  all files encrypted from the very beginning.  The `shred` program
  may be used to overwrite the source files but isn't guaranteed to be
  effective on all filesystems and storage devices.

- Direct I/O is supported on encrypted files only under some
  circumstances.  For details, see `Direct I/O support`_.

- The fallocate operations FALLOC_FL_COLLAPSE_RANGE and
  FALLOC_FL_INSERT_RANGE are not supported on encrypted files and will
  fail with EOPNOTSUPP.

- Online defragmentation of encrypted files is not supported.  The
  EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail with
  EOPNOTSUPP.

- The ext4 filesystem does not support data journaling with encrypted
  regular files.  It will fall back to ordered data mode instead.

- DAX (Direct Access) is not supported on encrypted files.

- The maximum length of an encrypted symlink is 2 bytes shorter than
  the maximum length of an unencrypted symlink.  For example, on an
  EXT4 filesystem with a 4K block size, unencrypted symlinks can be up
  to 4095 bytes long, while encrypted symlinks can only be up to 4093
  bytes long (both lengths excluding the terminating null).

Note that mmap *is* supported.  This is possible because the pagecache
for an encrypted file contains the plaintext, not the ciphertext.

Without the key
---------------

Some filesystem operations may be performed on encrypted regular
files, directories, and symlinks even before their encryption key has
been added, or after their encryption key has been removed:

- File metadata may be read, e.g. using stat().

- Directories may be listed, in which case the filenames will be
  listed in an encoded form derived from their ciphertext.  The
  current encoding algorithm is described in `Filename hashing and
  encoding`_.  The algorithm is subject to change, but it is
  guaranteed that the presented filenames will be no longer than
  NAME_MAX bytes, will not contain the ``/`` or ``\0`` characters, and
  will uniquely identify directory entries.

  The ``.`` and ``..`` directory entries are special.  They are always
  present and are not encrypted or encoded.

- Files may be deleted.  That is, nondirectory files may be deleted
  with unlink() as usual, and empty directories may be deleted with
  rmdir() as usual.  Therefore, ``rm`` and ``rm -r`` will work as
  expected.

- Symlink targets may be read and followed, but they will be presented
  in encrypted form, similar to filenames in directories.  Hence, they
  are unlikely to point to anywhere useful.

Without the key, regular files cannot be opened or truncated.
Attempts to do so will fail with ENOKEY.  This implies that any
regular file operations that require a file descriptor, such as
read(), write(), mmap(), fallocate(), and ioctl(), are also forbidden.

Also without the key, files of any type (including directories) cannot
be created or linked into an encrypted directory, nor can a name in an
encrypted directory be the source or target of a rename, nor can an
O_TMPFILE temporary file be created in an encrypted directory.  All
such operations will fail with ENOKEY.

It is not currently possible to backup and restore encrypted files
without the encryption key.  This would require special APIs which
have not yet been implemented.

Encryption policy enforcement
=============================

After an encryption policy has been set on a directory, all regular
files, directories, and symbolic links created in that directory
(recursively) will inherit that encryption policy.  Special files ---
that is, named pipes, device nodes, and UNIX domain sockets --- will
not be encrypted.

Except for those special files, it is forbidden to have unencrypted
files, or files encrypted with a different encryption policy, in an
encrypted directory tree.  Attempts to link or rename such a file into
an encrypted directory will fail with EXDEV.  This is also enforced
during ->lookup() to provide limited protection against offline
attacks that try to disable or downgrade encryption in known locations
where applications may later write sensitive data.  It is recommended
that systems implementing a form of "verified boot" take advantage of
this by validating all top-level encryption policies prior to access.

인라인 암호화, hardware-wrapped key와 direct I/O

1320-1445

최신 모바일 SoC 등의 inline encryption hardware는 저장장치로 오가는 동안 데이터를 암복호화합니다. Linux의 block layer 확장인 blk-crypto는 filesystem이 bio에 encryption context를 붙이게 합니다. 자세한 내용은 `Documentation/block/inline-encryption.rst`의 `inline_encryption` 절에 있습니다.

현재 ext4와 F2FS에서 fscrypt는 파일 내용에 Crypto API 대신 blk-crypto를 사용할 수 있습니다. 커널에서 `CONFIG_FS_ENCRYPTION_INLINE_CRYPT=y`를 설정하고 파일시스템을 `inlinecrypt` 옵션으로 마운트합니다.

`inlinecrypt`는 가능할 때 인라인 암호화를 사용하라는 뜻이지 강제하지는 않습니다. 하드웨어가 필요한 알고리즘·data unit size를 지원하지 않고 blk-crypto fallback도 사용할 수 없으면 Crypto API로 폴백합니다. blk-crypto fallback에는 `CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK=y`가 필요하고 파일은 hardware-wrapped key가 아닌 raw key로 보호되어야 합니다.

이 문서가 설명하는 현재 구현에서 fscrypt는 항상 보통 4096바이트인 파일시스템 블록 크기를 data unit size로 쓰므로 그 크기를 지원하는 하드웨어만 사용할 수 있습니다. 인라인 사용 여부는 암호문이나 on-disk format을 바꾸지 않으므로 자유롭게 전환할 수 있습니다. 단, hardware-wrapped key 파일은 하드웨어만 암복호화할 수 있어 `inlinecrypt` 마운트에서만 접근할 수 있습니다.

hardware-wrapped key는 커널 메모리에 래핑된 암호문 형태로만 존재하고 인라인 하드웨어만 풀 수 있으며 현재 부팅에 시간적으로 결속됩니다. 커널 메모리가 유출되어도 키를 보호하고 키 개수를 제한하지 않으면서, 파일 이름 암호화처럼 같은 키에 연계되지만 인라인 하드웨어로 처리할 수 없는 작업도 지원합니다. 이는 fscrypt 전용이 아니라 blk-crypto 기능입니다.

`FS_IOC_ADD_ENCRYPTION_KEY`로 hardware-wrapped key를 추가할 때 `struct fscrypt_add_key_arg.flags`와 provisioning key를 쓴다면 `struct fscrypt_provisioning_key_payload.flags` 모두에 `FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED`를 지정합니다. 키는 장기 래핑 형태가 아니라 ephemeral-wrapped 형태여야 합니다.

wrapped key 파일은 시스템의 인라인 하드웨어에 묶이므로 portable filesystem image에 넣을 수 없습니다. 현재는 master key마다 내용 키 하나만 있다고 가정하는 `IV_INO_LBLK_64`와 `IV_INO_LBLK_32` 정책만 호환됩니다. 향후 per-file nonce를 storage stack으로 전달해 하드웨어가 per-file key를 파생하도록 개선할 수 있습니다.

내용 I/O에서 fscrypt는 wrapped key를 bio crypt context에 붙입니다. block layer가 keyslot을 프로그래밍할 때 하드웨어는 입력 키를 직접 넣지 않고 ephemeral wrapping key로 풀어 inline encryption key를 파생합니다. 실제 keyslot에는 이 파생 키가 들어가며 소프트웨어에는 절대 노출되지 않습니다.

파일 이름 키, key identifier, dirhash key 같은 다른 하위 키에는 raw key material이 필요합니다. fscrypt는 하드웨어에 wrapped key로부터 암호학적으로 격리된 `software secret`을 파생해 달라고 요청하고, 이를 KDF 키로 삼아 내용 키 외 하위 키를 파생합니다. 따라서 wrapped 기능이 보호하는 것은 파일 내용 암호화 키이며 파일 이름 키 등은 보호하지 않습니다.

암호화 파일의 direct I/O에는 인라인 암호화가 필요합니다. 보통 `-o inlinecrypt`와 하드웨어가 필요하지만 소프트웨어 fallback도 가능합니다. 또한 파일 위치, 모든 I/O segment 길이, 모든 buffer 메모리 주소가 파일시스템 블록 크기의 배수여야 합니다. 파일시스템 블록은 장치 logical block보다 클 수 있습니다. 조건 하나라도 맞지 않으면 buffered I/O로 폴백합니다.

hardware-wrapped 내용 키 경로
사용자 공간이 ephemeral-wrapped master key 추가커널 메모리에는 wrapped 형태만 보관bio crypt context가 wrapped key를 block layer로 전달하드웨어가 unwrap 후 inline encryption key 파생파생 내용 키를 keyslot에 넣고 소프트웨어에는 미노출별도 software secret으로 파일 이름·identifier·dirhash 키 파생

소프트웨어에 노출되는 정보와 하드웨어에만 존재하는 키를 분리합니다.

Direct I/O 추가 조건
조건요구 사항불충족 시
암호화 경로inline encryption 사용buffered I/O 폴백
파일 위치filesystem block size 배수buffered I/O 폴백
각 segment 길이filesystem block size 배수buffered I/O 폴백
각 buffer 주소filesystem block size 배수buffered I/O 폴백

평문 파일의 일반 조건에 더해 모두 만족해야 합니다.

Inline encryption support
=========================

Many newer systems (especially mobile SoCs) have *inline encryption
hardware* that can encrypt/decrypt data while it is on its way to/from
the storage device.  Linux supports inline encryption through a set of
extensions to the block layer called *blk-crypto*.  blk-crypto allows
filesystems to attach encryption contexts to bios (I/O requests) to
specify how the data will be encrypted or decrypted in-line.  For more
information about blk-crypto, see
:ref:`Documentation/block/inline-encryption.rst <inline_encryption>`.

On supported filesystems (currently ext4 and f2fs), fscrypt can use
blk-crypto instead of the kernel crypto API to encrypt/decrypt file
contents.  To enable this, set CONFIG_FS_ENCRYPTION_INLINE_CRYPT=y in
the kernel configuration, and specify the "inlinecrypt" mount option
when mounting the filesystem.

Note that the "inlinecrypt" mount option just specifies to use inline
encryption when possible; it doesn't force its use.  fscrypt will
still fall back to using the kernel crypto API on files where the
inline encryption hardware doesn't have the needed crypto capabilities
(e.g. support for the needed encryption algorithm and data unit size)
and where blk-crypto-fallback is unusable.  (For blk-crypto-fallback
to be usable, it must be enabled in the kernel configuration with
CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK=y, and the file must be
protected by a raw key rather than a hardware-wrapped key.)

Currently fscrypt always uses the filesystem block size (which is
usually 4096 bytes) as the data unit size.  Therefore, it can only use
inline encryption hardware that supports that data unit size.

Inline encryption doesn't affect the ciphertext or other aspects of
the on-disk format, so users may freely switch back and forth between
using "inlinecrypt" and not using "inlinecrypt".  An exception is that
files that are protected by a hardware-wrapped key can only be
encrypted/decrypted by the inline encryption hardware and therefore
can only be accessed when the "inlinecrypt" mount option is used.  For
more information about hardware-wrapped keys, see below.

Hardware-wrapped keys
---------------------

fscrypt supports using *hardware-wrapped keys* when the inline
encryption hardware supports it.  Such keys are only present in kernel
memory in wrapped (encrypted) form; they can only be unwrapped
(decrypted) by the inline encryption hardware and are temporally bound
to the current boot.  This prevents the keys from being compromised if
kernel memory is leaked.  This is done without limiting the number of
keys that can be used and while still allowing the execution of
cryptographic tasks that are tied to the same key but can't use inline
encryption hardware, e.g. filenames encryption.

Note that hardware-wrapped keys aren't specific to fscrypt; they are a
block layer feature (part of *blk-crypto*).  For more details about
hardware-wrapped keys, see the block layer documentation at
:ref:`Documentation/block/inline-encryption.rst
<hardware_wrapped_keys>`.  The rest of this section just focuses on
the details of how fscrypt can use hardware-wrapped keys.

fscrypt supports hardware-wrapped keys by allowing the fscrypt master
keys to be hardware-wrapped keys as an alternative to raw keys.  To
add a hardware-wrapped key with `FS_IOC_ADD_ENCRYPTION_KEY`_,
userspace must specify FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED in the
``flags`` field of struct fscrypt_add_key_arg and also in the
``flags`` field of struct fscrypt_provisioning_key_payload when
applicable.  The key must be in ephemerally-wrapped form, not
long-term wrapped form.

Some limitations apply.  First, files protected by a hardware-wrapped
key are tied to the system's inline encryption hardware.  Therefore
they can only be accessed when the "inlinecrypt" mount option is used,
and they can't be included in portable filesystem images.  Second,
currently the hardware-wrapped key support is only compatible with
`IV_INO_LBLK_64 policies`_ and `IV_INO_LBLK_32 policies`_, as it
assumes that there is just one file contents encryption key per
fscrypt master key rather than one per file.  Future work may address
this limitation by passing per-file nonces down the storage stack to
allow the hardware to derive per-file keys.

Implementation-wise, to encrypt/decrypt the contents of files that are
protected by a hardware-wrapped key, fscrypt uses blk-crypto,
attaching the hardware-wrapped key to the bio crypt contexts.  As is
the case with raw keys, the block layer will program the key into a
keyslot when it isn't already in one.  However, when programming a
hardware-wrapped key, the hardware doesn't program the given key
directly into a keyslot but rather unwraps it (using the hardware's
ephemeral wrapping key) and derives the inline encryption key from it.
The inline encryption key is the key that actually gets programmed
into a keyslot, and it is never exposed to software.

However, fscrypt doesn't just do file contents encryption; it also
uses its master keys to derive filenames encryption keys, key
identifiers, and sometimes some more obscure types of subkeys such as
dirhash keys.  So even with file contents encryption out of the
picture, fscrypt still needs a raw key to work with.  To get such a
key from a hardware-wrapped key, fscrypt asks the inline encryption
hardware to derive a cryptographically isolated "software secret" from
the hardware-wrapped key.  fscrypt uses this "software secret" to key
its KDF to derive all subkeys other than file contents keys.

Note that this implies that the hardware-wrapped key feature only
protects the file contents encryption keys.  It doesn't protect other
fscrypt subkeys such as filenames encryption keys.

Direct I/O support
==================

For direct I/O on an encrypted file to work, the following conditions
must be met (in addition to the conditions for direct I/O on an
unencrypted file):

* The file must be using inline encryption.  Usually this means that
  the filesystem must be mounted with ``-o inlinecrypt`` and inline
  encryption hardware must be present.  However, a software fallback
  is also available.  For details, see `Inline encryption support`_.

* The I/O request must be fully aligned to the filesystem block size.
  This means that the file position the I/O is targeting, the lengths
  of all I/O segments, and the memory addresses of all I/O buffers
  must be multiples of this value.  Note that the filesystem block
  size may be greater than the logical block size of the block device.

If either of the above conditions is not met, then direct I/O on the
encrypted file will fall back to buffered I/O.

On-disk context, 데이터 경로와 이름 인코딩

1446-1556

암호화 정책의 on-disk 표현은 `struct fscrypt_context_v1` 또는 `struct fscrypt_context_v2`입니다. 저장 위치는 파일시스템이 정하지만 보통 숨은 확장 속성입니다. 암호화 xattr에는 특별한 의미가 있으므로 `getxattr()`·`setxattr()` 같은 일반 xattr system call에 노출하면 안 됩니다. 빈 디렉터리가 아닌 객체에 정책이 임의로 추가·제거되는 혼란을 막기 위해서입니다.

context 구조체는 대응하는 policy 구조체와 같은 정보를 담고 16바이트 nonce를 추가합니다. nonce는 커널이 무작위로 생성하며 KDF 입력 또는 파일마다 다른 암호문을 만들기 위한 tweak로 사용합니다.

#define FSCRYPT_FILE_NONCE_SIZE 16
struct fscrypt_context_v1 {
        u8 version;
        u8 contents_encryption_mode;
        u8 filenames_encryption_mode;
        u8 flags;
        u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
        u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
};

struct fscrypt_context_v2 {
        u8 version;
        u8 contents_encryption_mode;
        u8 filenames_encryption_mode;
        u8 flags;
        u8 log2_data_unit_size;
        u8 __reserved[3];
        u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
        u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
};

인라인 암호화를 쓸 때 파일시스템은 bio에 encryption context를 연결해 block layer나 하드웨어가 파일 내용을 암복호화하도록 지정하면 됩니다.

인라인을 쓰지 않는 일반 파일 read 경로 `->read_folio()`에서는 암호문을 page cache로 읽고 제자리 복호화할 수 있습니다. 복호화가 끝나기 전에 folio가 사용자 공간에 보이지 않도록 folio lock을 끝까지 유지해야 합니다.

write 경로 `->writepages()`에서는 cache의 평문을 보존해야 하므로 page cache에서 제자리 암호화할 수 없습니다. 임시 buffer 또는 bounce page에 암호화해 그 버퍼를 기록합니다. UBIFS는 암호화와 무관하게 임시 버퍼를 쓰지만 ext4와 F2FS는 암호화를 위해 bounce page를 별도로 할당합니다.

현대 파일시스템의 indexed directory는 파일 이름 해시를 key로 한 트리입니다. 키가 없는 상태에서도 효율적으로 조회해야 하므로 평문 이름이 아니라 directory entry에 실제 저장된 암호문 이름을 해시합니다. 키가 있을 때 `->lookup()`은 사용자가 준 이름을 암호화해 암호문을 얻고 조회합니다. 이 설계는 fsck가 암호화 디렉터리를 최적화하는 것도 가능하게 합니다.

키가 없을 때 raw ciphertext에는 파일 이름에서 금지된 NUL과 `/`가 들어갈 수 있으므로 `readdir()`은 base64url로 인코딩합니다. 보통 `->lookup()`은 이를 디코딩해 원래 암호문으로 되돌립니다.

매우 긴 이름은 base64url 인코딩하면 `NAME_MAX`를 넘으므로 강한 암호문 hash와 디렉터리 조회에 필요한 선택적 파일시스템별 hash를 담은 축약 형식으로 표시합니다. `struct fscrypt_nokey_name`에 세부 구조가 있습니다. `readdir()`로 본 이름을 `->lookup()`이 높은 확률로 같은 entry에 매핑할 수 있게 합니다.

키 없는 상태의 파일 이름 표현은 향후 바뀔 수 있습니다. 영구 백업 형식이 아니라 `rm -r` 같은 명령이 암호화 디렉터리에서도 동작하도록 일시적으로 유효한 이름을 제시하는 수단입니다.

비인라인 데이터 경로
읽기: 디스크 암호문을 page cache folio로 읽기folio lock을 유지한 채 제자리 복호화복호화 완료 뒤 사용자 공간에 평문 노출쓰기: page cache 평문은 그대로 보존bounce page·임시 buffer에 암호화임시 암호문을 저장장치에 기록

page cache 평문 보존 요구가 읽기와 쓰기 경로를 다르게 만듭니다.

키 없는 이름 조회
directory entry에는 암호문 이름 저장짧은 암호문은 base64url로 표시긴 암호문은 strong hash와 filesystem hash로 축약사용자 공간이 표시 이름으로 lookup 요청디코딩 또는 fscrypt_nokey_name hash로 entry 식별

불법 바이트와 NAME_MAX를 피하면서 entry를 다시 찾는 경로입니다.

Implementation details
======================

Encryption context
------------------

An encryption policy is represented on-disk by
struct fscrypt_context_v1 or struct fscrypt_context_v2.  It is up to
individual filesystems to decide where to store it, but normally it
would be stored in a hidden extended attribute.  It should *not* be
exposed by the xattr-related system calls such as getxattr() and
setxattr() because of the special semantics of the encryption xattr.
(In particular, there would be much confusion if an encryption policy
were to be added to or removed from anything other than an empty
directory.)  These structs are defined as follows::

    #define FSCRYPT_FILE_NONCE_SIZE 16

    #define FSCRYPT_KEY_DESCRIPTOR_SIZE  8
    struct fscrypt_context_v1 {
            u8 version;
            u8 contents_encryption_mode;
            u8 filenames_encryption_mode;
            u8 flags;
            u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
            u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
    };

    #define FSCRYPT_KEY_IDENTIFIER_SIZE  16
    struct fscrypt_context_v2 {
            u8 version;
            u8 contents_encryption_mode;
            u8 filenames_encryption_mode;
            u8 flags;
            u8 log2_data_unit_size;
            u8 __reserved[3];
            u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
            u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
    };

The context structs contain the same information as the corresponding
policy structs (see `Setting an encryption policy`_), except that the
context structs also contain a nonce.  The nonce is randomly generated
by the kernel and is used as KDF input or as a tweak to cause
different files to be encrypted differently; see `Per-file encryption
keys`_ and `DIRECT_KEY policies`_.

Data path changes
-----------------

When inline encryption is used, filesystems just need to associate
encryption contexts with bios to specify how the block layer or the
inline encryption hardware will encrypt/decrypt the file contents.

When inline encryption isn't used, filesystems must encrypt/decrypt
the file contents themselves, as described below:

For the read path (->read_folio()) of regular files, filesystems can
read the ciphertext into the page cache and decrypt it in-place.  The
folio lock must be held until decryption has finished, to prevent the
folio from becoming visible to userspace prematurely.

For the write path (->writepages()) of regular files, filesystems
cannot encrypt data in-place in the page cache, since the cached
plaintext must be preserved.  Instead, filesystems must encrypt into a
temporary buffer or "bounce page", then write out the temporary
buffer.  Some filesystems, such as UBIFS, already use temporary
buffers regardless of encryption.  Other filesystems, such as ext4 and
F2FS, have to allocate bounce pages specially for encryption.

Filename hashing and encoding
-----------------------------

Modern filesystems accelerate directory lookups by using indexed
directories.  An indexed directory is organized as a tree keyed by
filename hashes.  When a ->lookup() is requested, the filesystem
normally hashes the filename being looked up so that it can quickly
find the corresponding directory entry, if any.

With encryption, lookups must be supported and efficient both with and
without the encryption key.  Clearly, it would not work to hash the
plaintext filenames, since the plaintext filenames are unavailable
without the key.  (Hashing the plaintext filenames would also make it
impossible for the filesystem's fsck tool to optimize encrypted
directories.)  Instead, filesystems hash the ciphertext filenames,
i.e. the bytes actually stored on-disk in the directory entries.  When
asked to do a ->lookup() with the key, the filesystem just encrypts
the user-supplied name to get the ciphertext.

Lookups without the key are more complicated.  The raw ciphertext may
contain the ``\0`` and ``/`` characters, which are illegal in
filenames.  Therefore, readdir() must base64url-encode the ciphertext
for presentation.  For most filenames, this works fine; on ->lookup(),
the filesystem just base64url-decodes the user-supplied name to get
back to the raw ciphertext.

However, for very long filenames, base64url encoding would cause the
filename length to exceed NAME_MAX.  To prevent this, readdir()
actually presents long filenames in an abbreviated form which encodes
a strong "hash" of the ciphertext filename, along with the optional
filesystem-specific hash(es) needed for directory lookups.  This
allows the filesystem to still, with a high degree of confidence, map
the filename given in ->lookup() back to a particular directory entry
that was previously listed by readdir().  See
struct fscrypt_nokey_name in the source for more details.

Note that the precise way that filenames are presented to userspace
without the key is subject to change in the future.  It is only meant
as a way to temporarily present valid filenames so that commands like
``rm -r`` work as expected on encrypted directories.

xfstests를 이용한 검증

1557-1599

fscrypt 검증에는 Linux 파일시스템의 사실상 표준 테스트 스위트인 xfstests를 사용합니다. 먼저 대상 파일시스템에서 `encrypt` 그룹 전체를 실행하고 `inlinecrypt` 마운트 옵션을 추가한 실행으로 인라인 구현도 검사합니다.

kvm-xfstests -c ext4,f2fs -g encrypt
kvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt
kvm-xfstests -c ubifs -g encrypt

UBIFS도 같은 방식으로 테스트할 수 있지만 emulated UBI volume 준비에 시간이 걸리므로 별도 명령으로 실행합니다. 실패하는 테스트가 없어야 합니다. 다만 generic/549와 generic/550처럼 비기본 암호화 모드를 쓰는 테스트는 필요한 알고리즘이 커널 Crypto API에 빌드되지 않았으면 skip됩니다.

raw block device에 접근하는 generic/399, generic/548, generic/549, generic/550은 UBIFS에서 skip됩니다. 이는 지원되지 않는 테스트 환경 조건에 따른 skip이며 실패와 구분해야 합니다.

ext4와 F2FS에서는 `test_dummy_encryption` 마운트 옵션으로 대부분의 xfstests를 실행할 수도 있습니다. API 호출 없이 모든 새 파일을 dummy key로 자동 암호화해 encrypted I/O path를 더 폭넓게 검사합니다.

kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt

gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt

`-g auto`는 `-g encrypt`보다 훨씬 많은 테스트를 실행해 오래 걸리므로 필요하면 kvm-xfstests 대신 gce-xfstests를 사용할 수 있습니다. raw key·인라인·비기본 모드·UBIFS의 환경 차이를 고려해 skip 이유를 확인하되 실제 실패는 허용하지 않습니다.

fscrypt 테스트 매트릭스
대상명령·구성판정
ext4·F2FS 기본`-c ext4,f2fs -g encrypt`실패 0
ext4·F2FS 인라인`-g encrypt -m inlinecrypt`인라인 경로 실패 0
UBIFS`-c ubifs -g encrypt`raw block 접근 테스트 skip 가능
dummy encryption`-c ext4/encrypt,f2fs/encrypt -g auto`광범위 encrypted I/O
대규모 실행gce-xfstests + `-g auto`장시간 테스트에 적합

파일시스템과 경로별 권장 실행 및 예상 skip입니다.

Tests
=====

To test fscrypt, use xfstests, which is Linux's de facto standard
filesystem test suite.  First, run all the tests in the "encrypt"
group on the relevant filesystem(s).  One can also run the tests
with the 'inlinecrypt' mount option to test the implementation for
inline encryption support.  For example, to test ext4 and
f2fs encryption using `kvm-xfstests
<https://github.com/tytso/xfstests-bld/blob/master/Documentation/kvm-quickstart.md>`_::

    kvm-xfstests -c ext4,f2fs -g encrypt
    kvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt

UBIFS encryption can also be tested this way, but it should be done in
a separate command, and it takes some time for kvm-xfstests to set up
emulated UBI volumes::

    kvm-xfstests -c ubifs -g encrypt

No tests should fail.  However, tests that use non-default encryption
modes (e.g. generic/549 and generic/550) will be skipped if the needed
algorithms were not built into the kernel's crypto API.  Also, tests
that access the raw block device (e.g. generic/399, generic/548,
generic/549, generic/550) will be skipped on UBIFS.

Besides running the "encrypt" group tests, for ext4 and f2fs it's also
possible to run most xfstests with the "test_dummy_encryption" mount
option.  This option causes all new files to be automatically
encrypted with a dummy key, without having to make any API calls.
This tests the encrypted I/O paths more thoroughly.  To do this with
kvm-xfstests, use the "encrypt" filesystem configuration::

    kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
    kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt

Because this runs many more tests than "-g encrypt" does, it takes
much longer to run; so also consider using `gce-xfstests
<https://github.com/tytso/xfstests-bld/blob/master/Documentation/gce-xfstests.md>`_
instead of kvm-xfstests::

    gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
    gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt