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];
47 static char buildvariant[BUILD_VARIANT];
49 static bool target_added;
50 static bool verity_enabled = true;
51 static struct dentry *debug_dir;
52 static int android_verity_ctr(struct dm_target *ti, unsigned argc, char **argv);
54 static struct target_type android_verity_target = {
55 .name = "android-verity",
57 .module = THIS_MODULE,
58 .ctr = android_verity_ctr,
61 .status = verity_status,
62 .prepare_ioctl = verity_prepare_ioctl,
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 int __init verity_buildvariant(char *line)
93 strlcpy(buildvariant, line, sizeof(buildvariant));
97 __setup("buildvariant=", verity_buildvariant);
99 static inline bool default_verity_key_id(void)
101 return veritykeyid[0] != '\0';
104 static inline bool is_eng(void)
106 static const char typeeng[] = "eng";
108 return !strncmp(buildvariant, typeeng, sizeof(typeeng));
111 static inline bool is_userdebug(void)
113 static const char typeuserdebug[] = "userdebug";
115 return !strncmp(buildvariant, typeuserdebug, sizeof(typeuserdebug));
118 static inline bool is_unlocked(void)
120 static const char unlocked[] = "orange";
122 return !strncmp(verifiedbootstate, unlocked, sizeof(unlocked));
125 static int table_extract_mpi_array(struct public_key_signature *pks,
126 const void *data, size_t len)
128 MPI mpi = mpi_read_raw_data(data, len);
131 DMERR("Error while allocating mpi array");
140 static struct public_key_signature *table_make_digest(
143 unsigned long table_len)
145 struct public_key_signature *pks = NULL;
146 struct crypto_shash *tfm;
147 struct shash_desc *desc;
148 size_t digest_size, desc_size;
151 /* Allocate the hashing algorithm we're going to need and find out how
152 * big the hash operational data will be.
154 tfm = crypto_alloc_shash(hash_algo_name[hash], 0, 0);
156 return ERR_CAST(tfm);
158 desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
159 digest_size = crypto_shash_digestsize(tfm);
161 /* We allocate the hash operational data storage on the end of out
162 * context data and the digest output buffer on the end of that.
165 pks = kzalloc(digest_size + sizeof(*pks) + desc_size, GFP_KERNEL);
169 pks->pkey_hash_algo = hash;
170 pks->digest = (u8 *)pks + sizeof(*pks) + desc_size;
171 pks->digest_size = digest_size;
173 desc = (struct shash_desc *)(pks + 1);
175 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
177 ret = crypto_shash_init(desc);
181 ret = crypto_shash_finup(desc, table, table_len, pks->digest);
185 crypto_free_shash(tfm);
190 crypto_free_shash(tfm);
194 static int read_block_dev(struct bio_read *payload, struct block_device *bdev,
195 sector_t offset, int length)
200 payload->number_of_pages = DIV_ROUND_UP(length, PAGE_SIZE);
202 bio = bio_alloc(GFP_KERNEL, payload->number_of_pages);
204 DMERR("Error while allocating bio");
209 bio->bi_iter.bi_sector = offset;
211 payload->page_io = kzalloc(sizeof(struct page *) *
212 payload->number_of_pages, GFP_KERNEL);
213 if (!payload->page_io) {
214 DMERR("page_io array alloc failed");
219 for (i = 0; i < payload->number_of_pages; i++) {
220 payload->page_io[i] = alloc_page(GFP_KERNEL);
221 if (!payload->page_io[i]) {
222 DMERR("alloc_page failed");
226 if (!bio_add_page(bio, payload->page_io[i], PAGE_SIZE, 0)) {
227 DMERR("bio_add_page error");
233 if (!submit_bio_wait(READ, bio))
236 DMERR("bio read failed");
240 for (i = 0; i < payload->number_of_pages; i++)
241 if (payload->page_io[i])
242 __free_page(payload->page_io[i]);
243 kfree(payload->page_io);
249 static inline u64 fec_div_round_up(u64 x, u64 y)
253 return div64_u64_rem(x, y, &remainder) +
254 (remainder > 0 ? 1 : 0);
257 static inline void populate_fec_metadata(struct fec_header *header,
258 struct fec_ecc_metadata *ecc)
260 ecc->blocks = fec_div_round_up(le64_to_cpu(header->inp_size),
262 ecc->roots = le32_to_cpu(header->roots);
263 ecc->start = le64_to_cpu(header->inp_size);
266 static inline int validate_fec_header(struct fec_header *header, u64 offset)
268 /* move offset to make the sanity check work for backup header
270 offset -= offset % FEC_BLOCK_SIZE;
271 if (le32_to_cpu(header->magic) != FEC_MAGIC ||
272 le32_to_cpu(header->version) != FEC_VERSION ||
273 le32_to_cpu(header->size) != sizeof(struct fec_header) ||
274 le32_to_cpu(header->roots) == 0 ||
275 le32_to_cpu(header->roots) >= FEC_RSM)
281 static int extract_fec_header(dev_t dev, struct fec_header *fec,
282 struct fec_ecc_metadata *ecc)
285 struct bio_read payload;
287 struct block_device *bdev;
289 bdev = blkdev_get_by_dev(dev, FMODE_READ, NULL);
291 if (IS_ERR_OR_NULL(bdev)) {
292 DMERR("bdev get error");
293 return PTR_ERR(bdev);
296 device_size = i_size_read(bdev->bd_inode);
298 /* fec metadata size is a power of 2 and PAGE_SIZE
299 * is a power of 2 as well.
301 BUG_ON(FEC_BLOCK_SIZE > PAGE_SIZE);
302 /* 512 byte sector alignment */
303 BUG_ON(((device_size - FEC_BLOCK_SIZE) % (1 << SECTOR_SHIFT)) != 0);
305 err = read_block_dev(&payload, bdev, (device_size -
306 FEC_BLOCK_SIZE) / (1 << SECTOR_SHIFT), FEC_BLOCK_SIZE);
308 DMERR("Error while reading verity metadata");
312 BUG_ON(sizeof(struct fec_header) > PAGE_SIZE);
313 memcpy(fec, page_address(payload.page_io[0]),
317 if (validate_fec_header(fec, device_size - FEC_BLOCK_SIZE)) {
318 /* Try the backup header */
319 memcpy(fec, page_address(payload.page_io[0]) + FEC_BLOCK_SIZE
322 if (validate_fec_header(fec, device_size -
323 sizeof(struct fec_header)))
328 populate_fec_metadata(fec, ecc);
330 for (i = 0; i < payload.number_of_pages; i++)
331 __free_page(payload.page_io[i]);
332 kfree(payload.page_io);
335 blkdev_put(bdev, FMODE_READ);
338 static void find_metadata_offset(struct fec_header *fec,
339 struct block_device *bdev, u64 *metadata_offset)
343 device_size = i_size_read(bdev->bd_inode);
345 if (le32_to_cpu(fec->magic) == FEC_MAGIC)
346 *metadata_offset = le64_to_cpu(fec->inp_size) -
347 VERITY_METADATA_SIZE;
349 *metadata_offset = device_size - VERITY_METADATA_SIZE;
352 static int find_size(dev_t dev, u64 *device_size)
354 struct block_device *bdev;
356 bdev = blkdev_get_by_dev(dev, FMODE_READ, NULL);
357 if (IS_ERR_OR_NULL(bdev)) {
358 DMERR("blkdev_get_by_dev failed");
359 return PTR_ERR(bdev);
362 *device_size = i_size_read(bdev->bd_inode);
363 *device_size >>= SECTOR_SHIFT;
365 DMINFO("blkdev size in sectors: %llu", *device_size);
366 blkdev_put(bdev, FMODE_READ);
370 static int verify_header(struct android_metadata_header *header)
372 int retval = -EINVAL;
374 if (is_userdebug() && le32_to_cpu(header->magic_number) ==
375 VERITY_METADATA_MAGIC_DISABLE)
376 return VERITY_STATE_DISABLE;
378 if (!(le32_to_cpu(header->magic_number) ==
379 VERITY_METADATA_MAGIC_NUMBER) ||
380 (le32_to_cpu(header->magic_number) ==
381 VERITY_METADATA_MAGIC_DISABLE)) {
382 DMERR("Incorrect magic number");
386 if (le32_to_cpu(header->protocol_version) !=
387 VERITY_METADATA_VERSION) {
388 DMERR("Unsupported version %u",
389 le32_to_cpu(header->protocol_version));
396 static int extract_metadata(dev_t dev, struct fec_header *fec,
397 struct android_metadata **metadata,
398 bool *verity_enabled)
400 struct block_device *bdev;
401 struct android_metadata_header *header;
403 u32 table_length, copy_length, offset;
405 struct bio_read payload;
408 bdev = blkdev_get_by_dev(dev, FMODE_READ, NULL);
410 if (IS_ERR_OR_NULL(bdev)) {
411 DMERR("blkdev_get_by_dev failed");
415 find_metadata_offset(fec, bdev, &metadata_offset);
417 /* Verity metadata size is a power of 2 and PAGE_SIZE
418 * is a power of 2 as well.
419 * PAGE_SIZE is also a multiple of 512 bytes.
421 if (VERITY_METADATA_SIZE > PAGE_SIZE)
422 BUG_ON(VERITY_METADATA_SIZE % PAGE_SIZE != 0);
423 /* 512 byte sector alignment */
424 BUG_ON(metadata_offset % (1 << SECTOR_SHIFT) != 0);
426 err = read_block_dev(&payload, bdev, metadata_offset /
427 (1 << SECTOR_SHIFT), VERITY_METADATA_SIZE);
429 DMERR("Error while reading verity metadata");
433 header = kzalloc(sizeof(*header), GFP_KERNEL);
435 DMERR("kzalloc failed for header");
440 memcpy(header, page_address(payload.page_io[0]),
443 DMINFO("bio magic_number:%u protocol_version:%d table_length:%u",
444 le32_to_cpu(header->magic_number),
445 le32_to_cpu(header->protocol_version),
446 le32_to_cpu(header->table_length));
448 err = verify_header(header);
450 if (err == VERITY_STATE_DISABLE) {
451 DMERR("Mounting root with verity disabled");
452 *verity_enabled = false;
453 /* we would still have to read the metadata to figure out
454 * the data blocks size. Or may be could map the entire
455 * partition similar to mounting the device.
457 * Reset error as well as the verity_enabled flag is changed.
463 *metadata = kzalloc(sizeof(**metadata), GFP_KERNEL);
465 DMERR("kzalloc for metadata failed");
470 (*metadata)->header = header;
471 table_length = le32_to_cpu(header->table_length);
473 if (table_length == 0 ||
474 table_length > (VERITY_METADATA_SIZE -
475 sizeof(struct android_metadata_header))) {
476 DMERR("table_length too long");
481 (*metadata)->verity_table = kzalloc(table_length + 1, GFP_KERNEL);
483 if (!(*metadata)->verity_table) {
484 DMERR("kzalloc verity_table failed");
489 if (sizeof(struct android_metadata_header) +
490 table_length <= PAGE_SIZE) {
491 memcpy((*metadata)->verity_table,
492 page_address(payload.page_io[0])
493 + sizeof(struct android_metadata_header),
496 copy_length = PAGE_SIZE -
497 sizeof(struct android_metadata_header);
498 memcpy((*metadata)->verity_table,
499 page_address(payload.page_io[0])
500 + sizeof(struct android_metadata_header),
502 table_length -= copy_length;
503 offset = copy_length;
505 while (table_length != 0) {
506 if (table_length > PAGE_SIZE) {
507 memcpy((*metadata)->verity_table + offset,
508 page_address(payload.page_io[i]),
511 table_length -= PAGE_SIZE;
513 memcpy((*metadata)->verity_table + offset,
514 page_address(payload.page_io[i]),
521 (*metadata)->verity_table[table_length] = '\0';
523 DMINFO("verity_table: %s", (*metadata)->verity_table);
531 for (i = 0; i < payload.number_of_pages; i++)
532 if (payload.page_io[i])
533 __free_page(payload.page_io[i]);
534 kfree(payload.page_io);
536 blkdev_put(bdev, FMODE_READ);
540 /* helper functions to extract properties from dts */
541 static const char *find_dt_value(const char *name)
543 struct device_node *firmware;
546 firmware = of_find_node_by_path("/firmware/android");
549 value = of_get_property(firmware, name, NULL);
550 of_node_put(firmware);
555 static int verity_mode(void)
557 static const char enforcing[] = "enforcing";
558 static const char verified_mode_prop[] = "veritymode";
561 value = find_dt_value(verified_mode_prop);
564 if (!strncmp(value, enforcing, sizeof(enforcing) - 1))
565 return DM_VERITY_MODE_RESTART;
567 return DM_VERITY_MODE_EIO;
570 static int verify_verity_signature(char *key_id,
571 struct android_metadata *metadata)
575 struct public_key_signature *pks = NULL;
576 int retval = -EINVAL;
578 key_ref = keyring_search(make_key_ref(system_trusted_keyring, 1),
579 &key_type_asymmetric, key_id);
581 if (IS_ERR(key_ref)) {
582 DMERR("keyring: key not found");
586 key = key_ref_to_ptr(key_ref);
588 pks = table_make_digest(HASH_ALGO_SHA256,
589 (const void *)metadata->verity_table,
590 le32_to_cpu(metadata->header->table_length));
593 DMERR("hashing failed");
594 retval = PTR_ERR(pks);
599 retval = table_extract_mpi_array(pks, &metadata->header->signature[0],
602 DMERR("Error extracting mpi %d", retval);
606 retval = verify_signature(key, pks);
607 mpi_free(pks->rsa.s);
615 static void handle_error(void)
617 int mode = verity_mode();
618 if (mode == DM_VERITY_MODE_RESTART) {
619 DMERR("triggering restart");
620 kernel_restart("dm-verity device corrupted");
622 DMERR("Mounting verity root failed");
626 static inline bool test_mult_overflow(sector_t a, u32 b)
628 sector_t r = (sector_t)~0ULL;
634 static int add_as_linear_device(struct dm_target *ti, char *dev)
636 /*Move to linear mapping defines*/
637 char *linear_table_args[DM_LINEAR_ARGS] = {dev,
638 DM_LINEAR_TARGET_OFFSET};
641 android_verity_target.dtr = dm_linear_dtr,
642 android_verity_target.map = dm_linear_map,
643 android_verity_target.status = dm_linear_status,
644 android_verity_target.prepare_ioctl = dm_linear_prepare_ioctl,
645 android_verity_target.iterate_devices = dm_linear_iterate_devices,
646 android_verity_target.io_hints = NULL;
648 set_disk_ro(dm_disk(dm_table_get_md(ti->table)), 0);
650 err = dm_linear_ctr(ti, DM_LINEAR_ARGS, linear_table_args);
653 DMINFO("Added android-verity as a linear target");
656 DMERR("Failed to add android-verity as linear target");
661 static int create_linear_device(struct dm_target *ti, dev_t dev,
665 int err = find_size(dev, &device_size);
668 DMERR("error finding bdev size");
673 ti->len = device_size;
674 err = add_as_linear_device(ti, target_device);
679 verity_enabled = false;
685 * <key id> Key id of the public key in the system keyring.
686 * Verity metadata's signature would be verified against
687 * this. If the key id contains spaces, replace them
689 * <block device> The block device for which dm-verity is being setup.
691 static int android_verity_ctr(struct dm_target *ti, unsigned argc, char **argv)
693 dev_t uninitialized_var(dev);
694 struct android_metadata *metadata = NULL;
695 int err = 0, i, mode;
696 char *key_id = NULL, *table_ptr, dummy, *target_device,
697 *verity_table_args[VERITY_TABLE_ARGS + 2 + VERITY_TABLE_OPT_FEC_ARGS];
698 /* One for specifying number of opt args and one for mode */
699 sector_t data_sectors;
701 unsigned int no_of_args = VERITY_TABLE_ARGS + 2 + VERITY_TABLE_OPT_FEC_ARGS;
702 struct fec_header uninitialized_var(fec);
703 struct fec_ecc_metadata uninitialized_var(ecc);
704 char buf[FEC_ARG_LENGTH], *buf_ptr;
705 unsigned long long tmpll;
708 /* Use the default keyid */
709 if (default_verity_key_id())
710 key_id = veritykeyid;
711 else if (!is_eng()) {
712 DMERR("veritykeyid= is not set");
716 } else if (argc == 2)
719 DMERR("Incorrect number of arguments");
724 target_device = argv[0];
726 dev = name_to_dev_t(target_device);
728 DMERR("no dev found for %s", target_device);
734 return create_linear_device(ti, dev, target_device);
736 strreplace(key_id, '#', ' ');
738 DMINFO("key:%s dev:%s", key_id, target_device);
740 if (extract_fec_header(dev, &fec, &ecc)) {
741 DMERR("Error while extracting fec header");
746 err = extract_metadata(dev, &fec, &metadata, &verity_enabled);
749 /* Allow invalid metadata when the device is unlocked */
751 DMWARN("Allow invalid metadata when unlocked");
752 return create_linear_device(ti, dev, target_device);
754 DMERR("Error while extracting metadata");
759 if (verity_enabled) {
760 err = verify_verity_signature(key_id, metadata);
763 DMERR("Signature verification failed");
767 DMINFO("Signature verification success");
770 table_ptr = metadata->verity_table;
772 for (i = 0; i < VERITY_TABLE_ARGS; i++) {
773 verity_table_args[i] = strsep(&table_ptr, " ");
774 if (verity_table_args[i] == NULL)
778 if (i != VERITY_TABLE_ARGS) {
779 DMERR("Verity table not in the expected format");
785 if (sscanf(verity_table_args[5], "%llu%c", &tmpll, &dummy)
787 DMERR("Verity table not in the expected format");
793 if (tmpll > ULONG_MAX) {
794 DMERR("<num_data_blocks> too large. Forgot to turn on CONFIG_LBDAF?");
800 data_sectors = tmpll;
802 if (sscanf(verity_table_args[3], "%u%c", &data_block_size, &dummy)
804 DMERR("Verity table not in the expected format");
810 if (test_mult_overflow(data_sectors, data_block_size >>
812 DMERR("data_sectors too large");
818 data_sectors *= data_block_size >> SECTOR_SHIFT;
819 DMINFO("Data sectors %llu", (unsigned long long)data_sectors);
821 /* update target length */
822 ti->len = data_sectors;
824 /* Setup linear target and free */
825 if (!verity_enabled) {
826 err = add_as_linear_device(ti, target_device);
830 /*substitute data_dev and hash_dev*/
831 verity_table_args[1] = target_device;
832 verity_table_args[2] = target_device;
834 mode = verity_mode();
836 if (ecc.valid && IS_BUILTIN(CONFIG_DM_VERITY_FEC)) {
838 err = snprintf(buf, FEC_ARG_LENGTH,
839 "%u %s " VERITY_TABLE_OPT_FEC_FORMAT,
840 1 + VERITY_TABLE_OPT_FEC_ARGS,
841 mode == DM_VERITY_MODE_RESTART ?
842 VERITY_TABLE_OPT_RESTART :
843 VERITY_TABLE_OPT_LOGGING,
845 ecc.start / FEC_BLOCK_SIZE, ecc.blocks,
848 err = snprintf(buf, FEC_ARG_LENGTH,
849 "%u " VERITY_TABLE_OPT_FEC_FORMAT,
850 VERITY_TABLE_OPT_FEC_ARGS, target_device,
851 ecc.start / FEC_BLOCK_SIZE, ecc.blocks,
855 err = snprintf(buf, FEC_ARG_LENGTH,
856 "2 " VERITY_TABLE_OPT_IGNZERO " %s",
857 mode == DM_VERITY_MODE_RESTART ?
858 VERITY_TABLE_OPT_RESTART : VERITY_TABLE_OPT_LOGGING);
860 err = snprintf(buf, FEC_ARG_LENGTH, "1 %s",
861 "ignore_zero_blocks");
864 if (err < 0 || err >= FEC_ARG_LENGTH)
869 for (i = VERITY_TABLE_ARGS; i < (VERITY_TABLE_ARGS +
870 VERITY_TABLE_OPT_FEC_ARGS + 2); i++) {
871 verity_table_args[i] = strsep(&buf_ptr, " ");
872 if (verity_table_args[i] == NULL) {
878 err = verity_ctr(ti, no_of_args, verity_table_args);
881 DMERR("android-verity failed to mount as verity target");
884 DMINFO("android-verity mounted as verity target");
889 kfree(metadata->header);
890 kfree(metadata->verity_table);
896 static int __init dm_android_verity_init(void)
901 r = dm_register_target(&android_verity_target);
903 DMERR("register failed %d", r);
905 /* Tracks the status of the last added target */
906 debug_dir = debugfs_create_dir("android_verity", NULL);
908 if (IS_ERR_OR_NULL(debug_dir)) {
909 DMERR("Cannot create android_verity debugfs directory: %ld",
914 file = debugfs_create_bool("target_added", S_IRUGO, debug_dir,
917 if (IS_ERR_OR_NULL(file)) {
918 DMERR("Cannot create android_verity debugfs directory: %ld",
920 debugfs_remove_recursive(debug_dir);
924 file = debugfs_create_bool("verity_enabled", S_IRUGO, debug_dir,
927 if (IS_ERR_OR_NULL(file)) {
928 DMERR("Cannot create android_verity debugfs directory: %ld",
930 debugfs_remove_recursive(debug_dir);
937 static void __exit dm_android_verity_exit(void)
939 if (!IS_ERR_OR_NULL(debug_dir))
940 debugfs_remove_recursive(debug_dir);
942 dm_unregister_target(&android_verity_target);
945 module_init(dm_android_verity_init);
946 module_exit(dm_android_verity_exit);