blob: 1dc52a0ef1121f35f0a10920180f588e7ce0c5fa [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>
Elliott Hughes8febafa2016-04-13 16:39:56 -070037
38#include "asn1_decoder.h"
Tao Bao09e468f2017-09-29 14:39:33 -070039#include "otautil/print_sha1.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070040
Elliott Hughes8febafa2016-04-13 16:39:56 -070041static constexpr size_t MiB = 1024 * 1024;
42
Kenny Root7a4adb52013-10-09 10:14:35 -070043/*
44 * Simple version of PKCS#7 SignedData extraction. This extracts the
45 * signature OCTET STRING to be used for signature verification.
46 *
47 * For full details, see http://www.ietf.org/rfc/rfc3852.txt
48 *
49 * The PKCS#7 structure looks like:
50 *
51 * SEQUENCE (ContentInfo)
52 * OID (ContentType)
53 * [0] (content)
54 * SEQUENCE (SignedData)
55 * INTEGER (version CMSVersion)
56 * SET (DigestAlgorithmIdentifiers)
57 * SEQUENCE (EncapsulatedContentInfo)
58 * [0] (CertificateSet OPTIONAL)
59 * [1] (RevocationInfoChoices OPTIONAL)
60 * SET (SignerInfos)
61 * SEQUENCE (SignerInfo)
62 * INTEGER (CMSVersion)
63 * SEQUENCE (SignerIdentifier)
64 * SEQUENCE (DigestAlgorithmIdentifier)
65 * SEQUENCE (SignatureAlgorithmIdentifier)
66 * OCTET STRING (SignatureValue)
67 */
Tao Bao76fdb242017-03-20 17:09:13 -070068static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len,
69 std::vector<uint8_t>* sig_der) {
70 CHECK(sig_der != nullptr);
71 sig_der->clear();
Kenny Root7a4adb52013-10-09 10:14:35 -070072
Tao Bao861c53c2017-03-20 17:09:13 -070073 asn1_context ctx(pkcs7_der, pkcs7_der_len);
74
75 std::unique_ptr<asn1_context> pkcs7_seq(ctx.asn1_sequence_get());
76 if (pkcs7_seq == nullptr || !pkcs7_seq->asn1_sequence_next()) {
Tao Bao76fdb242017-03-20 17:09:13 -070077 return false;
78 }
79
Tao Bao861c53c2017-03-20 17:09:13 -070080 std::unique_ptr<asn1_context> signed_data_app(pkcs7_seq->asn1_constructed_get());
81 if (signed_data_app == nullptr) {
82 return false;
Tao Bao76fdb242017-03-20 17:09:13 -070083 }
Kenny Root7a4adb52013-10-09 10:14:35 -070084
Tao Bao861c53c2017-03-20 17:09:13 -070085 std::unique_ptr<asn1_context> signed_data_seq(signed_data_app->asn1_sequence_get());
86 if (signed_data_seq == nullptr ||
87 !signed_data_seq->asn1_sequence_next() ||
88 !signed_data_seq->asn1_sequence_next() ||
89 !signed_data_seq->asn1_sequence_next() ||
90 !signed_data_seq->asn1_constructed_skip_all()) {
91 return false;
92 }
93
94 std::unique_ptr<asn1_context> sig_set(signed_data_seq->asn1_set_get());
95 if (sig_set == nullptr) {
96 return false;
97 }
98
99 std::unique_ptr<asn1_context> sig_seq(sig_set->asn1_sequence_get());
100 if (sig_seq == nullptr ||
101 !sig_seq->asn1_sequence_next() ||
102 !sig_seq->asn1_sequence_next() ||
103 !sig_seq->asn1_sequence_next() ||
104 !sig_seq->asn1_sequence_next()) {
105 return false;
106 }
107
108 const uint8_t* sig_der_ptr;
109 size_t sig_der_length;
110 if (!sig_seq->asn1_octet_string_get(&sig_der_ptr, &sig_der_length)) {
111 return false;
112 }
113
114 sig_der->resize(sig_der_length);
115 std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin());
116 return true;
Kenny Root7a4adb52013-10-09 10:14:35 -0700117}
118
Tao Bao5e535012017-03-16 17:37:38 -0700119/*
120 * Looks for an RSA signature embedded in the .ZIP file comment given the path to the zip. Verifies
121 * that it matches one of the given public keys. A callback function can be optionally provided for
122 * posting the progress.
123 *
124 * Returns VERIFY_SUCCESS or VERIFY_FAILURE (if any error is encountered or no key matches the
125 * signature).
126 */
Tao Bao76fdb242017-03-20 17:09:13 -0700127int verify_file(const unsigned char* addr, size_t length, const std::vector<Certificate>& keys,
Tao Bao5e535012017-03-16 17:37:38 -0700128 const std::function<void(float)>& set_progress) {
129 if (set_progress) {
130 set_progress(0.0);
131 }
Doug Zongker54e2e862009-08-17 13:21:04 -0700132
Tao Bao5e535012017-03-16 17:37:38 -0700133 // An archive with a whole-file signature will end in six bytes:
134 //
135 // (2-byte signature start) $ff $ff (2-byte comment size)
136 //
137 // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by
138 // reading this footer, this tells us how far back from the end we have to start reading to find
139 // the whole comment.
Doug Zongker54e2e862009-08-17 13:21:04 -0700140
141#define FOOTER_SIZE 6
142
Tao Bao5e535012017-03-16 17:37:38 -0700143 if (length < FOOTER_SIZE) {
144 LOG(ERROR) << "not big enough to contain footer";
145 return VERIFY_FAILURE;
146 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800147
Tao Bao76fdb242017-03-20 17:09:13 -0700148 const unsigned char* footer = addr + length - FOOTER_SIZE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800149
Tao Bao5e535012017-03-16 17:37:38 -0700150 if (footer[2] != 0xff || footer[3] != 0xff) {
151 LOG(ERROR) << "footer is wrong";
152 return VERIFY_FAILURE;
153 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800154
Tao Bao5e535012017-03-16 17:37:38 -0700155 size_t comment_size = footer[4] + (footer[5] << 8);
156 size_t signature_start = footer[0] + (footer[1] << 8);
157 LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start
158 << " bytes from end";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800159
Tao Bao553c7bd2017-03-18 07:33:26 -0700160 if (signature_start > comment_size) {
161 LOG(ERROR) << "signature start: " << signature_start << " is larger than comment size: "
162 << comment_size;
163 return VERIFY_FAILURE;
164 }
Tianjie Xu54ea1362016-12-16 16:24:09 -0800165
Tao Bao5e535012017-03-16 17:37:38 -0700166 if (signature_start <= FOOTER_SIZE) {
167 LOG(ERROR) << "Signature start is in the footer";
168 return VERIFY_FAILURE;
169 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800170
Doug Zongker54e2e862009-08-17 13:21:04 -0700171#define EOCD_HEADER_SIZE 22
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800172
Tao Bao5e535012017-03-16 17:37:38 -0700173 // The end-of-central-directory record is 22 bytes plus any comment length.
174 size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800175
Tao Bao5e535012017-03-16 17:37:38 -0700176 if (length < eocd_size) {
177 LOG(ERROR) << "not big enough to contain EOCD";
Doug Zongker54e2e862009-08-17 13:21:04 -0700178 return VERIFY_FAILURE;
Tao Bao5e535012017-03-16 17:37:38 -0700179 }
180
181 // Determine how much of the file is covered by the signature. This is everything except the
182 // signature data and length, which includes all of the EOCD except for the comment length field
183 // (2 bytes) and the comment data.
184 size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
185
Tao Bao76fdb242017-03-20 17:09:13 -0700186 const unsigned char* eocd = addr + length - eocd_size;
Tao Bao5e535012017-03-16 17:37:38 -0700187
188 // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06.
189 if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) {
190 LOG(ERROR) << "signature length doesn't match EOCD marker";
191 return VERIFY_FAILURE;
192 }
193
194 for (size_t i = 4; i < eocd_size-3; ++i) {
Tao Bao76fdb242017-03-20 17:09:13 -0700195 if (eocd[i] == 0x50 && eocd[i+1] == 0x4b && eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
Tao Bao5e535012017-03-16 17:37:38 -0700196 // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will
197 // find the later (wrong) one, which could be exploitable. Fail the verification if this
198 // sequence occurs anywhere after the real one.
199 LOG(ERROR) << "EOCD marker occurs after start of EOCD";
200 return VERIFY_FAILURE;
201 }
202 }
203
204 bool need_sha1 = false;
205 bool need_sha256 = false;
206 for (const auto& key : keys) {
207 switch (key.hash_len) {
208 case SHA_DIGEST_LENGTH: need_sha1 = true; break;
209 case SHA256_DIGEST_LENGTH: need_sha256 = true; break;
210 }
211 }
212
213 SHA_CTX sha1_ctx;
214 SHA256_CTX sha256_ctx;
215 SHA1_Init(&sha1_ctx);
216 SHA256_Init(&sha256_ctx);
217
218 double frac = -1.0;
219 size_t so_far = 0;
220 while (so_far < signed_len) {
221 // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a
222 // 1196MiB full OTA and 60% for an 89MiB incremental OTA.
223 // http://b/28135231.
224 size_t size = std::min(signed_len - so_far, 16 * MiB);
225
226 if (need_sha1) SHA1_Update(&sha1_ctx, addr + so_far, size);
227 if (need_sha256) SHA256_Update(&sha256_ctx, addr + so_far, size);
228 so_far += size;
229
230 if (set_progress) {
231 double f = so_far / (double)signed_len;
232 if (f > frac + 0.02 || size == so_far) {
233 set_progress(f);
234 frac = f;
235 }
236 }
237 }
238
239 uint8_t sha1[SHA_DIGEST_LENGTH];
240 SHA1_Final(sha1, &sha1_ctx);
241 uint8_t sha256[SHA256_DIGEST_LENGTH];
242 SHA256_Final(sha256, &sha256_ctx);
243
Tao Bao76fdb242017-03-20 17:09:13 -0700244 const uint8_t* signature = eocd + eocd_size - signature_start;
Tao Bao5e535012017-03-16 17:37:38 -0700245 size_t signature_size = signature_start - FOOTER_SIZE;
246
247 LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) << ", length: "
248 << signature_size << "): " << print_hex(signature, signature_size);
249
Tao Bao76fdb242017-03-20 17:09:13 -0700250 std::vector<uint8_t> sig_der;
251 if (!read_pkcs7(signature, signature_size, &sig_der)) {
Tao Bao5e535012017-03-16 17:37:38 -0700252 LOG(ERROR) << "Could not find signature DER block";
253 return VERIFY_FAILURE;
254 }
255
256 // Check to make sure at least one of the keys matches the signature. Since any key can match,
257 // we need to try each before determining a verification failure has happened.
258 size_t i = 0;
259 for (const auto& key : keys) {
260 const uint8_t* hash;
261 int hash_nid;
262 switch (key.hash_len) {
263 case SHA_DIGEST_LENGTH:
264 hash = sha1;
265 hash_nid = NID_sha1;
266 break;
267 case SHA256_DIGEST_LENGTH:
268 hash = sha256;
269 hash_nid = NID_sha256;
270 break;
271 default:
272 continue;
273 }
274
275 // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends
276 // after the signature itself.
277 if (key.key_type == Certificate::KEY_TYPE_RSA) {
Tao Bao76fdb242017-03-20 17:09:13 -0700278 if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(),
279 key.rsa.get())) {
Tao Bao5e535012017-03-16 17:37:38 -0700280 LOG(INFO) << "failed to verify against RSA key " << i;
281 continue;
282 }
283
284 LOG(INFO) << "whole-file signature verified against RSA key " << i;
Tao Bao5e535012017-03-16 17:37:38 -0700285 return VERIFY_SUCCESS;
286 } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) {
Tao Bao76fdb242017-03-20 17:09:13 -0700287 if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) {
Tao Bao5e535012017-03-16 17:37:38 -0700288 LOG(INFO) << "failed to verify against EC key " << i;
289 continue;
290 }
291
292 LOG(INFO) << "whole-file signature verified against EC key " << i;
Tao Bao5e535012017-03-16 17:37:38 -0700293 return VERIFY_SUCCESS;
294 } else {
295 LOG(INFO) << "Unknown key type " << key.key_type;
296 }
297 i++;
298 }
299
300 if (need_sha1) {
301 LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
302 }
303 if (need_sha256) {
304 LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
305 }
Tao Bao5e535012017-03-16 17:37:38 -0700306 LOG(ERROR) << "failed to verify whole-file signature";
307 return VERIFY_FAILURE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800308}
Doug Zongker6c249f72012-11-02 15:04:05 -0700309
Elliott Hughes8febafa2016-04-13 16:39:56 -0700310std::unique_ptr<RSA, RSADeleter> parse_rsa_key(FILE* file, uint32_t exponent) {
311 // Read key length in words and n0inv. n0inv is a precomputed montgomery
312 // parameter derived from the modulus and can be used to speed up
313 // verification. n0inv is 32 bits wide here, assuming the verification logic
314 // uses 32 bit arithmetic. However, BoringSSL may use a word size of 64 bits
315 // internally, in which case we don't have a valid n0inv. Thus, we just
316 // ignore the montgomery parameters and have BoringSSL recompute them
317 // internally. If/When the speedup from using the montgomery parameters
318 // becomes relevant, we can add more sophisticated code here to obtain a
319 // 64-bit n0inv and initialize the montgomery parameters in the key object.
320 uint32_t key_len_words = 0;
321 uint32_t n0inv = 0;
322 if (fscanf(file, " %i , 0x%x", &key_len_words, &n0inv) != 2) {
323 return nullptr;
324 }
325
326 if (key_len_words > 8192 / 32) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700327 LOG(ERROR) << "key length (" << key_len_words << ") too large";
Elliott Hughes8febafa2016-04-13 16:39:56 -0700328 return nullptr;
329 }
330
331 // Read the modulus.
332 std::unique_ptr<uint32_t[]> modulus(new uint32_t[key_len_words]);
333 if (fscanf(file, " , { %u", &modulus[0]) != 1) {
334 return nullptr;
335 }
336 for (uint32_t i = 1; i < key_len_words; ++i) {
337 if (fscanf(file, " , %u", &modulus[i]) != 1) {
338 return nullptr;
339 }
340 }
341
342 // Cconvert from little-endian array of little-endian words to big-endian
343 // byte array suitable as input for BN_bin2bn.
344 std::reverse((uint8_t*)modulus.get(),
345 (uint8_t*)(modulus.get() + key_len_words));
346
347 // The next sequence of values is the montgomery parameter R^2. Since we
348 // generally don't have a valid |n0inv|, we ignore this (see comment above).
349 uint32_t rr_value;
350 if (fscanf(file, " } , { %u", &rr_value) != 1) {
351 return nullptr;
352 }
353 for (uint32_t i = 1; i < key_len_words; ++i) {
354 if (fscanf(file, " , %u", &rr_value) != 1) {
355 return nullptr;
356 }
357 }
358 if (fscanf(file, " } } ") != 0) {
359 return nullptr;
360 }
361
362 // Initialize the key.
363 std::unique_ptr<RSA, RSADeleter> key(RSA_new());
364 if (!key) {
365 return nullptr;
366 }
367
368 key->n = BN_bin2bn((uint8_t*)modulus.get(),
369 key_len_words * sizeof(uint32_t), NULL);
370 if (!key->n) {
371 return nullptr;
372 }
373
374 key->e = BN_new();
375 if (!key->e || !BN_set_word(key->e, exponent)) {
376 return nullptr;
377 }
378
379 return key;
380}
381
382struct BNDeleter {
Mikhail Lappob49767c2017-03-23 21:44:26 +0100383 void operator()(BIGNUM* bn) const {
Elliott Hughes8febafa2016-04-13 16:39:56 -0700384 BN_free(bn);
385 }
386};
387
388std::unique_ptr<EC_KEY, ECKEYDeleter> parse_ec_key(FILE* file) {
389 uint32_t key_len_bytes = 0;
390 if (fscanf(file, " %i", &key_len_bytes) != 1) {
391 return nullptr;
392 }
393
394 std::unique_ptr<EC_GROUP, void (*)(EC_GROUP*)> group(
395 EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1), EC_GROUP_free);
396 if (!group) {
397 return nullptr;
398 }
399
400 // Verify that |key_len| matches the group order.
401 if (key_len_bytes != BN_num_bytes(EC_GROUP_get0_order(group.get()))) {
402 return nullptr;
403 }
404
405 // Read the public key coordinates. Note that the byte order in the file is
406 // little-endian, so we convert to big-endian here.
407 std::unique_ptr<uint8_t[]> bytes(new uint8_t[key_len_bytes]);
408 std::unique_ptr<BIGNUM, BNDeleter> point[2];
409 for (int i = 0; i < 2; ++i) {
410 unsigned int byte = 0;
411 if (fscanf(file, " , { %u", &byte) != 1) {
412 return nullptr;
413 }
414 bytes[key_len_bytes - 1] = byte;
415
416 for (size_t i = 1; i < key_len_bytes; ++i) {
417 if (fscanf(file, " , %u", &byte) != 1) {
418 return nullptr;
419 }
420 bytes[key_len_bytes - i - 1] = byte;
421 }
422
423 point[i].reset(BN_bin2bn(bytes.get(), key_len_bytes, nullptr));
424 if (!point[i]) {
425 return nullptr;
426 }
427
428 if (fscanf(file, " }") != 0) {
429 return nullptr;
430 }
431 }
432
433 if (fscanf(file, " } ") != 0) {
434 return nullptr;
435 }
436
437 // Create and initialize the key.
438 std::unique_ptr<EC_KEY, ECKEYDeleter> key(EC_KEY_new());
439 if (!key || !EC_KEY_set_group(key.get(), group.get()) ||
440 !EC_KEY_set_public_key_affine_coordinates(key.get(), point[0].get(),
441 point[1].get())) {
442 return nullptr;
443 }
444
445 return key;
446}
447
Tianjie Xu82566982018-10-10 15:44:17 -0700448bool LoadCertificateFromBuffer(const std::vector<uint8_t>& pem_content, Certificate* cert) {
449 std::unique_ptr<BIO, decltype(&BIO_free)> content(
450 BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free);
451
452 std::unique_ptr<X509, decltype(&X509_free)> x509(
453 PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free);
454 if (!x509) {
455 LOG(ERROR) << "Failed to read x509 certificate";
456 return false;
457 }
458
459 int nid = X509_get_signature_nid(x509.get());
460 switch (nid) {
461 // SignApk has historically accepted md5WithRSA certificates, but treated them as
462 // sha1WithRSA anyway. Continue to do so for backwards compatibility.
463 case NID_md5WithRSA:
464 case NID_md5WithRSAEncryption:
465 case NID_sha1WithRSA:
466 case NID_sha1WithRSAEncryption:
467 cert->hash_len = SHA_DIGEST_LENGTH;
468 break;
469 case NID_sha256WithRSAEncryption:
470 case NID_ecdsa_with_SHA256:
471 cert->hash_len = SHA256_DIGEST_LENGTH;
472 break;
473 default:
474 LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid);
475 return false;
476 }
477
478 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> public_key(X509_get_pubkey(x509.get()),
479 EVP_PKEY_free);
480 if (!public_key) {
481 LOG(ERROR) << "Failed to extract the public key from x509 certificate";
482 return false;
483 }
484
485 int key_type = EVP_PKEY_id(public_key.get());
486 // TODO(xunchang) check the rsa key has exponent 3 or 65537 with RSA_get0_key; and ec key is
487 // 256 bits.
488 if (key_type == EVP_PKEY_RSA) {
489 cert->key_type = Certificate::KEY_TYPE_RSA;
490 cert->ec.reset();
491 cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get()));
492 if (!cert->rsa) {
493 LOG(ERROR) << "Failed to get the rsa key info from public key";
494 return false;
495 }
496 } else if (key_type == EVP_PKEY_EC) {
497 cert->key_type = Certificate::KEY_TYPE_EC;
498 cert->rsa.reset();
499 cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get()));
500 if (!cert->ec) {
501 LOG(ERROR) << "Failed to get the ec key info from the public key";
502 return false;
503 }
504 } else {
505 LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type);
506 return false;
507 }
508
509 return true;
510}
511
Doug Zongker6c249f72012-11-02 15:04:05 -0700512// Reads a file containing one or more public keys as produced by
513// DumpPublicKey: this is an RSAPublicKey struct as it would appear
514// as a C source literal, eg:
515//
516// "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
517//
518// For key versions newer than the original 2048-bit e=3 keys
519// supported by Android, the string is preceded by a version
520// identifier, eg:
521//
522// "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
523//
524// (Note that the braces and commas in this example are actual
525// characters the parser expects to find in the file; the ellipses
526// indicate more numbers omitted from this example.)
527//
528// The file may contain multiple keys in this format, separated by
529// commas. The last key must not be followed by a comma.
530//
Doug Zongker30362a62013-04-10 11:32:17 -0700531// A Certificate is a pair of an RSAPublicKey and a particular hash
532// (we support SHA-1 and SHA-256; we store the hash length to signify
533// which is being used). The hash used is implied by the version number.
534//
535// 1: 2048-bit RSA key with e=3 and SHA-1 hash
536// 2: 2048-bit RSA key with e=65537 and SHA-1 hash
537// 3: 2048-bit RSA key with e=3 and SHA-256 hash
538// 4: 2048-bit RSA key with e=65537 and SHA-256 hash
Kenny Root7a4adb52013-10-09 10:14:35 -0700539// 5: 256-bit EC key using the NIST P-256 curve parameters and SHA-256 hash
Doug Zongker30362a62013-04-10 11:32:17 -0700540//
Tao Bao71e3e092016-02-02 14:02:27 -0800541// Returns true on success, and appends the found keys (at least one) to certs.
542// Otherwise returns false if the file failed to parse, or if it contains zero
543// keys. The contents in certs would be unspecified on failure.
544bool load_keys(const char* filename, std::vector<Certificate>& certs) {
Tianjie Xude6735e2017-07-10 15:13:33 -0700545 std::unique_ptr<FILE, decltype(&fclose)> f(fopen(filename, "re"), fclose);
546 if (!f) {
547 PLOG(ERROR) << "error opening " << filename;
548 return false;
549 }
550
551 while (true) {
552 certs.emplace_back(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
553 Certificate& cert = certs.back();
554 uint32_t exponent = 0;
555
556 char start_char;
557 if (fscanf(f.get(), " %c", &start_char) != 1) return false;
558 if (start_char == '{') {
559 // a version 1 key has no version specifier.
560 cert.key_type = Certificate::KEY_TYPE_RSA;
561 exponent = 3;
562 cert.hash_len = SHA_DIGEST_LENGTH;
563 } else if (start_char == 'v') {
564 int version;
565 if (fscanf(f.get(), "%d {", &version) != 1) return false;
566 switch (version) {
567 case 2:
568 cert.key_type = Certificate::KEY_TYPE_RSA;
569 exponent = 65537;
570 cert.hash_len = SHA_DIGEST_LENGTH;
571 break;
572 case 3:
573 cert.key_type = Certificate::KEY_TYPE_RSA;
574 exponent = 3;
575 cert.hash_len = SHA256_DIGEST_LENGTH;
576 break;
577 case 4:
578 cert.key_type = Certificate::KEY_TYPE_RSA;
579 exponent = 65537;
580 cert.hash_len = SHA256_DIGEST_LENGTH;
581 break;
582 case 5:
583 cert.key_type = Certificate::KEY_TYPE_EC;
584 cert.hash_len = SHA256_DIGEST_LENGTH;
585 break;
586 default:
587 return false;
588 }
589 }
590
591 if (cert.key_type == Certificate::KEY_TYPE_RSA) {
592 cert.rsa = parse_rsa_key(f.get(), exponent);
593 if (!cert.rsa) {
Tao Bao71e3e092016-02-02 14:02:27 -0800594 return false;
Tianjie Xude6735e2017-07-10 15:13:33 -0700595 }
596
597 LOG(INFO) << "read key e=" << exponent << " hash=" << cert.hash_len;
598 } else if (cert.key_type == Certificate::KEY_TYPE_EC) {
599 cert.ec = parse_ec_key(f.get());
600 if (!cert.ec) {
601 return false;
602 }
603 } else {
604 LOG(ERROR) << "Unknown key type " << cert.key_type;
605 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700606 }
607
Tianjie Xude6735e2017-07-10 15:13:33 -0700608 // if the line ends in a comma, this file has more keys.
609 int ch = fgetc(f.get());
610 if (ch == ',') {
611 // more keys to come.
612 continue;
613 } else if (ch == EOF) {
614 break;
615 } else {
616 LOG(ERROR) << "unexpected character between keys";
617 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700618 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700619 }
620 return true;
Doug Zongker6c249f72012-11-02 15:04:05 -0700621}