blob: 02ec987de90b3de99378a2c90b1ab8638526761e [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
bigbifff3d93e12021-07-04 11:44:32 -0400113int verify_file(VerifierInterface* package, const std::vector<Certificate>& keys, const std::function<void(float)>& set_progress) {
bigbiff1f9e4842020-10-31 11:33:15 -0400114 CHECK(package);
115 package->SetProgress(0.0);
116
117 if (set_progress) {
118 set_progress(0.0);
119 }
120
121 // An archive with a whole-file signature will end in six bytes:
122 //
123 // (2-byte signature start) $ff $ff (2-byte comment size)
124 //
125 // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by
126 // reading this footer, this tells us how far back from the end we have to start reading to find
127 // the whole comment.
128
129#define FOOTER_SIZE 6
130 uint64_t length = package->GetPackageSize();
131
132 if (length < FOOTER_SIZE) {
133 LOG(ERROR) << "not big enough to contain footer";
134 return VERIFY_FAILURE;
135 }
136
137 uint8_t footer[FOOTER_SIZE];
138 if (!package->ReadFullyAtOffset(footer, FOOTER_SIZE, length - FOOTER_SIZE)) {
139 LOG(ERROR) << "Failed to read footer";
140 return VERIFY_FAILURE;
141 }
142
143 if (footer[2] != 0xff || footer[3] != 0xff) {
144 LOG(ERROR) << "footer is wrong";
145 return VERIFY_FAILURE;
146 }
147
148 size_t comment_size = footer[4] + (footer[5] << 8);
149 size_t signature_start = footer[0] + (footer[1] << 8);
150 LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start
151 << " bytes from end";
152
153 if (signature_start > comment_size) {
154 LOG(ERROR) << "signature start: " << signature_start
155 << " is larger than comment size: " << comment_size;
156 return VERIFY_FAILURE;
157 }
158
159 if (signature_start <= FOOTER_SIZE) {
160 LOG(ERROR) << "Signature start is in the footer";
161 return VERIFY_FAILURE;
162 }
163
164#define EOCD_HEADER_SIZE 22
165
166 // The end-of-central-directory record is 22 bytes plus any comment length.
167 size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
168
169 if (length < eocd_size) {
170 LOG(ERROR) << "not big enough to contain EOCD";
171 return VERIFY_FAILURE;
172 }
173
174 // Determine how much of the file is covered by the signature. This is everything except the
175 // signature data and length, which includes all of the EOCD except for the comment length field
176 // (2 bytes) and the comment data.
177 uint64_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
178
179 uint8_t eocd[eocd_size];
180 if (!package->ReadFullyAtOffset(eocd, eocd_size, length - eocd_size)) {
181 LOG(ERROR) << "Failed to read EOCD of " << eocd_size << " bytes";
182 return VERIFY_FAILURE;
183 }
184
185 // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06.
186 if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) {
187 LOG(ERROR) << "signature length doesn't match EOCD marker";
188 return VERIFY_FAILURE;
189 }
190
191 for (size_t i = 4; i < eocd_size - 3; ++i) {
192 if (eocd[i] == 0x50 && eocd[i + 1] == 0x4b && eocd[i + 2] == 0x05 && eocd[i + 3] == 0x06) {
193 // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will
194 // find the later (wrong) one, which could be exploitable. Fail the verification if this
195 // sequence occurs anywhere after the real one.
196 LOG(ERROR) << "EOCD marker occurs after start of EOCD";
197 return VERIFY_FAILURE;
198 }
199 }
200
201 bool need_sha1 = false;
202 bool need_sha256 = false;
203 for (const auto& key : keys) {
204 switch (key.hash_len) {
205 case SHA_DIGEST_LENGTH:
206 need_sha1 = true;
207 break;
208 case SHA256_DIGEST_LENGTH:
209 need_sha256 = true;
210 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 std::vector<HasherUpdateCallback> hashers;
220 if (need_sha1) {
221 hashers.emplace_back(
222 std::bind(&SHA1_Update, &sha1_ctx, std::placeholders::_1, std::placeholders::_2));
223 }
224 if (need_sha256) {
225 hashers.emplace_back(
226 std::bind(&SHA256_Update, &sha256_ctx, std::placeholders::_1, std::placeholders::_2));
227 }
228
229 double frac = -1.0;
230 uint64_t so_far = 0;
231 while (so_far < signed_len) {
232 // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a 1196MiB full OTA and
233 // 60% for an 89MiB incremental OTA. http://b/28135231.
234 uint64_t read_size = std::min<uint64_t>(signed_len - so_far, 16 * MiB);
235 package->UpdateHashAtOffset(hashers, so_far, read_size);
236 so_far += read_size;
237
238 double f = so_far / static_cast<double>(signed_len);
239 if (f > frac + 0.02 || read_size == so_far) {
240 package->SetProgress(f);
241 frac = f;
242 if (set_progress) {
243 set_progress(f);
244 }
245 }
246 }
247
248 uint8_t sha1[SHA_DIGEST_LENGTH];
249 SHA1_Final(sha1, &sha1_ctx);
250 uint8_t sha256[SHA256_DIGEST_LENGTH];
251 SHA256_Final(sha256, &sha256_ctx);
252
253 const uint8_t* signature = eocd + eocd_size - signature_start;
254 size_t signature_size = signature_start - FOOTER_SIZE;
255
256 LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start)
257 << ", length: " << signature_size << "): " << print_hex(signature, signature_size);
258
259 std::vector<uint8_t> sig_der;
260 if (!read_pkcs7(signature, signature_size, &sig_der)) {
261 LOG(ERROR) << "Could not find signature DER block";
262 return VERIFY_FAILURE;
263 }
264
265 // Check to make sure at least one of the keys matches the signature. Since any key can match,
266 // we need to try each before determining a verification failure has happened.
267 size_t i = 0;
268 for (const auto& key : keys) {
269 const uint8_t* hash;
270 int hash_nid;
271 switch (key.hash_len) {
272 case SHA_DIGEST_LENGTH:
273 hash = sha1;
274 hash_nid = NID_sha1;
275 break;
276 case SHA256_DIGEST_LENGTH:
277 hash = sha256;
278 hash_nid = NID_sha256;
279 break;
280 default:
281 continue;
282 }
283
284 // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends
285 // after the signature itself.
286 if (key.key_type == Certificate::KEY_TYPE_RSA) {
287 if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(),
288 key.rsa.get())) {
289 LOG(INFO) << "failed to verify against RSA key " << i;
290 continue;
291 }
292
293 LOG(INFO) << "whole-file signature verified against RSA key " << i;
294 return VERIFY_SUCCESS;
295 } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) {
296 if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) {
297 LOG(INFO) << "failed to verify against EC key " << i;
298 continue;
299 }
300
301 LOG(INFO) << "whole-file signature verified against EC key " << i;
302 return VERIFY_SUCCESS;
303 } else {
304 LOG(INFO) << "Unknown key type " << key.key_type;
305 }
306 i++;
307 }
308
309 if (need_sha1) {
310 LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
311 }
312 if (need_sha256) {
313 LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
314 }
315 LOG(ERROR) << "failed to verify whole-file signature";
316 return VERIFY_FAILURE;
317}
318
bigbiff1f9e4842020-10-31 11:33:15 -0400319static std::vector<Certificate> IterateZipEntriesAndSearchForKeys(const ZipArchiveHandle& handle) {
320 void* cookie;
bigbifff3d93e12021-07-04 11:44:32 -0400321 int32_t iter_status = StartIteration(handle, &cookie, "", "x509.pem");
bigbiff1f9e4842020-10-31 11:33:15 -0400322 if (iter_status != 0) {
323 LOG(ERROR) << "Failed to iterate over entries in the certificate zipfile: "
324 << ErrorCodeString(iter_status);
325 return {};
326 }
327
328 std::vector<Certificate> result;
329
bigbifff3d93e12021-07-04 11:44:32 -0400330 std::string_view name;
GarfieldHand2161882021-11-29 00:04:53 +0800331 ZipEntry64 entry;
bigbiff1f9e4842020-10-31 11:33:15 -0400332 while ((iter_status = Next(cookie, &entry, &name)) == 0) {
333 std::vector<uint8_t> pem_content(entry.uncompressed_length);
334 if (int32_t extract_status =
335 ExtractToMemory(handle, &entry, pem_content.data(), pem_content.size());
336 extract_status != 0) {
bigbifff3d93e12021-07-04 11:44:32 -0400337 LOG(ERROR) << "Failed to extract " << name;
bigbiff1f9e4842020-10-31 11:33:15 -0400338 return {};
339 }
340
341 Certificate cert(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
342 // Aborts the parsing if we fail to load one of the key file.
343 if (!LoadCertificateFromBuffer(pem_content, &cert)) {
bigbifff3d93e12021-07-04 11:44:32 -0400344 LOG(ERROR) << "Failed to load keys from " << name;
bigbiff1f9e4842020-10-31 11:33:15 -0400345 return {};
346 }
347
348 result.emplace_back(std::move(cert));
349 }
350
351 if (iter_status != -1) {
352 LOG(ERROR) << "Error while iterating over zip entries: " << ErrorCodeString(iter_status);
353 return {};
354 }
355
356 return result;
357}
358
359std::vector<Certificate> LoadKeysFromZipfile(const std::string& zip_name) {
360 ZipArchiveHandle handle;
361 if (int32_t open_status = OpenArchive(zip_name.c_str(), &handle); open_status != 0) {
362 LOG(ERROR) << "Failed to open " << zip_name << ": " << ErrorCodeString(open_status);
363 return {};
364 }
365
366 std::vector<Certificate> result = IterateZipEntriesAndSearchForKeys(handle);
367 CloseArchive(handle);
368 return result;
369}
370
371bool CheckRSAKey(const std::unique_ptr<RSA, RSADeleter>& rsa) {
372 if (!rsa) {
373 return false;
374 }
375
376 const BIGNUM* out_n;
377 const BIGNUM* out_e;
378 RSA_get0_key(rsa.get(), &out_n, &out_e, nullptr /* private exponent */);
379 auto modulus_bits = BN_num_bits(out_n);
380 if (modulus_bits != 2048 && modulus_bits != 4096) {
381 LOG(ERROR) << "Modulus should be 2048 or 4096 bits long, actual: " << modulus_bits;
382 return false;
383 }
384
385 BN_ULONG exponent = BN_get_word(out_e);
386 if (exponent != 3 && exponent != 65537) {
387 LOG(ERROR) << "Public exponent should be 3 or 65537, actual: " << exponent;
388 return false;
389 }
390
391 return true;
392}
393
394bool CheckECKey(const std::unique_ptr<EC_KEY, ECKEYDeleter>& ec_key) {
395 if (!ec_key) {
396 return false;
397 }
398
399 const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key.get());
400 if (!ec_group) {
401 LOG(ERROR) << "Failed to get the ec_group from the ec_key";
402 return false;
403 }
404 auto degree = EC_GROUP_get_degree(ec_group);
405 if (degree != 256) {
406 LOG(ERROR) << "Field size of the ec key should be 256 bits long, actual: " << degree;
407 return false;
408 }
409
410 return true;
411}
412
413bool LoadCertificateFromBuffer(const std::vector<uint8_t>& pem_content, Certificate* cert) {
414 std::unique_ptr<BIO, decltype(&BIO_free)> content(
415 BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free);
416
417 std::unique_ptr<X509, decltype(&X509_free)> x509(
418 PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free);
419 if (!x509) {
420 LOG(ERROR) << "Failed to read x509 certificate";
421 return false;
422 }
423
424 int nid = X509_get_signature_nid(x509.get());
425 switch (nid) {
426 // SignApk has historically accepted md5WithRSA certificates, but treated them as
427 // sha1WithRSA anyway. Continue to do so for backwards compatibility.
428 case NID_md5WithRSA:
429 case NID_md5WithRSAEncryption:
430 case NID_sha1WithRSA:
431 case NID_sha1WithRSAEncryption:
432 cert->hash_len = SHA_DIGEST_LENGTH;
433 break;
434 case NID_sha256WithRSAEncryption:
435 case NID_ecdsa_with_SHA256:
436 cert->hash_len = SHA256_DIGEST_LENGTH;
437 break;
438 default:
439 LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid);
440 return false;
441 }
442
443 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> public_key(X509_get_pubkey(x509.get()),
444 EVP_PKEY_free);
445 if (!public_key) {
446 LOG(ERROR) << "Failed to extract the public key from x509 certificate";
447 return false;
448 }
449
450 int key_type = EVP_PKEY_id(public_key.get());
451 if (key_type == EVP_PKEY_RSA) {
452 cert->key_type = Certificate::KEY_TYPE_RSA;
453 cert->ec.reset();
454 cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get()));
455 if (!cert->rsa || !CheckRSAKey(cert->rsa)) {
456 LOG(ERROR) << "Failed to validate the rsa key info from public key";
457 return false;
458 }
459 } else if (key_type == EVP_PKEY_EC) {
460 cert->key_type = Certificate::KEY_TYPE_EC;
461 cert->rsa.reset();
462 cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get()));
463 if (!cert->ec || !CheckECKey(cert->ec)) {
464 LOG(ERROR) << "Failed to validate the ec key info from the public key";
465 return false;
466 }
467 } else {
468 LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type);
469 return false;
470 }
471
472 return true;
473}