1.. SPDX-License-Identifier: GPL-2.0
2
3.. _fsverity:
4
5=======================================================
6fs-verity: read-only file-based authenticity protection
7=======================================================
8
9Introduction
10============
11
12fs-verity (``fs/verity/``) is a support layer that filesystems can
13hook into to support transparent integrity and authenticity protection
14of read-only files.  Currently, it is supported by the ext4, f2fs, and
15btrfs filesystems.  Like fscrypt, not too much filesystem-specific
16code is needed to support fs-verity.
17
18fs-verity is similar to `dm-verity
19<https://www.kernel.org/doc/Documentation/device-mapper/verity.txt>`_
20but works on files rather than block devices.  On regular files on
21filesystems supporting fs-verity, userspace can execute an ioctl that
22causes the filesystem to build a Merkle tree for the file and persist
23it to a filesystem-specific location associated with the file.
24
25After this, the file is made readonly, and all reads from the file are
26automatically verified against the file's Merkle tree.  Reads of any
27corrupted data, including mmap reads, will fail.
28
29Userspace can use another ioctl to retrieve the root hash (actually
30the "fs-verity file digest", which is a hash that includes the Merkle
31tree root hash) that fs-verity is enforcing for the file.  This ioctl
32executes in constant time, regardless of the file size.
33
34fs-verity is essentially a way to hash a file in constant time,
35subject to the caveat that reads which would violate the hash will
36fail at runtime.
37
38Use cases
39=========
40
41By itself, fs-verity only provides integrity protection, i.e.
42detection of accidental (non-malicious) corruption.
43
44However, because fs-verity makes retrieving the file hash extremely
45efficient, it's primarily meant to be used as a tool to support
46authentication (detection of malicious modifications) or auditing
47(logging file hashes before use).
48
49A standard file hash could be used instead of fs-verity.  However,
50this is inefficient if the file is large and only a small portion may
51be accessed.  This is often the case for Android application package
52(APK) files, for example.  These typically contain many translations,
53classes, and other resources that are infrequently or even never
54accessed on a particular device.  It would be slow and wasteful to
55read and hash the entire file before starting the application.
56
57Unlike an ahead-of-time hash, fs-verity also re-verifies data each
58time it's paged in.  This ensures that malicious disk firmware can't
59undetectably change the contents of the file at runtime.
60
61fs-verity does not replace or obsolete dm-verity.  dm-verity should
62still be used on read-only filesystems.  fs-verity is for files that
63must live on a read-write filesystem because they are independently
64updated and potentially user-installed, so dm-verity cannot be used.
65
66fs-verity does not mandate a particular scheme for authenticating its
67file hashes.  (Similarly, dm-verity does not mandate a particular
68scheme for authenticating its block device root hashes.)  Options for
69authenticating fs-verity file hashes include:
70
71- Trusted userspace code.  Often, the userspace code that accesses
72  files can be trusted to authenticate them.  Consider e.g. an
73  application that wants to authenticate data files before using them,
74  or an application loader that is part of the operating system (which
75  is already authenticated in a different way, such as by being loaded
76  from a read-only partition that uses dm-verity) and that wants to
77  authenticate applications before loading them.  In these cases, this
78  trusted userspace code can authenticate a file's contents by
79  retrieving its fs-verity digest using `FS_IOC_MEASURE_VERITY`_, then
80  verifying a signature of it using any userspace cryptographic
81  library that supports digital signatures.
82
83- Integrity Measurement Architecture (IMA).  IMA supports fs-verity
84  file digests as an alternative to its traditional full file digests.
85  "IMA appraisal" enforces that files contain a valid, matching
86  signature in their "security.ima" extended attribute, as controlled
87  by the IMA policy.  For more information, see the IMA documentation.
88
89- Trusted userspace code in combination with `Built-in signature
90  verification`_.  This approach should be used only with great care.
91
92User API
93========
94
95FS_IOC_ENABLE_VERITY
96--------------------
97
98The FS_IOC_ENABLE_VERITY ioctl enables fs-verity on a file.  It takes
99in a pointer to a struct fsverity_enable_arg, defined as
100follows::
101
102    struct fsverity_enable_arg {
103            __u32 version;
104            __u32 hash_algorithm;
105            __u32 block_size;
106            __u32 salt_size;
107            __u64 salt_ptr;
108            __u32 sig_size;
109            __u32 __reserved1;
110            __u64 sig_ptr;
111            __u64 __reserved2[11];
112    };
113
114This structure contains the parameters of the Merkle tree to build for
115the file.  It must be initialized as follows:
116
117- ``version`` must be 1.
118- ``hash_algorithm`` must be the identifier for the hash algorithm to
119  use for the Merkle tree, such as FS_VERITY_HASH_ALG_SHA256.  See
120  ``include/uapi/linux/fsverity.h`` for the list of possible values.
121- ``block_size`` is the Merkle tree block size, in bytes.  In Linux
122  v6.3 and later, this can be any power of 2 between (inclusively)
123  1024 and the minimum of the system page size and the filesystem
124  block size.  In earlier versions, the page size was the only allowed
125  value.
126- ``salt_size`` is the size of the salt in bytes, or 0 if no salt is
127  provided.  The salt is a value that is prepended to every hashed
128  block; it can be used to personalize the hashing for a particular
129  file or device.  Currently the maximum salt size is 32 bytes.
130- ``salt_ptr`` is the pointer to the salt, or NULL if no salt is
131  provided.
132- ``sig_size`` is the size of the builtin signature in bytes, or 0 if no
133  builtin signature is provided.  Currently the builtin signature is
134  (somewhat arbitrarily) limited to 16128 bytes.
135- ``sig_ptr``  is the pointer to the builtin signature, or NULL if no
136  builtin signature is provided.  A builtin signature is only needed
137  if the `Built-in signature verification`_ feature is being used.  It
138  is not needed for IMA appraisal, and it is not needed if the file
139  signature is being handled entirely in userspace.
140- All reserved fields must be zeroed.
141
142FS_IOC_ENABLE_VERITY causes the filesystem to build a Merkle tree for
143the file and persist it to a filesystem-specific location associated
144with the file, then mark the file as a verity file.  This ioctl may
145take a long time to execute on large files, and it is interruptible by
146fatal signals.
147
148FS_IOC_ENABLE_VERITY checks for write access to the inode.  However,
149it must be executed on an O_RDONLY file descriptor and no processes
150can have the file open for writing.  Attempts to open the file for
151writing while this ioctl is executing will fail with ETXTBSY.  (This
152is necessary to guarantee that no writable file descriptors will exist
153after verity is enabled, and to guarantee that the file's contents are
154stable while the Merkle tree is being built over it.)
155
156On success, FS_IOC_ENABLE_VERITY returns 0, and the file becomes a
157verity file.  On failure (including the case of interruption by a
158fatal signal), no changes are made to the file.
159
160FS_IOC_ENABLE_VERITY can fail with the following errors:
161
162- ``EACCES``: the process does not have write access to the file
163- ``EBADMSG``: the builtin signature is malformed
164- ``EBUSY``: this ioctl is already running on the file
165- ``EEXIST``: the file already has verity enabled
166- ``EFAULT``: the caller provided inaccessible memory
167- ``EFBIG``: the file is too large to enable verity on
168- ``EINTR``: the operation was interrupted by a fatal signal
169- ``EINVAL``: unsupported version, hash algorithm, or block size; or
170  reserved bits are set; or the file descriptor refers to neither a
171  regular file nor a directory.
172- ``EISDIR``: the file descriptor refers to a directory
173- ``EKEYREJECTED``: the builtin signature doesn't match the file
174- ``EMSGSIZE``: the salt or builtin signature is too long
175- ``ENOKEY``: the ".fs-verity" keyring doesn't contain the certificate
176  needed to verify the builtin signature
177- ``ENOPKG``: fs-verity recognizes the hash algorithm, but it's not
178  available in the kernel's crypto API as currently configured (e.g.
179  for SHA-512, missing CONFIG_CRYPTO_SHA512).
180- ``ENOTTY``: this type of filesystem does not implement fs-verity
181- ``EOPNOTSUPP``: the kernel was not configured with fs-verity
182  support; or the filesystem superblock has not had the 'verity'
183  feature enabled on it; or the filesystem does not support fs-verity
184  on this file.  (See `Filesystem support`_.)
185- ``EPERM``: the file is append-only; or, a builtin signature is
186  required and one was not provided.
187- ``EROFS``: the filesystem is read-only
188- ``ETXTBSY``: someone has the file open for writing.  This can be the
189  caller's file descriptor, another open file descriptor, or the file
190  reference held by a writable memory map.
191
192FS_IOC_MEASURE_VERITY
193---------------------
194
195The FS_IOC_MEASURE_VERITY ioctl retrieves the digest of a verity file.
196The fs-verity file digest is a cryptographic digest that identifies
197the file contents that are being enforced on reads; it is computed via
198a Merkle tree and is different from a traditional full-file digest.
199
200This ioctl takes in a pointer to a variable-length structure::
201
202    struct fsverity_digest {
203            __u16 digest_algorithm;
204            __u16 digest_size; /* input/output */
205            __u8 digest[];
206    };
207
208``digest_size`` is an input/output field.  On input, it must be
209initialized to the number of bytes allocated for the variable-length
210``digest`` field.
211
212On success, 0 is returned and the kernel fills in the structure as
213follows:
214
215- ``digest_algorithm`` will be the hash algorithm used for the file
216  digest.  It will match ``fsverity_enable_arg::hash_algorithm``.
217- ``digest_size`` will be the size of the digest in bytes, e.g. 32
218  for SHA-256.  (This can be redundant with ``digest_algorithm``.)
219- ``digest`` will be the actual bytes of the digest.
220
221FS_IOC_MEASURE_VERITY is guaranteed to execute in constant time,
222regardless of the size of the file.
223
224FS_IOC_MEASURE_VERITY can fail with the following errors:
225
226- ``EFAULT``: the caller provided inaccessible memory
227- ``ENODATA``: the file is not a verity file
228- ``ENOTTY``: this type of filesystem does not implement fs-verity
229- ``EOPNOTSUPP``: the kernel was not configured with fs-verity
230  support, or the filesystem superblock has not had the 'verity'
231  feature enabled on it.  (See `Filesystem support`_.)
232- ``EOVERFLOW``: the digest is longer than the specified
233  ``digest_size`` bytes.  Try providing a larger buffer.
234
235FS_IOC_READ_VERITY_METADATA
236---------------------------
237
238The FS_IOC_READ_VERITY_METADATA ioctl reads verity metadata from a
239verity file.  This ioctl is available since Linux v5.12.
240
241This ioctl allows writing a server program that takes a verity file
242and serves it to a client program, such that the client can do its own
243fs-verity compatible verification of the file.  This only makes sense
244if the client doesn't trust the server and if the server needs to
245provide the storage for the client.
246
247This is a fairly specialized use case, and most fs-verity users won't
248need this ioctl.
249
250This ioctl takes in a pointer to the following structure::
251
252   #define FS_VERITY_METADATA_TYPE_MERKLE_TREE     1
253   #define FS_VERITY_METADATA_TYPE_DESCRIPTOR      2
254   #define FS_VERITY_METADATA_TYPE_SIGNATURE       3
255
256   struct fsverity_read_metadata_arg {
257           __u64 metadata_type;
258           __u64 offset;
259           __u64 length;
260           __u64 buf_ptr;
261           __u64 __reserved;
262   };
263
264``metadata_type`` specifies the type of metadata to read:
265
266- ``FS_VERITY_METADATA_TYPE_MERKLE_TREE`` reads the blocks of the
267  Merkle tree.  The blocks are returned in order from the root level
268  to the leaf level.  Within each level, the blocks are returned in
269  the same order that their hashes are themselves hashed.
270  See `Merkle tree`_ for more information.
271
272- ``FS_VERITY_METADATA_TYPE_DESCRIPTOR`` reads the fs-verity
273  descriptor.  See `fs-verity descriptor`_.
274
275- ``FS_VERITY_METADATA_TYPE_SIGNATURE`` reads the builtin signature
276  which was passed to FS_IOC_ENABLE_VERITY, if any.  See `Built-in
277  signature verification`_.
278
279The semantics are similar to those of ``pread()``.  ``offset``
280specifies the offset in bytes into the metadata item to read from, and
281``length`` specifies the maximum number of bytes to read from the
282metadata item.  ``buf_ptr`` is the pointer to the buffer to read into,
283cast to a 64-bit integer.  ``__reserved`` must be 0.  On success, the
284number of bytes read is returned.  0 is returned at the end of the
285metadata item.  The returned length may be less than ``length``, for
286example if the ioctl is interrupted.
287
288The metadata returned by FS_IOC_READ_VERITY_METADATA isn't guaranteed
289to be authenticated against the file digest that would be returned by
290`FS_IOC_MEASURE_VERITY`_, as the metadata is expected to be used to
291implement fs-verity compatible verification anyway (though absent a
292malicious disk, the metadata will indeed match).  E.g. to implement
293this ioctl, the filesystem is allowed to just read the Merkle tree
294blocks from disk without actually verifying the path to the root node.
295
296FS_IOC_READ_VERITY_METADATA can fail with the following errors:
297
298- ``EFAULT``: the caller provided inaccessible memory
299- ``EINTR``: the ioctl was interrupted before any data was read
300- ``EINVAL``: reserved fields were set, or ``offset + length``
301  overflowed
302- ``ENODATA``: the file is not a verity file, or
303  FS_VERITY_METADATA_TYPE_SIGNATURE was requested but the file doesn't
304  have a builtin signature
305- ``ENOTTY``: this type of filesystem does not implement fs-verity, or
306  this ioctl is not yet implemented on it
307- ``EOPNOTSUPP``: the kernel was not configured with fs-verity
308  support, or the filesystem superblock has not had the 'verity'
309  feature enabled on it.  (See `Filesystem support`_.)
310
311FS_IOC_GETFLAGS
312---------------
313
314The existing ioctl FS_IOC_GETFLAGS (which isn't specific to fs-verity)
315can also be used to check whether a file has fs-verity enabled or not.
316To do so, check for FS_VERITY_FL (0x00100000) in the returned flags.
317
318The verity flag is not settable via FS_IOC_SETFLAGS.  You must use
319FS_IOC_ENABLE_VERITY instead, since parameters must be provided.
320
321statx
322-----
323
324Since Linux v5.5, the statx() system call sets STATX_ATTR_VERITY if
325the file has fs-verity enabled.  This can perform better than
326FS_IOC_GETFLAGS and FS_IOC_MEASURE_VERITY because it doesn't require
327opening the file, and opening verity files can be expensive.
328
329Accessing verity files
330======================
331
332Applications can transparently access a verity file just like a
333non-verity one, with the following exceptions:
334
335- Verity files are readonly.  They cannot be opened for writing or
336  truncate()d, even if the file mode bits allow it.  Attempts to do
337  one of these things will fail with EPERM.  However, changes to
338  metadata such as owner, mode, timestamps, and xattrs are still
339  allowed, since these are not measured by fs-verity.  Verity files
340  can also still be renamed, deleted, and linked to.
341
342- Direct I/O is not supported on verity files.  Attempts to use direct
343  I/O on such files will fall back to buffered I/O.
344
345- DAX (Direct Access) is not supported on verity files, because this
346  would circumvent the data verification.
347
348- Reads of data that doesn't match the verity Merkle tree will fail
349  with EIO (for read()) or SIGBUS (for mmap() reads).
350
351- If the sysctl "fs.verity.require_signatures" is set to 1 and the
352  file is not signed by a key in the ".fs-verity" keyring, then
353  opening the file will fail.  See `Built-in signature verification`_.
354
355Direct access to the Merkle tree is not supported.  Therefore, if a
356verity file is copied, or is backed up and restored, then it will lose
357its "verity"-ness.  fs-verity is primarily meant for files like
358executables that are managed by a package manager.
359
360File digest computation
361=======================
362
363This section describes how fs-verity hashes the file contents using a
364Merkle tree to produce the digest which cryptographically identifies
365the file contents.  This algorithm is the same for all filesystems
366that support fs-verity.
367
368Userspace only needs to be aware of this algorithm if it needs to
369compute fs-verity file digests itself, e.g. in order to sign files.
370
371.. _fsverity_merkle_tree:
372
373Merkle tree
374-----------
375
376The file contents is divided into blocks, where the block size is
377configurable but is usually 4096 bytes.  The end of the last block is
378zero-padded if needed.  Each block is then hashed, producing the first
379level of hashes.  Then, the hashes in this first level are grouped
380into 'blocksize'-byte blocks (zero-padding the ends as needed) and
381these blocks are hashed, producing the second level of hashes.  This
382proceeds up the tree until only a single block remains.  The hash of
383this block is the "Merkle tree root hash".
384
385If the file fits in one block and is nonempty, then the "Merkle tree
386root hash" is simply the hash of the single data block.  If the file
387is empty, then the "Merkle tree root hash" is all zeroes.
388
389The "blocks" here are not necessarily the same as "filesystem blocks".
390
391If a salt was specified, then it's zero-padded to the closest multiple
392of the input size of the hash algorithm's compression function, e.g.
39364 bytes for SHA-256 or 128 bytes for SHA-512.  The padded salt is
394prepended to every data or Merkle tree block that is hashed.
395
396The purpose of the block padding is to cause every hash to be taken
397over the same amount of data, which simplifies the implementation and
398keeps open more possibilities for hardware acceleration.  The purpose
399of the salt padding is to make the salting "free" when the salted hash
400state is precomputed, then imported for each hash.
401
402Example: in the recommended configuration of SHA-256 and 4K blocks,
403128 hash values fit in each block.  Thus, each level of the Merkle
404tree is approximately 128 times smaller than the previous, and for
405large files the Merkle tree's size converges to approximately 1/127 of
406the original file size.  However, for small files, the padding is
407significant, making the space overhead proportionally more.
408
409.. _fsverity_descriptor:
410
411fs-verity descriptor
412--------------------
413
414By itself, the Merkle tree root hash is ambiguous.  For example, it
415can't a distinguish a large file from a small second file whose data
416is exactly the top-level hash block of the first file.  Ambiguities
417also arise from the convention of padding to the next block boundary.
418
419To solve this problem, the fs-verity file digest is actually computed
420as a hash of the following structure, which contains the Merkle tree
421root hash as well as other fields such as the file size::
422
423    struct fsverity_descriptor {
424            __u8 version;           /* must be 1 */
425            __u8 hash_algorithm;    /* Merkle tree hash algorithm */
426            __u8 log_blocksize;     /* log2 of size of data and tree blocks */
427            __u8 salt_size;         /* size of salt in bytes; 0 if none */
428            __le32 __reserved_0x04; /* must be 0 */
429            __le64 data_size;       /* size of file the Merkle tree is built over */
430            __u8 root_hash[64];     /* Merkle tree root hash */
431            __u8 salt[32];          /* salt prepended to each hashed block */
432            __u8 __reserved[144];   /* must be 0's */
433    };
434
435Built-in signature verification
436===============================
437
438CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y adds supports for in-kernel
439verification of fs-verity builtin signatures.
440
441**IMPORTANT**!  Please take great care before using this feature.
442It is not the only way to do signatures with fs-verity, and the
443alternatives (such as userspace signature verification, and IMA
444appraisal) can be much better.  It's also easy to fall into a trap
445of thinking this feature solves more problems than it actually does.
446
447Enabling this option adds the following:
448
4491. At boot time, the kernel creates a keyring named ".fs-verity".  The
450   root user can add trusted X.509 certificates to this keyring using
451   the add_key() system call.
452
4532. `FS_IOC_ENABLE_VERITY`_ accepts a pointer to a PKCS#7 formatted
454   detached signature in DER format of the file's fs-verity digest.
455   On success, the ioctl persists the signature alongside the Merkle
456   tree.  Then, any time the file is opened, the kernel verifies the
457   file's actual digest against this signature, using the certificates
458   in the ".fs-verity" keyring.
459
4603. A new sysctl "fs.verity.require_signatures" is made available.
461   When set to 1, the kernel requires that all verity files have a
462   correctly signed digest as described in (2).
463
464The data that the signature as described in (2) must be a signature of
465is the fs-verity file digest in the following format::
466
467    struct fsverity_formatted_digest {
468            char magic[8];                  /* must be "FSVerity" */
469            __le16 digest_algorithm;
470            __le16 digest_size;
471            __u8 digest[];
472    };
473
474That's it.  It should be emphasized again that fs-verity builtin
475signatures are not the only way to do signatures with fs-verity.  See
476`Use cases`_ for an overview of ways in which fs-verity can be used.
477fs-verity builtin signatures have some major limitations that should
478be carefully considered before using them:
479
480- Builtin signature verification does *not* make the kernel enforce
481  that any files actually have fs-verity enabled.  Thus, it is not a
482  complete authentication policy.  Currently, if it is used, the only
483  way to complete the authentication policy is for trusted userspace
484  code to explicitly check whether files have fs-verity enabled with a
485  signature before they are accessed.  (With
486  fs.verity.require_signatures=1, just checking whether fs-verity is
487  enabled suffices.)  But, in this case the trusted userspace code
488  could just store the signature alongside the file and verify it
489  itself using a cryptographic library, instead of using this feature.
490
491- A file's builtin signature can only be set at the same time that
492  fs-verity is being enabled on the file.  Changing or deleting the
493  builtin signature later requires re-creating the file.
494
495- Builtin signature verification uses the same set of public keys for
496  all fs-verity enabled files on the system.  Different keys cannot be
497  trusted for different files; each key is all or nothing.
498
499- The sysctl fs.verity.require_signatures applies system-wide.
500  Setting it to 1 only works when all users of fs-verity on the system
501  agree that it should be set to 1.  This limitation can prevent
502  fs-verity from being used in cases where it would be helpful.
503
504- Builtin signature verification can only use signature algorithms
505  that are supported by the kernel.  For example, the kernel does not
506  yet support Ed25519, even though this is often the signature
507  algorithm that is recommended for new cryptographic designs.
508
509- fs-verity builtin signatures are in PKCS#7 format, and the public
510  keys are in X.509 format.  These formats are commonly used,
511  including by some other kernel features (which is why the fs-verity
512  builtin signatures use them), and are very feature rich.
513  Unfortunately, history has shown that code that parses and handles
514  these formats (which are from the 1990s and are based on ASN.1)
515  often has vulnerabilities as a result of their complexity.  This
516  complexity is not inherent to the cryptography itself.
517
518  fs-verity users who do not need advanced features of X.509 and
519  PKCS#7 should strongly consider using simpler formats, such as plain
520  Ed25519 keys and signatures, and verifying signatures in userspace.
521
522  fs-verity users who choose to use X.509 and PKCS#7 anyway should
523  still consider that verifying those signatures in userspace is more
524  flexible (for other reasons mentioned earlier in this document) and
525  eliminates the need to enable CONFIG_FS_VERITY_BUILTIN_SIGNATURES
526  and its associated increase in kernel attack surface.  In some cases
527  it can even be necessary, since advanced X.509 and PKCS#7 features
528  do not always work as intended with the kernel.  For example, the
529  kernel does not check X.509 certificate validity times.
530
531  Note: IMA appraisal, which supports fs-verity, does not use PKCS#7
532  for its signatures, so it partially avoids the issues discussed
533  here.  IMA appraisal does use X.509.
534
535Filesystem support
536==================
537
538fs-verity is supported by several filesystems, described below.  The
539CONFIG_FS_VERITY kconfig option must be enabled to use fs-verity on
540any of these filesystems.
541
542``include/linux/fsverity.h`` declares the interface between the
543``fs/verity/`` support layer and filesystems.  Briefly, filesystems
544must provide an ``fsverity_operations`` structure that provides
545methods to read and write the verity metadata to a filesystem-specific
546location, including the Merkle tree blocks and
547``fsverity_descriptor``.  Filesystems must also call functions in
548``fs/verity/`` at certain times, such as when a file is opened or when
549pages have been read into the pagecache.  (See `Verifying data`_.)
550
551ext4
552----
553
554ext4 supports fs-verity since Linux v5.4 and e2fsprogs v1.45.2.
555
556To create verity files on an ext4 filesystem, the filesystem must have
557been formatted with ``-O verity`` or had ``tune2fs -O verity`` run on
558it.  "verity" is an RO_COMPAT filesystem feature, so once set, old
559kernels will only be able to mount the filesystem readonly, and old
560versions of e2fsck will be unable to check the filesystem.
561
562Originally, an ext4 filesystem with the "verity" feature could only be
563mounted when its block size was equal to the system page size
564(typically 4096 bytes).  In Linux v6.3, this limitation was removed.
565
566ext4 sets the EXT4_VERITY_FL on-disk inode flag on verity files.  It
567can only be set by `FS_IOC_ENABLE_VERITY`_, and it cannot be cleared.
568
569ext4 also supports encryption, which can be used simultaneously with
570fs-verity.  In this case, the plaintext data is verified rather than
571the ciphertext.  This is necessary in order to make the fs-verity file
572digest meaningful, since every file is encrypted differently.
573
574ext4 stores the verity metadata (Merkle tree and fsverity_descriptor)
575past the end of the file, starting at the first 64K boundary beyond
576i_size.  This approach works because (a) verity files are readonly,
577and (b) pages fully beyond i_size aren't visible to userspace but can
578be read/written internally by ext4 with only some relatively small
579changes to ext4.  This approach avoids having to depend on the
580EA_INODE feature and on rearchitecturing ext4's xattr support to
581support paging multi-gigabyte xattrs into memory, and to support
582encrypting xattrs.  Note that the verity metadata *must* be encrypted
583when the file is, since it contains hashes of the plaintext data.
584
585ext4 only allows verity on extent-based files.
586
587f2fs
588----
589
590f2fs supports fs-verity since Linux v5.4 and f2fs-tools v1.11.0.
591
592To create verity files on an f2fs filesystem, the filesystem must have
593been formatted with ``-O verity``.
594
595f2fs sets the FADVISE_VERITY_BIT on-disk inode flag on verity files.
596It can only be set by `FS_IOC_ENABLE_VERITY`_, and it cannot be
597cleared.
598
599Like ext4, f2fs stores the verity metadata (Merkle tree and
600fsverity_descriptor) past the end of the file, starting at the first
60164K boundary beyond i_size.  See explanation for ext4 above.
602Moreover, f2fs supports at most 4096 bytes of xattr entries per inode
603which usually wouldn't be enough for even a single Merkle tree block.
604
605f2fs doesn't support enabling verity on files that currently have
606atomic or volatile writes pending.
607
608btrfs
609-----
610
611btrfs supports fs-verity since Linux v5.15.  Verity-enabled inodes are
612marked with a RO_COMPAT inode flag, and the verity metadata is stored
613in separate btree items.
614
615Implementation details
616======================
617
618Verifying data
619--------------
620
621fs-verity ensures that all reads of a verity file's data are verified,
622regardless of which syscall is used to do the read (e.g. mmap(),
623read(), pread()) and regardless of whether it's the first read or a
624later read (unless the later read can return cached data that was
625already verified).  Below, we describe how filesystems implement this.
626
627Pagecache
628~~~~~~~~~
629
630For filesystems using Linux's pagecache, the ``->read_folio()`` and
631``->readahead()`` methods must be modified to verify folios before
632they are marked Uptodate.  Merely hooking ``->read_iter()`` would be
633insufficient, since ``->read_iter()`` is not used for memory maps.
634
635Therefore, fs/verity/ provides the function fsverity_verify_blocks()
636which verifies data that has been read into the pagecache of a verity
637inode.  The containing folio must still be locked and not Uptodate, so
638it's not yet readable by userspace.  As needed to do the verification,
639fsverity_verify_blocks() will call back into the filesystem to read
640hash blocks via fsverity_operations::read_merkle_tree_page().
641
642fsverity_verify_blocks() returns false if verification failed; in this
643case, the filesystem must not set the folio Uptodate.  Following this,
644as per the usual Linux pagecache behavior, attempts by userspace to
645read() from the part of the file containing the folio will fail with
646EIO, and accesses to the folio within a memory map will raise SIGBUS.
647
648In principle, verifying a data block requires verifying the entire
649path in the Merkle tree from the data block to the root hash.
650However, for efficiency the filesystem may cache the hash blocks.
651Therefore, fsverity_verify_blocks() only ascends the tree reading hash
652blocks until an already-verified hash block is seen.  It then verifies
653the path to that block.
654
655This optimization, which is also used by dm-verity, results in
656excellent sequential read performance.  This is because usually (e.g.
657127 in 128 times for 4K blocks and SHA-256) the hash block from the
658bottom level of the tree will already be cached and checked from
659reading a previous data block.  However, random reads perform worse.
660
661Block device based filesystems
662~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
663
664Block device based filesystems (e.g. ext4 and f2fs) in Linux also use
665the pagecache, so the above subsection applies too.  However, they
666also usually read many data blocks from a file at once, grouped into a
667structure called a "bio".  To make it easier for these types of
668filesystems to support fs-verity, fs/verity/ also provides a function
669fsverity_verify_bio() which verifies all data blocks in a bio.
670
671ext4 and f2fs also support encryption.  If a verity file is also
672encrypted, the data must be decrypted before being verified.  To
673support this, these filesystems allocate a "post-read context" for
674each bio and store it in ``->bi_private``::
675
676    struct bio_post_read_ctx {
677           struct bio *bio;
678           struct work_struct work;
679           unsigned int cur_step;
680           unsigned int enabled_steps;
681    };
682
683``enabled_steps`` is a bitmask that specifies whether decryption,
684verity, or both is enabled.  After the bio completes, for each needed
685postprocessing step the filesystem enqueues the bio_post_read_ctx on a
686workqueue, and then the workqueue work does the decryption or
687verification.  Finally, folios where no decryption or verity error
688occurred are marked Uptodate, and the folios are unlocked.
689
690On many filesystems, files can contain holes.  Normally,
691``->readahead()`` simply zeroes hole blocks and considers the
692corresponding data to be up-to-date; no bios are issued.  To prevent
693this case from bypassing fs-verity, filesystems use
694fsverity_verify_blocks() to verify hole blocks.
695
696Filesystems also disable direct I/O on verity files, since otherwise
697direct I/O would bypass fs-verity.
698
699Userspace utility
700=================
701
702This document focuses on the kernel, but a userspace utility for
703fs-verity can be found at:
704
705	https://git.kernel.org/pub/scm/fs/fsverity/fsverity-utils.git
706
707See the README.md file in the fsverity-utils source tree for details,
708including examples of setting up fs-verity protected files.
709
710Tests
711=====
712
713To test fs-verity, use xfstests.  For example, using `kvm-xfstests
714<https://github.com/tytso/xfstests-bld/blob/master/Documentation/kvm-quickstart.md>`_::
715
716    kvm-xfstests -c ext4,f2fs,btrfs -g verity
717
718FAQ
719===
720
721This section answers frequently asked questions about fs-verity that
722weren't already directly answered in other parts of this document.
723
724:Q: Why isn't fs-verity part of IMA?
725:A: fs-verity and IMA (Integrity Measurement Architecture) have
726    different focuses.  fs-verity is a filesystem-level mechanism for
727    hashing individual files using a Merkle tree.  In contrast, IMA
728    specifies a system-wide policy that specifies which files are
729    hashed and what to do with those hashes, such as log them,
730    authenticate them, or add them to a measurement list.
731
732    IMA supports the fs-verity hashing mechanism as an alternative
733    to full file hashes, for those who want the performance and
734    security benefits of the Merkle tree based hash.  However, it
735    doesn't make sense to force all uses of fs-verity to be through
736    IMA.  fs-verity already meets many users' needs even as a
737    standalone filesystem feature, and it's testable like other
738    filesystem features e.g. with xfstests.
739
740:Q: Isn't fs-verity useless because the attacker can just modify the
741    hashes in the Merkle tree, which is stored on-disk?
742:A: To verify the authenticity of an fs-verity file you must verify
743    the authenticity of the "fs-verity file digest", which
744    incorporates the root hash of the Merkle tree.  See `Use cases`_.
745
746:Q: Isn't fs-verity useless because the attacker can just replace a
747    verity file with a non-verity one?
748:A: See `Use cases`_.  In the initial use case, it's really trusted
749    userspace code that authenticates the files; fs-verity is just a
750    tool to do this job efficiently and securely.  The trusted
751    userspace code will consider non-verity files to be inauthentic.
752
753:Q: Why does the Merkle tree need to be stored on-disk?  Couldn't you
754    store just the root hash?
755:A: If the Merkle tree wasn't stored on-disk, then you'd have to
756    compute the entire tree when the file is first accessed, even if
757    just one byte is being read.  This is a fundamental consequence of
758    how Merkle tree hashing works.  To verify a leaf node, you need to
759    verify the whole path to the root hash, including the root node
760    (the thing which the root hash is a hash of).  But if the root
761    node isn't stored on-disk, you have to compute it by hashing its
762    children, and so on until you've actually hashed the entire file.
763
764    That defeats most of the point of doing a Merkle tree-based hash,
765    since if you have to hash the whole file ahead of time anyway,
766    then you could simply do sha256(file) instead.  That would be much
767    simpler, and a bit faster too.
768
769    It's true that an in-memory Merkle tree could still provide the
770    advantage of verification on every read rather than just on the
771    first read.  However, it would be inefficient because every time a
772    hash page gets evicted (you can't pin the entire Merkle tree into
773    memory, since it may be very large), in order to restore it you
774    again need to hash everything below it in the tree.  This again
775    defeats most of the point of doing a Merkle tree-based hash, since
776    a single block read could trigger re-hashing gigabytes of data.
777
778:Q: But couldn't you store just the leaf nodes and compute the rest?
779:A: See previous answer; this really just moves up one level, since
780    one could alternatively interpret the data blocks as being the
781    leaf nodes of the Merkle tree.  It's true that the tree can be
782    computed much faster if the leaf level is stored rather than just
783    the data, but that's only because each level is less than 1% the
784    size of the level below (assuming the recommended settings of
785    SHA-256 and 4K blocks).  For the exact same reason, by storing
786    "just the leaf nodes" you'd already be storing over 99% of the
787    tree, so you might as well simply store the whole tree.
788
789:Q: Can the Merkle tree be built ahead of time, e.g. distributed as
790    part of a package that is installed to many computers?
791:A: This isn't currently supported.  It was part of the original
792    design, but was removed to simplify the kernel UAPI and because it
793    wasn't a critical use case.  Files are usually installed once and
794    used many times, and cryptographic hashing is somewhat fast on
795    most modern processors.
796
797:Q: Why doesn't fs-verity support writes?
798:A: Write support would be very difficult and would require a
799    completely different design, so it's well outside the scope of
800    fs-verity.  Write support would require:
801
802    - A way to maintain consistency between the data and hashes,
803      including all levels of hashes, since corruption after a crash
804      (especially of potentially the entire file!) is unacceptable.
805      The main options for solving this are data journalling,
806      copy-on-write, and log-structured volume.  But it's very hard to
807      retrofit existing filesystems with new consistency mechanisms.
808      Data journalling is available on ext4, but is very slow.
809
810    - Rebuilding the Merkle tree after every write, which would be
811      extremely inefficient.  Alternatively, a different authenticated
812      dictionary structure such as an "authenticated skiplist" could
813      be used.  However, this would be far more complex.
814
815    Compare it to dm-verity vs. dm-integrity.  dm-verity is very
816    simple: the kernel just verifies read-only data against a
817    read-only Merkle tree.  In contrast, dm-integrity supports writes
818    but is slow, is much more complex, and doesn't actually support
819    full-device authentication since it authenticates each sector
820    independently, i.e. there is no "root hash".  It doesn't really
821    make sense for the same device-mapper target to support these two
822    very different cases; the same applies to fs-verity.
823
824:Q: Since verity files are immutable, why isn't the immutable bit set?
825:A: The existing "immutable" bit (FS_IMMUTABLE_FL) already has a
826    specific set of semantics which not only make the file contents
827    read-only, but also prevent the file from being deleted, renamed,
828    linked to, or having its owner or mode changed.  These extra
829    properties are unwanted for fs-verity, so reusing the immutable
830    bit isn't appropriate.
831
832:Q: Why does the API use ioctls instead of setxattr() and getxattr()?
833:A: Abusing the xattr interface for basically arbitrary syscalls is
834    heavily frowned upon by most of the Linux filesystem developers.
835    An xattr should really just be an xattr on-disk, not an API to
836    e.g. magically trigger construction of a Merkle tree.
837
838:Q: Does fs-verity support remote filesystems?
839:A: So far all filesystems that have implemented fs-verity support are
840    local filesystems, but in principle any filesystem that can store
841    per-file verity metadata can support fs-verity, regardless of
842    whether it's local or remote.  Some filesystems may have fewer
843    options of where to store the verity metadata; one possibility is
844    to store it past the end of the file and "hide" it from userspace
845    by manipulating i_size.  The data verification functions provided
846    by ``fs/verity/`` also assume that the filesystem uses the Linux
847    pagecache, but both local and remote filesystems normally do so.
848
849:Q: Why is anything filesystem-specific at all?  Shouldn't fs-verity
850    be implemented entirely at the VFS level?
851:A: There are many reasons why this is not possible or would be very
852    difficult, including the following:
853
854    - To prevent bypassing verification, folios must not be marked
855      Uptodate until they've been verified.  Currently, each
856      filesystem is responsible for marking folios Uptodate via
857      ``->readahead()``.  Therefore, currently it's not possible for
858      the VFS to do the verification on its own.  Changing this would
859      require significant changes to the VFS and all filesystems.
860
861    - It would require defining a filesystem-independent way to store
862      the verity metadata.  Extended attributes don't work for this
863      because (a) the Merkle tree may be gigabytes, but many
864      filesystems assume that all xattrs fit into a single 4K
865      filesystem block, and (b) ext4 and f2fs encryption doesn't
866      encrypt xattrs, yet the Merkle tree *must* be encrypted when the
867      file contents are, because it stores hashes of the plaintext
868      file contents.
869
870      So the verity metadata would have to be stored in an actual
871      file.  Using a separate file would be very ugly, since the
872      metadata is fundamentally part of the file to be protected, and
873      it could cause problems where users could delete the real file
874      but not the metadata file or vice versa.  On the other hand,
875      having it be in the same file would break applications unless
876      filesystems' notion of i_size were divorced from the VFS's,
877      which would be complex and require changes to all filesystems.
878
879    - It's desirable that FS_IOC_ENABLE_VERITY uses the filesystem's
880      transaction mechanism so that either the file ends up with
881      verity enabled, or no changes were made.  Allowing intermediate
882      states to occur after a crash may cause problems.
883