fscrypt.rst 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. =====================================
  2. Filesystem-level encryption (fscrypt)
  3. =====================================
  4. Introduction
  5. ============
  6. fscrypt is a library which filesystems can hook into to support
  7. transparent encryption of files and directories.
  8. Note: "fscrypt" in this document refers to the kernel-level portion,
  9. implemented in ``fs/crypto/``, as opposed to the userspace tool
  10. `fscrypt <https://github.com/google/fscrypt>`_. This document only
  11. covers the kernel-level portion. For command-line examples of how to
  12. use encryption, see the documentation for the userspace tool `fscrypt
  13. <https://github.com/google/fscrypt>`_. Also, it is recommended to use
  14. the fscrypt userspace tool, or other existing userspace tools such as
  15. `fscryptctl <https://github.com/google/fscryptctl>`_ or `Android's key
  16. management system
  17. <https://source.android.com/security/encryption/file-based>`_, over
  18. using the kernel's API directly. Using existing tools reduces the
  19. chance of introducing your own security bugs. (Nevertheless, for
  20. completeness this documentation covers the kernel's API anyway.)
  21. Unlike dm-crypt, fscrypt operates at the filesystem level rather than
  22. at the block device level. This allows it to encrypt different files
  23. with different keys and to have unencrypted files on the same
  24. filesystem. This is useful for multi-user systems where each user's
  25. data-at-rest needs to be cryptographically isolated from the others.
  26. However, except for filenames, fscrypt does not encrypt filesystem
  27. metadata.
  28. Unlike eCryptfs, which is a stacked filesystem, fscrypt is integrated
  29. directly into supported filesystems --- currently ext4, F2FS, and
  30. UBIFS. This allows encrypted files to be read and written without
  31. caching both the decrypted and encrypted pages in the pagecache,
  32. thereby nearly halving the memory used and bringing it in line with
  33. unencrypted files. Similarly, half as many dentries and inodes are
  34. needed. eCryptfs also limits encrypted filenames to 143 bytes,
  35. causing application compatibility issues; fscrypt allows the full 255
  36. bytes (NAME_MAX). Finally, unlike eCryptfs, the fscrypt API can be
  37. used by unprivileged users, with no need to mount anything.
  38. fscrypt does not support encrypting files in-place. Instead, it
  39. supports marking an empty directory as encrypted. Then, after
  40. userspace provides the key, all regular files, directories, and
  41. symbolic links created in that directory tree are transparently
  42. encrypted.
  43. Threat model
  44. ============
  45. Offline attacks
  46. ---------------
  47. Provided that userspace chooses a strong encryption key, fscrypt
  48. protects the confidentiality of file contents and filenames in the
  49. event of a single point-in-time permanent offline compromise of the
  50. block device content. fscrypt does not protect the confidentiality of
  51. non-filename metadata, e.g. file sizes, file permissions, file
  52. timestamps, and extended attributes. Also, the existence and location
  53. of holes (unallocated blocks which logically contain all zeroes) in
  54. files is not protected.
  55. fscrypt is not guaranteed to protect confidentiality or authenticity
  56. if an attacker is able to manipulate the filesystem offline prior to
  57. an authorized user later accessing the filesystem.
  58. Online attacks
  59. --------------
  60. fscrypt (and storage encryption in general) can only provide limited
  61. protection, if any at all, against online attacks. In detail:
  62. fscrypt is only resistant to side-channel attacks, such as timing or
  63. electromagnetic attacks, to the extent that the underlying Linux
  64. Cryptographic API algorithms are. If a vulnerable algorithm is used,
  65. such as a table-based implementation of AES, it may be possible for an
  66. attacker to mount a side channel attack against the online system.
  67. Side channel attacks may also be mounted against applications
  68. consuming decrypted data.
  69. After an encryption key has been provided, fscrypt is not designed to
  70. hide the plaintext file contents or filenames from other users on the
  71. same system, regardless of the visibility of the keyring key.
  72. Instead, existing access control mechanisms such as file mode bits,
  73. POSIX ACLs, LSMs, or mount namespaces should be used for this purpose.
  74. Also note that as long as the encryption keys are *anywhere* in
  75. memory, an online attacker can necessarily compromise them by mounting
  76. a physical attack or by exploiting any kernel security vulnerability
  77. which provides an arbitrary memory read primitive.
  78. While it is ostensibly possible to "evict" keys from the system,
  79. recently accessed encrypted files will remain accessible at least
  80. until the filesystem is unmounted or the VFS caches are dropped, e.g.
  81. using ``echo 2 > /proc/sys/vm/drop_caches``. Even after that, if the
  82. RAM is compromised before being powered off, it will likely still be
  83. possible to recover portions of the plaintext file contents, if not
  84. some of the encryption keys as well. (Since Linux v4.12, all
  85. in-kernel keys related to fscrypt are sanitized before being freed.
  86. However, userspace would need to do its part as well.)
  87. Currently, fscrypt does not prevent a user from maliciously providing
  88. an incorrect key for another user's existing encrypted files. A
  89. protection against this is planned.
  90. Key hierarchy
  91. =============
  92. Master Keys
  93. -----------
  94. Each encrypted directory tree is protected by a *master key*. Master
  95. keys can be up to 64 bytes long, and must be at least as long as the
  96. greater of the key length needed by the contents and filenames
  97. encryption modes being used. For example, if AES-256-XTS is used for
  98. contents encryption, the master key must be 64 bytes (512 bits). Note
  99. that the XTS mode is defined to require a key twice as long as that
  100. required by the underlying block cipher.
  101. To "unlock" an encrypted directory tree, userspace must provide the
  102. appropriate master key. There can be any number of master keys, each
  103. of which protects any number of directory trees on any number of
  104. filesystems.
  105. Userspace should generate master keys either using a cryptographically
  106. secure random number generator, or by using a KDF (Key Derivation
  107. Function). Note that whenever a KDF is used to "stretch" a
  108. lower-entropy secret such as a passphrase, it is critical that a KDF
  109. designed for this purpose be used, such as scrypt, PBKDF2, or Argon2.
  110. Per-file keys
  111. -------------
  112. Master keys are not used to encrypt file contents or names directly.
  113. Instead, a unique key is derived for each encrypted file, including
  114. each regular file, directory, and symbolic link. This has several
  115. advantages:
  116. - In cryptosystems, the same key material should never be used for
  117. different purposes. Using the master key as both an XTS key for
  118. contents encryption and as a CTS-CBC key for filenames encryption
  119. would violate this rule.
  120. - Per-file keys simplify the choice of IVs (Initialization Vectors)
  121. for contents encryption. Without per-file keys, to ensure IV
  122. uniqueness both the inode and logical block number would need to be
  123. encoded in the IVs. This would make it impossible to renumber
  124. inodes, which e.g. ``resize2fs`` can do when resizing an ext4
  125. filesystem. With per-file keys, it is sufficient to encode just the
  126. logical block number in the IVs.
  127. - Per-file keys strengthen the encryption of filenames, where IVs are
  128. reused out of necessity. With a unique key per directory, IV reuse
  129. is limited to within a single directory.
  130. - Per-file keys allow individual files to be securely erased simply by
  131. securely erasing their keys. (Not yet implemented.)
  132. A KDF (Key Derivation Function) is used to derive per-file keys from
  133. the master key. This is done instead of wrapping a randomly-generated
  134. key for each file because it reduces the size of the encryption xattr,
  135. which for some filesystems makes the xattr more likely to fit in-line
  136. in the filesystem's inode table. With a KDF, only a 16-byte nonce is
  137. required --- long enough to make key reuse extremely unlikely. A
  138. wrapped key, on the other hand, would need to be up to 64 bytes ---
  139. the length of an AES-256-XTS key. Furthermore, currently there is no
  140. requirement to support unlocking a file with multiple alternative
  141. master keys or to support rotating master keys. Instead, the master
  142. keys may be wrapped in userspace, e.g. as done by the `fscrypt
  143. <https://github.com/google/fscrypt>`_ tool.
  144. The current KDF encrypts the master key using the 16-byte nonce as an
  145. AES-128-ECB key. The output is used as the derived key. If the
  146. output is longer than needed, then it is truncated to the needed
  147. length. Truncation is the norm for directories and symlinks, since
  148. those use the CTS-CBC encryption mode which requires a key half as
  149. long as that required by the XTS encryption mode.
  150. Note: this KDF meets the primary security requirement, which is to
  151. produce unique derived keys that preserve the entropy of the master
  152. key, assuming that the master key is already a good pseudorandom key.
  153. However, it is nonstandard and has some problems such as being
  154. reversible, so it is generally considered to be a mistake! It may be
  155. replaced with HKDF or another more standard KDF in the future.
  156. Encryption modes and usage
  157. ==========================
  158. fscrypt allows one encryption mode to be specified for file contents
  159. and one encryption mode to be specified for filenames. Different
  160. directory trees are permitted to use different encryption modes.
  161. Currently, the following pairs of encryption modes are supported:
  162. - AES-256-XTS for contents and AES-256-CTS-CBC for filenames
  163. - AES-128-CBC for contents and AES-128-CTS-CBC for filenames
  164. - Speck128/256-XTS for contents and Speck128/256-CTS-CBC for filenames
  165. It is strongly recommended to use AES-256-XTS for contents encryption.
  166. AES-128-CBC was added only for low-powered embedded devices with
  167. crypto accelerators such as CAAM or CESA that do not support XTS.
  168. Similarly, Speck128/256 support was only added for older or low-end
  169. CPUs which cannot do AES fast enough -- especially ARM CPUs which have
  170. NEON instructions but not the Cryptography Extensions -- and for which
  171. it would not otherwise be feasible to use encryption at all. It is
  172. not recommended to use Speck on CPUs that have AES instructions.
  173. Speck support is only available if it has been enabled in the crypto
  174. API via CONFIG_CRYPTO_SPECK. Also, on ARM platforms, to get
  175. acceptable performance CONFIG_CRYPTO_SPECK_NEON must be enabled.
  176. New encryption modes can be added relatively easily, without changes
  177. to individual filesystems. However, authenticated encryption (AE)
  178. modes are not currently supported because of the difficulty of dealing
  179. with ciphertext expansion.
  180. For file contents, each filesystem block is encrypted independently.
  181. Currently, only the case where the filesystem block size is equal to
  182. the system's page size (usually 4096 bytes) is supported. With the
  183. XTS mode of operation (recommended), the logical block number within
  184. the file is used as the IV. With the CBC mode of operation (not
  185. recommended), ESSIV is used; specifically, the IV for CBC is the
  186. logical block number encrypted with AES-256, where the AES-256 key is
  187. the SHA-256 hash of the inode's data encryption key.
  188. For filenames, the full filename is encrypted at once. Because of the
  189. requirements to retain support for efficient directory lookups and
  190. filenames of up to 255 bytes, a constant initialization vector (IV) is
  191. used. However, each encrypted directory uses a unique key, which
  192. limits IV reuse to within a single directory. Note that IV reuse in
  193. the context of CTS-CBC encryption means that when the original
  194. filenames share a common prefix at least as long as the cipher block
  195. size (16 bytes for AES), the corresponding encrypted filenames will
  196. also share a common prefix. This is undesirable; it may be fixed in
  197. the future by switching to an encryption mode that is a strong
  198. pseudorandom permutation on arbitrary-length messages, e.g. the HEH
  199. (Hash-Encrypt-Hash) mode.
  200. Since filenames are encrypted with the CTS-CBC mode of operation, the
  201. plaintext and ciphertext filenames need not be multiples of the AES
  202. block size, i.e. 16 bytes. However, the minimum size that can be
  203. encrypted is 16 bytes, so shorter filenames are NUL-padded to 16 bytes
  204. before being encrypted. In addition, to reduce leakage of filename
  205. lengths via their ciphertexts, all filenames are NUL-padded to the
  206. next 4, 8, 16, or 32-byte boundary (configurable). 32 is recommended
  207. since this provides the best confidentiality, at the cost of making
  208. directory entries consume slightly more space. Note that since NUL
  209. (``\0``) is not otherwise a valid character in filenames, the padding
  210. will never produce duplicate plaintexts.
  211. Symbolic link targets are considered a type of filename and are
  212. encrypted in the same way as filenames in directory entries. Each
  213. symlink also uses a unique key; hence, the hardcoded IV is not a
  214. problem for symlinks.
  215. User API
  216. ========
  217. Setting an encryption policy
  218. ----------------------------
  219. The FS_IOC_SET_ENCRYPTION_POLICY ioctl sets an encryption policy on an
  220. empty directory or verifies that a directory or regular file already
  221. has the specified encryption policy. It takes in a pointer to a
  222. :c:type:`struct fscrypt_policy`, defined as follows::
  223. #define FS_KEY_DESCRIPTOR_SIZE 8
  224. struct fscrypt_policy {
  225. __u8 version;
  226. __u8 contents_encryption_mode;
  227. __u8 filenames_encryption_mode;
  228. __u8 flags;
  229. __u8 master_key_descriptor[FS_KEY_DESCRIPTOR_SIZE];
  230. };
  231. This structure must be initialized as follows:
  232. - ``version`` must be 0.
  233. - ``contents_encryption_mode`` and ``filenames_encryption_mode`` must
  234. be set to constants from ``<linux/fs.h>`` which identify the
  235. encryption modes to use. If unsure, use
  236. FS_ENCRYPTION_MODE_AES_256_XTS (1) for ``contents_encryption_mode``
  237. and FS_ENCRYPTION_MODE_AES_256_CTS (4) for
  238. ``filenames_encryption_mode``.
  239. - ``flags`` must be set to a value from ``<linux/fs.h>`` which
  240. identifies the amount of NUL-padding to use when encrypting
  241. filenames. If unsure, use FS_POLICY_FLAGS_PAD_32 (0x3).
  242. - ``master_key_descriptor`` specifies how to find the master key in
  243. the keyring; see `Adding keys`_. It is up to userspace to choose a
  244. unique ``master_key_descriptor`` for each master key. The e4crypt
  245. and fscrypt tools use the first 8 bytes of
  246. ``SHA-512(SHA-512(master_key))``, but this particular scheme is not
  247. required. Also, the master key need not be in the keyring yet when
  248. FS_IOC_SET_ENCRYPTION_POLICY is executed. However, it must be added
  249. before any files can be created in the encrypted directory.
  250. If the file is not yet encrypted, then FS_IOC_SET_ENCRYPTION_POLICY
  251. verifies that the file is an empty directory. If so, the specified
  252. encryption policy is assigned to the directory, turning it into an
  253. encrypted directory. After that, and after providing the
  254. corresponding master key as described in `Adding keys`_, all regular
  255. files, directories (recursively), and symlinks created in the
  256. directory will be encrypted, inheriting the same encryption policy.
  257. The filenames in the directory's entries will be encrypted as well.
  258. Alternatively, if the file is already encrypted, then
  259. FS_IOC_SET_ENCRYPTION_POLICY validates that the specified encryption
  260. policy exactly matches the actual one. If they match, then the ioctl
  261. returns 0. Otherwise, it fails with EEXIST. This works on both
  262. regular files and directories, including nonempty directories.
  263. Note that the ext4 filesystem does not allow the root directory to be
  264. encrypted, even if it is empty. Users who want to encrypt an entire
  265. filesystem with one key should consider using dm-crypt instead.
  266. FS_IOC_SET_ENCRYPTION_POLICY can fail with the following errors:
  267. - ``EACCES``: the file is not owned by the process's uid, nor does the
  268. process have the CAP_FOWNER capability in a namespace with the file
  269. owner's uid mapped
  270. - ``EEXIST``: the file is already encrypted with an encryption policy
  271. different from the one specified
  272. - ``EINVAL``: an invalid encryption policy was specified (invalid
  273. version, mode(s), or flags)
  274. - ``ENOTDIR``: the file is unencrypted and is a regular file, not a
  275. directory
  276. - ``ENOTEMPTY``: the file is unencrypted and is a nonempty directory
  277. - ``ENOTTY``: this type of filesystem does not implement encryption
  278. - ``EOPNOTSUPP``: the kernel was not configured with encryption
  279. support for this filesystem, or the filesystem superblock has not
  280. had encryption enabled on it. (For example, to use encryption on an
  281. ext4 filesystem, CONFIG_EXT4_ENCRYPTION must be enabled in the
  282. kernel config, and the superblock must have had the "encrypt"
  283. feature flag enabled using ``tune2fs -O encrypt`` or ``mkfs.ext4 -O
  284. encrypt``.)
  285. - ``EPERM``: this directory may not be encrypted, e.g. because it is
  286. the root directory of an ext4 filesystem
  287. - ``EROFS``: the filesystem is readonly
  288. Getting an encryption policy
  289. ----------------------------
  290. The FS_IOC_GET_ENCRYPTION_POLICY ioctl retrieves the :c:type:`struct
  291. fscrypt_policy`, if any, for a directory or regular file. See above
  292. for the struct definition. No additional permissions are required
  293. beyond the ability to open the file.
  294. FS_IOC_GET_ENCRYPTION_POLICY can fail with the following errors:
  295. - ``EINVAL``: the file is encrypted, but it uses an unrecognized
  296. encryption context format
  297. - ``ENODATA``: the file is not encrypted
  298. - ``ENOTTY``: this type of filesystem does not implement encryption
  299. - ``EOPNOTSUPP``: the kernel was not configured with encryption
  300. support for this filesystem
  301. Note: if you only need to know whether a file is encrypted or not, on
  302. most filesystems it is also possible to use the FS_IOC_GETFLAGS ioctl
  303. and check for FS_ENCRYPT_FL, or to use the statx() system call and
  304. check for STATX_ATTR_ENCRYPTED in stx_attributes.
  305. Getting the per-filesystem salt
  306. -------------------------------
  307. Some filesystems, such as ext4 and F2FS, also support the deprecated
  308. ioctl FS_IOC_GET_ENCRYPTION_PWSALT. This ioctl retrieves a randomly
  309. generated 16-byte value stored in the filesystem superblock. This
  310. value is intended to used as a salt when deriving an encryption key
  311. from a passphrase or other low-entropy user credential.
  312. FS_IOC_GET_ENCRYPTION_PWSALT is deprecated. Instead, prefer to
  313. generate and manage any needed salt(s) in userspace.
  314. Adding keys
  315. -----------
  316. To provide a master key, userspace must add it to an appropriate
  317. keyring using the add_key() system call (see:
  318. ``Documentation/security/keys/core.rst``). The key type must be
  319. "logon"; keys of this type are kept in kernel memory and cannot be
  320. read back by userspace. The key description must be "fscrypt:"
  321. followed by the 16-character lower case hex representation of the
  322. ``master_key_descriptor`` that was set in the encryption policy. The
  323. key payload must conform to the following structure::
  324. #define FS_MAX_KEY_SIZE 64
  325. struct fscrypt_key {
  326. u32 mode;
  327. u8 raw[FS_MAX_KEY_SIZE];
  328. u32 size;
  329. };
  330. ``mode`` is ignored; just set it to 0. The actual key is provided in
  331. ``raw`` with ``size`` indicating its size in bytes. That is, the
  332. bytes ``raw[0..size-1]`` (inclusive) are the actual key.
  333. The key description prefix "fscrypt:" may alternatively be replaced
  334. with a filesystem-specific prefix such as "ext4:". However, the
  335. filesystem-specific prefixes are deprecated and should not be used in
  336. new programs.
  337. There are several different types of keyrings in which encryption keys
  338. may be placed, such as a session keyring, a user session keyring, or a
  339. user keyring. Each key must be placed in a keyring that is "attached"
  340. to all processes that might need to access files encrypted with it, in
  341. the sense that request_key() will find the key. Generally, if only
  342. processes belonging to a specific user need to access a given
  343. encrypted directory and no session keyring has been installed, then
  344. that directory's key should be placed in that user's user session
  345. keyring or user keyring. Otherwise, a session keyring should be
  346. installed if needed, and the key should be linked into that session
  347. keyring, or in a keyring linked into that session keyring.
  348. Note: introducing the complex visibility semantics of keyrings here
  349. was arguably a mistake --- especially given that by design, after any
  350. process successfully opens an encrypted file (thereby setting up the
  351. per-file key), possessing the keyring key is not actually required for
  352. any process to read/write the file until its in-memory inode is
  353. evicted. In the future there probably should be a way to provide keys
  354. directly to the filesystem instead, which would make the intended
  355. semantics clearer.
  356. Access semantics
  357. ================
  358. With the key
  359. ------------
  360. With the encryption key, encrypted regular files, directories, and
  361. symlinks behave very similarly to their unencrypted counterparts ---
  362. after all, the encryption is intended to be transparent. However,
  363. astute users may notice some differences in behavior:
  364. - Unencrypted files, or files encrypted with a different encryption
  365. policy (i.e. different key, modes, or flags), cannot be renamed or
  366. linked into an encrypted directory; see `Encryption policy
  367. enforcement`_. Attempts to do so will fail with EPERM. However,
  368. encrypted files can be renamed within an encrypted directory, or
  369. into an unencrypted directory.
  370. - Direct I/O is not supported on encrypted files. Attempts to use
  371. direct I/O on such files will fall back to buffered I/O.
  372. - The fallocate operations FALLOC_FL_COLLAPSE_RANGE,
  373. FALLOC_FL_INSERT_RANGE, and FALLOC_FL_ZERO_RANGE are not supported
  374. on encrypted files and will fail with EOPNOTSUPP.
  375. - Online defragmentation of encrypted files is not supported. The
  376. EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail with
  377. EOPNOTSUPP.
  378. - The ext4 filesystem does not support data journaling with encrypted
  379. regular files. It will fall back to ordered data mode instead.
  380. - DAX (Direct Access) is not supported on encrypted files.
  381. - The st_size of an encrypted symlink will not necessarily give the
  382. length of the symlink target as required by POSIX. It will actually
  383. give the length of the ciphertext, which will be slightly longer
  384. than the plaintext due to NUL-padding and an extra 2-byte overhead.
  385. - The maximum length of an encrypted symlink is 2 bytes shorter than
  386. the maximum length of an unencrypted symlink. For example, on an
  387. EXT4 filesystem with a 4K block size, unencrypted symlinks can be up
  388. to 4095 bytes long, while encrypted symlinks can only be up to 4093
  389. bytes long (both lengths excluding the terminating null).
  390. Note that mmap *is* supported. This is possible because the pagecache
  391. for an encrypted file contains the plaintext, not the ciphertext.
  392. Without the key
  393. ---------------
  394. Some filesystem operations may be performed on encrypted regular
  395. files, directories, and symlinks even before their encryption key has
  396. been provided:
  397. - File metadata may be read, e.g. using stat().
  398. - Directories may be listed, in which case the filenames will be
  399. listed in an encoded form derived from their ciphertext. The
  400. current encoding algorithm is described in `Filename hashing and
  401. encoding`_. The algorithm is subject to change, but it is
  402. guaranteed that the presented filenames will be no longer than
  403. NAME_MAX bytes, will not contain the ``/`` or ``\0`` characters, and
  404. will uniquely identify directory entries.
  405. The ``.`` and ``..`` directory entries are special. They are always
  406. present and are not encrypted or encoded.
  407. - Files may be deleted. That is, nondirectory files may be deleted
  408. with unlink() as usual, and empty directories may be deleted with
  409. rmdir() as usual. Therefore, ``rm`` and ``rm -r`` will work as
  410. expected.
  411. - Symlink targets may be read and followed, but they will be presented
  412. in encrypted form, similar to filenames in directories. Hence, they
  413. are unlikely to point to anywhere useful.
  414. Without the key, regular files cannot be opened or truncated.
  415. Attempts to do so will fail with ENOKEY. This implies that any
  416. regular file operations that require a file descriptor, such as
  417. read(), write(), mmap(), fallocate(), and ioctl(), are also forbidden.
  418. Also without the key, files of any type (including directories) cannot
  419. be created or linked into an encrypted directory, nor can a name in an
  420. encrypted directory be the source or target of a rename, nor can an
  421. O_TMPFILE temporary file be created in an encrypted directory. All
  422. such operations will fail with ENOKEY.
  423. It is not currently possible to backup and restore encrypted files
  424. without the encryption key. This would require special APIs which
  425. have not yet been implemented.
  426. Encryption policy enforcement
  427. =============================
  428. After an encryption policy has been set on a directory, all regular
  429. files, directories, and symbolic links created in that directory
  430. (recursively) will inherit that encryption policy. Special files ---
  431. that is, named pipes, device nodes, and UNIX domain sockets --- will
  432. not be encrypted.
  433. Except for those special files, it is forbidden to have unencrypted
  434. files, or files encrypted with a different encryption policy, in an
  435. encrypted directory tree. Attempts to link or rename such a file into
  436. an encrypted directory will fail with EPERM. This is also enforced
  437. during ->lookup() to provide limited protection against offline
  438. attacks that try to disable or downgrade encryption in known locations
  439. where applications may later write sensitive data. It is recommended
  440. that systems implementing a form of "verified boot" take advantage of
  441. this by validating all top-level encryption policies prior to access.
  442. Implementation details
  443. ======================
  444. Encryption context
  445. ------------------
  446. An encryption policy is represented on-disk by a :c:type:`struct
  447. fscrypt_context`. It is up to individual filesystems to decide where
  448. to store it, but normally it would be stored in a hidden extended
  449. attribute. It should *not* be exposed by the xattr-related system
  450. calls such as getxattr() and setxattr() because of the special
  451. semantics of the encryption xattr. (In particular, there would be
  452. much confusion if an encryption policy were to be added to or removed
  453. from anything other than an empty directory.) The struct is defined
  454. as follows::
  455. #define FS_KEY_DESCRIPTOR_SIZE 8
  456. #define FS_KEY_DERIVATION_NONCE_SIZE 16
  457. struct fscrypt_context {
  458. u8 format;
  459. u8 contents_encryption_mode;
  460. u8 filenames_encryption_mode;
  461. u8 flags;
  462. u8 master_key_descriptor[FS_KEY_DESCRIPTOR_SIZE];
  463. u8 nonce[FS_KEY_DERIVATION_NONCE_SIZE];
  464. };
  465. Note that :c:type:`struct fscrypt_context` contains the same
  466. information as :c:type:`struct fscrypt_policy` (see `Setting an
  467. encryption policy`_), except that :c:type:`struct fscrypt_context`
  468. also contains a nonce. The nonce is randomly generated by the kernel
  469. and is used to derive the inode's encryption key as described in
  470. `Per-file keys`_.
  471. Data path changes
  472. -----------------
  473. For the read path (->readpage()) of regular files, filesystems can
  474. read the ciphertext into the page cache and decrypt it in-place. The
  475. page lock must be held until decryption has finished, to prevent the
  476. page from becoming visible to userspace prematurely.
  477. For the write path (->writepage()) of regular files, filesystems
  478. cannot encrypt data in-place in the page cache, since the cached
  479. plaintext must be preserved. Instead, filesystems must encrypt into a
  480. temporary buffer or "bounce page", then write out the temporary
  481. buffer. Some filesystems, such as UBIFS, already use temporary
  482. buffers regardless of encryption. Other filesystems, such as ext4 and
  483. F2FS, have to allocate bounce pages specially for encryption.
  484. Filename hashing and encoding
  485. -----------------------------
  486. Modern filesystems accelerate directory lookups by using indexed
  487. directories. An indexed directory is organized as a tree keyed by
  488. filename hashes. When a ->lookup() is requested, the filesystem
  489. normally hashes the filename being looked up so that it can quickly
  490. find the corresponding directory entry, if any.
  491. With encryption, lookups must be supported and efficient both with and
  492. without the encryption key. Clearly, it would not work to hash the
  493. plaintext filenames, since the plaintext filenames are unavailable
  494. without the key. (Hashing the plaintext filenames would also make it
  495. impossible for the filesystem's fsck tool to optimize encrypted
  496. directories.) Instead, filesystems hash the ciphertext filenames,
  497. i.e. the bytes actually stored on-disk in the directory entries. When
  498. asked to do a ->lookup() with the key, the filesystem just encrypts
  499. the user-supplied name to get the ciphertext.
  500. Lookups without the key are more complicated. The raw ciphertext may
  501. contain the ``\0`` and ``/`` characters, which are illegal in
  502. filenames. Therefore, readdir() must base64-encode the ciphertext for
  503. presentation. For most filenames, this works fine; on ->lookup(), the
  504. filesystem just base64-decodes the user-supplied name to get back to
  505. the raw ciphertext.
  506. However, for very long filenames, base64 encoding would cause the
  507. filename length to exceed NAME_MAX. To prevent this, readdir()
  508. actually presents long filenames in an abbreviated form which encodes
  509. a strong "hash" of the ciphertext filename, along with the optional
  510. filesystem-specific hash(es) needed for directory lookups. This
  511. allows the filesystem to still, with a high degree of confidence, map
  512. the filename given in ->lookup() back to a particular directory entry
  513. that was previously listed by readdir(). See :c:type:`struct
  514. fscrypt_digested_name` in the source for more details.
  515. Note that the precise way that filenames are presented to userspace
  516. without the key is subject to change in the future. It is only meant
  517. as a way to temporarily present valid filenames so that commands like
  518. ``rm -r`` work as expected on encrypted directories.