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 "dm-audit.h"
20 #include <linux/module.h>
21 #include <linux/reboot.h>
22 #include <linux/string.h>
23 #include <linux/jump_label.h>
24 #include <linux/security.h>
25
26 #define DM_MSG_PREFIX "verity"
27
28 #define DM_VERITY_ENV_LENGTH 42
29 #define DM_VERITY_ENV_VAR_NAME "DM_VERITY_ERR_BLOCK_NR"
30
31 #define DM_VERITY_DEFAULT_PREFETCH_SIZE 262144
32 #define DM_VERITY_USE_BH_DEFAULT_BYTES 8192
33
34 #define DM_VERITY_MAX_CORRUPTED_ERRS 100
35
36 #define DM_VERITY_OPT_LOGGING "ignore_corruption"
37 #define DM_VERITY_OPT_RESTART "restart_on_corruption"
38 #define DM_VERITY_OPT_PANIC "panic_on_corruption"
39 #define DM_VERITY_OPT_ERROR_RESTART "restart_on_error"
40 #define DM_VERITY_OPT_ERROR_PANIC "panic_on_error"
41 #define DM_VERITY_OPT_IGN_ZEROES "ignore_zero_blocks"
42 #define DM_VERITY_OPT_AT_MOST_ONCE "check_at_most_once"
43 #define DM_VERITY_OPT_TASKLET_VERIFY "try_verify_in_tasklet"
44
45 #define DM_VERITY_OPTS_MAX (5 + DM_VERITY_OPTS_FEC + \
46 DM_VERITY_ROOT_HASH_VERIFICATION_OPTS)
47
48 static unsigned int dm_verity_prefetch_cluster = DM_VERITY_DEFAULT_PREFETCH_SIZE;
49
50 module_param_named(prefetch_cluster, dm_verity_prefetch_cluster, uint, 0644);
51
52 static unsigned int dm_verity_use_bh_bytes[4] = {
53 DM_VERITY_USE_BH_DEFAULT_BYTES, // IOPRIO_CLASS_NONE
54 DM_VERITY_USE_BH_DEFAULT_BYTES, // IOPRIO_CLASS_RT
55 DM_VERITY_USE_BH_DEFAULT_BYTES, // IOPRIO_CLASS_BE
56 0 // IOPRIO_CLASS_IDLE
57 };
58
59 module_param_array_named(use_bh_bytes, dm_verity_use_bh_bytes, uint, NULL, 0644);
60
61 static DEFINE_STATIC_KEY_FALSE(use_bh_wq_enabled);
62
63 struct dm_verity_prefetch_work {
64 struct work_struct work;
65 struct dm_verity *v;
66 unsigned short ioprio;
67 sector_t block;
68 unsigned int n_blocks;
69 };
70
71 /*
72 * Auxiliary structure appended to each dm-bufio buffer. If the value
73 * hash_verified is nonzero, hash of the block has been verified.
74 *
75 * The variable hash_verified is set to 0 when allocating the buffer, then
76 * it can be changed to 1 and it is never reset to 0 again.
77 *
78 * There is no lock around this value, a race condition can at worst cause
79 * that multiple processes verify the hash of the same buffer simultaneously
80 * and write 1 to hash_verified simultaneously.
81 * This condition is harmless, so we don't need locking.
82 */
83 struct buffer_aux {
84 int hash_verified;
85 };
86
87 /*
88 * Initialize struct buffer_aux for a freshly created buffer.
89 */
dm_bufio_alloc_callback(struct dm_buffer * buf)90 static void dm_bufio_alloc_callback(struct dm_buffer *buf)
91 {
92 struct buffer_aux *aux = dm_bufio_get_aux_data(buf);
93
94 aux->hash_verified = 0;
95 }
96
97 /*
98 * Translate input sector number to the sector number on the target device.
99 */
verity_map_sector(struct dm_verity * v,sector_t bi_sector)100 static sector_t verity_map_sector(struct dm_verity *v, sector_t bi_sector)
101 {
102 return dm_target_offset(v->ti, bi_sector);
103 }
104
105 /*
106 * Return hash position of a specified block at a specified tree level
107 * (0 is the lowest level).
108 * The lowest "hash_per_block_bits"-bits of the result denote hash position
109 * inside a hash block. The remaining bits denote location of the hash block.
110 */
verity_position_at_level(struct dm_verity * v,sector_t block,int level)111 static sector_t verity_position_at_level(struct dm_verity *v, sector_t block,
112 int level)
113 {
114 return block >> (level * v->hash_per_block_bits);
115 }
116
verity_hash(struct dm_verity * v,struct dm_verity_io * io,const u8 * data,size_t len,u8 * digest)117 int verity_hash(struct dm_verity *v, struct dm_verity_io *io,
118 const u8 *data, size_t len, u8 *digest)
119 {
120 struct shash_desc *desc = &io->hash_desc;
121 int r;
122
123 desc->tfm = v->shash_tfm;
124 if (unlikely(v->initial_hashstate == NULL)) {
125 /* Version 0: salt at end */
126 r = crypto_shash_init(desc) ?:
127 crypto_shash_update(desc, data, len) ?:
128 crypto_shash_update(desc, v->salt, v->salt_size) ?:
129 crypto_shash_final(desc, digest);
130 } else {
131 /* Version 1: salt at beginning */
132 r = crypto_shash_import(desc, v->initial_hashstate) ?:
133 crypto_shash_finup(desc, data, len, digest);
134 }
135 if (unlikely(r))
136 DMERR("Error hashing block: %d", r);
137 return r;
138 }
139
verity_hash_at_level(struct dm_verity * v,sector_t block,int level,sector_t * hash_block,unsigned int * offset)140 static void verity_hash_at_level(struct dm_verity *v, sector_t block, int level,
141 sector_t *hash_block, unsigned int *offset)
142 {
143 sector_t position = verity_position_at_level(v, block, level);
144 unsigned int idx;
145
146 *hash_block = v->hash_level_block[level] + (position >> v->hash_per_block_bits);
147
148 if (!offset)
149 return;
150
151 idx = position & ((1 << v->hash_per_block_bits) - 1);
152 if (!v->version)
153 *offset = idx * v->digest_size;
154 else
155 *offset = idx << (v->hash_dev_block_bits - v->hash_per_block_bits);
156 }
157
158 /*
159 * Handle verification errors.
160 */
verity_handle_err(struct dm_verity * v,enum verity_block_type type,unsigned long long block)161 static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
162 unsigned long long block)
163 {
164 char verity_env[DM_VERITY_ENV_LENGTH];
165 char *envp[] = { verity_env, NULL };
166 const char *type_str = "";
167 struct mapped_device *md = dm_table_get_md(v->ti->table);
168
169 /* Corruption should be visible in device status in all modes */
170 v->hash_failed = true;
171
172 if (v->corrupted_errs >= DM_VERITY_MAX_CORRUPTED_ERRS)
173 goto out;
174
175 v->corrupted_errs++;
176
177 switch (type) {
178 case DM_VERITY_BLOCK_TYPE_DATA:
179 type_str = "data";
180 break;
181 case DM_VERITY_BLOCK_TYPE_METADATA:
182 type_str = "metadata";
183 break;
184 default:
185 BUG();
186 }
187
188 DMERR_LIMIT("%s: %s block %llu is corrupted", v->data_dev->name,
189 type_str, block);
190
191 if (v->corrupted_errs == DM_VERITY_MAX_CORRUPTED_ERRS) {
192 DMERR("%s: reached maximum errors", v->data_dev->name);
193 dm_audit_log_target(DM_MSG_PREFIX, "max-corrupted-errors", v->ti, 0);
194 }
195
196 snprintf(verity_env, DM_VERITY_ENV_LENGTH, "%s=%d,%llu",
197 DM_VERITY_ENV_VAR_NAME, type, block);
198
199 kobject_uevent_env(&disk_to_dev(dm_disk(md))->kobj, KOBJ_CHANGE, envp);
200
201 out:
202 if (v->mode == DM_VERITY_MODE_LOGGING)
203 return 0;
204
205 if (v->mode == DM_VERITY_MODE_RESTART)
206 kernel_restart("dm-verity device corrupted");
207
208 if (v->mode == DM_VERITY_MODE_PANIC)
209 panic("dm-verity device corrupted");
210
211 return 1;
212 }
213
214 /*
215 * Verify hash of a metadata block pertaining to the specified data block
216 * ("block" argument) at a specified level ("level" argument).
217 *
218 * On successful return, verity_io_want_digest(v, io) contains the hash value
219 * for a lower tree level or for the data block (if we're at the lowest level).
220 *
221 * If "skip_unverified" is true, unverified buffer is skipped and 1 is returned.
222 * If "skip_unverified" is false, unverified buffer is hashed and verified
223 * against current value of verity_io_want_digest(v, io).
224 */
verity_verify_level(struct dm_verity * v,struct dm_verity_io * io,sector_t block,int level,bool skip_unverified,u8 * want_digest)225 static int verity_verify_level(struct dm_verity *v, struct dm_verity_io *io,
226 sector_t block, int level, bool skip_unverified,
227 u8 *want_digest)
228 {
229 struct dm_buffer *buf;
230 struct buffer_aux *aux;
231 u8 *data;
232 int r;
233 sector_t hash_block;
234 unsigned int offset;
235 struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
236
237 verity_hash_at_level(v, block, level, &hash_block, &offset);
238
239 if (static_branch_unlikely(&use_bh_wq_enabled) && io->in_bh) {
240 data = dm_bufio_get(v->bufio, hash_block, &buf);
241 if (IS_ERR_OR_NULL(data)) {
242 /*
243 * In tasklet and the hash was not in the bufio cache.
244 * Return early and resume execution from a work-queue
245 * to read the hash from disk.
246 */
247 return -EAGAIN;
248 }
249 } else {
250 data = dm_bufio_read_with_ioprio(v->bufio, hash_block,
251 &buf, bio->bi_ioprio);
252 }
253
254 if (IS_ERR(data)) {
255 if (skip_unverified)
256 return 1;
257 r = PTR_ERR(data);
258 data = dm_bufio_new(v->bufio, hash_block, &buf);
259 if (IS_ERR(data))
260 return r;
261 if (verity_fec_decode(v, io, DM_VERITY_BLOCK_TYPE_METADATA,
262 hash_block, data) == 0) {
263 aux = dm_bufio_get_aux_data(buf);
264 aux->hash_verified = 1;
265 goto release_ok;
266 } else {
267 dm_bufio_release(buf);
268 dm_bufio_forget(v->bufio, hash_block);
269 return r;
270 }
271 }
272
273 aux = dm_bufio_get_aux_data(buf);
274
275 if (!aux->hash_verified) {
276 if (skip_unverified) {
277 r = 1;
278 goto release_ret_r;
279 }
280
281 r = verity_hash(v, io, data, 1 << v->hash_dev_block_bits,
282 verity_io_real_digest(v, io));
283 if (unlikely(r < 0))
284 goto release_ret_r;
285
286 if (likely(memcmp(verity_io_real_digest(v, io), want_digest,
287 v->digest_size) == 0))
288 aux->hash_verified = 1;
289 else if (static_branch_unlikely(&use_bh_wq_enabled) && io->in_bh) {
290 /*
291 * Error handling code (FEC included) cannot be run in a
292 * tasklet since it may sleep, so fallback to work-queue.
293 */
294 r = -EAGAIN;
295 goto release_ret_r;
296 } else if (verity_fec_decode(v, io, DM_VERITY_BLOCK_TYPE_METADATA,
297 hash_block, data) == 0)
298 aux->hash_verified = 1;
299 else if (verity_handle_err(v,
300 DM_VERITY_BLOCK_TYPE_METADATA,
301 hash_block)) {
302 struct bio *bio;
303 io->had_mismatch = true;
304 bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
305 dm_audit_log_bio(DM_MSG_PREFIX, "verify-metadata", bio,
306 block, 0);
307 r = -EIO;
308 goto release_ret_r;
309 }
310 }
311
312 release_ok:
313 data += offset;
314 memcpy(want_digest, data, v->digest_size);
315 r = 0;
316
317 release_ret_r:
318 dm_bufio_release(buf);
319 return r;
320 }
321
322 /*
323 * Find a hash for a given block, write it to digest and verify the integrity
324 * of the hash tree if necessary.
325 */
verity_hash_for_block(struct dm_verity * v,struct dm_verity_io * io,sector_t block,u8 * digest,bool * is_zero)326 int verity_hash_for_block(struct dm_verity *v, struct dm_verity_io *io,
327 sector_t block, u8 *digest, bool *is_zero)
328 {
329 int r = 0, i;
330
331 if (likely(v->levels)) {
332 /*
333 * First, we try to get the requested hash for
334 * the current block. If the hash block itself is
335 * verified, zero is returned. If it isn't, this
336 * function returns 1 and we fall back to whole
337 * chain verification.
338 */
339 r = verity_verify_level(v, io, block, 0, true, digest);
340 if (likely(r <= 0))
341 goto out;
342 }
343
344 memcpy(digest, v->root_digest, v->digest_size);
345
346 for (i = v->levels - 1; i >= 0; i--) {
347 r = verity_verify_level(v, io, block, i, false, digest);
348 if (unlikely(r))
349 goto out;
350 }
351 out:
352 if (!r && v->zero_digest)
353 *is_zero = !memcmp(v->zero_digest, digest, v->digest_size);
354 else
355 *is_zero = false;
356
357 return r;
358 }
359
verity_recheck(struct dm_verity * v,struct dm_verity_io * io,sector_t cur_block,u8 * dest)360 static noinline int verity_recheck(struct dm_verity *v, struct dm_verity_io *io,
361 sector_t cur_block, u8 *dest)
362 {
363 struct page *page;
364 void *buffer;
365 int r;
366 struct dm_io_request io_req;
367 struct dm_io_region io_loc;
368
369 page = mempool_alloc(&v->recheck_pool, GFP_NOIO);
370 buffer = page_to_virt(page);
371
372 io_req.bi_opf = REQ_OP_READ;
373 io_req.mem.type = DM_IO_KMEM;
374 io_req.mem.ptr.addr = buffer;
375 io_req.notify.fn = NULL;
376 io_req.client = v->io;
377 io_loc.bdev = v->data_dev->bdev;
378 io_loc.sector = cur_block << (v->data_dev_block_bits - SECTOR_SHIFT);
379 io_loc.count = 1 << (v->data_dev_block_bits - SECTOR_SHIFT);
380 r = dm_io(&io_req, 1, &io_loc, NULL, IOPRIO_DEFAULT);
381 if (unlikely(r))
382 goto free_ret;
383
384 r = verity_hash(v, io, buffer, 1 << v->data_dev_block_bits,
385 verity_io_real_digest(v, io));
386 if (unlikely(r))
387 goto free_ret;
388
389 if (memcmp(verity_io_real_digest(v, io),
390 verity_io_want_digest(v, io), v->digest_size)) {
391 r = -EIO;
392 goto free_ret;
393 }
394
395 memcpy(dest, buffer, 1 << v->data_dev_block_bits);
396 r = 0;
397 free_ret:
398 mempool_free(page, &v->recheck_pool);
399
400 return r;
401 }
402
verity_handle_data_hash_mismatch(struct dm_verity * v,struct dm_verity_io * io,struct bio * bio,sector_t blkno,u8 * data)403 static int verity_handle_data_hash_mismatch(struct dm_verity *v,
404 struct dm_verity_io *io,
405 struct bio *bio, sector_t blkno,
406 u8 *data)
407 {
408 if (static_branch_unlikely(&use_bh_wq_enabled) && io->in_bh) {
409 /*
410 * Error handling code (FEC included) cannot be run in the
411 * BH workqueue, so fallback to a standard workqueue.
412 */
413 return -EAGAIN;
414 }
415 if (verity_recheck(v, io, blkno, data) == 0) {
416 if (v->validated_blocks)
417 set_bit(blkno, v->validated_blocks);
418 return 0;
419 }
420 #if defined(CONFIG_DM_VERITY_FEC)
421 if (verity_fec_decode(v, io, DM_VERITY_BLOCK_TYPE_DATA, blkno,
422 data) == 0)
423 return 0;
424 #endif
425 if (bio->bi_status)
426 return -EIO; /* Error correction failed; Just return error */
427
428 if (verity_handle_err(v, DM_VERITY_BLOCK_TYPE_DATA, blkno)) {
429 io->had_mismatch = true;
430 dm_audit_log_bio(DM_MSG_PREFIX, "verify-data", bio, blkno, 0);
431 return -EIO;
432 }
433 return 0;
434 }
435
436 /*
437 * Verify one "dm_verity_io" structure.
438 */
verity_verify_io(struct dm_verity_io * io)439 static int verity_verify_io(struct dm_verity_io *io)
440 {
441 struct dm_verity *v = io->v;
442 const unsigned int block_size = 1 << v->data_dev_block_bits;
443 struct bvec_iter iter_copy;
444 struct bvec_iter *iter;
445 struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
446 unsigned int b;
447
448 if (static_branch_unlikely(&use_bh_wq_enabled) && io->in_bh) {
449 /*
450 * Copy the iterator in case we need to restart
451 * verification in a work-queue.
452 */
453 iter_copy = io->iter;
454 iter = &iter_copy;
455 } else
456 iter = &io->iter;
457
458 for (b = 0; b < io->n_blocks;
459 b++, bio_advance_iter(bio, iter, block_size)) {
460 int r;
461 sector_t cur_block = io->block + b;
462 bool is_zero;
463 struct bio_vec bv;
464 void *data;
465
466 if (v->validated_blocks && bio->bi_status == BLK_STS_OK &&
467 likely(test_bit(cur_block, v->validated_blocks)))
468 continue;
469
470 r = verity_hash_for_block(v, io, cur_block,
471 verity_io_want_digest(v, io),
472 &is_zero);
473 if (unlikely(r < 0))
474 return r;
475
476 bv = bio_iter_iovec(bio, *iter);
477 if (unlikely(bv.bv_len < block_size)) {
478 /*
479 * Data block spans pages. This should not happen,
480 * since dm-verity sets dma_alignment to the data block
481 * size minus 1, and dm-verity also doesn't allow the
482 * data block size to be greater than PAGE_SIZE.
483 */
484 DMERR_LIMIT("unaligned io (data block spans pages)");
485 return -EIO;
486 }
487
488 data = bvec_kmap_local(&bv);
489
490 if (is_zero) {
491 /*
492 * If we expect a zero block, don't validate, just
493 * return zeros.
494 */
495 memset(data, 0, block_size);
496 kunmap_local(data);
497 continue;
498 }
499
500 r = verity_hash(v, io, data, block_size,
501 verity_io_real_digest(v, io));
502 if (unlikely(r < 0)) {
503 kunmap_local(data);
504 return r;
505 }
506
507 if (likely(memcmp(verity_io_real_digest(v, io),
508 verity_io_want_digest(v, io), v->digest_size) == 0)) {
509 if (v->validated_blocks)
510 set_bit(cur_block, v->validated_blocks);
511 kunmap_local(data);
512 continue;
513 }
514 r = verity_handle_data_hash_mismatch(v, io, bio, cur_block,
515 data);
516 kunmap_local(data);
517 if (unlikely(r))
518 return r;
519 }
520
521 return 0;
522 }
523
524 /*
525 * Skip verity work in response to I/O error when system is shutting down.
526 */
verity_is_system_shutting_down(void)527 static inline bool verity_is_system_shutting_down(void)
528 {
529 return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
530 || system_state == SYSTEM_RESTART;
531 }
532
restart_io_error(struct work_struct * w)533 static void restart_io_error(struct work_struct *w)
534 {
535 kernel_restart("dm-verity device has I/O error");
536 }
537
538 /*
539 * End one "io" structure with a given error.
540 */
verity_finish_io(struct dm_verity_io * io,blk_status_t status)541 static void verity_finish_io(struct dm_verity_io *io, blk_status_t status)
542 {
543 struct dm_verity *v = io->v;
544 struct bio *bio = dm_bio_from_per_bio_data(io, v->ti->per_io_data_size);
545
546 bio->bi_end_io = io->orig_bi_end_io;
547 bio->bi_status = status;
548
549 if (!static_branch_unlikely(&use_bh_wq_enabled) || !io->in_bh)
550 verity_fec_finish_io(io);
551
552 if (unlikely(status != BLK_STS_OK) &&
553 unlikely(!(bio->bi_opf & REQ_RAHEAD)) &&
554 !io->had_mismatch &&
555 !verity_is_system_shutting_down()) {
556 if (v->error_mode == DM_VERITY_MODE_PANIC) {
557 panic("dm-verity device has I/O error");
558 }
559 if (v->error_mode == DM_VERITY_MODE_RESTART) {
560 static DECLARE_WORK(restart_work, restart_io_error);
561 queue_work(v->verify_wq, &restart_work);
562 /*
563 * We deliberately don't call bio_endio here, because
564 * the machine will be restarted anyway.
565 */
566 return;
567 }
568 }
569
570 bio_endio(bio);
571 }
572
verity_work(struct work_struct * w)573 static void verity_work(struct work_struct *w)
574 {
575 struct dm_verity_io *io = container_of(w, struct dm_verity_io, work);
576
577 io->in_bh = false;
578
579 verity_finish_io(io, errno_to_blk_status(verity_verify_io(io)));
580 }
581
verity_bh_work(struct work_struct * w)582 static void verity_bh_work(struct work_struct *w)
583 {
584 struct dm_verity_io *io = container_of(w, struct dm_verity_io, bh_work);
585 int err;
586
587 io->in_bh = true;
588 err = verity_verify_io(io);
589 if (err == -EAGAIN || err == -ENOMEM) {
590 /* fallback to retrying with work-queue */
591 INIT_WORK(&io->work, verity_work);
592 queue_work(io->v->verify_wq, &io->work);
593 return;
594 }
595
596 verity_finish_io(io, errno_to_blk_status(err));
597 }
598
verity_use_bh(unsigned int bytes,unsigned short ioprio)599 static inline bool verity_use_bh(unsigned int bytes, unsigned short ioprio)
600 {
601 return ioprio <= IOPRIO_CLASS_IDLE &&
602 bytes <= READ_ONCE(dm_verity_use_bh_bytes[ioprio]) &&
603 !need_resched();
604 }
605
verity_end_io(struct bio * bio)606 static void verity_end_io(struct bio *bio)
607 {
608 struct dm_verity_io *io = bio->bi_private;
609 unsigned short ioprio = IOPRIO_PRIO_CLASS(bio->bi_ioprio);
610 unsigned int bytes = io->n_blocks << io->v->data_dev_block_bits;
611
612 if (bio->bi_status &&
613 (!verity_fec_is_enabled(io->v) ||
614 verity_is_system_shutting_down() ||
615 (bio->bi_opf & REQ_RAHEAD))) {
616 verity_finish_io(io, bio->bi_status);
617 return;
618 }
619
620 if (static_branch_unlikely(&use_bh_wq_enabled) && io->v->use_bh_wq &&
621 verity_use_bh(bytes, ioprio)) {
622 if (in_hardirq() || irqs_disabled()) {
623 INIT_WORK(&io->bh_work, verity_bh_work);
624 queue_work(system_bh_wq, &io->bh_work);
625 } else {
626 verity_bh_work(&io->bh_work);
627 }
628 } else {
629 INIT_WORK(&io->work, verity_work);
630 queue_work(io->v->verify_wq, &io->work);
631 }
632 }
633
634 /*
635 * Prefetch buffers for the specified io.
636 * The root buffer is not prefetched, it is assumed that it will be cached
637 * all the time.
638 */
verity_prefetch_io(struct work_struct * work)639 static void verity_prefetch_io(struct work_struct *work)
640 {
641 struct dm_verity_prefetch_work *pw =
642 container_of(work, struct dm_verity_prefetch_work, work);
643 struct dm_verity *v = pw->v;
644 int i;
645
646 for (i = v->levels - 2; i >= 0; i--) {
647 sector_t hash_block_start;
648 sector_t hash_block_end;
649
650 verity_hash_at_level(v, pw->block, i, &hash_block_start, NULL);
651 verity_hash_at_level(v, pw->block + pw->n_blocks - 1, i, &hash_block_end, NULL);
652
653 if (!i) {
654 unsigned int cluster = READ_ONCE(dm_verity_prefetch_cluster);
655
656 cluster >>= v->data_dev_block_bits;
657 if (unlikely(!cluster))
658 goto no_prefetch_cluster;
659
660 if (unlikely(cluster & (cluster - 1)))
661 cluster = 1 << __fls(cluster);
662
663 hash_block_start &= ~(sector_t)(cluster - 1);
664 hash_block_end |= cluster - 1;
665 if (unlikely(hash_block_end >= v->hash_blocks))
666 hash_block_end = v->hash_blocks - 1;
667 }
668 no_prefetch_cluster:
669 dm_bufio_prefetch_with_ioprio(v->bufio, hash_block_start,
670 hash_block_end - hash_block_start + 1,
671 pw->ioprio);
672 }
673
674 kfree(pw);
675 }
676
verity_submit_prefetch(struct dm_verity * v,struct dm_verity_io * io,unsigned short ioprio)677 static void verity_submit_prefetch(struct dm_verity *v, struct dm_verity_io *io,
678 unsigned short ioprio)
679 {
680 sector_t block = io->block;
681 unsigned int n_blocks = io->n_blocks;
682 struct dm_verity_prefetch_work *pw;
683
684 if (v->validated_blocks) {
685 while (n_blocks && test_bit(block, v->validated_blocks)) {
686 block++;
687 n_blocks--;
688 }
689 while (n_blocks && test_bit(block + n_blocks - 1,
690 v->validated_blocks))
691 n_blocks--;
692 if (!n_blocks)
693 return;
694 }
695
696 pw = kmalloc(sizeof(struct dm_verity_prefetch_work),
697 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
698
699 if (!pw)
700 return;
701
702 INIT_WORK(&pw->work, verity_prefetch_io);
703 pw->v = v;
704 pw->block = block;
705 pw->n_blocks = n_blocks;
706 pw->ioprio = ioprio;
707 queue_work(v->verify_wq, &pw->work);
708 }
709
710 /*
711 * Bio map function. It allocates dm_verity_io structure and bio vector and
712 * fills them. Then it issues prefetches and the I/O.
713 */
verity_map(struct dm_target * ti,struct bio * bio)714 static int verity_map(struct dm_target *ti, struct bio *bio)
715 {
716 struct dm_verity *v = ti->private;
717 struct dm_verity_io *io;
718
719 bio_set_dev(bio, v->data_dev->bdev);
720 bio->bi_iter.bi_sector = verity_map_sector(v, bio->bi_iter.bi_sector);
721
722 if (((unsigned int)bio->bi_iter.bi_sector | bio_sectors(bio)) &
723 ((1 << (v->data_dev_block_bits - SECTOR_SHIFT)) - 1)) {
724 DMERR_LIMIT("unaligned io");
725 return DM_MAPIO_KILL;
726 }
727
728 if (bio_end_sector(bio) >>
729 (v->data_dev_block_bits - SECTOR_SHIFT) > v->data_blocks) {
730 DMERR_LIMIT("io out of range");
731 return DM_MAPIO_KILL;
732 }
733
734 if (bio_data_dir(bio) == WRITE)
735 return DM_MAPIO_KILL;
736
737 io = dm_per_bio_data(bio, ti->per_io_data_size);
738 io->v = v;
739 io->orig_bi_end_io = bio->bi_end_io;
740 io->block = bio->bi_iter.bi_sector >> (v->data_dev_block_bits - SECTOR_SHIFT);
741 io->n_blocks = bio->bi_iter.bi_size >> v->data_dev_block_bits;
742 io->had_mismatch = false;
743
744 bio->bi_end_io = verity_end_io;
745 bio->bi_private = io;
746 io->iter = bio->bi_iter;
747
748 verity_fec_init_io(io);
749
750 verity_submit_prefetch(v, io, bio->bi_ioprio);
751
752 submit_bio_noacct(bio);
753
754 return DM_MAPIO_SUBMITTED;
755 }
756
verity_postsuspend(struct dm_target * ti)757 static void verity_postsuspend(struct dm_target *ti)
758 {
759 struct dm_verity *v = ti->private;
760 flush_workqueue(v->verify_wq);
761 dm_bufio_client_reset(v->bufio);
762 }
763
764 /*
765 * Status: V (valid) or C (corruption found)
766 */
verity_status(struct dm_target * ti,status_type_t type,unsigned int status_flags,char * result,unsigned int maxlen)767 static void verity_status(struct dm_target *ti, status_type_t type,
768 unsigned int status_flags, char *result, unsigned int maxlen)
769 {
770 struct dm_verity *v = ti->private;
771 unsigned int args = 0;
772 unsigned int sz = 0;
773 unsigned int x;
774
775 switch (type) {
776 case STATUSTYPE_INFO:
777 DMEMIT("%c", v->hash_failed ? 'C' : 'V');
778 break;
779 case STATUSTYPE_TABLE:
780 DMEMIT("%u %s %s %u %u %llu %llu %s ",
781 v->version,
782 v->data_dev->name,
783 v->hash_dev->name,
784 1 << v->data_dev_block_bits,
785 1 << v->hash_dev_block_bits,
786 (unsigned long long)v->data_blocks,
787 (unsigned long long)v->hash_start,
788 v->alg_name
789 );
790 for (x = 0; x < v->digest_size; x++)
791 DMEMIT("%02x", v->root_digest[x]);
792 DMEMIT(" ");
793 if (!v->salt_size)
794 DMEMIT("-");
795 else
796 for (x = 0; x < v->salt_size; x++)
797 DMEMIT("%02x", v->salt[x]);
798 if (v->mode != DM_VERITY_MODE_EIO)
799 args++;
800 if (v->error_mode != DM_VERITY_MODE_EIO)
801 args++;
802 if (verity_fec_is_enabled(v))
803 args += DM_VERITY_OPTS_FEC;
804 if (v->zero_digest)
805 args++;
806 if (v->validated_blocks)
807 args++;
808 if (v->use_bh_wq)
809 args++;
810 if (v->signature_key_desc)
811 args += DM_VERITY_ROOT_HASH_VERIFICATION_OPTS;
812 if (!args)
813 return;
814 DMEMIT(" %u", args);
815 if (v->mode != DM_VERITY_MODE_EIO) {
816 DMEMIT(" ");
817 switch (v->mode) {
818 case DM_VERITY_MODE_LOGGING:
819 DMEMIT(DM_VERITY_OPT_LOGGING);
820 break;
821 case DM_VERITY_MODE_RESTART:
822 DMEMIT(DM_VERITY_OPT_RESTART);
823 break;
824 case DM_VERITY_MODE_PANIC:
825 DMEMIT(DM_VERITY_OPT_PANIC);
826 break;
827 default:
828 BUG();
829 }
830 }
831 if (v->error_mode != DM_VERITY_MODE_EIO) {
832 DMEMIT(" ");
833 switch (v->error_mode) {
834 case DM_VERITY_MODE_RESTART:
835 DMEMIT(DM_VERITY_OPT_ERROR_RESTART);
836 break;
837 case DM_VERITY_MODE_PANIC:
838 DMEMIT(DM_VERITY_OPT_ERROR_PANIC);
839 break;
840 default:
841 BUG();
842 }
843 }
844 if (v->zero_digest)
845 DMEMIT(" " DM_VERITY_OPT_IGN_ZEROES);
846 if (v->validated_blocks)
847 DMEMIT(" " DM_VERITY_OPT_AT_MOST_ONCE);
848 if (v->use_bh_wq)
849 DMEMIT(" " DM_VERITY_OPT_TASKLET_VERIFY);
850 sz = verity_fec_status_table(v, sz, result, maxlen);
851 if (v->signature_key_desc)
852 DMEMIT(" " DM_VERITY_ROOT_HASH_VERIFICATION_OPT_SIG_KEY
853 " %s", v->signature_key_desc);
854 break;
855
856 case STATUSTYPE_IMA:
857 DMEMIT_TARGET_NAME_VERSION(ti->type);
858 DMEMIT(",hash_failed=%c", v->hash_failed ? 'C' : 'V');
859 DMEMIT(",verity_version=%u", v->version);
860 DMEMIT(",data_device_name=%s", v->data_dev->name);
861 DMEMIT(",hash_device_name=%s", v->hash_dev->name);
862 DMEMIT(",verity_algorithm=%s", v->alg_name);
863
864 DMEMIT(",root_digest=");
865 for (x = 0; x < v->digest_size; x++)
866 DMEMIT("%02x", v->root_digest[x]);
867
868 DMEMIT(",salt=");
869 if (!v->salt_size)
870 DMEMIT("-");
871 else
872 for (x = 0; x < v->salt_size; x++)
873 DMEMIT("%02x", v->salt[x]);
874
875 DMEMIT(",ignore_zero_blocks=%c", v->zero_digest ? 'y' : 'n');
876 DMEMIT(",check_at_most_once=%c", v->validated_blocks ? 'y' : 'n');
877 if (v->signature_key_desc)
878 DMEMIT(",root_hash_sig_key_desc=%s", v->signature_key_desc);
879
880 if (v->mode != DM_VERITY_MODE_EIO) {
881 DMEMIT(",verity_mode=");
882 switch (v->mode) {
883 case DM_VERITY_MODE_LOGGING:
884 DMEMIT(DM_VERITY_OPT_LOGGING);
885 break;
886 case DM_VERITY_MODE_RESTART:
887 DMEMIT(DM_VERITY_OPT_RESTART);
888 break;
889 case DM_VERITY_MODE_PANIC:
890 DMEMIT(DM_VERITY_OPT_PANIC);
891 break;
892 default:
893 DMEMIT("invalid");
894 }
895 }
896 if (v->error_mode != DM_VERITY_MODE_EIO) {
897 DMEMIT(",verity_error_mode=");
898 switch (v->error_mode) {
899 case DM_VERITY_MODE_RESTART:
900 DMEMIT(DM_VERITY_OPT_ERROR_RESTART);
901 break;
902 case DM_VERITY_MODE_PANIC:
903 DMEMIT(DM_VERITY_OPT_ERROR_PANIC);
904 break;
905 default:
906 DMEMIT("invalid");
907 }
908 }
909 DMEMIT(";");
910 break;
911 }
912 }
913
verity_prepare_ioctl(struct dm_target * ti,struct block_device ** bdev,unsigned int cmd,unsigned long arg,bool * forward)914 static int verity_prepare_ioctl(struct dm_target *ti, struct block_device **bdev,
915 unsigned int cmd, unsigned long arg,
916 bool *forward)
917 {
918 struct dm_verity *v = ti->private;
919
920 *bdev = v->data_dev->bdev;
921
922 if (ti->len != bdev_nr_sectors(v->data_dev->bdev))
923 return 1;
924 return 0;
925 }
926
verity_iterate_devices(struct dm_target * ti,iterate_devices_callout_fn fn,void * data)927 static int verity_iterate_devices(struct dm_target *ti,
928 iterate_devices_callout_fn fn, void *data)
929 {
930 struct dm_verity *v = ti->private;
931
932 return fn(ti, v->data_dev, 0, ti->len, data);
933 }
934
verity_io_hints(struct dm_target * ti,struct queue_limits * limits)935 static void verity_io_hints(struct dm_target *ti, struct queue_limits *limits)
936 {
937 struct dm_verity *v = ti->private;
938
939 if (limits->logical_block_size < 1 << v->data_dev_block_bits)
940 limits->logical_block_size = 1 << v->data_dev_block_bits;
941
942 if (limits->physical_block_size < 1 << v->data_dev_block_bits)
943 limits->physical_block_size = 1 << v->data_dev_block_bits;
944
945 limits->io_min = limits->logical_block_size;
946
947 /*
948 * Similar to what dm-crypt does, opt dm-verity out of support for
949 * direct I/O that is aligned to less than the traditional direct I/O
950 * alignment requirement of logical_block_size. This prevents dm-verity
951 * data blocks from crossing pages, eliminating various edge cases.
952 */
953 limits->dma_alignment = limits->logical_block_size - 1;
954 }
955
956 #ifdef CONFIG_SECURITY
957
verity_init_sig(struct dm_verity * v,const void * sig,size_t sig_size)958 static int verity_init_sig(struct dm_verity *v, const void *sig,
959 size_t sig_size)
960 {
961 v->sig_size = sig_size;
962
963 if (sig) {
964 v->root_digest_sig = kmemdup(sig, v->sig_size, GFP_KERNEL);
965 if (!v->root_digest_sig)
966 return -ENOMEM;
967 }
968
969 return 0;
970 }
971
verity_free_sig(struct dm_verity * v)972 static void verity_free_sig(struct dm_verity *v)
973 {
974 kfree(v->root_digest_sig);
975 }
976
977 #else
978
verity_init_sig(struct dm_verity * v,const void * sig,size_t sig_size)979 static inline int verity_init_sig(struct dm_verity *v, const void *sig,
980 size_t sig_size)
981 {
982 return 0;
983 }
984
verity_free_sig(struct dm_verity * v)985 static inline void verity_free_sig(struct dm_verity *v)
986 {
987 }
988
989 #endif /* CONFIG_SECURITY */
990
verity_dtr(struct dm_target * ti)991 static void verity_dtr(struct dm_target *ti)
992 {
993 struct dm_verity *v = ti->private;
994
995 if (v->verify_wq)
996 destroy_workqueue(v->verify_wq);
997
998 mempool_exit(&v->recheck_pool);
999 if (v->io)
1000 dm_io_client_destroy(v->io);
1001
1002 if (v->bufio)
1003 dm_bufio_client_destroy(v->bufio);
1004
1005 kvfree(v->validated_blocks);
1006 kfree(v->salt);
1007 kfree(v->initial_hashstate);
1008 kfree(v->root_digest);
1009 kfree(v->zero_digest);
1010 verity_free_sig(v);
1011
1012 crypto_free_shash(v->shash_tfm);
1013
1014 kfree(v->alg_name);
1015
1016 if (v->hash_dev)
1017 dm_put_device(ti, v->hash_dev);
1018
1019 if (v->data_dev)
1020 dm_put_device(ti, v->data_dev);
1021
1022 verity_fec_dtr(v);
1023
1024 kfree(v->signature_key_desc);
1025
1026 if (v->use_bh_wq)
1027 static_branch_dec(&use_bh_wq_enabled);
1028
1029 kfree(v);
1030
1031 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
1032 }
1033
verity_alloc_most_once(struct dm_verity * v)1034 static int verity_alloc_most_once(struct dm_verity *v)
1035 {
1036 struct dm_target *ti = v->ti;
1037
1038 if (v->validated_blocks)
1039 return 0;
1040
1041 /* the bitset can only handle INT_MAX blocks */
1042 if (v->data_blocks > INT_MAX) {
1043 ti->error = "device too large to use check_at_most_once";
1044 return -E2BIG;
1045 }
1046
1047 v->validated_blocks = kvcalloc(BITS_TO_LONGS(v->data_blocks),
1048 sizeof(unsigned long),
1049 GFP_KERNEL);
1050 if (!v->validated_blocks) {
1051 ti->error = "failed to allocate bitset for check_at_most_once";
1052 return -ENOMEM;
1053 }
1054
1055 return 0;
1056 }
1057
verity_alloc_zero_digest(struct dm_verity * v)1058 static int verity_alloc_zero_digest(struct dm_verity *v)
1059 {
1060 int r = -ENOMEM;
1061 struct dm_verity_io *io;
1062 u8 *zero_data;
1063
1064 if (v->zero_digest)
1065 return 0;
1066
1067 v->zero_digest = kmalloc(v->digest_size, GFP_KERNEL);
1068
1069 if (!v->zero_digest)
1070 return r;
1071
1072 io = kmalloc(sizeof(*io) + crypto_shash_descsize(v->shash_tfm),
1073 GFP_KERNEL);
1074
1075 if (!io)
1076 return r; /* verity_dtr will free zero_digest */
1077
1078 zero_data = kzalloc(1 << v->data_dev_block_bits, GFP_KERNEL);
1079
1080 if (!zero_data)
1081 goto out;
1082
1083 r = verity_hash(v, io, zero_data, 1 << v->data_dev_block_bits,
1084 v->zero_digest);
1085
1086 out:
1087 kfree(io);
1088 kfree(zero_data);
1089
1090 return r;
1091 }
1092
verity_is_verity_mode(const char * arg_name)1093 static inline bool verity_is_verity_mode(const char *arg_name)
1094 {
1095 return (!strcasecmp(arg_name, DM_VERITY_OPT_LOGGING) ||
1096 !strcasecmp(arg_name, DM_VERITY_OPT_RESTART) ||
1097 !strcasecmp(arg_name, DM_VERITY_OPT_PANIC));
1098 }
1099
verity_parse_verity_mode(struct dm_verity * v,const char * arg_name)1100 static int verity_parse_verity_mode(struct dm_verity *v, const char *arg_name)
1101 {
1102 if (v->mode)
1103 return -EINVAL;
1104
1105 if (!strcasecmp(arg_name, DM_VERITY_OPT_LOGGING))
1106 v->mode = DM_VERITY_MODE_LOGGING;
1107 else if (!strcasecmp(arg_name, DM_VERITY_OPT_RESTART))
1108 v->mode = DM_VERITY_MODE_RESTART;
1109 else if (!strcasecmp(arg_name, DM_VERITY_OPT_PANIC))
1110 v->mode = DM_VERITY_MODE_PANIC;
1111
1112 return 0;
1113 }
1114
verity_is_verity_error_mode(const char * arg_name)1115 static inline bool verity_is_verity_error_mode(const char *arg_name)
1116 {
1117 return (!strcasecmp(arg_name, DM_VERITY_OPT_ERROR_RESTART) ||
1118 !strcasecmp(arg_name, DM_VERITY_OPT_ERROR_PANIC));
1119 }
1120
verity_parse_verity_error_mode(struct dm_verity * v,const char * arg_name)1121 static int verity_parse_verity_error_mode(struct dm_verity *v, const char *arg_name)
1122 {
1123 if (v->error_mode)
1124 return -EINVAL;
1125
1126 if (!strcasecmp(arg_name, DM_VERITY_OPT_ERROR_RESTART))
1127 v->error_mode = DM_VERITY_MODE_RESTART;
1128 else if (!strcasecmp(arg_name, DM_VERITY_OPT_ERROR_PANIC))
1129 v->error_mode = DM_VERITY_MODE_PANIC;
1130
1131 return 0;
1132 }
1133
verity_parse_opt_args(struct dm_arg_set * as,struct dm_verity * v,struct dm_verity_sig_opts * verify_args,bool only_modifier_opts)1134 static int verity_parse_opt_args(struct dm_arg_set *as, struct dm_verity *v,
1135 struct dm_verity_sig_opts *verify_args,
1136 bool only_modifier_opts)
1137 {
1138 int r = 0;
1139 unsigned int argc;
1140 struct dm_target *ti = v->ti;
1141 const char *arg_name;
1142
1143 static const struct dm_arg _args[] = {
1144 {0, DM_VERITY_OPTS_MAX, "Invalid number of feature args"},
1145 };
1146
1147 r = dm_read_arg_group(_args, as, &argc, &ti->error);
1148 if (r)
1149 return -EINVAL;
1150
1151 if (!argc)
1152 return 0;
1153
1154 do {
1155 arg_name = dm_shift_arg(as);
1156 argc--;
1157
1158 if (verity_is_verity_mode(arg_name)) {
1159 if (only_modifier_opts)
1160 continue;
1161 r = verity_parse_verity_mode(v, arg_name);
1162 if (r) {
1163 ti->error = "Conflicting error handling parameters";
1164 return r;
1165 }
1166 continue;
1167
1168 } else if (verity_is_verity_error_mode(arg_name)) {
1169 if (only_modifier_opts)
1170 continue;
1171 r = verity_parse_verity_error_mode(v, arg_name);
1172 if (r) {
1173 ti->error = "Conflicting error handling parameters";
1174 return r;
1175 }
1176 continue;
1177
1178 } else if (!strcasecmp(arg_name, DM_VERITY_OPT_IGN_ZEROES)) {
1179 if (only_modifier_opts)
1180 continue;
1181 r = verity_alloc_zero_digest(v);
1182 if (r) {
1183 ti->error = "Cannot allocate zero digest";
1184 return r;
1185 }
1186 continue;
1187
1188 } else if (!strcasecmp(arg_name, DM_VERITY_OPT_AT_MOST_ONCE)) {
1189 if (only_modifier_opts)
1190 continue;
1191 r = verity_alloc_most_once(v);
1192 if (r)
1193 return r;
1194 continue;
1195
1196 } else if (!strcasecmp(arg_name, DM_VERITY_OPT_TASKLET_VERIFY)) {
1197 v->use_bh_wq = true;
1198 static_branch_inc(&use_bh_wq_enabled);
1199 continue;
1200
1201 } else if (verity_is_fec_opt_arg(arg_name)) {
1202 if (only_modifier_opts)
1203 continue;
1204 r = verity_fec_parse_opt_args(as, v, &argc, arg_name);
1205 if (r)
1206 return r;
1207 continue;
1208
1209 } else if (verity_verify_is_sig_opt_arg(arg_name)) {
1210 if (only_modifier_opts)
1211 continue;
1212 r = verity_verify_sig_parse_opt_args(as, v,
1213 verify_args,
1214 &argc, arg_name);
1215 if (r)
1216 return r;
1217 continue;
1218
1219 } else if (only_modifier_opts) {
1220 /*
1221 * Ignore unrecognized opt, could easily be an extra
1222 * argument to an option whose parsing was skipped.
1223 * Normal parsing (@only_modifier_opts=false) will
1224 * properly parse all options (and their extra args).
1225 */
1226 continue;
1227 }
1228
1229 DMERR("Unrecognized verity feature request: %s", arg_name);
1230 ti->error = "Unrecognized verity feature request";
1231 return -EINVAL;
1232 } while (argc && !r);
1233
1234 return r;
1235 }
1236
verity_setup_hash_alg(struct dm_verity * v,const char * alg_name)1237 static int verity_setup_hash_alg(struct dm_verity *v, const char *alg_name)
1238 {
1239 struct dm_target *ti = v->ti;
1240 struct crypto_shash *shash;
1241
1242 v->alg_name = kstrdup(alg_name, GFP_KERNEL);
1243 if (!v->alg_name) {
1244 ti->error = "Cannot allocate algorithm name";
1245 return -ENOMEM;
1246 }
1247
1248 shash = crypto_alloc_shash(alg_name, 0, 0);
1249 if (IS_ERR(shash)) {
1250 ti->error = "Cannot initialize hash function";
1251 return PTR_ERR(shash);
1252 }
1253 v->shash_tfm = shash;
1254 v->digest_size = crypto_shash_digestsize(shash);
1255 DMINFO("%s using \"%s\"", alg_name, crypto_shash_driver_name(shash));
1256 if ((1 << v->hash_dev_block_bits) < v->digest_size * 2) {
1257 ti->error = "Digest size too big";
1258 return -EINVAL;
1259 }
1260 return 0;
1261 }
1262
verity_setup_salt_and_hashstate(struct dm_verity * v,const char * arg)1263 static int verity_setup_salt_and_hashstate(struct dm_verity *v, const char *arg)
1264 {
1265 struct dm_target *ti = v->ti;
1266
1267 if (strcmp(arg, "-") != 0) {
1268 v->salt_size = strlen(arg) / 2;
1269 v->salt = kmalloc(v->salt_size, GFP_KERNEL);
1270 if (!v->salt) {
1271 ti->error = "Cannot allocate salt";
1272 return -ENOMEM;
1273 }
1274 if (strlen(arg) != v->salt_size * 2 ||
1275 hex2bin(v->salt, arg, v->salt_size)) {
1276 ti->error = "Invalid salt";
1277 return -EINVAL;
1278 }
1279 }
1280 if (v->version) { /* Version 1: salt at beginning */
1281 SHASH_DESC_ON_STACK(desc, v->shash_tfm);
1282 int r;
1283
1284 /*
1285 * Compute the pre-salted hash state that can be passed to
1286 * crypto_shash_import() for each block later.
1287 */
1288 v->initial_hashstate = kmalloc(
1289 crypto_shash_statesize(v->shash_tfm), GFP_KERNEL);
1290 if (!v->initial_hashstate) {
1291 ti->error = "Cannot allocate initial hash state";
1292 return -ENOMEM;
1293 }
1294 desc->tfm = v->shash_tfm;
1295 r = crypto_shash_init(desc) ?:
1296 crypto_shash_update(desc, v->salt, v->salt_size) ?:
1297 crypto_shash_export(desc, v->initial_hashstate);
1298 if (r) {
1299 ti->error = "Cannot set up initial hash state";
1300 return r;
1301 }
1302 }
1303 return 0;
1304 }
1305
1306 /*
1307 * Target parameters:
1308 * <version> The current format is version 1.
1309 * Vsn 0 is compatible with original Chromium OS releases.
1310 * <data device>
1311 * <hash device>
1312 * <data block size>
1313 * <hash block size>
1314 * <the number of data blocks>
1315 * <hash start block>
1316 * <algorithm>
1317 * <digest>
1318 * <salt> Hex string or "-" if no salt.
1319 */
verity_ctr(struct dm_target * ti,unsigned int argc,char ** argv)1320 static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1321 {
1322 struct dm_verity *v;
1323 struct dm_verity_sig_opts verify_args = {0};
1324 struct dm_arg_set as;
1325 unsigned int num;
1326 unsigned long long num_ll;
1327 int r;
1328 int i;
1329 sector_t hash_position;
1330 char dummy;
1331 char *root_hash_digest_to_validate;
1332
1333 v = kzalloc(sizeof(struct dm_verity), GFP_KERNEL);
1334 if (!v) {
1335 ti->error = "Cannot allocate verity structure";
1336 return -ENOMEM;
1337 }
1338 ti->private = v;
1339 v->ti = ti;
1340
1341 r = verity_fec_ctr_alloc(v);
1342 if (r)
1343 goto bad;
1344
1345 if ((dm_table_get_mode(ti->table) & ~BLK_OPEN_READ)) {
1346 ti->error = "Device must be readonly";
1347 r = -EINVAL;
1348 goto bad;
1349 }
1350
1351 if (argc < 10) {
1352 ti->error = "Not enough arguments";
1353 r = -EINVAL;
1354 goto bad;
1355 }
1356
1357 /* Parse optional parameters that modify primary args */
1358 if (argc > 10) {
1359 as.argc = argc - 10;
1360 as.argv = argv + 10;
1361 r = verity_parse_opt_args(&as, v, &verify_args, true);
1362 if (r < 0)
1363 goto bad;
1364 }
1365
1366 if (sscanf(argv[0], "%u%c", &num, &dummy) != 1 ||
1367 num > 1) {
1368 ti->error = "Invalid version";
1369 r = -EINVAL;
1370 goto bad;
1371 }
1372 v->version = num;
1373
1374 r = dm_get_device(ti, argv[1], BLK_OPEN_READ, &v->data_dev);
1375 if (r) {
1376 ti->error = "Data device lookup failed";
1377 goto bad;
1378 }
1379
1380 r = dm_get_device(ti, argv[2], BLK_OPEN_READ, &v->hash_dev);
1381 if (r) {
1382 ti->error = "Hash device lookup failed";
1383 goto bad;
1384 }
1385
1386 if (sscanf(argv[3], "%u%c", &num, &dummy) != 1 ||
1387 !num || (num & (num - 1)) ||
1388 num < bdev_logical_block_size(v->data_dev->bdev) ||
1389 num > PAGE_SIZE) {
1390 ti->error = "Invalid data device block size";
1391 r = -EINVAL;
1392 goto bad;
1393 }
1394 v->data_dev_block_bits = __ffs(num);
1395
1396 if (sscanf(argv[4], "%u%c", &num, &dummy) != 1 ||
1397 !num || (num & (num - 1)) ||
1398 num < bdev_logical_block_size(v->hash_dev->bdev) ||
1399 num > INT_MAX) {
1400 ti->error = "Invalid hash device block size";
1401 r = -EINVAL;
1402 goto bad;
1403 }
1404 v->hash_dev_block_bits = __ffs(num);
1405
1406 if (sscanf(argv[5], "%llu%c", &num_ll, &dummy) != 1 ||
1407 (sector_t)(num_ll << (v->data_dev_block_bits - SECTOR_SHIFT))
1408 >> (v->data_dev_block_bits - SECTOR_SHIFT) != num_ll) {
1409 ti->error = "Invalid data blocks";
1410 r = -EINVAL;
1411 goto bad;
1412 }
1413 v->data_blocks = num_ll;
1414
1415 if (ti->len > (v->data_blocks << (v->data_dev_block_bits - SECTOR_SHIFT))) {
1416 ti->error = "Data device is too small";
1417 r = -EINVAL;
1418 goto bad;
1419 }
1420
1421 if (sscanf(argv[6], "%llu%c", &num_ll, &dummy) != 1 ||
1422 (sector_t)(num_ll << (v->hash_dev_block_bits - SECTOR_SHIFT))
1423 >> (v->hash_dev_block_bits - SECTOR_SHIFT) != num_ll) {
1424 ti->error = "Invalid hash start";
1425 r = -EINVAL;
1426 goto bad;
1427 }
1428 v->hash_start = num_ll;
1429
1430 r = verity_setup_hash_alg(v, argv[7]);
1431 if (r)
1432 goto bad;
1433
1434 v->root_digest = kmalloc(v->digest_size, GFP_KERNEL);
1435 if (!v->root_digest) {
1436 ti->error = "Cannot allocate root digest";
1437 r = -ENOMEM;
1438 goto bad;
1439 }
1440 if (strlen(argv[8]) != v->digest_size * 2 ||
1441 hex2bin(v->root_digest, argv[8], v->digest_size)) {
1442 ti->error = "Invalid root digest";
1443 r = -EINVAL;
1444 goto bad;
1445 }
1446 root_hash_digest_to_validate = argv[8];
1447
1448 r = verity_setup_salt_and_hashstate(v, argv[9]);
1449 if (r)
1450 goto bad;
1451
1452 argv += 10;
1453 argc -= 10;
1454
1455 /* Optional parameters */
1456 if (argc) {
1457 as.argc = argc;
1458 as.argv = argv;
1459 r = verity_parse_opt_args(&as, v, &verify_args, false);
1460 if (r < 0)
1461 goto bad;
1462 }
1463
1464 /* Root hash signature is an optional parameter */
1465 r = verity_verify_root_hash(root_hash_digest_to_validate,
1466 strlen(root_hash_digest_to_validate),
1467 verify_args.sig,
1468 verify_args.sig_size);
1469 if (r < 0) {
1470 ti->error = "Root hash verification failed";
1471 goto bad;
1472 }
1473
1474 r = verity_init_sig(v, verify_args.sig, verify_args.sig_size);
1475 if (r < 0) {
1476 ti->error = "Cannot allocate root digest signature";
1477 goto bad;
1478 }
1479
1480 v->hash_per_block_bits =
1481 __fls((1 << v->hash_dev_block_bits) / v->digest_size);
1482
1483 v->levels = 0;
1484 if (v->data_blocks)
1485 while (v->hash_per_block_bits * v->levels < 64 &&
1486 (unsigned long long)(v->data_blocks - 1) >>
1487 (v->hash_per_block_bits * v->levels))
1488 v->levels++;
1489
1490 if (v->levels > DM_VERITY_MAX_LEVELS) {
1491 ti->error = "Too many tree levels";
1492 r = -E2BIG;
1493 goto bad;
1494 }
1495
1496 hash_position = v->hash_start;
1497 for (i = v->levels - 1; i >= 0; i--) {
1498 sector_t s;
1499
1500 v->hash_level_block[i] = hash_position;
1501 s = (v->data_blocks + ((sector_t)1 << ((i + 1) * v->hash_per_block_bits)) - 1)
1502 >> ((i + 1) * v->hash_per_block_bits);
1503 if (hash_position + s < hash_position) {
1504 ti->error = "Hash device offset overflow";
1505 r = -E2BIG;
1506 goto bad;
1507 }
1508 hash_position += s;
1509 }
1510 v->hash_blocks = hash_position;
1511
1512 r = mempool_init_page_pool(&v->recheck_pool, 1, 0);
1513 if (unlikely(r)) {
1514 ti->error = "Cannot allocate mempool";
1515 goto bad;
1516 }
1517
1518 v->io = dm_io_client_create();
1519 if (IS_ERR(v->io)) {
1520 r = PTR_ERR(v->io);
1521 v->io = NULL;
1522 ti->error = "Cannot allocate dm io";
1523 goto bad;
1524 }
1525
1526 v->bufio = dm_bufio_client_create(v->hash_dev->bdev,
1527 1 << v->hash_dev_block_bits, 1, sizeof(struct buffer_aux),
1528 dm_bufio_alloc_callback, NULL,
1529 v->use_bh_wq ? DM_BUFIO_CLIENT_NO_SLEEP : 0);
1530 if (IS_ERR(v->bufio)) {
1531 ti->error = "Cannot initialize dm-bufio";
1532 r = PTR_ERR(v->bufio);
1533 v->bufio = NULL;
1534 goto bad;
1535 }
1536
1537 if (dm_bufio_get_device_size(v->bufio) < v->hash_blocks) {
1538 ti->error = "Hash device is too small";
1539 r = -E2BIG;
1540 goto bad;
1541 }
1542
1543 /*
1544 * Using WQ_HIGHPRI improves throughput and completion latency by
1545 * reducing wait times when reading from a dm-verity device.
1546 *
1547 * Also as required for the "try_verify_in_tasklet" feature: WQ_HIGHPRI
1548 * allows verify_wq to preempt softirq since verification in BH workqueue
1549 * will fall-back to using it for error handling (or if the bufio cache
1550 * doesn't have required hashes).
1551 */
1552 v->verify_wq = alloc_workqueue("kverityd", WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
1553 if (!v->verify_wq) {
1554 ti->error = "Cannot allocate workqueue";
1555 r = -ENOMEM;
1556 goto bad;
1557 }
1558
1559 ti->per_io_data_size = sizeof(struct dm_verity_io) +
1560 crypto_shash_descsize(v->shash_tfm);
1561
1562 r = verity_fec_ctr(v);
1563 if (r)
1564 goto bad;
1565
1566 ti->per_io_data_size = roundup(ti->per_io_data_size,
1567 __alignof__(struct dm_verity_io));
1568
1569 verity_verify_sig_opts_cleanup(&verify_args);
1570
1571 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
1572
1573 return 0;
1574
1575 bad:
1576
1577 verity_verify_sig_opts_cleanup(&verify_args);
1578 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
1579 verity_dtr(ti);
1580
1581 return r;
1582 }
1583
1584 /*
1585 * Get the verity mode (error behavior) of a verity target.
1586 *
1587 * Returns the verity mode of the target, or -EINVAL if 'ti' is not a verity
1588 * target.
1589 */
dm_verity_get_mode(struct dm_target * ti)1590 int dm_verity_get_mode(struct dm_target *ti)
1591 {
1592 struct dm_verity *v = ti->private;
1593
1594 if (!dm_is_verity_target(ti))
1595 return -EINVAL;
1596
1597 return v->mode;
1598 }
1599
1600 /*
1601 * Get the root digest of a verity target.
1602 *
1603 * Returns a copy of the root digest, the caller is responsible for
1604 * freeing the memory of the digest.
1605 */
dm_verity_get_root_digest(struct dm_target * ti,u8 ** root_digest,unsigned int * digest_size)1606 int dm_verity_get_root_digest(struct dm_target *ti, u8 **root_digest, unsigned int *digest_size)
1607 {
1608 struct dm_verity *v = ti->private;
1609
1610 if (!dm_is_verity_target(ti))
1611 return -EINVAL;
1612
1613 *root_digest = kmemdup(v->root_digest, v->digest_size, GFP_KERNEL);
1614 if (*root_digest == NULL)
1615 return -ENOMEM;
1616
1617 *digest_size = v->digest_size;
1618
1619 return 0;
1620 }
1621
1622 #ifdef CONFIG_SECURITY
1623
1624 #ifdef CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG
1625
verity_security_set_signature(struct block_device * bdev,struct dm_verity * v)1626 static int verity_security_set_signature(struct block_device *bdev,
1627 struct dm_verity *v)
1628 {
1629 /*
1630 * if the dm-verity target is unsigned, v->root_digest_sig will
1631 * be NULL, and the hook call is still required to let LSMs mark
1632 * the device as unsigned. This information is crucial for LSMs to
1633 * block operations such as execution on unsigned files
1634 */
1635 return security_bdev_setintegrity(bdev,
1636 LSM_INT_DMVERITY_SIG_VALID,
1637 v->root_digest_sig,
1638 v->sig_size);
1639 }
1640
1641 #else
1642
verity_security_set_signature(struct block_device * bdev,struct dm_verity * v)1643 static inline int verity_security_set_signature(struct block_device *bdev,
1644 struct dm_verity *v)
1645 {
1646 return 0;
1647 }
1648
1649 #endif /* CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG */
1650
1651 /*
1652 * Expose verity target's root hash and signature data to LSMs before resume.
1653 *
1654 * Returns 0 on success, or -ENOMEM if the system is out of memory.
1655 */
verity_preresume(struct dm_target * ti)1656 static int verity_preresume(struct dm_target *ti)
1657 {
1658 struct block_device *bdev;
1659 struct dm_verity_digest root_digest;
1660 struct dm_verity *v;
1661 int r;
1662
1663 v = ti->private;
1664 bdev = dm_disk(dm_table_get_md(ti->table))->part0;
1665 root_digest.digest = v->root_digest;
1666 root_digest.digest_len = v->digest_size;
1667 root_digest.alg = crypto_shash_alg_name(v->shash_tfm);
1668
1669 r = security_bdev_setintegrity(bdev, LSM_INT_DMVERITY_ROOTHASH, &root_digest,
1670 sizeof(root_digest));
1671 if (r)
1672 return r;
1673
1674 r = verity_security_set_signature(bdev, v);
1675 if (r)
1676 goto bad;
1677
1678 return 0;
1679
1680 bad:
1681
1682 security_bdev_setintegrity(bdev, LSM_INT_DMVERITY_ROOTHASH, NULL, 0);
1683
1684 return r;
1685 }
1686
1687 #endif /* CONFIG_SECURITY */
1688
1689 static struct target_type verity_target = {
1690 .name = "verity",
1691 /* Note: the LSMs depend on the singleton and immutable features */
1692 .features = DM_TARGET_SINGLETON | DM_TARGET_IMMUTABLE,
1693 .version = {1, 12, 0},
1694 .module = THIS_MODULE,
1695 .ctr = verity_ctr,
1696 .dtr = verity_dtr,
1697 .map = verity_map,
1698 .postsuspend = verity_postsuspend,
1699 .status = verity_status,
1700 .prepare_ioctl = verity_prepare_ioctl,
1701 .iterate_devices = verity_iterate_devices,
1702 .io_hints = verity_io_hints,
1703 #ifdef CONFIG_SECURITY
1704 .preresume = verity_preresume,
1705 #endif /* CONFIG_SECURITY */
1706 };
1707 module_dm(verity);
1708
1709 /*
1710 * Check whether a DM target is a verity target.
1711 */
dm_is_verity_target(struct dm_target * ti)1712 bool dm_is_verity_target(struct dm_target *ti)
1713 {
1714 return ti->type == &verity_target;
1715 }
1716
1717 MODULE_AUTHOR("Mikulas Patocka <mpatocka@redhat.com>");
1718 MODULE_AUTHOR("Mandeep Baines <msb@chromium.org>");
1719 MODULE_AUTHOR("Will Drewry <wad@chromium.org>");
1720 MODULE_DESCRIPTION(DM_NAME " target for transparent disk integrity checking");
1721 MODULE_LICENSE("GPL");
1722