1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/init.h>
5 #include <linux/slab.h>
6 #include <linux/rwsem.h>
7 #include <linux/xattr.h>
8 #include <linux/security.h>
9 #include <linux/posix_acl_xattr.h>
10 #include <linux/iversion.h>
11 #include <linux/fsverity.h>
12 #include <linux/sched/mm.h>
14 #include "btrfs_inode.h"
15 #include "transaction.h"
20 * Implementation of the interface defined in struct fsverity_operations.
22 * The main question is how and where to store the verity descriptor and the
23 * Merkle tree. We store both in dedicated btree items in the filesystem tree,
24 * together with the rest of the inode metadata. This means we'll need to do
25 * extra work to encrypt them once encryption is supported in btrfs, but btrfs
26 * has a lot of careful code around i_size and it seems better to make a new key
27 * type than try and adjust all of our expectations for i_size.
29 * Note that this differs from the implementation in ext4 and f2fs, where
30 * this data is stored as if it were in the file, but past EOF. However, btrfs
31 * does not have a widespread mechanism for caching opaque metadata pages, so we
32 * do pretend that the Merkle tree pages themselves are past EOF for the
33 * purposes of caching them (as opposed to creating a virtual inode).
35 * fs verity items are stored under two different key types on disk.
36 * The descriptor items:
37 * [ inode objectid, BTRFS_VERITY_DESC_ITEM_KEY, offset ]
39 * At offset 0, we store a btrfs_verity_descriptor_item which tracks the
40 * size of the descriptor item and some extra data for encryption.
41 * Starting at offset 1, these hold the generic fs verity descriptor.
42 * The latter are opaque to btrfs, we just read and write them as a blob for
43 * the higher level verity code. The most common descriptor size is 256 bytes.
45 * The merkle tree items:
46 * [ inode objectid, BTRFS_VERITY_MERKLE_ITEM_KEY, offset ]
48 * These also start at offset 0, and correspond to the merkle tree bytes.
49 * So when fsverity asks for page 0 of the merkle tree, we pull up one page
50 * starting at offset 0 for this key type. These are also opaque to btrfs,
51 * we're blindly storing whatever fsverity sends down.
54 #define MERKLE_START_ALIGN 65536
57 * Compute the logical file offset where we cache the Merkle tree.
59 * @inode: inode of the verity file
61 * For the purposes of caching the Merkle tree pages, as required by
62 * fs-verity, it is convenient to do size computations in terms of a file
63 * offset, rather than in terms of page indices.
65 * Use 64K to be sure it's past the last page in the file, even with 64K pages.
66 * That rounding operation itself can overflow loff_t, so we do it in u64 and
69 * Returns the file offset on success, negative error code on failure.
71 static loff_t merkle_file_pos(const struct inode *inode)
73 u64 sz = inode->i_size;
74 u64 rounded = round_up(sz, MERKLE_START_ALIGN);
76 if (rounded > inode->i_sb->s_maxbytes)
83 * Drop all the items for this inode with this key_type.
85 * @inode: inode to drop items for
86 * @key_type: type of items to drop (BTRFS_VERITY_DESC_ITEM or
87 * BTRFS_VERITY_MERKLE_ITEM)
89 * Before doing a verity enable we cleanup any existing verity items.
90 * This is also used to clean up if a verity enable failed half way through.
92 * Returns number of dropped items on success, negative error code on failure.
94 static int drop_verity_items(struct btrfs_inode *inode, u8 key_type)
96 struct btrfs_trans_handle *trans;
97 struct btrfs_root *root = inode->root;
98 struct btrfs_path *path;
103 path = btrfs_alloc_path();
108 /* 1 for the item being dropped */
109 trans = btrfs_start_transaction(root, 1);
111 ret = PTR_ERR(trans);
116 * Walk backwards through all the items until we find one that
117 * isn't from our key type or objectid
119 key.objectid = btrfs_ino(inode);
121 key.offset = (u64)-1;
123 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
126 /* No more keys of this type, we're done */
127 if (path->slots[0] == 0)
130 } else if (ret < 0) {
131 btrfs_end_transaction(trans);
135 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
137 /* No more keys of this type, we're done */
138 if (key.objectid != btrfs_ino(inode) || key.type != key_type)
142 * This shouldn't be a performance sensitive function because
143 * it's not used as part of truncate. If it ever becomes
144 * perf sensitive, change this to walk forward and bulk delete
147 ret = btrfs_del_items(trans, root, path, path->slots[0], 1);
149 btrfs_end_transaction(trans);
153 btrfs_release_path(path);
154 btrfs_end_transaction(trans);
157 btrfs_end_transaction(trans);
159 btrfs_free_path(path);
164 * Drop all verity items
166 * @inode: inode to drop verity items for
168 * In most contexts where we are dropping verity items, we want to do it for all
169 * the types of verity items, not a particular one.
171 * Returns: 0 on success, negative error code on failure.
173 int btrfs_drop_verity_items(struct btrfs_inode *inode)
177 ret = drop_verity_items(inode, BTRFS_VERITY_DESC_ITEM_KEY);
180 ret = drop_verity_items(inode, BTRFS_VERITY_MERKLE_ITEM_KEY);
188 * Insert and write inode items with a given key type and offset.
190 * @inode: inode to insert for
191 * @key_type: key type to insert
192 * @offset: item offset to insert at
193 * @src: source data to write
194 * @len: length of source data to write
196 * Write len bytes from src into items of up to 2K length.
197 * The inserted items will have key (ino, key_type, offset + off) where off is
198 * consecutively increasing from 0 up to the last item ending at offset + len.
200 * Returns 0 on success and a negative error code on failure.
202 static int write_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
203 const char *src, u64 len)
205 struct btrfs_trans_handle *trans;
206 struct btrfs_path *path;
207 struct btrfs_root *root = inode->root;
208 struct extent_buffer *leaf;
209 struct btrfs_key key;
210 unsigned long copy_bytes;
211 unsigned long src_offset = 0;
215 path = btrfs_alloc_path();
220 /* 1 for the new item being inserted */
221 trans = btrfs_start_transaction(root, 1);
223 ret = PTR_ERR(trans);
227 key.objectid = btrfs_ino(inode);
232 * Insert 2K at a time mostly to be friendly for smaller leaf
235 copy_bytes = min_t(u64, len, 2048);
237 ret = btrfs_insert_empty_item(trans, root, path, &key, copy_bytes);
239 btrfs_end_transaction(trans);
243 leaf = path->nodes[0];
245 data = btrfs_item_ptr(leaf, path->slots[0], void);
246 write_extent_buffer(leaf, src + src_offset,
247 (unsigned long)data, copy_bytes);
248 offset += copy_bytes;
249 src_offset += copy_bytes;
252 btrfs_release_path(path);
253 btrfs_end_transaction(trans);
256 btrfs_free_path(path);
261 * Read inode items of the given key type and offset from the btree.
263 * @inode: inode to read items of
264 * @key_type: key type to read
265 * @offset: item offset to read from
266 * @dest: Buffer to read into. This parameter has slightly tricky
267 * semantics. If it is NULL, the function will not do any copying
268 * and will just return the size of all the items up to len bytes.
269 * If dest_page is passed, then the function will kmap_local the
270 * page and ignore dest, but it must still be non-NULL to avoid the
271 * counting-only behavior.
272 * @len: length in bytes to read
273 * @dest_page: copy into this page instead of the dest buffer
275 * Helper function to read items from the btree. This returns the number of
276 * bytes read or < 0 for errors. We can return short reads if the items don't
277 * exist on disk or aren't big enough to fill the desired length. Supports
278 * reading into a provided buffer (dest) or into the page cache
280 * Returns number of bytes read or a negative error code on failure.
282 static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,
283 char *dest, u64 len, struct page *dest_page)
285 struct btrfs_path *path;
286 struct btrfs_root *root = inode->root;
287 struct extent_buffer *leaf;
288 struct btrfs_key key;
293 unsigned long copy_bytes;
294 unsigned long dest_offset = 0;
299 path = btrfs_alloc_path();
304 path->reada = READA_FORWARD;
306 key.objectid = btrfs_ino(inode);
310 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
313 } else if (ret > 0) {
315 if (path->slots[0] == 0)
321 leaf = path->nodes[0];
322 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
324 if (key.objectid != btrfs_ino(inode) || key.type != key_type)
327 item_end = btrfs_item_size_nr(leaf, path->slots[0]) + key.offset;
331 * Once we've copied something, we want all of the items
334 if (key.offset != offset)
338 * Our initial offset might be in the middle of an
339 * item. Make sure it all makes sense.
341 if (key.offset > offset)
343 if (item_end <= offset)
347 /* desc = NULL to just sum all the item lengths */
351 copy_end = min(offset + len, item_end);
353 /* Number of bytes in this item we want to copy */
354 copy_bytes = copy_end - offset;
356 /* Offset from the start of item for copying */
357 copy_offset = offset - key.offset;
361 kaddr = kmap_local_page(dest_page);
363 data = btrfs_item_ptr(leaf, path->slots[0], void);
364 read_extent_buffer(leaf, kaddr + dest_offset,
365 (unsigned long)data + copy_offset,
372 offset += copy_bytes;
373 dest_offset += copy_bytes;
375 copied += copy_bytes;
378 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
380 * We've reached the last slot in this leaf and we need
381 * to go to the next leaf.
383 ret = btrfs_next_leaf(root, path);
386 } else if (ret > 0) {
393 btrfs_free_path(path);
400 * Rollback in-progress verity if we encounter an error.
402 * @inode: inode verity had an error for
404 * We try to handle recoverable errors while enabling verity by rolling it back
405 * and just failing the operation, rather than having an fs level error no
406 * matter what. However, any error in rollback is unrecoverable.
408 * Returns 0 on success, negative error code on failure.
410 static int rollback_verity(struct btrfs_inode *inode)
412 struct btrfs_trans_handle *trans;
413 struct btrfs_root *root = inode->root;
416 ASSERT(inode_is_locked(&inode->vfs_inode));
417 truncate_inode_pages(inode->vfs_inode.i_mapping, inode->vfs_inode.i_size);
418 clear_bit(BTRFS_INODE_VERITY_IN_PROGRESS, &inode->runtime_flags);
419 ret = btrfs_drop_verity_items(inode);
421 btrfs_handle_fs_error(root->fs_info, ret,
422 "failed to drop verity items in rollback %llu",
423 (u64)inode->vfs_inode.i_ino);
427 /* 1 for updating the inode flag */
428 trans = btrfs_start_transaction(root, 1);
430 ret = PTR_ERR(trans);
431 btrfs_handle_fs_error(root->fs_info, ret,
432 "failed to start transaction in verity rollback %llu",
433 (u64)inode->vfs_inode.i_ino);
436 inode->ro_flags &= ~BTRFS_INODE_RO_VERITY;
437 btrfs_sync_inode_flags_to_i_flags(&inode->vfs_inode);
438 ret = btrfs_update_inode(trans, root, inode);
440 btrfs_abort_transaction(trans, ret);
443 btrfs_end_transaction(trans);
449 * Finalize making the file a valid verity file
451 * @inode: inode to be marked as verity
452 * @desc: contents of the verity descriptor to write (not NULL)
453 * @desc_size: size of the verity descriptor
455 * Do the actual work of finalizing verity after successfully writing the Merkle
458 * - write out the descriptor items
459 * - mark the inode with the verity flag
460 * - mark the ro compat bit
461 * - clear the in progress bit
463 * Returns 0 on success, negative error code on failure.
465 static int finish_verity(struct btrfs_inode *inode, const void *desc,
468 struct btrfs_trans_handle *trans = NULL;
469 struct btrfs_root *root = inode->root;
470 struct btrfs_verity_descriptor_item item;
473 /* Write out the descriptor item */
474 memset(&item, 0, sizeof(item));
475 btrfs_set_stack_verity_descriptor_size(&item, desc_size);
476 ret = write_key_bytes(inode, BTRFS_VERITY_DESC_ITEM_KEY, 0,
477 (const char *)&item, sizeof(item));
481 /* Write out the descriptor itself */
482 ret = write_key_bytes(inode, BTRFS_VERITY_DESC_ITEM_KEY, 1,
487 /* 1 for updating the inode flag */
488 trans = btrfs_start_transaction(root, 1);
490 ret = PTR_ERR(trans);
493 inode->ro_flags |= BTRFS_INODE_RO_VERITY;
494 btrfs_sync_inode_flags_to_i_flags(&inode->vfs_inode);
495 ret = btrfs_update_inode(trans, root, inode);
498 clear_bit(BTRFS_INODE_VERITY_IN_PROGRESS, &inode->runtime_flags);
499 btrfs_set_fs_compat_ro(root->fs_info, VERITY);
501 btrfs_end_transaction(trans);
508 * fsverity op that begins enabling verity.
510 * @filp: file to enable verity on
512 * Begin enabling fsverity for the file. We drop any existing verity items
513 * and set the in progress bit.
515 * Returns 0 on success, negative error code on failure.
517 static int btrfs_begin_enable_verity(struct file *filp)
519 struct btrfs_inode *inode = BTRFS_I(file_inode(filp));
522 ASSERT(inode_is_locked(file_inode(filp)));
524 if (test_bit(BTRFS_INODE_VERITY_IN_PROGRESS, &inode->runtime_flags))
527 ret = btrfs_drop_verity_items(inode);
531 set_bit(BTRFS_INODE_VERITY_IN_PROGRESS, &inode->runtime_flags);
537 * fsverity op that ends enabling verity.
539 * @filp: file we are finishing enabling verity on
540 * @desc: verity descriptor to write out (NULL in error conditions)
541 * @desc_size: size of the verity descriptor (variable with signatures)
542 * @merkle_tree_size: size of the merkle tree in bytes
544 * If desc is null, then VFS is signaling an error occurred during verity
545 * enable, and we should try to rollback. Otherwise, attempt to finish verity.
547 * Returns 0 on success, negative error code on error.
549 static int btrfs_end_enable_verity(struct file *filp, const void *desc,
550 size_t desc_size, u64 merkle_tree_size)
552 struct btrfs_inode *inode = BTRFS_I(file_inode(filp));
556 ASSERT(inode_is_locked(file_inode(filp)));
561 ret = finish_verity(inode, desc, desc_size);
567 rollback_ret = rollback_verity(inode);
569 btrfs_err(inode->root->fs_info,
570 "failed to rollback verity items: %d", rollback_ret);
575 * fsverity op that gets the struct fsverity_descriptor.
577 * @inode: inode to get the descriptor of
578 * @buf: output buffer for the descriptor contents
579 * @buf_size: size of the output buffer. 0 to query the size
581 * fsverity does a two pass setup for reading the descriptor, in the first pass
582 * it calls with buf_size = 0 to query the size of the descriptor, and then in
583 * the second pass it actually reads the descriptor off disk.
585 * Returns the size on success or a negative error code on failure.
587 static int btrfs_get_verity_descriptor(struct inode *inode, void *buf,
592 struct btrfs_verity_descriptor_item item;
594 memset(&item, 0, sizeof(item));
595 ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_DESC_ITEM_KEY, 0,
596 (char *)&item, sizeof(item), NULL);
600 if (item.reserved[0] != 0 || item.reserved[1] != 0)
603 true_size = btrfs_stack_verity_descriptor_size(&item);
604 if (true_size > INT_MAX)
609 if (buf_size < true_size)
612 ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_DESC_ITEM_KEY, 1,
613 buf, buf_size, NULL);
616 if (ret != true_size)
623 * fsverity op that reads and caches a merkle tree page.
625 * @inode: inode to read a merkle tree page for
626 * @index: page index relative to the start of the merkle tree
627 * @num_ra_pages: number of pages to readahead. Optional, we ignore it
629 * The Merkle tree is stored in the filesystem btree, but its pages are cached
630 * with a logical position past EOF in the inode's mapping.
632 * Returns the page we read, or an ERR_PTR on error.
634 static struct page *btrfs_read_merkle_tree_page(struct inode *inode,
636 unsigned long num_ra_pages)
639 u64 off = (u64)index << PAGE_SHIFT;
640 loff_t merkle_pos = merkle_file_pos(inode);
644 return ERR_PTR(merkle_pos);
645 if (merkle_pos > inode->i_sb->s_maxbytes - off - PAGE_SIZE)
646 return ERR_PTR(-EFBIG);
647 index += merkle_pos >> PAGE_SHIFT;
649 page = find_get_page_flags(inode->i_mapping, index, FGP_ACCESSED);
651 if (PageUptodate(page))
656 * We only insert uptodate pages, so !Uptodate has to be
659 if (!PageUptodate(page)) {
662 return ERR_PTR(-EIO);
668 page = __page_cache_alloc(mapping_gfp_constraint(inode->i_mapping, ~__GFP_FS));
670 return ERR_PTR(-ENOMEM);
673 * Merkle item keys are indexed from byte 0 in the merkle tree.
674 * They have the form:
676 * [ inode objectid, BTRFS_MERKLE_ITEM_KEY, offset in bytes ]
678 ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_MERKLE_ITEM_KEY, off,
679 page_address(page), PAGE_SIZE, page);
685 memzero_page(page, ret, PAGE_SIZE - ret);
687 SetPageUptodate(page);
688 ret = add_to_page_cache_lru(page, inode->i_mapping, index, GFP_NOFS);
691 /* Inserted and ready for fsverity */
695 /* Did someone race us into inserting this page? */
704 * fsverity op that writes a Merkle tree block into the btree.
706 * @inode: inode to write a Merkle tree block for
707 * @buf: Merkle tree data block to write
708 * @index: index of the block in the Merkle tree
709 * @log_blocksize: log base 2 of the Merkle tree block size
711 * Note that the block size could be different from the page size, so it is not
712 * safe to assume that index is a page index.
714 * Returns 0 on success or negative error code on failure
716 static int btrfs_write_merkle_tree_block(struct inode *inode, const void *buf,
717 u64 index, int log_blocksize)
719 u64 off = index << log_blocksize;
720 u64 len = 1ULL << log_blocksize;
721 loff_t merkle_pos = merkle_file_pos(inode);
725 if (merkle_pos > inode->i_sb->s_maxbytes - off - len)
728 return write_key_bytes(BTRFS_I(inode), BTRFS_VERITY_MERKLE_ITEM_KEY,
732 const struct fsverity_operations btrfs_verityops = {
733 .begin_enable_verity = btrfs_begin_enable_verity,
734 .end_enable_verity = btrfs_end_enable_verity,
735 .get_verity_descriptor = btrfs_get_verity_descriptor,
736 .read_merkle_tree_page = btrfs_read_merkle_tree_page,
737 .write_merkle_tree_block = btrfs_write_merkle_tree_block,