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