blob: c4cd612c7a5854782ca7c8d931753a412156e55c [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
Doug Zongker54e2e862009-08-17 13:21:04 -070017#include <errno.h>
Elliott Hughes26dbad22015-01-28 12:09:05 -080018#include <malloc.h>
19#include <stdio.h>
20#include <string.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080021
Elliott Hughes8febafa2016-04-13 16:39:56 -070022#include <algorithm>
23#include <memory>
24
25#include <openssl/ecdsa.h>
26#include <openssl/obj_mac.h>
27
28#include "asn1_decoder.h"
29#include "common.h"
Tao Baoe1792762016-04-19 22:31:01 -070030#include "print_sha1.h"
Elliott Hughes8febafa2016-04-13 16:39:56 -070031#include "ui.h"
32#include "verifier.h"
33
Dees_Troy2673cec2013-04-02 20:22:16 +000034//extern RecoveryUI* ui;
35
36#define PUBLIC_KEYS_FILE "/res/keys"
37
Elliott Hughes8febafa2016-04-13 16:39:56 -070038static constexpr size_t MiB = 1024 * 1024;
39
Kenny Root7a4adb52013-10-09 10:14:35 -070040/*
41 * Simple version of PKCS#7 SignedData extraction. This extracts the
42 * signature OCTET STRING to be used for signature verification.
43 *
44 * For full details, see http://www.ietf.org/rfc/rfc3852.txt
45 *
46 * The PKCS#7 structure looks like:
47 *
48 * SEQUENCE (ContentInfo)
49 * OID (ContentType)
50 * [0] (content)
51 * SEQUENCE (SignedData)
52 * INTEGER (version CMSVersion)
53 * SET (DigestAlgorithmIdentifiers)
54 * SEQUENCE (EncapsulatedContentInfo)
55 * [0] (CertificateSet OPTIONAL)
56 * [1] (RevocationInfoChoices OPTIONAL)
57 * SET (SignerInfos)
58 * SEQUENCE (SignerInfo)
59 * INTEGER (CMSVersion)
60 * SEQUENCE (SignerIdentifier)
61 * SEQUENCE (DigestAlgorithmIdentifier)
62 * SEQUENCE (SignatureAlgorithmIdentifier)
63 * OCTET STRING (SignatureValue)
64 */
65static bool read_pkcs7(uint8_t* pkcs7_der, size_t pkcs7_der_len, uint8_t** sig_der,
66 size_t* sig_der_length) {
67 asn1_context_t* ctx = asn1_context_new(pkcs7_der, pkcs7_der_len);
68 if (ctx == NULL) {
69 return false;
70 }
71
72 asn1_context_t* pkcs7_seq = asn1_sequence_get(ctx);
73 if (pkcs7_seq != NULL && asn1_sequence_next(pkcs7_seq)) {
74 asn1_context_t *signed_data_app = asn1_constructed_get(pkcs7_seq);
75 if (signed_data_app != NULL) {
76 asn1_context_t* signed_data_seq = asn1_sequence_get(signed_data_app);
77 if (signed_data_seq != NULL
78 && asn1_sequence_next(signed_data_seq)
79 && asn1_sequence_next(signed_data_seq)
80 && asn1_sequence_next(signed_data_seq)
81 && asn1_constructed_skip_all(signed_data_seq)) {
82 asn1_context_t *sig_set = asn1_set_get(signed_data_seq);
83 if (sig_set != NULL) {
84 asn1_context_t* sig_seq = asn1_sequence_get(sig_set);
85 if (sig_seq != NULL
86 && asn1_sequence_next(sig_seq)
87 && asn1_sequence_next(sig_seq)
88 && asn1_sequence_next(sig_seq)
89 && asn1_sequence_next(sig_seq)) {
90 uint8_t* sig_der_ptr;
91 if (asn1_octet_string_get(sig_seq, &sig_der_ptr, sig_der_length)) {
92 *sig_der = (uint8_t*) malloc(*sig_der_length);
93 if (*sig_der != NULL) {
94 memcpy(*sig_der, sig_der_ptr, *sig_der_length);
95 }
96 }
97 asn1_context_free(sig_seq);
98 }
99 asn1_context_free(sig_set);
100 }
101 asn1_context_free(signed_data_seq);
102 }
103 asn1_context_free(signed_data_app);
104 }
105 asn1_context_free(pkcs7_seq);
106 }
107 asn1_context_free(ctx);
108
109 return *sig_der != NULL;
110}
111
Doug Zongker54e2e862009-08-17 13:21:04 -0700112// Look for an RSA signature embedded in the .ZIP file comment given
113// the path to the zip. Verify it matches one of the given public
114// keys.
115//
116// Return VERIFY_SUCCESS, VERIFY_FAILURE (if any error is encountered
117// or no key matches the signature).
118
Ethan Yonkera1674162014-11-06 08:35:10 -0600119int verify_file(unsigned char* addr, size_t length) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000120 //ui->SetProgress(0.0);
Doug Zongker54e2e862009-08-17 13:21:04 -0700121
Ethan Yonker34ae4832016-08-24 15:32:18 -0500122 std::vector<Certificate> keys;
123 if (!load_keys(PUBLIC_KEYS_FILE, keys)) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000124 LOGE("Failed to load keys\n");
Dees Troybb4c0cb2013-11-02 20:25:14 +0000125 return INSTALL_CORRUPT;
Dees_Troy2673cec2013-04-02 20:22:16 +0000126 }
Ethan Yonker34ae4832016-08-24 15:32:18 -0500127 LOGI("%d key(s) loaded from %s\n", keys.size(), PUBLIC_KEYS_FILE);
Doug Zongker54e2e862009-08-17 13:21:04 -0700128
Doug Zongker54e2e862009-08-17 13:21:04 -0700129 // An archive with a whole-file signature will end in six bytes:
130 //
Doug Zongker73ae31c2009-12-09 17:01:45 -0800131 // (2-byte signature start) $ff $ff (2-byte comment size)
Doug Zongker54e2e862009-08-17 13:21:04 -0700132 //
133 // (As far as the ZIP format is concerned, these are part of the
134 // archive comment.) We start by reading this footer, this tells
135 // us how far back from the end we have to start reading to find
136 // the whole comment.
137
138#define FOOTER_SIZE 6
139
Doug Zongker99916f02014-01-13 14:16:58 -0800140 if (length < FOOTER_SIZE) {
141 LOGE("not big enough to contain footer\n");
Doug Zongker54e2e862009-08-17 13:21:04 -0700142 return VERIFY_FAILURE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800143 }
144
Doug Zongker99916f02014-01-13 14:16:58 -0800145 unsigned char* footer = addr + length - FOOTER_SIZE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800146
Doug Zongker54e2e862009-08-17 13:21:04 -0700147 if (footer[2] != 0xff || footer[3] != 0xff) {
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700148 LOGE("footer is wrong\n");
Doug Zongker54e2e862009-08-17 13:21:04 -0700149 return VERIFY_FAILURE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800150 }
151
Doug Zongker28ce47c2011-10-28 10:33:05 -0700152 size_t comment_size = footer[4] + (footer[5] << 8);
153 size_t signature_start = footer[0] + (footer[1] << 8);
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700154 LOGI("comment is %zu bytes; signature %zu bytes from end\n",
Doug Zongker54e2e862009-08-17 13:21:04 -0700155 comment_size, signature_start);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800156
Kenny Root7a4adb52013-10-09 10:14:35 -0700157 if (signature_start <= FOOTER_SIZE) {
158 LOGE("Signature start is in the footer");
Doug Zongker54e2e862009-08-17 13:21:04 -0700159 return VERIFY_FAILURE;
160 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800161
Doug Zongker54e2e862009-08-17 13:21:04 -0700162#define EOCD_HEADER_SIZE 22
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800163
Doug Zongker54e2e862009-08-17 13:21:04 -0700164 // The end-of-central-directory record is 22 bytes plus any
165 // comment length.
166 size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800167
Doug Zongker99916f02014-01-13 14:16:58 -0800168 if (length < eocd_size) {
169 LOGE("not big enough to contain EOCD\n");
Doug Zongker54e2e862009-08-17 13:21:04 -0700170 return VERIFY_FAILURE;
171 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800172
Doug Zongker54e2e862009-08-17 13:21:04 -0700173 // Determine how much of the file is covered by the signature.
174 // This is everything except the signature data and length, which
175 // includes all of the EOCD except for the comment length field (2
176 // bytes) and the comment data.
Doug Zongker99916f02014-01-13 14:16:58 -0800177 size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800178
Doug Zongker99916f02014-01-13 14:16:58 -0800179 unsigned char* eocd = addr + length - eocd_size;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800180
Doug Zongker54e2e862009-08-17 13:21:04 -0700181 // If this is really is the EOCD record, it will begin with the
182 // magic number $50 $4b $05 $06.
183 if (eocd[0] != 0x50 || eocd[1] != 0x4b ||
184 eocd[2] != 0x05 || eocd[3] != 0x06) {
185 LOGE("signature length doesn't match EOCD marker\n");
Doug Zongker54e2e862009-08-17 13:21:04 -0700186 return VERIFY_FAILURE;
187 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800188
Tao Bao71e3e092016-02-02 14:02:27 -0800189 for (size_t i = 4; i < eocd_size-3; ++i) {
Doug Zongker54e2e862009-08-17 13:21:04 -0700190 if (eocd[i ] == 0x50 && eocd[i+1] == 0x4b &&
Doug Zongkerc652e412009-12-08 15:30:09 -0800191 eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
Doug Zongker54e2e862009-08-17 13:21:04 -0700192 // if the sequence $50 $4b $05 $06 appears anywhere after
193 // the real one, minzip will find the later (wrong) one,
194 // which could be exploitable. Fail verification if
195 // this sequence occurs anywhere after the real one.
196 LOGE("EOCD marker occurs after start of EOCD\n");
Doug Zongker54e2e862009-08-17 13:21:04 -0700197 return VERIFY_FAILURE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800198 }
199 }
200
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700201 bool need_sha1 = false;
202 bool need_sha256 = false;
Tao Bao71e3e092016-02-02 14:02:27 -0800203 for (const auto& key : keys) {
204 switch (key.hash_len) {
Elliott Hughes8febafa2016-04-13 16:39:56 -0700205 case SHA_DIGEST_LENGTH: need_sha1 = true; break;
206 case SHA256_DIGEST_LENGTH: need_sha256 = true; break;
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700207 }
208 }
209
210 SHA_CTX sha1_ctx;
211 SHA256_CTX sha256_ctx;
Elliott Hughes8febafa2016-04-13 16:39:56 -0700212 SHA1_Init(&sha1_ctx);
213 SHA256_Init(&sha256_ctx);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800214
Doug Zongker54e2e862009-08-17 13:21:04 -0700215 double frac = -1.0;
216 size_t so_far = 0;
Doug Zongker54e2e862009-08-17 13:21:04 -0700217 while (so_far < signed_len) {
Elliott Hughesdd895d02016-04-19 15:24:38 -0700218 // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a
219 // 1196MiB full OTA and 60% for an 89MiB incremental OTA.
220 // http://b/28135231.
221 size_t size = std::min(signed_len - so_far, 16 * MiB);
Doug Zongker99916f02014-01-13 14:16:58 -0800222
Elliott Hughes8febafa2016-04-13 16:39:56 -0700223 if (need_sha1) SHA1_Update(&sha1_ctx, addr + so_far, size);
224 if (need_sha256) SHA256_Update(&sha256_ctx, addr + so_far, size);
Doug Zongker54e2e862009-08-17 13:21:04 -0700225 so_far += size;
Doug Zongker99916f02014-01-13 14:16:58 -0800226
Doug Zongker54e2e862009-08-17 13:21:04 -0700227 double f = so_far / (double)signed_len;
228 if (f > frac + 0.02 || size == so_far) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000229 //ui->SetProgress(f);
Doug Zongker54e2e862009-08-17 13:21:04 -0700230 frac = f;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800231 }
232 }
233
Elliott Hughes8febafa2016-04-13 16:39:56 -0700234 uint8_t sha1[SHA_DIGEST_LENGTH];
235 SHA1_Final(sha1, &sha1_ctx);
236 uint8_t sha256[SHA256_DIGEST_LENGTH];
237 SHA256_Final(sha256, &sha256_ctx);
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700238
Tao Bao71e3e092016-02-02 14:02:27 -0800239 uint8_t* sig_der = nullptr;
Kenny Root7a4adb52013-10-09 10:14:35 -0700240 size_t sig_der_length = 0;
241
Tao Baoe1792762016-04-19 22:31:01 -0700242 uint8_t* signature = eocd + eocd_size - signature_start;
Kenny Root7a4adb52013-10-09 10:14:35 -0700243 size_t signature_size = signature_start - FOOTER_SIZE;
Tao Baoe1792762016-04-19 22:31:01 -0700244
245 LOGI("signature (offset: 0x%zx, length: %zu): %s\n",
246 length - signature_start, signature_size,
247 print_hex(signature, signature_size).c_str());
248
249 if (!read_pkcs7(signature, signature_size, &sig_der, &sig_der_length)) {
Kenny Root7a4adb52013-10-09 10:14:35 -0700250 LOGE("Could not find signature DER block\n");
Kenny Root7a4adb52013-10-09 10:14:35 -0700251 return VERIFY_FAILURE;
252 }
Kenny Root7a4adb52013-10-09 10:14:35 -0700253
254 /*
255 * Check to make sure at least one of the keys matches the signature. Since
256 * any key can match, we need to try each before determining a verification
257 * failure has happened.
258 */
Tao Bao71e3e092016-02-02 14:02:27 -0800259 size_t i = 0;
260 for (const auto& key : keys) {
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700261 const uint8_t* hash;
Elliott Hughes8febafa2016-04-13 16:39:56 -0700262 int hash_nid;
Tao Bao71e3e092016-02-02 14:02:27 -0800263 switch (key.hash_len) {
Elliott Hughes8febafa2016-04-13 16:39:56 -0700264 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;
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700274 }
275
Doug Zongker73ae31c2009-12-09 17:01:45 -0800276 // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that
Doug Zongker54e2e862009-08-17 13:21:04 -0700277 // the signing tool appends after the signature itself.
Elliott Hughes8febafa2016-04-13 16:39:56 -0700278 if (key.key_type == Certificate::KEY_TYPE_RSA) {
279 if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der,
280 sig_der_length, key.rsa.get())) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700281 LOGI("failed to verify against RSA key %zu\n", i);
Kenny Root7a4adb52013-10-09 10:14:35 -0700282 continue;
283 }
284
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700285 LOGI("whole-file signature verified against RSA key %zu\n", i);
Kenny Root7a4adb52013-10-09 10:14:35 -0700286 free(sig_der);
287 return VERIFY_SUCCESS;
Elliott Hughes8febafa2016-04-13 16:39:56 -0700288 } else if (key.key_type == Certificate::KEY_TYPE_EC
289 && key.hash_len == SHA256_DIGEST_LENGTH) {
290 if (!ECDSA_verify(0, hash, key.hash_len, sig_der,
291 sig_der_length, key.ec.get())) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700292 LOGI("failed to verify against EC key %zu\n", i);
Kenny Root7a4adb52013-10-09 10:14:35 -0700293 continue;
294 }
295
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700296 LOGI("whole-file signature verified against EC key %zu\n", i);
Kenny Root7a4adb52013-10-09 10:14:35 -0700297 free(sig_der);
Doug Zongker54e2e862009-08-17 13:21:04 -0700298 return VERIFY_SUCCESS;
Doug Zongker6c249f72012-11-02 15:04:05 -0700299 } else {
Tao Bao71e3e092016-02-02 14:02:27 -0800300 LOGI("Unknown key type %d\n", key.key_type);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800301 }
Tao Bao71e3e092016-02-02 14:02:27 -0800302 i++;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800303 }
Tao Baoe1792762016-04-19 22:31:01 -0700304
305 if (need_sha1) {
306 LOGI("SHA-1 digest: %s\n", print_hex(sha1, SHA_DIGEST_LENGTH).c_str());
307 }
308 if (need_sha256) {
309 LOGI("SHA-256 digest: %s\n", print_hex(sha256, SHA256_DIGEST_LENGTH).c_str());
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800310 }
Kenny Root7a4adb52013-10-09 10:14:35 -0700311 free(sig_der);
Doug Zongker54e2e862009-08-17 13:21:04 -0700312 LOGE("failed to verify whole-file signature\n");
313 return VERIFY_FAILURE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800314}
Doug Zongker6c249f72012-11-02 15:04:05 -0700315
Elliott Hughes8febafa2016-04-13 16:39:56 -0700316std::unique_ptr<RSA, RSADeleter> parse_rsa_key(FILE* file, uint32_t exponent) {
317 // Read key length in words and n0inv. n0inv is a precomputed montgomery
318 // parameter derived from the modulus and can be used to speed up
319 // verification. n0inv is 32 bits wide here, assuming the verification logic
320 // uses 32 bit arithmetic. However, BoringSSL may use a word size of 64 bits
321 // internally, in which case we don't have a valid n0inv. Thus, we just
322 // ignore the montgomery parameters and have BoringSSL recompute them
323 // internally. If/When the speedup from using the montgomery parameters
324 // becomes relevant, we can add more sophisticated code here to obtain a
325 // 64-bit n0inv and initialize the montgomery parameters in the key object.
326 uint32_t key_len_words = 0;
327 uint32_t n0inv = 0;
328 if (fscanf(file, " %i , 0x%x", &key_len_words, &n0inv) != 2) {
329 return nullptr;
330 }
331
332 if (key_len_words > 8192 / 32) {
333 LOGE("key length (%d) too large\n", key_len_words);
334 return nullptr;
335 }
336
337 // Read the modulus.
338 std::unique_ptr<uint32_t[]> modulus(new uint32_t[key_len_words]);
339 if (fscanf(file, " , { %u", &modulus[0]) != 1) {
340 return nullptr;
341 }
342 for (uint32_t i = 1; i < key_len_words; ++i) {
343 if (fscanf(file, " , %u", &modulus[i]) != 1) {
344 return nullptr;
345 }
346 }
347
348 // Cconvert from little-endian array of little-endian words to big-endian
349 // byte array suitable as input for BN_bin2bn.
350 std::reverse((uint8_t*)modulus.get(),
351 (uint8_t*)(modulus.get() + key_len_words));
352
353 // The next sequence of values is the montgomery parameter R^2. Since we
354 // generally don't have a valid |n0inv|, we ignore this (see comment above).
355 uint32_t rr_value;
356 if (fscanf(file, " } , { %u", &rr_value) != 1) {
357 return nullptr;
358 }
359 for (uint32_t i = 1; i < key_len_words; ++i) {
360 if (fscanf(file, " , %u", &rr_value) != 1) {
361 return nullptr;
362 }
363 }
364 if (fscanf(file, " } } ") != 0) {
365 return nullptr;
366 }
367
368 // Initialize the key.
369 std::unique_ptr<RSA, RSADeleter> key(RSA_new());
370 if (!key) {
371 return nullptr;
372 }
373
374 key->n = BN_bin2bn((uint8_t*)modulus.get(),
375 key_len_words * sizeof(uint32_t), NULL);
376 if (!key->n) {
377 return nullptr;
378 }
379
380 key->e = BN_new();
381 if (!key->e || !BN_set_word(key->e, exponent)) {
382 return nullptr;
383 }
384
385 return key;
386}
387
388struct BNDeleter {
389 void operator()(BIGNUM* bn) {
390 BN_free(bn);
391 }
392};
393
394std::unique_ptr<EC_KEY, ECKEYDeleter> parse_ec_key(FILE* file) {
395 uint32_t key_len_bytes = 0;
396 if (fscanf(file, " %i", &key_len_bytes) != 1) {
397 return nullptr;
398 }
399
400 std::unique_ptr<EC_GROUP, void (*)(EC_GROUP*)> group(
401 EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1), EC_GROUP_free);
402 if (!group) {
403 return nullptr;
404 }
405
406 // Verify that |key_len| matches the group order.
407 if (key_len_bytes != BN_num_bytes(EC_GROUP_get0_order(group.get()))) {
408 return nullptr;
409 }
410
411 // Read the public key coordinates. Note that the byte order in the file is
412 // little-endian, so we convert to big-endian here.
413 std::unique_ptr<uint8_t[]> bytes(new uint8_t[key_len_bytes]);
414 std::unique_ptr<BIGNUM, BNDeleter> point[2];
415 for (int i = 0; i < 2; ++i) {
416 unsigned int byte = 0;
417 if (fscanf(file, " , { %u", &byte) != 1) {
418 return nullptr;
419 }
420 bytes[key_len_bytes - 1] = byte;
421
422 for (size_t i = 1; i < key_len_bytes; ++i) {
423 if (fscanf(file, " , %u", &byte) != 1) {
424 return nullptr;
425 }
426 bytes[key_len_bytes - i - 1] = byte;
427 }
428
429 point[i].reset(BN_bin2bn(bytes.get(), key_len_bytes, nullptr));
430 if (!point[i]) {
431 return nullptr;
432 }
433
434 if (fscanf(file, " }") != 0) {
435 return nullptr;
436 }
437 }
438
439 if (fscanf(file, " } ") != 0) {
440 return nullptr;
441 }
442
443 // Create and initialize the key.
444 std::unique_ptr<EC_KEY, ECKEYDeleter> key(EC_KEY_new());
445 if (!key || !EC_KEY_set_group(key.get(), group.get()) ||
446 !EC_KEY_set_public_key_affine_coordinates(key.get(), point[0].get(),
447 point[1].get())) {
448 return nullptr;
449 }
450
451 return key;
452}
453
Doug Zongker6c249f72012-11-02 15:04:05 -0700454// Reads a file containing one or more public keys as produced by
455// DumpPublicKey: this is an RSAPublicKey struct as it would appear
456// as a C source literal, eg:
457//
458// "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
459//
460// For key versions newer than the original 2048-bit e=3 keys
461// supported by Android, the string is preceded by a version
462// identifier, eg:
463//
464// "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
465//
466// (Note that the braces and commas in this example are actual
467// characters the parser expects to find in the file; the ellipses
468// indicate more numbers omitted from this example.)
469//
470// The file may contain multiple keys in this format, separated by
471// commas. The last key must not be followed by a comma.
472//
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700473// A Certificate is a pair of an RSAPublicKey and a particular hash
474// (we support SHA-1 and SHA-256; we store the hash length to signify
475// which is being used). The hash used is implied by the version number.
476//
477// 1: 2048-bit RSA key with e=3 and SHA-1 hash
478// 2: 2048-bit RSA key with e=65537 and SHA-1 hash
479// 3: 2048-bit RSA key with e=3 and SHA-256 hash
480// 4: 2048-bit RSA key with e=65537 and SHA-256 hash
Kenny Root7a4adb52013-10-09 10:14:35 -0700481// 5: 256-bit EC key using the NIST P-256 curve parameters and SHA-256 hash
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700482//
Tao Bao71e3e092016-02-02 14:02:27 -0800483// Returns true on success, and appends the found keys (at least one) to certs.
484// Otherwise returns false if the file failed to parse, or if it contains zero
485// keys. The contents in certs would be unspecified on failure.
486bool load_keys(const char* filename, std::vector<Certificate>& certs) {
487 std::unique_ptr<FILE, decltype(&fclose)> f(fopen(filename, "r"), fclose);
488 if (!f) {
Doug Zongker6c249f72012-11-02 15:04:05 -0700489 LOGE("opening %s: %s\n", filename, strerror(errno));
Tao Bao71e3e092016-02-02 14:02:27 -0800490 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700491 }
492
Tao Bao71e3e092016-02-02 14:02:27 -0800493 while (true) {
Elliott Hughes8febafa2016-04-13 16:39:56 -0700494 certs.emplace_back(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
Tao Bao71e3e092016-02-02 14:02:27 -0800495 Certificate& cert = certs.back();
Elliott Hughes8febafa2016-04-13 16:39:56 -0700496 uint32_t exponent = 0;
Doug Zongker6c249f72012-11-02 15:04:05 -0700497
Tao Bao71e3e092016-02-02 14:02:27 -0800498 char start_char;
499 if (fscanf(f.get(), " %c", &start_char) != 1) return false;
500 if (start_char == '{') {
501 // a version 1 key has no version specifier.
Elliott Hughes8febafa2016-04-13 16:39:56 -0700502 cert.key_type = Certificate::KEY_TYPE_RSA;
503 exponent = 3;
504 cert.hash_len = SHA_DIGEST_LENGTH;
Tao Bao71e3e092016-02-02 14:02:27 -0800505 } else if (start_char == 'v') {
506 int version;
507 if (fscanf(f.get(), "%d {", &version) != 1) return false;
508 switch (version) {
509 case 2:
Elliott Hughes8febafa2016-04-13 16:39:56 -0700510 cert.key_type = Certificate::KEY_TYPE_RSA;
511 exponent = 65537;
512 cert.hash_len = SHA_DIGEST_LENGTH;
Tao Bao71e3e092016-02-02 14:02:27 -0800513 break;
514 case 3:
Elliott Hughes8febafa2016-04-13 16:39:56 -0700515 cert.key_type = Certificate::KEY_TYPE_RSA;
516 exponent = 3;
517 cert.hash_len = SHA256_DIGEST_LENGTH;
Tao Bao71e3e092016-02-02 14:02:27 -0800518 break;
519 case 4:
Elliott Hughes8febafa2016-04-13 16:39:56 -0700520 cert.key_type = Certificate::KEY_TYPE_RSA;
521 exponent = 65537;
522 cert.hash_len = SHA256_DIGEST_LENGTH;
Tao Bao71e3e092016-02-02 14:02:27 -0800523 break;
524 case 5:
Elliott Hughes8febafa2016-04-13 16:39:56 -0700525 cert.key_type = Certificate::KEY_TYPE_EC;
526 cert.hash_len = SHA256_DIGEST_LENGTH;
Tao Bao71e3e092016-02-02 14:02:27 -0800527 break;
528 default:
529 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700530 }
Tao Bao71e3e092016-02-02 14:02:27 -0800531 }
Doug Zongker6c249f72012-11-02 15:04:05 -0700532
Elliott Hughes8febafa2016-04-13 16:39:56 -0700533 if (cert.key_type == Certificate::KEY_TYPE_RSA) {
534 cert.rsa = parse_rsa_key(f.get(), exponent);
535 if (!cert.rsa) {
536 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700537 }
538
Elliott Hughes8febafa2016-04-13 16:39:56 -0700539 LOGI("read key e=%d hash=%d\n", exponent, cert.hash_len);
540 } else if (cert.key_type == Certificate::KEY_TYPE_EC) {
541 cert.ec = parse_ec_key(f.get());
542 if (!cert.ec) {
543 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700544 }
Tao Bao71e3e092016-02-02 14:02:27 -0800545 } else {
546 LOGE("Unknown key type %d\n", cert.key_type);
547 return false;
548 }
Doug Zongker6c249f72012-11-02 15:04:05 -0700549
Tao Bao71e3e092016-02-02 14:02:27 -0800550 // if the line ends in a comma, this file has more keys.
551 int ch = fgetc(f.get());
552 if (ch == ',') {
553 // more keys to come.
554 continue;
555 } else if (ch == EOF) {
556 break;
557 } else {
558 LOGE("unexpected character between keys\n");
559 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700560 }
561 }
562
Tao Bao71e3e092016-02-02 14:02:27 -0800563 return true;
Doug Zongker6c249f72012-11-02 15:04:05 -0700564}