1 //
2 // Copyright (C) 2015 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_file.h"
18 
19 #include <endian.h>
20 
21 #include <algorithm>
22 #include <map>
23 #include <utility>
24 
25 #include <base/strings/stringprintf.h>
26 
27 #include "update_engine/common/hash_calculator.h"
28 #include "update_engine/payload_consumer/delta_performer.h"
29 #include "update_engine/payload_consumer/file_writer.h"
30 #include "update_engine/payload_consumer/payload_constants.h"
31 #include "update_engine/payload_generator/annotated_operation.h"
32 #include "update_engine/payload_generator/delta_diff_utils.h"
33 #include "update_engine/payload_generator/payload_signer.h"
34 
35 using std::string;
36 using std::vector;
37 
38 namespace chromeos_update_engine {
39 
40 namespace {
41 
42 struct DeltaObject {
DeltaObjectchromeos_update_engine::__anon3fa7f6d60111::DeltaObject43   DeltaObject(const string& in_name, const int in_type, const off_t in_size)
44       : name(in_name), type(in_type), size(in_size) {}
operator <chromeos_update_engine::__anon3fa7f6d60111::DeltaObject45   bool operator<(const DeltaObject& object) const {
46     return (size != object.size) ? (size < object.size) : (name < object.name);
47   }
48   string name;
49   int type;
50   off_t size;
51 };
52 
53 // Writes the uint64_t passed in in host-endian to the file as big-endian.
54 // Returns true on success.
WriteUint64AsBigEndian(FileWriter * writer,const uint64_t value)55 bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
56   uint64_t value_be = htobe64(value);
57   TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
58   return true;
59 }
60 
61 }  // namespace
62 
Init(const PayloadGenerationConfig & config)63 bool PayloadFile::Init(const PayloadGenerationConfig& config) {
64   TEST_AND_RETURN_FALSE(config.version.Validate());
65   major_version_ = config.version.major;
66   manifest_.set_minor_version(config.version.minor);
67 
68   if (!config.source.ImageInfoIsEmpty())
69     *(manifest_.mutable_old_image_info()) = config.source.image_info;
70 
71   if (!config.target.ImageInfoIsEmpty())
72     *(manifest_.mutable_new_image_info()) = config.target.image_info;
73 
74   manifest_.set_block_size(config.block_size);
75   manifest_.set_max_timestamp(config.max_timestamp);
76 
77   if (config.target.dynamic_partition_metadata != nullptr)
78     *(manifest_.mutable_dynamic_partition_metadata()) =
79         *(config.target.dynamic_partition_metadata);
80 
81   if (config.is_partial_update) {
82     manifest_.set_partial_update(true);
83   }
84   return true;
85 }
86 
AddPartition(const PartitionConfig & old_conf,const PartitionConfig & new_conf,vector<AnnotatedOperation> aops)87 bool PayloadFile::AddPartition(const PartitionConfig& old_conf,
88                                const PartitionConfig& new_conf,
89                                vector<AnnotatedOperation> aops) {
90   Partition part;
91   part.name = new_conf.name;
92   part.aops = std::move(aops);
93   part.postinstall = new_conf.postinstall;
94   part.verity = new_conf.verity;
95   // Initialize the PartitionInfo objects if present.
96   if (!old_conf.path.empty())
97     TEST_AND_RETURN_FALSE(
98         diff_utils::InitializePartitionInfo(old_conf, &part.old_info));
99   TEST_AND_RETURN_FALSE(
100       diff_utils::InitializePartitionInfo(new_conf, &part.new_info));
101   part_vec_.push_back(std::move(part));
102   return true;
103 }
104 
WritePayload(const string & payload_file,const string & data_blobs_path,const string & private_key_path,uint64_t * metadata_size_out)105 bool PayloadFile::WritePayload(const string& payload_file,
106                                const string& data_blobs_path,
107                                const string& private_key_path,
108                                uint64_t* metadata_size_out) {
109   // Reorder the data blobs with the manifest_.
110   string ordered_blobs_path;
111   TEST_AND_RETURN_FALSE(utils::MakeTempFile(
112       "CrAU_temp_data.ordered.XXXXXX", &ordered_blobs_path, nullptr));
113   ScopedPathUnlinker ordered_blobs_unlinker(ordered_blobs_path);
114   TEST_AND_RETURN_FALSE(ReorderDataBlobs(data_blobs_path, ordered_blobs_path));
115 
116   // Check that install op blobs are in order.
117   uint64_t next_blob_offset = 0;
118   for (const auto& part : part_vec_) {
119     for (const auto& aop : part.aops) {
120       if (!aop.op.has_data_offset())
121         continue;
122       if (aop.op.data_offset() != next_blob_offset) {
123         LOG(FATAL) << "bad blob offset! " << aop.op.data_offset()
124                    << " != " << next_blob_offset;
125       }
126       next_blob_offset += aop.op.data_length();
127     }
128   }
129 
130   // Copy the operations and partition info from the part_vec_ to the manifest.
131   manifest_.clear_partitions();
132   for (const auto& part : part_vec_) {
133     PartitionUpdate* partition = manifest_.add_partitions();
134     partition->set_partition_name(part.name);
135     if (part.postinstall.run) {
136       partition->set_run_postinstall(true);
137       if (!part.postinstall.path.empty())
138         partition->set_postinstall_path(part.postinstall.path);
139       if (!part.postinstall.filesystem_type.empty())
140         partition->set_filesystem_type(part.postinstall.filesystem_type);
141       partition->set_postinstall_optional(part.postinstall.optional);
142     }
143     if (!part.verity.IsEmpty()) {
144       if (part.verity.hash_tree_extent.num_blocks() != 0) {
145         *partition->mutable_hash_tree_data_extent() =
146             part.verity.hash_tree_data_extent;
147         *partition->mutable_hash_tree_extent() = part.verity.hash_tree_extent;
148         partition->set_hash_tree_algorithm(part.verity.hash_tree_algorithm);
149         if (!part.verity.hash_tree_salt.empty())
150           partition->set_hash_tree_salt(part.verity.hash_tree_salt.data(),
151                                         part.verity.hash_tree_salt.size());
152       }
153       if (part.verity.fec_extent.num_blocks() != 0) {
154         *partition->mutable_fec_data_extent() = part.verity.fec_data_extent;
155         *partition->mutable_fec_extent() = part.verity.fec_extent;
156         partition->set_fec_roots(part.verity.fec_roots);
157       }
158     }
159     for (const AnnotatedOperation& aop : part.aops) {
160       *partition->add_operations() = aop.op;
161     }
162     if (part.old_info.has_size() || part.old_info.has_hash())
163       *(partition->mutable_old_partition_info()) = part.old_info;
164     if (part.new_info.has_size() || part.new_info.has_hash())
165       *(partition->mutable_new_partition_info()) = part.new_info;
166   }
167 
168   // Signatures appear at the end of the blobs. Note the offset in the
169   // |manifest_|.
170   uint64_t signature_blob_length = 0;
171   if (!private_key_path.empty()) {
172     TEST_AND_RETURN_FALSE(PayloadSigner::SignatureBlobLength(
173         {private_key_path}, &signature_blob_length));
174     PayloadSigner::AddSignatureToManifest(
175         next_blob_offset, signature_blob_length, &manifest_);
176   }
177 
178   // Serialize protobuf
179   string serialized_manifest;
180   TEST_AND_RETURN_FALSE(manifest_.SerializeToString(&serialized_manifest));
181 
182   uint64_t metadata_size =
183       sizeof(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
184 
185   LOG(INFO) << "Writing final delta file header...";
186   DirectFileWriter writer;
187   TEST_AND_RETURN_FALSE_ERRNO(writer.Open(payload_file.c_str(),
188                                           O_WRONLY | O_CREAT | O_TRUNC,
189                                           0644) == 0);
190   ScopedFileWriterCloser writer_closer(&writer);
191 
192   // Write header
193   TEST_AND_RETURN_FALSE_ERRNO(writer.Write(kDeltaMagic, sizeof(kDeltaMagic)));
194 
195   // Write major version number
196   TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, major_version_));
197 
198   // Write protobuf length
199   TEST_AND_RETURN_FALSE(
200       WriteUint64AsBigEndian(&writer, serialized_manifest.size()));
201 
202   // Metadata signature has the same size as payload signature, because they
203   // are both the same kind of signature for the same kind of hash.
204   uint32_t metadata_signature_size = htobe32(signature_blob_length);
205   TEST_AND_RETURN_FALSE_ERRNO(
206       writer.Write(&metadata_signature_size, sizeof(metadata_signature_size)));
207   metadata_size += sizeof(metadata_signature_size);
208   // Set correct size instead of big endian size.
209   metadata_signature_size = signature_blob_length;
210 
211   // Write protobuf
212   LOG(INFO) << "Writing final delta file protobuf... "
213             << serialized_manifest.size();
214   TEST_AND_RETURN_FALSE_ERRNO(
215       writer.Write(serialized_manifest.data(), serialized_manifest.size()));
216 
217   // Write metadata signature blob.
218   if (!private_key_path.empty()) {
219     brillo::Blob metadata_hash;
220     TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfFile(
221         payload_file, metadata_size, &metadata_hash));
222     string metadata_signature;
223     TEST_AND_RETURN_FALSE(PayloadSigner::SignHashWithKeys(
224         metadata_hash, {private_key_path}, &metadata_signature));
225     TEST_AND_RETURN_FALSE_ERRNO(
226         writer.Write(metadata_signature.data(), metadata_signature.size()));
227   }
228 
229   // Append the data blobs.
230   LOG(INFO) << "Writing final delta file data blobs...";
231   int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
232   ScopedFdCloser blobs_fd_closer(&blobs_fd);
233   TEST_AND_RETURN_FALSE(blobs_fd >= 0);
234   for (;;) {
235     vector<char> buf(1024 * 1024);
236     ssize_t rc = read(blobs_fd, buf.data(), buf.size());
237     if (0 == rc) {
238       // EOF
239       break;
240     }
241     TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
242     TEST_AND_RETURN_FALSE_ERRNO(writer.Write(buf.data(), rc));
243   }
244 
245   // Write payload signature blob.
246   if (!private_key_path.empty()) {
247     LOG(INFO) << "Signing the update...";
248     string signature;
249     TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
250         payload_file,
251         {private_key_path},
252         metadata_size,
253         metadata_signature_size,
254         metadata_size + metadata_signature_size + manifest_.signatures_offset(),
255         &signature));
256     TEST_AND_RETURN_FALSE_ERRNO(
257         writer.Write(signature.data(), signature.size()));
258   }
259 
260   ReportPayloadUsage(metadata_size);
261   *metadata_size_out = metadata_size;
262   return true;
263 }
264 
ReorderDataBlobs(const string & data_blobs_path,const string & new_data_blobs_path)265 bool PayloadFile::ReorderDataBlobs(const string& data_blobs_path,
266                                    const string& new_data_blobs_path) {
267   int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
268   TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
269   ScopedFdCloser in_fd_closer(&in_fd);
270 
271   DirectFileWriter writer;
272   int rc = writer.Open(
273       new_data_blobs_path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0644);
274   if (rc != 0) {
275     PLOG(ERROR) << "Error creating " << new_data_blobs_path;
276     return false;
277   }
278   ScopedFileWriterCloser writer_closer(&writer);
279   uint64_t out_file_size = 0;
280 
281   for (auto& part : part_vec_) {
282     for (AnnotatedOperation& aop : part.aops) {
283       if (!aop.op.has_data_offset())
284         continue;
285       CHECK(aop.op.has_data_length());
286       brillo::Blob buf(aop.op.data_length());
287       ssize_t rc = pread(in_fd, buf.data(), buf.size(), aop.op.data_offset());
288       TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
289 
290       // Add the hash of the data blobs for this operation
291       TEST_AND_RETURN_FALSE(AddOperationHash(&aop.op, buf));
292 
293       aop.op.set_data_offset(out_file_size);
294       TEST_AND_RETURN_FALSE_ERRNO(writer.Write(buf.data(), buf.size()));
295       out_file_size += buf.size();
296     }
297   }
298   return true;
299 }
300 
AddOperationHash(InstallOperation * op,const brillo::Blob & buf)301 bool PayloadFile::AddOperationHash(InstallOperation* op,
302                                    const brillo::Blob& buf) {
303   brillo::Blob hash;
304   TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfData(buf, &hash));
305   op->set_data_sha256_hash(hash.data(), hash.size());
306   return true;
307 }
308 
ReportPayloadUsage(uint64_t metadata_size) const309 void PayloadFile::ReportPayloadUsage(uint64_t metadata_size) const {
310   std::map<DeltaObject, int> object_counts;
311   off_t total_size = 0;
312   int total_op = 0;
313 
314   for (const auto& part : part_vec_) {
315     string part_prefix = "<" + part.name + ">:";
316     for (const AnnotatedOperation& aop : part.aops) {
317       DeltaObject delta(
318           part_prefix + aop.name, aop.op.type(), aop.op.data_length());
319       object_counts[delta]++;
320       total_size += aop.op.data_length();
321     }
322     total_op += part.aops.size();
323   }
324 
325   object_counts[DeltaObject("<manifest-metadata>", -1, metadata_size)] = 1;
326   total_size += metadata_size;
327 
328   constexpr char kFormatString[] = "%6.2f%% %10jd %-13s %s %d\n";
329   for (const auto& object_count : object_counts) {
330     const DeltaObject& object = object_count.first;
331     // Use printf() instead of LOG(INFO) because timestamp makes it difficult to
332     // compare two reports.
333     printf(kFormatString,
334            object.size * 100.0 / total_size,
335            object.size,
336            (object.type >= 0
337                 ? InstallOperationTypeName(
338                       static_cast<InstallOperation::Type>(object.type))
339                 : "-"),
340            object.name.c_str(),
341            object_count.second);
342   }
343   printf(kFormatString, 100.0, total_size, "", "<total>", total_op);
344   fflush(stdout);
345 }
346 
347 }  // namespace chromeos_update_engine
348