blob: f5779619d8f784307ce1210a7b041182d5333234 [file] [log] [blame]
bigbiff1f9e4842020-10-31 11:33:15 -04001/*
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
17#include "twinstall/verifier.h"
18
19#include <errno.h>
20#include <stdio.h>
21#include <stdlib.h>
22#include <string.h>
23
24#include <algorithm>
25#include <functional>
26#include <memory>
27#include <vector>
28
29#include <android-base/logging.h>
30#include <openssl/bio.h>
31#include <openssl/bn.h>
32#include <openssl/ecdsa.h>
33#include <openssl/evp.h>
34#include <openssl/obj_mac.h>
35#include <openssl/pem.h>
36#include <openssl/rsa.h>
37#include <ziparchive/zip_archive.h>
38
39#include "otautil/print_sha1.h"
40#include "private/asn1_decoder.h"
41
42/*
43 * Simple version of PKCS#7 SignedData extraction. This extracts the
44 * signature OCTET STRING to be used for signature verification.
45 *
46 * For full details, see http://www.ietf.org/rfc/rfc3852.txt
47 *
48 * The PKCS#7 structure looks like:
49 *
50 * SEQUENCE (ContentInfo)
51 * OID (ContentType)
52 * [0] (content)
53 * SEQUENCE (SignedData)
54 * INTEGER (version CMSVersion)
55 * SET (DigestAlgorithmIdentifiers)
56 * SEQUENCE (EncapsulatedContentInfo)
57 * [0] (CertificateSet OPTIONAL)
58 * [1] (RevocationInfoChoices OPTIONAL)
59 * SET (SignerInfos)
60 * SEQUENCE (SignerInfo)
61 * INTEGER (CMSVersion)
62 * SEQUENCE (SignerIdentifier)
63 * SEQUENCE (DigestAlgorithmIdentifier)
64 * SEQUENCE (SignatureAlgorithmIdentifier)
65 * OCTET STRING (SignatureValue)
66 */
67static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len,
68 std::vector<uint8_t>* sig_der) {
69 CHECK(sig_der != nullptr);
70 sig_der->clear();
71
72 asn1_context ctx(pkcs7_der, pkcs7_der_len);
73
74 std::unique_ptr<asn1_context> pkcs7_seq(ctx.asn1_sequence_get());
75 if (pkcs7_seq == nullptr || !pkcs7_seq->asn1_sequence_next()) {
76 return false;
77 }
78
79 std::unique_ptr<asn1_context> signed_data_app(pkcs7_seq->asn1_constructed_get());
80 if (signed_data_app == nullptr) {
81 return false;
82 }
83
84 std::unique_ptr<asn1_context> signed_data_seq(signed_data_app->asn1_sequence_get());
85 if (signed_data_seq == nullptr || !signed_data_seq->asn1_sequence_next() ||
86 !signed_data_seq->asn1_sequence_next() || !signed_data_seq->asn1_sequence_next() ||
87 !signed_data_seq->asn1_constructed_skip_all()) {
88 return false;
89 }
90
91 std::unique_ptr<asn1_context> sig_set(signed_data_seq->asn1_set_get());
92 if (sig_set == nullptr) {
93 return false;
94 }
95
96 std::unique_ptr<asn1_context> sig_seq(sig_set->asn1_sequence_get());
97 if (sig_seq == nullptr || !sig_seq->asn1_sequence_next() || !sig_seq->asn1_sequence_next() ||
98 !sig_seq->asn1_sequence_next() || !sig_seq->asn1_sequence_next()) {
99 return false;
100 }
101
102 const uint8_t* sig_der_ptr;
103 size_t sig_der_length;
104 if (!sig_seq->asn1_octet_string_get(&sig_der_ptr, &sig_der_length)) {
105 return false;
106 }
107
108 sig_der->resize(sig_der_length);
109 std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin());
110 return true;
111}
112
113int verify_file(VerifierInterface* package, const std::vector<Certificate>& keys,
114 const std::function<void(float)>& set_progress) {
115 CHECK(package);
116 package->SetProgress(0.0);
117
118 if (set_progress) {
119 set_progress(0.0);
120 }
121
122 // An archive with a whole-file signature will end in six bytes:
123 //
124 // (2-byte signature start) $ff $ff (2-byte comment size)
125 //
126 // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by
127 // reading this footer, this tells us how far back from the end we have to start reading to find
128 // the whole comment.
129
130#define FOOTER_SIZE 6
131 uint64_t length = package->GetPackageSize();
132
133 if (length < FOOTER_SIZE) {
134 LOG(ERROR) << "not big enough to contain footer";
135 return VERIFY_FAILURE;
136 }
137
138 uint8_t footer[FOOTER_SIZE];
139 if (!package->ReadFullyAtOffset(footer, FOOTER_SIZE, length - FOOTER_SIZE)) {
140 LOG(ERROR) << "Failed to read footer";
141 return VERIFY_FAILURE;
142 }
143
144 if (footer[2] != 0xff || footer[3] != 0xff) {
145 LOG(ERROR) << "footer is wrong";
146 return VERIFY_FAILURE;
147 }
148
149 size_t comment_size = footer[4] + (footer[5] << 8);
150 size_t signature_start = footer[0] + (footer[1] << 8);
151 LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start
152 << " bytes from end";
153
154 if (signature_start > comment_size) {
155 LOG(ERROR) << "signature start: " << signature_start
156 << " is larger than comment size: " << comment_size;
157 return VERIFY_FAILURE;
158 }
159
160 if (signature_start <= FOOTER_SIZE) {
161 LOG(ERROR) << "Signature start is in the footer";
162 return VERIFY_FAILURE;
163 }
164
165#define EOCD_HEADER_SIZE 22
166
167 // The end-of-central-directory record is 22 bytes plus any comment length.
168 size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
169
170 if (length < eocd_size) {
171 LOG(ERROR) << "not big enough to contain EOCD";
172 return VERIFY_FAILURE;
173 }
174
175 // Determine how much of the file is covered by the signature. This is everything except the
176 // signature data and length, which includes all of the EOCD except for the comment length field
177 // (2 bytes) and the comment data.
178 uint64_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
179
180 uint8_t eocd[eocd_size];
181 if (!package->ReadFullyAtOffset(eocd, eocd_size, length - eocd_size)) {
182 LOG(ERROR) << "Failed to read EOCD of " << eocd_size << " bytes";
183 return VERIFY_FAILURE;
184 }
185
186 // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06.
187 if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) {
188 LOG(ERROR) << "signature length doesn't match EOCD marker";
189 return VERIFY_FAILURE;
190 }
191
192 for (size_t i = 4; i < eocd_size - 3; ++i) {
193 if (eocd[i] == 0x50 && eocd[i + 1] == 0x4b && eocd[i + 2] == 0x05 && eocd[i + 3] == 0x06) {
194 // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will
195 // find the later (wrong) one, which could be exploitable. Fail the verification if this
196 // sequence occurs anywhere after the real one.
197 LOG(ERROR) << "EOCD marker occurs after start of EOCD";
198 return VERIFY_FAILURE;
199 }
200 }
201
202 bool need_sha1 = false;
203 bool need_sha256 = false;
204 for (const auto& key : keys) {
205 switch (key.hash_len) {
206 case SHA_DIGEST_LENGTH:
207 need_sha1 = true;
208 break;
209 case SHA256_DIGEST_LENGTH:
210 need_sha256 = true;
211 break;
212 }
213 }
214
215 SHA_CTX sha1_ctx;
216 SHA256_CTX sha256_ctx;
217 SHA1_Init(&sha1_ctx);
218 SHA256_Init(&sha256_ctx);
219
220 std::vector<HasherUpdateCallback> hashers;
221 if (need_sha1) {
222 hashers.emplace_back(
223 std::bind(&SHA1_Update, &sha1_ctx, std::placeholders::_1, std::placeholders::_2));
224 }
225 if (need_sha256) {
226 hashers.emplace_back(
227 std::bind(&SHA256_Update, &sha256_ctx, std::placeholders::_1, std::placeholders::_2));
228 }
229
230 double frac = -1.0;
231 uint64_t so_far = 0;
232 while (so_far < signed_len) {
233 // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a 1196MiB full OTA and
234 // 60% for an 89MiB incremental OTA. http://b/28135231.
235 uint64_t read_size = std::min<uint64_t>(signed_len - so_far, 16 * MiB);
236 package->UpdateHashAtOffset(hashers, so_far, read_size);
237 so_far += read_size;
238
239 double f = so_far / static_cast<double>(signed_len);
240 if (f > frac + 0.02 || read_size == so_far) {
241 package->SetProgress(f);
242 frac = f;
243 if (set_progress) {
244 set_progress(f);
245 }
246 }
247 }
248
249 uint8_t sha1[SHA_DIGEST_LENGTH];
250 SHA1_Final(sha1, &sha1_ctx);
251 uint8_t sha256[SHA256_DIGEST_LENGTH];
252 SHA256_Final(sha256, &sha256_ctx);
253
254 const uint8_t* signature = eocd + eocd_size - signature_start;
255 size_t signature_size = signature_start - FOOTER_SIZE;
256
257 LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start)
258 << ", length: " << signature_size << "): " << print_hex(signature, signature_size);
259
260 std::vector<uint8_t> sig_der;
261 if (!read_pkcs7(signature, signature_size, &sig_der)) {
262 LOG(ERROR) << "Could not find signature DER block";
263 return VERIFY_FAILURE;
264 }
265
266 // Check to make sure at least one of the keys matches the signature. Since any key can match,
267 // we need to try each before determining a verification failure has happened.
268 size_t i = 0;
269 for (const auto& key : keys) {
270 const uint8_t* hash;
271 int hash_nid;
272 switch (key.hash_len) {
273 case SHA_DIGEST_LENGTH:
274 hash = sha1;
275 hash_nid = NID_sha1;
276 break;
277 case SHA256_DIGEST_LENGTH:
278 hash = sha256;
279 hash_nid = NID_sha256;
280 break;
281 default:
282 continue;
283 }
284
285 // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends
286 // after the signature itself.
287 if (key.key_type == Certificate::KEY_TYPE_RSA) {
288 if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(),
289 key.rsa.get())) {
290 LOG(INFO) << "failed to verify against RSA key " << i;
291 continue;
292 }
293
294 LOG(INFO) << "whole-file signature verified against RSA key " << i;
295 return VERIFY_SUCCESS;
296 } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) {
297 if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) {
298 LOG(INFO) << "failed to verify against EC key " << i;
299 continue;
300 }
301
302 LOG(INFO) << "whole-file signature verified against EC key " << i;
303 return VERIFY_SUCCESS;
304 } else {
305 LOG(INFO) << "Unknown key type " << key.key_type;
306 }
307 i++;
308 }
309
310 if (need_sha1) {
311 LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
312 }
313 if (need_sha256) {
314 LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
315 }
316 LOG(ERROR) << "failed to verify whole-file signature";
317 return VERIFY_FAILURE;
318}
319
320std::unique_ptr<RSA, RSADeleter> parse_rsa_key(FILE* file, uint32_t exponent) {
321 // Read key length in words and n0inv. n0inv is a precomputed montgomery
322 // parameter derived from the modulus and can be used to speed up
323 // verification. n0inv is 32 bits wide here, assuming the verification logic
324 // uses 32 bit arithmetic. However, BoringSSL may use a word size of 64 bits
325 // internally, in which case we don't have a valid n0inv. Thus, we just
326 // ignore the montgomery parameters and have BoringSSL recompute them
327 // internally. If/When the speedup from using the montgomery parameters
328 // becomes relevant, we can add more sophisticated code here to obtain a
329 // 64-bit n0inv and initialize the montgomery parameters in the key object.
330 uint32_t key_len_words = 0;
331 uint32_t n0inv = 0;
332 if (fscanf(file, " %i , 0x%x", &key_len_words, &n0inv) != 2) {
333 return nullptr;
334 }
335
336 if (key_len_words > 8192 / 32) {
337 LOG(ERROR) << "key length (" << key_len_words << ") too large";
338 return nullptr;
339 }
340
341 // Read the modulus.
342 std::unique_ptr<uint32_t[]> modulus(new uint32_t[key_len_words]);
343 if (fscanf(file, " , { %u", &modulus[0]) != 1) {
344 return nullptr;
345 }
346 for (uint32_t i = 1; i < key_len_words; ++i) {
347 if (fscanf(file, " , %u", &modulus[i]) != 1) {
348 return nullptr;
349 }
350 }
351
352 // Cconvert from little-endian array of little-endian words to big-endian
353 // byte array suitable as input for BN_bin2bn.
354 std::reverse((uint8_t*)modulus.get(),
355 (uint8_t*)(modulus.get() + key_len_words));
356
357 // The next sequence of values is the montgomery parameter R^2. Since we
358 // generally don't have a valid |n0inv|, we ignore this (see comment above).
359 uint32_t rr_value;
360 if (fscanf(file, " } , { %u", &rr_value) != 1) {
361 return nullptr;
362 }
363 for (uint32_t i = 1; i < key_len_words; ++i) {
364 if (fscanf(file, " , %u", &rr_value) != 1) {
365 return nullptr;
366 }
367 }
368 if (fscanf(file, " } } ") != 0) {
369 return nullptr;
370 }
371
372 // Initialize the key.
373 std::unique_ptr<RSA, RSADeleter> key(RSA_new());
374 if (!key) {
375 return nullptr;
376 }
377
378 key->n = BN_bin2bn((uint8_t*)modulus.get(),
379 key_len_words * sizeof(uint32_t), NULL);
380 if (!key->n) {
381 return nullptr;
382 }
383
384 key->e = BN_new();
385 if (!key->e || !BN_set_word(key->e, exponent)) {
386 return nullptr;
387 }
388
389 return key;
390}
391
392
393static std::vector<Certificate> IterateZipEntriesAndSearchForKeys(const ZipArchiveHandle& handle) {
394 void* cookie;
395 ZipString suffix("x509.pem");
396 int32_t iter_status = StartIteration(handle, &cookie, nullptr, &suffix);
397 if (iter_status != 0) {
398 LOG(ERROR) << "Failed to iterate over entries in the certificate zipfile: "
399 << ErrorCodeString(iter_status);
400 return {};
401 }
402
403 std::vector<Certificate> result;
404
405 ZipString name;
406 ZipEntry entry;
407 while ((iter_status = Next(cookie, &entry, &name)) == 0) {
408 std::vector<uint8_t> pem_content(entry.uncompressed_length);
409 if (int32_t extract_status =
410 ExtractToMemory(handle, &entry, pem_content.data(), pem_content.size());
411 extract_status != 0) {
412 LOG(ERROR) << "Failed to extract " << std::string(name.name, name.name + name.name_length);
413 return {};
414 }
415
416 Certificate cert(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
417 // Aborts the parsing if we fail to load one of the key file.
418 if (!LoadCertificateFromBuffer(pem_content, &cert)) {
419 LOG(ERROR) << "Failed to load keys from "
420 << std::string(name.name, name.name + name.name_length);
421 return {};
422 }
423
424 result.emplace_back(std::move(cert));
425 }
426
427 if (iter_status != -1) {
428 LOG(ERROR) << "Error while iterating over zip entries: " << ErrorCodeString(iter_status);
429 return {};
430 }
431
432 return result;
433}
434
435std::vector<Certificate> LoadKeysFromZipfile(const std::string& zip_name) {
436 ZipArchiveHandle handle;
437 if (int32_t open_status = OpenArchive(zip_name.c_str(), &handle); open_status != 0) {
438 LOG(ERROR) << "Failed to open " << zip_name << ": " << ErrorCodeString(open_status);
439 return {};
440 }
441
442 std::vector<Certificate> result = IterateZipEntriesAndSearchForKeys(handle);
443 CloseArchive(handle);
444 return result;
445}
446
447bool CheckRSAKey(const std::unique_ptr<RSA, RSADeleter>& rsa) {
448 if (!rsa) {
449 return false;
450 }
451
452 const BIGNUM* out_n;
453 const BIGNUM* out_e;
454 RSA_get0_key(rsa.get(), &out_n, &out_e, nullptr /* private exponent */);
455 auto modulus_bits = BN_num_bits(out_n);
456 if (modulus_bits != 2048 && modulus_bits != 4096) {
457 LOG(ERROR) << "Modulus should be 2048 or 4096 bits long, actual: " << modulus_bits;
458 return false;
459 }
460
461 BN_ULONG exponent = BN_get_word(out_e);
462 if (exponent != 3 && exponent != 65537) {
463 LOG(ERROR) << "Public exponent should be 3 or 65537, actual: " << exponent;
464 return false;
465 }
466
467 return true;
468}
469
470bool CheckECKey(const std::unique_ptr<EC_KEY, ECKEYDeleter>& ec_key) {
471 if (!ec_key) {
472 return false;
473 }
474
475 const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key.get());
476 if (!ec_group) {
477 LOG(ERROR) << "Failed to get the ec_group from the ec_key";
478 return false;
479 }
480 auto degree = EC_GROUP_get_degree(ec_group);
481 if (degree != 256) {
482 LOG(ERROR) << "Field size of the ec key should be 256 bits long, actual: " << degree;
483 return false;
484 }
485
486 return true;
487}
488
489bool LoadCertificateFromBuffer(const std::vector<uint8_t>& pem_content, Certificate* cert) {
490 std::unique_ptr<BIO, decltype(&BIO_free)> content(
491 BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free);
492
493 std::unique_ptr<X509, decltype(&X509_free)> x509(
494 PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free);
495 if (!x509) {
496 LOG(ERROR) << "Failed to read x509 certificate";
497 return false;
498 }
499
500 int nid = X509_get_signature_nid(x509.get());
501 switch (nid) {
502 // SignApk has historically accepted md5WithRSA certificates, but treated them as
503 // sha1WithRSA anyway. Continue to do so for backwards compatibility.
504 case NID_md5WithRSA:
505 case NID_md5WithRSAEncryption:
506 case NID_sha1WithRSA:
507 case NID_sha1WithRSAEncryption:
508 cert->hash_len = SHA_DIGEST_LENGTH;
509 break;
510 case NID_sha256WithRSAEncryption:
511 case NID_ecdsa_with_SHA256:
512 cert->hash_len = SHA256_DIGEST_LENGTH;
513 break;
514 default:
515 LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid);
516 return false;
517 }
518
519 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> public_key(X509_get_pubkey(x509.get()),
520 EVP_PKEY_free);
521 if (!public_key) {
522 LOG(ERROR) << "Failed to extract the public key from x509 certificate";
523 return false;
524 }
525
526 int key_type = EVP_PKEY_id(public_key.get());
527 if (key_type == EVP_PKEY_RSA) {
528 cert->key_type = Certificate::KEY_TYPE_RSA;
529 cert->ec.reset();
530 cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get()));
531 if (!cert->rsa || !CheckRSAKey(cert->rsa)) {
532 LOG(ERROR) << "Failed to validate the rsa key info from public key";
533 return false;
534 }
535 } else if (key_type == EVP_PKEY_EC) {
536 cert->key_type = Certificate::KEY_TYPE_EC;
537 cert->rsa.reset();
538 cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get()));
539 if (!cert->ec || !CheckECKey(cert->ec)) {
540 LOG(ERROR) << "Failed to validate the ec key info from the public key";
541 return false;
542 }
543 } else {
544 LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type);
545 return false;
546 }
547
548 return true;
549}