1 //
2 // Copyright (C) 2014 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 "update_engine/payload_consumer/payload_verifier.h"
18 
19 #include <utility>
20 #include <vector>
21 
22 #include <base/logging.h>
23 #include <openssl/pem.h>
24 
25 #include "update_engine/common/constants.h"
26 #include "update_engine/common/utils.h"
27 #include "update_engine/payload_consumer/certificate_parser_interface.h"
28 #include "update_engine/update_metadata.pb.h"
29 
30 using std::string;
31 
32 namespace chromeos_update_engine {
33 
34 namespace {
35 
36 // The ASN.1 DigestInfo prefix for encoding SHA256 digest. The complete 51-byte
37 // DigestInfo consists of 19-byte SHA256_DIGEST_INFO_PREFIX and 32-byte SHA256
38 // digest.
39 //
40 // SEQUENCE(2+49) {
41 //   SEQUENCE(2+13) {
42 //     OBJECT(2+9) id-sha256
43 //     NULL(2+0)
44 //   }
45 //   OCTET STRING(2+32) <actual signature bytes...>
46 // }
47 const uint8_t kSHA256DigestInfoPrefix[] = {
48     0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
49     0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20,
50 };
51 
52 }  // namespace
53 
CreateInstance(const std::string & pem_public_key)54 std::unique_ptr<PayloadVerifier> PayloadVerifier::CreateInstance(
55     const std::string& pem_public_key) {
56   std::unique_ptr<BIO, decltype(&BIO_free)> bp(
57       BIO_new_mem_buf(pem_public_key.data(), pem_public_key.size()), BIO_free);
58   if (!bp) {
59     LOG(ERROR) << "Failed to read " << pem_public_key << " into buffer.";
60     return nullptr;
61   }
62 
63   auto pub_key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>(
64       PEM_read_bio_PUBKEY(bp.get(), nullptr, nullptr, nullptr), EVP_PKEY_free);
65   if (!pub_key) {
66     LOG(ERROR) << "Failed to parse the public key in: " << pem_public_key;
67     return nullptr;
68   }
69 
70   std::vector<std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>> keys;
71   keys.emplace_back(std::move(pub_key));
72   return std::unique_ptr<PayloadVerifier>(new PayloadVerifier(std::move(keys)));
73 }
74 
CreateInstanceFromZipPath(const std::string & certificate_zip_path)75 std::unique_ptr<PayloadVerifier> PayloadVerifier::CreateInstanceFromZipPath(
76     const std::string& certificate_zip_path) {
77   auto parser = CreateCertificateParser();
78   if (!parser) {
79     LOG(ERROR) << "Failed to create certificate parser from "
80                << certificate_zip_path;
81     return nullptr;
82   }
83 
84   std::vector<std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>> public_keys;
85   if (!parser->ReadPublicKeysFromCertificates(certificate_zip_path,
86                                               &public_keys) ||
87       public_keys.empty()) {
88     LOG(ERROR) << "Failed to parse public keys in: " << certificate_zip_path;
89     return nullptr;
90   }
91 
92   return std::unique_ptr<PayloadVerifier>(
93       new PayloadVerifier(std::move(public_keys)));
94 }
95 
VerifySignature(const string & signature_proto,const brillo::Blob & sha256_hash_data) const96 bool PayloadVerifier::VerifySignature(
97     const string& signature_proto, const brillo::Blob& sha256_hash_data) const {
98   TEST_AND_RETURN_FALSE(!public_keys_.empty());
99 
100   Signatures signatures;
101   LOG(INFO) << "signature blob size = " << signature_proto.size();
102   TEST_AND_RETURN_FALSE(signatures.ParseFromString(signature_proto));
103 
104   if (!signatures.signatures_size()) {
105     LOG(ERROR) << "No signatures stored in the blob.";
106     return false;
107   }
108 
109   std::vector<brillo::Blob> tested_hashes;
110   // Tries every signature in the signature blob.
111   for (int i = 0; i < signatures.signatures_size(); i++) {
112     const Signatures::Signature& signature = signatures.signatures(i);
113     brillo::Blob sig_data;
114     if (signature.has_unpadded_signature_size()) {
115       TEST_AND_RETURN_FALSE(signature.unpadded_signature_size() <=
116                             signature.data().size());
117       LOG(INFO) << "Truncating the signature to its unpadded size: "
118                 << signature.unpadded_signature_size() << ".";
119       sig_data.assign(
120           signature.data().begin(),
121           signature.data().begin() + signature.unpadded_signature_size());
122     } else {
123       sig_data.assign(signature.data().begin(), signature.data().end());
124     }
125 
126     brillo::Blob sig_hash_data;
127     if (VerifyRawSignature(sig_data, sha256_hash_data, &sig_hash_data)) {
128       LOG(INFO) << "Verified correct signature " << i + 1 << " out of "
129                 << signatures.signatures_size() << " signatures.";
130       return true;
131     }
132     if (!sig_hash_data.empty()) {
133       tested_hashes.push_back(sig_hash_data);
134     }
135   }
136   LOG(ERROR) << "None of the " << signatures.signatures_size()
137              << " signatures is correct. Expected hash before padding:";
138   utils::HexDumpVector(sha256_hash_data);
139   LOG(ERROR) << "But found RSA decrypted hashes:";
140   for (const auto& sig_hash_data : tested_hashes) {
141     utils::HexDumpVector(sig_hash_data);
142   }
143   return false;
144 }
145 
VerifyRawSignature(const brillo::Blob & sig_data,const brillo::Blob & sha256_hash_data,brillo::Blob * decrypted_sig_data) const146 bool PayloadVerifier::VerifyRawSignature(
147     const brillo::Blob& sig_data,
148     const brillo::Blob& sha256_hash_data,
149     brillo::Blob* decrypted_sig_data) const {
150   TEST_AND_RETURN_FALSE(!public_keys_.empty());
151 
152   for (const auto& public_key : public_keys_) {
153     int key_type = EVP_PKEY_id(public_key.get());
154     if (key_type == EVP_PKEY_RSA) {
155       brillo::Blob sig_hash_data;
156       if (!GetRawHashFromSignature(
157               sig_data, public_key.get(), &sig_hash_data)) {
158         LOG(WARNING)
159             << "Failed to get the raw hash with RSA key. Trying other keys.";
160         continue;
161       }
162 
163       if (decrypted_sig_data != nullptr) {
164         *decrypted_sig_data = sig_hash_data;
165       }
166 
167       brillo::Blob padded_hash_data = sha256_hash_data;
168       TEST_AND_RETURN_FALSE(
169           PadRSASHA256Hash(&padded_hash_data, sig_hash_data.size()));
170 
171       if (padded_hash_data == sig_hash_data) {
172         return true;
173       }
174     } else if (key_type == EVP_PKEY_EC) {
175       EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(public_key.get());
176       TEST_AND_RETURN_FALSE(ec_key != nullptr);
177       if (ECDSA_verify(0,
178                        sha256_hash_data.data(),
179                        sha256_hash_data.size(),
180                        sig_data.data(),
181                        sig_data.size(),
182                        ec_key) == 1) {
183         return true;
184       }
185     } else {
186       LOG(ERROR) << "Unsupported key type " << key_type;
187       return false;
188     }
189   }
190   LOG(INFO) << "Failed to verify the signature with " << public_keys_.size()
191             << " keys.";
192   return false;
193 }
194 
GetRawHashFromSignature(const brillo::Blob & sig_data,const EVP_PKEY * public_key,brillo::Blob * out_hash_data) const195 bool PayloadVerifier::GetRawHashFromSignature(
196     const brillo::Blob& sig_data,
197     const EVP_PKEY* public_key,
198     brillo::Blob* out_hash_data) const {
199   // The code below executes the equivalent of:
200   //
201   // openssl rsautl -verify -pubin -inkey <(echo pem_public_key)
202   //   -in |sig_data| -out |out_hash_data|
203   RSA* rsa = EVP_PKEY_get0_RSA(const_cast<EVP_PKEY*>(public_key));
204 
205   TEST_AND_RETURN_FALSE(rsa != nullptr);
206   unsigned int keysize = RSA_size(rsa);
207   if (sig_data.size() > 2 * keysize) {
208     LOG(ERROR) << "Signature size is too big for public key size.";
209     return false;
210   }
211 
212   // Decrypts the signature.
213   brillo::Blob hash_data(keysize);
214   int decrypt_size = RSA_public_decrypt(
215       sig_data.size(), sig_data.data(), hash_data.data(), rsa, RSA_NO_PADDING);
216   TEST_AND_RETURN_FALSE(decrypt_size > 0 &&
217                         decrypt_size <= static_cast<int>(hash_data.size()));
218   hash_data.resize(decrypt_size);
219   out_hash_data->swap(hash_data);
220   return true;
221 }
222 
PadRSASHA256Hash(brillo::Blob * hash,size_t rsa_size)223 bool PayloadVerifier::PadRSASHA256Hash(brillo::Blob* hash, size_t rsa_size) {
224   TEST_AND_RETURN_FALSE(hash->size() == kSHA256Size);
225   TEST_AND_RETURN_FALSE(rsa_size == 256 || rsa_size == 512);
226 
227   // The following is a standard PKCS1-v1_5 padding for SHA256 signatures, as
228   // defined in RFC3447 section 9.2. It is prepended to the actual signature
229   // (32 bytes) to form a sequence of 256|512 bytes (2048|4096 bits) that is
230   // amenable to RSA signing. The padded hash will look as follows:
231   //
232   //    0x00 0x01 0xff ... 0xff 0x00  ASN1HEADER  SHA256HASH
233   //   |-----------205|461----------||----19----||----32----|
234   size_t padding_string_size =
235       rsa_size - hash->size() - sizeof(kSHA256DigestInfoPrefix) - 3;
236   brillo::Blob padded_result = brillo::CombineBlobs({
237       {0x00, 0x01},
238       brillo::Blob(padding_string_size, 0xff),
239       {0x00},
240       brillo::Blob(kSHA256DigestInfoPrefix,
241                    kSHA256DigestInfoPrefix + sizeof(kSHA256DigestInfoPrefix)),
242       *hash,
243   });
244 
245   *hash = std::move(padded_result);
246   TEST_AND_RETURN_FALSE(hash->size() == rsa_size);
247   return true;
248 }
249 
250 }  // namespace chromeos_update_engine
251