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