blob: 68a011e0d8082225210744c93be5910488f5bd77 [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
Kenny Root7a4adb52013-10-09 10:14:35 -070042/*
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 */
Tao Bao76fdb242017-03-20 17:09:13 -070067static 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();
Kenny Root7a4adb52013-10-09 10:14:35 -070071
Tao Bao861c53c2017-03-20 17:09:13 -070072 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()) {
Tao Bao76fdb242017-03-20 17:09:13 -070076 return false;
77 }
78
Tao Bao861c53c2017-03-20 17:09:13 -070079 std::unique_ptr<asn1_context> signed_data_app(pkcs7_seq->asn1_constructed_get());
80 if (signed_data_app == nullptr) {
81 return false;
Tao Bao76fdb242017-03-20 17:09:13 -070082 }
Kenny Root7a4adb52013-10-09 10:14:35 -070083
Tao Bao861c53c2017-03-20 17:09:13 -070084 std::unique_ptr<asn1_context> signed_data_seq(signed_data_app->asn1_sequence_get());
85 if (signed_data_seq == nullptr ||
86 !signed_data_seq->asn1_sequence_next() ||
87 !signed_data_seq->asn1_sequence_next() ||
88 !signed_data_seq->asn1_sequence_next() ||
89 !signed_data_seq->asn1_constructed_skip_all()) {
90 return false;
91 }
92
93 std::unique_ptr<asn1_context> sig_set(signed_data_seq->asn1_set_get());
94 if (sig_set == nullptr) {
95 return false;
96 }
97
98 std::unique_ptr<asn1_context> sig_seq(sig_set->asn1_sequence_get());
99 if (sig_seq == nullptr ||
100 !sig_seq->asn1_sequence_next() ||
101 !sig_seq->asn1_sequence_next() ||
102 !sig_seq->asn1_sequence_next() ||
103 !sig_seq->asn1_sequence_next()) {
104 return false;
105 }
106
107 const uint8_t* sig_der_ptr;
108 size_t sig_der_length;
109 if (!sig_seq->asn1_octet_string_get(&sig_der_ptr, &sig_der_length)) {
110 return false;
111 }
112
113 sig_der->resize(sig_der_length);
114 std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin());
115 return true;
Kenny Root7a4adb52013-10-09 10:14:35 -0700116}
117
xunchangf07ed2e2019-02-25 14:14:01 -0800118int verify_file(VerifierInterface* package, const std::vector<Certificate>& keys) {
119 CHECK(package);
120 package->SetProgress(0.0);
Doug Zongker54e2e862009-08-17 13:21:04 -0700121
Tao Bao5e535012017-03-16 17:37:38 -0700122 // 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.
Doug Zongker54e2e862009-08-17 13:21:04 -0700129
130#define FOOTER_SIZE 6
xunchangf07ed2e2019-02-25 14:14:01 -0800131 uint64_t length = package->GetPackageSize();
Doug Zongker54e2e862009-08-17 13:21:04 -0700132
Tao Bao5e535012017-03-16 17:37:38 -0700133 if (length < FOOTER_SIZE) {
134 LOG(ERROR) << "not big enough to contain footer";
135 return VERIFY_FAILURE;
136 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800137
xunchangf07ed2e2019-02-25 14:14:01 -0800138 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 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800143
Tao Bao5e535012017-03-16 17:37:38 -0700144 if (footer[2] != 0xff || footer[3] != 0xff) {
145 LOG(ERROR) << "footer is wrong";
146 return VERIFY_FAILURE;
147 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800148
Tao Bao5e535012017-03-16 17:37:38 -0700149 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";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800153
Tao Bao553c7bd2017-03-18 07:33:26 -0700154 if (signature_start > comment_size) {
155 LOG(ERROR) << "signature start: " << signature_start << " is larger than comment size: "
156 << comment_size;
157 return VERIFY_FAILURE;
158 }
Tianjie Xu54ea1362016-12-16 16:24:09 -0800159
Tao Bao5e535012017-03-16 17:37:38 -0700160 if (signature_start <= FOOTER_SIZE) {
161 LOG(ERROR) << "Signature start is in the footer";
162 return VERIFY_FAILURE;
163 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800164
Doug Zongker54e2e862009-08-17 13:21:04 -0700165#define EOCD_HEADER_SIZE 22
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800166
Tao Bao5e535012017-03-16 17:37:38 -0700167 // The end-of-central-directory record is 22 bytes plus any comment length.
168 size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800169
Tao Bao5e535012017-03-16 17:37:38 -0700170 if (length < eocd_size) {
171 LOG(ERROR) << "not big enough to contain EOCD";
Doug Zongker54e2e862009-08-17 13:21:04 -0700172 return VERIFY_FAILURE;
Tao Bao5e535012017-03-16 17:37:38 -0700173 }
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.
xunchangf07ed2e2019-02-25 14:14:01 -0800178 uint64_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
Tao Bao5e535012017-03-16 17:37:38 -0700179
xunchangf07ed2e2019-02-25 14:14:01 -0800180 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 }
Tao Bao5e535012017-03-16 17:37:38 -0700185
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) {
Tao Bao76fdb242017-03-20 17:09:13 -0700193 if (eocd[i] == 0x50 && eocd[i+1] == 0x4b && eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
Tao Bao5e535012017-03-16 17:37:38 -0700194 // 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: need_sha1 = true; break;
207 case SHA256_DIGEST_LENGTH: need_sha256 = true; break;
208 }
209 }
210
211 SHA_CTX sha1_ctx;
212 SHA256_CTX sha256_ctx;
213 SHA1_Init(&sha1_ctx);
214 SHA256_Init(&sha256_ctx);
215
xunchangf07ed2e2019-02-25 14:14:01 -0800216 std::vector<HasherUpdateCallback> hashers;
217 if (need_sha1) {
218 hashers.emplace_back(
219 std::bind(&SHA1_Update, &sha1_ctx, std::placeholders::_1, std::placeholders::_2));
220 }
221 if (need_sha256) {
222 hashers.emplace_back(
223 std::bind(&SHA256_Update, &sha256_ctx, std::placeholders::_1, std::placeholders::_2));
224 }
225
Tao Bao5e535012017-03-16 17:37:38 -0700226 double frac = -1.0;
xunchangf07ed2e2019-02-25 14:14:01 -0800227 uint64_t so_far = 0;
Tao Bao5e535012017-03-16 17:37:38 -0700228 while (so_far < signed_len) {
xunchangf07ed2e2019-02-25 14:14:01 -0800229 // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a 1196MiB full OTA and
230 // 60% for an 89MiB incremental OTA. http://b/28135231.
231 uint64_t read_size = std::min<uint64_t>(signed_len - so_far, 16 * MiB);
232 package->UpdateHashAtOffset(hashers, so_far, read_size);
233 so_far += read_size;
Tao Bao5e535012017-03-16 17:37:38 -0700234
xunchangf07ed2e2019-02-25 14:14:01 -0800235 double f = so_far / static_cast<double>(signed_len);
236 if (f > frac + 0.02 || read_size == so_far) {
237 package->SetProgress(f);
238 frac = f;
Tao Bao5e535012017-03-16 17:37:38 -0700239 }
240 }
241
242 uint8_t sha1[SHA_DIGEST_LENGTH];
243 SHA1_Final(sha1, &sha1_ctx);
244 uint8_t sha256[SHA256_DIGEST_LENGTH];
245 SHA256_Final(sha256, &sha256_ctx);
246
Tao Bao76fdb242017-03-20 17:09:13 -0700247 const uint8_t* signature = eocd + eocd_size - signature_start;
Tao Bao5e535012017-03-16 17:37:38 -0700248 size_t signature_size = signature_start - FOOTER_SIZE;
249
250 LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) << ", length: "
251 << signature_size << "): " << print_hex(signature, signature_size);
252
Tao Bao76fdb242017-03-20 17:09:13 -0700253 std::vector<uint8_t> sig_der;
254 if (!read_pkcs7(signature, signature_size, &sig_der)) {
Tao Bao5e535012017-03-16 17:37:38 -0700255 LOG(ERROR) << "Could not find signature DER block";
256 return VERIFY_FAILURE;
257 }
258
259 // Check to make sure at least one of the keys matches the signature. Since any key can match,
260 // we need to try each before determining a verification failure has happened.
261 size_t i = 0;
262 for (const auto& key : keys) {
263 const uint8_t* hash;
264 int hash_nid;
265 switch (key.hash_len) {
266 case SHA_DIGEST_LENGTH:
267 hash = sha1;
268 hash_nid = NID_sha1;
269 break;
270 case SHA256_DIGEST_LENGTH:
271 hash = sha256;
272 hash_nid = NID_sha256;
273 break;
274 default:
275 continue;
276 }
277
278 // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends
279 // after the signature itself.
280 if (key.key_type == Certificate::KEY_TYPE_RSA) {
Tao Bao76fdb242017-03-20 17:09:13 -0700281 if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(),
282 key.rsa.get())) {
Tao Bao5e535012017-03-16 17:37:38 -0700283 LOG(INFO) << "failed to verify against RSA key " << i;
284 continue;
285 }
286
287 LOG(INFO) << "whole-file signature verified against RSA key " << i;
Tao Bao5e535012017-03-16 17:37:38 -0700288 return VERIFY_SUCCESS;
289 } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) {
Tao Bao76fdb242017-03-20 17:09:13 -0700290 if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) {
Tao Bao5e535012017-03-16 17:37:38 -0700291 LOG(INFO) << "failed to verify against EC key " << i;
292 continue;
293 }
294
295 LOG(INFO) << "whole-file signature verified against EC key " << i;
Tao Bao5e535012017-03-16 17:37:38 -0700296 return VERIFY_SUCCESS;
297 } else {
298 LOG(INFO) << "Unknown key type " << key.key_type;
299 }
300 i++;
301 }
302
303 if (need_sha1) {
304 LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
305 }
306 if (need_sha256) {
307 LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
308 }
Tao Bao5e535012017-03-16 17:37:38 -0700309 LOG(ERROR) << "failed to verify whole-file signature";
310 return VERIFY_FAILURE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800311}
Doug Zongker6c249f72012-11-02 15:04:05 -0700312
Tianjie Xu0dd96852018-10-15 11:44:14 -0700313static std::vector<Certificate> IterateZipEntriesAndSearchForKeys(const ZipArchiveHandle& handle) {
314 void* cookie;
315 ZipString suffix("x509.pem");
316 int32_t iter_status = StartIteration(handle, &cookie, nullptr, &suffix);
317 if (iter_status != 0) {
318 LOG(ERROR) << "Failed to iterate over entries in the certificate zipfile: "
319 << ErrorCodeString(iter_status);
320 return {};
321 }
322
323 std::vector<Certificate> result;
324
325 ZipString name;
326 ZipEntry entry;
327 while ((iter_status = Next(cookie, &entry, &name)) == 0) {
328 std::vector<uint8_t> pem_content(entry.uncompressed_length);
329 if (int32_t extract_status =
330 ExtractToMemory(handle, &entry, pem_content.data(), pem_content.size());
331 extract_status != 0) {
332 LOG(ERROR) << "Failed to extract " << std::string(name.name, name.name + name.name_length);
333 return {};
334 }
335
336 Certificate cert(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
337 // Aborts the parsing if we fail to load one of the key file.
338 if (!LoadCertificateFromBuffer(pem_content, &cert)) {
339 LOG(ERROR) << "Failed to load keys from "
340 << std::string(name.name, name.name + name.name_length);
341 return {};
342 }
343
344 result.emplace_back(std::move(cert));
345 }
346
347 if (iter_status != -1) {
348 LOG(ERROR) << "Error while iterating over zip entries: " << ErrorCodeString(iter_status);
349 return {};
350 }
351
352 return result;
353}
354
355std::vector<Certificate> LoadKeysFromZipfile(const std::string& zip_name) {
356 ZipArchiveHandle handle;
357 if (int32_t open_status = OpenArchive(zip_name.c_str(), &handle); open_status != 0) {
358 LOG(ERROR) << "Failed to open " << zip_name << ": " << ErrorCodeString(open_status);
359 return {};
360 }
361
362 std::vector<Certificate> result = IterateZipEntriesAndSearchForKeys(handle);
363 CloseArchive(handle);
364 return result;
365}
366
Tianjie Xub5110de2018-10-23 23:31:43 -0700367bool CheckRSAKey(const std::unique_ptr<RSA, RSADeleter>& rsa) {
368 if (!rsa) {
369 return false;
370 }
371
372 const BIGNUM* out_n;
373 const BIGNUM* out_e;
374 RSA_get0_key(rsa.get(), &out_n, &out_e, nullptr /* private exponent */);
375 auto modulus_bits = BN_num_bits(out_n);
376 if (modulus_bits != 2048) {
377 LOG(ERROR) << "Modulus should be 2048 bits long, actual: " << modulus_bits;
378 return false;
379 }
380
381 BN_ULONG exponent = BN_get_word(out_e);
382 if (exponent != 3 && exponent != 65537) {
383 LOG(ERROR) << "Public exponent should be 3 or 65537, actual: " << exponent;
384 return false;
385 }
386
387 return true;
388}
389
390bool CheckECKey(const std::unique_ptr<EC_KEY, ECKEYDeleter>& ec_key) {
391 if (!ec_key) {
392 return false;
393 }
394
395 const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key.get());
396 if (!ec_group) {
397 LOG(ERROR) << "Failed to get the ec_group from the ec_key";
398 return false;
399 }
400 auto degree = EC_GROUP_get_degree(ec_group);
401 if (degree != 256) {
402 LOG(ERROR) << "Field size of the ec key should be 256 bits long, actual: " << degree;
403 return false;
404 }
405
406 return true;
407}
408
Tianjie Xu82566982018-10-10 15:44:17 -0700409bool LoadCertificateFromBuffer(const std::vector<uint8_t>& pem_content, Certificate* cert) {
410 std::unique_ptr<BIO, decltype(&BIO_free)> content(
411 BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free);
412
413 std::unique_ptr<X509, decltype(&X509_free)> x509(
414 PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free);
415 if (!x509) {
416 LOG(ERROR) << "Failed to read x509 certificate";
417 return false;
418 }
419
420 int nid = X509_get_signature_nid(x509.get());
421 switch (nid) {
422 // SignApk has historically accepted md5WithRSA certificates, but treated them as
423 // sha1WithRSA anyway. Continue to do so for backwards compatibility.
424 case NID_md5WithRSA:
425 case NID_md5WithRSAEncryption:
426 case NID_sha1WithRSA:
427 case NID_sha1WithRSAEncryption:
428 cert->hash_len = SHA_DIGEST_LENGTH;
429 break;
430 case NID_sha256WithRSAEncryption:
431 case NID_ecdsa_with_SHA256:
432 cert->hash_len = SHA256_DIGEST_LENGTH;
433 break;
434 default:
435 LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid);
436 return false;
437 }
438
439 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> public_key(X509_get_pubkey(x509.get()),
440 EVP_PKEY_free);
441 if (!public_key) {
442 LOG(ERROR) << "Failed to extract the public key from x509 certificate";
443 return false;
444 }
445
446 int key_type = EVP_PKEY_id(public_key.get());
Tianjie Xu82566982018-10-10 15:44:17 -0700447 if (key_type == EVP_PKEY_RSA) {
448 cert->key_type = Certificate::KEY_TYPE_RSA;
449 cert->ec.reset();
450 cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get()));
Tianjie Xub5110de2018-10-23 23:31:43 -0700451 if (!cert->rsa || !CheckRSAKey(cert->rsa)) {
452 LOG(ERROR) << "Failed to validate the rsa key info from public key";
Tianjie Xu82566982018-10-10 15:44:17 -0700453 return false;
454 }
455 } else if (key_type == EVP_PKEY_EC) {
456 cert->key_type = Certificate::KEY_TYPE_EC;
457 cert->rsa.reset();
458 cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get()));
Tianjie Xub5110de2018-10-23 23:31:43 -0700459 if (!cert->ec || !CheckECKey(cert->ec)) {
460 LOG(ERROR) << "Failed to validate the ec key info from the public key";
Tianjie Xu82566982018-10-10 15:44:17 -0700461 return false;
462 }
463 } else {
464 LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type);
465 return false;
466 }
467
468 return true;
469}