blob: 2dfc208083d4df2f39f054fb1f5abb8bd1abce13 [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 Xub5110de2018-10-23 23:31:43 -0700503bool CheckRSAKey(const std::unique_ptr<RSA, RSADeleter>& rsa) {
504 if (!rsa) {
505 return false;
506 }
507
508 const BIGNUM* out_n;
509 const BIGNUM* out_e;
510 RSA_get0_key(rsa.get(), &out_n, &out_e, nullptr /* private exponent */);
511 auto modulus_bits = BN_num_bits(out_n);
512 if (modulus_bits != 2048) {
513 LOG(ERROR) << "Modulus should be 2048 bits long, actual: " << modulus_bits;
514 return false;
515 }
516
517 BN_ULONG exponent = BN_get_word(out_e);
518 if (exponent != 3 && exponent != 65537) {
519 LOG(ERROR) << "Public exponent should be 3 or 65537, actual: " << exponent;
520 return false;
521 }
522
523 return true;
524}
525
526bool CheckECKey(const std::unique_ptr<EC_KEY, ECKEYDeleter>& ec_key) {
527 if (!ec_key) {
528 return false;
529 }
530
531 const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key.get());
532 if (!ec_group) {
533 LOG(ERROR) << "Failed to get the ec_group from the ec_key";
534 return false;
535 }
536 auto degree = EC_GROUP_get_degree(ec_group);
537 if (degree != 256) {
538 LOG(ERROR) << "Field size of the ec key should be 256 bits long, actual: " << degree;
539 return false;
540 }
541
542 return true;
543}
544
Tianjie Xu82566982018-10-10 15:44:17 -0700545bool LoadCertificateFromBuffer(const std::vector<uint8_t>& pem_content, Certificate* cert) {
546 std::unique_ptr<BIO, decltype(&BIO_free)> content(
547 BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free);
548
549 std::unique_ptr<X509, decltype(&X509_free)> x509(
550 PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free);
551 if (!x509) {
552 LOG(ERROR) << "Failed to read x509 certificate";
553 return false;
554 }
555
556 int nid = X509_get_signature_nid(x509.get());
557 switch (nid) {
558 // SignApk has historically accepted md5WithRSA certificates, but treated them as
559 // sha1WithRSA anyway. Continue to do so for backwards compatibility.
560 case NID_md5WithRSA:
561 case NID_md5WithRSAEncryption:
562 case NID_sha1WithRSA:
563 case NID_sha1WithRSAEncryption:
564 cert->hash_len = SHA_DIGEST_LENGTH;
565 break;
566 case NID_sha256WithRSAEncryption:
567 case NID_ecdsa_with_SHA256:
568 cert->hash_len = SHA256_DIGEST_LENGTH;
569 break;
570 default:
571 LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid);
572 return false;
573 }
574
575 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> public_key(X509_get_pubkey(x509.get()),
576 EVP_PKEY_free);
577 if (!public_key) {
578 LOG(ERROR) << "Failed to extract the public key from x509 certificate";
579 return false;
580 }
581
582 int key_type = EVP_PKEY_id(public_key.get());
Tianjie Xu82566982018-10-10 15:44:17 -0700583 if (key_type == EVP_PKEY_RSA) {
584 cert->key_type = Certificate::KEY_TYPE_RSA;
585 cert->ec.reset();
586 cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get()));
Tianjie Xub5110de2018-10-23 23:31:43 -0700587 if (!cert->rsa || !CheckRSAKey(cert->rsa)) {
588 LOG(ERROR) << "Failed to validate the rsa key info from public key";
Tianjie Xu82566982018-10-10 15:44:17 -0700589 return false;
590 }
591 } else if (key_type == EVP_PKEY_EC) {
592 cert->key_type = Certificate::KEY_TYPE_EC;
593 cert->rsa.reset();
594 cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get()));
Tianjie Xub5110de2018-10-23 23:31:43 -0700595 if (!cert->ec || !CheckECKey(cert->ec)) {
596 LOG(ERROR) << "Failed to validate the ec key info from the public key";
Tianjie Xu82566982018-10-10 15:44:17 -0700597 return false;
598 }
599 } else {
600 LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type);
601 return false;
602 }
603
604 return true;
605}
606
Doug Zongker6c249f72012-11-02 15:04:05 -0700607// Reads a file containing one or more public keys as produced by
608// DumpPublicKey: this is an RSAPublicKey struct as it would appear
609// as a C source literal, eg:
610//
611// "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
612//
613// For key versions newer than the original 2048-bit e=3 keys
614// supported by Android, the string is preceded by a version
615// identifier, eg:
616//
617// "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
618//
619// (Note that the braces and commas in this example are actual
620// characters the parser expects to find in the file; the ellipses
621// indicate more numbers omitted from this example.)
622//
623// The file may contain multiple keys in this format, separated by
624// commas. The last key must not be followed by a comma.
625//
Doug Zongker30362a62013-04-10 11:32:17 -0700626// A Certificate is a pair of an RSAPublicKey and a particular hash
627// (we support SHA-1 and SHA-256; we store the hash length to signify
628// which is being used). The hash used is implied by the version number.
629//
630// 1: 2048-bit RSA key with e=3 and SHA-1 hash
631// 2: 2048-bit RSA key with e=65537 and SHA-1 hash
632// 3: 2048-bit RSA key with e=3 and SHA-256 hash
633// 4: 2048-bit RSA key with e=65537 and SHA-256 hash
Kenny Root7a4adb52013-10-09 10:14:35 -0700634// 5: 256-bit EC key using the NIST P-256 curve parameters and SHA-256 hash
Doug Zongker30362a62013-04-10 11:32:17 -0700635//
Tao Bao71e3e092016-02-02 14:02:27 -0800636// Returns true on success, and appends the found keys (at least one) to certs.
637// Otherwise returns false if the file failed to parse, or if it contains zero
638// keys. The contents in certs would be unspecified on failure.
639bool load_keys(const char* filename, std::vector<Certificate>& certs) {
Tianjie Xude6735e2017-07-10 15:13:33 -0700640 std::unique_ptr<FILE, decltype(&fclose)> f(fopen(filename, "re"), fclose);
641 if (!f) {
642 PLOG(ERROR) << "error opening " << filename;
643 return false;
644 }
645
646 while (true) {
647 certs.emplace_back(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
648 Certificate& cert = certs.back();
649 uint32_t exponent = 0;
650
651 char start_char;
652 if (fscanf(f.get(), " %c", &start_char) != 1) return false;
653 if (start_char == '{') {
654 // a version 1 key has no version specifier.
655 cert.key_type = Certificate::KEY_TYPE_RSA;
656 exponent = 3;
657 cert.hash_len = SHA_DIGEST_LENGTH;
658 } else if (start_char == 'v') {
659 int version;
660 if (fscanf(f.get(), "%d {", &version) != 1) return false;
661 switch (version) {
662 case 2:
663 cert.key_type = Certificate::KEY_TYPE_RSA;
664 exponent = 65537;
665 cert.hash_len = SHA_DIGEST_LENGTH;
666 break;
667 case 3:
668 cert.key_type = Certificate::KEY_TYPE_RSA;
669 exponent = 3;
670 cert.hash_len = SHA256_DIGEST_LENGTH;
671 break;
672 case 4:
673 cert.key_type = Certificate::KEY_TYPE_RSA;
674 exponent = 65537;
675 cert.hash_len = SHA256_DIGEST_LENGTH;
676 break;
677 case 5:
678 cert.key_type = Certificate::KEY_TYPE_EC;
679 cert.hash_len = SHA256_DIGEST_LENGTH;
680 break;
681 default:
682 return false;
683 }
684 }
685
686 if (cert.key_type == Certificate::KEY_TYPE_RSA) {
687 cert.rsa = parse_rsa_key(f.get(), exponent);
688 if (!cert.rsa) {
Tao Bao71e3e092016-02-02 14:02:27 -0800689 return false;
Tianjie Xude6735e2017-07-10 15:13:33 -0700690 }
691
692 LOG(INFO) << "read key e=" << exponent << " hash=" << cert.hash_len;
693 } else if (cert.key_type == Certificate::KEY_TYPE_EC) {
694 cert.ec = parse_ec_key(f.get());
695 if (!cert.ec) {
696 return false;
697 }
698 } else {
699 LOG(ERROR) << "Unknown key type " << cert.key_type;
700 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700701 }
702
Tianjie Xude6735e2017-07-10 15:13:33 -0700703 // if the line ends in a comma, this file has more keys.
704 int ch = fgetc(f.get());
705 if (ch == ',') {
706 // more keys to come.
707 continue;
708 } else if (ch == EOF) {
709 break;
710 } else {
711 LOG(ERROR) << "unexpected character between keys";
712 return false;
Doug Zongker6c249f72012-11-02 15:04:05 -0700713 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700714 }
715 return true;
Doug Zongker6c249f72012-11-02 15:04:05 -0700716}