From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:05
Hello,
This is a redesigned version of the fs-verity patchset, implementing
Ted's suggestion to build the Merkle tree in the kernel
(https://lore.kernel.org/linux-fsdevel/20190207031101.GA7387@mit.edu/).
This greatly simplifies the UAPI, since the verity metadata no longer
needs to be transferred to the kernel. Now to enable fs-verity on a
file, one simply calls FS_IOC_ENABLE_VERITY, passing it this structure:
struct fsverity_enable_arg {
__u32 version;
__u32 hash_algorithm;
__u32 block_size;
__u32 salt_size;
__u64 salt_ptr;
__u32 sig_size;
__u32 __reserved1;
__u64 sig_ptr;
__u64 __reserved2[11];
};
The filesystem then builds the file's Merkle tree and stores it in a
filesystem-specific location associated with the file. Afterwards,
FS_IOC_MEASURE_VERITY can be used to retrieve the file measurement
("root hash"). The way the file measurement is computed is also
effectively part of the API (it has to be), but it's logically
independent of where/how the filesystem stores the Merkle tree.
The API is fully documented in Documentation/filesystems/fsverity.rst,
along with other aspects of fs-verity. I also added an FAQ section that
answers frequently asked questions about fs-verity, e.g. why isn't it
all at the VFS level, why isn't it part of IMA, why does the Merkle tree
need to be stored on-disk, etc.
Overview
--------
This patchset implements fs-verity for ext4 and f2fs. fs-verity is
similar to dm-verity, but implemented on a per-file basis: a Merkle tree
is used to measure (hash) a read-only file's data as it is paged in.
ext4 and f2fs hide this Merkle tree beyond the end of the file, but
other filesystems can implement it differently if desired.
In general, fs-verity is intended for use on writable filesystems;
dm-verity is still recommended on read-only ones.
Similar to fscrypt, most of the code is in fs/verity/, and not too many
filesystem-specific changes are needed. The Merkle tree is built by the
filesystem when the FS_IOC_ENABLE_VERITY ioctl is executed.
fs-verity provides a file measurement (hash) in constant time and
verifies data on-demand. Thus, it is useful for efficiently verifying
the authenticity of large files of which only a small portion may be
accessed, such as Android application package (APK) files. It may also
be useful in "audit" use cases where file hashes are logged.
fs-verity can also provide better protection against malicious disks
than an ahead-of-time hash, since fs-verity re-verifies data each time
it's paged in. Note, however, that any authenticity guarantee is still
dependent on verification of the file measurement and other relevant
metadata in a way that makes sense for the overall system; fs-verity is
only a tool to help with this.
This patchset doesn't include IMA support for fs-verity file
measurements. This is planned and we'd like to collaborate with the IMA
maintainers. Although fs-verity can be used on its own without IMA,
fs-verity is primarily a lower level feature (think of it as a way of
hashing a file), so some users may still need IMA's policy mechanism.
However, an optional in-kernel signature verification mechanism within
fs-verity itself is also included.
This patchset is based on v5.2-rc3. It can also be found in git at tag
fsverity_2019-06-06 of:
https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux.git
fs-verity has a userspace utility:
https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/fsverity-utils.git
xfstests for fs-verity can be found at branch "fsverity" of:
https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/xfstests-dev.git
fs-verity is supported by f2fs-tools v1.11.0+ and e2fsprogs v1.45.2+.
Examples of setting up fs-verity protected files can be found in the
README.md file of fsverity-utils.
Other useful references include:
- Documentation/filesystems/fsverity.rst, added by the first patch.
- LWN coverage of v3 patchset: https://lwn.net/Articles/790185/
- LWN coverage of v2 patchset: https://lwn.net/Articles/775872/
- LWN coverage of v1 patchset: https://lwn.net/Articles/763729/
- Presentation at Linux Security Summit North America 2018:
- Slides: https://schd.ws/hosted_files/lssna18/af/fs-verity%20slide%20deck.pdf
- Video: https://www.youtube.com/watch?v=Aw5h6aBhu6M
(This corresponded to the v1 patchset; changes have been made since then.)
- LWN coverage of LSFMM 2018 discussion: https://lwn.net/Articles/752614/
Changed since v3:
- The FS_IOC_GETFLAGS ioctl now returns the verity flag.
- Fixed setting i_verity_info too early.
- Restored pagecache invalidation in FS_IOC_ENABLE_VERITY.
- Fixed truncation of fsverity_enable_arg::hash_algorithm.
- Reject empty files for both open and enable, not just enable.
- Added a couple more FAQ entries to the documentation.
- A few minor cleanups.
- Rebased onto v5.2-rc3.
Changed since v2:
- Large redesign: the Merkle tree is now built by
FS_IOC_ENABLE_VERITY, rather than being provided by userspace. The
fsverity_operations provide an interface for filesystems to read and
write the Merkle tree from/to a filesystem-specific location.
- Lot of refactoring, cleanups, and documentation improvements.
- Many simplifications, such as simplifying the fsverity_descriptor
format, dropping CRC-32 support, and limiting the salt size.
- ext4 and f2fs now store an xattr that gives the location of the
fsverity_descriptor, so loading it is more straightforward.
- f2fs no longer counts the verity metadata in the on-disk i_size,
making it consistent with ext4.
- Replaced the filesystem-specific fs-verity kconfig options with
CONFIG_FS_VERITY.
- Replaced the filesystem-specific verity bit checks with IS_VERITY().
Changed since v1:
- Added documentation file.
- Require write permission for FS_IOC_ENABLE_VERITY, rather than
CAP_SYS_ADMIN.
- Eliminated dependency on CONFIG_BLOCK and clarified that filesystems
can verify a page at a time rather than a bio at a time.
- Fixed conditions for verifying holes.
- ext4 now only allows fs-verity on extent-based files.
- Eliminated most of the assumptions that the verity metadata is
stored beyond EOF, in case filesystems want to do things
differently.
- Other cleanups.
Eric Biggers (16):
fs-verity: add a documentation file
fs-verity: add MAINTAINERS file entry
fs-verity: add UAPI header
fs: uapi: define verity bit for FS_IOC_GETFLAGS
fs-verity: add Kconfig and the helper functions for hashing
fs-verity: add inode and superblock fields
fs-verity: add the hook for file ->open()
fs-verity: add the hook for file ->setattr()
fs-verity: add data verification hooks for ->readpages()
fs-verity: implement FS_IOC_ENABLE_VERITY ioctl
fs-verity: implement FS_IOC_MEASURE_VERITY ioctl
fs-verity: add SHA-512 support
fs-verity: support builtin file signatures
ext4: add basic fs-verity support
ext4: add fs-verity read support
f2fs: add fs-verity support
Documentation/filesystems/fsverity.rst | 708 +++++++++++++++++++++++++
Documentation/filesystems/index.rst | 1 +
Documentation/ioctl/ioctl-number.txt | 1 +
MAINTAINERS | 12 +
fs/Kconfig | 2 +
fs/Makefile | 1 +
fs/ext4/Makefile | 1 +
fs/ext4/ext4.h | 23 +-
fs/ext4/file.c | 4 +
fs/ext4/inode.c | 48 +-
fs/ext4/ioctl.c | 12 +
fs/ext4/readpage.c | 207 +++++++-
fs/ext4/super.c | 18 +-
fs/ext4/sysfs.c | 6 +
fs/ext4/verity.c | 272 ++++++++++
fs/ext4/xattr.h | 2 +
fs/f2fs/Makefile | 1 +
fs/f2fs/data.c | 72 ++-
fs/f2fs/f2fs.h | 23 +-
fs/f2fs/file.c | 40 ++
fs/f2fs/inode.c | 5 +-
fs/f2fs/super.c | 3 +
fs/f2fs/sysfs.c | 11 +
fs/f2fs/verity.c | 224 ++++++++
fs/f2fs/xattr.h | 2 +
fs/verity/Kconfig | 55 ++
fs/verity/Makefile | 10 +
fs/verity/enable.c | 353 ++++++++++++
fs/verity/fsverity_private.h | 188 +++++++
fs/verity/hash_algs.c | 279 ++++++++++
fs/verity/init.c | 61 +++
fs/verity/measure.c | 57 ++
fs/verity/open.c | 363 +++++++++++++
fs/verity/signature.c | 207 ++++++++
fs/verity/verify.c | 281 ++++++++++
include/linux/fs.h | 11 +
include/linux/fsverity.h | 209 ++++++++
include/uapi/linux/fs.h | 1 +
include/uapi/linux/fsverity.h | 40 ++
39 files changed, 3755 insertions(+), 59 deletions(-)
create mode 100644 Documentation/filesystems/fsverity.rst
create mode 100644 fs/ext4/verity.c
create mode 100644 fs/f2fs/verity.c
create mode 100644 fs/verity/Kconfig
create mode 100644 fs/verity/Makefile
create mode 100644 fs/verity/enable.c
create mode 100644 fs/verity/fsverity_private.h
create mode 100644 fs/verity/hash_algs.c
create mode 100644 fs/verity/init.c
create mode 100644 fs/verity/measure.c
create mode 100644 fs/verity/open.c
create mode 100644 fs/verity/signature.c
create mode 100644 fs/verity/verify.c
create mode 100644 include/linux/fsverity.h
create mode 100644 include/uapi/linux/fsverity.h
--
2.22.0.rc1.311.g5d7573a151-goog
@@ -0,0 +1,708 @@+=======================================================+fs-verity: read-only file-based authenticity protection+=======================================================++Introduction+============++fs-verity (``fs/verity/``) is a support layer that filesystems can+hook into to support transparent integrity and authenticity protection+of read-only files. Currently, it is supported by the ext4 and f2fs+filesystems. Like fscrypt, not too much filesystem-specific code is+needed to support fs-verity.++fs-verity is similar to `dm-verity+<https://www.kernel.org/doc/Documentation/device-mapper/verity.txt>`_+but works on files rather than block devices. On regular files on+filesystems supporting fs-verity, userspace can execute an ioctl that+causes the filesystem to build a Merkle tree for the file and persist+it to a filesystem-specific location associated with the file.++After this, the file is made readonly, and all reads from the file are+automatically verified against the file's Merkle tree. Reads of any+corrupted data, including mmap reads, will fail.++Userspace can use another ioctl to retrieve the root hash (actually+the "file measurement", which is a hash that includes the root hash)+that fs-verity is enforcing for the file. This ioctl executes in+constant time, regardless of the file size.++fs-verity is essentially a way to hash a file in constant time,+subject to the caveat that reads which would violate the hash will+fail at runtime.++Use cases+=========++By itself, the base fs-verity feature only provides integrity+protection, i.e. detection of accidental (non-malicious) corruption.++However, because fs-verity makes retrieving the file hash extremely+efficient, it's primarily meant to be used as a tool to support+authentication (detection of malicious modifications) or auditing+(logging file hashes before use).++Trusted userspace code (e.g. operating system code running on a+read-only partition that is itself authenticated by dm-verity) can+authenticate the contents of an fs-verity file by using the+`FS_IOC_MEASURE_VERITY`_ ioctl to retrieve its hash, then verifying a+digital signature of it.++A standard file hash could be used instead of fs-verity. However,+this is inefficient if the file is large and only a small portion may+be accessed. This is often the case for Android application package+(APK) files, for example. These typically contain many translations,+classes, and other resources that are infrequently or even never+accessed on a particular device. It would be slow and wasteful to+read and hash the entire file before starting the application.++Unlike an ahead-of-time hash, fs-verity also re-verifies data each+time it's paged in. This ensures that malicious disk firmware can't+undetectably change the contents of the file at runtime.++fs-verity does not replace or obsolete dm-verity. dm-verity should+still be used on read-only filesystems. fs-verity is for files that+must live on a read-write filesystem because they are independently+updated and potentially user-installed, so dm-verity cannot be used.++The base fs-verity feature is a hashing mechanism only; actually+authenticating the files is up to userspace. However, to meet some+users' needs, fs-verity optionally supports a simple signature+verification mechanism where users can configure the kernel to require+that all fs-verity files be signed by a key loaded into a keyring; see+`Built-in signature verification`_. Support for fs-verity file hashes+in IMA (Integrity Measurement Architecture) policies is also planned.++User API+========++FS_IOC_ENABLE_VERITY+--------------------++The FS_IOC_ENABLE_VERITY ioctl enables fs-verity on a file. It takes+in a pointer to a :c:type:`struct fsverity_enable_arg`, defined as+follows::++ struct fsverity_enable_arg {+ __u32 version;+ __u32 hash_algorithm;+ __u32 block_size;+ __u32 salt_size;+ __u64 salt_ptr;+ __u32 sig_size;+ __u32 __reserved1;+ __u64 sig_ptr;+ __u64 __reserved2[11];+ };++This structure contains the parameters of the Merkle tree to build for+the file, and optionally contains a signature. It must be initialized+as follows:++-``version`` must be 1.+-``hash_algorithm`` must be the identifier for the hash algorithm to+ use for the Merkle tree, such as FS_VERITY_HASH_ALG_SHA256. See+``include/uapi/linux/fsverity.h`` for the list of possible values.+-``block_size`` must be the Merkle tree block size. Currently, this+ must be equal to the system page size, which is usually 4096 bytes.+ Other sizes may be supported in the future. This value is not+ necessarily the same as the filesystem block size.+-``salt_size`` is the size of the salt in bytes, or 0 if no salt is+ provided. The salt is a value that is prepended to every hashed+ block; it can be used to personalize the hashing for a particular+ file or device. Currently the maximum salt size is 32 bytes.+-``salt_ptr`` is the pointer to the salt, or NULL if no salt is+ provided.+-``sig_size`` is the size of the signature in bytes, or 0 if no+ signature is provided. Currently the signature is (somewhat+ arbitrarily) limited to 16128 bytes. See `Built-in signature+ verification`_ for more information.+-``sig_ptr`` is the pointer to the signature, or NULL if no+ signature is provided.+- All reserved fields must be zeroed.++FS_IOC_ENABLE_VERITY causes the filesystem to build a Merkle tree for+the file and persist it to a filesystem-specific location associated+with the file, then mark the file as a verity file. This ioctl may+take a long time to execute on large files, and it is interruptible by+fatal signals.++FS_IOC_ENABLE_VERITY checks for write access to the inode. However,+it must be executed on an O_RDONLY file descriptor and no processes+can have the file open for writing. Attempts to open the file for+writing while this ioctl is executing will fail with ETXTBSY. (This+is necessary to guarantee that no writable file descriptors will exist+after verity is enabled, and to guarantee that the file's contents are+stable while the Merkle tree is being built over it.)++On success, FS_IOC_ENABLE_VERITY returns 0, and the file becomes a+verity file. On failure (including the case of interruption by a+fatal signal), no changes are made to the file.++FS_IOC_ENABLE_VERITY can fail with the following errors:++-``EACCES``: the process does not have write access to the file+-``EEXIST``: the file already has verity enabled+-``EFAULT``: the caller provided inaccessible memory+-``EINTR``: the operation was interrupted by a fatal signal+-``EINVAL``: unsupported version, hash algorithm, or block size; or+ reserved bits are set; or the file descriptor refers to neither a+ regular file nor a directory; or the file is empty.+-``EISDIR``: the file descriptor refers to a directory+-``EMSGSIZE``: the salt or signature is too long+-``ENOENT``: fs-verity recognizes the hash algorithm, but it's not+ available in the kernel's crypto API as currently configured (e.g.+ for SHA-512, missing CONFIG_CRYPTO_SHA512).+-``ENOTTY``: this type of filesystem does not implement fs-verity+-``EOPNOTSUPP``: the kernel was not configured with fs-verity+ support, or the filesystem superblock has not had the 'verity'+ feature enabled on it. (See `Filesystem support`_.)+-``EPERM``: the file is append-only+-``EROFS``: the filesystem is read-only+-``ETXTBSY``: someone has the file open for writing. This can be the+ caller's file descriptor, another open file descriptor, or the file+ reference held by a writable memory map.++FS_IOC_MEASURE_VERITY+---------------------++The FS_IOC_MEASURE_VERITY ioctl retrieves the measurement of a verity+file. The file measurement is a digest that cryptographically+identifies the file contents that are being enforced on reads.++This ioctl takes in a pointer to a variable-length structure::++ struct fsverity_digest {+ __u16 digest_algorithm;+ __u16 digest_size; /* input/output */+ __u8 digest[];+ };++``digest_size`` is an input/output field. On input, it must be+initialized to the number of bytes allocated for the variable-length+``digest`` field.++On success, 0 is returned and the kernel fills in the structure as+follows:++-``digest_algorithm`` will be the hash algorithm used for the file+ measurement. It will match ``fsverity_enable_arg::hash_algorithm``.+-``digest_size`` will be the size of the digest in bytes, e.g. 32+ for SHA-256. (This can be redundant with ``digest_algorithm``.)+-``digest`` will be the actual bytes of the digest.++FS_IOC_MEASURE_VERITY is guaranteed to execute in constant time,+regardless of the size of the file.++FS_IOC_MEASURE_VERITY can fail with the following errors:++-``EFAULT``: the caller provided inaccessible memory+-``ENODATA``: the file is not a verity file+-``ENOTTY``: this type of filesystem does not implement fs-verity+-``EOPNOTSUPP``: the kernel was not configured with fs-verity+ support, or the filesystem superblock has not had the 'verity'+ feature enabled on it. (See `Filesystem support`_.)+-``EOVERFLOW``: the digest is longer than the specified+``digest_size`` bytes. Try providing a larger buffer.++FS_IOC_GETFLAGS+---------------++The existing ioctl FS_IOC_GETFLAGS (which isn't specific to fs-verity)+can also be used to check whether a file has fs-verity enabled or not.+To do so, check for FS_VERITY_FL (0x00100000) in the returned flags.++The verity flag is not settable via FS_IOC_SETFLAGS. You must use+FS_IOC_ENABLE_VERITY instead, since parameters must be provided.++Accessing verity files+======================++Applications can transparently access a verity file just like a+non-verity one, with the following exceptions:++- Verity files are readonly. They cannot be opened for writing or+ truncate()d, even if the file mode bits allow it. Attempts to do+ one of these things will fail with EPERM. However, changes to+ metadata such as owner, mode, timestamps, and xattrs are still+ allowed, since these are not measured by fs-verity. Verity files+ can also still be renamed, deleted, and linked to.++- Direct I/O is not supported on verity files. Attempts to use direct+ I/O on such files will fall back to buffered I/O.++- DAX (Direct Access) is not supported on verity files, because this+ would circumvent the data verification.++- Reads of data that doesn't match the verity Merkle tree will fail+ with EIO (for read()) or SIGBUS (for mmap() reads).++- If the sysctl "fs.verity.require_signatures" is set to 1 and the+ file's verity measurement is not signed by a key in the fs-verity+ keyring, then opening the file will fail. See `Built-in signature+ verification`_.++Direct access to the Merkle tree is not supported. Therefore, if a+verity file is copied, or is backed up and restored, then it will lose+its "verity"-ness. fs-verity is primarily meant for files like+executables that are managed by a package manager.++File measurement computation+============================++This section describes how fs-verity hashes the file contents using a+Merkle tree to produce the "file measurement" which cryptographically+identifies the file contents. This algorithm is the same for all+filesystems that support fs-verity.++Userspace only needs to be aware of this algorithm if it needs to+compute the file measurement itself, e.g. in order to sign the file.++Merkle tree+-----------++The file contents is divided into blocks, where the block size is+configurable but is usually 4096 bytes. The end of the last block is+zero-padded if needed. Each block is then hashed, producing the first+level of hashes. Then, the hashes in this first level are grouped+into 'blocksize'-byte blocks (zero-padding the ends as needed) and+these blocks are hashed, producing the second level of hashes. This+proceeds up the tree until only a single block remains. The hash of+this block is the "Merkle tree root hash".++If the entire file contents fit in one block, then the "Merkle tree+root hash" is simply the hash of the single data block. Empty files+are not supported.++The "blocks" here are not necessarily the same as "filesystem blocks".++If a salt was specified, then it's zero-padded to the closest multiple+of the input size of the hash algorithm's compression function, e.g.+64 bytes for for SHA-256 or 128 bytes for SHA-512. The padded salt is+prepended to every data or Merkle tree block that is hashed.++The purpose of the block padding is to cause every hash to be taken+over the same amount of data, which simplifies the implementation and+keeps open more possibilities for hardware acceleration. The purpose+of the salt padding is to make the salting "free" when the salted hash+state is precomputed, then imported for each hash.++Example: in the recommended configuration of SHA-256 and 4K blocks,+128 hash values fit in each block. Thus, each level of the Merkle+tree is approximately 128 times smaller than the previous, and for+large files the Merkle tree's size converges to approximately 1/127 of+the original file size. However, for small files, the padding is+significant, making the space overhead proportionally more.++fs-verity descriptor+--------------------++By itself, the Merkle tree root hash is ambiguous. For example, it+can't a distinguish a large file from a small second file whose data+is exactly the top-level hash block of the first file. Ambiguities+also arise from the convention of padding to the next block boundary.++To solve this problem, the verity file measurement is actually+computed as a hash of the following structure, which contains the+Merkle tree root hash as well as other fields such as the file size::++ struct fsverity_descriptor {+ __u8 version; /* must be 1 */+ __u8 hash_algorithm; /* Merkle tree hash algorithm */+ __u8 log_blocksize; /* log2 of size of data and tree blocks */+ __u8 salt_size; /* size of salt in bytes; 0 if none */+ __le32 sig_size; /* must be 0 */+ __le64 data_size; /* size of file the Merkle tree is built over */+ __u8 root_hash[64]; /* Merkle tree root hash */+ __u8 salt[32]; /* salt prepended to each hashed block */+ __u8 __reserved[144]; /* must be 0's */+ };++Note that the ``sig_size`` field must be set to 0 for the purpose of+computing the file measurement, even if a signature was provided (or+will be provided) to `FS_IOC_ENABLE_VERITY`_.++Built-in signature verification+===============================++With CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y, fs-verity supports putting+a portion of an authentication policy (see `Use cases`_) in the+kernel. Specifically, it adds support for:++1. At fs-verity module initialization time, a keyring ".fs-verity" is+ created. The root user can add trusted X.509 certificates to this+ keyring using the add_key() system call, then (when done)+ optionally use keyctl_restrict_keyring() to prevent additional+ certificates from being added.++2.`FS_IOC_ENABLE_VERITY`_ accepts a pointer to a PKCS#7 formatted+ signature in DER format of the file measurement. On success, this+ signature is persisted alongside the Merkle tree. Then, any time+ the file is opened, the kernel will verify this signature against+ the certificates in the ".fs-verity" keyring, and verify that it+ matches the actual file measurement.++3. A new sysctl "fs.verity.require_signatures" is made available.+ When set to 1, the kernel requires that all verity files have a+ correctly signed file measurement as described in (2).++File measurements must be signed in the following format, which is+similar to the structure used by `FS_IOC_MEASURE_VERITY`_::++ struct fsverity_signed_digest {+ char magic[8]; /* must be "FSVerity" */+ __le16 digest_algorithm;+ __le16 digest_size;+ __u8 digest[];+ };++fs-verity's built-in signature verification support is meant as a+relatively simple mechanism that can be used to provide some level of+authenticity protection for verity files, as an alternative to doing+the signature verification in userspace or using IMA-appraisal.+However, with this mechanism, userspace programs still need to check+that the verity bit is set, and there is no protection against verity+files being swapped around.++Filesystem support+==================++fs-verity is currently supported by the ext4 and f2fs filesystems.+The CONFIG_FS_VERITY kconfig option must be enabled to use fs-verity+on either filesystem.++``include/linux/fsverity.h`` declares the interface between the+``fs/verity/`` support layer and filesystems. Briefly, filesystems+must provide an ``fsverity_operations`` structure that provides+methods to read and write the verity metadata to a filesystem-specific+location, including the Merkle tree blocks and+``fsverity_descriptor``. Filesystems must also call functions in+``fs/verity/`` at certain times, such as when a file is opened or when+pages have been read into the pagecache. (See `Verifying data`_.)++ext4+----++ext4 supports fs-verity since Linux TODO and e2fsprogs v1.45.2.++To create verity files on an ext4 filesystem, the filesystem must have+been formatted with ``-O verity`` or had ``tune2fs -O verity`` run on+it. "verity" is an RO_COMPAT filesystem feature, so once set, old+kernels will only be able to mount the filesystem readonly, and old+versions of e2fsck will be unable to check the filesystem. Moreover,+currently ext4 only supports mounting a filesystem with the "verity"+feature when its block size is equal to PAGE_SIZE (often 4096 bytes).++ext4 sets the EXT4_VERITY_FL on-disk inode flag on verity files. It+can only be set by `FS_IOC_ENABLE_VERITY`_, and it cannot be cleared.++ext4 also supports encryption, which can be used simultaneously with+fs-verity. In this case, the plaintext data is verified rather than+the ciphertext. This is necessary in order to make the file+measurement meaningful, since every file is encrypted differently.++ext4 stores the verity metadata (Merkle tree and fsverity_descriptor)+past the end of the file, starting at the first page fully beyond+i_size. This approach works because (a) verity files are readonly,+and (b) pages fully beyond i_size aren't visible to userspace but can+be read/written internally by ext4 with only some relatively small+changes to ext4. This approach avoids having to depend on the+EA_INODE feature and on rearchitecturing ext4's xattr support to+support paging multi-gigabyte xattrs into memory, and to support+encrypting xattrs. Note that the verity metadata *must* be encrypted+when the file is, since it contains hashes of the plaintext data.++Currently, ext4 verity only supports the case where the Merkle tree+block size, filesystem block size, and page size are all the same.++f2fs+----++f2fs supports fs-verity since Linux TODO and f2fs-tools v1.11.0.++To create verity files on an f2fs filesystem, the filesystem must have+been formatted with ``-O verity``.++f2fs sets the FADVISE_VERITY_BIT on-disk inode flag on verity files.+It can only be set by `FS_IOC_ENABLE_VERITY`_, and it cannot be+cleared.++Like ext4, f2fs stores the verity metadata (Merkle tree and+fsverity_descriptor) past the end of the file, starting at the first+page fully beyond i_size. See explanation for ext4 above. Moreover,+f2fs supports at most 4096 bytes of xattr entries per inode which+wouldn't be enough for even a single Merkle tree block.++Currently, f2fs verity only supports a Merkle tree block size of 4096.++Implementation details+======================++Verifying data+--------------++fs-verity ensures that all reads of a verity file's data are verified,+regardless of which syscall is used to do the read (e.g. mmap(),+read(), pread()) and regardless of whether it's the first read or a+later read (unless the later read can return cached data that was+already verified). Below, we describe how filesystems implement this.++Pagecache+~~~~~~~~~++For filesystems using Linux's pagecache, the ``->readpage()`` and+``->readpages()`` methods must be modified to verify pages before they+are marked Uptodate. Merely hooking ``->read_iter()`` would be+insufficient, since ``->read_iter()`` is not used for memory maps.++Therefore, fs/verity/ provides a function fsverity_verify_page() which+verifies a page that has been read into the pagecache of a verity+inode, but is still locked and not Uptodate, so it's not yet readable+by userspace. As needed to do the verification,+fsverity_verify_page() will call back into the filesystem to read+Merkle tree pages via fsverity_operations::read_merkle_tree_page().++fsverity_verify_page() returns false if verification failed; in this+case, the filesystem must not set the page Uptodate. Following this,+as per the usual Linux pagecache behavior, attempts by userspace to+read() from the part of the file containing the page will fail with+EIO, and accesses to the page within a memory map will raise SIGBUS.++fsverity_verify_page() currently only supports the case where the+Merkle tree block size is equal to PAGE_SIZE (often 4096 bytes).++In principle, fsverity_verify_page() verifies the entire path in the+Merkle tree from the data page to the root hash. However, for+efficiency the filesystem may cache the hash pages. Therefore,+fsverity_verify_page() only ascends the tree reading hash pages until+an already-verified hash page is seen, as indicated by the PageChecked+bit being set. It then verifies the path to that page.++This optimization, which is also used by dm-verity, results in+excellent sequential read performance. This is because usually (e.g.+127 in 128 times for 4K blocks and SHA-256) the hash page from the+bottom level of the tree will already be cached and checked from+reading a previous data page. However, random reads perform worse.++Block device based filesystems+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Block device based filesystems (e.g. ext4 and f2fs) in Linux also use+the pagecache, so the above subsection applies too. However, they+also usually read many pages from a file at once, grouped into a+structure called a "bio". To make it easier for these types of+filesystems to support fs-verity, fs/verity/ also provides a function+fsverity_verify_bio() which verifies all pages in a bio.++ext4 and f2fs also support encryption. If a verity file is also+encrypted, the pages must be decrypted before being verified. To+support this, these filesystems allocate a "post-read context" for+each bio and store it in ``->bi_private``::++ struct bio_post_read_ctx {+ struct bio *bio;+ struct work_struct work;+ unsigned int cur_step;+ unsigned int enabled_steps;+ };++``enabled_steps`` is a bitmask that specifies whether decryption,+verity, or both is enabled. After the bio completes, for each needed+postprocessing step the filesystem enqueues the bio_post_read_ctx on a+workqueue, and then the workqueue work does the decryption or+verification. Finally, pages where no decryption or verity error+occurred are marked Uptodate, and the pages are unlocked.++Files on ext4 and f2fs may contain holes. Normally, ``->readpages()``+simply zeroes holes and sets the corresponding pages Uptodate; no bios+are issued. To prevent this case from bypassing fs-verity, these+filesystems use fsverity_verify_page() to verify hole pages.++ext4 and f2fs disable direct I/O on verity files, since otherwise+direct I/O would bypass fs-verity. (They also do the same for+encrypted files.)++Userspace utility+=================++This document focuses on the kernel, but a userspace utility for+fs-verity can be found at:++ https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/fsverity-utils.git++See the README.md file in the fsverity-utils source tree for details,+including examples of setting up fs-verity protected files.++Tests+=====++To test fs-verity, use xfstests. For example, using `kvm-xfstests+<https://git.kernel.org/pub/scm/fs/ext2/xfstests-bld.git/tree/Documentation/kvm-quickstart.md>`_::++ kvm-xfstests -c ext4,f2fs -g verity++FAQ+===++This section answers frequently asked questions about fs-verity that+weren't already directly answered in other parts of this document.++:Q: Why isn't fs-verity part of IMA?+:A: fs-verity and IMA (Integrity Measurement Architecture) have+ different focuses. fs-verity is a filesystem-level mechanism for+ hashing individual files using a Merkle tree. In contrast, IMA+ specifies a system-wide policy that specifies which files are+ hashed and what to do with those hashes, such as log them,+ authenticate them, or add them to a measurement list.++ IMA is planned to support the fs-verity hashing mechanism as an+ alternative to doing full file hashes, for people who want the+ performance and security benefits of the Merkle tree based hash.+ But it doesn't make sense to force all uses of fs-verity to be+ through IMA. As a standalone filesystem feature, fs-verity+ already meets many users' needs, and it's testable like other+ filesystem features e.g. with xfstests.++:Q: Isn't fs-verity useless because the attacker can just modify the+ hashes in the Merkle tree, which is stored on-disk?+:A: To verify the authenticity of an fs-verity file you must verify+ the authenticity of the "file measurement", which is basically the+ root hash of the Merkle tree. See `Use cases`_.++:Q: Isn't fs-verity useless because the attacker can just replace a+ verity file with a non-verity one?+:A: See `Use cases`_. In the initial use case, it's really trusted+ userspace code that authenticates the files; fs-verity is just a+ tool to do this job efficiently and securely. The trusted+ userspace code will consider non-verity files to be inauthentic.++:Q: Why does the Merkle tree need to be stored on-disk? Couldn't you+ store just the root hash?+:A: If the Merkle tree wasn't stored on-disk, then you'd have to+ compute the entire tree when the file is first accessed, even if+ just one byte is being read. This is a fundamental consequence of+ how Merkle tree hashing works. To verify a leaf node, you need to+ verify the whole path to the root hash, including the root node+ (the thing which the root hash is a hash of). But if the root+ node isn't stored on-disk, you have to compute it by hashing its+ children, and so on until you've actually hashed the entire file.++ That defeats most of the point of doing a Merkle tree-based hash,+ since if you have to hash the whole file ahead of time anyway,+ then you could simply do sha256(file) instead. That would be much+ simpler, and a bit faster too.++ It's true that an in-memory Merkle tree could still provide the+ advantage of verification on every read rather than just on the+ first read. However, it would be inefficient because every time a+ hash page gets evicted (you can't pin the entire Merkle tree into+ memory, since it may be very large), in order to restore it you+ again need to hash everything below it in the tree. This again+ defeats most of the point of doing a Merkle tree-based hash, since+ a single block read could trigger re-hashing gigabytes of data.++:Q: But couldn't you store just the leaf nodes and compute the rest?+:A: See previous answer; this really just moves up one level, since+ one could alternatively interpret the data blocks as being the+ leaf nodes of the Merkle tree. It's true that the tree can be+ computed much faster if the leaf level is stored rather than just+ the data, but that's only because each level is less than 1% the+ size of the level below (assuming the recommended settings of+ SHA-256 and 4K blocks). For the exact same reason, by storing+ "just the leaf nodes" you'd already be storing over 99% of the+ tree, so you might as well simply store the whole tree.++:Q: Can the Merkle tree be built ahead of time, e.g. distributed as+ part of a package that is installed to many computers?+:A: This isn't currently supported. It was part of the original+ design, but was removed to simplify the kernel UAPI and because it+ wasn't a critical use case. Files are usually installed once and+ used many times, and cryptographic hashing is somewhat fast on+ most modern processors.++:Q: Why doesn't fs-verity support writes?+:A: Write support would be very difficult and would require a+ completely different design, so it's well outside the scope of+ fs-verity. Write support would require:++- A way to maintain consistency between the data and hashes,+ including all levels of hashes, since corruption after a crash+ (especially of potentially the entire file!) is unacceptable.+ The main options for solving this are data journalling,+ copy-on-write, and log-structured volume. But it's very hard to+ retrofit existing filesystems with new consistency mechanisms.+ Data journalling is available on ext4, but is very slow.++- Rebuilding the the Merkle tree after every write, which would be+ extremely inefficient. Alternatively, a different authenticated+ dictionary structure such as an "authenticated skiplist" could+ be used. However, this would be far more complex.++ Compare it to dm-verity vs. dm-integrity. dm-verity is very+ simple: the kernel just verifies read-only data against a+ read-only Merkle tree. In contrast, dm-integrity supports writes+ but is slow, is much more complex, and doesn't actually support+ full-device authentication since it authenticates each sector+ independently, i.e. there is no "root hash". It doesn't really+ make sense for the same device-mapper target to support these two+ very different cases; the same applies to fs-verity.++:Q: Since verity files are immutable, why isn't the immutable bit set?+:A: The existing "immutable" bit (FS_IMMUTABLE_FL) already has a+ specific set of semantics which not only make the file contents+ read-only, but also prevent the file from being deleted, renamed,+ linked to, or having its owner or mode changed. These extra+ properties are unwanted for fs-verity, so reusing the immutable+ bit isn't appropriate.++:Q: Why does the API use ioctls instead of setxattr() and getxattr()?+:A: Abusing the xattr interface for basically arbitrary syscalls is+ heavily frowned upon by most of the Linux filesystem developers.+ An xattr should really just be an xattr on-disk, not an API to+ e.g. magically trigger construction of a Merkle tree.++:Q: Does fs-verity support remote filesystems?+:A: Only ext4 and f2fs support is implemented currently, but in+ principle any filesystem that can store per-file verity metadata+ can support fs-verity, regardless of whether it's local or remote.+ Some filesystems may have fewer options of where to store the+ verity metadata; one possibility is to store it past the end of+ the file and "hide" it from userspace by manipulating i_size. The+ data verification functions provided by ``fs/verity/`` also assume+ that the filesystem uses the Linux pagecache, but both local and+ remote filesystems normally do so.++:Q: Why is anything filesystem-specific at all? Shouldn't fs-verity+ be implemented entirely at the VFS level?+:A: There are many reasons why this is not possible or would be very+ difficult, including the following:++- To prevent bypassing verification, pages must not be marked+ Uptodate until they've been verified. Currently, each+ filesystem is responsible for marking pages Uptodate via+``->readpages()``. Therefore, currently it's not possible for+ the VFS to do the verification on its own. Changing this would+ require significant changes to the VFS and all filesystems.++- It would require defining a filesystem-independent way to store+ the verity metadata. Extended attributes don't work for this+ because (a) the Merkle tree may be gigabytes, but many+ filesystems assume that all xattrs fit into a single 4K+ filesystem block, and (b) ext4 and f2fs encryption doesn't+ encrypt xattrs, yet the Merkle tree *must* be encrypted when the+ file contents are, because it stores hashes of the plaintext+ file contents.++ So the verity metadata would have to be stored in an actual+ file. Using a separate file would be very ugly, since the+ metadata is fundamentally part of the file to be protected, and+ it could cause problems where users could delete the real file+ but not the metadata file or vice versa. On the other hand,+ having it be in the same file would break applications unless+ filesystems' notion of i_size were divorced from the VFS's,+ which would be complex and require changes to all filesystems.++- It's desirable that FS_IOC_ENABLE_VERITY uses the filesystem's+ transaction mechanism so that either the file ends up with+ verity enabled, or no changes were made. Allowing intermediate+ states to occur after a crash may cause problems.
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:11
From: Eric Biggers <redacted>
Add functions that verify data pages that have been read from a
fs-verity file, against that file's Merkle tree. These will be called
from filesystems' ->readpage() and ->readpages() methods.
Since data verification can block, a workqueue is provided for these
methods to enqueue verification work from their bio completion callback.
See the "Verifying data" section of
Documentation/filesystems/fsverity.rst for more information.
Signed-off-by: Eric Biggers <redacted>
---
fs/verity/Makefile | 3 +-
fs/verity/fsverity_private.h | 5 +
fs/verity/init.c | 8 +
fs/verity/open.c | 6 +
fs/verity/verify.c | 275 +++++++++++++++++++++++++++++++++++
include/linux/fsverity.h | 56 +++++++
6 files changed, 352 insertions(+), 1 deletion(-)
create mode 100644 fs/verity/verify.c
@@ -0,0 +1,275 @@+// SPDX-License-Identifier: GPL-2.0+/*+*fs/verity/verify.c:dataverificationfunctions,i.e.hooksfor->readpages()+*+*Copyright2019GoogleLLC+*/++#include"fsverity_private.h"++#include<crypto/hash.h>+#include<linux/bio.h>+#include<linux/ratelimit.h>++staticstructworkqueue_struct*fsverity_read_workqueue;++/**+*hash_at_level()-computethelocationoftheblock'shashatthegivenlevel+*+*@params:(in)theMerkletreeparameters+*@dindex:(in)theindexofthedatablockbeingverified+*@level:(in)thelevelofhashwewant(0isleaflevel)+*@hindex:(out)theindexofthehashblockcontainingthewantedhash+*@hoffset:(out)thebyteoffsettothewantedhashwithinthehashblock+*/+staticvoidhash_at_level(conststructmerkle_tree_params*params,+pgoff_tdindex,unsignedintlevel,pgoff_t*hindex,+unsignedint*hoffset)+{+pgoff_tposition;++/* Offset of the hash within the level's region, in hashes */+position=dindex>>(level*params->log_arity);++/* Index of the hash block in the tree overall */+*hindex=params->level_start[level]+(position>>params->log_arity);++/* Offset of the wanted hash (in bytes) within the hash block */+*hoffset=(position&((1<<params->log_arity)-1))<<+(params->log_blocksize-params->log_arity);+}++/* Extract a hash from a hash page */+staticvoidextract_hash(structpage*hpage,unsignedinthoffset,+unsignedinthsize,u8*out)+{+void*virt=kmap_atomic(hpage);++memcpy(out,virt+hoffset,hsize);+kunmap_atomic(virt);+}++staticinlineintcmp_hashes(conststructfsverity_info*vi,+constu8*want_hash,constu8*real_hash,+pgoff_tindex,intlevel)+{+constunsignedinthsize=vi->tree_params.digest_size;++if(memcmp(want_hash,real_hash,hsize)==0)+return0;++fsverity_err(vi->inode,+"FILE CORRUPTED! index=%lu, level=%d, want_hash=%s:%*phN, real_hash=%s:%*phN",+index,level,+vi->tree_params.hash_alg->name,hsize,want_hash,+vi->tree_params.hash_alg->name,hsize,real_hash);+return-EBADMSG;+}++/*+*Verifyasingledatapageagainstthefile'sMerkletree.+*+*Inprinciple,weneedtoverifytheentirepathtotherootnode.However,+*forefficiencythefilesystemmaycachethehashpages.Thereforeweneed+*onlyascendthetreeuntilanalready-verifiedpageisseen,asindicatedby+*thePageCheckedbitbeingset;thenverifythepathtothatpage.+*+*Thiscodecurrentlyonlysupportsthecasewheretheverityblocksizeis+*equaltoPAGE_SIZE.Doingotherwisewouldbepossiblebuttricky,sincewe+*wouldn'tbeabletousethePageCheckedbit.+*+*Notethatmultipleprocessesmayracetoverifyahashpageandmarkit+*Checked,butitdoesn'tmatter;theresultwillbethesameeitherway.+*+*Return:trueifthepageisvalid,elsefalse.+*/+staticboolverify_page(structinode*inode,conststructfsverity_info*vi,+structahash_request*req,structpage*data_page)+{+conststructmerkle_tree_params*params=&vi->tree_params;+constunsignedinthsize=params->digest_size;+constpgoff_tindex=data_page->index;+intlevel;+u8_want_hash[FS_VERITY_MAX_DIGEST_SIZE];+constu8*want_hash;+u8real_hash[FS_VERITY_MAX_DIGEST_SIZE];+structpage*hpages[FS_VERITY_MAX_LEVELS];+unsignedinthoffsets[FS_VERITY_MAX_LEVELS];+interr;++if(WARN_ON_ONCE(!PageLocked(data_page)||PageUptodate(data_page)))+returnfalse;++pr_debug_ratelimited("Verifying data page %lu...\n",index);++/*+*Startingattheleaflevel,ascendthetreesavinghashpagesalong+*thewayuntilwefindaverifiedhashpage,indicatedbyPageChecked;+*oruntilwereachtheroot.+*/+for(level=0;level<params->num_levels;level++){+pgoff_thindex;+unsignedinthoffset;+structpage*hpage;++hash_at_level(params,index,level,&hindex,&hoffset);++pr_debug_ratelimited("Level %d: hindex=%lu, hoffset=%u\n",+level,hindex,hoffset);++hpage=inode->i_sb->s_vop->read_merkle_tree_page(inode,+hindex);+if(IS_ERR(hpage)){+err=PTR_ERR(hpage);+fsverity_err(inode,+"Error %d reading Merkle tree page %lu",+err,hindex);+gotoout;+}++if(PageChecked(hpage)){+extract_hash(hpage,hoffset,hsize,_want_hash);+want_hash=_want_hash;+put_page(hpage);+pr_debug_ratelimited("Hash page already checked, want %s:%*phN\n",+params->hash_alg->name,+hsize,want_hash);+gotodescend;+}+pr_debug_ratelimited("Hash page not yet checked\n");+hpages[level]=hpage;+hoffsets[level]=hoffset;+}++want_hash=vi->root_hash;+pr_debug("Want root hash: %s:%*phN\n",+params->hash_alg->name,hsize,want_hash);+descend:+/* Descend the tree verifying hash pages */+for(;level>0;level--){+structpage*hpage=hpages[level-1];+unsignedinthoffset=hoffsets[level-1];++err=fsverity_hash_page(params,inode,req,hpage,real_hash);+if(err)+gotoout;+err=cmp_hashes(vi,want_hash,real_hash,index,level-1);+if(err)+gotoout;+SetPageChecked(hpage);+extract_hash(hpage,hoffset,hsize,_want_hash);+want_hash=_want_hash;+put_page(hpage);+pr_debug("Verified hash page at level %d, now want %s:%*phN\n",+level-1,params->hash_alg->name,hsize,want_hash);+}++/* Finally, verify the data page */+err=fsverity_hash_page(params,inode,req,data_page,real_hash);+if(err)+gotoout;+err=cmp_hashes(vi,want_hash,real_hash,index,-1);+out:+for(;level>0;level--)+put_page(hpages[level-1]);++returnerr==0;+}++/**+*fsverity_verify_page-verifyadatapage+*+*Verifyapagethathasjustbeenreadfromaverityfile.Thepagemustbea+*pagecachepagethatisstilllockedandnotyetuptodate.+*+*Return:trueifthepageisvalid,elsefalse.+*/+boolfsverity_verify_page(structpage*page)+{+structinode*inode=page->mapping->host;+conststructfsverity_info*vi=inode->i_verity_info;+structahash_request*req;+boolvalid;++req=ahash_request_alloc(vi->tree_params.hash_alg->tfm,GFP_NOFS);+if(unlikely(!req))+returnfalse;++valid=verify_page(inode,vi,req,page);++ahash_request_free(req);++returnvalid;+}+EXPORT_SYMBOL_GPL(fsverity_verify_page);++#ifdef CONFIG_BLOCK+/**+*fsverity_verify_bio-verifya'read'biothathasjustcompleted+*+*Verifyasetofpagesthathavejustbeenreadfromaverityfile.Thepages+*mustbepagecachepagesthatarestilllockedandnotyetuptodate.Pages+*thatfailverificationaresettotheErrorstate.Verificationisskipped+*forpagesalreadyintheErrorstate,e.g.duetofscryptdecryptionfailure.+*+*Thisisahelperfunctionforusebythe->readpages()methodoffilesystems+*thatissuebiostoreaddatadirectlyintothepagecache.Filesystemsthat+*populatethepagecachewithoutissuingbios(e.g.nonblock-based+*filesystems)mustinsteadcallfsverity_verify_page()directlyoneachpage.+*Allfilesystemsmustalsocallfsverity_verify_page()onholes.+*/+voidfsverity_verify_bio(structbio*bio)+{+structinode*inode=bio_first_page_all(bio)->mapping->host;+conststructfsverity_info*vi=inode->i_verity_info;+structahash_request*req;+structbio_vec*bv;+structbvec_iter_alliter_all;++req=ahash_request_alloc(vi->tree_params.hash_alg->tfm,GFP_NOFS);+if(unlikely(!req)){+bio_for_each_segment_all(bv,bio,iter_all)+SetPageError(bv->bv_page);+return;+}++bio_for_each_segment_all(bv,bio,iter_all){+structpage*page=bv->bv_page;++if(!PageError(page)&&!verify_page(inode,vi,req,page))+SetPageError(page);+}++ahash_request_free(req);+}+EXPORT_SYMBOL_GPL(fsverity_verify_bio);+#endif /* CONFIG_BLOCK */++/**+*fsverity_enqueue_verify_work-enqueueworkonthefs-verityworkqueue+*+*Enqueueverificationworkforasynchronousprocessing.+*/+voidfsverity_enqueue_verify_work(structwork_struct*work)+{+queue_work(fsverity_read_workqueue,work);+}+EXPORT_SYMBOL_GPL(fsverity_enqueue_verify_work);++int__initfsverity_init_workqueue(void)+{+/*+*Useanunboundworkqueuetoallowbiostobeverifiedinparallel+*evenwhentheyhappentocompleteonthesameCPU.Thissacrifices+*locality,butit'sworthwhilesincehashingisCPU-intensive.+*+*Alsouseahigh-priorityworkqueuetoprioritizeverificationwork,+*whichblocksreadsfromcompleting,overregularapplicationtasks.+*/+fsverity_read_workqueue=alloc_workqueue("fsverity_read_queue",+WQ_UNBOUND|WQ_HIGHPRI,+num_online_cpus());+if(!fsverity_read_workqueue)+return-ENOMEM;+return0;+}
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:11
From: Eric Biggers <redacted>
Add the fsverity_file_open() function, which prepares an fs-verity file
to be read from. If not already done, it loads the fs-verity descriptor
from the filesystem and sets up an fsverity_info structure for the inode
which describes the Merkle tree and contains the file measurement. It
also denies all attempts to open verity files for writing.
This commit also begins the include/linux/fsverity.h header, which
declares the interface between fs/verity/ and filesystems.
Signed-off-by: Eric Biggers <redacted>
---
fs/verity/Makefile | 3 +-
fs/verity/fsverity_private.h | 54 +++++-
fs/verity/init.c | 6 +
fs/verity/open.c | 325 +++++++++++++++++++++++++++++++++++
include/linux/fsverity.h | 71 ++++++++
5 files changed, 456 insertions(+), 3 deletions(-)
create mode 100644 fs/verity/open.c
create mode 100644 include/linux/fsverity.h
@@ -62,6 +61,40 @@ struct merkle_tree_params {u64level_start[FS_VERITY_MAX_LEVELS];};+/**+*fsverity_info-cachedveritymetadataforaninode+*+*Whenaverityfileisfirstopened,aninstanceofthisstructisallocated+*andstoredin->i_verity_info;itremainsuntiltheinodeisevicted.It+*cachesinformationabouttheMerkletreethat'sneededtoefficientlyverify+*datareadfromthefile.Italsocachesthefilemeasurement.TheMerkle+*treepagesthemselvesarenotcachedhere,butthefilesystemmaycachethem.+*/+structfsverity_info{+structmerkle_tree_paramstree_params;+u8root_hash[FS_VERITY_MAX_DIGEST_SIZE];+u8measurement[FS_VERITY_MAX_DIGEST_SIZE];+conststructinode*inode;+};++/*+*Merkletreeproperties.Thefilemeasurementisthehashofthisstructure.+*/+structfsverity_descriptor{+__u8version;/* must be 1 */+__u8hash_algorithm;/* Merkle tree hash algorithm */+__u8log_blocksize;/* log2 of size of data and tree blocks */+__u8salt_size;/* size of salt in bytes; 0 if none */+__le32sig_size;/* reserved, must be 0 */+__le64data_size;/* size of file the Merkle tree is built over */+__u8root_hash[64];/* Merkle tree root hash */+__u8salt[32];/* salt prepended to each hashed block */+__u8__reserved[144];/* must be 0's */+};++/* Arbitrary limit to bound the kmalloc() size. Can be changed. */+#define FS_VERITY_MAX_DESCRIPTOR_SIZE 16384+/* hash_algs.c */externstructfsverity_hash_algfsverity_hash_algs[];
@@ -0,0 +1,325 @@+// SPDX-License-Identifier: GPL-2.0+/*+*fs/verity/open.c:openingfs-verityfiles+*+*Copyright2019GoogleLLC+*/++#include"fsverity_private.h"++#include<linux/slab.h>++staticstructkmem_cache*fsverity_info_cachep;++/**+*fsverity_init_merkle_tree_params()-initializeMerkletreeparameters+*@params:theparametersstructtoinitialize+*@inode:theinodeforwhichtheMerkletreeisbeingbuilt+*@hash_algorithm:numberofhashalgorithmtouse+*@log_blocksize:logbase2ofblocksizetouse+*@salt:pointertosalt(optional)+*@salt_size:sizeofsalt,possibly0+*+*Validatethehashalgorithmandblocksize,thencomputethetreetopology+*(numlevels,numblocksineachlevel,etc.)andinitialize@params.+*+*Return:0onsuccess,-errnoonfailure+*/+intfsverity_init_merkle_tree_params(structmerkle_tree_params*params,+conststructinode*inode,+unsignedinthash_algorithm,+unsignedintlog_blocksize,+constu8*salt,size_tsalt_size)+{+conststructfsverity_hash_alg*hash_alg;+interr;+u64blocks;+u64offset;+intlevel;++memset(params,0,sizeof(*params));++if(inode->i_size<=0){+fsverity_warn(inode,"File is empty. This is not supported.");+return-EINVAL;+}++hash_alg=fsverity_get_hash_alg(inode,hash_algorithm);+if(IS_ERR(hash_alg))+returnPTR_ERR(hash_alg);+params->hash_alg=hash_alg;+params->digest_size=hash_alg->digest_size;++params->hashstate=fsverity_prepare_hash_state(hash_alg,salt,+salt_size);+if(IS_ERR(params->hashstate)){+err=PTR_ERR(params->hashstate);+params->hashstate=NULL;+fsverity_err(inode,"Error %d preparing hash state",err);+gotoout_err;+}++if(log_blocksize!=PAGE_SHIFT){+fsverity_warn(inode,"Unsupported log_blocksize: %u",+log_blocksize);+err=-EINVAL;+gotoout_err;+}+params->log_blocksize=log_blocksize;+params->block_size=1<<log_blocksize;++if(WARN_ON(!is_power_of_2(params->digest_size))){+err=-EINVAL;+gotoout_err;+}+if(params->block_size<2*params->digest_size){+fsverity_warn(inode,+"Merkle tree block size (%u) too small for hash algorithm \"%s\"",+params->block_size,hash_alg->name);+err=-EINVAL;+gotoout_err;+}+params->log_arity=params->log_blocksize-ilog2(params->digest_size);+params->hashes_per_block=1<<params->log_arity;++pr_debug("Merkle tree uses %s with %u-byte blocks (%u hashes/block), salt=%*phN\n",+hash_alg->name,params->block_size,params->hashes_per_block,+(int)salt_size,salt);++/*+*ComputethenumberoflevelsintheMerkletreeandcreateamapfrom+*leveltothestartingblockofthatlevel.Level'num_levels-1'is+*therootandisstoredfirst.Level0istheleveldirectly"above"+*thedatablocksandisstoredlast.+*/++/* Compute number of levels and the number of blocks in each level */+blocks=(inode->i_size+params->block_size-1)>>log_blocksize;+pr_debug("Data is %lld bytes (%llu blocks)\n",inode->i_size,blocks);+while(blocks>1){+if(params->num_levels>=FS_VERITY_MAX_LEVELS){+fsverity_err(inode,"Too many levels in Merkle tree");+err=-EINVAL;+gotoout_err;+}+blocks=(blocks+params->hashes_per_block-1)>>+params->log_arity;+/* temporarily using level_start[] to store blocks in level */+params->level_start[params->num_levels++]=blocks;+}++/* Compute the starting block of each level */+offset=0;+for(level=(int)params->num_levels-1;level>=0;level--){+blocks=params->level_start[level];+params->level_start[level]=offset;+pr_debug("Level %d is %llu blocks starting at index %llu\n",+level,blocks,offset);+offset+=blocks;+}++params->data_size=inode->i_size;+params->tree_size=offset<<log_blocksize;+return0;++out_err:+kfree(params->hashstate);+memset(params,0,sizeof(*params));+returnerr;+}++/* Compute the file measurement by hashing the fsverity_descriptor. */+staticintcompute_file_measurement(conststructfsverity_hash_alg*hash_alg,+conststructfsverity_descriptor*desc,+u8*measurement)+{+returnfsverity_hash_buffer(hash_alg,desc,sizeof(*desc),measurement);+}++/*+*Validatethegivenfsverity_descriptorandcreateanewfsverity_infofrom+*it.Thesignature(ifpresent)isalsochecked.+*/+structfsverity_info*fsverity_create_info(conststructinode*inode,+constvoid*_desc,size_tdesc_size)+{+conststructfsverity_descriptor*desc=_desc;+structfsverity_info*vi;+interr;++if(desc_size<sizeof(*desc)){+fsverity_err(inode,"Unrecognized descriptor size (%zu)",+desc_size);+returnERR_PTR(-EINVAL);+}++if(desc->version!=1){+fsverity_err(inode,"Unrecognized descriptor version: %u",+desc->version);+returnERR_PTR(-EINVAL);+}++if(desc->sig_size||+memchr_inv(desc->__reserved,0,sizeof(desc->__reserved))){+fsverity_err(inode,"Reserved bits set in descriptor");+returnERR_PTR(-EINVAL);+}++if(desc->salt_size>sizeof(desc->salt)){+fsverity_err(inode,"Invalid salt_size: %u",desc->salt_size);+returnERR_PTR(-EINVAL);+}++if(le64_to_cpu(desc->data_size)!=inode->i_size){+fsverity_err(inode,+"Wrong data_size: %llu (desc) != %lld (inode)",+le64_to_cpu(desc->data_size),inode->i_size);+returnERR_PTR(-EINVAL);+}++vi=kmem_cache_zalloc(fsverity_info_cachep,GFP_KERNEL);+if(!vi)+returnERR_PTR(-ENOMEM);+vi->inode=inode;++err=fsverity_init_merkle_tree_params(&vi->tree_params,inode,+desc->hash_algorithm,+desc->log_blocksize,+desc->salt,desc->salt_size);+if(err){+fsverity_err(inode,+"Error %d initializing Merkle tree parameters",+err);+gotoout;+}++memcpy(vi->root_hash,desc->root_hash,vi->tree_params.digest_size);++err=compute_file_measurement(vi->tree_params.hash_alg,desc,+vi->measurement);+if(err){+fsverity_err(vi->inode,"Error %d computing file measurement",+err);+gotoout;+}+pr_debug("Computed file measurement: %s:%*phN\n",+vi->tree_params.hash_alg->name,+vi->tree_params.digest_size,vi->measurement);+out:+if(err){+fsverity_free_info(vi);+vi=ERR_PTR(err);+}+returnvi;+}++voidfsverity_set_info(structinode*inode,structfsverity_info*vi)+{+/*+*Multipleprocessesmayracetoset->i_verity_info,sousecmpxchg.+*ThispairswiththeREAD_ONCE()infsverity_get_info().+*/+if(cmpxchg_release(&inode->i_verity_info,NULL,vi)!=NULL)+fsverity_free_info(vi);+}++voidfsverity_free_info(structfsverity_info*vi)+{+if(!vi)+return;+kfree(vi->tree_params.hashstate);+kmem_cache_free(fsverity_info_cachep,vi);+}++/* Ensure the inode has an ->i_verity_info */+staticintensure_verity_info(structinode*inode)+{+structfsverity_info*vi=fsverity_get_info(inode);+structfsverity_descriptor*desc;+intres;++if(vi)+return0;++res=inode->i_sb->s_vop->get_verity_descriptor(inode,NULL,0);+if(res<0){+fsverity_err(inode,+"Error %d getting verity descriptor size",res);+returnres;+}+if(res>FS_VERITY_MAX_DESCRIPTOR_SIZE){+fsverity_err(inode,"Verity descriptor is too large (%d bytes)",+res);+return-EMSGSIZE;+}+desc=kmalloc(res,GFP_KERNEL);+if(!desc)+return-ENOMEM;+res=inode->i_sb->s_vop->get_verity_descriptor(inode,desc,res);+if(res<0){+fsverity_err(inode,"Error %d reading verity descriptor",res);+gotoout_free_desc;+}++vi=fsverity_create_info(inode,desc,res);+if(IS_ERR(vi)){+res=PTR_ERR(vi);+gotoout_free_desc;+}++fsverity_set_info(inode,vi);+res=0;+out_free_desc:+kfree(desc);+returnres;+}++/**+*fsverity_file_open-preparetoopenaverityfile+*@inode:theinodebeingopened+*@filp:thestructfilebeingsetup+*+*Whenopeningaverityfile,denytheopenifitisforwriting.Otherwise,+*setuptheinode's->i_verity_infoifnotalreadydone.+*+*Whencombinedwithfscrypt,thismustbecalledafterfscrypt_file_open().+*Otherwise,wewon'thavethekeysetuptodecrypttheveritymetadata.+*+*Return:0onsuccess,-errnoonfailure+*/+intfsverity_file_open(structinode*inode,structfile*filp)+{+if(!IS_VERITY(inode))+return0;++if(filp->f_mode&FMODE_WRITE){+pr_debug("Denying opening verity file (ino %lu) for write\n",+inode->i_ino);+return-EPERM;+}++returnensure_verity_info(inode);+}+EXPORT_SYMBOL_GPL(fsverity_file_open);++/**+*fsverity_cleanup_inode-freetheinode'sverityinfo,ifpresent+*+*Filesystemsmustcallthisoninodeevictiontofree->i_verity_info.+*/+voidfsverity_cleanup_inode(structinode*inode)+{+fsverity_free_info(inode->i_verity_info);+inode->i_verity_info=NULL;+}+EXPORT_SYMBOL_GPL(fsverity_cleanup_inode);++int__initfsverity_init_info_cache(void)+{+fsverity_info_cachep=KMEM_CACHE_USERCOPY(fsverity_info,+SLAB_RECLAIM_ACCOUNT,+measurement);+if(!fsverity_info_cachep)+return-ENOMEM;+return0;+}
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:17
From: Eric Biggers <redacted>
Add a function for filesystems to call to implement the
FS_IOC_MEASURE_VERITY ioctl. This ioctl retrieves the file measurement
that fs-verity calculated for the given file and is enforcing for reads;
i.e., reads that don't match this hash will fail. This ioctl can be
used for authentication or logging of file measurements in userspace.
See the "FS_IOC_MEASURE_VERITY" section of
Documentation/filesystems/fsverity.rst for the documentation.
Signed-off-by: Eric Biggers <redacted>
---
fs/verity/Makefile | 1 +
fs/verity/measure.c | 57 ++++++++++++++++++++++++++++++++++++++++
include/linux/fsverity.h | 11 ++++++++
3 files changed, 69 insertions(+)
create mode 100644 fs/verity/measure.c
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:17
From: Eric Biggers <redacted>
To meet some users' needs, add optional support for having fs-verity
handle a portion of the authentication policy in the kernel. An
".fs-verity" keyring is created to which X.509 certificates can be
added; then a sysctl 'fs.verity.require_signatures' can be set to cause
the kernel to enforce that all fs-verity files contain a signature of
their file measurement by a key in this keyring.
See the "Built-in signature verification" section of
Documentation/filesystems/fsverity.rst for the full documentation.
Signed-off-by: Eric Biggers <redacted>
---
fs/verity/Kconfig | 17 +++
fs/verity/Makefile | 2 +
fs/verity/enable.c | 20 +++-
fs/verity/fsverity_private.h | 48 +++++++-
fs/verity/init.c | 6 +
fs/verity/open.c | 25 +++--
fs/verity/signature.c | 207 +++++++++++++++++++++++++++++++++++
fs/verity/verify.c | 6 +
8 files changed, 318 insertions(+), 13 deletions(-)
create mode 100644 fs/verity/signature.c
@@ -147,7 +147,7 @@ static int enable_verity(struct file *filp,conststructfsverity_operations*vops=inode->i_sb->s_vop;structmerkle_tree_paramsparams={};structfsverity_descriptor*desc;-size_tdesc_size=sizeof(*desc);+size_tdesc_size=sizeof(*desc)+arg->sig_size;structfsverity_info*vi;interr;
@@ -169,6 +169,16 @@ static int enable_verity(struct file *filp,}desc->salt_size=arg->salt_size;+/* Get the signature if the user provided one */+if(arg->sig_size&&+copy_from_user(desc->signature,+(constu8__user*)(uintptr_t)arg->sig_ptr,+arg->sig_size)){+err=-EFAULT;+gotoout;+}+desc->sig_size=cpu_to_le32(arg->sig_size);+desc->data_size=cpu_to_le64(inode->i_size);pr_debug("Building Merkle tree...\n");
@@ -209,6 +219,10 @@ static int enable_verity(struct file *filp,gotorollback;}+if(arg->sig_size)+pr_debug("Storing a %u-byte PKCS#7 signature alongside the file\n",+arg->sig_size);+/* Tell the filesystem to finish enabling verity on the file */err=vops->end_enable_verity(filp,desc,desc_size,params.tree_size);if(err){
@@ -78,23 +78,41 @@ struct fsverity_info {};/*-*Merkletreeproperties.Thefilemeasurementisthehashofthisstructure.+*Merkletreeproperties.Thefilemeasurementisthehashofthisstructure+*excludingthesignatureandwiththesig_sizefieldsetto0.*/structfsverity_descriptor{__u8version;/* must be 1 */__u8hash_algorithm;/* Merkle tree hash algorithm */__u8log_blocksize;/* log2 of size of data and tree blocks */__u8salt_size;/* size of salt in bytes; 0 if none */-__le32sig_size;/* reserved, must be 0 */+__le32sig_size;/* size of signature in bytes; 0 if none */__le64data_size;/* size of file the Merkle tree is built over */__u8root_hash[64];/* Merkle tree root hash */__u8salt[32];/* salt prepended to each hashed block */__u8__reserved[144];/* must be 0's */+__u8signature[];/* optional PKCS#7 signature */};/* Arbitrary limit to bound the kmalloc() size. Can be changed. */#define FS_VERITY_MAX_DESCRIPTOR_SIZE 16384+#define FS_VERITY_MAX_SIGNATURE_SIZE (FS_VERITY_MAX_DESCRIPTOR_SIZE - \+sizeof(structfsverity_descriptor))++/*+*Formatinwhichverityfilemeasurementsaresigned.Thisisthesameas+*'structfsverity_digest',exceptheresomemagicbytesareprependedto+*providesomecontextaboutwhatisbeingsignedincasethesamekeyisused+*fornon-fsveritypurposes,andherethefieldshavefixedendianness.+*/+structfsverity_signed_digest{+charmagic[8];/* must be "FSVerity" */+__le16digest_algorithm;+__le16digest_size;+__u8digest[];+};+/* hash_algs.c */externstructfsverity_hash_algfsverity_hash_algs[];
@@ -130,7 +148,7 @@ int fsverity_init_merkle_tree_params(struct merkle_tree_params *params,constu8*salt,size_tsalt_size);structfsverity_info*fsverity_create_info(conststructinode*inode,-constvoid*desc,size_tdesc_size);+void*desc,size_tdesc_size);voidfsverity_set_info(structinode*inode,structfsverity_info*vi);
@@ -128,12 +128,22 @@ int fsverity_init_merkle_tree_params(struct merkle_tree_params *params,returnerr;}-/* Compute the file measurement by hashing the fsverity_descriptor. */+/*+*Computethefilemeasurementbyhashingthefsverity_descriptorexcludingthe+*signatureandwiththesig_sizefieldsetto0.+*/staticintcompute_file_measurement(conststructfsverity_hash_alg*hash_alg,-conststructfsverity_descriptor*desc,+structfsverity_descriptor*desc,u8*measurement){-returnfsverity_hash_buffer(hash_alg,desc,sizeof(*desc),measurement);+__le32sig_size=desc->sig_size;+interr;++desc->sig_size=0;+err=fsverity_hash_buffer(hash_alg,desc,sizeof(*desc),measurement);+desc->sig_size=sig_size;++returnerr;}/*
@@ -141,9 +151,9 @@ static int compute_file_measurement(const struct fsverity_hash_alg *hash_alg,*it.Thesignature(ifpresent)isalsochecked.*/structfsverity_info*fsverity_create_info(conststructinode*inode,-constvoid*_desc,size_tdesc_size)+void*_desc,size_tdesc_size){-conststructfsverity_descriptor*desc=_desc;+structfsverity_descriptor*desc=_desc;structfsverity_info*vi;interr;
@@ -159,8 +169,7 @@ struct fsverity_info *fsverity_create_info(const struct inode *inode,returnERR_PTR(-EINVAL);}-if(desc->sig_size||-memchr_inv(desc->__reserved,0,sizeof(desc->__reserved))){+if(memchr_inv(desc->__reserved,0,sizeof(desc->__reserved))){fsverity_err(inode,"Reserved bits set in descriptor");returnERR_PTR(-EINVAL);}
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:19
From: Eric Biggers <redacted>
Add fs-verity support to f2fs. fs-verity is a filesystem feature that
enables transparent integrity protection and authentication of read-only
files. It uses a dm-verity like mechanism at the file level: a Merkle
tree is used to verify any block in the file in log(filesize) time. It
is implemented mainly by helper functions in fs/verity/. See
Documentation/filesystems/fsverity.rst for the full documentation.
The f2fs support for fs-verity consists of:
- Adding a filesystem feature flag and an inode flag for fs-verity.
- Implementing the fsverity_operations to support enabling verity on an
inode and reading/writing the verity metadata.
- Updating ->readpages() to verify data as it's read from verity files
and to support reading verity metadata pages.
- Updating ->write_begin(), ->write_end(), and ->writepages() to support
writing verity metadata pages.
- Calling the fs-verity hooks for ->open(), ->setattr(), and ->ioctl().
Like ext4, f2fs stores the verity metadata (Merkle tree and
fsverity_descriptor) past the end of the file, starting at the first
page fully beyond i_size. This approach works because (a) verity files
are readonly, and (b) pages fully beyond i_size aren't visible to
userspace but can be read/written internally by f2fs with only some
relatively small changes to f2fs. Extended attributes cannot be used
because (a) f2fs limits the total size of an inode's xattr entries to
4096 bytes, which wouldn't be enough for even a single Merkle tree
block, and (b) f2fs encryption doesn't encrypt xattrs, yet the verity
metadata *must* be encrypted when the file is because it contains hashes
of the plaintext data.
Signed-off-by: Eric Biggers <redacted>
---
fs/f2fs/Makefile | 1 +
fs/f2fs/data.c | 72 +++++++++++++--
fs/f2fs/f2fs.h | 23 ++++-
fs/f2fs/file.c | 40 +++++++++
fs/f2fs/inode.c | 5 +-
fs/f2fs/super.c | 3 +
fs/f2fs/sysfs.c | 11 +++
fs/f2fs/verity.c | 224 +++++++++++++++++++++++++++++++++++++++++++++++
fs/f2fs/xattr.h | 2 +
9 files changed, 367 insertions(+), 14 deletions(-)
create mode 100644 fs/f2fs/verity.c
@@ -2344,6 +2347,7 @@ static inline void f2fs_change_bit(unsigned int nr, char *addr)#define F2FS_TOPDIR_FL 0x00020000 /* Top of directory hierarchies*/#define F2FS_HUGE_FILE_FL 0x00040000 /* Set to each huge file */#define F2FS_EXTENTS_FL 0x00080000 /* Inode uses extents */+#define F2FS_VERITY_FL 0x00100000 /* Verity protected inode */#define F2FS_EA_INODE_FL 0x00200000 /* Inode used for large EA */#define F2FS_EOFBLOCKS_FL 0x00400000 /* Blocks allocated beyond EOF */#define F2FS_NOCOW_FL 0x00800000 /* Do not cow file */
@@ -2351,7 +2355,7 @@ static inline void f2fs_change_bit(unsigned int nr, char *addr)#define F2FS_PROJINHERIT_FL 0x20000000 /* Create with parents projid */#define F2FS_RESERVED_FL 0x80000000 /* reserved for ext4 lib */-#define F2FS_FL_USER_VISIBLE 0x30CBDFFF /* User visible flags */+#define F2FS_FL_USER_VISIBLE 0x30DBDFFF /* User visible flags */#define F2FS_FL_USER_MODIFIABLE 0x204BC0FF /* User modifiable flags *//* Flags we can manipulate with through F2FS_IOC_FSSETXATTR */
@@ -2417,6 +2421,7 @@ enum {FI_PROJ_INHERIT,/* indicate file inherits projectid */FI_PIN_FILE,/* indicate file should not be gced */FI_ATOMIC_REVOKE_REQUEST,/* request to drop atomic data */+FI_VERITY_IN_PROGRESS,/* building fs-verity Merkle tree */};staticinlinevoid__mark_inode_dirty_flag(structinode*inode,
@@ -1656,6 +1664,8 @@ static int f2fs_ioc_getflags(struct file *filp, unsigned long arg)if(IS_ENCRYPTED(inode))flags|=F2FS_ENCRYPT_FL;+if(IS_VERITY(inode))+flags|=F2FS_VERITY_FL;if(f2fs_has_inline_data(inode)||f2fs_has_inline_dentry(inode))flags|=F2FS_INLINE_DATA_FL;if(is_inode_flag_set(inode,FI_PIN_FILE))
@@ -2980,6 +2990,30 @@ static int f2fs_ioc_precache_extents(struct file *filp, unsigned long arg)returnf2fs_precache_extents(file_inode(filp));}+staticintf2fs_ioc_enable_verity(structfile*filp,unsignedlongarg)+{+structinode*inode=file_inode(filp);++f2fs_update_time(F2FS_I_SB(inode),REQ_TIME);++if(!f2fs_sb_has_verity(F2FS_I_SB(inode))){+f2fs_msg(inode->i_sb,KERN_WARNING,+"Can't enable fs-verity on inode %lu: the verity feature is not enabled on this filesystem.\n",+inode->i_ino);+return-EOPNOTSUPP;+}++returnfsverity_ioctl_enable(filp,(constvoid__user*)arg);+}++staticintf2fs_ioc_measure_verity(structfile*filp,unsignedlongarg)+{+if(!f2fs_sb_has_verity(F2FS_I_SB(file_inode(filp))))+return-EOPNOTSUPP;++returnfsverity_ioctl_measure(filp,(void__user*)arg);+}+longf2fs_ioctl(structfile*filp,unsignedintcmd,unsignedlongarg){if(unlikely(f2fs_cp_error(F2FS_I_SB(file_inode(filp)))))
@@ -3036,6 +3070,10 @@ long f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)returnf2fs_ioc_set_pin_file(filp,arg);caseF2FS_IOC_PRECACHE_EXTENTS:returnf2fs_ioc_precache_extents(filp,arg);+caseFS_IOC_ENABLE_VERITY:+returnf2fs_ioc_enable_verity(filp,arg);+caseFS_IOC_MEASURE_VERITY:+returnf2fs_ioc_measure_verity(filp,arg);default:return-ENOTTY;}
@@ -3149,6 +3187,8 @@ long f2fs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)caseF2FS_IOC_GET_PIN_FILE:caseF2FS_IOC_SET_PIN_FILE:caseF2FS_IOC_PRECACHE_EXTENTS:+caseFS_IOC_ENABLE_VERITY:+caseFS_IOC_MEASURE_VERITY:break;default:return-ENOIOCTLCMD;
@@ -0,0 +1,224 @@+// SPDX-License-Identifier: GPL-2.0+/*+*fs/f2fs/verity.c:fs-veritysupportforf2fs+*+*Copyright2019GoogleLLC+*/++/*+*Implementationoffsverity_operationsforf2fs.+*+*Likeext4,f2fsstorestheveritymetadata(Merkletreeand+*fsverity_descriptor)pasttheendofthefile,startingatthefirstpage+*fullybeyondi_size.Thisapproachworksbecause(a)verityfilesare+*readonly,and(b)pagesfullybeyondi_sizearen'tvisibletouserspacebut+*canberead/writteninternallybyf2fswithonlysomerelativelysmall+*changestof2fs.Extendedattributescannotbeusedbecause(a)f2fslimits+*thetotalsizeofaninode'sxattrentriesto4096bytes,whichwouldn'tbe+*enoughforevenasingleMerkletreeblock,and(b)f2fsencryptiondoesn't+*encryptxattrs,yettheveritymetadata*must*beencryptedwhenthefileis+*becauseitcontainshashesoftheplaintextdata.+*/++#include<linux/f2fs_fs.h>++#include"f2fs.h"+#include"xattr.h"++/*+*Readsomeveritymetadatafromtheinode.__vfs_read()can'tbeusedbecause+*weneedtoreadbeyondi_size.+*/+staticintpagecache_read(structinode*inode,void*buf,size_tcount,+loff_tpos)+{+constsize_torig_count=count;++while(count){+size_tn=min_t(size_t,count,+PAGE_SIZE-offset_in_page(pos));+structpage*page;+void*addr;++page=read_mapping_page(inode->i_mapping,pos>>PAGE_SHIFT,+NULL);+if(IS_ERR(page))+returnPTR_ERR(page);++addr=kmap_atomic(page);+memcpy(buf,addr+offset_in_page(pos),n);+kunmap_atomic(addr);++put_page(page);++buf+=n;+pos+=n;+count-=n;+}+returnorig_count;+}++/*+*WritesomeveritymetadatatotheinodeforFS_IOC_ENABLE_VERITY.+*kernel_write()can'tbeusedbecausethefiledescriptorisreadonly.+*/+staticintpagecache_write(structinode*inode,constvoid*buf,size_tcount,+loff_tpos)+{+while(count){+size_tn=min_t(size_t,count,+PAGE_SIZE-offset_in_page(pos));+structpage*page;+void*fsdata;+void*addr;+intres;++res=pagecache_write_begin(NULL,inode->i_mapping,pos,n,0,+&page,&fsdata);+if(res)+returnres;++addr=kmap_atomic(page);+memcpy(addr+offset_in_page(pos),buf,n);+kunmap_atomic(addr);++res=pagecache_write_end(NULL,inode->i_mapping,pos,n,n,+page,fsdata);+if(res<0)+returnres;+if(res!=n)+return-EIO;++buf+=n;+pos+=n;+count-=n;+}+return0;+}++/*+*Formatoff2fsverityxattr.Thispointstothelocationoftheverity+*descriptorwithinthefiledataratherthancontainingitdirectlybecause+*theveritydescriptor*must*beencryptedwhenf2fsencryptionisused.But,+*f2fsencryptiondoesnotencryptxattrs.+*/+structfsverity_descriptor_location{+__le32version;+__le32size;+__le64pos;+};++staticintf2fs_begin_enable_verity(structfile*filp)+{+structinode*inode=file_inode(filp);+interr;++err=f2fs_convert_inline_inode(inode);+if(err)+returnerr;++err=dquot_initialize(inode);+if(err)+returnerr;++set_inode_flag(inode,FI_VERITY_IN_PROGRESS);+return0;+}++staticintf2fs_end_enable_verity(structfile*filp,constvoid*desc,+size_tdesc_size,u64merkle_tree_size)+{+structinode*inode=file_inode(filp);+u64desc_pos=round_up(inode->i_size,PAGE_SIZE)+merkle_tree_size;+structfsverity_descriptor_locationdloc={+.version=cpu_to_le32(1),+.size=cpu_to_le32(desc_size),+.pos=cpu_to_le64(desc_pos),+};+interr=0;++if(desc!=NULL){+/* Succeeded; write the verity descriptor. */+err=pagecache_write(inode,desc,desc_size,desc_pos);++/* Write all pages before clearing FI_VERITY_IN_PROGRESS. */+if(!err)+err=filemap_write_and_wait(inode->i_mapping);+}else{+/* Failed; truncate anything we wrote past i_size. */+f2fs_truncate(inode);+}++clear_inode_flag(inode,FI_VERITY_IN_PROGRESS);++if(desc!=NULL&&!err){+err=f2fs_setxattr(inode,F2FS_XATTR_INDEX_VERITY,+F2FS_XATTR_NAME_VERITY,&dloc,sizeof(dloc),+NULL,XATTR_CREATE);+if(!err){+file_set_verity(inode);+f2fs_set_inode_flags(inode);+f2fs_mark_inode_dirty_sync(inode,true);+}+}+returnerr;+}++staticintf2fs_get_verity_descriptor(structinode*inode,void*buf,+size_tbuf_size)+{+structfsverity_descriptor_locationdloc;+intres;+u32size;+u64pos;++/* Get the descriptor location */+res=f2fs_getxattr(inode,F2FS_XATTR_INDEX_VERITY,+F2FS_XATTR_NAME_VERITY,&dloc,sizeof(dloc),NULL);+if(res<0&&res!=-ERANGE)+returnres;+if(res!=sizeof(dloc)||dloc.version!=cpu_to_le32(1)){+f2fs_msg(inode->i_sb,KERN_WARNING,+"unknown verity xattr format");+return-EINVAL;+}+size=le32_to_cpu(dloc.size);+pos=le64_to_cpu(dloc.pos);++/* Get the descriptor */+if(pos+size<pos||pos+size>inode->i_sb->s_maxbytes||+pos<round_up(inode->i_size,PAGE_SIZE)||size>INT_MAX){+f2fs_msg(inode->i_sb,KERN_WARNING,"invalid verity xattr");+return-EUCLEAN;/* EFSCORRUPTED */+}+if(buf_size==0)+returnsize;+if(size>buf_size)+return-ERANGE;+returnpagecache_read(inode,buf,size,pos);+}++staticstructpage*f2fs_read_merkle_tree_page(structinode*inode,+pgoff_tindex)+{+index+=DIV_ROUND_UP(inode->i_size,PAGE_SIZE);++returnread_mapping_page(inode->i_mapping,index,NULL);+}++staticintf2fs_write_merkle_tree_block(structinode*inode,constvoid*buf,+u64index,intlog_blocksize)+{+loff_tpos=round_up(inode->i_size,PAGE_SIZE)++(index<<log_blocksize);++returnpagecache_write(inode,buf,1<<log_blocksize,pos);+}++conststructfsverity_operationsf2fs_verityops={+.begin_enable_verity=f2fs_begin_enable_verity,+.end_enable_verity=f2fs_end_enable_verity,+.get_verity_descriptor=f2fs_get_verity_descriptor,+.read_merkle_tree_page=f2fs_read_merkle_tree_page,+.write_merkle_tree_block=f2fs_write_merkle_tree_block,+};
@@ -34,8 +34,10 @@#define F2FS_XATTR_INDEX_ADVISE 7/* Should be same as EXT4_XATTR_INDEX_ENCRYPTION */#define F2FS_XATTR_INDEX_ENCRYPTION 9+#define F2FS_XATTR_INDEX_VERITY 11#define F2FS_XATTR_NAME_ENCRYPTION_CONTEXT "c"+#define F2FS_XATTR_NAME_VERITY "v"structf2fs_xattr_header{__le32h_magic;/* magic number for identification */
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:21
From: Eric Biggers <redacted>
Make ext4_mpage_readpages() verify data as it is read from fs-verity
files, using the helper functions from fs/verity/.
To support both encryption and verity simultaneously, this required
refactoring the decryption workflow into a generic "post-read
processing" workflow which can do decryption, verification, or both.
The case where the ext4 block size is not equal to the PAGE_SIZE is not
supported yet, since in that case ext4_mpage_readpages() sometimes falls
back to block_read_full_page(), which does not support fs-verity yet.
Co-developed-by: Theodore Ts'o <tytso@mit.edu>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
Signed-off-by: Eric Biggers <redacted>
---
fs/ext4/ext4.h | 2 +
fs/ext4/inode.c | 2 +
fs/ext4/readpage.c | 207 ++++++++++++++++++++++++++++++++++++++-------
fs/ext4/super.c | 9 +-
4 files changed, 190 insertions(+), 30 deletions(-)
@@ -56,6 +61,100 @@ static inline bool ext4_bio_encrypted(struct bio *bio)#endif}+/* postprocessing steps for read bios */+enumbio_post_read_step{+STEP_INITIAL=0,+STEP_DECRYPT,+STEP_VERITY,+};++structbio_post_read_ctx{+structbio*bio;+structwork_structwork;+unsignedintcur_step;+unsignedintenabled_steps;+};++staticvoid__read_end_io(structbio*bio)+{+structpage*page;+structbio_vec*bv;+structbvec_iter_alliter_all;++bio_for_each_segment_all(bv,bio,iter_all){+page=bv->bv_page;++/* PG_error was set if any post_read step failed */+if(bio->bi_status||PageError(page)){+ClearPageUptodate(page);+/* will re-read again later */+ClearPageError(page);+}else{+SetPageUptodate(page);+}+unlock_page(page);+}+if(bio->bi_private)+mempool_free(bio->bi_private,bio_post_read_ctx_pool);+bio_put(bio);+}++staticvoidbio_post_read_processing(structbio_post_read_ctx*ctx);++staticvoiddecrypt_work(structwork_struct*work)+{+structbio_post_read_ctx*ctx=+container_of(work,structbio_post_read_ctx,work);++fscrypt_decrypt_bio(ctx->bio);++bio_post_read_processing(ctx);+}++staticvoidverity_work(structwork_struct*work)+{+structbio_post_read_ctx*ctx=+container_of(work,structbio_post_read_ctx,work);++fsverity_verify_bio(ctx->bio);++bio_post_read_processing(ctx);+}++staticvoidbio_post_read_processing(structbio_post_read_ctx*ctx)+{+/*+*Weusedifferentworkqueuesfordecryptionandforveritybecause+*veritymayrequirereadingmetadatapagesthatneeddecryption,and+*weshouldn'trecursetothesameworkqueue.+*/+switch(++ctx->cur_step){+caseSTEP_DECRYPT:+if(ctx->enabled_steps&(1<<STEP_DECRYPT)){+INIT_WORK(&ctx->work,decrypt_work);+fscrypt_enqueue_decrypt_work(&ctx->work);+return;+}+ctx->cur_step++;+/* fall-through */+caseSTEP_VERITY:+if(ctx->enabled_steps&(1<<STEP_VERITY)){+INIT_WORK(&ctx->work,verity_work);+fsverity_enqueue_verify_work(&ctx->work);+return;+}+ctx->cur_step++;+/* fall-through */+default:+__read_end_io(ctx->bio);+}+}++staticboolbio_post_read_required(structbio*bio)+{+returnbio->bi_private&&!bio->bi_status;+}+/**I/OcompletionhandlerformultipageBIOs.*
@@ -70,30 +169,53 @@ static inline bool ext4_bio_encrypted(struct bio *bio)*/staticvoidmpage_end_io(structbio*bio){-structbio_vec*bv;-structbvec_iter_alliter_all;+if(bio_post_read_required(bio)){+structbio_post_read_ctx*ctx=bio->bi_private;-if(ext4_bio_encrypted(bio)){-if(bio->bi_status){-fscrypt_release_ctx(bio->bi_private);-}else{-fscrypt_enqueue_decrypt_bio(bio->bi_private,bio);-return;-}+ctx->cur_step=STEP_INITIAL;+bio_post_read_processing(ctx);+return;}-bio_for_each_segment_all(bv,bio,iter_all){-structpage*page=bv->bv_page;+__read_end_io(bio);+}-if(!bio->bi_status){-SetPageUptodate(page);-}else{-ClearPageUptodate(page);-SetPageError(page);-}-unlock_page(page);+staticinlineboolext4_need_verity(conststructinode*inode,pgoff_tidx)+{+returnfsverity_active(inode)&&+idx<DIV_ROUND_UP(inode->i_size,PAGE_SIZE);+}++staticstructbio_post_read_ctx*get_bio_post_read_ctx(structinode*inode,+structbio*bio,+pgoff_tfirst_idx)+{+unsignedintpost_read_steps=0;+structbio_post_read_ctx*ctx=NULL;++if(IS_ENCRYPTED(inode)&&S_ISREG(inode->i_mode))+post_read_steps|=1<<STEP_DECRYPT;++if(ext4_need_verity(inode,first_idx))+post_read_steps|=1<<STEP_VERITY;++if(post_read_steps){+ctx=mempool_alloc(bio_post_read_ctx_pool,GFP_NOFS);+if(!ctx)+returnERR_PTR(-ENOMEM);+ctx->bio=bio;+ctx->enabled_steps=post_read_steps;+bio->bi_private=ctx;}+returnctx;+}-bio_put(bio);+staticinlineloff_text4_readpage_limit(structinode*inode)+{+if(IS_ENABLED(CONFIG_FS_VERITY)&&+(IS_VERITY(inode)||ext4_verity_in_progress(inode)))+returninode->i_sb->s_maxbytes;++returni_size_read(inode);}intext4_mpage_readpages(structaddress_space*mapping,
@@ -141,7 +263,8 @@ int ext4_mpage_readpages(struct address_space *mapping,block_in_file=(sector_t)page->index<<(PAGE_SHIFT-blkbits);last_block=block_in_file+nr_pages*blocks_per_page;-last_block_in_file=(i_size_read(inode)+blocksize-1)>>blkbits;+last_block_in_file=(ext4_readpage_limit(inode)++blocksize-1)>>blkbits;if(last_block>last_block_in_file)last_block=last_block_in_file;page_block=0;
@@ -218,6 +341,9 @@ int ext4_mpage_readpages(struct address_space *mapping,zero_user_segment(page,first_hole<<blkbits,PAGE_SIZE);if(first_hole==0){+if(ext4_need_verity(inode,page->index)&&+!fsverity_verify_page(page))+gotoset_error_page;SetPageUptodate(page);unlock_page(page);gotonext_page;
@@ -241,18 +367,15 @@ int ext4_mpage_readpages(struct address_space *mapping,bio=NULL;}if(bio==NULL){-structfscrypt_ctx*ctx=NULL;+structbio_post_read_ctx*ctx;-if(IS_ENCRYPTED(inode)&&S_ISREG(inode->i_mode)){-ctx=fscrypt_get_ctx(GFP_NOFS);-if(IS_ERR(ctx))-gotoset_error_page;-}bio=bio_alloc(GFP_KERNEL,min_t(int,nr_pages,BIO_MAX_PAGES));-if(!bio){-if(ctx)-fscrypt_release_ctx(ctx);+if(!bio)+gotoset_error_page;+ctx=get_bio_post_read_ctx(inode,bio,page->index);+if(IS_ERR(ctx)){+bio_put(bio);gotoset_error_page;}bio_set_dev(bio,bdev);
@@ -293,3 +416,29 @@ int ext4_mpage_readpages(struct address_space *mapping,submit_bio(bio);return0;}++int__initext4_init_post_read_processing(void)+{+bio_post_read_ctx_cache=+kmem_cache_create("ext4_bio_post_read_ctx",+sizeof(structbio_post_read_ctx),0,0,NULL);+if(!bio_post_read_ctx_cache)+gotofail;+bio_post_read_ctx_pool=+mempool_create_slab_pool(NUM_PREALLOC_POST_READ_CTXS,+bio_post_read_ctx_cache);+if(!bio_post_read_ctx_pool)+gotofail_free_cache;+return0;++fail_free_cache:+kmem_cache_destroy(bio_post_read_ctx_cache);+fail:+return-ENOMEM;+}++voidext4_exit_post_read_processing(void)+{+mempool_destroy(bio_post_read_ctx_pool);+kmem_cache_destroy(bio_post_read_ctx_cache);+}
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:22
From: Eric Biggers <redacted>
Add most of fs-verity support to ext4. fs-verity is a filesystem
feature that enables transparent integrity protection and authentication
of read-only files. It uses a dm-verity like mechanism at the file
level: a Merkle tree is used to verify any block in the file in
log(filesize) time. It is implemented mainly by helper functions in
fs/verity/. See Documentation/filesystems/fsverity.rst for the full
documentation.
This commit adds all of ext4 fs-verity support except for the actual
data verification, including:
- Adding a filesystem feature flag and an inode flag for fs-verity.
- Implementing the fsverity_operations to support enabling verity on an
inode and reading/writing the verity metadata.
- Updating ->write_begin(), ->write_end(), and ->writepages() to support
writing verity metadata pages.
- Calling the fs-verity hooks for ->open(), ->setattr(), and ->ioctl().
ext4 stores the verity metadata (Merkle tree and fsverity_descriptor)
past the end of the file, starting at the first page fully beyond
i_size. This approach works because (a) verity files are readonly, and
(b) pages fully beyond i_size aren't visible to userspace but can be
read/written internally by ext4 with only some relatively small changes
to ext4. This approach avoids having to depend on the EA_INODE feature
and on rearchitecturing ext4's xattr support to support paging
multi-gigabyte xattrs into memory, and to support encrypting xattrs.
Note that the verity metadata *must* be encrypted when the file is,
since it contains hashes of the plaintext data.
This patch incorporates work by Theodore Ts'o and Chandan Rajendra.
Signed-off-by: Eric Biggers <redacted>
---
fs/ext4/Makefile | 1 +
fs/ext4/ext4.h | 21 +++-
fs/ext4/file.c | 4 +
fs/ext4/inode.c | 46 +++++---
fs/ext4/ioctl.c | 12 +++
fs/ext4/super.c | 9 ++
fs/ext4/sysfs.c | 6 ++
fs/ext4/verity.c | 272 +++++++++++++++++++++++++++++++++++++++++++++++
fs/ext4/xattr.h | 2 +
9 files changed, 358 insertions(+), 15 deletions(-)
create mode 100644 fs/ext4/verity.c
@@ -395,6 +396,7 @@ struct flex_groups {#define EXT4_TOPDIR_FL 0x00020000 /* Top of directory hierarchies*/#define EXT4_HUGE_FILE_FL 0x00040000 /* Set to each huge file */#define EXT4_EXTENTS_FL 0x00080000 /* Inode uses extents */+#define EXT4_VERITY_FL 0x00100000 /* Verity protected inode */#define EXT4_EA_INODE_FL 0x00200000 /* Inode used for large EA */#define EXT4_EOFBLOCKS_FL 0x00400000 /* Blocks allocated beyond EOF */#define EXT4_INLINE_DATA_FL 0x10000000 /* Inode has inline data. */
@@ -402,7 +404,7 @@ struct flex_groups {#define EXT4_CASEFOLD_FL 0x40000000 /* Casefolded file */#define EXT4_RESERVED_FL 0x80000000 /* reserved for ext4 lib */-#define EXT4_FL_USER_VISIBLE 0x704BDFFF /* User visible flags */+#define EXT4_FL_USER_VISIBLE 0x705BDFFF /* User visible flags */#define EXT4_FL_USER_MODIFIABLE 0x604BC0FF /* User modifiable flags *//* Flags we can manipulate with through EXT4_IOC_FSSETXATTR */
@@ -466,6 +468,7 @@ enum {EXT4_INODE_TOPDIR=17,/* Top of directory hierarchies*/EXT4_INODE_HUGE_FILE=18,/* Set to each huge file */EXT4_INODE_EXTENTS=19,/* Inode uses extents */+EXT4_INODE_VERITY=20,/* Verity protected inode */EXT4_INODE_EA_INODE=21,/* Inode used for large EA */EXT4_INODE_EOFBLOCKS=22,/* Blocks allocated beyond EOF */EXT4_INODE_INLINE_DATA=28,/* Data in inode. */
@@ -1559,6 +1563,7 @@ enum {EXT4_STATE_MAY_INLINE_DATA,/* may have in-inode data */EXT4_STATE_EXT_PRECACHED,/* extents have been precached */EXT4_STATE_LUSTRE_EA_INODE,/* Lustre-style ea_inode */+EXT4_STATE_VERITY_IN_PROGRESS,/* building fs-verity Merkle tree */};#define EXT4_INODE_BIT_FNS(name, field, offset) \
@@ -1390,6 +1390,7 @@ static int ext4_write_end(struct file *file,intret=0,ret2;inti_size_changed=0;intinline_data=ext4_has_inline_data(inode);+boolverity=ext4_verity_in_progress(inode);trace_ext4_write_end(inode,pos,len,copied);if(inline_data){
@@ -1407,12 +1408,16 @@ static int ext4_write_end(struct file *file,/**it'simportanttoupdatei_sizewhilestillholdingpagelock:*pagewriteoutcouldotherwisecomeinandzerobeyondi_size.+*+*IfFS_IOC_ENABLE_VERITYisrunningonthisinode,thenMerkletree+*blocksarebeingwrittenpastEOF,soskipthei_sizeupdate.*/-i_size_changed=ext4_update_inode_size(inode,pos+copied);+if(!verity)+i_size_changed=ext4_update_inode_size(inode,pos+copied);unlock_page(page);put_page(page);-if(old_size<pos)+if(old_size<pos&&!verity)pagecache_isize_extended(inode,old_size,pos);/**Don'tmarktheinodedirtyunderpagelock.First,itunnecessarily
@@ -1423,7 +1428,7 @@ static int ext4_write_end(struct file *file,if(i_size_changed||inline_data)ext4_mark_inode_dirty(handle,inode);-if(pos+len>inode->i_size&&ext4_can_truncate(inode))+if(pos+len>inode->i_size&&!verity&&ext4_can_truncate(inode))/* if we have allocated more blocks and copied*less.Wewillhaveblocksallocatedoutside*inode->i_size.Sotruncatethem
@@ -1434,7 +1439,7 @@ static int ext4_write_end(struct file *file,if(!ret)ret=ret2;-if(pos+len>inode->i_size){+if(pos+len>inode->i_size&&!verity){ext4_truncate_failed_write(inode);/**Iftruncatefailedearlytheinodemightstillbe
@@ -1495,6 +1500,7 @@ static int ext4_journalled_write_end(struct file *file,unsignedfrom,to;intsize_changed=0;intinline_data=ext4_has_inline_data(inode);+boolverity=ext4_verity_in_progress(inode);trace_ext4_journalled_write_end(inode,pos,len,copied);from=pos&(PAGE_SIZE-1);
@@ -1524,13 +1530,14 @@ static int ext4_journalled_write_end(struct file *file,if(!partial)SetPageUptodate(page);}-size_changed=ext4_update_inode_size(inode,pos+copied);+if(!verity)+size_changed=ext4_update_inode_size(inode,pos+copied);ext4_set_inode_state(inode,EXT4_STATE_JDATA);EXT4_I(inode)->i_datasync_tid=handle->h_transaction->t_tid;unlock_page(page);put_page(page);-if(old_size<pos)+if(old_size<pos&&!verity)pagecache_isize_extended(inode,old_size,pos);if(size_changed||inline_data){
@@ -1539,7 +1546,7 @@ static int ext4_journalled_write_end(struct file *file,ret=ret2;}-if(pos+len>inode->i_size&&ext4_can_truncate(inode))+if(pos+len>inode->i_size&&!verity&&ext4_can_truncate(inode))/* if we have allocated more blocks and copied*less.Wewillhaveblocksallocatedoutside*inode->i_size.Sotruncatethem
@@ -1550,7 +1557,7 @@ static int ext4_journalled_write_end(struct file *file,ret2=ext4_journal_stop(handle);if(!ret)ret=ret2;-if(pos+len>inode->i_size){+if(pos+len>inode->i_size&&!verity){ext4_truncate_failed_write(inode);/**Iftruncatefailedearlytheinodemightstillbe
@@ -2146,7 +2153,8 @@ static int ext4_writepage(struct page *page,trace_ext4_writepage(page);size=i_size_read(inode);-if(page->index==size>>PAGE_SHIFT)+if(page->index==size>>PAGE_SHIFT&&+!ext4_verity_in_progress(inode))len=size&~PAGE_MASK;elselen=PAGE_SIZE;
@@ -1092,6 +1092,16 @@ long ext4_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)caseEXT4_IOC_GET_ENCRYPTION_POLICY:returnfscrypt_ioctl_get_policy(filp,(void__user*)arg);+caseFS_IOC_ENABLE_VERITY:+if(!ext4_has_feature_verity(sb))+return-EOPNOTSUPP;+returnfsverity_ioctl_enable(filp,(constvoid__user*)arg);++caseFS_IOC_MEASURE_VERITY:+if(!ext4_has_feature_verity(sb))+return-EOPNOTSUPP;+returnfsverity_ioctl_measure(filp,(void__user*)arg);+caseEXT4_IOC_FSGETXATTR:{structfsxattrfa;
@@ -1210,6 +1220,8 @@ long ext4_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)caseEXT4_IOC_SET_ENCRYPTION_POLICY:caseEXT4_IOC_GET_ENCRYPTION_PWSALT:caseEXT4_IOC_GET_ENCRYPTION_POLICY:+caseFS_IOC_ENABLE_VERITY:+caseFS_IOC_MEASURE_VERITY:caseEXT4_IOC_SHUTDOWN:caseFS_IOC_GETFSMAP:break;
@@ -0,0 +1,272 @@+// SPDX-License-Identifier: GPL-2.0+/*+*fs/ext4/verity.c:fs-veritysupportforext4+*+*Copyright2019GoogleLLC+*/++/*+*Implementationoffsverity_operationsforext4.+*+*ext4storestheveritymetadata(Merkletreeandfsverity_descriptor)past+*theendofthefile,startingatthefirstpagefullybeyondi_size.This+*approachworksbecause(a)verityfilesarereadonly,and(b)pagesfully+*beyondi_sizearen'tvisibletouserspacebutcanberead/writteninternally+*byext4withonlysomerelativelysmallchangestoext4.Thisapproach+*avoidshavingtodependontheEA_INODEfeatureandonrearchitecturing+*ext4'sxattrsupporttosupportpagingmulti-gigabytexattrsintomemory,and+*tosupportencryptingxattrs.Notethattheveritymetadata*must*be+*encryptedwhenthefileis,sinceitcontainshashesoftheplaintextdata.+*/++#include<linux/quotaops.h>++#include"ext4.h"+#include"ext4_jbd2.h"+#include"xattr.h"++/*+*Readsomeveritymetadatafromtheinode.__vfs_read()can'tbeusedbecause+*weneedtoreadbeyondi_size.+*/+staticintpagecache_read(structinode*inode,void*buf,size_tcount,+loff_tpos)+{+constsize_torig_count=count;++while(count){+size_tn=min_t(size_t,count,+PAGE_SIZE-offset_in_page(pos));+structpage*page;+void*addr;++page=read_mapping_page(inode->i_mapping,pos>>PAGE_SHIFT,+NULL);+if(IS_ERR(page))+returnPTR_ERR(page);++addr=kmap_atomic(page);+memcpy(buf,addr+offset_in_page(pos),n);+kunmap_atomic(addr);++put_page(page);++buf+=n;+pos+=n;+count-=n;+}+returnorig_count;+}++/*+*WritesomeveritymetadatatotheinodeforFS_IOC_ENABLE_VERITY.+*kernel_write()can'tbeusedbecausethefiledescriptorisreadonly.+*/+staticintpagecache_write(structinode*inode,constvoid*buf,size_tcount,+loff_tpos)+{+while(count){+size_tn=min_t(size_t,count,+PAGE_SIZE-offset_in_page(pos));+structpage*page;+void*fsdata;+void*addr;+intres;++res=pagecache_write_begin(NULL,inode->i_mapping,pos,n,0,+&page,&fsdata);+if(res)+returnres;++addr=kmap_atomic(page);+memcpy(addr+offset_in_page(pos),buf,n);+kunmap_atomic(addr);++res=pagecache_write_end(NULL,inode->i_mapping,pos,n,n,+page,fsdata);+if(res<0)+returnres;+if(res!=n)+return-EIO;++buf+=n;+pos+=n;+count-=n;+}+return0;+}++/*+*Formatofext4verityxattr.Thispointstothelocationoftheverity+*descriptorwithinthefiledataratherthancontainingitdirectlybecause+*theveritydescriptor*must*beencryptedwhenext4encryptionisused.But,+*ext4encryptiondoesnotencryptxattrs.+*/+structfsverity_descriptor_location{+__le32version;+__le32size;+__le64pos;+};++staticintext4_begin_enable_verity(structfile*filp)+{+structinode*inode=file_inode(filp);+intcredits=2;/* superblock and inode for ext4_orphan_add() */+handle_t*handle;+interr;++err=ext4_convert_inline_data(inode);+if(err)+returnerr;++err=ext4_inode_attach_jinode(inode);+if(err)+returnerr;++err=dquot_initialize(inode);+if(err)+returnerr;++handle=ext4_journal_start(inode,EXT4_HT_INODE,credits);+if(IS_ERR(handle))+returnPTR_ERR(handle);++err=ext4_orphan_add(handle,inode);+if(err==0)+ext4_set_inode_state(inode,EXT4_STATE_VERITY_IN_PROGRESS);++ext4_journal_stop(handle);+returnerr;+}++staticintext4_end_enable_verity(structfile*filp,constvoid*desc,+size_tdesc_size,u64merkle_tree_size)+{+structinode*inode=file_inode(filp);+u64desc_pos=round_up(inode->i_size,PAGE_SIZE)+merkle_tree_size;+structfsverity_descriptor_locationdloc={+.version=cpu_to_le32(1),+.size=cpu_to_le32(desc_size),+.pos=cpu_to_le64(desc_pos),+};+intcredits=0;+handle_t*handle;+interr1=0;+interr;++if(desc!=NULL){+/* Succeeded; write the verity descriptor. */+err1=pagecache_write(inode,desc,desc_size,desc_pos);++/* Write all pages before clearing VERITY_IN_PROGRESS. */+if(!err1)+err1=filemap_write_and_wait(inode->i_mapping);++if(!err1)+err1=ext4_xattr_set_credits(inode,sizeof(dloc),true,+&credits);+}else{+/* Failed; truncate anything we wrote past i_size. */+ext4_truncate(inode);+}++/*+*WemustalwayscleanupbyclearingEXT4_STATE_VERITY_IN_PROGRESSand+*deletingtheinodefromtheorphanlist,evenifsomethingfailed.+*Ifeverythingsucceeded,we'llalsosettheveritybitanddescriptor+*locationxattrinthesametransaction.+*/++ext4_clear_inode_state(inode,EXT4_STATE_VERITY_IN_PROGRESS);++credits+=2;/* superblock and inode for ext4_orphan_del() */++handle=ext4_journal_start(inode,EXT4_HT_INODE,credits);+if(IS_ERR(handle)){+ext4_orphan_del(NULL,inode);+returnPTR_ERR(handle);+}++err=ext4_orphan_del(handle,inode);+if(err)+gotoout_stop;++if(desc!=NULL&&!err1){+structext4_ilociloc;++err=ext4_xattr_set_handle(handle,inode,+EXT4_XATTR_INDEX_VERITY,+EXT4_XATTR_NAME_VERITY,+&dloc,sizeof(dloc),XATTR_CREATE);+if(err)+gotoout_stop;++err=ext4_reserve_inode_write(handle,inode,&iloc);+if(err)+gotoout_stop;+ext4_set_inode_flag(inode,EXT4_INODE_VERITY);+ext4_set_inode_flags(inode);+err=ext4_mark_iloc_dirty(handle,inode,&iloc);+}+out_stop:+ext4_journal_stop(handle);+returnerr?:err1;+}++staticintext4_get_verity_descriptor(structinode*inode,void*buf,+size_tbuf_size)+{+structfsverity_descriptor_locationdloc;+intres;+u32size;+u64pos;++/* Get the descriptor location */+res=ext4_xattr_get(inode,EXT4_XATTR_INDEX_VERITY,+EXT4_XATTR_NAME_VERITY,&dloc,sizeof(dloc));+if(res<0&&res!=-ERANGE)+returnres;+if(res!=sizeof(dloc)||dloc.version!=cpu_to_le32(1)){+ext4_warning_inode(inode,"unknown verity xattr format");+return-EINVAL;+}+size=le32_to_cpu(dloc.size);+pos=le64_to_cpu(dloc.pos);++/* Get the descriptor */+if(pos+size<pos||pos+size>inode->i_sb->s_maxbytes||+pos<round_up(inode->i_size,PAGE_SIZE)||size>INT_MAX){+ext4_warning_inode(inode,"invalid verity xattr");+return-EFSCORRUPTED;+}+if(buf_size==0)+returnsize;+if(size>buf_size)+return-ERANGE;+returnpagecache_read(inode,buf,size,pos);+}++staticstructpage*ext4_read_merkle_tree_page(structinode*inode,+pgoff_tindex)+{+index+=DIV_ROUND_UP(inode->i_size,PAGE_SIZE);++returnread_mapping_page(inode->i_mapping,index,NULL);+}++staticintext4_write_merkle_tree_block(structinode*inode,constvoid*buf,+u64index,intlog_blocksize)+{+loff_tpos=round_up(inode->i_size,PAGE_SIZE)++(index<<log_blocksize);++returnpagecache_write(inode,buf,1<<log_blocksize,pos);+}++conststructfsverity_operationsext4_verityops={+.begin_enable_verity=ext4_begin_enable_verity,+.end_enable_verity=ext4_end_enable_verity,+.get_verity_descriptor=ext4_get_verity_descriptor,+.read_merkle_tree_page=ext4_read_merkle_tree_page,+.write_merkle_tree_block=ext4_write_merkle_tree_block,+};
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:24
From: Eric Biggers <redacted>
Add a function for filesystems to call to implement the
FS_IOC_ENABLE_VERITY ioctl. This ioctl enables fs-verity on a file.
See the "FS_IOC_ENABLE_VERITY" section of
Documentation/filesystems/fsverity.rst for the documentation.
Signed-off-by: Eric Biggers <redacted>
---
fs/verity/Makefile | 3 +-
fs/verity/enable.c | 339 +++++++++++++++++++++++++++++++++++++++
include/linux/fsverity.h | 64 ++++++++
3 files changed, 405 insertions(+), 1 deletion(-)
create mode 100644 fs/verity/enable.c
@@ -0,0 +1,339 @@+// SPDX-License-Identifier: GPL-2.0+/*+*fs/verity/enable.c:ioctltoenableverityonafile+*+*Copyright2019GoogleLLC+*/++#include"fsverity_private.h"++#include<crypto/hash.h>+#include<linux/mount.h>+#include<linux/pagemap.h>+#include<linux/sched/signal.h>+#include<linux/uaccess.h>++staticintbuild_merkle_tree_level(structinode*inode,unsignedintlevel,+u64num_blocks_to_hash,+conststructmerkle_tree_params*params,+u8*pending_hashes,+structahash_request*req)+{+conststructfsverity_operations*vops=inode->i_sb->s_vop;+unsignedintpending_size=0;+u64dst_block_num;+u64i;+interr;++if(WARN_ON(params->block_size!=PAGE_SIZE))/* checked earlier too */+return-EINVAL;++if(level<params->num_levels){+dst_block_num=params->level_start[level];+}else{+if(WARN_ON(num_blocks_to_hash!=1))+return-EINVAL;+dst_block_num=0;/* unused */+}++for(i=0;i<num_blocks_to_hash;i++){+structpage*src_page;++if((pgoff_t)i%10000==0||i+1==num_blocks_to_hash)+pr_debug("Hashing block %llu of %llu for level %u\n",+i+1,num_blocks_to_hash,level);++if(level==0)+/* Leaf: hashing a data block */+src_page=read_mapping_page(inode->i_mapping,i,NULL);+else+/* Non-leaf: hashing hash block from level below */+src_page=vops->read_merkle_tree_page(inode,+params->level_start[level-1]+i);+if(IS_ERR(src_page)){+err=PTR_ERR(src_page);+fsverity_err(inode,+"Error %d reading Merkle tree page %llu",+err,params->level_start[level-1]+i);+returnerr;+}++err=fsverity_hash_page(params,inode,req,src_page,+&pending_hashes[pending_size]);+put_page(src_page);+if(err)+returnerr;+pending_size+=params->digest_size;++if(level==params->num_levels)/* Root hash? */+return0;++if(pending_size+params->digest_size>params->block_size||+i+1==num_blocks_to_hash){+/* Flush the pending hash block */+memset(&pending_hashes[pending_size],0,+params->block_size-pending_size);+err=vops->write_merkle_tree_block(inode,+pending_hashes,+dst_block_num,+params->log_blocksize);+if(err){+fsverity_err(inode,+"Error %d writing Merkle tree block %llu",+err,dst_block_num);+returnerr;+}+dst_block_num++;+pending_size=0;+}++if(fatal_signal_pending(current))+return-EINTR;+cond_resched();+}+return0;+}++/*+*BuildtheMerkletreeforthegiveninodeusingthegivenparameters,and+*returntheroothashin@root_hash.+*+*Thetreeiswrittentoafilesystem-specificlocationasdeterminedbythe+*->write_merkle_tree_block()method.However,theblocksthatcomprisethe+*treearethesameforallfilesystems.+*/+staticintbuild_merkle_tree(structinode*inode,+conststructmerkle_tree_params*params,+u8*root_hash)+{+u8*pending_hashes;+structahash_request*req;+u64blocks;+unsignedintlevel;+interr=-ENOMEM;++pending_hashes=kmalloc(params->block_size,GFP_KERNEL);+req=ahash_request_alloc(params->hash_alg->tfm,GFP_KERNEL);+if(!pending_hashes||!req)+gotoout;++/*+*BuildeachleveloftheMerkletree,startingattheleaflevel+*(level0)andascendingtotherootnode(level'num_levels-1').+*Thenattheend(level'num_levels'),calculatetheroothash.+*/+blocks=(params->data_size+params->block_size-1)>>+params->log_blocksize;+for(level=0;level<=params->num_levels;level++){+err=build_merkle_tree_level(inode,level,blocks,params,+pending_hashes,req);+if(err)+gotoout;+blocks=(blocks+params->hashes_per_block-1)>>+params->log_arity;+}+memcpy(root_hash,pending_hashes,params->digest_size);+err=0;+out:+kfree(pending_hashes);+ahash_request_free(req);+returnerr;+}++staticintenable_verity(structfile*filp,+conststructfsverity_enable_arg*arg)+{+structinode*inode=file_inode(filp);+conststructfsverity_operations*vops=inode->i_sb->s_vop;+structmerkle_tree_paramsparams={};+structfsverity_descriptor*desc;+size_tdesc_size=sizeof(*desc);+structfsverity_info*vi;+interr;++/* Start initializing the fsverity_descriptor */+desc=kzalloc(desc_size,GFP_KERNEL);+if(!desc)+return-ENOMEM;+desc->version=1;+desc->hash_algorithm=arg->hash_algorithm;+desc->log_blocksize=ilog2(arg->block_size);++/* Get the salt if the user provided one */+if(arg->salt_size&&+copy_from_user(desc->salt,+(constu8__user*)(uintptr_t)arg->salt_ptr,+arg->salt_size)){+err=-EFAULT;+gotoout;+}+desc->salt_size=arg->salt_size;++desc->data_size=cpu_to_le64(inode->i_size);++pr_debug("Building Merkle tree...\n");++/* Prepare the Merkle tree parameters */+err=fsverity_init_merkle_tree_params(¶ms,inode,+arg->hash_algorithm,+desc->log_blocksize,+desc->salt,desc->salt_size);+if(err)+gotoout;++/* Tell the filesystem that verity is being enabled on the file */+err=vops->begin_enable_verity(filp);+if(err)+gotoout;++/* Build the Merkle tree */+BUILD_BUG_ON(sizeof(desc->root_hash)<FS_VERITY_MAX_DIGEST_SIZE);+err=build_merkle_tree(inode,¶ms,desc->root_hash);+if(err){+fsverity_err(inode,"Error %d building Merkle tree",err);+gotorollback;+}+pr_debug("Done building Merkle tree. Root hash is %s:%*phN\n",+params.hash_alg->name,params.digest_size,desc->root_hash);++/*+*Createthefsverity_info.Don'tbothertryingtosaveworkby+*reusingthemerkle_tree_paramsfromabove.Instead,justcreatethe+*fsverity_infofromthefsverity_descriptorasifitwerejustloaded+*fromdisk.Thisissimpler,anditservesasanextracheckthatthe+*metadatawe'rewritingisvalidbeforeactuallyenablingverity.+*/+vi=fsverity_create_info(inode,desc,desc_size);+if(IS_ERR(vi)){+err=PTR_ERR(vi);+gotorollback;+}++/* Tell the filesystem to finish enabling verity on the file */+err=vops->end_enable_verity(filp,desc,desc_size,params.tree_size);+if(err){+fsverity_err(inode,"%ps() failed with err %d",+vops->end_enable_verity,err);+fsverity_free_info(vi);+}else{+/* Successfully enabled verity */++WARN_ON(!IS_VERITY(inode));++/*+*Readerscanstartusing->i_verity_infoimmediately,soit+*can'tberolledbackonceset.Sodon'tsetituntiljust+*afterthefilesystemhassuccessfullyenabledverity.+*/+fsverity_set_info(inode,vi);+}+out:+kfree(params.hashstate);+kfree(desc);+returnerr;++rollback:+(void)vops->end_enable_verity(filp,NULL,0,params.tree_size);+gotoout;+}++/**+*fsverity_ioctl_enable()-enableverityonafile+*+*Enablefs-verityonafile.Seethe"FS_IOC_ENABLE_VERITY"sectionof+*Documentation/filesystems/fsverity.rstforthedocumentation.+*+*Return:0onsuccess,-errnoonfailure+*/+intfsverity_ioctl_enable(structfile*filp,constvoid__user*uarg)+{+structinode*inode=file_inode(filp);+structfsverity_enable_argarg;+interr;++if(copy_from_user(&arg,uarg,sizeof(arg)))+return-EFAULT;++if(arg.version!=1)+return-EINVAL;++if(arg.__reserved1||+memchr_inv(arg.__reserved2,0,sizeof(arg.__reserved2)))+return-EINVAL;++if(arg.block_size!=PAGE_SIZE)+return-EINVAL;++if(arg.salt_size>FIELD_SIZEOF(structfsverity_descriptor,salt))+return-EMSGSIZE;++if(arg.sig_size)+return-EINVAL;++/*+*Requirearegularfilewithwriteaccess.Buttheactualfdmust+*stillbereadonlysothatwecanlockoutallwriters.Thisis+*neededtoguaranteethatnowritablefdsexisttothefileonceit+*hasverityenabled,andtostabilizethedatabeinghashed.+*/++err=inode_permission(inode,MAY_WRITE);+if(err)+returnerr;++if(IS_APPEND(inode))+return-EPERM;++if(S_ISDIR(inode->i_mode))+return-EISDIR;++if(!S_ISREG(inode->i_mode))+return-EINVAL;++err=mnt_want_write_file(filp);+if(err)/* -EROFS */+returnerr;++err=deny_write_access(filp);+if(err)/* -ETXTBSY */+gotoout_drop_write;++inode_lock(inode);++if(IS_VERITY(inode)){+err=-EEXIST;+gotoout_unlock;+}++if(inode->i_size<=0){+err=-EINVAL;+gotoout_unlock;+}++err=enable_verity(filp,&arg);+if(err)+gotoout_unlock;++/*+*Somepagesofthefilemayhavebeenevictedfrompagecacheafter+*beingusedintheMerkletreeconstruction,thenreadintopagecache+*againbyanotherprocessreadingfromthefileconcurrently.Since+*thesepagesdidn'tundergoverificationagainstthefilemeasurement+*whichfs-veritynowclaimstobeenforcing,wehavetowipethe+*pagecachetoensurethatallfuturereadsareverified.+*/+filemap_write_and_wait(inode->i_mapping);+truncate_inode_pages(inode->i_mapping,0);++/*+*allow_write_access()isneededtopairwithdeny_write_access().+*Regardless,thefilesystemwon'tallowwritingtoverityfiles.+*/+out_unlock:+inode_unlock(inode);+allow_write_access(filp);+out_drop_write:+mnt_drop_write_file(filp);+returnerr;+}+EXPORT_SYMBOL_GPL(fsverity_ioctl_enable);
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:25
From: Eric Biggers <redacted>
Add SHA-512 support to fs-verity. This is primarily a demonstration of
the trivial changes needed to support a new hash algorithm in fs-verity;
most users will still use SHA-256, due to the smaller space required to
store the hashes. But some users may prefer SHA-512.
Signed-off-by: Eric Biggers <redacted>
---
fs/verity/fsverity_private.h | 2 +-
fs/verity/hash_algs.c | 5 +++++
include/uapi/linux/fsverity.h | 1 +
3 files changed, 7 insertions(+), 1 deletion(-)
@@ -0,0 +1,38 @@+# SPDX-License-Identifier: GPL-2.0++configFS_VERITY+bool"FS Verity (read-only file-based authenticity protection)"+selectCRYPTO+# SHA-256 is selected as it's intended to be the default hash algorithm.+# To avoid bloat, other wanted algorithms must be selected explicitly.+selectCRYPTO_SHA256+help+Thisoptionenablesfs-verity.fs-verityisthedm-verity+mechanismimplementedatthefilelevel.Onsupported+filesystems(currentlyEXT4andF2FS),userspacecanusean+ioctltoenableverityforafile,whichcausesthefilesystem+tobuildaMerkletreeforthefile.Thefilesystemwillthen+transparentlyverifyanydatareadfromthefileagainstthe+Merkletree.Thefileisalsomaderead-only.++Thisservesasanintegritycheck,buttheavailabilityofthe+Merkletreeroothashalsoallowsefficientlysupporting+varioususecaseswherenormallythewholefilewouldneedto+behashedatonce,suchas:(a)auditing(loggingthefile's+hash),or(b)authenticityverification(comparingthehash+againstaknowngoodvalue,e.g.fromadigitalsignature).++fs-verityisespeciallyusefulonlargefileswherenotall+thecontentsmayactuallybeneeded.Also,fs-verityverifies+dataeachtimeitispagedbackin,whichprovidesbetter+protectionagainstmaliciousdisksvs.anahead-of-timehash.++Ifunsure,sayN.++configFS_VERITY_DEBUG+bool"FS Verity debugging"+depends onFS_VERITY+help+Enabledebuggingmessagesrelatedtofs-veritybydefault.++SayNunlessyouareanfs-veritydeveloper.
@@ -0,0 +1,91 @@+/* SPDX-License-Identifier: GPL-2.0 */+/*+*fs-verity:read-onlyfile-basedauthenticityprotection+*+*Copyright2019GoogleLLC+*/++#ifndef _FSVERITY_PRIVATE_H+#define _FSVERITY_PRIVATE_H++#ifdef CONFIG_FS_VERITY_DEBUG+#define DEBUG+#endif++#define pr_fmt(fmt) "fs-verity: " fmt++#include<crypto/sha.h>+#include<linux/fs.h>+#include<uapi/linux/fsverity.h>++structahash_request;++/*+*MaximumdepthoftheMerkletree.Upto64levelsaretheoreticallypossible+*withaverysmallblocksize,butwe'dliketolimitstackusageduring+*verification,andinpracticethisisplenty.E.g.,withSHA-256and4K+*blocks,afilewithsizeUINT64_MAXbytesneedsjust8levels.+*/+#define FS_VERITY_MAX_LEVELS 16++/*+*Largestdigestsizeamongallhashalgorithmssupportedbyfs-verity.+*Currentlyassumedtobe<=sizeoffsverity_descriptor::root_hash.+*/+#define FS_VERITY_MAX_DIGEST_SIZE SHA256_DIGEST_SIZE++/* A hash algorithm supported by fs-verity */+structfsverity_hash_alg{+structcrypto_ahash*tfm;/* hash tfm, allocated on demand */+constchar*name;/* crypto API name, e.g. sha256 */+unsignedintdigest_size;/* digest size in bytes, e.g. 32 for SHA-256 */+unsignedintblock_size;/* block size in bytes, e.g. 64 for SHA-256 */+};++/* Merkle tree parameters: hash algorithm, initial hash state, and topology */+structmerkle_tree_params{+conststructfsverity_hash_alg*hash_alg;/* the hash algorithm */+constu8*hashstate;/* initial hash state or NULL */+unsignedintdigest_size;/* same as hash_alg->digest_size */+unsignedintblock_size;/* size of data and tree blocks */+unsignedinthashes_per_block;/* number of hashes per tree block */+unsignedintlog_blocksize;/* log2(block_size) */+unsignedintlog_arity;/* log2(hashes_per_block) */+unsignedintnum_levels;/* number of levels in Merkle tree */+u64data_size;/* data size in bytes */+u64tree_size;/* Merkle tree size in bytes */++/*+*Startingblockindexforeachtreelevel,orderedfromleaflevel(0)+*torootlevel('num_levels-1')+*/+u64level_start[FS_VERITY_MAX_LEVELS];+};++/* hash_algs.c */++externstructfsverity_hash_algfsverity_hash_algs[];++conststructfsverity_hash_alg*fsverity_get_hash_alg(conststructinode*inode,+unsignedintnum);+constu8*fsverity_prepare_hash_state(conststructfsverity_hash_alg*alg,+constu8*salt,size_tsalt_size);+intfsverity_hash_page(conststructmerkle_tree_params*params,+conststructinode*inode,+structahash_request*req,structpage*page,u8*out);+intfsverity_hash_buffer(conststructfsverity_hash_alg*alg,+constvoid*data,size_tsize,u8*out);+void__initfsverity_check_hash_algs(void);++/* init.c */++externvoid__printf(3,4)__cold+fsverity_msg(conststructinode*inode,constchar*level,+constchar*fmt,...);++#define fsverity_warn(inode, fmt, ...) \+fsverity_msg((inode),KERN_WARNING,fmt,##__VA_ARGS__)+#define fsverity_err(inode, fmt, ...) \+fsverity_msg((inode),KERN_ERR,fmt,##__VA_ARGS__)++#endif /* _FSVERITY_PRIVATE_H */
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:29
From: Eric Biggers <redacted>
Add a function fsverity_prepare_setattr() which filesystems that support
fs-verity must call to deny truncates of verity files.
Signed-off-by: Eric Biggers <redacted>
---
fs/verity/open.c | 21 +++++++++++++++++++++
include/linux/fsverity.h | 7 +++++++
2 files changed, 28 insertions(+)
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:31
From: Eric Biggers <redacted>
Analogous to fs/crypto/, add fields to the VFS inode and superblock for
use by the fs/verity/ support layer:
- ->s_vop: points to the fsverity_operations if the filesystem supports
fs-verity, otherwise is NULL.
- ->i_verity_info: points to cached fs-verity information for the inode
after someone opens it, otherwise is NULL.
- S_VERITY: bit in ->i_flags that identifies verity inodes, even when
they haven't been opened yet and thus still have NULL ->i_verity_info.
Signed-off-by: Eric Biggers <redacted>
---
include/linux/fs.h | 11 +++++++++++
1 file changed, 11 insertions(+)
@@ -1429,6 +1435,9 @@ struct super_block {conststructxattr_handler**s_xattr;#ifdef CONFIG_FS_ENCRYPTIONconststructfscrypt_operations*s_cop;+#endif+#ifdef CONFIG_FS_VERITY+conststructfsverity_operations*s_vop;#endifstructhlist_bl_heads_roots;/* alternate root dentries for NFS */structlist_heads_mounts;/* list of mounts; _not_ for fs use */
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:38
From: Eric Biggers <redacted>
Add FS_VERITY_FL to the flags for FS_IOC_GETFLAGS, so that applications
can easily determine whether a file is a verity file at the same time as
they're checking other file flags. This flag will be gettable only;
FS_IOC_SETFLAGS won't allow setting it, since an ioctl must be used
instead to provide more parameters.
This flag matches the on-disk bit that was already allocated for ext4.
Signed-off-by: Eric Biggers <redacted>
---
include/uapi/linux/fs.h | 1 +
1 file changed, 1 insertion(+)
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:38
From: Eric Biggers <redacted>
fs-verity will be jointly maintained by Eric Biggers and Theodore Ts'o.
Signed-off-by: Eric Biggers <redacted>
---
MAINTAINERS | 12 ++++++++++++
1 file changed, 12 insertions(+)
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 15:54:39
From: Eric Biggers <redacted>
Add the UAPI header for fs-verity, including two ioctls:
- FS_IOC_ENABLE_VERITY
- FS_IOC_MEASURE_VERITY
These ioctls are documented in the "User API" section of
Documentation/filesystems/fsverity.rst.
Examples of using these ioctls can be found in fsverity-utils
(https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/fsverity-utils.git).
I've also written xfstests that test these ioctls
(https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/xfstests-dev.git/log/?h=fsverity).
Signed-off-by: Eric Biggers <redacted>
---
Documentation/ioctl/ioctl-number.txt | 1 +
include/uapi/linux/fsverity.h | 39 ++++++++++++++++++++++++++++
2 files changed, 40 insertions(+)
create mode 100644 include/uapi/linux/fsverity.h
On Thu, Jun 6, 2019 at 8:54 AM Eric Biggers [off-list ref] wrote:
This is a redesigned version of the fs-verity patchset, implementing
Ted's suggestion to build the Merkle tree in the kernel
(https://lore.kernel.org/linux-fsdevel/20190207031101.GA7387@mit.edu/).
This greatly simplifies the UAPI, since the verity metadata no longer
needs to be transferred to the kernel.
Interfaces look sane to me. My only real concern is whether it would
make sense to make the FS_IOC_ENABLE_VERITY ioctl be something that
could be done incrementally, since the way it is done now it looks
like any random user could create a big file and then do the
FS_IOC_ENABLE_VERITY to make the kernel do a _very_ expensive
operation.
Yes, I see the
+ if (fatal_signal_pending(current))
+ return -EINTR;
+ cond_resched();
in there, so it's not like it's some entirely unkillable thing, and
maybe we don't care as a result. But maybe the ioctl interface could
be fundamentally restartable?
If that was already considered and people just went "too complex", never mind.
Linus
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-06 19:43:48
On Thu, Jun 06, 2019 at 10:21:12AM -0700, Linus Torvalds wrote:
On Thu, Jun 6, 2019 at 8:54 AM Eric Biggers [off-list ref] wrote:
quoted
This is a redesigned version of the fs-verity patchset, implementing
Ted's suggestion to build the Merkle tree in the kernel
(https://lore.kernel.org/linux-fsdevel/20190207031101.GA7387@mit.edu/).
This greatly simplifies the UAPI, since the verity metadata no longer
needs to be transferred to the kernel.
Interfaces look sane to me. My only real concern is whether it would
make sense to make the FS_IOC_ENABLE_VERITY ioctl be something that
could be done incrementally, since the way it is done now it looks
like any random user could create a big file and then do the
FS_IOC_ENABLE_VERITY to make the kernel do a _very_ expensive
operation.
Yes, I see the
+ if (fatal_signal_pending(current))
+ return -EINTR;
+ cond_resched();
in there, so it's not like it's some entirely unkillable thing, and
maybe we don't care as a result. But maybe the ioctl interface could
be fundamentally restartable?
If that was already considered and people just went "too complex", never mind.
Linus
Making it incremental would be complex. We could make FS_IOC_ENABLE_VERITY
write checkpoints periodically, and make it resume from the checkpoint if
present. But then we'd have to worry about sync'ing the Merkle tree before
writing each checkpoint, and storing the Merkle tree parameters in each
checkpoint so that if the second call to FS_IOC_ENABLE_VERITY is made with
different parameters it knows to delete everything and restart from scratch.
Or we could make it explicit in the UAPI, where userspace calls ioctls to build
blocks 0 through 9999, then 10000 through 19999, etc. But that would make the
UAPI much more complex, and the kernel would need to do lots of extra validation
of the parameters passed in. This approach would also not be crash-safe unless
userspace did its own checkpointing, whereas the all-or-nothing API naturally
avoids inconsistent states.
And either way of making it incremental, the "partial Merkle tree" would also
become a valid on-disk state. Conceptually that adds a lot of complexity, and
probably people would want fsck to support removing all the partial trees,
similar to how e2fsck supports optimizing directories and extent trees.
So in the end, it's not something I decided to add.
- Eric
On Thu, Jun 06, 2019 at 08:51:50AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add a documentation file for fs-verity, covering....
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-by: Theodore Ts'o <tytso@mit.edu>
One minor design point below:
+ext4 stores the verity metadata (Merkle tree and fsverity_descriptor)
+past the end of the file, starting at the first page fully beyond
^^^^
+i_size. This approach works because (a) verity files are readonly,
+and (b) pages fully beyond i_size aren't visible to userspace but can
+be read/written internally by ext4 with only some relatively small
+changes to ext4. This approach avoids having to depend on the
+EA_INODE feature and on rearchitecturing ext4's xattr support to
+support paging multi-gigabyte xattrs into memory, and to support
+encrypting xattrs. Note that the verity metadata *must* be encrypted
+when the file is, since it contains hashes of the plaintext data.
If we ever want to support mounting, say, a file system with 4k blocks
and fsverity enabled on a architecture with a 16k or 64k page size,
then "page" in that first sentence will need to become "block". At
the moment we only support fsverity when page size == block size, so
it's not an issue.
However, it's worth reflecting on what this means. In order to
satisfy this requirement (from the mmap man page):
A file is mapped in multiples of the page size. For a file
that is not a multiple of the page size, the remaining memory
is zeroed when mapped...
we're going to have to special case how the last page gets mmaped.
The simplest way to do this will be to map in an anonymous page which
just has the blocks that are part of the data block copied in, and the
rest of the page can be zero'ed.
One thing we might consider doing just to make life much easier for
ourselves (should we ever want to support page size != block size ---
which I could imagine some folks like Chandan might find desirable) is
to specify that the fsverity metadata begins at an offset which begins
at i_size rounded up to the next 64k binary, which should handle all
current and future architectures' page sizes.
- Ted
On Thu, Jun 06, 2019 at 08:51:53AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add FS_VERITY_FL to the flags for FS_IOC_GETFLAGS, so that applications
can easily determine whether a file is a verity file at the same time as
they're checking other file flags. This flag will be gettable only;
FS_IOC_SETFLAGS won't allow setting it, since an ioctl must be used
instead to provide more parameters.
This flag matches the on-disk bit that was already allocated for ext4.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
On Thu, Jun 06, 2019 at 08:51:54AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add the beginnings of the fs/verity/ support layer, including the
Kconfig option and various helper functions for hashing. To start, only
SHA-256 is supported, but other hash algorithms can easily be added.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
One thought for consideration below...
+
+/*
+ * Maximum depth of the Merkle tree. Up to 64 levels are theoretically possible
+ * with a very small block size, but we'd like to limit stack usage during
+ * verification, and in practice this is plenty. E.g., with SHA-256 and 4K
+ * blocks, a file with size UINT64_MAX bytes needs just 8 levels.
+ */
+#define FS_VERITY_MAX_LEVELS 16
Maybe we should make FS_VERITY_MAX_LEVELS 8 for now? This is an
implementation-level restriction, and currently we don't support any
architectures that have a page size < 4k. We can always bump this
number up in the future if it ever becomes necessary, and limiting max
levels to 8 saves almost 100 bytes of stack space in verify_page().
- Ted
On Thu, Jun 06, 2019 at 08:51:55AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Analogous to fs/crypto/, add fields to the VFS inode and superblock for
use by the fs/verity/ support layer:
- ->s_vop: points to the fsverity_operations if the filesystem supports
fs-verity, otherwise is NULL.
- ->i_verity_info: points to cached fs-verity information for the inode
after someone opens it, otherwise is NULL.
- S_VERITY: bit in ->i_flags that identifies verity inodes, even when
they haven't been opened yet and thus still have NULL ->i_verity_info.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
On Thu, Jun 06, 2019 at 08:51:56AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add the fsverity_file_open() function, which prepares an fs-verity file
to be read from. If not already done, it loads the fs-verity descriptor
from the filesystem and sets up an fsverity_info structure for the inode
which describes the Merkle tree and contains the file measurement. It
also denies all attempts to open verity files for writing.
This commit also begins the include/linux/fsverity.h header, which
declares the interface between fs/verity/ and filesystems.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
+/*
+ * Validate the given fsverity_descriptor and create a new fsverity_info from
+ * it. The signature (if present) is also checked.
+ */
+struct fsverity_info *fsverity_create_info(const struct inode *inode,
+ const void *_desc, size_t desc_size)
Well, technically it's not checked (yet). It doesn't get checked
until [PATCH 13/16]: support builtin file signatures. If we want to
be really nit-picky, that portion of the comment could be moved to
later in the series.
On Thu, Jun 06, 2019 at 08:51:57AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add a function fsverity_prepare_setattr() which filesystems that support
fs-verity must call to deny truncates of verity files.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
On Thu, Jun 06, 2019 at 08:51:58AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add functions that verify data pages that have been read from a
fs-verity file, against that file's Merkle tree. These will be called
from filesystems' ->readpage() and ->readpages() methods.
Since data verification can block, a workqueue is provided for these
methods to enqueue verification work from their bio completion callback.
See the "Verifying data" section of
Documentation/filesystems/fsverity.rst for more information.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
On Thu, Jun 06, 2019 at 08:51:59AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add a function for filesystems to call to implement the
FS_IOC_ENABLE_VERITY ioctl. This ioctl enables fs-verity on a file.
See the "FS_IOC_ENABLE_VERITY" section of
Documentation/filesystems/fsverity.rst for the documentation.
Signed-off-by: Eric Biggers <redacted>
quoted hunk
diff --git a/fs/verity/enable.c b/fs/verity/enable.cnew file mode 100644index 000000000000..7e7ef9d3c376--- /dev/null+++ b/fs/verity/enable.c
+ /* Tell the filesystem to finish enabling verity on the file */
+ err = vops->end_enable_verity(filp, desc, desc_size, params.tree_size);
+ if (err) {
+ fsverity_err(inode, "%ps() failed with err %d",
+ vops->end_enable_verity, err);
+ fsverity_free_info(vi);
+ } else {
+ /* Successfully enabled verity */
+
+ WARN_ON(!IS_VERITY(inode));
+
+ /*
+ * Readers can start using ->i_verity_info immediately, so it
+ * can't be rolled back once set. So don't set it until just
+ * after the filesystem has successfully enabled verity.
+ */
+ fsverity_set_info(inode, vi);
+ }
If end_enable_Verity() retuns success, and IS_VERITY is not set, I
would think that we should report the error via fsverity_err() and
return an error to userspace, and *not* call fsverity_set_info(). I
don't think the stack trace printed by WARN_ON is going to very
interesting, since the call path which gets us to enable_verity() is
not going to be surprising.
How hard would it be to support fsverity for zero-length files? There
would be no Merkle tree, but there still would be an fsverity header
file on which we can calculate a checksum for the digital signature.
- Ted
On Thu, Jun 06, 2019 at 08:52:00AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add a function for filesystems to call to implement the
FS_IOC_MEASURE_VERITY ioctl. This ioctl retrieves the file measurement
that fs-verity calculated for the given file and is enforcing for reads;
i.e., reads that don't match this hash will fail. This ioctl can be
used for authentication or logging of file measurements in userspace.
See the "FS_IOC_MEASURE_VERITY" section of
Documentation/filesystems/fsverity.rst for the documentation.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
On Thu, Jun 06, 2019 at 08:52:01AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
Add SHA-512 support to fs-verity. This is primarily a demonstration of
the trivial changes needed to support a new hash algorithm in fs-verity;
most users will still use SHA-256, due to the smaller space required to
store the hashes. But some users may prefer SHA-512.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
On Thu, Jun 06, 2019 at 08:52:02AM -0700, Eric Biggers wrote:
From: Eric Biggers <redacted>
To meet some users' needs, add optional support for having fs-verity
handle a portion of the authentication policy in the kernel. An
".fs-verity" keyring is created to which X.509 certificates can be
added; then a sysctl 'fs.verity.require_signatures' can be set to cause
the kernel to enforce that all fs-verity files contain a signature of
their file measurement by a key in this keyring.
I think it might be a good idea to allow the require_signatures
setting to be set on a per-file system basis, via a mount option? We
could plumb it in via a flag in fsverity_info, set by the file system.
Other than this feature request, looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
On Thu, Jun 06, 2019 at 08:52:03AM -0700, Eric Biggers wrote:
+/*
+ * Format of ext4 verity xattr. This points to the location of the verity
+ * descriptor within the file data rather than containing it directly because
+ * the verity descriptor *must* be encrypted when ext4 encryption is used. But,
+ * ext4 encryption does not encrypt xattrs.
+ */
+struct fsverity_descriptor_location {
+ __le32 version;
+ __le32 size;
+ __le64 pos;
+};
What's the benefit of storing the location in an xattr as opposed to
just keying it off the end of i_size, rounded up to next page size (or
64k) as I had suggested earlier?
Using an xattr burns xattr space, which is a limited resource, and it
adds some additional code complexity. Does the benefits outweigh the
added complexity?
- Ted
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-18 16:31:22
Hi Ted,
On Sat, Jun 15, 2019 at 08:39:20AM -0400, Theodore Ts'o wrote:
On Thu, Jun 06, 2019 at 08:51:50AM -0700, Eric Biggers wrote:
quoted
From: Eric Biggers <redacted>
Add a documentation file for fs-verity, covering....
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-by: Theodore Ts'o <tytso@mit.edu>
One minor design point below:
quoted
+ext4 stores the verity metadata (Merkle tree and fsverity_descriptor)
+past the end of the file, starting at the first page fully beyond
^^^^
quoted
+i_size. This approach works because (a) verity files are readonly,
+and (b) pages fully beyond i_size aren't visible to userspace but can
+be read/written internally by ext4 with only some relatively small
+changes to ext4. This approach avoids having to depend on the
+EA_INODE feature and on rearchitecturing ext4's xattr support to
+support paging multi-gigabyte xattrs into memory, and to support
+encrypting xattrs. Note that the verity metadata *must* be encrypted
+when the file is, since it contains hashes of the plaintext data.
If we ever want to support mounting, say, a file system with 4k blocks
and fsverity enabled on a architecture with a 16k or 64k page size,
then "page" in that first sentence will need to become "block". At
the moment we only support fsverity when page size == block size, so
it's not an issue.
However, it's worth reflecting on what this means. In order to
satisfy this requirement (from the mmap man page):
A file is mapped in multiples of the page size. For a file
that is not a multiple of the page size, the remaining memory
is zeroed when mapped...
we're going to have to special case how the last page gets mmaped.
The simplest way to do this will be to map in an anonymous page which
just has the blocks that are part of the data block copied in, and the
rest of the page can be zero'ed.
One thing we might consider doing just to make life much easier for
ourselves (should we ever want to support page size != block size ---
which I could imagine some folks like Chandan might find desirable) is
to specify that the fsverity metadata begins at an offset which begins
at i_size rounded up to the next 64k binary, which should handle all
current and future architectures' page sizes.
Thanks for the review. Good point; I think we should just go with the "always
round up to the next 64K boundary" method. Special-casing how the last page
gets mmap()ed seems it would be really painful.
Since there can be a hole between the end of the file and the start of the
verity metadata, this doesn't even necessarily use any additional disk space.
For consistency and since there is little downside I think I'll do the same for
f2fs too, though f2fs doesn't currently support PAGE_SIZE != 4096 at all anyway.
- Eric
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-18 16:33:00
On Sat, Jun 15, 2019 at 08:57:31AM -0400, Theodore Ts'o wrote:
On Thu, Jun 06, 2019 at 08:51:54AM -0700, Eric Biggers wrote:
quoted
From: Eric Biggers <redacted>
Add the beginnings of the fs/verity/ support layer, including the
Kconfig option and various helper functions for hashing. To start, only
SHA-256 is supported, but other hash algorithms can easily be added.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
One thought for consideration below...
quoted
+
+/*
+ * Maximum depth of the Merkle tree. Up to 64 levels are theoretically possible
+ * with a very small block size, but we'd like to limit stack usage during
+ * verification, and in practice this is plenty. E.g., with SHA-256 and 4K
+ * blocks, a file with size UINT64_MAX bytes needs just 8 levels.
+ */
+#define FS_VERITY_MAX_LEVELS 16
Maybe we should make FS_VERITY_MAX_LEVELS 8 for now? This is an
implementation-level restriction, and currently we don't support any
architectures that have a page size < 4k. We can always bump this
number up in the future if it ever becomes necessary, and limiting max
levels to 8 saves almost 100 bytes of stack space in verify_page().
- Ted
Yes, I agree. I'll reduce MAX_LEVELS to 8 for now and tweak the comment.
- Eric
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-18 16:35:09
On Sat, Jun 15, 2019 at 10:42:07AM -0400, Theodore Ts'o wrote:
On Thu, Jun 06, 2019 at 08:51:56AM -0700, Eric Biggers wrote:
quoted
From: Eric Biggers <redacted>
Add the fsverity_file_open() function, which prepares an fs-verity file
to be read from. If not already done, it loads the fs-verity descriptor
from the filesystem and sets up an fsverity_info structure for the inode
which describes the Merkle tree and contains the file measurement. It
also denies all attempts to open verity files for writing.
This commit also begins the include/linux/fsverity.h header, which
declares the interface between fs/verity/ and filesystems.
Signed-off-by: Eric Biggers <redacted>
Looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
- Ted
quoted
+/*
+ * Validate the given fsverity_descriptor and create a new fsverity_info from
+ * it. The signature (if present) is also checked.
+ */
+struct fsverity_info *fsverity_create_info(const struct inode *inode,
+ const void *_desc, size_t desc_size)
Well, technically it's not checked (yet). It doesn't get checked
until [PATCH 13/16]: support builtin file signatures. If we want to
be really nit-picky, that portion of the comment could be moved to
later in the series.
Yes, I missed this when splitting out the patches. I'll move it to patch 13.
- Eric
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-18 16:50:22
On Sat, Jun 15, 2019 at 11:08:21AM -0400, Theodore Ts'o wrote:
On Thu, Jun 06, 2019 at 08:51:59AM -0700, Eric Biggers wrote:
quoted
From: Eric Biggers <redacted>
Add a function for filesystems to call to implement the
FS_IOC_ENABLE_VERITY ioctl. This ioctl enables fs-verity on a file.
See the "FS_IOC_ENABLE_VERITY" section of
Documentation/filesystems/fsverity.rst for the documentation.
Signed-off-by: Eric Biggers <redacted>
quoted
diff --git a/fs/verity/enable.c b/fs/verity/enable.cnew file mode 100644index 000000000000..7e7ef9d3c376--- /dev/null+++ b/fs/verity/enable.c
+ /* Tell the filesystem to finish enabling verity on the file */
+ err = vops->end_enable_verity(filp, desc, desc_size, params.tree_size);
+ if (err) {
+ fsverity_err(inode, "%ps() failed with err %d",
+ vops->end_enable_verity, err);
+ fsverity_free_info(vi);
+ } else {
+ /* Successfully enabled verity */
+
+ WARN_ON(!IS_VERITY(inode));
+
+ /*
+ * Readers can start using ->i_verity_info immediately, so it
+ * can't be rolled back once set. So don't set it until just
+ * after the filesystem has successfully enabled verity.
+ */
+ fsverity_set_info(inode, vi);
+ }
If end_enable_Verity() retuns success, and IS_VERITY is not set, I
would think that we should report the error via fsverity_err() and
return an error to userspace, and *not* call fsverity_set_info(). I
don't think the stack trace printed by WARN_ON is going to very
interesting, since the call path which gets us to enable_verity() is
not going to be surprising.
I want to keep it as WARN_ON() because if it happens it's a kernel bug, and
WARNs are reported as bugs by automated tools. But I can do the following so it
returns an error code too:
@@ -229,11 +235,12 @@ static int enable_verity(struct file *filp, fsverity_err(inode, "%ps() failed with err %d", vops->end_enable_verity, err); fsverity_free_info(vi);+ } else if (WARN_ON(!IS_VERITY(inode))) {+ err = -EINVAL;+ fsverity_free_info(vi); } else { /* Successfully enabled verity */- WARN_ON(!IS_VERITY(inode));- /* * Readers can start using ->i_verity_info immediately, so it * can't be rolled back once set. So don't set it until just
How hard would it be to support fsverity for zero-length files? There
would be no Merkle tree, but there still would be an fsverity header
file on which we can calculate a checksum for the digital signature.
- Ted
Empty files would have to be special-cased, e.g. defining the root hash to be
all 0's, since there are no blocks to checksum. It would be straightforward,
but it would still be a special case, e.g.:
@@ -112,6 +112,12 @@ static int build_merkle_tree(struct inode *inode,unsignedintlevel;interr=-ENOMEM;+if(inode->i_size==0){+/* Empty file is a special case; root hash is all 0's */+memset(root_hash,0,params->digest_size);+return0;+}+
On the other hand, *not* supporting empty files is a special case from the
user's point of view. It means that fs-verity isn't supported on every possible
file. Thinking about it, that's probably worse than having a special case in
the *implementation*.
So now I'm leaning towards changing it to support empty files.
- Eric
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-18 16:58:54
On Sat, Jun 15, 2019 at 11:21:43AM -0400, Theodore Ts'o wrote:
On Thu, Jun 06, 2019 at 08:52:02AM -0700, Eric Biggers wrote:
quoted
From: Eric Biggers <redacted>
To meet some users' needs, add optional support for having fs-verity
handle a portion of the authentication policy in the kernel. An
".fs-verity" keyring is created to which X.509 certificates can be
added; then a sysctl 'fs.verity.require_signatures' can be set to cause
the kernel to enforce that all fs-verity files contain a signature of
their file measurement by a key in this keyring.
I think it might be a good idea to allow the require_signatures
setting to be set on a per-file system basis, via a mount option? We
could plumb it in via a flag in fsverity_info, set by the file system.
Perhaps, but this is something that can be added later, so I think we should
hold off on it until someone needs it.
Other than this feature request, looks good; you can add:
Reviewed-off-by: Theodore Ts'o [off-list ref]
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-18 17:51:22
On Sat, Jun 15, 2019 at 11:31:12AM -0400, Theodore Ts'o wrote:
On Thu, Jun 06, 2019 at 08:52:03AM -0700, Eric Biggers wrote:
quoted
+/*
+ * Format of ext4 verity xattr. This points to the location of the verity
+ * descriptor within the file data rather than containing it directly because
+ * the verity descriptor *must* be encrypted when ext4 encryption is used. But,
+ * ext4 encryption does not encrypt xattrs.
+ */
+struct fsverity_descriptor_location {
+ __le32 version;
+ __le32 size;
+ __le64 pos;
+};
What's the benefit of storing the location in an xattr as opposed to
just keying it off the end of i_size, rounded up to next page size (or
64k) as I had suggested earlier?
Using an xattr burns xattr space, which is a limited resource, and it
adds some additional code complexity. Does the benefits outweigh the
added complexity?
- Ted
It means that only the fs/verity/ support layer has to be aware of the format of
the fsverity_descriptor, and the filesystem can just treat it an as opaque blob.
Otherwise the filesystem would need to read the first 'sizeof(struct
fsverity_descriptor)' bytes and use those to calculate the size as
'sizeof(struct fsverity_descriptor) + le32_to_cpu(desc.sig_size)', then read the
rest. Is this what you have in mind?
Alternatively the filesystem could prepend the fsverity_descriptor with its
size, similar to how in the v1 and v2 patchsets there was an fsverity_footer
appended to the fsverity_descriptor. But an xattr seems a cleaner approach to
store a few bytes that don't need to be encrypted.
Putting the verity descriptor before the Merkle tree also means that we'd have
to pass the desc_size to ->begin_enable_verity(), ->read_merkle_tree_page(), and
->write_merkle_tree_block(), versus just passing the merkle_tree_size to
->end_enable_verity(). This would be easy, but it would still add a bit of
complexity in the fsverity_operations rather than reduce it.
It's also somewhat nice to have the version number in the xattr, in case we ever
introduce a new fs-verity format for ext4 or f2fs.
So to me, it doesn't seem like the other possible solutions are better.
- Eric
On Tue, Jun 18, 2019 at 10:51:18AM -0700, Eric Biggers wrote:
On Sat, Jun 15, 2019 at 11:31:12AM -0400, Theodore Ts'o wrote:
quoted
On Thu, Jun 06, 2019 at 08:52:03AM -0700, Eric Biggers wrote:
quoted
+/*
+ * Format of ext4 verity xattr. This points to the location of the verity
+ * descriptor within the file data rather than containing it directly because
+ * the verity descriptor *must* be encrypted when ext4 encryption is used. But,
+ * ext4 encryption does not encrypt xattrs.
+ */
+struct fsverity_descriptor_location {
+ __le32 version;
+ __le32 size;
+ __le64 pos;
+};
What's the benefit of storing the location in an xattr as opposed to
just keying it off the end of i_size, rounded up to next page size (or
64k) as I had suggested earlier?
Using an xattr burns xattr space, which is a limited resource, and it
adds some additional code complexity. Does the benefits outweigh the
added complexity?
- Ted
It means that only the fs/verity/ support layer has to be aware of the format of
the fsverity_descriptor, and the filesystem can just treat it an as opaque blob.
Otherwise the filesystem would need to read the first 'sizeof(struct
fsverity_descriptor)' bytes and use those to calculate the size as
'sizeof(struct fsverity_descriptor) + le32_to_cpu(desc.sig_size)', then read the
rest. Is this what you have in mind?
So right now, the way enable_verity() works is that it appends the
Merkle tree to the data file, rounding up to the next page (but we
might change so we round up to the next 64k boundary). Then it calls
end_enable_verity(), which is a file system specific function, passing
in the descriptor and the descriptor size.
Today ext4 and f2fs appends the descriptor after the Merkle, and then
sets the xattr containing the fsverity_descriptor_location. Correct?
What I'm suggesting that ext4 do instead is that it appends the
descriptor to the Merkle tree, and then assuming that there is the
(descriptor size % block_size) is less than PAGE_SIZE-4, we can write
the descriptor size into the last 4 bytes of the last block in the
file. If there is not enough space at the end of the descriptor, then
we append a block to the file, and then write the descriptor_size into
last 4 bytes of that block.
When ext4 needs to find the descriptor, it simply reads the last block
from the file, reads it into the page cache, reads the last 4 bytes
from that block to fetch the descriptor size, and it can use the
logical offset of the last block and the descriptor size to calculate
the beginning offset of the descriptor size.
We can then fake up the fsverity_descriptor_location structure, and
pass that into fsverity.
It does add a bit of extra complexity, but 99.9% of the time, it
requires no extra space. The last 0.098% of the time, the file size
will grow by 4k, but if we can avoid spilling over to an external
xattr block, it will all be worth it.
And in the V1 version of the fsverity code, I had already written the
code to descend the extent tree to find the last logical block in the
extent tree.
It's also somewhat nice to have the version number in the xattr, in case we ever
introduce a new fs-verity format for ext4 or f2fs.
We already have a version number in the fsverity descriptor. Surely
that is what we would bump if we need to itnroduce a new fs-verity
format?
- Ted
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-18 23:41:39
On Tue, Jun 18, 2019 at 06:46:15PM -0400, Theodore Ts'o wrote:
On Tue, Jun 18, 2019 at 10:51:18AM -0700, Eric Biggers wrote:
quoted
On Sat, Jun 15, 2019 at 11:31:12AM -0400, Theodore Ts'o wrote:
quoted
On Thu, Jun 06, 2019 at 08:52:03AM -0700, Eric Biggers wrote:
quoted
+/*
+ * Format of ext4 verity xattr. This points to the location of the verity
+ * descriptor within the file data rather than containing it directly because
+ * the verity descriptor *must* be encrypted when ext4 encryption is used. But,
+ * ext4 encryption does not encrypt xattrs.
+ */
+struct fsverity_descriptor_location {
+ __le32 version;
+ __le32 size;
+ __le64 pos;
+};
What's the benefit of storing the location in an xattr as opposed to
just keying it off the end of i_size, rounded up to next page size (or
64k) as I had suggested earlier?
Using an xattr burns xattr space, which is a limited resource, and it
adds some additional code complexity. Does the benefits outweigh the
added complexity?
- Ted
It means that only the fs/verity/ support layer has to be aware of the format of
the fsverity_descriptor, and the filesystem can just treat it an as opaque blob.
Otherwise the filesystem would need to read the first 'sizeof(struct
fsverity_descriptor)' bytes and use those to calculate the size as
'sizeof(struct fsverity_descriptor) + le32_to_cpu(desc.sig_size)', then read the
rest. Is this what you have in mind?
So right now, the way enable_verity() works is that it appends the
Merkle tree to the data file, rounding up to the next page (but we
might change so we round up to the next 64k boundary). Then it calls
end_enable_verity(), which is a file system specific function, passing
in the descriptor and the descriptor size.
Today ext4 and f2fs appends the descriptor after the Merkle, and then
sets the xattr containing the fsverity_descriptor_location. Correct?
That's all correct, except that enable_verity() itself doesn't know or care that
the Merkle tree is being appended to the file. That's up to the
->write_merkle_tree_block() and ->read_merkle_tree_page() methods which are
filesystem-specific.
What I'm suggesting that ext4 do instead is that it appends the
descriptor to the Merkle tree, and then assuming that there is the
(descriptor size % block_size) is less than PAGE_SIZE-4, we can write
the descriptor size into the last 4 bytes of the last block in the
file. If there is not enough space at the end of the descriptor, then
we append a block to the file, and then write the descriptor_size into
last 4 bytes of that block.
When ext4 needs to find the descriptor, it simply reads the last block
from the file, reads it into the page cache, reads the last 4 bytes
from that block to fetch the descriptor size, and it can use the
logical offset of the last block and the descriptor size to calculate
the beginning offset of the descriptor size.
We can then fake up the fsverity_descriptor_location structure, and
pass that into fsverity.
It does add a bit of extra complexity, but 99.9% of the time, it
requires no extra space. The last 0.098% of the time, the file size
will grow by 4k, but if we can avoid spilling over to an external
xattr block, it will all be worth it.
And in the V1 version of the fsverity code, I had already written the
code to descend the extent tree to find the last logical block in the
extent tree.
I don't think your proposed solution is so simple. By definition the last
extent ends on a filesystem block boundary, while the Merkle tree ends on a
Merkle tree block boundary. In the future we might support the case where these
differ, so we don't want to preclude that in the on-disk format we choose now.
Therefore, just storing the desc_size isn't enough; we'd actually have to store
(desc_pos, desc_size), like I'm doing in the xattr.
Also, using ext4_find_extent() to find the last mapped block (as the v1 and v2
patchsets did) assumes the file actually uses extents. So we'd have to forbid
non-extents based files as a special case, as the v2 patchset did. We'd also
have to find a way to implement the same functionality on f2fs (which should be
possible, but it seems it would require some new code; there's nothing like
f2fs_get_extent()) unless we did something different for f2fs.
Note that on Android devices (the motivating use case for fs-verity), the xattrs
of user data files on ext4 already spill into an external xattr block, due to
the fscrypt and SELinux xattrs. If/when people actually start caring about
this, they'll need to increase the inode size to 512 bytes anyway, in which case
there will be plenty of space for a few more in-line xattrs. So I don't think
we should jump through too many hoops to avoid using an xattr.
quoted
It's also somewhat nice to have the version number in the xattr, in case we ever
introduce a new fs-verity format for ext4 or f2fs.
We already have a version number in the fsverity descriptor. Surely
that is what we would bump if we need to itnroduce a new fs-verity
format?
I'm talking about if we ever wanted to make a filesystem-specific change to
where the verity metadata is stored. That's what the version number in the
filesystem-specific xattr is for. The version number in the fsverity_descriptor
is different: that's for if we made a change to fs-verity for *all* filesystems.
We hopefully won't ever need the filesystem-specific version number, but as long
as we have to store the (desc_pos, desc_size) anyway, I think it's wise to add a
version number just in case; it doesn't really cost anything.
- Eric
On Tue, Jun 18, 2019 at 04:41:34PM -0700, Eric Biggers wrote:
I don't think your proposed solution is so simple. By definition the last
extent ends on a filesystem block boundary, while the Merkle tree ends on a
Merkle tree block boundary. In the future we might support the case where these
differ, so we don't want to preclude that in the on-disk format we choose now.
Therefore, just storing the desc_size isn't enough; we'd actually have to store
(desc_pos, desc_size), like I'm doing in the xattr.
I don't think any of this matters much, since what you're describing
above is all about the Merkle tree, and that doesn't affect how we
find the fsverity descriptor information. We can just say that
fsverity descriptor block begins on the next file system block
boundary after the Merkle tree. And in the case where say, the Merkle
tree is 4k and the file system block size is 64k, that's fine --- the
fs descriptor would just begin at the next 64k (fs blocksize)
boundary.
Also, using ext4_find_extent() to find the last mapped block (as the v1 and v2
patchsets did) assumes the file actually uses extents. So we'd have to forbid
non-extents based files as a special case, as the v2 patchset did. We'd also
have to find a way to implement the same functionality on f2fs (which should be
possible, but it seems it would require some new code; there's nothing like
f2fs_get_extent()) unless we did something different for f2fs.
So first, if f2fs wants to continue using the xattr, that's fine. The
code to write and fetch the fsverity descriptor is in file system
specific code, and so this is something I'm happy to support just for
ext4, and it shouldn't require any special changes in the common
fsverity code at all. Secondly, I suspect it's not *that* hard to
find the last logical block mapping in f2fs, but I'll let Jaeguk
comment on that.
Finally, it's not that hard to find the last mapped block for indirect
blocks, if we really care about supporting that combination. (There
are enough other things --- like fallocate --- which don't work with
indirect mapped files, so I don't feel especially bad forbidding that
combination. A quick check in enable_verity() to return EOPNOTSUPP if
the EXTENTS_FL flag is not present is not all that different from what
we do with fallocate today.)
But if we *did* want to support it, it's actually quite easy to find
the last mapped block for an indirect mapped inode. I just didn't
bother to write the code, but it requires at most 3 block reads if
there is a triple indirection block. Otherwise, if there is a double
indirection block in the inode, it requires at most 2 block reads, and
otherwise, at most a single block read.
Note that on Android devices (the motivating use case for fs-verity), the xattrs
of user data files on ext4 already spill into an external xattr block, due to
the fscrypt and SELinux xattrs. If/when people actually start caring about
this, they'll need to increase the inode size to 512 bytes anyway, in which case
there will be plenty of space for a few more in-line xattrs. So I don't think
we should jump through too many hoops to avoid using an xattr.
I'm thinking about other cases where we might not be using fscrypt,
but where we might still be using fsverity and SELinux --- or maybe
cases where the file systems are using 128 byte inodes, and where only
fsverity is required. (There are a *vast* number of production file
systems using 128 byte inodes.)
Cheers,
- Ted
From: Eric Biggers <ebiggers@kernel.org> Date: 2019-06-19 19:13:34
On Tue, Jun 18, 2019 at 11:05:22PM -0400, Theodore Ts'o wrote:
On Tue, Jun 18, 2019 at 04:41:34PM -0700, Eric Biggers wrote:
quoted
I don't think your proposed solution is so simple. By definition the last
extent ends on a filesystem block boundary, while the Merkle tree ends on a
Merkle tree block boundary. In the future we might support the case where these
differ, so we don't want to preclude that in the on-disk format we choose now.
Therefore, just storing the desc_size isn't enough; we'd actually have to store
(desc_pos, desc_size), like I'm doing in the xattr.
I don't think any of this matters much, since what you're describing
above is all about the Merkle tree, and that doesn't affect how we
find the fsverity descriptor information. We can just say that
fsverity descriptor block begins on the next file system block
boundary after the Merkle tree. And in the case where say, the Merkle
tree is 4k and the file system block size is 64k, that's fine --- the
fs descriptor would just begin at the next 64k (fs blocksize)
boundary.
Sure, that works.
I implemented this for ext4 and extents only, and it does work, though it's a
bit more complex than the xattr solution -- about 70 extra lines of code
including comments. See diff for fs/ext4/verity.c below.
But we can go with it if you think it's worthwhile to avoid using xattrs at all.
@@ -96,22 +103,10 @@ static int pagecache_write(struct inode *inode, const void *buf, size_t count,return0;}-/*-*Formatofext4verityxattr.Thispointstothelocationoftheverity-*descriptorwithinthefiledataratherthancontainingitdirectlybecause-*theveritydescriptor*must*beencryptedwhenext4encryptionisused.But,-*ext4encryptiondoesnotencryptxattrs.-*/-structfsverity_descriptor_location{-__le32version;-__le32size;-__le64pos;-};-staticintext4_begin_enable_verity(structfile*filp){structinode*inode=file_inode(filp);-intcredits=2;/* superblock and inode for ext4_orphan_add() */+constintcredits=2;/* superblock and inode for ext4_orphan_add() */handle_t*handle;interr;
@@ -119,10 +114,24 @@ static int ext4_begin_enable_verity(struct file *filp)if(err)returnerr;+if(!ext4_test_inode_flag(inode,EXT4_INODE_EXTENTS)){+ext4_warning_inode(inode,+"verity is only allowed on extent-based files");+return-EINVAL;+}+err=ext4_inode_attach_jinode(inode);if(err)returnerr;+/*+*ext4usesthelastallocatedblocktofindtheveritydescriptor,so+*wemustremoveanyotherblockswhichmightconfusethings.+*/+err=ext4_truncate(inode);+if(err)+returnerr;+err=dquot_initialize(inode);if(err)returnerr;
@@ -139,32 +148,55 @@ static int ext4_begin_enable_verity(struct file *filp)returnerr;}+/*+*ext4storestheveritydescriptorbeginningonthenextfilesystemblock+*boundaryaftertheMerkletree.Then,thedescriptorsizeisstoredinthe+*last4bytesofthelastallocatedfilesystemblock---whichiseitherthe+*blockinwhichthedescriptorends,orthenextblockafterthatifthere+*weren'tatleast4bytesremaining.+*+*Wecan'tsimplystorethedescriptorinanxattrbecauseit*must*be+*encryptedwhenext4encryptionisused,butext4encryptiondoesn'tencrypt+*xattrs.Also,ifthedescriptorincludesalargesignatureblobitmaybe+*toolargetostoreinanxattrwithouttheEA_INODEfeature.+*/+staticintext4_write_verity_descriptor(structinode*inode,constvoid*desc,+size_tdesc_size,u64merkle_tree_size)+{+constu64desc_pos=round_up(ext4_verity_metadata_pos(inode)++merkle_tree_size,i_blocksize(inode));+constu64desc_end=desc_pos+desc_size;+const__le32desc_size_disk=cpu_to_le32(desc_size);+constu64desc_size_pos=round_up(desc_end+sizeof(desc_size_disk),+i_blocksize(inode))-+sizeof(desc_size_disk);+interr;++err=pagecache_write(inode,desc,desc_size,desc_pos);+if(err)+returnerr;++returnpagecache_write(inode,&desc_size_disk,sizeof(desc_size_disk),+desc_size_pos);+}+staticintext4_end_enable_verity(structfile*filp,constvoid*desc,size_tdesc_size,u64merkle_tree_size){structinode*inode=file_inode(filp);-u64desc_pos=round_up(inode->i_size,PAGE_SIZE)+merkle_tree_size;-structfsverity_descriptor_locationdloc={-.version=cpu_to_le32(1),-.size=cpu_to_le32(desc_size),-.pos=cpu_to_le64(desc_pos),-};-intcredits=0;+constintcredits=2;/* superblock and inode for ext4_orphan_add() */handle_t*handle;interr1=0;interr;if(desc!=NULL){/* Succeeded; write the verity descriptor. */-err1=pagecache_write(inode,desc,desc_size,desc_pos);+err1=ext4_write_verity_descriptor(inode,desc,desc_size,+merkle_tree_size);/* Write all pages before clearing VERITY_IN_PROGRESS. */if(!err1)err1=filemap_write_and_wait(inode->i_mapping);--if(!err1)-err1=ext4_xattr_set_credits(inode,sizeof(dloc),true,-&credits);}else{/* Failed; truncate anything we wrote past i_size. */ext4_truncate(inode);
@@ -173,14 +205,12 @@ static int ext4_end_enable_verity(struct file *filp, const void *desc,/**WemustalwayscleanupbyclearingEXT4_STATE_VERITY_IN_PROGRESSand*deletingtheinodefromtheorphanlist,evenifsomethingfailed.-*Ifeverythingsucceeded,we'llalsosettheveritybitanddescriptor-*locationxattrinthesametransaction.+*Ifeverythingsucceeded,we'llalsosettheveritybitinthesame+*transaction.*/ext4_clear_inode_state(inode,EXT4_STATE_VERITY_IN_PROGRESS);-credits+=2;/* superblock and inode for ext4_orphan_del() */-handle=ext4_journal_start(inode,EXT4_HT_INODE,credits);if(IS_ERR(handle)){ext4_orphan_del(NULL,inode);
@@ -213,43 +236,103 @@ static int ext4_end_enable_verity(struct file *filp, const void *desc,returnerr?:err1;}-staticintext4_get_verity_descriptor(structinode*inode,void*buf,-size_tbuf_size)+staticintext4_get_verity_descriptor_location(structinode*inode,+size_t*desc_size_ret,+u64*desc_pos_ret){-structfsverity_descriptor_locationdloc;-intres;-u32size;-u64pos;--/* Get the descriptor location */-res=ext4_xattr_get(inode,EXT4_XATTR_INDEX_VERITY,-EXT4_XATTR_NAME_VERITY,&dloc,sizeof(dloc));-if(res<0&&res!=-ERANGE)-returnres;-if(res!=sizeof(dloc)||dloc.version!=cpu_to_le32(1)){-ext4_warning_inode(inode,"unknown verity xattr format");-return-EINVAL;+structext4_ext_path*path;+structext4_extent*last_extent;+u32end_lblk;+u64desc_size_pos;+__le32desc_size_disk;+u32desc_size;+u64desc_pos;+interr;++/*+*Descriptorsizeisinlast4bytesoflastallocatedblock.+*Seeext4_write_verity_descriptor().+*/++if(!ext4_test_inode_flag(inode,EXT4_INODE_EXTENTS)){+EXT4_ERROR_INODE(inode,"verity file doesn't use extents");+return-EFSCORRUPTED;}-size=le32_to_cpu(dloc.size);-pos=le64_to_cpu(dloc.pos);-/* Get the descriptor */-if(pos+size<pos||pos+size>inode->i_sb->s_maxbytes||-pos<round_up(inode->i_size,PAGE_SIZE)||size>INT_MAX){-ext4_warning_inode(inode,"invalid verity xattr");+path=ext4_find_extent(inode,EXT_MAX_BLOCKS-1,NULL,0);+if(IS_ERR(path))+returnPTR_ERR(path);++last_extent=path[path->p_depth].p_ext;+if(!last_extent){+EXT4_ERROR_INODE(inode,"verity file has no extents");+ext4_ext_drop_refs(path);+kfree(path);return-EFSCORRUPTED;}-if(buf_size==0)-returnsize;-if(size>buf_size)-return-ERANGE;-returnpagecache_read(inode,buf,size,pos);++end_lblk=le32_to_cpu(last_extent->ee_block)++ext4_ext_get_actual_len(last_extent);+desc_size_pos=(u64)end_lblk<<inode->i_blkbits;+ext4_ext_drop_refs(path);+kfree(path);++if(desc_size_pos<sizeof(desc_size_disk))+gotobad;+desc_size_pos-=sizeof(desc_size_disk);++err=pagecache_read(inode,&desc_size_disk,sizeof(desc_size_disk),+desc_size_pos);+if(err)+returnerr;+desc_size=le32_to_cpu(desc_size_disk);++/*+*Thedescriptorisstoredjustbeforethedesc_size_disk,butstarting+*onafilesystemblockboundary.+*/++if(desc_size>INT_MAX||desc_size>desc_size_pos)+gotobad;++desc_pos=round_down(desc_size_pos-desc_size,i_blocksize(inode));+if(desc_pos<ext4_verity_metadata_pos(inode))+gotobad;++*desc_size_ret=desc_size;+*desc_pos_ret=desc_pos;+return0;++bad:+EXT4_ERROR_INODE(inode,"verity file corrupted; can't find descriptor");+return-EFSCORRUPTED;+}++staticintext4_get_verity_descriptor(structinode*inode,void*buf,+size_tbuf_size)+{+size_tdesc_size=0;+u64desc_pos=0;+interr;++err=ext4_get_verity_descriptor_location(inode,&desc_size,&desc_pos);+if(err)+returnerr;++if(buf_size){+if(desc_size>buf_size)+return-ERANGE;+err=pagecache_read(inode,buf,desc_size,desc_pos);+if(err)+returnerr;+}+returndesc_size;}staticstructpage*ext4_read_merkle_tree_page(structinode*inode,pgoff_tindex){-index+=DIV_ROUND_UP(inode->i_size,PAGE_SIZE);+index+=ext4_verity_metadata_pos(inode)>>PAGE_SHIFT;returnread_mapping_page(inode->i_mapping,index,NULL);}