No Description

verifier.cpp 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /*
  2. * Copyright (C) 2008 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 "verifier.h"
  17. #include <errno.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <algorithm>
  22. #include <functional>
  23. #include <memory>
  24. #include <vector>
  25. #include <android-base/logging.h>
  26. #include <openssl/bn.h>
  27. #include <openssl/ecdsa.h>
  28. #include <openssl/obj_mac.h>
  29. #include "asn1_decoder.h"
  30. #include "otautil/print_sha1.h"
  31. static constexpr size_t MiB = 1024 * 1024;
  32. /*
  33. * Simple version of PKCS#7 SignedData extraction. This extracts the
  34. * signature OCTET STRING to be used for signature verification.
  35. *
  36. * For full details, see http://www.ietf.org/rfc/rfc3852.txt
  37. *
  38. * The PKCS#7 structure looks like:
  39. *
  40. * SEQUENCE (ContentInfo)
  41. * OID (ContentType)
  42. * [0] (content)
  43. * SEQUENCE (SignedData)
  44. * INTEGER (version CMSVersion)
  45. * SET (DigestAlgorithmIdentifiers)
  46. * SEQUENCE (EncapsulatedContentInfo)
  47. * [0] (CertificateSet OPTIONAL)
  48. * [1] (RevocationInfoChoices OPTIONAL)
  49. * SET (SignerInfos)
  50. * SEQUENCE (SignerInfo)
  51. * INTEGER (CMSVersion)
  52. * SEQUENCE (SignerIdentifier)
  53. * SEQUENCE (DigestAlgorithmIdentifier)
  54. * SEQUENCE (SignatureAlgorithmIdentifier)
  55. * OCTET STRING (SignatureValue)
  56. */
  57. static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len,
  58. std::vector<uint8_t>* sig_der) {
  59. CHECK(sig_der != nullptr);
  60. sig_der->clear();
  61. asn1_context ctx(pkcs7_der, pkcs7_der_len);
  62. std::unique_ptr<asn1_context> pkcs7_seq(ctx.asn1_sequence_get());
  63. if (pkcs7_seq == nullptr || !pkcs7_seq->asn1_sequence_next()) {
  64. return false;
  65. }
  66. std::unique_ptr<asn1_context> signed_data_app(pkcs7_seq->asn1_constructed_get());
  67. if (signed_data_app == nullptr) {
  68. return false;
  69. }
  70. std::unique_ptr<asn1_context> signed_data_seq(signed_data_app->asn1_sequence_get());
  71. if (signed_data_seq == nullptr ||
  72. !signed_data_seq->asn1_sequence_next() ||
  73. !signed_data_seq->asn1_sequence_next() ||
  74. !signed_data_seq->asn1_sequence_next() ||
  75. !signed_data_seq->asn1_constructed_skip_all()) {
  76. return false;
  77. }
  78. std::unique_ptr<asn1_context> sig_set(signed_data_seq->asn1_set_get());
  79. if (sig_set == nullptr) {
  80. return false;
  81. }
  82. std::unique_ptr<asn1_context> sig_seq(sig_set->asn1_sequence_get());
  83. if (sig_seq == nullptr ||
  84. !sig_seq->asn1_sequence_next() ||
  85. !sig_seq->asn1_sequence_next() ||
  86. !sig_seq->asn1_sequence_next() ||
  87. !sig_seq->asn1_sequence_next()) {
  88. return false;
  89. }
  90. const uint8_t* sig_der_ptr;
  91. size_t sig_der_length;
  92. if (!sig_seq->asn1_octet_string_get(&sig_der_ptr, &sig_der_length)) {
  93. return false;
  94. }
  95. sig_der->resize(sig_der_length);
  96. std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin());
  97. return true;
  98. }
  99. /*
  100. * Looks for an RSA signature embedded in the .ZIP file comment given the path to the zip. Verifies
  101. * that it matches one of the given public keys. A callback function can be optionally provided for
  102. * posting the progress.
  103. *
  104. * Returns VERIFY_SUCCESS or VERIFY_FAILURE (if any error is encountered or no key matches the
  105. * signature).
  106. */
  107. int verify_file(const unsigned char* addr, size_t length, const std::vector<Certificate>& keys,
  108. const std::function<void(float)>& set_progress) {
  109. if (set_progress) {
  110. set_progress(0.0);
  111. }
  112. // An archive with a whole-file signature will end in six bytes:
  113. //
  114. // (2-byte signature start) $ff $ff (2-byte comment size)
  115. //
  116. // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by
  117. // reading this footer, this tells us how far back from the end we have to start reading to find
  118. // the whole comment.
  119. #define FOOTER_SIZE 6
  120. if (length < FOOTER_SIZE) {
  121. LOG(ERROR) << "not big enough to contain footer";
  122. return VERIFY_FAILURE;
  123. }
  124. const unsigned char* footer = addr + length - FOOTER_SIZE;
  125. if (footer[2] != 0xff || footer[3] != 0xff) {
  126. LOG(ERROR) << "footer is wrong";
  127. return VERIFY_FAILURE;
  128. }
  129. size_t comment_size = footer[4] + (footer[5] << 8);
  130. size_t signature_start = footer[0] + (footer[1] << 8);
  131. LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start
  132. << " bytes from end";
  133. if (signature_start > comment_size) {
  134. LOG(ERROR) << "signature start: " << signature_start << " is larger than comment size: "
  135. << comment_size;
  136. return VERIFY_FAILURE;
  137. }
  138. if (signature_start <= FOOTER_SIZE) {
  139. LOG(ERROR) << "Signature start is in the footer";
  140. return VERIFY_FAILURE;
  141. }
  142. #define EOCD_HEADER_SIZE 22
  143. // The end-of-central-directory record is 22 bytes plus any comment length.
  144. size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
  145. if (length < eocd_size) {
  146. LOG(ERROR) << "not big enough to contain EOCD";
  147. return VERIFY_FAILURE;
  148. }
  149. // Determine how much of the file is covered by the signature. This is everything except the
  150. // signature data and length, which includes all of the EOCD except for the comment length field
  151. // (2 bytes) and the comment data.
  152. size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
  153. const unsigned char* eocd = addr + length - eocd_size;
  154. // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06.
  155. if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) {
  156. LOG(ERROR) << "signature length doesn't match EOCD marker";
  157. return VERIFY_FAILURE;
  158. }
  159. for (size_t i = 4; i < eocd_size-3; ++i) {
  160. if (eocd[i] == 0x50 && eocd[i+1] == 0x4b && eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
  161. // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will
  162. // find the later (wrong) one, which could be exploitable. Fail the verification if this
  163. // sequence occurs anywhere after the real one.
  164. LOG(ERROR) << "EOCD marker occurs after start of EOCD";
  165. return VERIFY_FAILURE;
  166. }
  167. }
  168. bool need_sha1 = false;
  169. bool need_sha256 = false;
  170. for (const auto& key : keys) {
  171. switch (key.hash_len) {
  172. case SHA_DIGEST_LENGTH: need_sha1 = true; break;
  173. case SHA256_DIGEST_LENGTH: need_sha256 = true; break;
  174. }
  175. }
  176. SHA_CTX sha1_ctx;
  177. SHA256_CTX sha256_ctx;
  178. SHA1_Init(&sha1_ctx);
  179. SHA256_Init(&sha256_ctx);
  180. double frac = -1.0;
  181. size_t so_far = 0;
  182. while (so_far < signed_len) {
  183. // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a
  184. // 1196MiB full OTA and 60% for an 89MiB incremental OTA.
  185. // http://b/28135231.
  186. size_t size = std::min(signed_len - so_far, 16 * MiB);
  187. if (need_sha1) SHA1_Update(&sha1_ctx, addr + so_far, size);
  188. if (need_sha256) SHA256_Update(&sha256_ctx, addr + so_far, size);
  189. so_far += size;
  190. if (set_progress) {
  191. double f = so_far / (double)signed_len;
  192. if (f > frac + 0.02 || size == so_far) {
  193. set_progress(f);
  194. frac = f;
  195. }
  196. }
  197. }
  198. uint8_t sha1[SHA_DIGEST_LENGTH];
  199. SHA1_Final(sha1, &sha1_ctx);
  200. uint8_t sha256[SHA256_DIGEST_LENGTH];
  201. SHA256_Final(sha256, &sha256_ctx);
  202. const uint8_t* signature = eocd + eocd_size - signature_start;
  203. size_t signature_size = signature_start - FOOTER_SIZE;
  204. LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) << ", length: "
  205. << signature_size << "): " << print_hex(signature, signature_size);
  206. std::vector<uint8_t> sig_der;
  207. if (!read_pkcs7(signature, signature_size, &sig_der)) {
  208. LOG(ERROR) << "Could not find signature DER block";
  209. return VERIFY_FAILURE;
  210. }
  211. // Check to make sure at least one of the keys matches the signature. Since any key can match,
  212. // we need to try each before determining a verification failure has happened.
  213. size_t i = 0;
  214. for (const auto& key : keys) {
  215. const uint8_t* hash;
  216. int hash_nid;
  217. switch (key.hash_len) {
  218. case SHA_DIGEST_LENGTH:
  219. hash = sha1;
  220. hash_nid = NID_sha1;
  221. break;
  222. case SHA256_DIGEST_LENGTH:
  223. hash = sha256;
  224. hash_nid = NID_sha256;
  225. break;
  226. default:
  227. continue;
  228. }
  229. // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends
  230. // after the signature itself.
  231. if (key.key_type == Certificate::KEY_TYPE_RSA) {
  232. if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(),
  233. key.rsa.get())) {
  234. LOG(INFO) << "failed to verify against RSA key " << i;
  235. continue;
  236. }
  237. LOG(INFO) << "whole-file signature verified against RSA key " << i;
  238. return VERIFY_SUCCESS;
  239. } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) {
  240. if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) {
  241. LOG(INFO) << "failed to verify against EC key " << i;
  242. continue;
  243. }
  244. LOG(INFO) << "whole-file signature verified against EC key " << i;
  245. return VERIFY_SUCCESS;
  246. } else {
  247. LOG(INFO) << "Unknown key type " << key.key_type;
  248. }
  249. i++;
  250. }
  251. if (need_sha1) {
  252. LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
  253. }
  254. if (need_sha256) {
  255. LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
  256. }
  257. LOG(ERROR) << "failed to verify whole-file signature";
  258. return VERIFY_FAILURE;
  259. }
  260. std::unique_ptr<RSA, RSADeleter> parse_rsa_key(FILE* file, uint32_t exponent) {
  261. // Read key length in words and n0inv. n0inv is a precomputed montgomery
  262. // parameter derived from the modulus and can be used to speed up
  263. // verification. n0inv is 32 bits wide here, assuming the verification logic
  264. // uses 32 bit arithmetic. However, BoringSSL may use a word size of 64 bits
  265. // internally, in which case we don't have a valid n0inv. Thus, we just
  266. // ignore the montgomery parameters and have BoringSSL recompute them
  267. // internally. If/When the speedup from using the montgomery parameters
  268. // becomes relevant, we can add more sophisticated code here to obtain a
  269. // 64-bit n0inv and initialize the montgomery parameters in the key object.
  270. uint32_t key_len_words = 0;
  271. uint32_t n0inv = 0;
  272. if (fscanf(file, " %i , 0x%x", &key_len_words, &n0inv) != 2) {
  273. return nullptr;
  274. }
  275. if (key_len_words > 8192 / 32) {
  276. LOG(ERROR) << "key length (" << key_len_words << ") too large";
  277. return nullptr;
  278. }
  279. // Read the modulus.
  280. std::unique_ptr<uint32_t[]> modulus(new uint32_t[key_len_words]);
  281. if (fscanf(file, " , { %u", &modulus[0]) != 1) {
  282. return nullptr;
  283. }
  284. for (uint32_t i = 1; i < key_len_words; ++i) {
  285. if (fscanf(file, " , %u", &modulus[i]) != 1) {
  286. return nullptr;
  287. }
  288. }
  289. // Cconvert from little-endian array of little-endian words to big-endian
  290. // byte array suitable as input for BN_bin2bn.
  291. std::reverse((uint8_t*)modulus.get(),
  292. (uint8_t*)(modulus.get() + key_len_words));
  293. // The next sequence of values is the montgomery parameter R^2. Since we
  294. // generally don't have a valid |n0inv|, we ignore this (see comment above).
  295. uint32_t rr_value;
  296. if (fscanf(file, " } , { %u", &rr_value) != 1) {
  297. return nullptr;
  298. }
  299. for (uint32_t i = 1; i < key_len_words; ++i) {
  300. if (fscanf(file, " , %u", &rr_value) != 1) {
  301. return nullptr;
  302. }
  303. }
  304. if (fscanf(file, " } } ") != 0) {
  305. return nullptr;
  306. }
  307. // Initialize the key.
  308. std::unique_ptr<RSA, RSADeleter> key(RSA_new());
  309. if (!key) {
  310. return nullptr;
  311. }
  312. key->n = BN_bin2bn((uint8_t*)modulus.get(),
  313. key_len_words * sizeof(uint32_t), NULL);
  314. if (!key->n) {
  315. return nullptr;
  316. }
  317. key->e = BN_new();
  318. if (!key->e || !BN_set_word(key->e, exponent)) {
  319. return nullptr;
  320. }
  321. return key;
  322. }
  323. struct BNDeleter {
  324. void operator()(BIGNUM* bn) const {
  325. BN_free(bn);
  326. }
  327. };
  328. std::unique_ptr<EC_KEY, ECKEYDeleter> parse_ec_key(FILE* file) {
  329. uint32_t key_len_bytes = 0;
  330. if (fscanf(file, " %i", &key_len_bytes) != 1) {
  331. return nullptr;
  332. }
  333. std::unique_ptr<EC_GROUP, void (*)(EC_GROUP*)> group(
  334. EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1), EC_GROUP_free);
  335. if (!group) {
  336. return nullptr;
  337. }
  338. // Verify that |key_len| matches the group order.
  339. if (key_len_bytes != BN_num_bytes(EC_GROUP_get0_order(group.get()))) {
  340. return nullptr;
  341. }
  342. // Read the public key coordinates. Note that the byte order in the file is
  343. // little-endian, so we convert to big-endian here.
  344. std::unique_ptr<uint8_t[]> bytes(new uint8_t[key_len_bytes]);
  345. std::unique_ptr<BIGNUM, BNDeleter> point[2];
  346. for (int i = 0; i < 2; ++i) {
  347. unsigned int byte = 0;
  348. if (fscanf(file, " , { %u", &byte) != 1) {
  349. return nullptr;
  350. }
  351. bytes[key_len_bytes - 1] = byte;
  352. for (size_t i = 1; i < key_len_bytes; ++i) {
  353. if (fscanf(file, " , %u", &byte) != 1) {
  354. return nullptr;
  355. }
  356. bytes[key_len_bytes - i - 1] = byte;
  357. }
  358. point[i].reset(BN_bin2bn(bytes.get(), key_len_bytes, nullptr));
  359. if (!point[i]) {
  360. return nullptr;
  361. }
  362. if (fscanf(file, " }") != 0) {
  363. return nullptr;
  364. }
  365. }
  366. if (fscanf(file, " } ") != 0) {
  367. return nullptr;
  368. }
  369. // Create and initialize the key.
  370. std::unique_ptr<EC_KEY, ECKEYDeleter> key(EC_KEY_new());
  371. if (!key || !EC_KEY_set_group(key.get(), group.get()) ||
  372. !EC_KEY_set_public_key_affine_coordinates(key.get(), point[0].get(),
  373. point[1].get())) {
  374. return nullptr;
  375. }
  376. return key;
  377. }
  378. // Reads a file containing one or more public keys as produced by
  379. // DumpPublicKey: this is an RSAPublicKey struct as it would appear
  380. // as a C source literal, eg:
  381. //
  382. // "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
  383. //
  384. // For key versions newer than the original 2048-bit e=3 keys
  385. // supported by Android, the string is preceded by a version
  386. // identifier, eg:
  387. //
  388. // "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
  389. //
  390. // (Note that the braces and commas in this example are actual
  391. // characters the parser expects to find in the file; the ellipses
  392. // indicate more numbers omitted from this example.)
  393. //
  394. // The file may contain multiple keys in this format, separated by
  395. // commas. The last key must not be followed by a comma.
  396. //
  397. // A Certificate is a pair of an RSAPublicKey and a particular hash
  398. // (we support SHA-1 and SHA-256; we store the hash length to signify
  399. // which is being used). The hash used is implied by the version number.
  400. //
  401. // 1: 2048-bit RSA key with e=3 and SHA-1 hash
  402. // 2: 2048-bit RSA key with e=65537 and SHA-1 hash
  403. // 3: 2048-bit RSA key with e=3 and SHA-256 hash
  404. // 4: 2048-bit RSA key with e=65537 and SHA-256 hash
  405. // 5: 256-bit EC key using the NIST P-256 curve parameters and SHA-256 hash
  406. //
  407. // Returns true on success, and appends the found keys (at least one) to certs.
  408. // Otherwise returns false if the file failed to parse, or if it contains zero
  409. // keys. The contents in certs would be unspecified on failure.
  410. bool load_keys(const char* filename, std::vector<Certificate>& certs) {
  411. std::unique_ptr<FILE, decltype(&fclose)> f(fopen(filename, "re"), fclose);
  412. if (!f) {
  413. PLOG(ERROR) << "error opening " << filename;
  414. return false;
  415. }
  416. while (true) {
  417. certs.emplace_back(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
  418. Certificate& cert = certs.back();
  419. uint32_t exponent = 0;
  420. char start_char;
  421. if (fscanf(f.get(), " %c", &start_char) != 1) return false;
  422. if (start_char == '{') {
  423. // a version 1 key has no version specifier.
  424. cert.key_type = Certificate::KEY_TYPE_RSA;
  425. exponent = 3;
  426. cert.hash_len = SHA_DIGEST_LENGTH;
  427. } else if (start_char == 'v') {
  428. int version;
  429. if (fscanf(f.get(), "%d {", &version) != 1) return false;
  430. switch (version) {
  431. case 2:
  432. cert.key_type = Certificate::KEY_TYPE_RSA;
  433. exponent = 65537;
  434. cert.hash_len = SHA_DIGEST_LENGTH;
  435. break;
  436. case 3:
  437. cert.key_type = Certificate::KEY_TYPE_RSA;
  438. exponent = 3;
  439. cert.hash_len = SHA256_DIGEST_LENGTH;
  440. break;
  441. case 4:
  442. cert.key_type = Certificate::KEY_TYPE_RSA;
  443. exponent = 65537;
  444. cert.hash_len = SHA256_DIGEST_LENGTH;
  445. break;
  446. case 5:
  447. cert.key_type = Certificate::KEY_TYPE_EC;
  448. cert.hash_len = SHA256_DIGEST_LENGTH;
  449. break;
  450. default:
  451. return false;
  452. }
  453. }
  454. if (cert.key_type == Certificate::KEY_TYPE_RSA) {
  455. cert.rsa = parse_rsa_key(f.get(), exponent);
  456. if (!cert.rsa) {
  457. return false;
  458. }
  459. LOG(INFO) << "read key e=" << exponent << " hash=" << cert.hash_len;
  460. } else if (cert.key_type == Certificate::KEY_TYPE_EC) {
  461. cert.ec = parse_ec_key(f.get());
  462. if (!cert.ec) {
  463. return false;
  464. }
  465. } else {
  466. LOG(ERROR) << "Unknown key type " << cert.key_type;
  467. return false;
  468. }
  469. // if the line ends in a comma, this file has more keys.
  470. int ch = fgetc(f.get());
  471. if (ch == ',') {
  472. // more keys to come.
  473. continue;
  474. } else if (ch == EOF) {
  475. break;
  476. } else {
  477. LOG(ERROR) << "unexpected character between keys";
  478. return false;
  479. }
  480. }
  481. return true;
  482. }