2 * Copyright (C) 2015 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <android-base/strings.h>
20 #include "fec_private.h"
22 /* converts a hex nibble into an int */
23 static inline int hextobin(char c)
25 if (c >= '0' && c <= '9') {
27 } else if (c >= 'a' && c <= 'f') {
35 /* converts a hex string `src' of `size' characters to binary and copies the
36 the result into `dst' */
37 static int parse_hex(uint8_t *dst, uint32_t size, const char *src)
43 check(2 * size == strlen(src));
46 h = hextobin(tolower(*src++));
47 l = hextobin(tolower(*src++));
52 *dst++ = (h << 4) | l;
59 /* parses a 64-bit unsigned integer from string `src' into `dst' and if
60 `maxval' is >0, checks that `dst' <= `maxval' */
61 static int parse_uint64(const char *src, uint64_t maxval, uint64_t *dst)
64 unsigned long long int value;
70 value = strtoull(src, &end, 0);
72 if (*src == '\0' || *end != '\0' ||
73 (errno == ERANGE && value == ULLONG_MAX)) {
78 if (maxval && value > maxval) {
83 *dst = (uint64_t)value;
87 /* computes the size of verity hash tree for `file_size' bytes and returns the
88 number of hash tree levels in `verity_levels,' and the number of hashes per
89 level in `level_hashes', if the parameters are non-NULL */
90 uint64_t verity_get_size(uint64_t file_size, uint32_t *verity_levels,
91 uint32_t *level_hashes)
93 /* we assume a known metadata size, 4 KiB block size, and SHA-256 to avoid
94 relying on disk content */
98 uint64_t hashes = file_size / FEC_BLOCKSIZE;
102 level_hashes[level] = hashes;
105 hashes = fec_div_round_up(hashes * SHA256_DIGEST_LENGTH, FEC_BLOCKSIZE);
109 } while (hashes > 1);
112 *verity_levels = level;
115 return total * FEC_BLOCKSIZE;
118 /* computes a SHA-256 salted with `f->verity.salt' from a FEC_BLOCKSIZE byte
119 buffer `block', and copies the hash to `hash' */
120 static inline int verity_hash(fec_handle *f, const uint8_t *block,
127 check(f->verity.salt);
128 SHA256_Update(&ctx, f->verity.salt, f->verity.salt_size);
131 SHA256_Update(&ctx, block, FEC_BLOCKSIZE);
134 SHA256_Final(hash, &ctx);
138 /* computes a verity hash for FEC_BLOCKSIZE bytes from buffer `block' and
139 compares it to the expected value in `expected' */
140 bool verity_check_block(fec_handle *f, const uint8_t *expected,
141 const uint8_t *block)
146 uint8_t hash[SHA256_DIGEST_LENGTH];
148 if (unlikely(verity_hash(f, block, hash) == -1)) {
149 error("failed to hash");
154 return !memcmp(expected, hash, SHA256_DIGEST_LENGTH);
157 /* reads a verity hash and the corresponding data block using error correction,
159 static bool ecc_read_hashes(fec_handle *f, uint64_t hash_offset,
160 uint8_t *hash, uint64_t data_offset, uint8_t *data)
164 if (hash && fec_pread(f, hash, SHA256_DIGEST_LENGTH, hash_offset) !=
165 SHA256_DIGEST_LENGTH) {
166 error("failed to read hash tree: offset %" PRIu64 ": %s", hash_offset,
173 if (fec_pread(f, data, FEC_BLOCKSIZE, data_offset) != FEC_BLOCKSIZE) {
174 error("failed to read hash tree: data_offset %" PRIu64 ": %s",
175 data_offset, strerror(errno));
182 /* reads the verity hash tree, validates it against the root hash in `root',
183 corrects errors if necessary, and copies valid data blocks for later use
184 to `f->verity.hash' */
185 static int verify_tree(fec_handle *f, const uint8_t *root)
187 uint8_t data[FEC_BLOCKSIZE];
188 uint8_t hash[SHA256_DIGEST_LENGTH];
193 verity_info *v = &f->verity;
196 /* calculate the size and the number of levels in the hash tree */
198 verity_get_size(v->data_blocks * FEC_BLOCKSIZE, &levels, NULL);
200 check(v->hash_start < UINT64_MAX - v->hash_size);
201 check(v->hash_start + v->hash_size <= f->data_size);
203 uint64_t hash_offset = v->hash_start;
204 uint64_t data_offset = hash_offset + FEC_BLOCKSIZE;
206 v->hash_data_offset = data_offset;
208 /* validate the root hash */
209 if (!raw_pread(f, data, FEC_BLOCKSIZE, hash_offset) ||
210 !verity_check_block(f, root, data)) {
212 if (!ecc_read_hashes(f, 0, NULL, hash_offset, data) ||
213 !verity_check_block(f, root, data)) {
214 error("root hash invalid");
216 } else if (f->mode & O_RDWR &&
217 !raw_pwrite(f, data, FEC_BLOCKSIZE, hash_offset)) {
218 error("failed to rewrite the root block: %s", strerror(errno));
223 debug("root hash valid");
225 /* calculate the number of hashes on each level */
226 uint32_t hashes[levels];
228 verity_get_size(v->data_blocks * FEC_BLOCKSIZE, NULL, hashes);
230 /* calculate the size and offset for the data hashes */
231 for (uint32_t i = 1; i < levels; ++i) {
232 uint32_t blocks = hashes[levels - i];
233 debug("%u hash blocks on level %u", blocks, levels - i);
235 v->hash_data_offset = data_offset;
236 v->hash_data_blocks = blocks;
238 data_offset += blocks * FEC_BLOCKSIZE;
241 check(v->hash_data_blocks);
242 check(v->hash_data_blocks <= v->hash_size / FEC_BLOCKSIZE);
244 check(v->hash_data_offset);
245 check(v->hash_data_offset <=
246 UINT64_MAX - (v->hash_data_blocks * FEC_BLOCKSIZE));
247 check(v->hash_data_offset < f->data_size);
248 check(v->hash_data_offset + v->hash_data_blocks * FEC_BLOCKSIZE <=
251 /* copy data hashes to memory in case they are corrupted, so we don't
252 have to correct them every time they are needed */
253 std::unique_ptr<uint8_t[]> data_hashes(
254 new (std::nothrow) uint8_t[f->verity.hash_data_blocks * FEC_BLOCKSIZE]);
261 /* validate the rest of the hash tree */
262 data_offset = hash_offset + FEC_BLOCKSIZE;
264 for (uint32_t i = 1; i < levels; ++i) {
265 uint32_t blocks = hashes[levels - i];
267 for (uint32_t j = 0; j < blocks; ++j) {
268 /* ecc reads are very I/O intensive, so read raw hash tree and do
269 error correcting only if it doesn't validate */
270 if (!raw_pread(f, hash, SHA256_DIGEST_LENGTH,
271 hash_offset + j * SHA256_DIGEST_LENGTH) ||
272 !raw_pread(f, data, FEC_BLOCKSIZE,
273 data_offset + j * FEC_BLOCKSIZE)) {
274 error("failed to read hashes: %s", strerror(errno));
278 if (!verity_check_block(f, hash, data)) {
280 if (!ecc_read_hashes(f,
281 hash_offset + j * SHA256_DIGEST_LENGTH, hash,
282 data_offset + j * FEC_BLOCKSIZE, data) ||
283 !verity_check_block(f, hash, data)) {
284 error("invalid hash tree: hash_offset %" PRIu64 ", "
285 "data_offset %" PRIu64 ", block %u",
286 hash_offset, data_offset, j);
290 /* update the corrected blocks to the file if we are in r/w
292 if (f->mode & O_RDWR) {
293 if (!raw_pwrite(f, hash, SHA256_DIGEST_LENGTH,
294 hash_offset + j * SHA256_DIGEST_LENGTH) ||
295 !raw_pwrite(f, data, FEC_BLOCKSIZE,
296 data_offset + j * FEC_BLOCKSIZE)) {
297 error("failed to write hashes: %s", strerror(errno));
303 if (blocks == v->hash_data_blocks) {
304 memcpy(data_hashes.get() + j * FEC_BLOCKSIZE, data,
309 hash_offset = data_offset;
310 data_offset += blocks * FEC_BLOCKSIZE;
320 v->hash = data_hashes.release();
324 /* reads, corrects and parses the verity table, validates parameters, and if
325 `f->flags' does not have `FEC_VERITY_DISABLE' set, calls `verify_tree' to
326 load and validate the hash tree */
327 static int parse_table(fec_handle *f, uint64_t offset, uint32_t size, bool useecc)
330 check(size >= VERITY_MIN_TABLE_SIZE);
331 check(size <= VERITY_MAX_TABLE_SIZE);
333 debug("offset = %" PRIu64 ", size = %u", offset, size);
335 verity_info *v = &f->verity;
336 std::unique_ptr<char[]> table(new (std::nothrow) char[size + 1]);
344 if (!raw_pread(f, table.get(), size, offset)) {
345 error("failed to read verity table: %s", strerror(errno));
348 } else if (fec_pread(f, table.get(), size, offset) != (ssize_t)size) {
349 error("failed to ecc read verity table: %s", strerror(errno));
354 debug("verity table: '%s'", table.get());
357 std::unique_ptr<uint8_t[]> salt;
358 uint8_t root[SHA256_DIGEST_LENGTH];
360 auto tokens = android::base::Split(table.get(), " ");
362 for (const auto& token : tokens) {
364 case 0: /* version */
365 if (token != stringify(VERITY_TABLE_VERSION)) {
366 error("unsupported verity table version: %s", token.c_str());
370 case 3: /* data_block_size */
371 case 4: /* hash_block_size */
372 /* assume 4 KiB block sizes for everything */
373 if (token != stringify(FEC_BLOCKSIZE)) {
374 error("unsupported verity block size: %s", token.c_str());
378 case 5: /* num_data_blocks */
379 if (parse_uint64(token.c_str(), f->data_size / FEC_BLOCKSIZE,
380 &v->data_blocks) == -1) {
381 error("invalid number of verity data blocks: %s",
386 case 6: /* hash_start_block */
387 if (parse_uint64(token.c_str(), f->data_size / FEC_BLOCKSIZE,
388 &v->hash_start) == -1) {
389 error("invalid verity hash start block: %s", token.c_str());
393 v->hash_start *= FEC_BLOCKSIZE;
395 case 7: /* algorithm */
396 if (token != "sha256") {
397 error("unsupported verity hash algorithm: %s", token.c_str());
402 if (parse_hex(root, sizeof(root), token.c_str()) == -1) {
403 error("invalid verity root hash: %s", token.c_str());
408 v->salt_size = token.size();
409 check(v->salt_size % 2 == 0);
412 salt.reset(new (std::nothrow) uint8_t[v->salt_size]);
419 if (parse_hex(salt.get(), v->salt_size, token.c_str()) == -1) {
420 error("invalid verity salt: %s", token.c_str());
429 if (i < VERITY_TABLE_ARGS) {
430 error("not enough arguments in verity table: %d; expected at least "
431 stringify(VERITY_TABLE_ARGS), i);
435 check(v->hash_start < f->data_size);
437 if (v->metadata_start < v->hash_start) {
438 check(v->data_blocks == v->metadata_start / FEC_BLOCKSIZE);
440 check(v->data_blocks == v->hash_start / FEC_BLOCKSIZE);
448 v->salt = salt.release();
455 v->table = table.release();
457 if (!(f->flags & FEC_VERITY_DISABLE)) {
458 if (verify_tree(f, root) == -1) {
464 uint8_t zero_block[FEC_BLOCKSIZE];
465 memset(zero_block, 0, FEC_BLOCKSIZE);
467 if (verity_hash(f, zero_block, v->zero_hash) == -1) {
468 error("failed to hash");
476 /* rewrites verity metadata block using error corrected data in `f->verity' */
477 static int rewrite_metadata(fec_handle *f, uint64_t offset)
480 check(f->data_size > VERITY_METADATA_SIZE);
481 check(offset <= f->data_size - VERITY_METADATA_SIZE);
483 std::unique_ptr<uint8_t[]> metadata(
484 new (std::nothrow) uint8_t[VERITY_METADATA_SIZE]);
491 memset(metadata.get(), 0, VERITY_METADATA_SIZE);
493 verity_info *v = &f->verity;
494 memcpy(metadata.get(), &v->header, sizeof(v->header));
497 size_t len = strlen(v->table);
499 check(sizeof(v->header) + len <= VERITY_METADATA_SIZE);
500 memcpy(metadata.get() + sizeof(v->header), v->table, len);
502 return raw_pwrite(f, metadata.get(), VERITY_METADATA_SIZE, offset);
505 static int validate_header(const fec_handle *f, const verity_header *header,
511 if (header->magic != VERITY_MAGIC &&
512 header->magic != VERITY_MAGIC_DISABLE) {
516 if (header->version != VERITY_VERSION) {
517 error("unsupported verity version %u", header->version);
521 if (header->length < VERITY_MIN_TABLE_SIZE ||
522 header->length > VERITY_MAX_TABLE_SIZE) {
523 error("invalid verity table size: %u; expected ["
524 stringify(VERITY_MIN_TABLE_SIZE) ", "
525 stringify(VERITY_MAX_TABLE_SIZE) ")", header->length);
529 /* signature is skipped, because for our purposes it won't matter from
530 where the data originates; the caller of the library is responsible
531 for signature verification */
533 if (offset > UINT64_MAX - header->length) {
534 error("invalid verity table length: %u", header->length);
536 } else if (offset + header->length >= f->data_size) {
537 error("invalid verity table length: %u", header->length);
544 /* attempts to read verity metadata from `f->fd' position `offset'; if in r/w
545 mode, rewrites the metadata if it had errors */
546 int verity_parse_header(fec_handle *f, uint64_t offset)
549 check(f->data_size > VERITY_METADATA_SIZE);
551 if (offset > f->data_size - VERITY_METADATA_SIZE) {
552 debug("failed to read verity header: offset %" PRIu64 " is too far",
557 verity_info *v = &f->verity;
558 uint64_t errors = f->errors;
560 if (!raw_pread(f, &v->header, sizeof(v->header), offset)) {
561 error("failed to read verity header: %s", strerror(errno));
565 /* use raw data to check for the alternative magic, because it will
566 be error corrected to VERITY_MAGIC otherwise */
567 if (v->header.magic == VERITY_MAGIC_DISABLE) {
568 /* this value is not used by us, but can be used by a caller to
569 decide whether dm-verity should be enabled */
573 if (fec_pread(f, &v->ecc_header, sizeof(v->ecc_header), offset) !=
574 sizeof(v->ecc_header)) {
575 warn("failed to read verity header: %s", strerror(errno));
579 if (validate_header(f, &v->header, offset)) {
580 /* raw verity header is invalid; this could be due to corruption, or
581 due to missing verity metadata */
583 if (validate_header(f, &v->ecc_header, offset)) {
584 return -1; /* either way, we cannot recover */
587 /* report mismatching fields */
588 if (!v->disabled && v->header.magic != v->ecc_header.magic) {
589 warn("corrected verity header magic");
590 v->header.magic = v->ecc_header.magic;
593 if (v->header.version != v->ecc_header.version) {
594 warn("corrected verity header version");
595 v->header.version = v->ecc_header.version;
598 if (v->header.length != v->ecc_header.length) {
599 warn("corrected verity header length");
600 v->header.length = v->ecc_header.length;
603 if (memcmp(v->header.signature, v->ecc_header.signature,
604 sizeof(v->header.signature))) {
605 warn("corrected verity header signature");
606 /* we have no way of knowing which signature is correct, if either
611 v->metadata_start = offset;
613 if (parse_table(f, offset + sizeof(v->header), v->header.length,
615 parse_table(f, offset + sizeof(v->header), v->header.length,
620 /* if we corrected something while parsing metadata and we are in r/w
621 mode, rewrite the corrected metadata */
622 if (f->mode & O_RDWR && f->errors > errors &&
623 rewrite_metadata(f, offset) < 0) {
624 warn("failed to rewrite verity metadata: %s", strerror(errno));
627 if (v->metadata_start < v->hash_start) {
628 f->data_size = v->metadata_start;
630 f->data_size = v->hash_start;
636 int fec_verity_set_status(struct fec_handle *f, bool enabled)
640 if (!(f->mode & O_RDWR)) {
641 error("cannot update verity magic: read-only handle");
646 verity_info *v = &f->verity;
648 if (!v->metadata_start) {
649 error("cannot update verity magic: no metadata found");
654 if (v->disabled == !enabled) {
655 return 0; /* nothing to do */
658 uint32_t magic = enabled ? VERITY_MAGIC : VERITY_MAGIC_DISABLE;
660 if (!raw_pwrite(f, &magic, sizeof(magic), v->metadata_start)) {
661 error("failed to update verity magic to %08x: %s", magic,
666 warn("updated verity magic to %08x (%s)", magic,
667 enabled ? "enabled" : "disabled");
668 v->disabled = !enabled;