• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2012 Red Hat, Inc.
4  *
5  * Author: Mikulas Patocka <mpatocka@redhat.com>
6  *
7  * Based on Chromium dm-verity driver (C) 2011 The Chromium OS Authors
8  *
9  * In the file "/sys/module/dm_verity/parameters/prefetch_cluster" you can set
10  * default prefetch value. Data are read in "prefetch_cluster" chunks from the
11  * hash device. Setting this greatly improves performance when data and hash
12  * are on the same disk on different partitions on devices with poor random
13  * access behavior.
14  */
15 
16 #include "dm-verity.h"
17 #include "dm-verity-fec.h"
18 #include "dm-verity-verify-sig.h"
19 #include <linux/module.h>
20 #include <linux/reboot.h>
21 
22 #define DM_MSG_PREFIX			"verity"
23 
24 #define DM_VERITY_ENV_LENGTH		42
25 #define DM_VERITY_ENV_VAR_NAME		"DM_VERITY_ERR_BLOCK_NR"
26 
27 #define DM_VERITY_DEFAULT_PREFETCH_SIZE	262144
28 
29 #define DM_VERITY_MAX_CORRUPTED_ERRS	100
30 
31 #define DM_VERITY_OPT_LOGGING		"ignore_corruption"
32 #define DM_VERITY_OPT_RESTART		"restart_on_corruption"
33 #define DM_VERITY_OPT_IGN_ZEROES	"ignore_zero_blocks"
34 #define DM_VERITY_OPT_AT_MOST_ONCE	"check_at_most_once"
35 
36 #define DM_VERITY_OPTS_MAX		(2 + DM_VERITY_OPTS_FEC + \
37 					 DM_VERITY_ROOT_HASH_VERIFICATION_OPTS)
38 
39 static unsigned dm_verity_prefetch_cluster = DM_VERITY_DEFAULT_PREFETCH_SIZE;
40 
41 module_param_named(prefetch_cluster, dm_verity_prefetch_cluster, uint, S_IRUGO | S_IWUSR);
42 
43 struct dm_verity_prefetch_work {
44 	struct work_struct work;
45 	struct dm_verity *v;
46 	sector_t block;
47 	unsigned n_blocks;
48 };
49 
50 /*
51  * Auxiliary structure appended to each dm-bufio buffer. If the value
52  * hash_verified is nonzero, hash of the block has been verified.
53  *
54  * The variable hash_verified is set to 0 when allocating the buffer, then
55  * it can be changed to 1 and it is never reset to 0 again.
56  *
57  * There is no lock around this value, a race condition can at worst cause
58  * that multiple processes verify the hash of the same buffer simultaneously
59  * and write 1 to hash_verified simultaneously.
60  * This condition is harmless, so we don't need locking.
61  */
62 struct buffer_aux {
63 	int hash_verified;
64 };
65 
66 /*
67  * Initialize struct buffer_aux for a freshly created buffer.
68  */
dm_bufio_alloc_callback(struct dm_buffer * buf)69 static void dm_bufio_alloc_callback(struct dm_buffer *buf)
70 {
71 	struct buffer_aux *aux = dm_bufio_get_aux_data(buf);
72 
73 	aux->hash_verified = 0;
74 }
75 
76 /*
77  * Translate input sector number to the sector number on the target device.
78  */
verity_map_sector(struct dm_verity * v,sector_t bi_sector)79 static sector_t verity_map_sector(struct dm_verity *v, sector_t bi_sector)
80 {
81 	return v->data_start + dm_target_offset(v->ti, bi_sector);
82 }
83 
84 /*
85  * Return hash position of a specified block at a specified tree level
86  * (0 is the lowest level).
87  * The lowest "hash_per_block_bits"-bits of the result denote hash position
88  * inside a hash block. The remaining bits denote location of the hash block.
89  */
verity_position_at_level(struct dm_verity * v,sector_t block,int level)90 static sector_t verity_position_at_level(struct dm_verity *v, sector_t block,
91 					 int level)
92 {
93 	return block >> (level * v->hash_per_block_bits);
94 }
95 
verity_hash_update(struct dm_verity * v,struct ahash_request * req,const u8 * data,size_t len,struct crypto_wait * wait)96 static int verity_hash_update(struct dm_verity *v, struct ahash_request *req,
97 				const u8 *data, size_t len,
98 				struct crypto_wait *wait)
99 {
100 	struct scatterlist sg;
101 
102 	if (likely(!is_vmalloc_addr(data))) {
103 		sg_init_one(&sg, data, len);
104 		ahash_request_set_crypt(req, &sg, NULL, len);
105 		return crypto_wait_req(crypto_ahash_update(req), wait);
106 	} else {
107 		do {
108 			int r;
109 			size_t this_step = min_t(size_t, len, PAGE_SIZE - offset_in_page(data));
110 			flush_kernel_vmap_range((void *)data, this_step);
111 			sg_init_table(&sg, 1);
112 			sg_set_page(&sg, vmalloc_to_page(data), this_step, offset_in_page(data));
113 			ahash_request_set_crypt(req, &sg, NULL, this_step);
114 			r = crypto_wait_req(crypto_ahash_update(req), wait);
115 			if (unlikely(r))
116 				return r;
117 			data += this_step;
118 			len -= this_step;
119 		} while (len);
120 		return 0;
121 	}
122 }
123 
124 /*
125  * Wrapper for crypto_ahash_init, which handles verity salting.
126  */
verity_hash_init(struct dm_verity * v,struct ahash_request * req,struct crypto_wait * wait)127 static int verity_hash_init(struct dm_verity *v, struct ahash_request *req,
128 				struct crypto_wait *wait)
129 {
130 	int r;
131 
132 	ahash_request_set_tfm(req, v->tfm);
133 	ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP |
134 					CRYPTO_TFM_REQ_MAY_BACKLOG,
135 					crypto_req_done, (void *)wait);
136 	crypto_init_wait(wait);
137 
138 	r = crypto_wait_req(crypto_ahash_init(req), wait);
139 
140 	if (unlikely(r < 0)) {
141 		DMERR("crypto_ahash_init failed: %d", r);
142 		return r;
143 	}
144 
145 	if (likely(v->salt_size && (v->version >= 1)))
146 		r = verity_hash_update(v, req, v->salt, v->salt_size, wait);
147 
148 	return r;
149 }
150 
verity_hash_final(struct dm_verity * v,struct ahash_request * req,u8 * digest,struct crypto_wait * wait)151 static int verity_hash_final(struct dm_verity *v, struct ahash_request *req,
152 			     u8 *digest, struct crypto_wait *wait)
153 {
154 	int r;
155 
156 	if (unlikely(v->salt_size && (!v->version))) {
157 		r = verity_hash_update(v, req, v->salt, v->salt_size, wait);
158 
159 		if (r < 0) {
160 			DMERR("verity_hash_final failed updating salt: %d", r);
161 			goto out;
162 		}
163 	}
164 
165 	ahash_request_set_crypt(req, NULL, digest, 0);
166 	r = crypto_wait_req(crypto_ahash_final(req), wait);
167 out:
168 	return r;
169 }
170 
verity_hash(struct dm_verity * v,struct ahash_request * req,const u8 * data,size_t len,u8 * digest)171 int verity_hash(struct dm_verity *v, struct ahash_request *req,
172 		const u8 *data, size_t len, u8 *digest)
173 {
174 	int r;
175 	struct crypto_wait wait;
176 
177 	r = verity_hash_init(v, req, &wait);
178 	if (unlikely(r < 0))
179 		goto out;
180 
181 	r = verity_hash_update(v, req, data, len, &wait);
182 	if (unlikely(r < 0))
183 		goto out;
184 
185 	r = verity_hash_final(v, req, digest, &wait);
186 
187 out:
188 	return r;
189 }
190 
verity_hash_at_level(struct dm_verity * v,sector_t block,int level,sector_t * hash_block,unsigned * offset)191 static void verity_hash_at_level(struct dm_verity *v, sector_t block, int level,
192 				 sector_t *hash_block, unsigned *offset)
193 {
194 	sector_t position = verity_position_at_level(v, block, level);
195 	unsigned idx;
196 
197 	*hash_block = v->hash_level_block[level] + (position >> v->hash_per_block_bits);
198 
199 	if (!offset)
200 		return;
201 
202 	idx = position & ((1 << v->hash_per_block_bits) - 1);
203 	if (!v->version)
204 		*offset = idx * v->digest_size;
205 	else
206 		*offset = idx << (v->hash_dev_block_bits - v->hash_per_block_bits);
207 }
208 
209 /*
210  * Handle verification errors.
211  */
verity_handle_err(struct dm_verity * v,enum verity_block_type type,unsigned long long block)212 static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
213 			     unsigned long long block)
214 {
215 	char verity_env[DM_VERITY_ENV_LENGTH];
216 	char *envp[] = { verity_env, NULL };
217 	const char *type_str = "";
218 	struct mapped_device *md = dm_table_get_md(v->ti->table);
219 
220 	/* Corruption should be visible in device status in all modes */
221 	v->hash_failed = 1;
222 
223 	if (v->corrupted_errs >= DM_VERITY_MAX_CORRUPTED_ERRS)
224 		goto out;
225 
226 	v->corrupted_errs++;
227 
228 	switch (type) {
229 	case DM_VERITY_BLOCK_TYPE_DATA:
230 		type_str = "data";
231 		break;
232 	case DM_VERITY_BLOCK_TYPE_METADATA:
233 		type_str = "metadata";
234 		break;
235 	default:
236 		BUG();
237 	}
238 
239 	DMERR_LIMIT("%s: %s block %llu is corrupted", v->data_dev->name,
240 		    type_str, block);
241 
242 	if (v->corrupted_errs == DM_VERITY_MAX_CORRUPTED_ERRS)
243 		DMERR("%s: reached maximum errors", v->data_dev->name);
244 
245 	snprintf(verity_env, DM_VERITY_ENV_LENGTH, "%s=%d,%llu",
246 		DM_VERITY_ENV_VAR_NAME, type, block);
247 
248 	kobject_uevent_env(&disk_to_dev(dm_disk(md))->kobj, KOBJ_CHANGE, envp);
249 
250 out:
251 	if (v->mode == DM_VERITY_MODE_LOGGING)
252 		return 0;
253 
254 	if (v->mode == DM_VERITY_MODE_RESTART) {
255 #ifdef CONFIG_DM_VERITY_AVB
256 		dm_verity_avb_error_handler();
257 #endif
258 		kernel_restart("dm-verity device corrupted");
259 	}
260 
261 	return 1;
262 }
263 
264 /*
265  * Verify hash of a metadata block pertaining to the specified data block
266  * ("block" argument) at a specified level ("level" argument).
267  *
268  * On successful return, verity_io_want_digest(v, io) contains the hash value
269  * for a lower tree level or for the data block (if we're at the lowest level).
270  *
271  * If "skip_unverified" is true, unverified buffer is skipped and 1 is returned.
272  * If "skip_unverified" is false, unverified buffer is hashed and verified
273  * against current value of verity_io_want_digest(v, io).
274  */
verity_verify_level(struct dm_verity * v,struct dm_verity_io * io,sector_t block,int level,bool skip_unverified,u8 * want_digest)275 static int verity_verify_level(struct dm_verity *v, struct dm_verity_io *io,
276 			       sector_t block, int level, bool skip_unverified,
277 			       u8 *want_digest)
278 {
279 	struct dm_buffer *buf;
280 	struct buffer_aux *aux;
281 	u8 *data;
282 	int r;
283 	sector_t hash_block;
284 	unsigned offset;
285 
286 	verity_hash_at_level(v, block, level, &hash_block, &offset);
287 
288 	data = dm_bufio_read(v->bufio, hash_block, &buf);
289 	if (IS_ERR(data))
290 		return PTR_ERR(data);
291 
292 	aux = dm_bufio_get_aux_data(buf);
293 
294 	if (!aux->hash_verified) {
295 		if (skip_unverified) {
296 			r = 1;
297 			goto release_ret_r;
298 		}
299 
300 		r = verity_hash(v, verity_io_hash_req(v, io),
301 				data, 1 << v->hash_dev_block_bits,
302 				verity_io_real_digest(v, io));
303 		if (unlikely(r < 0))
304 			goto release_ret_r;
305 
306 		if (likely(memcmp(verity_io_real_digest(v, io), want_digest,
307 				  v->digest_size) == 0))
308 			aux->hash_verified = 1;
309 		else if (verity_fec_decode(v, io,
310 					   DM_VERITY_BLOCK_TYPE_METADATA,
311 					   hash_block, data, NULL) == 0)
312 			aux->hash_verified = 1;
313 		else if (verity_handle_err(v,
314 					   DM_VERITY_BLOCK_TYPE_METADATA,
315 					   hash_block)) {
316 			r = -EIO;
317 			goto release_ret_r;
318 		}
319 	}
320 
321 	data += offset;
322 	memcpy(want_digest, data, v->digest_size);
323 	r = 0;
324 
325 release_ret_r:
326 	dm_bufio_release(buf);
327 	return r;
328 }
329 
330 /*
331  * Find a hash for a given block, write it to digest and verify the integrity
332  * of the hash tree if necessary.
333  */
verity_hash_for_block(struct dm_verity * v,struct dm_verity_io * io,sector_t block,u8 * digest,bool * is_zero)334 int verity_hash_for_block(struct dm_verity *v, struct dm_verity_io *io,
335 			  sector_t block, u8 *digest, bool *is_zero)
336 {
337 	int r = 0, i;
338 
339 	if (likely(v->levels)) {
340 		/*
341 		 * First, we try to get the requested hash for
342 		 * the current block. If the hash block itself is
343 		 * verified, zero is returned. If it isn't, this
344 		 * function returns 1 and we fall back to whole
345 		 * chain verification.
346 		 */
347 		r = verity_verify_level(v, io, block, 0, true, digest);
348 		if (likely(r <= 0))
349 			goto out;
350 	}
351 
352 	memcpy(digest, v->root_digest, v->digest_size);
353 
354 	for (i = v->levels - 1; i >= 0; i--) {
355 		r = verity_verify_level(v, io, block, i, false, digest);
356 		if (unlikely(r))
357 			goto out;
358 	}
359 out:
360 	if (!r && v->zero_digest)
361 		*is_zero = !memcmp(v->zero_digest, digest, v->digest_size);
362 	else
363 		*is_zero = false;
364 
365 	return r;
366 }
367 
368 /*
369  * Calculates the digest for the given bio
370  */
verity_for_io_block(struct dm_verity * v,struct dm_verity_io * io,struct bvec_iter * iter,struct crypto_wait * wait)371 static int verity_for_io_block(struct dm_verity *v, struct dm_verity_io *io,
372 			       struct bvec_iter *iter, struct crypto_wait *wait)
373 {
374 	unsigned int todo = 1 << v->data_dev_block_bits;
375 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
376 	struct scatterlist sg;
377 	struct ahash_request *req = verity_io_hash_req(v, io);
378 
379 	do {
380 		int r;
381 		unsigned int len;
382 		struct bio_vec bv = bio_iter_iovec(bio, *iter);
383 
384 		sg_init_table(&sg, 1);
385 
386 		len = bv.bv_len;
387 
388 		if (likely(len >= todo))
389 			len = todo;
390 		/*
391 		 * Operating on a single page at a time looks suboptimal
392 		 * until you consider the typical block size is 4,096B.
393 		 * Going through this loops twice should be very rare.
394 		 */
395 		sg_set_page(&sg, bv.bv_page, len, bv.bv_offset);
396 		ahash_request_set_crypt(req, &sg, NULL, len);
397 		r = crypto_wait_req(crypto_ahash_update(req), wait);
398 
399 		if (unlikely(r < 0)) {
400 			DMERR("verity_for_io_block crypto op failed: %d", r);
401 			return r;
402 		}
403 
404 		bio_advance_iter(bio, iter, len);
405 		todo -= len;
406 	} while (todo);
407 
408 	return 0;
409 }
410 
411 /*
412  * Calls function process for 1 << v->data_dev_block_bits bytes in the bio_vec
413  * starting from iter.
414  */
verity_for_bv_block(struct dm_verity * v,struct dm_verity_io * io,struct bvec_iter * iter,int (* process)(struct dm_verity * v,struct dm_verity_io * io,u8 * data,size_t len))415 int verity_for_bv_block(struct dm_verity *v, struct dm_verity_io *io,
416 			struct bvec_iter *iter,
417 			int (*process)(struct dm_verity *v,
418 				       struct dm_verity_io *io, u8 *data,
419 				       size_t len))
420 {
421 	unsigned todo = 1 << v->data_dev_block_bits;
422 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
423 
424 	do {
425 		int r;
426 		u8 *page;
427 		unsigned len;
428 		struct bio_vec bv = bio_iter_iovec(bio, *iter);
429 
430 		page = kmap_atomic(bv.bv_page);
431 		len = bv.bv_len;
432 
433 		if (likely(len >= todo))
434 			len = todo;
435 
436 		r = process(v, io, page + bv.bv_offset, len);
437 		kunmap_atomic(page);
438 
439 		if (r < 0)
440 			return r;
441 
442 		bio_advance_iter(bio, iter, len);
443 		todo -= len;
444 	} while (todo);
445 
446 	return 0;
447 }
448 
verity_bv_zero(struct dm_verity * v,struct dm_verity_io * io,u8 * data,size_t len)449 static int verity_bv_zero(struct dm_verity *v, struct dm_verity_io *io,
450 			  u8 *data, size_t len)
451 {
452 	memset(data, 0, len);
453 	return 0;
454 }
455 
456 /*
457  * Moves the bio iter one data block forward.
458  */
verity_bv_skip_block(struct dm_verity * v,struct dm_verity_io * io,struct bvec_iter * iter)459 static inline void verity_bv_skip_block(struct dm_verity *v,
460 					struct dm_verity_io *io,
461 					struct bvec_iter *iter)
462 {
463 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
464 
465 	bio_advance_iter(bio, iter, 1 << v->data_dev_block_bits);
466 }
467 
468 /*
469  * Verify one "dm_verity_io" structure.
470  */
verity_verify_io(struct dm_verity_io * io)471 static int verity_verify_io(struct dm_verity_io *io)
472 {
473 	bool is_zero;
474 	struct dm_verity *v = io->v;
475 	struct bvec_iter start;
476 	unsigned b;
477 	struct crypto_wait wait;
478 
479 	for (b = 0; b < io->n_blocks; b++) {
480 		int r;
481 		sector_t cur_block = io->block + b;
482 		struct ahash_request *req = verity_io_hash_req(v, io);
483 
484 		if (v->validated_blocks &&
485 		    likely(test_bit(cur_block, v->validated_blocks))) {
486 			verity_bv_skip_block(v, io, &io->iter);
487 			continue;
488 		}
489 
490 		r = verity_hash_for_block(v, io, cur_block,
491 					  verity_io_want_digest(v, io),
492 					  &is_zero);
493 		if (unlikely(r < 0))
494 			return r;
495 
496 		if (is_zero) {
497 			/*
498 			 * If we expect a zero block, don't validate, just
499 			 * return zeros.
500 			 */
501 			r = verity_for_bv_block(v, io, &io->iter,
502 						verity_bv_zero);
503 			if (unlikely(r < 0))
504 				return r;
505 
506 			continue;
507 		}
508 
509 		r = verity_hash_init(v, req, &wait);
510 		if (unlikely(r < 0))
511 			return r;
512 
513 		start = io->iter;
514 		r = verity_for_io_block(v, io, &io->iter, &wait);
515 		if (unlikely(r < 0))
516 			return r;
517 
518 		r = verity_hash_final(v, req, verity_io_real_digest(v, io),
519 					&wait);
520 		if (unlikely(r < 0))
521 			return r;
522 
523 		if (likely(memcmp(verity_io_real_digest(v, io),
524 				  verity_io_want_digest(v, io), v->digest_size) == 0)) {
525 			if (v->validated_blocks)
526 				set_bit(cur_block, v->validated_blocks);
527 			continue;
528 		}
529 		else if (verity_fec_decode(v, io, DM_VERITY_BLOCK_TYPE_DATA,
530 					   cur_block, NULL, &start) == 0)
531 			continue;
532 		else if (verity_handle_err(v, DM_VERITY_BLOCK_TYPE_DATA,
533 					   cur_block))
534 			return -EIO;
535 	}
536 
537 	return 0;
538 }
539 
540 /*
541  * End one "io" structure with a given error.
542  */
verity_finish_io(struct dm_verity_io * io,blk_status_t status)543 static void verity_finish_io(struct dm_verity_io *io, blk_status_t status)
544 {
545 	struct dm_verity *v = io->v;
546 	struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
547 
548 	bio->bi_end_io = io->orig_bi_end_io;
549 	bio->bi_status = status;
550 
551 	verity_fec_finish_io(io);
552 
553 	bio_endio(bio);
554 }
555 
verity_work(struct work_struct * w)556 static void verity_work(struct work_struct *w)
557 {
558 	struct dm_verity_io *io = container_of(w, struct dm_verity_io, work);
559 
560 	verity_finish_io(io, errno_to_blk_status(verity_verify_io(io)));
561 }
562 
verity_end_io(struct bio * bio)563 static void verity_end_io(struct bio *bio)
564 {
565 	struct dm_verity_io *io = bio->bi_private;
566 
567 	if (bio->bi_status && !verity_fec_is_enabled(io->v)) {
568 		verity_finish_io(io, bio->bi_status);
569 		return;
570 	}
571 
572 	INIT_WORK(&io->work, verity_work);
573 	queue_work(io->v->verify_wq, &io->work);
574 }
575 
576 /*
577  * Prefetch buffers for the specified io.
578  * The root buffer is not prefetched, it is assumed that it will be cached
579  * all the time.
580  */
verity_prefetch_io(struct work_struct * work)581 static void verity_prefetch_io(struct work_struct *work)
582 {
583 	struct dm_verity_prefetch_work *pw =
584 		container_of(work, struct dm_verity_prefetch_work, work);
585 	struct dm_verity *v = pw->v;
586 	int i;
587 
588 	for (i = v->levels - 2; i >= 0; i--) {
589 		sector_t hash_block_start;
590 		sector_t hash_block_end;
591 		verity_hash_at_level(v, pw->block, i, &hash_block_start, NULL);
592 		verity_hash_at_level(v, pw->block + pw->n_blocks - 1, i, &hash_block_end, NULL);
593 		if (!i) {
594 			unsigned cluster = READ_ONCE(dm_verity_prefetch_cluster);
595 
596 			cluster >>= v->data_dev_block_bits;
597 			if (unlikely(!cluster))
598 				goto no_prefetch_cluster;
599 
600 			if (unlikely(cluster & (cluster - 1)))
601 				cluster = 1 << __fls(cluster);
602 
603 			hash_block_start &= ~(sector_t)(cluster - 1);
604 			hash_block_end |= cluster - 1;
605 			if (unlikely(hash_block_end >= v->hash_blocks))
606 				hash_block_end = v->hash_blocks - 1;
607 		}
608 no_prefetch_cluster:
609 		dm_bufio_prefetch(v->bufio, hash_block_start,
610 				  hash_block_end - hash_block_start + 1);
611 	}
612 
613 	kfree(pw);
614 }
615 
verity_submit_prefetch(struct dm_verity * v,struct dm_verity_io * io)616 static void verity_submit_prefetch(struct dm_verity *v, struct dm_verity_io *io)
617 {
618 	struct dm_verity_prefetch_work *pw;
619 
620 	pw = kmalloc(sizeof(struct dm_verity_prefetch_work),
621 		GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
622 
623 	if (!pw)
624 		return;
625 
626 	INIT_WORK(&pw->work, verity_prefetch_io);
627 	pw->v = v;
628 	pw->block = io->block;
629 	pw->n_blocks = io->n_blocks;
630 	queue_work(v->verify_wq, &pw->work);
631 }
632 
633 /*
634  * Bio map function. It allocates dm_verity_io structure and bio vector and
635  * fills them. Then it issues prefetches and the I/O.
636  */
verity_map(struct dm_target * ti,struct bio * bio)637 static int verity_map(struct dm_target *ti, struct bio *bio)
638 {
639 	struct dm_verity *v = ti->private;
640 	struct dm_verity_io *io;
641 
642 	bio_set_dev(bio, v->data_dev->bdev);
643 	bio->bi_iter.bi_sector = verity_map_sector(v, bio->bi_iter.bi_sector);
644 
645 	if (((unsigned)bio->bi_iter.bi_sector | bio_sectors(bio)) &
646 	    ((1 << (v->data_dev_block_bits - SECTOR_SHIFT)) - 1)) {
647 		DMERR_LIMIT("unaligned io");
648 		return DM_MAPIO_KILL;
649 	}
650 
651 	if (bio_end_sector(bio) >>
652 	    (v->data_dev_block_bits - SECTOR_SHIFT) > v->data_blocks) {
653 		DMERR_LIMIT("io out of range");
654 		return DM_MAPIO_KILL;
655 	}
656 
657 	if (bio_data_dir(bio) == WRITE)
658 		return DM_MAPIO_KILL;
659 
660 	io = dm_per_bio_data(bio, ti->per_io_data_size);
661 	io->v = v;
662 	io->orig_bi_end_io = bio->bi_end_io;
663 	io->block = bio->bi_iter.bi_sector >> (v->data_dev_block_bits - SECTOR_SHIFT);
664 	io->n_blocks = bio->bi_iter.bi_size >> v->data_dev_block_bits;
665 
666 	bio->bi_end_io = verity_end_io;
667 	bio->bi_private = io;
668 	io->iter = bio->bi_iter;
669 
670 	verity_fec_init_io(io);
671 
672 	verity_submit_prefetch(v, io);
673 
674 	generic_make_request(bio);
675 
676 	return DM_MAPIO_SUBMITTED;
677 }
678 
679 /*
680  * Status: V (valid) or C (corruption found)
681  */
verity_status(struct dm_target * ti,status_type_t type,unsigned status_flags,char * result,unsigned maxlen)682 static void verity_status(struct dm_target *ti, status_type_t type,
683 			  unsigned status_flags, char *result, unsigned maxlen)
684 {
685 	struct dm_verity *v = ti->private;
686 	unsigned args = 0;
687 	unsigned sz = 0;
688 	unsigned x;
689 
690 	switch (type) {
691 	case STATUSTYPE_INFO:
692 		DMEMIT("%c", v->hash_failed ? 'C' : 'V');
693 		break;
694 	case STATUSTYPE_TABLE:
695 		DMEMIT("%u %s %s %u %u %llu %llu %s ",
696 			v->version,
697 			v->data_dev->name,
698 			v->hash_dev->name,
699 			1 << v->data_dev_block_bits,
700 			1 << v->hash_dev_block_bits,
701 			(unsigned long long)v->data_blocks,
702 			(unsigned long long)v->hash_start,
703 			v->alg_name
704 			);
705 		for (x = 0; x < v->digest_size; x++)
706 			DMEMIT("%02x", v->root_digest[x]);
707 		DMEMIT(" ");
708 		if (!v->salt_size)
709 			DMEMIT("-");
710 		else
711 			for (x = 0; x < v->salt_size; x++)
712 				DMEMIT("%02x", v->salt[x]);
713 		if (v->mode != DM_VERITY_MODE_EIO)
714 			args++;
715 		if (verity_fec_is_enabled(v))
716 			args += DM_VERITY_OPTS_FEC;
717 		if (v->zero_digest)
718 			args++;
719 		if (v->validated_blocks)
720 			args++;
721 		if (v->signature_key_desc)
722 			args += DM_VERITY_ROOT_HASH_VERIFICATION_OPTS;
723 		if (!args)
724 			return;
725 		DMEMIT(" %u", args);
726 		if (v->mode != DM_VERITY_MODE_EIO) {
727 			DMEMIT(" ");
728 			switch (v->mode) {
729 			case DM_VERITY_MODE_LOGGING:
730 				DMEMIT(DM_VERITY_OPT_LOGGING);
731 				break;
732 			case DM_VERITY_MODE_RESTART:
733 				DMEMIT(DM_VERITY_OPT_RESTART);
734 				break;
735 			default:
736 				BUG();
737 			}
738 		}
739 		if (v->zero_digest)
740 			DMEMIT(" " DM_VERITY_OPT_IGN_ZEROES);
741 		if (v->validated_blocks)
742 			DMEMIT(" " DM_VERITY_OPT_AT_MOST_ONCE);
743 		sz = verity_fec_status_table(v, sz, result, maxlen);
744 		if (v->signature_key_desc)
745 			DMEMIT(" " DM_VERITY_ROOT_HASH_VERIFICATION_OPT_SIG_KEY
746 				" %s", v->signature_key_desc);
747 		break;
748 	}
749 }
750 
verity_prepare_ioctl(struct dm_target * ti,struct block_device ** bdev)751 static int verity_prepare_ioctl(struct dm_target *ti, struct block_device **bdev)
752 {
753 	struct dm_verity *v = ti->private;
754 
755 	*bdev = v->data_dev->bdev;
756 
757 	if (v->data_start ||
758 	    ti->len != i_size_read(v->data_dev->bdev->bd_inode) >> SECTOR_SHIFT)
759 		return 1;
760 	return 0;
761 }
762 
verity_iterate_devices(struct dm_target * ti,iterate_devices_callout_fn fn,void * data)763 static int verity_iterate_devices(struct dm_target *ti,
764 				  iterate_devices_callout_fn fn, void *data)
765 {
766 	struct dm_verity *v = ti->private;
767 
768 	return fn(ti, v->data_dev, v->data_start, ti->len, data);
769 }
770 
verity_io_hints(struct dm_target * ti,struct queue_limits * limits)771 static void verity_io_hints(struct dm_target *ti, struct queue_limits *limits)
772 {
773 	struct dm_verity *v = ti->private;
774 
775 	if (limits->logical_block_size < 1 << v->data_dev_block_bits)
776 		limits->logical_block_size = 1 << v->data_dev_block_bits;
777 
778 	if (limits->physical_block_size < 1 << v->data_dev_block_bits)
779 		limits->physical_block_size = 1 << v->data_dev_block_bits;
780 
781 	blk_limits_io_min(limits, limits->logical_block_size);
782 }
783 
verity_dtr(struct dm_target * ti)784 static void verity_dtr(struct dm_target *ti)
785 {
786 	struct dm_verity *v = ti->private;
787 
788 	if (v->verify_wq)
789 		destroy_workqueue(v->verify_wq);
790 
791 	if (v->bufio)
792 		dm_bufio_client_destroy(v->bufio);
793 
794 	kvfree(v->validated_blocks);
795 	kfree(v->salt);
796 	kfree(v->root_digest);
797 	kfree(v->zero_digest);
798 
799 	if (v->tfm)
800 		crypto_free_ahash(v->tfm);
801 
802 	kfree(v->alg_name);
803 
804 	if (v->hash_dev)
805 		dm_put_device(ti, v->hash_dev);
806 
807 	if (v->data_dev)
808 		dm_put_device(ti, v->data_dev);
809 
810 	verity_fec_dtr(v);
811 
812 	kfree(v->signature_key_desc);
813 
814 	kfree(v);
815 }
816 
verity_alloc_most_once(struct dm_verity * v)817 static int verity_alloc_most_once(struct dm_verity *v)
818 {
819 	struct dm_target *ti = v->ti;
820 
821 	/* the bitset can only handle INT_MAX blocks */
822 	if (v->data_blocks > INT_MAX) {
823 		ti->error = "device too large to use check_at_most_once";
824 		return -E2BIG;
825 	}
826 
827 	v->validated_blocks = kvcalloc(BITS_TO_LONGS(v->data_blocks),
828 				       sizeof(unsigned long),
829 				       GFP_KERNEL);
830 	if (!v->validated_blocks) {
831 		ti->error = "failed to allocate bitset for check_at_most_once";
832 		return -ENOMEM;
833 	}
834 
835 	return 0;
836 }
837 
verity_alloc_zero_digest(struct dm_verity * v)838 static int verity_alloc_zero_digest(struct dm_verity *v)
839 {
840 	int r = -ENOMEM;
841 	struct ahash_request *req;
842 	u8 *zero_data;
843 
844 	v->zero_digest = kmalloc(v->digest_size, GFP_KERNEL);
845 
846 	if (!v->zero_digest)
847 		return r;
848 
849 	req = kmalloc(v->ahash_reqsize, GFP_KERNEL);
850 
851 	if (!req)
852 		return r; /* verity_dtr will free zero_digest */
853 
854 	zero_data = kzalloc(1 << v->data_dev_block_bits, GFP_KERNEL);
855 
856 	if (!zero_data)
857 		goto out;
858 
859 	r = verity_hash(v, req, zero_data, 1 << v->data_dev_block_bits,
860 			v->zero_digest);
861 
862 out:
863 	kfree(req);
864 	kfree(zero_data);
865 
866 	return r;
867 }
868 
verity_parse_opt_args(struct dm_arg_set * as,struct dm_verity * v,struct dm_verity_sig_opts * verify_args)869 static int verity_parse_opt_args(struct dm_arg_set *as, struct dm_verity *v,
870 				 struct dm_verity_sig_opts *verify_args)
871 {
872 	int r;
873 	unsigned argc;
874 	struct dm_target *ti = v->ti;
875 	const char *arg_name;
876 
877 	static const struct dm_arg _args[] = {
878 		{0, DM_VERITY_OPTS_MAX, "Invalid number of feature args"},
879 	};
880 
881 	r = dm_read_arg_group(_args, as, &argc, &ti->error);
882 	if (r)
883 		return -EINVAL;
884 
885 	if (!argc)
886 		return 0;
887 
888 	do {
889 		arg_name = dm_shift_arg(as);
890 		argc--;
891 
892 		if (!strcasecmp(arg_name, DM_VERITY_OPT_LOGGING)) {
893 			v->mode = DM_VERITY_MODE_LOGGING;
894 			continue;
895 
896 		} else if (!strcasecmp(arg_name, DM_VERITY_OPT_RESTART)) {
897 			v->mode = DM_VERITY_MODE_RESTART;
898 			continue;
899 
900 		} else if (!strcasecmp(arg_name, DM_VERITY_OPT_IGN_ZEROES)) {
901 			r = verity_alloc_zero_digest(v);
902 			if (r) {
903 				ti->error = "Cannot allocate zero digest";
904 				return r;
905 			}
906 			continue;
907 
908 		} else if (!strcasecmp(arg_name, DM_VERITY_OPT_AT_MOST_ONCE)) {
909 			r = verity_alloc_most_once(v);
910 			if (r)
911 				return r;
912 			continue;
913 
914 		} else if (verity_is_fec_opt_arg(arg_name)) {
915 			r = verity_fec_parse_opt_args(as, v, &argc, arg_name);
916 			if (r)
917 				return r;
918 			continue;
919 		} else if (verity_verify_is_sig_opt_arg(arg_name)) {
920 			r = verity_verify_sig_parse_opt_args(as, v,
921 							     verify_args,
922 							     &argc, arg_name);
923 			if (r)
924 				return r;
925 			continue;
926 
927 		}
928 
929 		ti->error = "Unrecognized verity feature request";
930 		return -EINVAL;
931 	} while (argc && !r);
932 
933 	return r;
934 }
935 
936 /*
937  * Target parameters:
938  *	<version>	The current format is version 1.
939  *			Vsn 0 is compatible with original Chromium OS releases.
940  *	<data device>
941  *	<hash device>
942  *	<data block size>
943  *	<hash block size>
944  *	<the number of data blocks>
945  *	<hash start block>
946  *	<algorithm>
947  *	<digest>
948  *	<salt>		Hex string or "-" if no salt.
949  */
verity_ctr(struct dm_target * ti,unsigned argc,char ** argv)950 static int verity_ctr(struct dm_target *ti, unsigned argc, char **argv)
951 {
952 	struct dm_verity *v;
953 	struct dm_verity_sig_opts verify_args = {0};
954 	struct dm_arg_set as;
955 	unsigned int num;
956 	unsigned long long num_ll;
957 	int r;
958 	int i;
959 	sector_t hash_position;
960 	char dummy;
961 	char *root_hash_digest_to_validate;
962 
963 	v = kzalloc(sizeof(struct dm_verity), GFP_KERNEL);
964 	if (!v) {
965 		ti->error = "Cannot allocate verity structure";
966 		return -ENOMEM;
967 	}
968 	ti->private = v;
969 	v->ti = ti;
970 
971 	r = verity_fec_ctr_alloc(v);
972 	if (r)
973 		goto bad;
974 
975 	if ((dm_table_get_mode(ti->table) & ~FMODE_READ)) {
976 		ti->error = "Device must be readonly";
977 		r = -EINVAL;
978 		goto bad;
979 	}
980 
981 	if (argc < 10) {
982 		ti->error = "Not enough arguments";
983 		r = -EINVAL;
984 		goto bad;
985 	}
986 
987 	if (sscanf(argv[0], "%u%c", &num, &dummy) != 1 ||
988 	    num > 1) {
989 		ti->error = "Invalid version";
990 		r = -EINVAL;
991 		goto bad;
992 	}
993 	v->version = num;
994 
995 	r = dm_get_device(ti, argv[1], FMODE_READ, &v->data_dev);
996 	if (r) {
997 		ti->error = "Data device lookup failed";
998 		goto bad;
999 	}
1000 
1001 	r = dm_get_device(ti, argv[2], FMODE_READ, &v->hash_dev);
1002 	if (r) {
1003 		ti->error = "Hash device lookup failed";
1004 		goto bad;
1005 	}
1006 
1007 	if (sscanf(argv[3], "%u%c", &num, &dummy) != 1 ||
1008 	    !num || (num & (num - 1)) ||
1009 	    num < bdev_logical_block_size(v->data_dev->bdev) ||
1010 	    num > PAGE_SIZE) {
1011 		ti->error = "Invalid data device block size";
1012 		r = -EINVAL;
1013 		goto bad;
1014 	}
1015 	v->data_dev_block_bits = __ffs(num);
1016 
1017 	if (sscanf(argv[4], "%u%c", &num, &dummy) != 1 ||
1018 	    !num || (num & (num - 1)) ||
1019 	    num < bdev_logical_block_size(v->hash_dev->bdev) ||
1020 	    num > INT_MAX) {
1021 		ti->error = "Invalid hash device block size";
1022 		r = -EINVAL;
1023 		goto bad;
1024 	}
1025 	v->hash_dev_block_bits = __ffs(num);
1026 
1027 	if (sscanf(argv[5], "%llu%c", &num_ll, &dummy) != 1 ||
1028 	    (sector_t)(num_ll << (v->data_dev_block_bits - SECTOR_SHIFT))
1029 	    >> (v->data_dev_block_bits - SECTOR_SHIFT) != num_ll) {
1030 		ti->error = "Invalid data blocks";
1031 		r = -EINVAL;
1032 		goto bad;
1033 	}
1034 	v->data_blocks = num_ll;
1035 
1036 	if (ti->len > (v->data_blocks << (v->data_dev_block_bits - SECTOR_SHIFT))) {
1037 		ti->error = "Data device is too small";
1038 		r = -EINVAL;
1039 		goto bad;
1040 	}
1041 
1042 	if (sscanf(argv[6], "%llu%c", &num_ll, &dummy) != 1 ||
1043 	    (sector_t)(num_ll << (v->hash_dev_block_bits - SECTOR_SHIFT))
1044 	    >> (v->hash_dev_block_bits - SECTOR_SHIFT) != num_ll) {
1045 		ti->error = "Invalid hash start";
1046 		r = -EINVAL;
1047 		goto bad;
1048 	}
1049 	v->hash_start = num_ll;
1050 
1051 	v->alg_name = kstrdup(argv[7], GFP_KERNEL);
1052 	if (!v->alg_name) {
1053 		ti->error = "Cannot allocate algorithm name";
1054 		r = -ENOMEM;
1055 		goto bad;
1056 	}
1057 
1058 	v->tfm = crypto_alloc_ahash(v->alg_name, 0, 0);
1059 	if (IS_ERR(v->tfm)) {
1060 		ti->error = "Cannot initialize hash function";
1061 		r = PTR_ERR(v->tfm);
1062 		v->tfm = NULL;
1063 		goto bad;
1064 	}
1065 
1066 	/*
1067 	 * dm-verity performance can vary greatly depending on which hash
1068 	 * algorithm implementation is used.  Help people debug performance
1069 	 * problems by logging the ->cra_driver_name.
1070 	 */
1071 	DMINFO("%s using implementation \"%s\"", v->alg_name,
1072 	       crypto_hash_alg_common(v->tfm)->base.cra_driver_name);
1073 
1074 	v->digest_size = crypto_ahash_digestsize(v->tfm);
1075 	if ((1 << v->hash_dev_block_bits) < v->digest_size * 2) {
1076 		ti->error = "Digest size too big";
1077 		r = -EINVAL;
1078 		goto bad;
1079 	}
1080 	v->ahash_reqsize = sizeof(struct ahash_request) +
1081 		crypto_ahash_reqsize(v->tfm);
1082 
1083 	v->root_digest = kmalloc(v->digest_size, GFP_KERNEL);
1084 	if (!v->root_digest) {
1085 		ti->error = "Cannot allocate root digest";
1086 		r = -ENOMEM;
1087 		goto bad;
1088 	}
1089 	if (strlen(argv[8]) != v->digest_size * 2 ||
1090 	    hex2bin(v->root_digest, argv[8], v->digest_size)) {
1091 		ti->error = "Invalid root digest";
1092 		r = -EINVAL;
1093 		goto bad;
1094 	}
1095 	root_hash_digest_to_validate = argv[8];
1096 
1097 	if (strcmp(argv[9], "-")) {
1098 		v->salt_size = strlen(argv[9]) / 2;
1099 		v->salt = kmalloc(v->salt_size, GFP_KERNEL);
1100 		if (!v->salt) {
1101 			ti->error = "Cannot allocate salt";
1102 			r = -ENOMEM;
1103 			goto bad;
1104 		}
1105 		if (strlen(argv[9]) != v->salt_size * 2 ||
1106 		    hex2bin(v->salt, argv[9], v->salt_size)) {
1107 			ti->error = "Invalid salt";
1108 			r = -EINVAL;
1109 			goto bad;
1110 		}
1111 	}
1112 
1113 	argv += 10;
1114 	argc -= 10;
1115 
1116 	/* Optional parameters */
1117 	if (argc) {
1118 		as.argc = argc;
1119 		as.argv = argv;
1120 
1121 		r = verity_parse_opt_args(&as, v, &verify_args);
1122 		if (r < 0)
1123 			goto bad;
1124 	}
1125 
1126 	/* Root hash signature is  a optional parameter*/
1127 	r = verity_verify_root_hash(root_hash_digest_to_validate,
1128 				    strlen(root_hash_digest_to_validate),
1129 				    verify_args.sig,
1130 				    verify_args.sig_size);
1131 	if (r < 0) {
1132 		ti->error = "Root hash verification failed";
1133 		goto bad;
1134 	}
1135 	v->hash_per_block_bits =
1136 		__fls((1 << v->hash_dev_block_bits) / v->digest_size);
1137 
1138 	v->levels = 0;
1139 	if (v->data_blocks)
1140 		while (v->hash_per_block_bits * v->levels < 64 &&
1141 		       (unsigned long long)(v->data_blocks - 1) >>
1142 		       (v->hash_per_block_bits * v->levels))
1143 			v->levels++;
1144 
1145 	if (v->levels > DM_VERITY_MAX_LEVELS) {
1146 		ti->error = "Too many tree levels";
1147 		r = -E2BIG;
1148 		goto bad;
1149 	}
1150 
1151 	hash_position = v->hash_start;
1152 	for (i = v->levels - 1; i >= 0; i--) {
1153 		sector_t s;
1154 		v->hash_level_block[i] = hash_position;
1155 		s = (v->data_blocks + ((sector_t)1 << ((i + 1) * v->hash_per_block_bits)) - 1)
1156 					>> ((i + 1) * v->hash_per_block_bits);
1157 		if (hash_position + s < hash_position) {
1158 			ti->error = "Hash device offset overflow";
1159 			r = -E2BIG;
1160 			goto bad;
1161 		}
1162 		hash_position += s;
1163 	}
1164 	v->hash_blocks = hash_position;
1165 
1166 	v->bufio = dm_bufio_client_create(v->hash_dev->bdev,
1167 		1 << v->hash_dev_block_bits, 1, sizeof(struct buffer_aux),
1168 		dm_bufio_alloc_callback, NULL);
1169 	if (IS_ERR(v->bufio)) {
1170 		ti->error = "Cannot initialize dm-bufio";
1171 		r = PTR_ERR(v->bufio);
1172 		v->bufio = NULL;
1173 		goto bad;
1174 	}
1175 
1176 	if (dm_bufio_get_device_size(v->bufio) < v->hash_blocks) {
1177 		ti->error = "Hash device is too small";
1178 		r = -E2BIG;
1179 		goto bad;
1180 	}
1181 
1182 	/* WQ_UNBOUND greatly improves performance when running on ramdisk */
1183 	v->verify_wq = alloc_workqueue("kverityd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND, num_online_cpus());
1184 	if (!v->verify_wq) {
1185 		ti->error = "Cannot allocate workqueue";
1186 		r = -ENOMEM;
1187 		goto bad;
1188 	}
1189 
1190 	ti->per_io_data_size = sizeof(struct dm_verity_io) +
1191 				v->ahash_reqsize + v->digest_size * 2;
1192 
1193 	r = verity_fec_ctr(v);
1194 	if (r)
1195 		goto bad;
1196 
1197 	ti->per_io_data_size = roundup(ti->per_io_data_size,
1198 				       __alignof__(struct dm_verity_io));
1199 
1200 	verity_verify_sig_opts_cleanup(&verify_args);
1201 
1202 	return 0;
1203 
1204 bad:
1205 
1206 	verity_verify_sig_opts_cleanup(&verify_args);
1207 	verity_dtr(ti);
1208 
1209 	return r;
1210 }
1211 
1212 static struct target_type verity_target = {
1213 	.name		= "verity",
1214 	.version	= {1, 5, 0},
1215 	.module		= THIS_MODULE,
1216 	.ctr		= verity_ctr,
1217 	.dtr		= verity_dtr,
1218 	.map		= verity_map,
1219 	.status		= verity_status,
1220 	.prepare_ioctl	= verity_prepare_ioctl,
1221 	.iterate_devices = verity_iterate_devices,
1222 	.io_hints	= verity_io_hints,
1223 };
1224 
dm_verity_init(void)1225 static int __init dm_verity_init(void)
1226 {
1227 	int r;
1228 
1229 	r = dm_register_target(&verity_target);
1230 	if (r < 0)
1231 		DMERR("register failed %d", r);
1232 
1233 	return r;
1234 }
1235 
dm_verity_exit(void)1236 static void __exit dm_verity_exit(void)
1237 {
1238 	dm_unregister_target(&verity_target);
1239 }
1240 
1241 module_init(dm_verity_init);
1242 module_exit(dm_verity_exit);
1243 
1244 MODULE_AUTHOR("Mikulas Patocka <mpatocka@redhat.com>");
1245 MODULE_AUTHOR("Mandeep Baines <msb@chromium.org>");
1246 MODULE_AUTHOR("Will Drewry <wad@chromium.org>");
1247 MODULE_DESCRIPTION(DM_NAME " target for transparent disk integrity checking");
1248 MODULE_LICENSE("GPL");
1249