1 //
2 // Copyright (C) 2011 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_generator/payload_signer.h"
18 
19 #include <endian.h>
20 
21 #include <memory>
22 #include <utility>
23 
24 #include <base/logging.h>
25 #include <base/strings/string_number_conversions.h>
26 #include <base/strings/string_split.h>
27 #include <base/strings/string_util.h>
28 #include <brillo/data_encoding.h>
29 #include <openssl/err.h>
30 #include <openssl/pem.h>
31 
32 #include "update_engine/common/constants.h"
33 #include "update_engine/common/hash_calculator.h"
34 #include "update_engine/common/subprocess.h"
35 #include "update_engine/common/utils.h"
36 #include "update_engine/payload_consumer/delta_performer.h"
37 #include "update_engine/payload_consumer/payload_constants.h"
38 #include "update_engine/payload_consumer/payload_metadata.h"
39 #include "update_engine/payload_consumer/payload_verifier.h"
40 #include "update_engine/payload_generator/delta_diff_generator.h"
41 #include "update_engine/payload_generator/payload_file.h"
42 #include "update_engine/update_metadata.pb.h"
43 
44 using std::string;
45 using std::vector;
46 
47 namespace chromeos_update_engine {
48 
49 namespace {
50 // Given raw |signatures|, packs them into a protobuf and serializes it into a
51 // string. Returns true on success, false otherwise.
ConvertSignaturesToProtobuf(const vector<brillo::Blob> & signatures,const vector<size_t> & padded_signature_sizes,string * out_serialized_signature)52 bool ConvertSignaturesToProtobuf(const vector<brillo::Blob>& signatures,
53                                  const vector<size_t>& padded_signature_sizes,
54                                  string* out_serialized_signature) {
55   TEST_AND_RETURN_FALSE(signatures.size() == padded_signature_sizes.size());
56   // Pack it into a protobuf
57   Signatures out_message;
58   for (size_t i = 0; i < signatures.size(); i++) {
59     const auto& signature = signatures[i];
60     const auto& padded_signature_size = padded_signature_sizes[i];
61     TEST_AND_RETURN_FALSE(padded_signature_size >= signature.size());
62     Signatures::Signature* sig_message = out_message.add_signatures();
63     // Skip assigning the same version number because we don't need to be
64     // compatible with old major version 1 client anymore.
65 
66     // TODO(Xunchang) don't need to set the unpadded_signature_size field for
67     // RSA key signed signatures.
68     sig_message->set_unpadded_signature_size(signature.size());
69     brillo::Blob padded_signature = signature;
70     padded_signature.insert(
71         padded_signature.end(), padded_signature_size - signature.size(), 0);
72     sig_message->set_data(padded_signature.data(), padded_signature.size());
73   }
74 
75   // Serialize protobuf
76   TEST_AND_RETURN_FALSE(
77       out_message.SerializeToString(out_serialized_signature));
78   LOG(INFO) << "Signature blob size: " << out_serialized_signature->size();
79   return true;
80 }
81 
82 // Given an unsigned payload under |payload_path| and the |payload_signature|
83 // and |metadata_signature| generates an updated payload that includes the
84 // signatures. It populates |out_metadata_size| with the size of the final
85 // manifest after adding the fake signature operation, and
86 // |out_signatures_offset| with the expected offset for the new blob, and
87 // |out_metadata_signature_size| which will be size of |metadata_signature|
88 // if the payload major version supports metadata signature, 0 otherwise.
89 // Returns true on success, false otherwise.
AddSignatureBlobToPayload(const string & payload_path,const string & payload_signature,const string & metadata_signature,brillo::Blob * out_payload,uint64_t * out_metadata_size,uint32_t * out_metadata_signature_size,uint64_t * out_signatures_offset)90 bool AddSignatureBlobToPayload(const string& payload_path,
91                                const string& payload_signature,
92                                const string& metadata_signature,
93                                brillo::Blob* out_payload,
94                                uint64_t* out_metadata_size,
95                                uint32_t* out_metadata_signature_size,
96                                uint64_t* out_signatures_offset) {
97   uint64_t manifest_offset = 20;
98   const int kProtobufSizeOffset = 12;
99 
100   brillo::Blob payload;
101   TEST_AND_RETURN_FALSE(utils::ReadFile(payload_path, &payload));
102   PayloadMetadata payload_metadata;
103   TEST_AND_RETURN_FALSE(payload_metadata.ParsePayloadHeader(payload));
104   uint64_t metadata_size = payload_metadata.GetMetadataSize();
105   uint32_t metadata_signature_size =
106       payload_metadata.GetMetadataSignatureSize();
107   // Write metadata signature size in header.
108   uint32_t metadata_signature_size_be = htobe32(metadata_signature.size());
109   memcpy(payload.data() + manifest_offset,
110          &metadata_signature_size_be,
111          sizeof(metadata_signature_size_be));
112   manifest_offset += sizeof(metadata_signature_size_be);
113   // Replace metadata signature.
114   payload.erase(payload.begin() + metadata_size,
115                 payload.begin() + metadata_size + metadata_signature_size);
116   payload.insert(payload.begin() + metadata_size,
117                  metadata_signature.begin(),
118                  metadata_signature.end());
119   metadata_signature_size = metadata_signature.size();
120   LOG(INFO) << "Metadata signature size: " << metadata_signature_size;
121 
122   DeltaArchiveManifest manifest;
123   TEST_AND_RETURN_FALSE(payload_metadata.GetManifest(payload, &manifest));
124 
125   // Is there already a signature op in place?
126   if (manifest.has_signatures_size()) {
127     // The signature op is tied to the size of the signature blob, but not it's
128     // contents. We don't allow the manifest to change if there is already an op
129     // present, because that might invalidate previously generated
130     // hashes/signatures.
131     if (manifest.signatures_size() != payload_signature.size()) {
132       LOG(ERROR) << "Attempt to insert different signature sized blob. "
133                  << "(current:" << manifest.signatures_size()
134                  << "new:" << payload_signature.size() << ")";
135       return false;
136     }
137 
138     LOG(INFO) << "Matching signature sizes already present.";
139   } else {
140     // Updates the manifest to include the signature operation.
141     PayloadSigner::AddSignatureToManifest(
142         payload.size() - metadata_size - metadata_signature_size,
143         payload_signature.size(),
144         &manifest);
145 
146     // Updates the payload to include the new manifest.
147     string serialized_manifest;
148     TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
149     LOG(INFO) << "Updated protobuf size: " << serialized_manifest.size();
150     payload.erase(payload.begin() + manifest_offset,
151                   payload.begin() + metadata_size);
152     payload.insert(payload.begin() + manifest_offset,
153                    serialized_manifest.begin(),
154                    serialized_manifest.end());
155 
156     // Updates the protobuf size.
157     uint64_t size_be = htobe64(serialized_manifest.size());
158     memcpy(&payload[kProtobufSizeOffset], &size_be, sizeof(size_be));
159     metadata_size = serialized_manifest.size() + manifest_offset;
160 
161     LOG(INFO) << "Updated payload size: " << payload.size();
162     LOG(INFO) << "Updated metadata size: " << metadata_size;
163   }
164   uint64_t signatures_offset =
165       metadata_size + metadata_signature_size + manifest.signatures_offset();
166   LOG(INFO) << "Signature Blob Offset: " << signatures_offset;
167   payload.resize(signatures_offset);
168   payload.insert(payload.begin() + signatures_offset,
169                  payload_signature.begin(),
170                  payload_signature.end());
171 
172   *out_payload = std::move(payload);
173   *out_metadata_size = metadata_size;
174   *out_metadata_signature_size = metadata_signature_size;
175   *out_signatures_offset = signatures_offset;
176   return true;
177 }
178 
179 // Given a |payload| with correct signature op and metadata signature size in
180 // header and |metadata_size|, |metadata_signature_size|, |signatures_offset|,
181 // calculate hash for payload and metadata, save it to |out_hash_data| and
182 // |out_metadata_hash|.
CalculateHashFromPayload(const brillo::Blob & payload,const uint64_t metadata_size,const uint32_t metadata_signature_size,const uint64_t signatures_offset,brillo::Blob * out_hash_data,brillo::Blob * out_metadata_hash)183 bool CalculateHashFromPayload(const brillo::Blob& payload,
184                               const uint64_t metadata_size,
185                               const uint32_t metadata_signature_size,
186                               const uint64_t signatures_offset,
187                               brillo::Blob* out_hash_data,
188                               brillo::Blob* out_metadata_hash) {
189   if (out_metadata_hash) {
190     // Calculates the hash on the manifest.
191     TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfBytes(
192         payload.data(), metadata_size, out_metadata_hash));
193   }
194   if (out_hash_data) {
195     // Calculates the hash on the updated payload. Note that we skip metadata
196     // signature and payload signature.
197     HashCalculator calc;
198     TEST_AND_RETURN_FALSE(calc.Update(payload.data(), metadata_size));
199     TEST_AND_RETURN_FALSE(signatures_offset >=
200                           metadata_size + metadata_signature_size);
201     TEST_AND_RETURN_FALSE(calc.Update(
202         payload.data() + metadata_size + metadata_signature_size,
203         signatures_offset - metadata_size - metadata_signature_size));
204     TEST_AND_RETURN_FALSE(calc.Finalize());
205     *out_hash_data = calc.raw_hash();
206   }
207   return true;
208 }
209 
CreatePrivateKeyFromPath(const string & private_key_path)210 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> CreatePrivateKeyFromPath(
211     const string& private_key_path) {
212   FILE* fprikey = fopen(private_key_path.c_str(), "rb");
213   if (!fprikey) {
214     PLOG(ERROR) << "Failed to read " << private_key_path;
215     return {nullptr, nullptr};
216   }
217 
218   auto private_key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>(
219       PEM_read_PrivateKey(fprikey, nullptr, nullptr, nullptr), EVP_PKEY_free);
220   fclose(fprikey);
221   return private_key;
222 }
223 
224 }  // namespace
225 
GetMaximumSignatureSize(const string & private_key_path,size_t * signature_size)226 bool PayloadSigner::GetMaximumSignatureSize(const string& private_key_path,
227                                             size_t* signature_size) {
228   *signature_size = 0;
229   auto private_key = CreatePrivateKeyFromPath(private_key_path);
230   if (!private_key) {
231     LOG(ERROR) << "Failed to create private key from " << private_key_path;
232     return false;
233   }
234 
235   *signature_size = EVP_PKEY_size(private_key.get());
236   return true;
237 }
238 
AddSignatureToManifest(uint64_t signature_blob_offset,uint64_t signature_blob_length,DeltaArchiveManifest * manifest)239 void PayloadSigner::AddSignatureToManifest(uint64_t signature_blob_offset,
240                                            uint64_t signature_blob_length,
241                                            DeltaArchiveManifest* manifest) {
242   LOG(INFO) << "Making room for signature in file";
243   manifest->set_signatures_offset(signature_blob_offset);
244   LOG(INFO) << "set? " << manifest->has_signatures_offset();
245   manifest->set_signatures_offset(signature_blob_offset);
246   manifest->set_signatures_size(signature_blob_length);
247 }
248 
VerifySignedPayload(const string & payload_path,const string & public_key_path)249 bool PayloadSigner::VerifySignedPayload(const string& payload_path,
250                                         const string& public_key_path) {
251   brillo::Blob payload;
252   TEST_AND_RETURN_FALSE(utils::ReadFile(payload_path, &payload));
253   PayloadMetadata payload_metadata;
254   TEST_AND_RETURN_FALSE(payload_metadata.ParsePayloadHeader(payload));
255   DeltaArchiveManifest manifest;
256   TEST_AND_RETURN_FALSE(payload_metadata.GetManifest(payload, &manifest));
257   TEST_AND_RETURN_FALSE(manifest.has_signatures_offset() &&
258                         manifest.has_signatures_size());
259   uint64_t metadata_size = payload_metadata.GetMetadataSize();
260   uint32_t metadata_signature_size =
261       payload_metadata.GetMetadataSignatureSize();
262   uint64_t signatures_offset =
263       metadata_size + metadata_signature_size + manifest.signatures_offset();
264   CHECK_EQ(payload.size(), signatures_offset + manifest.signatures_size());
265   brillo::Blob payload_hash, metadata_hash;
266   TEST_AND_RETURN_FALSE(CalculateHashFromPayload(payload,
267                                                  metadata_size,
268                                                  metadata_signature_size,
269                                                  signatures_offset,
270                                                  &payload_hash,
271                                                  &metadata_hash));
272   string signature(payload.begin() + signatures_offset, payload.end());
273   string public_key;
274   TEST_AND_RETURN_FALSE(utils::ReadFile(public_key_path, &public_key));
275   TEST_AND_RETURN_FALSE(payload_hash.size() == kSHA256Size);
276 
277   auto payload_verifier = PayloadVerifier::CreateInstance(public_key);
278   TEST_AND_RETURN_FALSE(payload_verifier != nullptr);
279 
280   TEST_AND_RETURN_FALSE(
281       payload_verifier->VerifySignature(signature, payload_hash));
282   if (metadata_signature_size) {
283     signature.assign(payload.begin() + metadata_size,
284                      payload.begin() + metadata_size + metadata_signature_size);
285     TEST_AND_RETURN_FALSE(metadata_hash.size() == kSHA256Size);
286     TEST_AND_RETURN_FALSE(
287         payload_verifier->VerifySignature(signature, metadata_hash));
288   }
289   return true;
290 }
291 
SignHash(const brillo::Blob & hash,const string & private_key_path,brillo::Blob * out_signature)292 bool PayloadSigner::SignHash(const brillo::Blob& hash,
293                              const string& private_key_path,
294                              brillo::Blob* out_signature) {
295   LOG(INFO) << "Signing hash with private key: " << private_key_path;
296   // We expect unpadded SHA256 hash coming in
297   TEST_AND_RETURN_FALSE(hash.size() == kSHA256Size);
298   // The code below executes the equivalent of:
299   //
300   // openssl rsautl -raw -sign -inkey |private_key_path|
301   //   -in |padded_hash| -out |out_signature|
302 
303   auto private_key = CreatePrivateKeyFromPath(private_key_path);
304   if (!private_key) {
305     LOG(ERROR) << "Failed to create private key from " << private_key_path;
306     return false;
307   }
308 
309   int key_type = EVP_PKEY_id(private_key.get());
310   brillo::Blob signature;
311   if (key_type == EVP_PKEY_RSA) {
312     RSA* rsa = EVP_PKEY_get0_RSA(private_key.get());
313     TEST_AND_RETURN_FALSE(rsa != nullptr);
314 
315     brillo::Blob padded_hash = hash;
316     PayloadVerifier::PadRSASHA256Hash(&padded_hash, RSA_size(rsa));
317 
318     signature.resize(RSA_size(rsa));
319     ssize_t signature_size = RSA_private_encrypt(padded_hash.size(),
320                                                  padded_hash.data(),
321                                                  signature.data(),
322                                                  rsa,
323                                                  RSA_NO_PADDING);
324 
325     if (signature_size < 0) {
326       LOG(ERROR) << "Signing hash failed: "
327                  << ERR_error_string(ERR_get_error(), nullptr);
328       return false;
329     }
330     TEST_AND_RETURN_FALSE(static_cast<size_t>(signature_size) ==
331                           signature.size());
332   } else if (key_type == EVP_PKEY_EC) {
333     EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(private_key.get());
334     TEST_AND_RETURN_FALSE(ec_key != nullptr);
335 
336     signature.resize(ECDSA_size(ec_key));
337     unsigned int signature_size;
338     if (ECDSA_sign(0,
339                    hash.data(),
340                    hash.size(),
341                    signature.data(),
342                    &signature_size,
343                    ec_key) != 1) {
344       LOG(ERROR) << "Signing hash failed: "
345                  << ERR_error_string(ERR_get_error(), nullptr);
346       return false;
347     }
348 
349     // NIST P-256
350     LOG(ERROR) << "signature max size " << signature.size() << " size "
351                << signature_size;
352     TEST_AND_RETURN_FALSE(signature.size() >= signature_size);
353     signature.resize(signature_size);
354   } else {
355     LOG(ERROR) << "key_type " << key_type << " isn't supported for signing";
356     return false;
357   }
358   out_signature->swap(signature);
359   return true;
360 }
361 
SignHashWithKeys(const brillo::Blob & hash_data,const vector<string> & private_key_paths,string * out_serialized_signature)362 bool PayloadSigner::SignHashWithKeys(const brillo::Blob& hash_data,
363                                      const vector<string>& private_key_paths,
364                                      string* out_serialized_signature) {
365   vector<brillo::Blob> signatures;
366   vector<size_t> padded_signature_sizes;
367   for (const string& path : private_key_paths) {
368     brillo::Blob signature;
369     TEST_AND_RETURN_FALSE(SignHash(hash_data, path, &signature));
370     signatures.push_back(signature);
371 
372     size_t padded_signature_size;
373     TEST_AND_RETURN_FALSE(
374         GetMaximumSignatureSize(path, &padded_signature_size));
375     padded_signature_sizes.push_back(padded_signature_size);
376   }
377   TEST_AND_RETURN_FALSE(ConvertSignaturesToProtobuf(
378       signatures, padded_signature_sizes, out_serialized_signature));
379   return true;
380 }
381 
SignPayload(const string & unsigned_payload_path,const vector<string> & private_key_paths,const uint64_t metadata_size,const uint32_t metadata_signature_size,const uint64_t signatures_offset,string * out_serialized_signature)382 bool PayloadSigner::SignPayload(const string& unsigned_payload_path,
383                                 const vector<string>& private_key_paths,
384                                 const uint64_t metadata_size,
385                                 const uint32_t metadata_signature_size,
386                                 const uint64_t signatures_offset,
387                                 string* out_serialized_signature) {
388   brillo::Blob payload;
389   TEST_AND_RETURN_FALSE(utils::ReadFile(unsigned_payload_path, &payload));
390   brillo::Blob hash_data;
391   TEST_AND_RETURN_FALSE(CalculateHashFromPayload(payload,
392                                                  metadata_size,
393                                                  metadata_signature_size,
394                                                  signatures_offset,
395                                                  &hash_data,
396                                                  nullptr));
397   TEST_AND_RETURN_FALSE(
398       SignHashWithKeys(hash_data, private_key_paths, out_serialized_signature));
399   return true;
400 }
401 
SignatureBlobLength(const vector<string> & private_key_paths,uint64_t * out_length)402 bool PayloadSigner::SignatureBlobLength(const vector<string>& private_key_paths,
403                                         uint64_t* out_length) {
404   DCHECK(out_length);
405   brillo::Blob hash_blob;
406   TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfData({'x'}, &hash_blob));
407   string sig_blob;
408   TEST_AND_RETURN_FALSE(
409       SignHashWithKeys(hash_blob, private_key_paths, &sig_blob));
410   *out_length = sig_blob.size();
411   return true;
412 }
413 
HashPayloadForSigning(const string & payload_path,const vector<size_t> & signature_sizes,brillo::Blob * out_payload_hash_data,brillo::Blob * out_metadata_hash)414 bool PayloadSigner::HashPayloadForSigning(const string& payload_path,
415                                           const vector<size_t>& signature_sizes,
416                                           brillo::Blob* out_payload_hash_data,
417                                           brillo::Blob* out_metadata_hash) {
418   // Create a signature blob with signatures filled with 0.
419   // Will be used for both payload signature and metadata signature.
420   vector<brillo::Blob> signatures;
421   for (int signature_size : signature_sizes) {
422     signatures.emplace_back(signature_size, 0);
423   }
424   string signature;
425   TEST_AND_RETURN_FALSE(
426       ConvertSignaturesToProtobuf(signatures, signature_sizes, &signature));
427 
428   brillo::Blob payload;
429   uint64_t metadata_size, signatures_offset;
430   uint32_t metadata_signature_size;
431   // Prepare payload for hashing.
432   TEST_AND_RETURN_FALSE(AddSignatureBlobToPayload(payload_path,
433                                                   signature,
434                                                   signature,
435                                                   &payload,
436                                                   &metadata_size,
437                                                   &metadata_signature_size,
438                                                   &signatures_offset));
439   TEST_AND_RETURN_FALSE(CalculateHashFromPayload(payload,
440                                                  metadata_size,
441                                                  metadata_signature_size,
442                                                  signatures_offset,
443                                                  out_payload_hash_data,
444                                                  out_metadata_hash));
445   return true;
446 }
447 
AddSignatureToPayload(const string & payload_path,const vector<size_t> & padded_signature_sizes,const vector<brillo::Blob> & payload_signatures,const vector<brillo::Blob> & metadata_signatures,const string & signed_payload_path,uint64_t * out_metadata_size)448 bool PayloadSigner::AddSignatureToPayload(
449     const string& payload_path,
450     const vector<size_t>& padded_signature_sizes,
451     const vector<brillo::Blob>& payload_signatures,
452     const vector<brillo::Blob>& metadata_signatures,
453     const string& signed_payload_path,
454     uint64_t* out_metadata_size) {
455   // TODO(petkov): Reduce memory usage -- the payload is manipulated in memory.
456 
457   // Loads the payload and adds the signature op to it.
458   string payload_signature, metadata_signature;
459   TEST_AND_RETURN_FALSE(ConvertSignaturesToProtobuf(
460       payload_signatures, padded_signature_sizes, &payload_signature));
461   if (!metadata_signatures.empty()) {
462     TEST_AND_RETURN_FALSE(ConvertSignaturesToProtobuf(
463         metadata_signatures, padded_signature_sizes, &metadata_signature));
464   }
465   brillo::Blob payload;
466   uint64_t signatures_offset;
467   uint32_t metadata_signature_size;
468   TEST_AND_RETURN_FALSE(AddSignatureBlobToPayload(payload_path,
469                                                   payload_signature,
470                                                   metadata_signature,
471                                                   &payload,
472                                                   out_metadata_size,
473                                                   &metadata_signature_size,
474                                                   &signatures_offset));
475 
476   LOG(INFO) << "Signed payload size: " << payload.size();
477   TEST_AND_RETURN_FALSE(utils::WriteFile(
478       signed_payload_path.c_str(), payload.data(), payload.size()));
479   return true;
480 }
481 
GetMetadataSignature(const void * const metadata,size_t metadata_size,const string & private_key_path,string * out_signature)482 bool PayloadSigner::GetMetadataSignature(const void* const metadata,
483                                          size_t metadata_size,
484                                          const string& private_key_path,
485                                          string* out_signature) {
486   // Calculates the hash on the updated payload. Note that the payload includes
487   // the signature op but doesn't include the signature blob at the end.
488   brillo::Blob metadata_hash;
489   TEST_AND_RETURN_FALSE(
490       HashCalculator::RawHashOfBytes(metadata, metadata_size, &metadata_hash));
491 
492   brillo::Blob signature;
493   TEST_AND_RETURN_FALSE(SignHash(metadata_hash, private_key_path, &signature));
494 
495   *out_signature = brillo::data_encoding::Base64Encode(signature);
496   return true;
497 }
498 
499 }  // namespace chromeos_update_engine
500