xref: /linux/fs/verity/verify.c (revision 64275e9fda3702bfb5ab3b95f7c2b9b414667164)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Data verification functions, i.e. hooks for ->readahead()
4  *
5  * Copyright 2019 Google LLC
6  */
7 
8 #include "fsverity_private.h"
9 
10 #include <linux/bio.h>
11 #include <linux/export.h>
12 
13 #define FS_VERITY_MAX_PENDING_BLOCKS 2
14 
15 struct fsverity_pending_block {
16 	const void *data;
17 	u64 pos;
18 	u8 real_hash[FS_VERITY_MAX_DIGEST_SIZE];
19 };
20 
21 struct fsverity_verification_context {
22 	struct fsverity_info *vi;
23 
24 	/*
25 	 * This is the queue of data blocks that are pending verification.  When
26 	 * the crypto layer supports interleaved hashing, we allow multiple
27 	 * blocks to be queued up in order to utilize it.  This can improve
28 	 * performance significantly vs. sequential hashing of each block.
29 	 */
30 	int num_pending;
31 	int max_pending;
32 	struct fsverity_pending_block
33 		pending_blocks[FS_VERITY_MAX_PENDING_BLOCKS];
34 };
35 
36 static struct workqueue_struct *fsverity_read_workqueue;
37 
38 /**
39  * fsverity_readahead() - kick off readahead on fsverity hashes
40  * @vi:			fsverity_info for the inode to be read
41  * @index:		first file data page index that is being read
42  * @nr_pages:		number of file data pages to be read
43  *
44  * Start readahead on the fsverity hashes that are needed to verify the file
45  * data in the range from @index to @index + @nr_pages (exclusive upper bound).
46  *
47  * To be called from the file systems' ->read_folio and ->readahead methods to
48  * ensure that the hashes are already cached on completion of the file data
49  * read if possible.
50  */
51 void fsverity_readahead(struct fsverity_info *vi, pgoff_t index,
52 			unsigned long nr_pages)
53 {
54 	struct inode *inode = vi->inode;
55 	const struct merkle_tree_params *params = &vi->tree_params;
56 	u64 start_hidx = (u64)index << params->log_blocks_per_page;
57 	u64 end_hidx =
58 		(((u64)index + nr_pages) << params->log_blocks_per_page) - 1;
59 	int level;
60 
61 	if (!inode->i_sb->s_vop->readahead_merkle_tree)
62 		return;
63 
64 	for (level = 0; level < params->num_levels; level++) {
65 		unsigned long level_start = params->level_start[level];
66 		unsigned long next_start_hidx = start_hidx >> params->log_arity;
67 		unsigned long next_end_hidx = end_hidx >> params->log_arity;
68 		pgoff_t start_idx = (level_start + next_start_hidx) >>
69 				    params->log_blocks_per_page;
70 		pgoff_t end_idx = (level_start + next_end_hidx) >>
71 				  params->log_blocks_per_page;
72 
73 		inode->i_sb->s_vop->readahead_merkle_tree(
74 			inode, start_idx, end_idx - start_idx + 1);
75 
76 		start_hidx = next_start_hidx;
77 		end_hidx = next_end_hidx;
78 	}
79 }
80 EXPORT_SYMBOL_GPL(fsverity_readahead);
81 
82 /*
83  * Returns true if the hash block with index @hblock_idx in the tree, located in
84  * @hpage, has already been verified.
85  */
86 static bool is_hash_block_verified(struct fsverity_info *vi, struct page *hpage,
87 				   unsigned long hblock_idx)
88 {
89 	unsigned int blocks_per_page;
90 	unsigned int i;
91 
92 	/*
93 	 * When the Merkle tree block size and page size are the same, then the
94 	 * ->hash_block_verified bitmap isn't allocated, and we use PG_checked
95 	 * to directly indicate whether the page's block has been verified.
96 	 *
97 	 * Using PG_checked also guarantees that we re-verify hash pages that
98 	 * get evicted and re-instantiated from the backing storage, as new
99 	 * pages always start out with PG_checked cleared.
100 	 */
101 	if (!vi->hash_block_verified)
102 		return PageChecked(hpage);
103 
104 	/*
105 	 * When the Merkle tree block size and page size differ, we use a bitmap
106 	 * to indicate whether each hash block has been verified.
107 	 *
108 	 * However, we still need to ensure that hash pages that get evicted and
109 	 * re-instantiated from the backing storage are re-verified.  To do
110 	 * this, we use PG_checked again, but now it doesn't really mean
111 	 * "checked".  Instead, now it just serves as an indicator for whether
112 	 * the hash page is newly instantiated or not.  If the page is new, as
113 	 * indicated by PG_checked=0, we clear the bitmap bits for the page's
114 	 * blocks since they are untrustworthy, then set PG_checked=1.
115 	 * Otherwise we return the bitmap bit for the requested block.
116 	 *
117 	 * Multiple threads may execute this code concurrently on the same page.
118 	 * This is safe because we use memory barriers to ensure that if a
119 	 * thread sees PG_checked=1, then it also sees the associated bitmap
120 	 * clearing to have occurred.  Also, all writes and their corresponding
121 	 * reads are atomic, and all writes are safe to repeat in the event that
122 	 * multiple threads get into the PG_checked=0 section.  (Clearing a
123 	 * bitmap bit again at worst causes a hash block to be verified
124 	 * redundantly.  That event should be very rare, so it's not worth using
125 	 * a lock to avoid.  Setting PG_checked again has no effect.)
126 	 */
127 	if (PageChecked(hpage)) {
128 		/*
129 		 * A read memory barrier is needed here to give ACQUIRE
130 		 * semantics to the above PageChecked() test.
131 		 */
132 		smp_rmb();
133 		return test_bit(hblock_idx, vi->hash_block_verified);
134 	}
135 	blocks_per_page = vi->tree_params.blocks_per_page;
136 	hblock_idx = round_down(hblock_idx, blocks_per_page);
137 	for (i = 0; i < blocks_per_page; i++)
138 		clear_bit(hblock_idx + i, vi->hash_block_verified);
139 	/*
140 	 * A write memory barrier is needed here to give RELEASE semantics to
141 	 * the below SetPageChecked() operation.
142 	 */
143 	smp_wmb();
144 	SetPageChecked(hpage);
145 	return false;
146 }
147 
148 /*
149  * Verify the hash of a single data block against the file's Merkle tree.
150  *
151  * In principle, we need to verify the entire path to the root node.  However,
152  * for efficiency the filesystem may cache the hash blocks.  Therefore we need
153  * only ascend the tree until an already-verified hash block is seen, and then
154  * verify the path to that block.
155  *
156  * Return: %true if the data block is valid, else %false.
157  */
158 static bool verify_data_block(struct fsverity_info *vi,
159 			      const struct fsverity_pending_block *dblock)
160 {
161 	struct inode *inode = vi->inode;
162 	const u64 data_pos = dblock->pos;
163 	const struct merkle_tree_params *params = &vi->tree_params;
164 	const unsigned int hsize = params->digest_size;
165 	int level;
166 	u8 _want_hash[FS_VERITY_MAX_DIGEST_SIZE];
167 	const u8 *want_hash;
168 	u8 real_hash[FS_VERITY_MAX_DIGEST_SIZE];
169 	/* The hash blocks that are traversed, indexed by level */
170 	struct {
171 		/* Page containing the hash block */
172 		struct page *page;
173 		/* Mapped address of the hash block (will be within @page) */
174 		const void *addr;
175 		/* Index of the hash block in the tree overall */
176 		unsigned long index;
177 		/* Byte offset of the wanted hash relative to @addr */
178 		unsigned int hoffset;
179 	} hblocks[FS_VERITY_MAX_LEVELS];
180 	/*
181 	 * The index of the previous level's block within that level; also the
182 	 * index of that block's hash within the current level.
183 	 */
184 	u64 hidx = data_pos >> params->log_blocksize;
185 
186 	/*
187 	 * Up to FS_VERITY_MAX_PENDING_BLOCKS + FS_VERITY_MAX_LEVELS pages may
188 	 * be mapped at once.
189 	 */
190 	static_assert(FS_VERITY_MAX_PENDING_BLOCKS + FS_VERITY_MAX_LEVELS <=
191 		      KM_MAX_IDX);
192 
193 	if (unlikely(data_pos >= inode->i_size)) {
194 		/*
195 		 * This can happen in the data page spanning EOF when the Merkle
196 		 * tree block size is less than the page size.  The Merkle tree
197 		 * doesn't cover data blocks fully past EOF.  But the entire
198 		 * page spanning EOF can be visible to userspace via a mmap, and
199 		 * any part past EOF should be all zeroes.  Therefore, we need
200 		 * to verify that any data blocks fully past EOF are all zeroes.
201 		 */
202 		if (memchr_inv(dblock->data, 0, params->block_size)) {
203 			fsverity_err(inode,
204 				     "FILE CORRUPTED!  Data past EOF is not zeroed");
205 			return false;
206 		}
207 		return true;
208 	}
209 
210 	/*
211 	 * Starting at the leaf level, ascend the tree saving hash blocks along
212 	 * the way until we find a hash block that has already been verified, or
213 	 * until we reach the root.
214 	 */
215 	for (level = 0; level < params->num_levels; level++) {
216 		unsigned long next_hidx;
217 		unsigned long hblock_idx;
218 		pgoff_t hpage_idx;
219 		unsigned int hblock_offset_in_page;
220 		unsigned int hoffset;
221 		struct page *hpage;
222 		const void *haddr;
223 
224 		/*
225 		 * The index of the block in the current level; also the index
226 		 * of that block's hash within the next level.
227 		 */
228 		next_hidx = hidx >> params->log_arity;
229 
230 		/* Index of the hash block in the tree overall */
231 		hblock_idx = params->level_start[level] + next_hidx;
232 
233 		/* Index of the hash page in the tree overall */
234 		hpage_idx = hblock_idx >> params->log_blocks_per_page;
235 
236 		/* Byte offset of the hash block within the page */
237 		hblock_offset_in_page =
238 			(hblock_idx << params->log_blocksize) & ~PAGE_MASK;
239 
240 		/* Byte offset of the hash within the block */
241 		hoffset = (hidx << params->log_digestsize) &
242 			  (params->block_size - 1);
243 
244 		hpage = inode->i_sb->s_vop->read_merkle_tree_page(inode,
245 								  hpage_idx);
246 		if (IS_ERR(hpage)) {
247 			fsverity_err(inode,
248 				     "Error %ld reading Merkle tree page %lu",
249 				     PTR_ERR(hpage), hpage_idx);
250 			goto error;
251 		}
252 		haddr = kmap_local_page(hpage) + hblock_offset_in_page;
253 		if (is_hash_block_verified(vi, hpage, hblock_idx)) {
254 			memcpy(_want_hash, haddr + hoffset, hsize);
255 			want_hash = _want_hash;
256 			kunmap_local(haddr);
257 			put_page(hpage);
258 			goto descend;
259 		}
260 		hblocks[level].page = hpage;
261 		hblocks[level].addr = haddr;
262 		hblocks[level].index = hblock_idx;
263 		hblocks[level].hoffset = hoffset;
264 		hidx = next_hidx;
265 	}
266 
267 	want_hash = vi->root_hash;
268 descend:
269 	/* Descend the tree verifying hash blocks. */
270 	for (; level > 0; level--) {
271 		struct page *hpage = hblocks[level - 1].page;
272 		const void *haddr = hblocks[level - 1].addr;
273 		unsigned long hblock_idx = hblocks[level - 1].index;
274 		unsigned int hoffset = hblocks[level - 1].hoffset;
275 
276 		fsverity_hash_block(params, haddr, real_hash);
277 		if (memcmp(want_hash, real_hash, hsize) != 0)
278 			goto corrupted;
279 		/*
280 		 * Mark the hash block as verified.  This must be atomic and
281 		 * idempotent, as the same hash block might be verified by
282 		 * multiple threads concurrently.
283 		 */
284 		if (vi->hash_block_verified)
285 			set_bit(hblock_idx, vi->hash_block_verified);
286 		else
287 			SetPageChecked(hpage);
288 		memcpy(_want_hash, haddr + hoffset, hsize);
289 		want_hash = _want_hash;
290 		kunmap_local(haddr);
291 		put_page(hpage);
292 	}
293 
294 	/* Finally, verify the hash of the data block. */
295 	if (memcmp(want_hash, dblock->real_hash, hsize) != 0)
296 		goto corrupted;
297 	return true;
298 
299 corrupted:
300 	fsverity_err(
301 		inode,
302 		"FILE CORRUPTED! pos=%llu, level=%d, want_hash=%s:%*phN, real_hash=%s:%*phN",
303 		data_pos, level - 1, params->hash_alg->name, hsize, want_hash,
304 		params->hash_alg->name, hsize,
305 		level == 0 ? dblock->real_hash : real_hash);
306 error:
307 	for (; level > 0; level--) {
308 		kunmap_local(hblocks[level - 1].addr);
309 		put_page(hblocks[level - 1].page);
310 	}
311 	return false;
312 }
313 
314 static void
315 fsverity_init_verification_context(struct fsverity_verification_context *ctx,
316 				   struct fsverity_info *vi)
317 {
318 	ctx->vi = vi;
319 	ctx->num_pending = 0;
320 	if (vi->tree_params.hash_alg->algo_id == HASH_ALGO_SHA256 &&
321 	    sha256_finup_2x_is_optimized())
322 		ctx->max_pending = 2;
323 	else
324 		ctx->max_pending = 1;
325 }
326 
327 static void
328 fsverity_clear_pending_blocks(struct fsverity_verification_context *ctx)
329 {
330 	int i;
331 
332 	for (i = ctx->num_pending - 1; i >= 0; i--) {
333 		kunmap_local(ctx->pending_blocks[i].data);
334 		ctx->pending_blocks[i].data = NULL;
335 	}
336 	ctx->num_pending = 0;
337 }
338 
339 static bool
340 fsverity_verify_pending_blocks(struct fsverity_verification_context *ctx)
341 {
342 	struct fsverity_info *vi = ctx->vi;
343 	const struct merkle_tree_params *params = &vi->tree_params;
344 	int i;
345 
346 	if (ctx->num_pending == 2) {
347 		/* num_pending == 2 implies that the algorithm is SHA-256 */
348 		sha256_finup_2x(params->hashstate ? &params->hashstate->sha256 :
349 						    NULL,
350 				ctx->pending_blocks[0].data,
351 				ctx->pending_blocks[1].data, params->block_size,
352 				ctx->pending_blocks[0].real_hash,
353 				ctx->pending_blocks[1].real_hash);
354 	} else {
355 		for (i = 0; i < ctx->num_pending; i++)
356 			fsverity_hash_block(params, ctx->pending_blocks[i].data,
357 					    ctx->pending_blocks[i].real_hash);
358 	}
359 
360 	for (i = 0; i < ctx->num_pending; i++) {
361 		if (!verify_data_block(vi, &ctx->pending_blocks[i]))
362 			return false;
363 	}
364 	fsverity_clear_pending_blocks(ctx);
365 	return true;
366 }
367 
368 static bool fsverity_add_data_blocks(struct fsverity_verification_context *ctx,
369 				     struct folio *data_folio, size_t len,
370 				     size_t offset)
371 {
372 	struct fsverity_info *vi = ctx->vi;
373 	const struct merkle_tree_params *params = &vi->tree_params;
374 	const unsigned int block_size = params->block_size;
375 	u64 pos = (u64)data_folio->index << PAGE_SHIFT;
376 
377 	if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offset, block_size)))
378 		return false;
379 	if (WARN_ON_ONCE(!folio_test_locked(data_folio) ||
380 			 folio_test_uptodate(data_folio)))
381 		return false;
382 	do {
383 		ctx->pending_blocks[ctx->num_pending].data =
384 			kmap_local_folio(data_folio, offset);
385 		ctx->pending_blocks[ctx->num_pending].pos = pos + offset;
386 		if (++ctx->num_pending == ctx->max_pending &&
387 		    !fsverity_verify_pending_blocks(ctx))
388 			return false;
389 		offset += block_size;
390 		len -= block_size;
391 	} while (len);
392 	return true;
393 }
394 
395 /**
396  * fsverity_verify_blocks() - verify data in a folio
397  * @vi: fsverity_info for the inode to be read
398  * @folio: the folio containing the data to verify
399  * @len: the length of the data to verify in the folio
400  * @offset: the offset of the data to verify in the folio
401  *
402  * Verify data that has just been read from a verity file.  The data must be
403  * located in a pagecache folio that is still locked and not yet uptodate.  The
404  * length and offset of the data must be Merkle tree block size aligned.
405  *
406  * Return: %true if the data is valid, else %false.
407  */
408 bool fsverity_verify_blocks(struct fsverity_info *vi, struct folio *folio,
409 			    size_t len, size_t offset)
410 {
411 	struct fsverity_verification_context ctx;
412 
413 	fsverity_init_verification_context(&ctx, vi);
414 
415 	if (fsverity_add_data_blocks(&ctx, folio, len, offset) &&
416 	    fsverity_verify_pending_blocks(&ctx))
417 		return true;
418 	fsverity_clear_pending_blocks(&ctx);
419 	return false;
420 }
421 EXPORT_SYMBOL_GPL(fsverity_verify_blocks);
422 
423 #ifdef CONFIG_BLOCK
424 /**
425  * fsverity_verify_bio() - verify a 'read' bio that has just completed
426  * @vi: fsverity_info for the inode to be read
427  * @bio: the bio to verify
428  *
429  * Verify the bio's data against the file's Merkle tree.  All bio data segments
430  * must be aligned to the file's Merkle tree block size.  If any data fails
431  * verification, then bio->bi_status is set to an error status.
432  *
433  * This is a helper function for use by the ->readahead() method of filesystems
434  * that issue bios to read data directly into the page cache.  Filesystems that
435  * populate the page cache without issuing bios (e.g. non block-based
436  * filesystems) must instead call fsverity_verify_page() directly on each page.
437  * All filesystems must also call fsverity_verify_page() on holes.
438  */
439 void fsverity_verify_bio(struct fsverity_info *vi, struct bio *bio)
440 {
441 	struct fsverity_verification_context ctx;
442 	struct folio_iter fi;
443 
444 	fsverity_init_verification_context(&ctx, vi);
445 
446 	bio_for_each_folio_all(fi, bio) {
447 		if (!fsverity_add_data_blocks(&ctx, fi.folio, fi.length,
448 					      fi.offset))
449 			goto ioerr;
450 	}
451 
452 	if (!fsverity_verify_pending_blocks(&ctx))
453 		goto ioerr;
454 	return;
455 
456 ioerr:
457 	fsverity_clear_pending_blocks(&ctx);
458 	bio->bi_status = BLK_STS_IOERR;
459 }
460 EXPORT_SYMBOL_GPL(fsverity_verify_bio);
461 #endif /* CONFIG_BLOCK */
462 
463 /**
464  * fsverity_enqueue_verify_work() - enqueue work on the fs-verity workqueue
465  * @work: the work to enqueue
466  *
467  * Enqueue verification work for asynchronous processing.
468  */
469 void fsverity_enqueue_verify_work(struct work_struct *work)
470 {
471 	queue_work(fsverity_read_workqueue, work);
472 }
473 EXPORT_SYMBOL_GPL(fsverity_enqueue_verify_work);
474 
475 void __init fsverity_init_workqueue(void)
476 {
477 	/*
478 	 * Use a high-priority workqueue to prioritize verification work, which
479 	 * blocks reads from completing, over regular application tasks.
480 	 *
481 	 * For performance reasons, don't use an unbound workqueue.  Using an
482 	 * unbound workqueue for crypto operations causes excessive scheduler
483 	 * latency on ARM64.
484 	 */
485 	fsverity_read_workqueue = alloc_workqueue("fsverity_read_queue",
486 						  WQ_HIGHPRI | WQ_PERCPU,
487 						  num_online_cpus());
488 	if (!fsverity_read_workqueue)
489 		panic("failed to allocate fsverity_read_queue");
490 }
491