fec_verity.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /*
  2. * Copyright (C) 2015 The Android Open Source Project
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. */
  16. #include <ctype.h>
  17. #include <stdlib.h>
  18. #include <android-base/strings.h>
  19. #include "fec_private.h"
  20. /* converts a hex nibble into an int */
  21. static inline int hextobin(char c)
  22. {
  23. if (c >= '0' && c <= '9') {
  24. return c - '0';
  25. } else if (c >= 'a' && c <= 'f') {
  26. return c - 'a' + 10;
  27. } else {
  28. errno = EINVAL;
  29. return -1;
  30. }
  31. }
  32. /* converts a hex string `src' of `size' characters to binary and copies the
  33. the result into `dst' */
  34. static int parse_hex(uint8_t *dst, uint32_t size, const char *src)
  35. {
  36. int l, h;
  37. check(dst);
  38. check(src);
  39. check(2 * size == strlen(src));
  40. while (size) {
  41. h = hextobin(tolower(*src++));
  42. l = hextobin(tolower(*src++));
  43. check(l >= 0);
  44. check(h >= 0);
  45. *dst++ = (h << 4) | l;
  46. --size;
  47. }
  48. return 0;
  49. }
  50. /* parses a 64-bit unsigned integer from string `src' into `dst' and if
  51. `maxval' is >0, checks that `dst' <= `maxval' */
  52. static int parse_uint64(const char *src, uint64_t maxval, uint64_t *dst)
  53. {
  54. char *end;
  55. unsigned long long int value;
  56. check(src);
  57. check(dst);
  58. errno = 0;
  59. value = strtoull(src, &end, 0);
  60. if (*src == '\0' || *end != '\0' ||
  61. (errno == ERANGE && value == ULLONG_MAX)) {
  62. errno = EINVAL;
  63. return -1;
  64. }
  65. if (maxval && value > maxval) {
  66. errno = EINVAL;
  67. return -1;
  68. }
  69. *dst = (uint64_t)value;
  70. return 0;
  71. }
  72. /* computes the size of verity hash tree for `file_size' bytes and returns the
  73. number of hash tree levels in `verity_levels,' and the number of hashes per
  74. level in `level_hashes', if the parameters are non-NULL */
  75. uint64_t verity_get_size(uint64_t file_size, uint32_t *verity_levels,
  76. uint32_t *level_hashes)
  77. {
  78. /* we assume a known metadata size, 4 KiB block size, and SHA-256 to avoid
  79. relying on disk content */
  80. uint32_t level = 0;
  81. uint64_t total = 0;
  82. uint64_t hashes = file_size / FEC_BLOCKSIZE;
  83. do {
  84. if (level_hashes) {
  85. level_hashes[level] = hashes;
  86. }
  87. hashes = fec_div_round_up(hashes * SHA256_DIGEST_LENGTH, FEC_BLOCKSIZE);
  88. total += hashes;
  89. ++level;
  90. } while (hashes > 1);
  91. if (verity_levels) {
  92. *verity_levels = level;
  93. }
  94. return total * FEC_BLOCKSIZE;
  95. }
  96. /* computes a SHA-256 salted with `f->verity.salt' from a FEC_BLOCKSIZE byte
  97. buffer `block', and copies the hash to `hash' */
  98. static inline int verity_hash(fec_handle *f, const uint8_t *block,
  99. uint8_t *hash)
  100. {
  101. SHA256_CTX ctx;
  102. SHA256_Init(&ctx);
  103. check(f);
  104. check(f->verity.salt);
  105. SHA256_Update(&ctx, f->verity.salt, f->verity.salt_size);
  106. check(block);
  107. SHA256_Update(&ctx, block, FEC_BLOCKSIZE);
  108. check(hash);
  109. SHA256_Final(hash, &ctx);
  110. return 0;
  111. }
  112. /* computes a verity hash for FEC_BLOCKSIZE bytes from buffer `block' and
  113. compares it to the expected value in `expected' */
  114. bool verity_check_block(fec_handle *f, const uint8_t *expected,
  115. const uint8_t *block)
  116. {
  117. check(f);
  118. check(block);
  119. uint8_t hash[SHA256_DIGEST_LENGTH];
  120. if (unlikely(verity_hash(f, block, hash) == -1)) {
  121. error("failed to hash");
  122. return false;
  123. }
  124. check(expected);
  125. return !memcmp(expected, hash, SHA256_DIGEST_LENGTH);
  126. }
  127. /* reads a verity hash and the corresponding data block using error correction,
  128. if available */
  129. static bool ecc_read_hashes(fec_handle *f, uint64_t hash_offset,
  130. uint8_t *hash, uint64_t data_offset, uint8_t *data)
  131. {
  132. check(f);
  133. if (hash && fec_pread(f, hash, SHA256_DIGEST_LENGTH, hash_offset) !=
  134. SHA256_DIGEST_LENGTH) {
  135. error("failed to read hash tree: offset %" PRIu64 ": %s", hash_offset,
  136. strerror(errno));
  137. return false;
  138. }
  139. check(data);
  140. if (fec_pread(f, data, FEC_BLOCKSIZE, data_offset) != FEC_BLOCKSIZE) {
  141. error("failed to read hash tree: data_offset %" PRIu64 ": %s",
  142. data_offset, strerror(errno));
  143. return false;
  144. }
  145. return true;
  146. }
  147. /* reads the verity hash tree, validates it against the root hash in `root',
  148. corrects errors if necessary, and copies valid data blocks for later use
  149. to `f->verity.hash' */
  150. static int verify_tree(fec_handle *f, const uint8_t *root)
  151. {
  152. uint8_t data[FEC_BLOCKSIZE];
  153. uint8_t hash[SHA256_DIGEST_LENGTH];
  154. check(f);
  155. check(root);
  156. verity_info *v = &f->verity;
  157. uint32_t levels = 0;
  158. /* calculate the size and the number of levels in the hash tree */
  159. v->hash_size =
  160. verity_get_size(v->data_blocks * FEC_BLOCKSIZE, &levels, NULL);
  161. check(v->hash_start < UINT64_MAX - v->hash_size);
  162. check(v->hash_start + v->hash_size <= f->data_size);
  163. uint64_t hash_offset = v->hash_start;
  164. uint64_t data_offset = hash_offset + FEC_BLOCKSIZE;
  165. v->hash_data_offset = data_offset;
  166. /* validate the root hash */
  167. if (!raw_pread(f, data, FEC_BLOCKSIZE, hash_offset) ||
  168. !verity_check_block(f, root, data)) {
  169. /* try to correct */
  170. if (!ecc_read_hashes(f, 0, NULL, hash_offset, data) ||
  171. !verity_check_block(f, root, data)) {
  172. error("root hash invalid");
  173. return -1;
  174. } else if (f->mode & O_RDWR &&
  175. !raw_pwrite(f, data, FEC_BLOCKSIZE, hash_offset)) {
  176. error("failed to rewrite the root block: %s", strerror(errno));
  177. return -1;
  178. }
  179. }
  180. debug("root hash valid");
  181. /* calculate the number of hashes on each level */
  182. uint32_t hashes[levels];
  183. verity_get_size(v->data_blocks * FEC_BLOCKSIZE, NULL, hashes);
  184. /* calculate the size and offset for the data hashes */
  185. for (uint32_t i = 1; i < levels; ++i) {
  186. uint32_t blocks = hashes[levels - i];
  187. debug("%u hash blocks on level %u", blocks, levels - i);
  188. v->hash_data_offset = data_offset;
  189. v->hash_data_blocks = blocks;
  190. data_offset += blocks * FEC_BLOCKSIZE;
  191. }
  192. check(v->hash_data_blocks);
  193. check(v->hash_data_blocks <= v->hash_size / FEC_BLOCKSIZE);
  194. check(v->hash_data_offset);
  195. check(v->hash_data_offset <=
  196. UINT64_MAX - (v->hash_data_blocks * FEC_BLOCKSIZE));
  197. check(v->hash_data_offset < f->data_size);
  198. check(v->hash_data_offset + v->hash_data_blocks * FEC_BLOCKSIZE <=
  199. f->data_size);
  200. /* copy data hashes to memory in case they are corrupted, so we don't
  201. have to correct them every time they are needed */
  202. std::unique_ptr<uint8_t[]> data_hashes(
  203. new (std::nothrow) uint8_t[f->verity.hash_data_blocks * FEC_BLOCKSIZE]);
  204. if (!data_hashes) {
  205. errno = ENOMEM;
  206. return -1;
  207. }
  208. /* validate the rest of the hash tree */
  209. data_offset = hash_offset + FEC_BLOCKSIZE;
  210. for (uint32_t i = 1; i < levels; ++i) {
  211. uint32_t blocks = hashes[levels - i];
  212. for (uint32_t j = 0; j < blocks; ++j) {
  213. /* ecc reads are very I/O intensive, so read raw hash tree and do
  214. error correcting only if it doesn't validate */
  215. if (!raw_pread(f, hash, SHA256_DIGEST_LENGTH,
  216. hash_offset + j * SHA256_DIGEST_LENGTH) ||
  217. !raw_pread(f, data, FEC_BLOCKSIZE,
  218. data_offset + j * FEC_BLOCKSIZE)) {
  219. error("failed to read hashes: %s", strerror(errno));
  220. return -1;
  221. }
  222. if (!verity_check_block(f, hash, data)) {
  223. /* try to correct */
  224. if (!ecc_read_hashes(f,
  225. hash_offset + j * SHA256_DIGEST_LENGTH, hash,
  226. data_offset + j * FEC_BLOCKSIZE, data) ||
  227. !verity_check_block(f, hash, data)) {
  228. error("invalid hash tree: hash_offset %" PRIu64 ", "
  229. "data_offset %" PRIu64 ", block %u",
  230. hash_offset, data_offset, j);
  231. return -1;
  232. }
  233. /* update the corrected blocks to the file if we are in r/w
  234. mode */
  235. if (f->mode & O_RDWR) {
  236. if (!raw_pwrite(f, hash, SHA256_DIGEST_LENGTH,
  237. hash_offset + j * SHA256_DIGEST_LENGTH) ||
  238. !raw_pwrite(f, data, FEC_BLOCKSIZE,
  239. data_offset + j * FEC_BLOCKSIZE)) {
  240. error("failed to write hashes: %s", strerror(errno));
  241. return -1;
  242. }
  243. }
  244. }
  245. if (blocks == v->hash_data_blocks) {
  246. memcpy(data_hashes.get() + j * FEC_BLOCKSIZE, data,
  247. FEC_BLOCKSIZE);
  248. }
  249. }
  250. hash_offset = data_offset;
  251. data_offset += blocks * FEC_BLOCKSIZE;
  252. }
  253. debug("valid");
  254. if (v->hash) {
  255. delete[] v->hash;
  256. v->hash = NULL;
  257. }
  258. v->hash = data_hashes.release();
  259. return 0;
  260. }
  261. /* reads, corrects and parses the verity table, validates parameters, and if
  262. `f->flags' does not have `FEC_VERITY_DISABLE' set, calls `verify_tree' to
  263. load and validate the hash tree */
  264. static int parse_table(fec_handle *f, uint64_t offset, uint32_t size, bool useecc)
  265. {
  266. check(f);
  267. check(size >= VERITY_MIN_TABLE_SIZE);
  268. check(size <= VERITY_MAX_TABLE_SIZE);
  269. debug("offset = %" PRIu64 ", size = %u", offset, size);
  270. verity_info *v = &f->verity;
  271. std::unique_ptr<char[]> table(new (std::nothrow) char[size + 1]);
  272. if (!table) {
  273. errno = ENOMEM;
  274. return -1;
  275. }
  276. if (!useecc) {
  277. if (!raw_pread(f, table.get(), size, offset)) {
  278. error("failed to read verity table: %s", strerror(errno));
  279. return -1;
  280. }
  281. } else if (fec_pread(f, table.get(), size, offset) != (ssize_t)size) {
  282. error("failed to ecc read verity table: %s", strerror(errno));
  283. return -1;
  284. }
  285. table[size] = '\0';
  286. debug("verity table: '%s'", table.get());
  287. int i = 0;
  288. std::unique_ptr<uint8_t[]> salt;
  289. uint8_t root[SHA256_DIGEST_LENGTH];
  290. auto tokens = android::base::Split(table.get(), " ");
  291. for (const auto& token : tokens) {
  292. switch (i++) {
  293. case 0: /* version */
  294. if (token != stringify(VERITY_TABLE_VERSION)) {
  295. error("unsupported verity table version: %s", token.c_str());
  296. return -1;
  297. }
  298. break;
  299. case 3: /* data_block_size */
  300. case 4: /* hash_block_size */
  301. /* assume 4 KiB block sizes for everything */
  302. if (token != stringify(FEC_BLOCKSIZE)) {
  303. error("unsupported verity block size: %s", token.c_str());
  304. return -1;
  305. }
  306. break;
  307. case 5: /* num_data_blocks */
  308. if (parse_uint64(token.c_str(), f->data_size / FEC_BLOCKSIZE,
  309. &v->data_blocks) == -1) {
  310. error("invalid number of verity data blocks: %s",
  311. token.c_str());
  312. return -1;
  313. }
  314. break;
  315. case 6: /* hash_start_block */
  316. if (parse_uint64(token.c_str(), f->data_size / FEC_BLOCKSIZE,
  317. &v->hash_start) == -1) {
  318. error("invalid verity hash start block: %s", token.c_str());
  319. return -1;
  320. }
  321. v->hash_start *= FEC_BLOCKSIZE;
  322. break;
  323. case 7: /* algorithm */
  324. if (token != "sha256") {
  325. error("unsupported verity hash algorithm: %s", token.c_str());
  326. return -1;
  327. }
  328. break;
  329. case 8: /* digest */
  330. if (parse_hex(root, sizeof(root), token.c_str()) == -1) {
  331. error("invalid verity root hash: %s", token.c_str());
  332. return -1;
  333. }
  334. break;
  335. case 9: /* salt */
  336. v->salt_size = token.size();
  337. check(v->salt_size % 2 == 0);
  338. v->salt_size /= 2;
  339. salt.reset(new (std::nothrow) uint8_t[v->salt_size]);
  340. if (!salt) {
  341. errno = ENOMEM;
  342. return -1;
  343. }
  344. if (parse_hex(salt.get(), v->salt_size, token.c_str()) == -1) {
  345. error("invalid verity salt: %s", token.c_str());
  346. return -1;
  347. }
  348. break;
  349. default:
  350. break;
  351. }
  352. }
  353. if (i < VERITY_TABLE_ARGS) {
  354. error("not enough arguments in verity table: %d; expected at least "
  355. stringify(VERITY_TABLE_ARGS), i);
  356. return -1;
  357. }
  358. check(v->hash_start < f->data_size);
  359. if (v->metadata_start < v->hash_start) {
  360. check(v->data_blocks == v->metadata_start / FEC_BLOCKSIZE);
  361. } else {
  362. check(v->data_blocks == v->hash_start / FEC_BLOCKSIZE);
  363. }
  364. if (v->salt) {
  365. delete[] v->salt;
  366. v->salt = NULL;
  367. }
  368. v->salt = salt.release();
  369. if (v->table) {
  370. delete[] v->table;
  371. v->table = NULL;
  372. }
  373. v->table = table.release();
  374. if (!(f->flags & FEC_VERITY_DISABLE)) {
  375. if (verify_tree(f, root) == -1) {
  376. return -1;
  377. }
  378. check(v->hash);
  379. uint8_t zero_block[FEC_BLOCKSIZE];
  380. memset(zero_block, 0, FEC_BLOCKSIZE);
  381. if (verity_hash(f, zero_block, v->zero_hash) == -1) {
  382. error("failed to hash");
  383. return -1;
  384. }
  385. }
  386. return 0;
  387. }
  388. /* rewrites verity metadata block using error corrected data in `f->verity' */
  389. static int rewrite_metadata(fec_handle *f, uint64_t offset)
  390. {
  391. check(f);
  392. check(f->data_size > VERITY_METADATA_SIZE);
  393. check(offset <= f->data_size - VERITY_METADATA_SIZE);
  394. std::unique_ptr<uint8_t[]> metadata(
  395. new (std::nothrow) uint8_t[VERITY_METADATA_SIZE]);
  396. if (!metadata) {
  397. errno = ENOMEM;
  398. return -1;
  399. }
  400. memset(metadata.get(), 0, VERITY_METADATA_SIZE);
  401. verity_info *v = &f->verity;
  402. memcpy(metadata.get(), &v->header, sizeof(v->header));
  403. check(v->table);
  404. size_t len = strlen(v->table);
  405. check(sizeof(v->header) + len <= VERITY_METADATA_SIZE);
  406. memcpy(metadata.get() + sizeof(v->header), v->table, len);
  407. return raw_pwrite(f, metadata.get(), VERITY_METADATA_SIZE, offset);
  408. }
  409. static int validate_header(const fec_handle *f, const verity_header *header,
  410. uint64_t offset)
  411. {
  412. check(f);
  413. check(header);
  414. if (header->magic != VERITY_MAGIC &&
  415. header->magic != VERITY_MAGIC_DISABLE) {
  416. return -1;
  417. }
  418. if (header->version != VERITY_VERSION) {
  419. error("unsupported verity version %u", header->version);
  420. return -1;
  421. }
  422. if (header->length < VERITY_MIN_TABLE_SIZE ||
  423. header->length > VERITY_MAX_TABLE_SIZE) {
  424. error("invalid verity table size: %u; expected ["
  425. stringify(VERITY_MIN_TABLE_SIZE) ", "
  426. stringify(VERITY_MAX_TABLE_SIZE) ")", header->length);
  427. return -1;
  428. }
  429. /* signature is skipped, because for our purposes it won't matter from
  430. where the data originates; the caller of the library is responsible
  431. for signature verification */
  432. if (offset > UINT64_MAX - header->length) {
  433. error("invalid verity table length: %u", header->length);
  434. return -1;
  435. } else if (offset + header->length >= f->data_size) {
  436. error("invalid verity table length: %u", header->length);
  437. return -1;
  438. }
  439. return 0;
  440. }
  441. /* attempts to read verity metadata from `f->fd' position `offset'; if in r/w
  442. mode, rewrites the metadata if it had errors */
  443. int verity_parse_header(fec_handle *f, uint64_t offset)
  444. {
  445. check(f);
  446. check(f->data_size > VERITY_METADATA_SIZE);
  447. if (offset > f->data_size - VERITY_METADATA_SIZE) {
  448. debug("failed to read verity header: offset %" PRIu64 " is too far",
  449. offset);
  450. return -1;
  451. }
  452. verity_info *v = &f->verity;
  453. uint64_t errors = f->errors;
  454. if (!raw_pread(f, &v->header, sizeof(v->header), offset)) {
  455. error("failed to read verity header: %s", strerror(errno));
  456. return -1;
  457. }
  458. /* use raw data to check for the alternative magic, because it will
  459. be error corrected to VERITY_MAGIC otherwise */
  460. if (v->header.magic == VERITY_MAGIC_DISABLE) {
  461. /* this value is not used by us, but can be used by a caller to
  462. decide whether dm-verity should be enabled */
  463. v->disabled = true;
  464. }
  465. if (fec_pread(f, &v->ecc_header, sizeof(v->ecc_header), offset) !=
  466. sizeof(v->ecc_header)) {
  467. warn("failed to read verity header: %s", strerror(errno));
  468. return -1;
  469. }
  470. if (validate_header(f, &v->header, offset)) {
  471. /* raw verity header is invalid; this could be due to corruption, or
  472. due to missing verity metadata */
  473. if (validate_header(f, &v->ecc_header, offset)) {
  474. return -1; /* either way, we cannot recover */
  475. }
  476. /* report mismatching fields */
  477. if (!v->disabled && v->header.magic != v->ecc_header.magic) {
  478. warn("corrected verity header magic");
  479. v->header.magic = v->ecc_header.magic;
  480. }
  481. if (v->header.version != v->ecc_header.version) {
  482. warn("corrected verity header version");
  483. v->header.version = v->ecc_header.version;
  484. }
  485. if (v->header.length != v->ecc_header.length) {
  486. warn("corrected verity header length");
  487. v->header.length = v->ecc_header.length;
  488. }
  489. if (memcmp(v->header.signature, v->ecc_header.signature,
  490. sizeof(v->header.signature))) {
  491. warn("corrected verity header signature");
  492. /* we have no way of knowing which signature is correct, if either
  493. of them is */
  494. }
  495. }
  496. v->metadata_start = offset;
  497. if (parse_table(f, offset + sizeof(v->header), v->header.length,
  498. false) == -1 &&
  499. parse_table(f, offset + sizeof(v->header), v->header.length,
  500. true) == -1) {
  501. return -1;
  502. }
  503. /* if we corrected something while parsing metadata and we are in r/w
  504. mode, rewrite the corrected metadata */
  505. if (f->mode & O_RDWR && f->errors > errors &&
  506. rewrite_metadata(f, offset) < 0) {
  507. warn("failed to rewrite verity metadata: %s", strerror(errno));
  508. }
  509. if (v->metadata_start < v->hash_start) {
  510. f->data_size = v->metadata_start;
  511. } else {
  512. f->data_size = v->hash_start;
  513. }
  514. return 0;
  515. }
  516. int fec_verity_set_status(struct fec_handle *f, bool enabled)
  517. {
  518. check(f);
  519. if (!(f->mode & O_RDWR)) {
  520. error("cannot update verity magic: read-only handle");
  521. errno = EBADF;
  522. return -1;
  523. }
  524. verity_info *v = &f->verity;
  525. if (!v->metadata_start) {
  526. error("cannot update verity magic: no metadata found");
  527. errno = EINVAL;
  528. return -1;
  529. }
  530. if (v->disabled == !enabled) {
  531. return 0; /* nothing to do */
  532. }
  533. uint32_t magic = enabled ? VERITY_MAGIC : VERITY_MAGIC_DISABLE;
  534. if (!raw_pwrite(f, &magic, sizeof(magic), v->metadata_start)) {
  535. error("failed to update verity magic to %08x: %s", magic,
  536. strerror(errno));
  537. return -1;
  538. }
  539. warn("updated verity magic to %08x (%s)", magic,
  540. enabled ? "enabled" : "disabled");
  541. v->disabled = !enabled;
  542. return 0;
  543. }