1 /*
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 "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/bn.h>
31 #include <openssl/ecdsa.h>
32 #include <openssl/obj_mac.h>
33 
34 #include "asn1_decoder.h"
35 #include "print_sha1.h"
36 
37 static constexpr size_t MiB = 1024 * 1024;
38 
39 /*
40  * Simple version of PKCS#7 SignedData extraction. This extracts the
41  * signature OCTET STRING to be used for signature verification.
42  *
43  * For full details, see http://www.ietf.org/rfc/rfc3852.txt
44  *
45  * The PKCS#7 structure looks like:
46  *
47  *   SEQUENCE (ContentInfo)
48  *     OID (ContentType)
49  *     [0] (content)
50  *       SEQUENCE (SignedData)
51  *         INTEGER (version CMSVersion)
52  *         SET (DigestAlgorithmIdentifiers)
53  *         SEQUENCE (EncapsulatedContentInfo)
54  *         [0] (CertificateSet OPTIONAL)
55  *         [1] (RevocationInfoChoices OPTIONAL)
56  *         SET (SignerInfos)
57  *           SEQUENCE (SignerInfo)
58  *             INTEGER (CMSVersion)
59  *             SEQUENCE (SignerIdentifier)
60  *             SEQUENCE (DigestAlgorithmIdentifier)
61  *             SEQUENCE (SignatureAlgorithmIdentifier)
62  *             OCTET STRING (SignatureValue)
63  */
read_pkcs7(const uint8_t * pkcs7_der,size_t pkcs7_der_len,std::vector<uint8_t> * sig_der)64 static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len,
65                        std::vector<uint8_t>* sig_der) {
66   CHECK(sig_der != nullptr);
67   sig_der->clear();
68 
69   asn1_context ctx(pkcs7_der, pkcs7_der_len);
70 
71   std::unique_ptr<asn1_context> pkcs7_seq(ctx.asn1_sequence_get());
72   if (pkcs7_seq == nullptr || !pkcs7_seq->asn1_sequence_next()) {
73     return false;
74   }
75 
76   std::unique_ptr<asn1_context> signed_data_app(pkcs7_seq->asn1_constructed_get());
77   if (signed_data_app == nullptr) {
78     return false;
79   }
80 
81   std::unique_ptr<asn1_context> signed_data_seq(signed_data_app->asn1_sequence_get());
82   if (signed_data_seq == nullptr ||
83       !signed_data_seq->asn1_sequence_next() ||
84       !signed_data_seq->asn1_sequence_next() ||
85       !signed_data_seq->asn1_sequence_next() ||
86       !signed_data_seq->asn1_constructed_skip_all()) {
87     return false;
88   }
89 
90   std::unique_ptr<asn1_context> sig_set(signed_data_seq->asn1_set_get());
91   if (sig_set == nullptr) {
92     return false;
93   }
94 
95   std::unique_ptr<asn1_context> sig_seq(sig_set->asn1_sequence_get());
96   if (sig_seq == nullptr ||
97       !sig_seq->asn1_sequence_next() ||
98       !sig_seq->asn1_sequence_next() ||
99       !sig_seq->asn1_sequence_next() ||
100       !sig_seq->asn1_sequence_next()) {
101     return false;
102   }
103 
104   const uint8_t* sig_der_ptr;
105   size_t sig_der_length;
106   if (!sig_seq->asn1_octet_string_get(&sig_der_ptr, &sig_der_length)) {
107     return false;
108   }
109 
110   sig_der->resize(sig_der_length);
111   std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin());
112   return true;
113 }
114 
115 /*
116  * Looks for an RSA signature embedded in the .ZIP file comment given the path to the zip. Verifies
117  * that it matches one of the given public keys. A callback function can be optionally provided for
118  * posting the progress.
119  *
120  * Returns VERIFY_SUCCESS or VERIFY_FAILURE (if any error is encountered or no key matches the
121  * signature).
122  */
verify_file(const unsigned char * addr,size_t length,const std::vector<Certificate> & keys,const std::function<void (float)> & set_progress)123 int verify_file(const unsigned char* addr, size_t length, const std::vector<Certificate>& keys,
124                 const std::function<void(float)>& set_progress) {
125   if (set_progress) {
126     set_progress(0.0);
127   }
128 
129   // An archive with a whole-file signature will end in six bytes:
130   //
131   //   (2-byte signature start) $ff $ff (2-byte comment size)
132   //
133   // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by
134   // reading this footer, this tells us how far back from the end we have to start reading to find
135   // the whole comment.
136 
137 #define FOOTER_SIZE 6
138 
139   if (length < FOOTER_SIZE) {
140     LOG(ERROR) << "not big enough to contain footer";
141     return VERIFY_FAILURE;
142   }
143 
144   const unsigned char* footer = addr + length - FOOTER_SIZE;
145 
146   if (footer[2] != 0xff || footer[3] != 0xff) {
147     LOG(ERROR) << "footer is wrong";
148     return VERIFY_FAILURE;
149   }
150 
151   size_t comment_size = footer[4] + (footer[5] << 8);
152   size_t signature_start = footer[0] + (footer[1] << 8);
153   LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start
154             << " bytes from end";
155 
156   if (signature_start > comment_size) {
157     LOG(ERROR) << "signature start: " << signature_start << " is larger than comment size: "
158                << comment_size;
159     return VERIFY_FAILURE;
160   }
161 
162   if (signature_start <= FOOTER_SIZE) {
163     LOG(ERROR) << "Signature start is in the footer";
164     return VERIFY_FAILURE;
165   }
166 
167 #define EOCD_HEADER_SIZE 22
168 
169   // The end-of-central-directory record is 22 bytes plus any comment length.
170   size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
171 
172   if (length < eocd_size) {
173     LOG(ERROR) << "not big enough to contain EOCD";
174     return VERIFY_FAILURE;
175   }
176 
177   // Determine how much of the file is covered by the signature. This is everything except the
178   // signature data and length, which includes all of the EOCD except for the comment length field
179   // (2 bytes) and the comment data.
180   size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
181 
182   const unsigned char* eocd = addr + length - eocd_size;
183 
184   // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06.
185   if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) {
186     LOG(ERROR) << "signature length doesn't match EOCD marker";
187     return VERIFY_FAILURE;
188   }
189 
190   for (size_t i = 4; i < eocd_size-3; ++i) {
191     if (eocd[i] == 0x50 && eocd[i+1] == 0x4b && eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
192       // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will
193       // find the later (wrong) one, which could be exploitable. Fail the verification if this
194       // sequence occurs anywhere after the real one.
195       LOG(ERROR) << "EOCD marker occurs after start of EOCD";
196       return VERIFY_FAILURE;
197     }
198   }
199 
200   bool need_sha1 = false;
201   bool need_sha256 = false;
202   for (const auto& key : keys) {
203     switch (key.hash_len) {
204       case SHA_DIGEST_LENGTH: need_sha1 = true; break;
205       case SHA256_DIGEST_LENGTH: need_sha256 = true; break;
206     }
207   }
208 
209   SHA_CTX sha1_ctx;
210   SHA256_CTX sha256_ctx;
211   SHA1_Init(&sha1_ctx);
212   SHA256_Init(&sha256_ctx);
213 
214   double frac = -1.0;
215   size_t so_far = 0;
216   while (so_far < signed_len) {
217     // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a
218     // 1196MiB full OTA and 60% for an 89MiB incremental OTA.
219     // http://b/28135231.
220     size_t size = std::min(signed_len - so_far, 16 * MiB);
221 
222     if (need_sha1) SHA1_Update(&sha1_ctx, addr + so_far, size);
223     if (need_sha256) SHA256_Update(&sha256_ctx, addr + so_far, size);
224     so_far += size;
225 
226     if (set_progress) {
227       double f = so_far / (double)signed_len;
228       if (f > frac + 0.02 || size == so_far) {
229         set_progress(f);
230         frac = f;
231       }
232     }
233   }
234 
235   uint8_t sha1[SHA_DIGEST_LENGTH];
236   SHA1_Final(sha1, &sha1_ctx);
237   uint8_t sha256[SHA256_DIGEST_LENGTH];
238   SHA256_Final(sha256, &sha256_ctx);
239 
240   const uint8_t* signature = eocd + eocd_size - signature_start;
241   size_t signature_size = signature_start - FOOTER_SIZE;
242 
243   LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) << ", length: "
244             << signature_size << "): " << print_hex(signature, signature_size);
245 
246   std::vector<uint8_t> sig_der;
247   if (!read_pkcs7(signature, signature_size, &sig_der)) {
248     LOG(ERROR) << "Could not find signature DER block";
249     return VERIFY_FAILURE;
250   }
251 
252   // Check to make sure at least one of the keys matches the signature. Since any key can match,
253   // we need to try each before determining a verification failure has happened.
254   size_t i = 0;
255   for (const auto& key : keys) {
256     const uint8_t* hash;
257     int hash_nid;
258     switch (key.hash_len) {
259       case SHA_DIGEST_LENGTH:
260         hash = sha1;
261         hash_nid = NID_sha1;
262         break;
263       case SHA256_DIGEST_LENGTH:
264         hash = sha256;
265         hash_nid = NID_sha256;
266         break;
267       default:
268         continue;
269     }
270 
271     // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends
272     // after the signature itself.
273     if (key.key_type == Certificate::KEY_TYPE_RSA) {
274       if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(),
275                       key.rsa.get())) {
276         LOG(INFO) << "failed to verify against RSA key " << i;
277         continue;
278       }
279 
280       LOG(INFO) << "whole-file signature verified against RSA key " << i;
281       return VERIFY_SUCCESS;
282     } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) {
283       if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) {
284         LOG(INFO) << "failed to verify against EC key " << i;
285         continue;
286       }
287 
288       LOG(INFO) << "whole-file signature verified against EC key " << i;
289       return VERIFY_SUCCESS;
290     } else {
291       LOG(INFO) << "Unknown key type " << key.key_type;
292     }
293     i++;
294   }
295 
296   if (need_sha1) {
297     LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH);
298   }
299   if (need_sha256) {
300     LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH);
301   }
302   LOG(ERROR) << "failed to verify whole-file signature";
303   return VERIFY_FAILURE;
304 }
305 
parse_rsa_key(FILE * file,uint32_t exponent)306 std::unique_ptr<RSA, RSADeleter> parse_rsa_key(FILE* file, uint32_t exponent) {
307     // Read key length in words and n0inv. n0inv is a precomputed montgomery
308     // parameter derived from the modulus and can be used to speed up
309     // verification. n0inv is 32 bits wide here, assuming the verification logic
310     // uses 32 bit arithmetic. However, BoringSSL may use a word size of 64 bits
311     // internally, in which case we don't have a valid n0inv. Thus, we just
312     // ignore the montgomery parameters and have BoringSSL recompute them
313     // internally. If/When the speedup from using the montgomery parameters
314     // becomes relevant, we can add more sophisticated code here to obtain a
315     // 64-bit n0inv and initialize the montgomery parameters in the key object.
316     uint32_t key_len_words = 0;
317     uint32_t n0inv = 0;
318     if (fscanf(file, " %i , 0x%x", &key_len_words, &n0inv) != 2) {
319         return nullptr;
320     }
321 
322     if (key_len_words > 8192 / 32) {
323         LOG(ERROR) << "key length (" << key_len_words << ") too large";
324         return nullptr;
325     }
326 
327     // Read the modulus.
328     std::unique_ptr<uint32_t[]> modulus(new uint32_t[key_len_words]);
329     if (fscanf(file, " , { %u", &modulus[0]) != 1) {
330         return nullptr;
331     }
332     for (uint32_t i = 1; i < key_len_words; ++i) {
333         if (fscanf(file, " , %u", &modulus[i]) != 1) {
334             return nullptr;
335         }
336     }
337 
338     // Cconvert from little-endian array of little-endian words to big-endian
339     // byte array suitable as input for BN_bin2bn.
340     std::reverse((uint8_t*)modulus.get(),
341                  (uint8_t*)(modulus.get() + key_len_words));
342 
343     // The next sequence of values is the montgomery parameter R^2. Since we
344     // generally don't have a valid |n0inv|, we ignore this (see comment above).
345     uint32_t rr_value;
346     if (fscanf(file, " } , { %u", &rr_value) != 1) {
347         return nullptr;
348     }
349     for (uint32_t i = 1; i < key_len_words; ++i) {
350         if (fscanf(file, " , %u", &rr_value) != 1) {
351             return nullptr;
352         }
353     }
354     if (fscanf(file, " } } ") != 0) {
355         return nullptr;
356     }
357 
358     // Initialize the key.
359     std::unique_ptr<RSA, RSADeleter> key(RSA_new());
360     if (!key) {
361       return nullptr;
362     }
363 
364     key->n = BN_bin2bn((uint8_t*)modulus.get(),
365                        key_len_words * sizeof(uint32_t), NULL);
366     if (!key->n) {
367       return nullptr;
368     }
369 
370     key->e = BN_new();
371     if (!key->e || !BN_set_word(key->e, exponent)) {
372       return nullptr;
373     }
374 
375     return key;
376 }
377 
378 struct BNDeleter {
operator ()BNDeleter379   void operator()(BIGNUM* bn) const {
380     BN_free(bn);
381   }
382 };
383 
parse_ec_key(FILE * file)384 std::unique_ptr<EC_KEY, ECKEYDeleter> parse_ec_key(FILE* file) {
385     uint32_t key_len_bytes = 0;
386     if (fscanf(file, " %i", &key_len_bytes) != 1) {
387         return nullptr;
388     }
389 
390     std::unique_ptr<EC_GROUP, void (*)(EC_GROUP*)> group(
391         EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1), EC_GROUP_free);
392     if (!group) {
393         return nullptr;
394     }
395 
396     // Verify that |key_len| matches the group order.
397     if (key_len_bytes != BN_num_bytes(EC_GROUP_get0_order(group.get()))) {
398         return nullptr;
399     }
400 
401     // Read the public key coordinates. Note that the byte order in the file is
402     // little-endian, so we convert to big-endian here.
403     std::unique_ptr<uint8_t[]> bytes(new uint8_t[key_len_bytes]);
404     std::unique_ptr<BIGNUM, BNDeleter> point[2];
405     for (int i = 0; i < 2; ++i) {
406         unsigned int byte = 0;
407         if (fscanf(file, " , { %u", &byte) != 1) {
408             return nullptr;
409         }
410         bytes[key_len_bytes - 1] = byte;
411 
412         for (size_t i = 1; i < key_len_bytes; ++i) {
413             if (fscanf(file, " , %u", &byte) != 1) {
414                 return nullptr;
415             }
416             bytes[key_len_bytes - i - 1] = byte;
417         }
418 
419         point[i].reset(BN_bin2bn(bytes.get(), key_len_bytes, nullptr));
420         if (!point[i]) {
421             return nullptr;
422         }
423 
424         if (fscanf(file, " }") != 0) {
425             return nullptr;
426         }
427     }
428 
429     if (fscanf(file, " } ") != 0) {
430         return nullptr;
431     }
432 
433     // Create and initialize the key.
434     std::unique_ptr<EC_KEY, ECKEYDeleter> key(EC_KEY_new());
435     if (!key || !EC_KEY_set_group(key.get(), group.get()) ||
436         !EC_KEY_set_public_key_affine_coordinates(key.get(), point[0].get(),
437                                                   point[1].get())) {
438         return nullptr;
439     }
440 
441     return key;
442 }
443 
444 // Reads a file containing one or more public keys as produced by
445 // DumpPublicKey:  this is an RSAPublicKey struct as it would appear
446 // as a C source literal, eg:
447 //
448 //  "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
449 //
450 // For key versions newer than the original 2048-bit e=3 keys
451 // supported by Android, the string is preceded by a version
452 // identifier, eg:
453 //
454 //  "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
455 //
456 // (Note that the braces and commas in this example are actual
457 // characters the parser expects to find in the file; the ellipses
458 // indicate more numbers omitted from this example.)
459 //
460 // The file may contain multiple keys in this format, separated by
461 // commas.  The last key must not be followed by a comma.
462 //
463 // A Certificate is a pair of an RSAPublicKey and a particular hash
464 // (we support SHA-1 and SHA-256; we store the hash length to signify
465 // which is being used).  The hash used is implied by the version number.
466 //
467 //       1: 2048-bit RSA key with e=3 and SHA-1 hash
468 //       2: 2048-bit RSA key with e=65537 and SHA-1 hash
469 //       3: 2048-bit RSA key with e=3 and SHA-256 hash
470 //       4: 2048-bit RSA key with e=65537 and SHA-256 hash
471 //       5: 256-bit EC key using the NIST P-256 curve parameters and SHA-256 hash
472 //
473 // Returns true on success, and appends the found keys (at least one) to certs.
474 // Otherwise returns false if the file failed to parse, or if it contains zero
475 // keys. The contents in certs would be unspecified on failure.
load_keys(const char * filename,std::vector<Certificate> & certs)476 bool load_keys(const char* filename, std::vector<Certificate>& certs) {
477     std::unique_ptr<FILE, decltype(&fclose)> f(fopen(filename, "r"), fclose);
478     if (!f) {
479         PLOG(ERROR) << "error opening " << filename;
480         return false;
481     }
482 
483     while (true) {
484         certs.emplace_back(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
485         Certificate& cert = certs.back();
486         uint32_t exponent = 0;
487 
488         char start_char;
489         if (fscanf(f.get(), " %c", &start_char) != 1) return false;
490         if (start_char == '{') {
491             // a version 1 key has no version specifier.
492             cert.key_type = Certificate::KEY_TYPE_RSA;
493             exponent = 3;
494             cert.hash_len = SHA_DIGEST_LENGTH;
495         } else if (start_char == 'v') {
496             int version;
497             if (fscanf(f.get(), "%d {", &version) != 1) return false;
498             switch (version) {
499                 case 2:
500                     cert.key_type = Certificate::KEY_TYPE_RSA;
501                     exponent = 65537;
502                     cert.hash_len = SHA_DIGEST_LENGTH;
503                     break;
504                 case 3:
505                     cert.key_type = Certificate::KEY_TYPE_RSA;
506                     exponent = 3;
507                     cert.hash_len = SHA256_DIGEST_LENGTH;
508                     break;
509                 case 4:
510                     cert.key_type = Certificate::KEY_TYPE_RSA;
511                     exponent = 65537;
512                     cert.hash_len = SHA256_DIGEST_LENGTH;
513                     break;
514                 case 5:
515                     cert.key_type = Certificate::KEY_TYPE_EC;
516                     cert.hash_len = SHA256_DIGEST_LENGTH;
517                     break;
518                 default:
519                     return false;
520             }
521         }
522 
523         if (cert.key_type == Certificate::KEY_TYPE_RSA) {
524             cert.rsa = parse_rsa_key(f.get(), exponent);
525             if (!cert.rsa) {
526               return false;
527             }
528 
529             LOG(INFO) << "read key e=" << exponent << " hash=" << cert.hash_len;
530         } else if (cert.key_type == Certificate::KEY_TYPE_EC) {
531             cert.ec = parse_ec_key(f.get());
532             if (!cert.ec) {
533               return false;
534             }
535         } else {
536             LOG(ERROR) << "Unknown key type " << cert.key_type;
537             return false;
538         }
539 
540         // if the line ends in a comma, this file has more keys.
541         int ch = fgetc(f.get());
542         if (ch == ',') {
543             // more keys to come.
544             continue;
545         } else if (ch == EOF) {
546             break;
547         } else {
548             LOG(ERROR) << "unexpected character between keys";
549             return false;
550         }
551     }
552 
553     return true;
554 }
555