blob: 2101dcb417c4e024036513a06a61c225c5b0542f [file] [log] [blame]
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001/*
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
Tao Baoac9d94d2016-11-03 11:37:15 -070017#include "verifier.h"
18
Doug Zongker54e2e862009-08-17 13:21:04 -070019#include <errno.h>
Elliott Hughes26dbad22015-01-28 12:09:05 -080020#include <stdio.h>
Tao Baoac9d94d2016-11-03 11:37:15 -070021#include <stdlib.h>
Elliott Hughes26dbad22015-01-28 12:09:05 -080022#include <string.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080023
Elliott Hughes8febafa2016-04-13 16:39:56 -070024#include <algorithm>
Tao Baod7bf82e2017-03-18 09:24:11 -070025#include <functional>
Elliott Hughes8febafa2016-04-13 16:39:56 -070026#include <memory>
Tao Bao76fdb242017-03-20 17:09:13 -070027#include <vector>
Elliott Hughes8febafa2016-04-13 16:39:56 -070028
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070029#include <android-base/logging.h>
Tianjie Xu82566982018-10-10 15:44:17 -070030#include <openssl/bio.h>
David Benjamina86392e2016-04-15 20:22:09 -040031#include <openssl/bn.h>
Elliott Hughes8febafa2016-04-13 16:39:56 -070032#include <openssl/ecdsa.h>
Tianjie Xu82566982018-10-10 15:44:17 -070033#include <openssl/evp.h>
Elliott Hughes8febafa2016-04-13 16:39:56 -070034#include <openssl/obj_mac.h>
Tianjie Xu82566982018-10-10 15:44:17 -070035#include <openssl/pem.h>
36#include <openssl/rsa.h>
Tianjie Xu0dd96852018-10-15 11:44:14 -070037#include <ziparchive/zip_archive.h>
Elliott Hughes8febafa2016-04-13 16:39:56 -070038
39#include "asn1_decoder.h"
Tao Bao09e468f2017-09-29 14:39:33 -070040#include "otautil/print_sha1.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070041
Elliott Hughes8febafa2016-04-13 16:39:56 -070042static constexpr size_t MiB = 1024 * 1024;
43
Kenny Root7a4adb52013-10-09 10:14:35 -070044/*
45 * Simple version of PKCS#7 SignedData extraction. This extracts the
46 * signature OCTET STRING to be used for signature verification.
47 *
48 * For full details, see http://www.ietf.org/rfc/rfc3852.txt
49 *
50 * The PKCS#7 structure looks like:
51 *
52 * SEQUENCE (ContentInfo)
53 * OID (ContentType)
54 * [0] (content)
55 * SEQUENCE (SignedData)
56 * INTEGER (version CMSVersion)
57 * SET (DigestAlgorithmIdentifiers)
58 * SEQUENCE (EncapsulatedContentInfo)
59 * [0] (CertificateSet OPTIONAL)
60 * [1] (RevocationInfoChoices OPTIONAL)
61 * SET (SignerInfos)
62 * SEQUENCE (SignerInfo)
63 * INTEGER (CMSVersion)
64 * SEQUENCE (SignerIdentifier)
65 * SEQUENCE (DigestAlgorithmIdentifier)
66 * SEQUENCE (SignatureAlgorithmIdentifier)
67 * OCTET STRING (SignatureValue)
68 */
Tao Bao76fdb242017-03-20 17:09:13 -070069static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len,
70 std::vector<uint8_t>* sig_der) {
71 CHECK(sig_der != nullptr);
72 sig_der->clear();
Kenny Root7a4adb52013-10-09 10:14:35 -070073
Tao Bao861c53c2017-03-20 17:09:13 -070074 asn1_context ctx(pkcs7_der, pkcs7_der_len);
75
76 std::unique_ptr<asn1_context> pkcs7_seq(ctx.asn1_sequence_get());
77 if (pkcs7_seq == nullptr || !pkcs7_seq->asn1_sequence_next()) {
Tao Bao76fdb242017-03-20 17:09:13 -070078 return false;
79 }
80
Tao Bao861c53c2017-03-20 17:09:13 -070081 std::unique_ptr<asn1_context> signed_data_app(pkcs7_seq->asn1_constructed_get());
82 if (signed_data_app == nullptr) {
83 return false;
Tao Bao76fdb242017-03-20 17:09:13 -070084 }
Kenny Root7a4adb52013-10-09 10:14:35 -070085
Tao Bao861c53c2017-03-20 17:09:13 -070086 std::unique_ptr<asn1_context> signed_data_seq(signed_data_app->asn1_sequence_get());
87 if (signed_data_seq == nullptr ||
88 !signed_data_seq->asn1_sequence_next() ||
89 !signed_data_seq->asn1_sequence_next() ||
90 !signed_data_seq->asn1_sequence_next() ||
91 !signed_data_seq->asn1_constructed_skip_all()) {
92 return false;
93 }
94
95 std::unique_ptr<asn1_context> sig_set(signed_data_seq->asn1_set_get());
96 if (sig_set == nullptr) {
97 return false;
98 }
99
100 std::unique_ptr<asn1_context> sig_seq(sig_set->asn1_sequence_get());
101 if (sig_seq == nullptr ||
102 !sig_seq->asn1_sequence_next() ||
103 !sig_seq->asn1_sequence_next() ||
104 !sig_seq->asn1_sequence_next() ||
105 !sig_seq->asn1_sequence_next()) {
106 return false;
107 }
108
109 const uint8_t* sig_der_ptr;
110 size_t sig_der_length;
111 if (!sig_seq->asn1_octet_string_get(&sig_der_ptr, &sig_der_length)) {
112 return false;
113 }
114
115 sig_der->resize(sig_der_length);
116 std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin());
117 return true;
Kenny Root7a4adb52013-10-09 10:14:35 -0700118}
119
Tao Bao5e535012017-03-16 17:37:38 -0700120/*
121 * Looks for an RSA signature embedded in the .ZIP file comment given the path to the zip. Verifies
122 * that it matches one of the given public keys. A callback function can be optionally provided for
123 * posting the progress.
124 *
125 * Returns VERIFY_SUCCESS or VERIFY_FAILURE (if any error is encountered or no key matches the
126 * signature).
127 */
Tao Bao76fdb242017-03-20 17:09:13 -0700128int verify_file(const unsigned char* addr, size_t length, const std::vector<Certificate>& keys,
Tao Bao5e535012017-03-16 17:37:38 -0700129 const std::function<void(float)>& set_progress) {
130 if (set_progress) {
131 set_progress(0.0);
132 }
Doug Zongker54e2e862009-08-17 13:21:04 -0700133
Tao Bao5e535012017-03-16 17:37:38 -0700134 // An archive with a whole-file signature will end in six bytes:
135 //
136 // (2-byte signature start) $ff $ff (2-byte comment size)
137 //
138 // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by
139 // reading this footer, this tells us how far back from the end we have to start reading to find
140 // the whole comment.
Doug Zongker54e2e862009-08-17 13:21:04 -0700141
142#define FOOTER_SIZE 6
143
Tao Bao5e535012017-03-16 17:37:38 -0700144 if (length < FOOTER_SIZE) {
145 LOG(ERROR) << "not big enough to contain footer";
146 return VERIFY_FAILURE;
147 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800148
Tao Bao76fdb242017-03-20 17:09:13 -0700149 const unsigned char* footer = addr + length - FOOTER_SIZE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800150
Tao Bao5e535012017-03-16 17:37:38 -0700151 if (footer[2] != 0xff || footer[3] != 0xff) {
152 LOG(ERROR) << "footer is wrong";
153 return VERIFY_FAILURE;
154 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800155
Tao Bao5e535012017-03-16 17:37:38 -0700156 size_t comment_size = footer[4] + (footer[5] << 8);
157 size_t signature_start = footer[0] + (footer[1] << 8);
158 LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start
159 << " bytes from end";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800160
Tao Bao553c7bd2017-03-18 07:33:26 -0700161 if (signature_start > comment_size) {
162 LOG(ERROR) << "signature start: " << signature_start << " is larger than comment size: "
163 << comment_size;
164 return VERIFY_FAILURE;
165 }
Tianjie Xu54ea1362016-12-16 16:24:09 -0800166
Tao Bao5e535012017-03-16 17:37:38 -0700167 if (signature_start <= FOOTER_SIZE) {
168 LOG(ERROR) << "Signature start is in the footer";
169 return VERIFY_FAILURE;
170 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800171
Doug Zongker54e2e862009-08-17 13:21:04 -0700172#define EOCD_HEADER_SIZE 22
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800173
Tao Bao5e535012017-03-16 17:37:38 -0700174 // The end-of-central-directory record is 22 bytes plus any comment length.
175 size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800176
Tao Bao5e535012017-03-16 17:37:38 -0700177 if (length < eocd_size) {
178 LOG(ERROR) << "not big enough to contain EOCD";
Doug Zongker54e2e862009-08-17 13:21:04 -0700179 return VERIFY_FAILURE;
Tao Bao5e535012017-03-16 17:37:38 -0700180 }
181
182 // Determine how much of the file is covered by the signature. This is everything except the
183 // signature data and length, which includes all of the EOCD except for the comment length field
184 // (2 bytes) and the comment data.
185 size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
186
Tao Bao76fdb242017-03-20 17:09:13 -0700187 const unsigned char* eocd = addr + length - eocd_size;
Tao Bao5e535012017-03-16 17:37:38 -0700188
189 // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06.
190 if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) {
191 LOG(ERROR) << "signature length doesn't match EOCD marker";
192 return VERIFY_FAILURE;
193 }
194
195 for (size_t i = 4; i < eocd_size-3; ++i) {
Tao Bao76fdb242017-03-20 17:09:13 -0700196 if (eocd[i] == 0x50 && eocd[i+1] == 0x4b && eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
Tao Bao5e535012017-03-16 17:37:38 -0700197 // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will
198 // find the later (wrong) one, which could be exploitable. Fail the verification if this
199 // sequence occurs anywhere after the real one.
200 LOG(ERROR) << "EOCD marker occurs after start of EOCD";
201 return VERIFY_FAILURE;
202 }
203 }
204
205 bool need_sha1 = false;
206 bool need_sha256 = false;
207 for (const auto& key : keys) {
208 switch (key.hash_len) {
209 case SHA_DIGEST_LENGTH: need_sha1 = true; break;
210 case SHA256_DIGEST_LENGTH: need_sha256 = true; break;
211 }
212 }
213
214 SHA_CTX sha1_ctx;
215 SHA256_CTX sha256_ctx;
216 SHA1_Init(&sha1_ctx);
217 SHA256_Init(&sha256_ctx);
218
219 double frac = -1.0;
220 size_t so_far = 0;
221 while (so_far < signed_len) {
222 // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a
223 // 1196MiB full OTA and 60% for an 89MiB incremental OTA.
224 // http://b/28135231.
225 size_t size = std::min(signed_len - so_far, 16 * MiB);
226
227 if (need_sha1) SHA1_Update(&sha1_ctx, addr + so_far, size);
228 if (need_sha256) SHA256_Update(&sha256_ctx, addr + so_far, size);
229 so_far += size;
230
231 if (set_progress) {
232 double f = so_far / (double)signed_len;
233 if (f > frac + 0.02 || size == so_far) {
234 set_progress(f);
235 frac = f;
236 }
237 }
238 }
239
240 uint8_t sha1[SHA_DIGEST_LENGTH];
241 SHA1_Final(sha1, &sha1_ctx);
242 uint8_t sha256[SHA256_DIGEST_LENGTH];
243 SHA256_Final(sha256, &sha256_ctx);
244
Tao Bao76fdb242017-03-20 17:09:13 -0700245 const uint8_t* signature = eocd + eocd_size - signature_start;
Tao Bao5e535012017-03-16 17:37:38 -0700246 size_t signature_size = signature_start - FOOTER_SIZE;
247
248 LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) << ", length: "
249 << signature_size << "): " << print_hex(signature, signature_size);
250
Tao Bao76fdb242017-03-20 17:09:13 -0700251 std::vector<uint8_t> sig_der;
252 if (!read_pkcs7(signature, signature_size, &sig_der)) {
Tao Bao5e535012017-03-16 17:37:38 -0700253 LOG(ERROR) << "Could not find signature DER block";
254 return VERIFY_FAILURE;
255 }
256
257 // Check to make sure at least one of the keys matches the signature. Since any key can match,
258 // we need to try each before determining a verification failure has happened.
259 size_t i = 0;
260 for (const auto& key : keys) {
261 const uint8_t* hash;
262 int hash_nid;
263 switch (key.hash_len) {
264 case SHA_DIGEST_LENGTH:
265 hash = sha1;
266 hash_nid = NID_sha1;
267 break;
268 case SHA256_DIGEST_LENGTH:
269 hash = sha256;
270 hash_nid = NID_sha256;
271 break;
272 default:
273 continue;
274 }
275
276 // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends
277 // after the signature itself.
278 if (key.key_type == Certificate::KEY_TYPE_RSA) {
Tao Bao76fdb242017-03-20 17:09:13 -0700279 if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(),
280 key.rsa.get())) {
Tao Bao5e535012017-03-16 17:37:38 -0700281 LOG(INFO) << "failed to verify against RSA key " << i;
282 continue;
283 }
284
285 LOG(INFO) << "whole-file signature verified against RSA key " << i;
Tao Bao5e535012017-03-16 17:37:38 -0700286 return VERIFY_SUCCESS;
287 } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) {
Tao Bao76fdb242017-03-20 17:09:13 -0700288 if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) {
Tao Bao5e535012017-03-16 17:37:38 -0700289 LOG(INFO) << "failed to verify against EC key " << i;
290 continue;
291 }
292
293 LOG(INFO) << "whole-file signature verified against EC key " << i;
Tao Bao5e535012017-03-16 17:37:38 -0700294 return VERIFY_SUCCESS;
295 } else {
296 LOG(INFO) << "Unknown key type " << key.key_type;
297 }
298 i++;
299 }
300
301 if (need_sha1) {
302 LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
303 }
304 if (need_sha256) {
305 LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
306 }
Tao Bao5e535012017-03-16 17:37:38 -0700307 LOG(ERROR) << "failed to verify whole-file signature";
308 return VERIFY_FAILURE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800309}
Doug Zongker6c249f72012-11-02 15:04:05 -0700310
Elliott Hughes8febafa2016-04-13 16:39:56 -0700311std::unique_ptr<RSA, RSADeleter> parse_rsa_key(FILE* file, uint32_t exponent) {
312 // Read key length in words and n0inv. n0inv is a precomputed montgomery
313 // parameter derived from the modulus and can be used to speed up
314 // verification. n0inv is 32 bits wide here, assuming the verification logic
315 // uses 32 bit arithmetic. However, BoringSSL may use a word size of 64 bits
316 // internally, in which case we don't have a valid n0inv. Thus, we just
317 // ignore the montgomery parameters and have BoringSSL recompute them
318 // internally. If/When the speedup from using the montgomery parameters
319 // becomes relevant, we can add more sophisticated code here to obtain a
320 // 64-bit n0inv and initialize the montgomery parameters in the key object.
321 uint32_t key_len_words = 0;
322 uint32_t n0inv = 0;
323 if (fscanf(file, " %i , 0x%x", &key_len_words, &n0inv) != 2) {
324 return nullptr;
325 }
326
327 if (key_len_words > 8192 / 32) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700328 LOG(ERROR) << "key length (" << key_len_words << ") too large";
Elliott Hughes8febafa2016-04-13 16:39:56 -0700329 return nullptr;
330 }
331
332 // Read the modulus.
333 std::unique_ptr<uint32_t[]> modulus(new uint32_t[key_len_words]);
334 if (fscanf(file, " , { %u", &modulus[0]) != 1) {
335 return nullptr;
336 }
337 for (uint32_t i = 1; i < key_len_words; ++i) {
338 if (fscanf(file, " , %u", &modulus[i]) != 1) {
339 return nullptr;
340 }
341 }
342
343 // Cconvert from little-endian array of little-endian words to big-endian
344 // byte array suitable as input for BN_bin2bn.
345 std::reverse((uint8_t*)modulus.get(),
346 (uint8_t*)(modulus.get() + key_len_words));
347
348 // The next sequence of values is the montgomery parameter R^2. Since we
349 // generally don't have a valid |n0inv|, we ignore this (see comment above).
350 uint32_t rr_value;
351 if (fscanf(file, " } , { %u", &rr_value) != 1) {
352 return nullptr;
353 }
354 for (uint32_t i = 1; i < key_len_words; ++i) {
355 if (fscanf(file, " , %u", &rr_value) != 1) {
356 return nullptr;
357 }
358 }
359 if (fscanf(file, " } } ") != 0) {
360 return nullptr;
361 }
362
363 // Initialize the key.
364 std::unique_ptr<RSA, RSADeleter> key(RSA_new());
365 if (!key) {
366 return nullptr;
367 }
368
369 key->n = BN_bin2bn((uint8_t*)modulus.get(),
370 key_len_words * sizeof(uint32_t), NULL);
371 if (!key->n) {
372 return nullptr;
373 }
374
375 key->e = BN_new();
376 if (!key->e || !BN_set_word(key->e, exponent)) {
377 return nullptr;
378 }
379
380 return key;
381}
382
383struct BNDeleter {
Mikhail Lappob49767c2017-03-23 21:44:26 +0100384 void operator()(BIGNUM* bn) const {
Elliott Hughes8febafa2016-04-13 16:39:56 -0700385 BN_free(bn);
386 }
387};
388
389std::unique_ptr<EC_KEY, ECKEYDeleter> parse_ec_key(FILE* file) {
390 uint32_t key_len_bytes = 0;
391 if (fscanf(file, " %i", &key_len_bytes) != 1) {
392 return nullptr;
393 }
394
395 std::unique_ptr<EC_GROUP, void (*)(EC_GROUP*)> group(
396 EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1), EC_GROUP_free);
397 if (!group) {
398 return nullptr;
399 }
400
401 // Verify that |key_len| matches the group order.
402 if (key_len_bytes != BN_num_bytes(EC_GROUP_get0_order(group.get()))) {
403 return nullptr;
404 }
405
406 // Read the public key coordinates. Note that the byte order in the file is
407 // little-endian, so we convert to big-endian here.
408 std::unique_ptr<uint8_t[]> bytes(new uint8_t[key_len_bytes]);
409 std::unique_ptr<BIGNUM, BNDeleter> point[2];
410 for (int i = 0; i < 2; ++i) {
411 unsigned int byte = 0;
412 if (fscanf(file, " , { %u", &byte) != 1) {
413 return nullptr;
414 }
415 bytes[key_len_bytes - 1] = byte;
416
417 for (size_t i = 1; i < key_len_bytes; ++i) {
418 if (fscanf(file, " , %u", &byte) != 1) {
419 return nullptr;
420 }
421 bytes[key_len_bytes - i - 1] = byte;
422 }
423
424 point[i].reset(BN_bin2bn(bytes.get(), key_len_bytes, nullptr));
425 if (!point[i]) {
426 return nullptr;
427 }
428
429 if (fscanf(file, " }") != 0) {
430 return nullptr;
431 }
432 }
433
434 if (fscanf(file, " } ") != 0) {
435 return nullptr;
436 }
437
438 // Create and initialize the key.
439 std::unique_ptr<EC_KEY, ECKEYDeleter> key(EC_KEY_new());
440 if (!key || !EC_KEY_set_group(key.get(), group.get()) ||
441 !EC_KEY_set_public_key_affine_coordinates(key.get(), point[0].get(),
442 point[1].get())) {
443 return nullptr;
444 }
445
446 return key;
447}
448
Tianjie Xu0dd96852018-10-15 11:44:14 -0700449static std::vector<Certificate> IterateZipEntriesAndSearchForKeys(const ZipArchiveHandle& handle) {
450 void* cookie;
451 ZipString suffix("x509.pem");
452 int32_t iter_status = StartIteration(handle, &cookie, nullptr, &suffix);
453 if (iter_status != 0) {
454 LOG(ERROR) << "Failed to iterate over entries in the certificate zipfile: "
455 << ErrorCodeString(iter_status);
456 return {};
457 }
458
459 std::vector<Certificate> result;
460
461 ZipString name;
462 ZipEntry entry;
463 while ((iter_status = Next(cookie, &entry, &name)) == 0) {
464 std::vector<uint8_t> pem_content(entry.uncompressed_length);
465 if (int32_t extract_status =
466 ExtractToMemory(handle, &entry, pem_content.data(), pem_content.size());
467 extract_status != 0) {
468 LOG(ERROR) << "Failed to extract " << std::string(name.name, name.name + name.name_length);
469 return {};
470 }
471
472 Certificate cert(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
473 // Aborts the parsing if we fail to load one of the key file.
474 if (!LoadCertificateFromBuffer(pem_content, &cert)) {
475 LOG(ERROR) << "Failed to load keys from "
476 << std::string(name.name, name.name + name.name_length);
477 return {};
478 }
479
480 result.emplace_back(std::move(cert));
481 }
482
483 if (iter_status != -1) {
484 LOG(ERROR) << "Error while iterating over zip entries: " << ErrorCodeString(iter_status);
485 return {};
486 }
487
488 return result;
489}
490
491std::vector<Certificate> LoadKeysFromZipfile(const std::string& zip_name) {
492 ZipArchiveHandle handle;
493 if (int32_t open_status = OpenArchive(zip_name.c_str(), &handle); open_status != 0) {
494 LOG(ERROR) << "Failed to open " << zip_name << ": " << ErrorCodeString(open_status);
495 return {};
496 }
497
498 std::vector<Certificate> result = IterateZipEntriesAndSearchForKeys(handle);
499 CloseArchive(handle);
500 return result;
501}
502
Tianjie Xu82566982018-10-10 15:44:17 -0700503bool LoadCertificateFromBuffer(const std::vector<uint8_t>& pem_content, Certificate* cert) {
504 std::unique_ptr<BIO, decltype(&BIO_free)> content(
505 BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free);
506
507 std::unique_ptr<X509, decltype(&X509_free)> x509(
508 PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free);
509 if (!x509) {
510 LOG(ERROR) << "Failed to read x509 certificate";
511 return false;
512 }
513
514 int nid = X509_get_signature_nid(x509.get());
515 switch (nid) {
516 // SignApk has historically accepted md5WithRSA certificates, but treated them as
517 // sha1WithRSA anyway. Continue to do so for backwards compatibility.
518 case NID_md5WithRSA:
519 case NID_md5WithRSAEncryption:
520 case NID_sha1WithRSA:
521 case NID_sha1WithRSAEncryption:
522 cert->hash_len = SHA_DIGEST_LENGTH;
523 break;
524 case NID_sha256WithRSAEncryption:
525 case NID_ecdsa_with_SHA256:
526 cert->hash_len = SHA256_DIGEST_LENGTH;
527 break;
528 default:
529 LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid);
530 return false;
531 }
532
533 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> public_key(X509_get_pubkey(x509.get()),
534 EVP_PKEY_free);
535 if (!public_key) {
536 LOG(ERROR) << "Failed to extract the public key from x509 certificate";
537 return false;
538 }
539
540 int key_type = EVP_PKEY_id(public_key.get());
541 // TODO(xunchang) check the rsa key has exponent 3 or 65537 with RSA_get0_key; and ec key is
542 // 256 bits.
543 if (key_type == EVP_PKEY_RSA) {
544 cert->key_type = Certificate::KEY_TYPE_RSA;
545 cert->ec.reset();
546 cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get()));
547 if (!cert->rsa) {
548 LOG(ERROR) << "Failed to get the rsa key info from public key";
549 return false;
550 }
551 } else if (key_type == EVP_PKEY_EC) {
552 cert->key_type = Certificate::KEY_TYPE_EC;
553 cert->rsa.reset();
554 cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get()));
555 if (!cert->ec) {
556 LOG(ERROR) << "Failed to get the ec key info from the public key";
557 return false;
558 }
559 } else {
560 LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type);
561 return false;
562 }
563
564 return true;
565}
566
Doug Zongker6c249f72012-11-02 15:04:05 -0700567// Reads a file containing one or more public keys as produced by
568// DumpPublicKey: this is an RSAPublicKey struct as it would appear
569// as a C source literal, eg:
570//
571// "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
572//
573// For key versions newer than the original 2048-bit e=3 keys
574// supported by Android, the string is preceded by a version
575// identifier, eg:
576//
577// "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
578//
579// (Note that the braces and commas in this example are actual
580// characters the parser expects to find in the file; the ellipses
581// indicate more numbers omitted from this example.)
582//
583// The file may contain multiple keys in this format, separated by
584// commas. The last key must not be followed by a comma.
585//
Doug Zongker30362a62013-04-10 11:32:17 -0700586// A Certificate is a pair of an RSAPublicKey and a particular hash
587// (we support SHA-1 and SHA-256; we store the hash length to signify
588// which is being used). The hash used is implied by the version number.
589//
590// 1: 2048-bit RSA key with e=3 and SHA-1 hash
591// 2: 2048-bit RSA key with e=65537 and SHA-1 hash
592// 3: 2048-bit RSA key with e=3 and SHA-256 hash
593// 4: 2048-bit RSA key with e=65537 and SHA-256 hash
Kenny Root7a4adb52013-10-09 10:14:35 -0700594// 5: 256-bit EC key using the NIST P-256 curve parameters and SHA-256 hash
Doug Zongker30362a62013-04-10 11:32:17 -0700595//
Tao Bao71e3e092016-02-02 14:02:27 -0800596// Returns true on success, and appends the found keys (at least one) to certs.
597// Otherwise returns false if the file failed to parse, or if it contains zero
598// keys. The contents in certs would be unspecified on failure.
599bool load_keys(const char* filename, std::vector<Certificate>& certs) {
Tianjie Xude6735e2017-07-10 15:13:33 -0700600 std::unique_ptr<FILE, decltype(&fclose)> f(fopen(filename, "re"), fclose);
601 if (!f) {
602 PLOG(ERROR) << "error opening " << filename;
603 return false;
604 }
605
606 while (true) {
607 certs.emplace_back(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
608 Certificate& cert = certs.back();
609 uint32_t exponent = 0;
610
611 char start_char;
612 if (fscanf(f.get(), " %c", &start_char) != 1) return false;
613 if (start_char == '{') {
614 // a version 1 key has no version specifier.
615 cert.key_type = Certificate::KEY_TYPE_RSA;
616 exponent = 3;
617 cert.hash_len = SHA_DIGEST_LENGTH;
618 } else if (start_char == 'v') {
619 int version;
620 if (fscanf(f.get(), "%d {", &version) != 1) return false;
621 switch (version) {
622 case 2:
623 cert.key_type = Certificate::KEY_TYPE_RSA;
624 exponent = 65537;
625 cert.hash_len = SHA_DIGEST_LENGTH;
626 break;
627 case 3:
628 cert.key_type = Certificate::KEY_TYPE_RSA;
629 exponent = 3;
630 cert.hash_len = SHA256_DIGEST_LENGTH;
631 break;
632 case 4:
633 cert.key_type = Certificate::KEY_TYPE_RSA;
634 exponent = 65537;
635 cert.hash_len = SHA256_DIGEST_LENGTH;
636 break;
637 case 5:
638 cert.key_type = Certificate::KEY_TYPE_EC;
639 cert.hash_len = SHA256_DIGEST_LENGTH;
640 break;
641 default:
642 return false;
643 }
644 }
645
646 if (cert.key_type == Certificate::KEY_TYPE_RSA) {
647 cert.rsa = parse_rsa_key(f.get(), exponent);
648 if (!cert.rsa) {
Tao Bao71e3e092016-02-02 14:02:27 -0800649 return false;
Tianjie Xude6735e2017-07-10 15:13:33 -0700650 }
651
652 LOG(INFO) << "read key e=" << exponent << " hash=" << cert.hash_len;
653 } else if (cert.key_type == Certificate::KEY_TYPE_EC) {
654 cert.ec = parse_ec_key(f.get());
655 if (!cert.ec) {
656 return false;
657 }
658 } else {
659 LOG(ERROR) << "Unknown key type " << cert.key_type;
660 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700661 }
662
Tianjie Xude6735e2017-07-10 15:13:33 -0700663 // if the line ends in a comma, this file has more keys.
664 int ch = fgetc(f.get());
665 if (ch == ',') {
666 // more keys to come.
667 continue;
668 } else if (ch == EOF) {
669 break;
670 } else {
671 LOG(ERROR) << "unexpected character between keys";
672 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700673 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700674 }
675 return true;
Doug Zongker6c249f72012-11-02 15:04:05 -0700676}