2 * Copyright (C) 2015 Google, Inc.
4 * This software is licensed under the terms of the GNU General Public
5 * License version 2, as published by the Free Software Foundation, and
6 * may be copied, distributed, and modified under those terms.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
15 #include <linux/buffer_head.h>
16 #include <linux/debugfs.h>
17 #include <linux/delay.h>
18 #include <linux/device.h>
19 #include <linux/device-mapper.h>
20 #include <linux/errno.h>
22 #include <linux/fcntl.h>
23 #include <linux/init.h>
24 #include <linux/kernel.h>
25 #include <linux/key.h>
26 #include <linux/module.h>
27 #include <linux/mount.h>
28 #include <linux/namei.h>
30 #include <linux/reboot.h>
31 #include <linux/string.h>
32 #include <linux/vmalloc.h>
34 #include <asm/setup.h>
35 #include <crypto/hash.h>
36 #include <crypto/public_key.h>
37 #include <crypto/sha.h>
38 #include <keys/asymmetric-type.h>
39 #include <keys/system_keyring.h>
41 #include "dm-verity.h"
42 #include "dm-android-verity.h"
44 static char verifiedbootstate[VERITY_COMMANDLINE_PARAM_LENGTH];
45 static char veritymode[VERITY_COMMANDLINE_PARAM_LENGTH];
46 static char veritykeyid[VERITY_DEFAULT_KEY_ID_LENGTH];
48 static bool target_added;
49 static bool verity_enabled = true;
50 struct dentry *debug_dir;
51 static int android_verity_ctr(struct dm_target *ti, unsigned argc, char **argv);
53 static struct target_type android_verity_target = {
54 .name = "android-verity",
56 .module = THIS_MODULE,
57 .ctr = android_verity_ctr,
60 .status = verity_status,
61 .ioctl = verity_ioctl,
62 .merge = verity_merge,
63 .iterate_devices = verity_iterate_devices,
64 .io_hints = verity_io_hints,
67 static int __init verified_boot_state_param(char *line)
69 strlcpy(verifiedbootstate, line, sizeof(verifiedbootstate));
73 __setup("androidboot.verifiedbootstate=", verified_boot_state_param);
75 static int __init verity_mode_param(char *line)
77 strlcpy(veritymode, line, sizeof(veritymode));
81 __setup("androidboot.veritymode=", verity_mode_param);
83 static int __init verity_keyid_param(char *line)
85 strlcpy(veritykeyid, line, sizeof(veritykeyid));
89 __setup("veritykeyid=", verity_keyid_param);
91 static inline bool default_verity_key_id(void)
93 return veritykeyid[0] != '\0';
96 static int table_extract_mpi_array(struct public_key_signature *pks,
97 const void *data, size_t len)
99 MPI mpi = mpi_read_raw_data(data, len);
102 DMERR("Error while allocating mpi array");
111 static struct public_key_signature *table_make_digest(
114 unsigned long table_len)
116 struct public_key_signature *pks = NULL;
117 struct crypto_shash *tfm;
118 struct shash_desc *desc;
119 size_t digest_size, desc_size;
122 /* Allocate the hashing algorithm we're going to need and find out how
123 * big the hash operational data will be.
125 tfm = crypto_alloc_shash(hash_algo_name[hash], 0, 0);
127 return ERR_CAST(tfm);
129 desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
130 digest_size = crypto_shash_digestsize(tfm);
132 /* We allocate the hash operational data storage on the end of out
133 * context data and the digest output buffer on the end of that.
136 pks = kzalloc(digest_size + sizeof(*pks) + desc_size, GFP_KERNEL);
140 pks->pkey_hash_algo = hash;
141 pks->digest = (u8 *)pks + sizeof(*pks) + desc_size;
142 pks->digest_size = digest_size;
144 desc = (struct shash_desc *)(pks + 1);
146 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
148 ret = crypto_shash_init(desc);
152 ret = crypto_shash_finup(desc, table, table_len, pks->digest);
156 crypto_free_shash(tfm);
161 crypto_free_shash(tfm);
165 static int read_block_dev(struct bio_read *payload, struct block_device *bdev,
166 sector_t offset, int length)
171 payload->number_of_pages = DIV_ROUND_UP(length, PAGE_SIZE);
173 bio = bio_alloc(GFP_KERNEL, payload->number_of_pages);
175 DMERR("Error while allocating bio");
180 bio->bi_iter.bi_sector = offset;
182 payload->page_io = kzalloc(sizeof(struct page *) *
183 payload->number_of_pages, GFP_KERNEL);
184 if (!payload->page_io) {
185 DMERR("page_io array alloc failed");
190 for (i = 0; i < payload->number_of_pages; i++) {
191 payload->page_io[i] = alloc_page(GFP_KERNEL);
192 if (!payload->page_io[i]) {
193 DMERR("alloc_page failed");
197 if (!bio_add_page(bio, payload->page_io[i], PAGE_SIZE, 0)) {
198 DMERR("bio_add_page error");
204 if (!submit_bio_wait(READ, bio))
207 DMERR("bio read failed");
211 for (i = 0; i < payload->number_of_pages; i++)
212 if (payload->page_io[i])
213 __free_page(payload->page_io[i]);
214 kfree(payload->page_io);
220 static inline u64 fec_div_round_up(u64 x, u64 y)
224 return div64_u64_rem(x, y, &remainder) +
225 (remainder > 0 ? 1 : 0);
228 static inline void populate_fec_metadata(struct fec_header *header,
229 struct fec_ecc_metadata *ecc)
231 ecc->blocks = fec_div_round_up(le64_to_cpu(header->inp_size),
233 ecc->roots = le32_to_cpu(header->roots);
234 ecc->start = le64_to_cpu(header->inp_size);
237 static inline int validate_fec_header(struct fec_header *header, u64 offset)
239 /* move offset to make the sanity check work for backup header
241 offset -= offset % FEC_BLOCK_SIZE;
242 if (le32_to_cpu(header->magic) != FEC_MAGIC ||
243 le32_to_cpu(header->version) != FEC_VERSION ||
244 le32_to_cpu(header->size) != sizeof(struct fec_header) ||
245 le32_to_cpu(header->roots) == 0 ||
246 le32_to_cpu(header->roots) >= FEC_RSM ||
247 offset < le32_to_cpu(header->fec_size) ||
248 offset - le32_to_cpu(header->fec_size) !=
249 le64_to_cpu(header->inp_size))
255 static int extract_fec_header(dev_t dev, struct fec_header *fec,
256 struct fec_ecc_metadata *ecc)
259 struct bio_read payload;
261 struct block_device *bdev;
263 bdev = blkdev_get_by_dev(dev, FMODE_READ, NULL);
266 DMERR("bdev get error");
267 return PTR_ERR(bdev);
270 device_size = i_size_read(bdev->bd_inode);
272 /* fec metadata size is a power of 2 and PAGE_SIZE
273 * is a power of 2 as well.
275 BUG_ON(FEC_BLOCK_SIZE > PAGE_SIZE);
276 /* 512 byte sector alignment */
277 BUG_ON(((device_size - FEC_BLOCK_SIZE) % (1 << SECTOR_SHIFT)) != 0);
279 err = read_block_dev(&payload, bdev, (device_size -
280 FEC_BLOCK_SIZE) / (1 << SECTOR_SHIFT), FEC_BLOCK_SIZE);
282 DMERR("Error while reading verity metadata");
286 BUG_ON(sizeof(struct fec_header) > PAGE_SIZE);
287 memcpy(fec, page_address(payload.page_io[0]),
291 if (validate_fec_header(fec, device_size - FEC_BLOCK_SIZE)) {
292 /* Try the backup header */
293 memcpy(fec, page_address(payload.page_io[0]) + FEC_BLOCK_SIZE
296 if (validate_fec_header(fec, device_size -
297 sizeof(struct fec_header)))
302 populate_fec_metadata(fec, ecc);
304 for (i = 0; i < payload.number_of_pages; i++)
305 __free_page(payload.page_io[i]);
306 kfree(payload.page_io);
309 blkdev_put(bdev, FMODE_READ);
312 static void find_metadata_offset(struct fec_header *fec,
313 struct block_device *bdev, u64 *metadata_offset)
317 device_size = i_size_read(bdev->bd_inode);
319 if (le32_to_cpu(fec->magic) == FEC_MAGIC)
320 *metadata_offset = le64_to_cpu(fec->inp_size) -
321 VERITY_METADATA_SIZE;
323 *metadata_offset = device_size - VERITY_METADATA_SIZE;
326 static struct android_metadata *extract_metadata(dev_t dev,
327 struct fec_header *fec)
329 struct block_device *bdev;
330 struct android_metadata_header *header;
331 struct android_metadata *uninitialized_var(metadata);
333 u32 table_length, copy_length, offset;
335 struct bio_read payload;
338 bdev = blkdev_get_by_dev(dev, FMODE_READ, NULL);
341 DMERR("blkdev_get_by_dev failed");
342 return ERR_CAST(bdev);
345 find_metadata_offset(fec, bdev, &metadata_offset);
347 /* Verity metadata size is a power of 2 and PAGE_SIZE
348 * is a power of 2 as well.
349 * PAGE_SIZE is also a multiple of 512 bytes.
351 if (VERITY_METADATA_SIZE > PAGE_SIZE)
352 BUG_ON(VERITY_METADATA_SIZE % PAGE_SIZE != 0);
353 /* 512 byte sector alignment */
354 BUG_ON(metadata_offset % (1 << SECTOR_SHIFT) != 0);
356 err = read_block_dev(&payload, bdev, metadata_offset /
357 (1 << SECTOR_SHIFT), VERITY_METADATA_SIZE);
359 DMERR("Error while reading verity metadata");
360 metadata = ERR_PTR(err);
364 header = kzalloc(sizeof(*header), GFP_KERNEL);
366 DMERR("kzalloc failed for header");
371 memcpy(header, page_address(payload.page_io[0]),
374 DMINFO("bio magic_number:%u protocol_version:%d table_length:%u",
375 le32_to_cpu(header->magic_number),
376 le32_to_cpu(header->protocol_version),
377 le32_to_cpu(header->table_length));
379 metadata = kzalloc(sizeof(*metadata), GFP_KERNEL);
381 DMERR("kzalloc for metadata failed");
386 metadata->header = header;
387 table_length = le32_to_cpu(header->table_length);
389 if (table_length == 0 ||
390 table_length > (VERITY_METADATA_SIZE -
391 sizeof(struct android_metadata_header)))
394 metadata->verity_table = kzalloc(table_length + 1, GFP_KERNEL);
396 if (!metadata->verity_table) {
397 DMERR("kzalloc verity_table failed");
402 if (sizeof(struct android_metadata_header) +
403 table_length <= PAGE_SIZE) {
404 memcpy(metadata->verity_table, page_address(payload.page_io[0])
405 + sizeof(struct android_metadata_header),
408 copy_length = PAGE_SIZE -
409 sizeof(struct android_metadata_header);
410 memcpy(metadata->verity_table, page_address(payload.page_io[0])
411 + sizeof(struct android_metadata_header),
413 table_length -= copy_length;
414 offset = copy_length;
416 while (table_length != 0) {
417 if (table_length > PAGE_SIZE) {
418 memcpy(metadata->verity_table + offset,
419 page_address(payload.page_io[i]),
422 table_length -= PAGE_SIZE;
424 memcpy(metadata->verity_table + offset,
425 page_address(payload.page_io[i]),
432 metadata->verity_table[table_length] = '\0';
440 metadata = ERR_PTR(err);
442 for (i = 0; i < payload.number_of_pages; i++)
443 if (payload.page_io[i])
444 __free_page(payload.page_io[i]);
445 kfree(payload.page_io);
447 DMINFO("verity_table: %s", metadata->verity_table);
449 blkdev_put(bdev, FMODE_READ);
453 /* helper functions to extract properties from dts */
454 const char *find_dt_value(const char *name)
456 struct device_node *firmware;
459 firmware = of_find_node_by_path("/firmware/android");
462 value = of_get_property(firmware, name, NULL);
463 of_node_put(firmware);
468 static bool is_unlocked(void)
470 static const char unlocked[] = "orange";
471 static const char verified_boot_prop[] = "verifiedbootstate";
474 value = find_dt_value(verified_boot_prop);
476 value = verifiedbootstate;
478 return !strncmp(value, unlocked, sizeof(unlocked) - 1);
481 static int verity_mode(void)
483 static const char enforcing[] = "enforcing";
484 static const char verified_mode_prop[] = "veritymode";
487 value = find_dt_value(verified_mode_prop);
490 if (!strncmp(value, enforcing, sizeof(enforcing) - 1))
491 return DM_VERITY_MODE_RESTART;
493 return DM_VERITY_MODE_EIO;
496 static int verify_header(struct android_metadata_header *header)
498 int retval = -EINVAL;
500 if (is_unlocked() && le32_to_cpu(header->magic_number) ==
501 VERITY_METADATA_MAGIC_DISABLE) {
502 retval = VERITY_STATE_DISABLE;
506 if (!(le32_to_cpu(header->magic_number) ==
507 VERITY_METADATA_MAGIC_NUMBER) ||
508 (le32_to_cpu(header->magic_number) ==
509 VERITY_METADATA_MAGIC_DISABLE)) {
510 DMERR("Incorrect magic number");
514 if (le32_to_cpu(header->protocol_version) !=
515 VERITY_METADATA_VERSION) {
516 DMERR("Unsupported version %u",
517 le32_to_cpu(header->protocol_version));
524 static int verify_verity_signature(char *key_id,
525 struct android_metadata *metadata)
529 struct public_key_signature *pks = NULL;
530 int retval = -EINVAL;
532 key_ref = keyring_search(make_key_ref(system_trusted_keyring, 1),
533 &key_type_asymmetric, key_id);
535 if (IS_ERR(key_ref)) {
536 DMERR("keyring: key not found");
540 key = key_ref_to_ptr(key_ref);
542 pks = table_make_digest(HASH_ALGO_SHA256,
543 (const void *)metadata->verity_table,
544 le32_to_cpu(metadata->header->table_length));
547 DMERR("hashing failed");
551 retval = table_extract_mpi_array(pks, &metadata->header->signature[0],
554 DMERR("Error extracting mpi %d", retval);
558 retval = verify_signature(key, pks);
559 mpi_free(pks->rsa.s);
567 static void handle_error(void)
569 int mode = verity_mode();
570 if (mode == DM_VERITY_MODE_RESTART) {
571 DMERR("triggering restart");
572 kernel_restart("dm-verity device corrupted");
574 DMERR("Mounting verity root failed");
578 static inline bool test_mult_overflow(sector_t a, u32 b)
580 sector_t r = (sector_t)~0ULL;
586 static int add_as_linear_device(struct dm_target *ti, char *dev)
588 /*Move to linear mapping defines*/
589 char *linear_table_args[DM_LINEAR_ARGS] = {dev,
590 DM_LINEAR_TARGET_OFFSET};
593 android_verity_target.dtr = dm_linear_dtr,
594 android_verity_target.map = dm_linear_map,
595 android_verity_target.status = dm_linear_status,
596 android_verity_target.ioctl = dm_linear_ioctl,
597 android_verity_target.merge = dm_linear_merge,
598 android_verity_target.iterate_devices = dm_linear_iterate_devices,
599 android_verity_target.io_hints = NULL;
601 err = dm_linear_ctr(ti, DM_LINEAR_ARGS, linear_table_args);
604 DMINFO("Added android-verity as a linear target");
607 DMERR("Failed to add android-verity as linear target");
614 * <key id> Key id of the public key in the system keyring.
615 * Verity metadata's signature would be verified against
616 * this. If the key id contains spaces, replace them
618 * <block device> The block device for which dm-verity is being setup.
620 static int android_verity_ctr(struct dm_target *ti, unsigned argc, char **argv)
622 dev_t uninitialized_var(dev);
623 struct android_metadata *uninitialized_var(metadata);
624 int err = 0, i, mode;
625 char *key_id, *table_ptr, dummy, *target_device,
626 *verity_table_args[VERITY_TABLE_ARGS + 2 + VERITY_TABLE_OPT_FEC_ARGS];
627 /* One for specifying number of opt args and one for mode */
628 sector_t data_sectors;
630 unsigned int no_of_args = VERITY_TABLE_ARGS + 2 + VERITY_TABLE_OPT_FEC_ARGS;
631 struct fec_header uninitialized_var(fec);
632 struct fec_ecc_metadata uninitialized_var(ecc);
633 char buf[FEC_ARG_LENGTH], *buf_ptr;
634 unsigned long long tmpll;
637 /* Use the default keyid */
638 if (default_verity_key_id())
639 key_id = veritykeyid;
641 DMERR("veritykeyid= is not set");
645 } else if (argc == 2)
648 DMERR("Incorrect number of arguments");
653 strreplace(key_id, '#', ' ');
654 target_device = argv[0];
656 dev = name_to_dev_t(target_device);
658 DMERR("no dev found for %s", target_device);
663 DMINFO("key:%s dev:%s", key_id, target_device);
665 if (extract_fec_header(dev, &fec, &ecc)) {
666 DMERR("Error while extracting fec header");
671 metadata = extract_metadata(dev, &fec);
673 if (IS_ERR(metadata)) {
674 DMERR("Error while extracting metadata");
679 err = verify_header(metadata->header);
681 if (err == VERITY_STATE_DISABLE) {
682 DMERR("Mounting root with verity disabled");
683 verity_enabled = false;
684 /* we would still have to parse the args to figure out
685 * the data blocks size. Or may be could map the entire
686 * partition similar to mounting the device.
689 DMERR("Verity header handle error");
694 if (verity_enabled) {
695 err = verify_verity_signature(key_id, metadata);
698 DMERR("Signature verification failed");
702 DMINFO("Signature verification success");
705 table_ptr = metadata->verity_table;
707 for (i = 0; i < VERITY_TABLE_ARGS; i++) {
708 verity_table_args[i] = strsep(&table_ptr, " ");
709 if (verity_table_args[i] == NULL)
713 if (i != VERITY_TABLE_ARGS) {
714 DMERR("Verity table not in the expected format");
720 if (sscanf(verity_table_args[5], "%llu%c", &tmpll, &dummy)
722 DMERR("Verity table not in the expected format");
728 if (tmpll > ULONG_MAX) {
729 DMERR("<num_data_blocks> too large. Forgot to turn on CONFIG_LBDAF?");
735 data_sectors = tmpll;
737 if (sscanf(verity_table_args[3], "%u%c", &data_block_size, &dummy)
739 DMERR("Verity table not in the expected format");
745 if (test_mult_overflow(data_sectors, data_block_size >>
747 DMERR("data_sectors too large");
753 data_sectors *= data_block_size >> SECTOR_SHIFT;
754 DMINFO("Data sectors %llu", (unsigned long long)data_sectors);
756 /* update target length */
757 ti->len = data_sectors;
759 /* Setup linear target and free */
760 if (!verity_enabled) {
761 err = add_as_linear_device(ti, target_device);
765 /*substitute data_dev and hash_dev*/
766 verity_table_args[1] = target_device;
767 verity_table_args[2] = target_device;
769 mode = verity_mode();
771 if (ecc.valid && IS_BUILTIN(CONFIG_DM_VERITY_FEC)) {
773 err = snprintf(buf, FEC_ARG_LENGTH,
774 "%u %s " VERITY_TABLE_OPT_FEC_FORMAT,
775 1 + VERITY_TABLE_OPT_FEC_ARGS,
776 mode == DM_VERITY_MODE_RESTART ?
777 VERITY_TABLE_OPT_RESTART :
778 VERITY_TABLE_OPT_LOGGING,
780 ecc.start / FEC_BLOCK_SIZE, ecc.blocks,
783 err = snprintf(buf, FEC_ARG_LENGTH,
784 "%u " VERITY_TABLE_OPT_FEC_FORMAT,
785 VERITY_TABLE_OPT_FEC_ARGS, target_device,
786 ecc.start / FEC_BLOCK_SIZE, ecc.blocks,
790 err = snprintf(buf, FEC_ARG_LENGTH,
791 "2 " VERITY_TABLE_OPT_IGNZERO " %s",
792 mode == DM_VERITY_MODE_RESTART ?
793 VERITY_TABLE_OPT_RESTART : VERITY_TABLE_OPT_LOGGING);
795 err = snprintf(buf, FEC_ARG_LENGTH, "1 %s",
796 "ignore_zero_blocks");
799 if (err < 0 || err >= FEC_ARG_LENGTH)
804 for (i = VERITY_TABLE_ARGS; i < (VERITY_TABLE_ARGS +
805 VERITY_TABLE_OPT_FEC_ARGS + 2); i++) {
806 verity_table_args[i] = strsep(&buf_ptr, " ");
807 if (verity_table_args[i] == NULL) {
813 err = verity_ctr(ti, no_of_args, verity_table_args);
816 DMERR("android-verity failed to mount as verity target");
819 DMINFO("android-verity mounted as verity target");
823 kfree(metadata->header);
824 kfree(metadata->verity_table);
829 static int __init dm_android_verity_init(void)
834 r = dm_register_target(&android_verity_target);
836 DMERR("register failed %d", r);
838 /* Tracks the status of the last added target */
839 debug_dir = debugfs_create_dir("android_verity", NULL);
841 if (IS_ERR_OR_NULL(debug_dir)) {
842 DMERR("Cannot create android_verity debugfs directory: %ld",
847 file = debugfs_create_bool("target_added", S_IRUGO, debug_dir,
848 (u32 *)&target_added);
850 if (IS_ERR_OR_NULL(file)) {
851 DMERR("Cannot create android_verity debugfs directory: %ld",
853 debugfs_remove_recursive(debug_dir);
857 file = debugfs_create_bool("verity_enabled", S_IRUGO, debug_dir,
858 (u32 *)&verity_enabled);
860 if (IS_ERR_OR_NULL(file)) {
861 DMERR("Cannot create android_verity debugfs directory: %ld",
863 debugfs_remove_recursive(debug_dir);
870 static void __exit dm_android_verity_exit(void)
872 if (!IS_ERR_OR_NULL(debug_dir))
873 debugfs_remove_recursive(debug_dir);
875 dm_unregister_target(&android_verity_target);
878 module_init(dm_android_verity_init);
879 module_exit(dm_android_verity_exit);