blob: 44bd4e1804bb2907d7cd8205d24950507a7d44f8 [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
Tianjie Xu0dd96852018-10-15 11:44:14 -0700311static std::vector<Certificate> IterateZipEntriesAndSearchForKeys(const ZipArchiveHandle& handle) {
312 void* cookie;
313 ZipString suffix("x509.pem");
314 int32_t iter_status = StartIteration(handle, &cookie, nullptr, &suffix);
315 if (iter_status != 0) {
316 LOG(ERROR) << "Failed to iterate over entries in the certificate zipfile: "
317 << ErrorCodeString(iter_status);
318 return {};
319 }
320
321 std::vector<Certificate> result;
322
323 ZipString name;
324 ZipEntry entry;
325 while ((iter_status = Next(cookie, &entry, &name)) == 0) {
326 std::vector<uint8_t> pem_content(entry.uncompressed_length);
327 if (int32_t extract_status =
328 ExtractToMemory(handle, &entry, pem_content.data(), pem_content.size());
329 extract_status != 0) {
330 LOG(ERROR) << "Failed to extract " << std::string(name.name, name.name + name.name_length);
331 return {};
332 }
333
334 Certificate cert(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
335 // Aborts the parsing if we fail to load one of the key file.
336 if (!LoadCertificateFromBuffer(pem_content, &cert)) {
337 LOG(ERROR) << "Failed to load keys from "
338 << std::string(name.name, name.name + name.name_length);
339 return {};
340 }
341
342 result.emplace_back(std::move(cert));
343 }
344
345 if (iter_status != -1) {
346 LOG(ERROR) << "Error while iterating over zip entries: " << ErrorCodeString(iter_status);
347 return {};
348 }
349
350 return result;
351}
352
353std::vector<Certificate> LoadKeysFromZipfile(const std::string& zip_name) {
354 ZipArchiveHandle handle;
355 if (int32_t open_status = OpenArchive(zip_name.c_str(), &handle); open_status != 0) {
356 LOG(ERROR) << "Failed to open " << zip_name << ": " << ErrorCodeString(open_status);
357 return {};
358 }
359
360 std::vector<Certificate> result = IterateZipEntriesAndSearchForKeys(handle);
361 CloseArchive(handle);
362 return result;
363}
364
Tianjie Xub5110de2018-10-23 23:31:43 -0700365bool CheckRSAKey(const std::unique_ptr<RSA, RSADeleter>& rsa) {
366 if (!rsa) {
367 return false;
368 }
369
370 const BIGNUM* out_n;
371 const BIGNUM* out_e;
372 RSA_get0_key(rsa.get(), &out_n, &out_e, nullptr /* private exponent */);
373 auto modulus_bits = BN_num_bits(out_n);
374 if (modulus_bits != 2048) {
375 LOG(ERROR) << "Modulus should be 2048 bits long, actual: " << modulus_bits;
376 return false;
377 }
378
379 BN_ULONG exponent = BN_get_word(out_e);
380 if (exponent != 3 && exponent != 65537) {
381 LOG(ERROR) << "Public exponent should be 3 or 65537, actual: " << exponent;
382 return false;
383 }
384
385 return true;
386}
387
388bool CheckECKey(const std::unique_ptr<EC_KEY, ECKEYDeleter>& ec_key) {
389 if (!ec_key) {
390 return false;
391 }
392
393 const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key.get());
394 if (!ec_group) {
395 LOG(ERROR) << "Failed to get the ec_group from the ec_key";
396 return false;
397 }
398 auto degree = EC_GROUP_get_degree(ec_group);
399 if (degree != 256) {
400 LOG(ERROR) << "Field size of the ec key should be 256 bits long, actual: " << degree;
401 return false;
402 }
403
404 return true;
405}
406
Tianjie Xu82566982018-10-10 15:44:17 -0700407bool LoadCertificateFromBuffer(const std::vector<uint8_t>& pem_content, Certificate* cert) {
408 std::unique_ptr<BIO, decltype(&BIO_free)> content(
409 BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free);
410
411 std::unique_ptr<X509, decltype(&X509_free)> x509(
412 PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free);
413 if (!x509) {
414 LOG(ERROR) << "Failed to read x509 certificate";
415 return false;
416 }
417
418 int nid = X509_get_signature_nid(x509.get());
419 switch (nid) {
420 // SignApk has historically accepted md5WithRSA certificates, but treated them as
421 // sha1WithRSA anyway. Continue to do so for backwards compatibility.
422 case NID_md5WithRSA:
423 case NID_md5WithRSAEncryption:
424 case NID_sha1WithRSA:
425 case NID_sha1WithRSAEncryption:
426 cert->hash_len = SHA_DIGEST_LENGTH;
427 break;
428 case NID_sha256WithRSAEncryption:
429 case NID_ecdsa_with_SHA256:
430 cert->hash_len = SHA256_DIGEST_LENGTH;
431 break;
432 default:
433 LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid);
434 return false;
435 }
436
437 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> public_key(X509_get_pubkey(x509.get()),
438 EVP_PKEY_free);
439 if (!public_key) {
440 LOG(ERROR) << "Failed to extract the public key from x509 certificate";
441 return false;
442 }
443
444 int key_type = EVP_PKEY_id(public_key.get());
Tianjie Xu82566982018-10-10 15:44:17 -0700445 if (key_type == EVP_PKEY_RSA) {
446 cert->key_type = Certificate::KEY_TYPE_RSA;
447 cert->ec.reset();
448 cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get()));
Tianjie Xub5110de2018-10-23 23:31:43 -0700449 if (!cert->rsa || !CheckRSAKey(cert->rsa)) {
450 LOG(ERROR) << "Failed to validate the rsa key info from public key";
Tianjie Xu82566982018-10-10 15:44:17 -0700451 return false;
452 }
453 } else if (key_type == EVP_PKEY_EC) {
454 cert->key_type = Certificate::KEY_TYPE_EC;
455 cert->rsa.reset();
456 cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get()));
Tianjie Xub5110de2018-10-23 23:31:43 -0700457 if (!cert->ec || !CheckECKey(cert->ec)) {
458 LOG(ERROR) << "Failed to validate the ec key info from the public key";
Tianjie Xu82566982018-10-10 15:44:17 -0700459 return false;
460 }
461 } else {
462 LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type);
463 return false;
464 }
465
466 return true;
467}