xref: /kernel/linux/linux-5.10/fs/verity/verify.c (revision 8c2ecf20)
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * fs/verity/verify.c: data verification functions, i.e. hooks for ->readpages()
4 *
5 * Copyright 2019 Google LLC
6 */
7
8#include "fsverity_private.h"
9
10#include <crypto/hash.h>
11#include <linux/bio.h>
12#include <linux/ratelimit.h>
13
14static struct workqueue_struct *fsverity_read_workqueue;
15
16/**
17 * hash_at_level() - compute the location of the block's hash at the given level
18 *
19 * @params:	(in) the Merkle tree parameters
20 * @dindex:	(in) the index of the data block being verified
21 * @level:	(in) the level of hash we want (0 is leaf level)
22 * @hindex:	(out) the index of the hash block containing the wanted hash
23 * @hoffset:	(out) the byte offset to the wanted hash within the hash block
24 */
25static void hash_at_level(const struct merkle_tree_params *params,
26			  pgoff_t dindex, unsigned int level, pgoff_t *hindex,
27			  unsigned int *hoffset)
28{
29	pgoff_t position;
30
31	/* Offset of the hash within the level's region, in hashes */
32	position = dindex >> (level * params->log_arity);
33
34	/* Index of the hash block in the tree overall */
35	*hindex = params->level_start[level] + (position >> params->log_arity);
36
37	/* Offset of the wanted hash (in bytes) within the hash block */
38	*hoffset = (position & ((1 << params->log_arity) - 1)) <<
39		   (params->log_blocksize - params->log_arity);
40}
41
42/* Extract a hash from a hash page */
43static void extract_hash(struct page *hpage, unsigned int hoffset,
44			 unsigned int hsize, u8 *out)
45{
46	void *virt = kmap_atomic(hpage);
47
48	memcpy(out, virt + hoffset, hsize);
49	kunmap_atomic(virt);
50}
51
52static inline int cmp_hashes(const struct fsverity_info *vi,
53			     const u8 *want_hash, const u8 *real_hash,
54			     pgoff_t index, int level)
55{
56	const unsigned int hsize = vi->tree_params.digest_size;
57
58	if (memcmp(want_hash, real_hash, hsize) == 0)
59		return 0;
60
61	fsverity_err(vi->inode,
62		     "FILE CORRUPTED! index=%lu, level=%d, want_hash=%s:%*phN, real_hash=%s:%*phN",
63		     index, level,
64		     vi->tree_params.hash_alg->name, hsize, want_hash,
65		     vi->tree_params.hash_alg->name, hsize, real_hash);
66	return -EBADMSG;
67}
68
69/*
70 * Verify a single data page against the file's Merkle tree.
71 *
72 * In principle, we need to verify the entire path to the root node.  However,
73 * for efficiency the filesystem may cache the hash pages.  Therefore we need
74 * only ascend the tree until an already-verified page is seen, as indicated by
75 * the PageChecked bit being set; then verify the path to that page.
76 *
77 * This code currently only supports the case where the verity block size is
78 * equal to PAGE_SIZE.  Doing otherwise would be possible but tricky, since we
79 * wouldn't be able to use the PageChecked bit.
80 *
81 * Note that multiple processes may race to verify a hash page and mark it
82 * Checked, but it doesn't matter; the result will be the same either way.
83 *
84 * Return: true if the page is valid, else false.
85 */
86static bool verify_page(struct inode *inode, const struct fsverity_info *vi,
87			struct ahash_request *req, struct page *data_page,
88			unsigned long level0_ra_pages)
89{
90	const struct merkle_tree_params *params = &vi->tree_params;
91	const unsigned int hsize = params->digest_size;
92	const pgoff_t index = data_page->index;
93	int level;
94	u8 _want_hash[FS_VERITY_MAX_DIGEST_SIZE];
95	const u8 *want_hash;
96	u8 real_hash[FS_VERITY_MAX_DIGEST_SIZE];
97	struct page *hpages[FS_VERITY_MAX_LEVELS];
98	unsigned int hoffsets[FS_VERITY_MAX_LEVELS];
99	int err;
100
101	if (WARN_ON_ONCE(!PageLocked(data_page) || PageUptodate(data_page)))
102		return false;
103
104	pr_debug_ratelimited("Verifying data page %lu...\n", index);
105
106#ifdef CONFIG_SECURITY_CODE_SIGN
107	if (index >= DIV_ROUND_UP(vi->verified_data_size, PAGE_SIZE)) {
108		pr_debug_ratelimited("Data out of verity range %lu\n",
109			vi->verified_data_size >> PAGE_SHIFT);
110		return true;
111	}
112#endif
113	/*
114	 * Starting at the leaf level, ascend the tree saving hash pages along
115	 * the way until we find a verified hash page, indicated by PageChecked;
116	 * or until we reach the root.
117	 */
118	for (level = 0; level < params->num_levels; level++) {
119		pgoff_t hindex;
120		unsigned int hoffset;
121		struct page *hpage;
122
123		hash_at_level(params, index, level, &hindex, &hoffset);
124
125		pr_debug_ratelimited("Level %d: hindex=%lu, hoffset=%u\n",
126				     level, hindex, hoffset);
127
128		hpage = inode->i_sb->s_vop->read_merkle_tree_page(inode, hindex,
129				level == 0 ? level0_ra_pages : 0);
130		if (IS_ERR(hpage)) {
131			err = PTR_ERR(hpage);
132			fsverity_err(inode,
133				     "Error %d reading Merkle tree page %lu",
134				     err, hindex);
135			goto out;
136		}
137
138		if (PageChecked(hpage)) {
139			extract_hash(hpage, hoffset, hsize, _want_hash);
140			want_hash = _want_hash;
141			put_page(hpage);
142			pr_debug_ratelimited("Hash page already checked, want %s:%*phN\n",
143					     params->hash_alg->name,
144					     hsize, want_hash);
145			goto descend;
146		}
147		pr_debug_ratelimited("Hash page not yet checked\n");
148		hpages[level] = hpage;
149		hoffsets[level] = hoffset;
150	}
151
152	want_hash = vi->root_hash;
153	pr_debug("Want root hash: %s:%*phN\n",
154		 params->hash_alg->name, hsize, want_hash);
155descend:
156	/* Descend the tree verifying hash pages */
157	for (; level > 0; level--) {
158		struct page *hpage = hpages[level - 1];
159		unsigned int hoffset = hoffsets[level - 1];
160
161		err = fsverity_hash_page(params, inode, req, hpage, real_hash);
162		if (err)
163			goto out;
164		err = cmp_hashes(vi, want_hash, real_hash, index, level - 1);
165		if (err)
166			goto out;
167		SetPageChecked(hpage);
168		extract_hash(hpage, hoffset, hsize, _want_hash);
169		want_hash = _want_hash;
170		put_page(hpage);
171		pr_debug("Verified hash page at level %d, now want %s:%*phN\n",
172			 level - 1, params->hash_alg->name, hsize, want_hash);
173	}
174
175	/* Finally, verify the data page */
176	err = fsverity_hash_page(params, inode, req, data_page, real_hash);
177	if (err)
178		goto out;
179	err = cmp_hashes(vi, want_hash, real_hash, index, -1);
180out:
181	for (; level > 0; level--)
182		put_page(hpages[level - 1]);
183
184	return err == 0;
185}
186
187/**
188 * fsverity_verify_page() - verify a data page
189 * @page: the page to verity
190 *
191 * Verify a page that has just been read from a verity file.  The page must be a
192 * pagecache page that is still locked and not yet uptodate.
193 *
194 * Return: true if the page is valid, else false.
195 */
196bool fsverity_verify_page(struct page *page)
197{
198	struct inode *inode = page->mapping->host;
199	const struct fsverity_info *vi = inode->i_verity_info;
200	struct ahash_request *req;
201	bool valid;
202
203	/* This allocation never fails, since it's mempool-backed. */
204	req = fsverity_alloc_hash_request(vi->tree_params.hash_alg, GFP_NOFS);
205
206	valid = verify_page(inode, vi, req, page, 0);
207
208	fsverity_free_hash_request(vi->tree_params.hash_alg, req);
209
210	return valid;
211}
212EXPORT_SYMBOL_GPL(fsverity_verify_page);
213
214#ifdef CONFIG_BLOCK
215/**
216 * fsverity_verify_bio() - verify a 'read' bio that has just completed
217 * @bio: the bio to verify
218 *
219 * Verify a set of pages that have just been read from a verity file.  The pages
220 * must be pagecache pages that are still locked and not yet uptodate.  Pages
221 * that fail verification are set to the Error state.  Verification is skipped
222 * for pages already in the Error state, e.g. due to fscrypt decryption failure.
223 *
224 * This is a helper function for use by the ->readpages() method of filesystems
225 * that issue bios to read data directly into the page cache.  Filesystems that
226 * populate the page cache without issuing bios (e.g. non block-based
227 * filesystems) must instead call fsverity_verify_page() directly on each page.
228 * All filesystems must also call fsverity_verify_page() on holes.
229 */
230void fsverity_verify_bio(struct bio *bio)
231{
232	struct inode *inode = bio_first_page_all(bio)->mapping->host;
233	const struct fsverity_info *vi = inode->i_verity_info;
234	const struct merkle_tree_params *params = &vi->tree_params;
235	struct ahash_request *req;
236	struct bio_vec *bv;
237	struct bvec_iter_all iter_all;
238	unsigned long max_ra_pages = 0;
239
240	/* This allocation never fails, since it's mempool-backed. */
241	req = fsverity_alloc_hash_request(params->hash_alg, GFP_NOFS);
242
243	if (bio->bi_opf & REQ_RAHEAD) {
244		/*
245		 * If this bio is for data readahead, then we also do readahead
246		 * of the first (largest) level of the Merkle tree.  Namely,
247		 * when a Merkle tree page is read, we also try to piggy-back on
248		 * some additional pages -- up to 1/4 the number of data pages.
249		 *
250		 * This improves sequential read performance, as it greatly
251		 * reduces the number of I/O requests made to the Merkle tree.
252		 */
253		bio_for_each_segment_all(bv, bio, iter_all)
254			max_ra_pages++;
255		max_ra_pages /= 4;
256	}
257
258	bio_for_each_segment_all(bv, bio, iter_all) {
259		struct page *page = bv->bv_page;
260		unsigned long level0_index = page->index >> params->log_arity;
261		unsigned long level0_ra_pages =
262			min(max_ra_pages, params->level0_blocks - level0_index);
263
264		if (!PageError(page) &&
265		    !verify_page(inode, vi, req, page, level0_ra_pages))
266			SetPageError(page);
267	}
268
269	fsverity_free_hash_request(params->hash_alg, req);
270}
271EXPORT_SYMBOL_GPL(fsverity_verify_bio);
272#endif /* CONFIG_BLOCK */
273
274
275/**
276 * fsverity_get_verified_data_size() - get verified data size of a verity file
277 * @inode: the file's inode
278 *
279 * Return: verified data size
280 */
281u64 fsverity_get_verified_data_size(const struct inode *inode)
282{
283#ifdef CONFIG_SECURITY_CODE_SIGN
284	return fsverity_get_info(inode)->verified_data_size;
285#else
286	return inode->i_size;
287#endif
288}
289
290
291/**
292 * fsverity_enqueue_verify_work() - enqueue work on the fs-verity workqueue
293 * @work: the work to enqueue
294 *
295 * Enqueue verification work for asynchronous processing.
296 */
297void fsverity_enqueue_verify_work(struct work_struct *work)
298{
299	queue_work(fsverity_read_workqueue, work);
300}
301EXPORT_SYMBOL_GPL(fsverity_enqueue_verify_work);
302
303int __init fsverity_init_workqueue(void)
304{
305	/*
306	 * Use a high-priority workqueue to prioritize verification work, which
307	 * blocks reads from completing, over regular application tasks.
308	 *
309	 * For performance reasons, don't use an unbound workqueue.  Using an
310	 * unbound workqueue for crypto operations causes excessive scheduler
311	 * latency on ARM64.
312	 */
313	fsverity_read_workqueue = alloc_workqueue("fsverity_read_queue",
314						  WQ_HIGHPRI,
315						  num_online_cpus());
316	if (!fsverity_read_workqueue)
317		return -ENOMEM;
318	return 0;
319}
320
321void __init fsverity_exit_workqueue(void)
322{
323	destroy_workqueue(fsverity_read_workqueue);
324	fsverity_read_workqueue = NULL;
325}
326