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 manifest->set_signatures_size(signature_blob_length);
245 }
246
VerifySignedPayload(const string & payload_path,const string & public_key_path)247 bool PayloadSigner::VerifySignedPayload(const string& payload_path,
248 const string& public_key_path) {
249 brillo::Blob payload;
250 TEST_AND_RETURN_FALSE(utils::ReadFile(payload_path, &payload));
251 PayloadMetadata payload_metadata;
252 TEST_AND_RETURN_FALSE(payload_metadata.ParsePayloadHeader(payload));
253 DeltaArchiveManifest manifest;
254 TEST_AND_RETURN_FALSE(payload_metadata.GetManifest(payload, &manifest));
255 TEST_AND_RETURN_FALSE(manifest.has_signatures_offset() &&
256 manifest.has_signatures_size());
257 uint64_t metadata_size = payload_metadata.GetMetadataSize();
258 uint32_t metadata_signature_size =
259 payload_metadata.GetMetadataSignatureSize();
260 uint64_t signatures_offset =
261 metadata_size + metadata_signature_size + manifest.signatures_offset();
262 CHECK_EQ(payload.size(), signatures_offset + manifest.signatures_size());
263 brillo::Blob payload_hash, metadata_hash;
264 TEST_AND_RETURN_FALSE(CalculateHashFromPayload(payload,
265 metadata_size,
266 metadata_signature_size,
267 signatures_offset,
268 &payload_hash,
269 &metadata_hash));
270 string signature(payload.begin() + signatures_offset, payload.end());
271 string public_key;
272 TEST_AND_RETURN_FALSE(utils::ReadFile(public_key_path, &public_key));
273 TEST_AND_RETURN_FALSE(payload_hash.size() == kSHA256Size);
274
275 auto payload_verifier = PayloadVerifier::CreateInstance(public_key);
276 TEST_AND_RETURN_FALSE(payload_verifier != nullptr);
277
278 TEST_AND_RETURN_FALSE(
279 payload_verifier->VerifySignature(signature, payload_hash));
280 if (metadata_signature_size) {
281 signature.assign(payload.begin() + metadata_size,
282 payload.begin() + metadata_size + metadata_signature_size);
283 TEST_AND_RETURN_FALSE(metadata_hash.size() == kSHA256Size);
284 TEST_AND_RETURN_FALSE(
285 payload_verifier->VerifySignature(signature, metadata_hash));
286 }
287 return true;
288 }
289
SignHash(const brillo::Blob & hash,const string & private_key_path,brillo::Blob * out_signature)290 bool PayloadSigner::SignHash(const brillo::Blob& hash,
291 const string& private_key_path,
292 brillo::Blob* out_signature) {
293 LOG(INFO) << "Signing hash with private key: " << private_key_path;
294 // We expect unpadded SHA256 hash coming in
295 TEST_AND_RETURN_FALSE(hash.size() == kSHA256Size);
296 // The code below executes the equivalent of:
297 //
298 // openssl rsautl -raw -sign -inkey |private_key_path|
299 // -in |padded_hash| -out |out_signature|
300
301 auto private_key = CreatePrivateKeyFromPath(private_key_path);
302 if (!private_key) {
303 LOG(ERROR) << "Failed to create private key from " << private_key_path;
304 return false;
305 }
306
307 int key_type = EVP_PKEY_id(private_key.get());
308 brillo::Blob signature;
309 if (key_type == EVP_PKEY_RSA) {
310 RSA* rsa = EVP_PKEY_get0_RSA(private_key.get());
311 TEST_AND_RETURN_FALSE(rsa != nullptr);
312
313 brillo::Blob padded_hash = hash;
314 PayloadVerifier::PadRSASHA256Hash(&padded_hash, RSA_size(rsa));
315
316 signature.resize(RSA_size(rsa));
317 ssize_t signature_size = RSA_private_encrypt(padded_hash.size(),
318 padded_hash.data(),
319 signature.data(),
320 rsa,
321 RSA_NO_PADDING);
322 if (signature_size < 0) {
323 LOG(ERROR) << "Signing hash failed: "
324 << ERR_error_string(ERR_get_error(), nullptr);
325 return false;
326 }
327 TEST_AND_RETURN_FALSE(static_cast<size_t>(signature_size) ==
328 signature.size());
329 } else if (key_type == EVP_PKEY_EC) {
330 EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(private_key.get());
331 TEST_AND_RETURN_FALSE(ec_key != nullptr);
332
333 signature.resize(ECDSA_size(ec_key));
334 unsigned int signature_size;
335 if (ECDSA_sign(0,
336 hash.data(),
337 hash.size(),
338 signature.data(),
339 &signature_size,
340 ec_key) != 1) {
341 LOG(ERROR) << "Signing hash failed: "
342 << ERR_error_string(ERR_get_error(), nullptr);
343 return false;
344 }
345
346 // NIST P-256
347 LOG(ERROR) << "signature max size " << signature.size() << " size "
348 << signature_size;
349 TEST_AND_RETURN_FALSE(signature.size() >= signature_size);
350 signature.resize(signature_size);
351 } else {
352 LOG(ERROR) << "key_type " << key_type << " isn't supported for signing";
353 return false;
354 }
355 out_signature->swap(signature);
356 return true;
357 }
358
SignHashWithKeys(const brillo::Blob & hash_data,const vector<string> & private_key_paths,string * out_serialized_signature)359 bool PayloadSigner::SignHashWithKeys(const brillo::Blob& hash_data,
360 const vector<string>& private_key_paths,
361 string* out_serialized_signature) {
362 vector<brillo::Blob> signatures;
363 vector<size_t> padded_signature_sizes;
364 for (const string& path : private_key_paths) {
365 brillo::Blob signature;
366 TEST_AND_RETURN_FALSE(SignHash(hash_data, path, &signature));
367 signatures.push_back(signature);
368
369 size_t padded_signature_size;
370 TEST_AND_RETURN_FALSE(
371 GetMaximumSignatureSize(path, &padded_signature_size));
372 padded_signature_sizes.push_back(padded_signature_size);
373 }
374 TEST_AND_RETURN_FALSE(ConvertSignaturesToProtobuf(
375 signatures, padded_signature_sizes, out_serialized_signature));
376 return true;
377 }
378
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)379 bool PayloadSigner::SignPayload(const string& unsigned_payload_path,
380 const vector<string>& private_key_paths,
381 const uint64_t metadata_size,
382 const uint32_t metadata_signature_size,
383 const uint64_t signatures_offset,
384 string* out_serialized_signature) {
385 brillo::Blob payload;
386 TEST_AND_RETURN_FALSE(utils::ReadFile(unsigned_payload_path, &payload));
387 brillo::Blob hash_data;
388 TEST_AND_RETURN_FALSE(CalculateHashFromPayload(payload,
389 metadata_size,
390 metadata_signature_size,
391 signatures_offset,
392 &hash_data,
393 nullptr));
394 TEST_AND_RETURN_FALSE(
395 SignHashWithKeys(hash_data, private_key_paths, out_serialized_signature));
396 return true;
397 }
398
SignatureBlobLength(const vector<string> & private_key_paths,uint64_t * out_length)399 bool PayloadSigner::SignatureBlobLength(const vector<string>& private_key_paths,
400 uint64_t* out_length) {
401 DCHECK(out_length);
402 brillo::Blob hash_blob;
403 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfData({'x'}, &hash_blob));
404 string sig_blob;
405 TEST_AND_RETURN_FALSE(
406 SignHashWithKeys(hash_blob, private_key_paths, &sig_blob));
407 *out_length = sig_blob.size();
408 return true;
409 }
410
HashPayloadForSigning(const string & payload_path,const vector<size_t> & signature_sizes,brillo::Blob * out_payload_hash_data,brillo::Blob * out_metadata_hash)411 bool PayloadSigner::HashPayloadForSigning(const string& payload_path,
412 const vector<size_t>& signature_sizes,
413 brillo::Blob* out_payload_hash_data,
414 brillo::Blob* out_metadata_hash) {
415 // Create a signature blob with signatures filled with 0.
416 // Will be used for both payload signature and metadata signature.
417 vector<brillo::Blob> signatures;
418 for (int signature_size : signature_sizes) {
419 signatures.emplace_back(signature_size, 0);
420 }
421 string signature;
422 TEST_AND_RETURN_FALSE(
423 ConvertSignaturesToProtobuf(signatures, signature_sizes, &signature));
424
425 brillo::Blob payload;
426 uint64_t metadata_size, signatures_offset;
427 uint32_t metadata_signature_size;
428 // Prepare payload for hashing.
429 TEST_AND_RETURN_FALSE(AddSignatureBlobToPayload(payload_path,
430 signature,
431 signature,
432 &payload,
433 &metadata_size,
434 &metadata_signature_size,
435 &signatures_offset));
436 TEST_AND_RETURN_FALSE(CalculateHashFromPayload(payload,
437 metadata_size,
438 metadata_signature_size,
439 signatures_offset,
440 out_payload_hash_data,
441 out_metadata_hash));
442 return true;
443 }
444
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)445 bool PayloadSigner::AddSignatureToPayload(
446 const string& payload_path,
447 const vector<size_t>& padded_signature_sizes,
448 const vector<brillo::Blob>& payload_signatures,
449 const vector<brillo::Blob>& metadata_signatures,
450 const string& signed_payload_path,
451 uint64_t* out_metadata_size) {
452 // TODO(petkov): Reduce memory usage -- the payload is manipulated in memory.
453
454 // Loads the payload and adds the signature op to it.
455 string payload_signature, metadata_signature;
456 TEST_AND_RETURN_FALSE(ConvertSignaturesToProtobuf(
457 payload_signatures, padded_signature_sizes, &payload_signature));
458 if (!metadata_signatures.empty()) {
459 TEST_AND_RETURN_FALSE(ConvertSignaturesToProtobuf(
460 metadata_signatures, padded_signature_sizes, &metadata_signature));
461 }
462 brillo::Blob payload;
463 uint64_t signatures_offset;
464 uint32_t metadata_signature_size;
465 TEST_AND_RETURN_FALSE(AddSignatureBlobToPayload(payload_path,
466 payload_signature,
467 metadata_signature,
468 &payload,
469 out_metadata_size,
470 &metadata_signature_size,
471 &signatures_offset));
472
473 LOG(INFO) << "Signed payload size: " << payload.size();
474 TEST_AND_RETURN_FALSE(utils::WriteFile(
475 signed_payload_path.c_str(), payload.data(), payload.size()));
476 return true;
477 }
478
GetMetadataSignature(const void * const metadata,size_t metadata_size,const string & private_key_path,string * out_signature)479 bool PayloadSigner::GetMetadataSignature(const void* const metadata,
480 size_t metadata_size,
481 const string& private_key_path,
482 string* out_signature) {
483 // Calculates the hash on the updated payload. Note that the payload includes
484 // the signature op but doesn't include the signature blob at the end.
485 brillo::Blob metadata_hash;
486 TEST_AND_RETURN_FALSE(
487 HashCalculator::RawHashOfBytes(metadata, metadata_size, &metadata_hash));
488
489 brillo::Blob signature;
490 TEST_AND_RETURN_FALSE(SignHash(metadata_hash, private_key_path, &signature));
491
492 *out_signature = brillo::data_encoding::Base64Encode(signature);
493 return true;
494 }
495
496 } // namespace chromeos_update_engine
497