blob: d0a38e03755139a511ddc6247231b25d6aae1454 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -07006
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07007#include <endian.h>
8#include <errno.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -07009
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070010#include <algorithm>
11#include <cstring>
12#include <string>
13#include <vector>
14
Chris Masoned903c3b2011-05-12 15:35:46 -070015#include <base/memory/scoped_ptr.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070016#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040017#include <base/stringprintf.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070018#include <google/protobuf/repeated_field.h>
19
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070020#include "update_engine/bzip_extent_writer.h"
21#include "update_engine/delta_diff_generator.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070022#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include "update_engine/extent_writer.h"
24#include "update_engine/graph_types.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070025#include "update_engine/payload_signer.h"
Darin Petkov73058b42010-10-06 16:32:19 -070026#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070027#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070028#include "update_engine/terminator.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070029
30using std::min;
31using std::string;
32using std::vector;
33using google::protobuf::RepeatedPtrField;
34
35namespace chromeos_update_engine {
36
Darin Petkovabc7bc02011-02-23 14:39:43 -080037const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
38 "/usr/share/update_engine/update-payload-key.pub.pem";
39
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040namespace {
41
42const int kDeltaVersionLength = 8;
43const int kDeltaProtobufLengthLength = 8;
Darin Petkov73058b42010-10-06 16:32:19 -070044const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070045const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070046
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070047// Converts extents to a human-readable string, for use by DumpUpdateProto().
48string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
49 string ret;
50 for (int i = 0; i < extents.size(); i++) {
51 const Extent& extent = extents.Get(i);
52 if (extent.start_block() == kSparseHole) {
53 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
54 } else {
55 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
56 extent.start_block(), extent.num_blocks());
57 }
58 }
59 if (!ret.empty()) {
60 DCHECK_GT(ret.size(), static_cast<size_t>(1));
61 ret.resize(ret.size() - 2);
62 }
63 return ret;
64}
65
66// LOGs a DeltaArchiveManifest object. Useful for debugging.
67void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
68 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070069 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070070 for (int i = 0; i < (manifest.install_operations_size() +
71 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070072 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070073 i < manifest.install_operations_size() ?
74 manifest.install_operations(i) :
75 manifest.kernel_install_operations(
76 i - manifest.install_operations_size());
77 if (i == 0)
78 LOG(INFO) << " Rootfs ops:";
79 else if (i == manifest.install_operations_size())
80 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070081 LOG(INFO) << " operation(" << i << ")";
82 LOG(INFO) << " type: "
83 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
84 if (op.has_data_offset())
85 LOG(INFO) << " data_offset: " << op.data_offset();
86 if (op.has_data_length())
87 LOG(INFO) << " data_length: " << op.data_length();
88 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
89 if (op.has_src_length())
90 LOG(INFO) << " src_length: " << op.src_length();
91 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
92 if (op.has_dst_length())
93 LOG(INFO) << " dst_length: " << op.dst_length();
94 }
95}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070096
97// Opens path for read/write, put the fd into *fd. On success returns true
98// and sets *err to 0. On failure, returns false and sets *err to errno.
99bool OpenFile(const char* path, int* fd, int* err) {
100 if (*fd != -1) {
101 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
102 *err = EINVAL;
103 return false;
104 }
105 *fd = open(path, O_RDWR, 000);
106 if (*fd < 0) {
107 *err = errno;
108 PLOG(ERROR) << "Unable to open file " << path;
109 return false;
110 }
111 *err = 0;
112 return true;
113}
114
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700115} // namespace {}
116
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700117// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
118// it safely. Returns false otherwise.
119bool DeltaPerformer::IsIdempotentOperation(
120 const DeltaArchiveManifest_InstallOperation& op) {
121 if (op.src_extents_size() == 0) {
122 return true;
123 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700124 // When in doubt, it's safe to declare an op non-idempotent. Note that we
125 // could detect other types of idempotent operations here such as a MOVE that
126 // moves blocks onto themselves. However, we rely on the server to not send
127 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700128 ExtentRanges src_ranges;
129 src_ranges.AddRepeatedExtents(op.src_extents());
130 const uint64_t block_count = src_ranges.blocks();
131 src_ranges.SubtractRepeatedExtents(op.dst_extents());
132 return block_count == src_ranges.blocks();
133}
134
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700135int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700136 int err;
137 if (OpenFile(path, &fd_, &err))
138 path_ = path;
139 return -err;
140}
141
142bool DeltaPerformer::OpenKernel(const char* kernel_path) {
143 int err;
144 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
145 if (success)
146 kernel_path_ = kernel_path;
147 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700148}
149
150int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700151 int err = 0;
152 if (close(kernel_fd_) == -1) {
153 err = errno;
154 PLOG(ERROR) << "Unable to close kernel fd:";
155 }
156 if (close(fd_) == -1) {
157 err = errno;
158 PLOG(ERROR) << "Unable to close rootfs fd:";
159 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700160 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800161 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800163 if (!buffer_.empty()) {
164 LOG(ERROR) << "Called Close() while buffer not empty!";
165 if (err >= 0) {
166 err = 1;
167 }
168 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700169 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700170}
171
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700172namespace {
173
174void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
175 string sha256;
176 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
177 info.hash().size(),
178 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800179 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
180 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700181 } else {
182 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
183 }
184}
185
186void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
187 if (manifest.has_old_kernel_info())
188 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
189 if (manifest.has_old_rootfs_info())
190 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
191 if (manifest.has_new_kernel_info())
192 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
193 if (manifest.has_new_rootfs_info())
194 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
195}
196
197} // namespace {}
198
Darin Petkov9574f7e2011-01-13 10:48:12 -0800199DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
200 const std::vector<char>& payload,
201 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700202 uint64_t* metadata_size,
203 ActionExitCode* error) {
204 *error = kActionCodeSuccess;
205
206 const uint64_t protobuf_offset = strlen(kDeltaMagic) + kDeltaVersionLength +
207 kDeltaProtobufLengthLength;
208 if (payload.size() < protobuf_offset) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800209 // Don't have enough bytes to know the protobuf length.
210 return kMetadataParseInsufficientData;
211 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700212
213 // Validate the magic number.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800214 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
215 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700216 *error = kActionCodeDownloadInvalidManifest;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800217 return kMetadataParseError;
218 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700219
220 // TODO(jaysri): Compare the version number and skip unknown manifest
221 // versions. We don't check the version at all today.
222
223 // Next, parse the proto buf length.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800224 uint64_t protobuf_length;
225 COMPILE_ASSERT(sizeof(protobuf_length) == kDeltaProtobufLengthLength,
226 protobuf_length_size_mismatch);
227 memcpy(&protobuf_length,
228 &payload[strlen(kDeltaMagic) + kDeltaVersionLength],
229 kDeltaProtobufLengthLength);
230 protobuf_length = be64toh(protobuf_length); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700231
232 // Now, check if the metasize we computed matches what was passed in
233 // through Omaha Response.
234 *metadata_size = protobuf_offset + protobuf_length;
235
236 // If the manifest size is present in install plan, check for it immediately
237 // even before waiting for that many number of bytes to be downloaded
238 // in the payload. This will prevent any attack which relies on us downloading
239 // data beyond the expected manifest size.
240 if (install_plan_->manifest_size > 0 &&
241 install_plan_->manifest_size != *metadata_size) {
242 LOG(ERROR) << "Invalid manifest size. Expected = "
243 << install_plan_->manifest_size
244 << "Actual = " << *metadata_size;
245 // TODO(jaysri): Add a UMA Stat here to help with the decision to enforce
246 // this check in a future release, as mentioned below.
247
248 // TODO(jaysri): VALIDATION: Initially we don't want to make this a fatal
249 // error. But in the next release, we should uncomment the lines below.
250 // *error = kActionCodeDownloadInvalidManifest;
251 // return kMetadataParseError;
252 }
253
254 // Now that we have validated the metadata size, we should wait for the full
255 // metadata to be read in before we can parse it.
256 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800257 return kMetadataParseInsufficientData;
258 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700259
260 // Log whether we validated the size or simply trusting what's in the payload
261 // here. This is logged here (after we received the full manifest data) so
262 // that we just log once (instead of logging n times) if it takes n
263 // DeltaPerformer::Write calls to download the full manifest.
264 if (install_plan_->manifest_size == 0)
265 LOG(WARNING) << "No manifest size specified in Omaha. "
266 << "Trusting manifest size in payload = " << *metadata_size;
267 else
268 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
269
270 // We have the full proto buffer in |payload|. Verify its integrity
271 // and authenticity based on what Omaha says.
272 *error = ValidateManifestSignature(&payload[protobuf_offset],
273 protobuf_length);
274 if (*error != kActionCodeSuccess) {
275 // TODO(jaysri): Add a UMA Stat here to help with the decision to enforce
276 // this check in a future release, as mentioned below.
277
278 // TODO(jaysri): VALIDATION: Initially we don't want to make this a fatal
279 // error. But in the next release, we should remove the line below and
280 // return an error.
281 *error = kActionCodeSuccess;
282 }
283
284 // The proto buffer in |payload| is deemed valid. Parse it.
285 if (!manifest->ParseFromArray(&payload[protobuf_offset], protobuf_length)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800286 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700287 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800288 return kMetadataParseError;
289 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800290 return kMetadataParseSuccess;
291}
292
293
Don Garrette410e0f2011-11-10 15:39:01 -0800294// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700295// were written, or false on any error, reguardless of progress
296// and stores an action exit code in |error|.
297bool DeltaPerformer::Write(const void* bytes, size_t count,
298 ActionExitCode *error) {
299 *error = kActionCodeSuccess;
300
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700301 const char* c_bytes = reinterpret_cast<const char*>(bytes);
302 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700303 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800304 MetadataParseResult result = ParsePayloadMetadata(buffer_,
305 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700306 &manifest_metadata_size_,
307 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800308 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800309 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800310 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800311 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800312 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700313 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700314 // Remove protobuf and header info from buffer_, so buffer_ contains
315 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700316 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700317 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700318 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700319 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700320 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700321
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700322 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700323 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700324 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700325 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800326 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700327 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700328 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700329 ssize_t total_operations = manifest_.install_operations_size() +
330 manifest_.kernel_install_operations_size();
331 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700332 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700333 next_operation_num_ < manifest_.install_operations_size() ?
334 manifest_.install_operations(next_operation_num_) :
335 manifest_.kernel_install_operations(
336 next_operation_num_ - manifest_.install_operations_size());
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700337 if (!CanPerformInstallOperation(op)) {
338 // This means we don't have enough bytes received yet to carry out the
339 // next operation.
340 return true;
341 }
342
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700343 bool should_log = (next_operation_num_ % 1000 == 0 ||
344 next_operation_num_ == total_operations - 1);
345
346 // Validate the operation only if the manifest signature is present.
347 // Otherwise, keep the old behavior. This serves as a knob to disable
348 // the validation logic in case we find some regression after rollout.
349 if (!install_plan_->manifest_signature.empty()) {
350 // Note: Validate must be called only if CanPerformInstallOperation is
351 // called. Otherwise, we might be failing operations before even if there
352 // isn't sufficient data to compute the proper hash.
353 *error = ValidateOperationHash(op, should_log);
354 if (*error != kActionCodeSuccess) {
355 // Cannot proceed further as operation hash is invalid.
356 // Higher level code will take care of retrying appropriately.
357 //
358 // TODO(jaysri): Add a UMA stat to indicate that an operation hash
359 // was failed to be validated as expected.
360 //
361 // TODO(jaysri): VALIDATION: For now, we don't treat this as fatal.
362 // But once we're confident that the new code works fine in the field,
363 // we should uncomment the line below.
364 // return false;
365 LOG(INFO) << "Ignoring operation validation errors for now";
366 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700367 }
368
Darin Petkov45580e42010-10-08 14:02:40 -0700369 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700370 ScopedTerminatorExitUnblocker exit_unblocker =
371 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700372 // Log every thousandth operation, and also the first and last ones
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700373 if (should_log) {
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700374 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
375 << total_operations;
376 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700377 bool is_kernel_partition =
378 (next_operation_num_ >= manifest_.install_operations_size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700379 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
380 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700381 if (!PerformReplaceOperation(op, is_kernel_partition)) {
382 LOG(ERROR) << "Failed to perform replace operation "
383 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700384 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800385 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700386 }
387 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700388 if (!PerformMoveOperation(op, is_kernel_partition)) {
389 LOG(ERROR) << "Failed to perform move operation "
390 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700391 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800392 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700393 }
394 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700395 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
396 LOG(ERROR) << "Failed to perform bsdiff operation "
397 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700398 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800399 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700400 }
401 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700402 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700403 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700404 }
Don Garrette410e0f2011-11-10 15:39:01 -0800405 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700406}
407
408bool DeltaPerformer::CanPerformInstallOperation(
409 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
410 operation) {
411 // Move operations don't require any data blob, so they can always
412 // be performed
413 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
414 return true;
415
416 // See if we have the entire data blob in the buffer
417 if (operation.data_offset() < buffer_offset_) {
418 LOG(ERROR) << "we threw away data it seems?";
419 return false;
420 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700421
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700422 return (operation.data_offset() + operation.data_length()) <=
423 (buffer_offset_ + buffer_.size());
424}
425
426bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700427 const DeltaArchiveManifest_InstallOperation& operation,
428 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700429 CHECK(operation.type() == \
430 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
431 operation.type() == \
432 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
433
434 // Since we delete data off the beginning of the buffer as we use it,
435 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700436 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
437 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700438
Darin Petkov437adc42010-10-07 13:12:24 -0700439 // Extract the signature message if it's in this operation.
440 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700441
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700442 DirectExtentWriter direct_writer;
443 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
444 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700445
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700446 // Since bzip decompression is optional, we have a variable writer that will
447 // point to one of the ExtentWriter objects above.
448 ExtentWriter* writer = NULL;
449 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
450 writer = &zero_pad_writer;
451 } else if (operation.type() ==
452 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
453 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
454 writer = bzip_writer.get();
455 } else {
456 NOTREACHED();
457 }
458
459 // Create a vector of extents to pass to the ExtentWriter.
460 vector<Extent> extents;
461 for (int i = 0; i < operation.dst_extents_size(); i++) {
462 extents.push_back(operation.dst_extents(i));
463 }
464
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700465 int fd = is_kernel_partition ? kernel_fd_ : fd_;
466
467 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700468 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
469 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700470
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700471 // Update buffer
472 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700473 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700474 return true;
475}
476
477bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700478 const DeltaArchiveManifest_InstallOperation& operation,
479 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700480 // Calculate buffer size. Note, this function doesn't do a sliding
481 // window to copy in case the source and destination blocks overlap.
482 // If we wanted to do a sliding window, we could program the server
483 // to generate deltas that effectively did a sliding window.
484
485 uint64_t blocks_to_read = 0;
486 for (int i = 0; i < operation.src_extents_size(); i++)
487 blocks_to_read += operation.src_extents(i).num_blocks();
488
489 uint64_t blocks_to_write = 0;
490 for (int i = 0; i < operation.dst_extents_size(); i++)
491 blocks_to_write += operation.dst_extents(i).num_blocks();
492
493 DCHECK_EQ(blocks_to_write, blocks_to_read);
494 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700495
496 int fd = is_kernel_partition ? kernel_fd_ : fd_;
497
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700498 // Read in bytes.
499 ssize_t bytes_read = 0;
500 for (int i = 0; i < operation.src_extents_size(); i++) {
501 ssize_t bytes_read_this_iteration = 0;
502 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700503 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700504 &buf[bytes_read],
505 extent.num_blocks() * block_size_,
506 extent.start_block() * block_size_,
507 &bytes_read_this_iteration));
508 TEST_AND_RETURN_FALSE(
509 bytes_read_this_iteration ==
510 static_cast<ssize_t>(extent.num_blocks() * block_size_));
511 bytes_read += bytes_read_this_iteration;
512 }
513
Darin Petkov45580e42010-10-08 14:02:40 -0700514 // If this is a non-idempotent operation, request a delayed exit and clear the
515 // update state in case the operation gets interrupted. Do this as late as
516 // possible.
517 if (!IsIdempotentOperation(operation)) {
518 Terminator::set_exit_blocked(true);
519 ResetUpdateProgress(prefs_, true);
520 }
521
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700522 // Write bytes out.
523 ssize_t bytes_written = 0;
524 for (int i = 0; i < operation.dst_extents_size(); i++) {
525 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700526 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700527 &buf[bytes_written],
528 extent.num_blocks() * block_size_,
529 extent.start_block() * block_size_));
530 bytes_written += extent.num_blocks() * block_size_;
531 }
532 DCHECK_EQ(bytes_written, bytes_read);
533 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
534 return true;
535}
536
537bool DeltaPerformer::ExtentsToBsdiffPositionsString(
538 const RepeatedPtrField<Extent>& extents,
539 uint64_t block_size,
540 uint64_t full_length,
541 string* positions_string) {
542 string ret;
543 uint64_t length = 0;
544 for (int i = 0; i < extents.size(); i++) {
545 Extent extent = extents.Get(i);
546 int64_t start = extent.start_block();
547 uint64_t this_length = min(full_length - length,
548 extent.num_blocks() * block_size);
549 if (start == static_cast<int64_t>(kSparseHole))
550 start = -1;
551 else
552 start *= block_size;
553 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
554 length += this_length;
555 }
556 TEST_AND_RETURN_FALSE(length == full_length);
557 if (!ret.empty())
558 ret.resize(ret.size() - 1); // Strip trailing comma off
559 *positions_string = ret;
560 return true;
561}
562
563bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700564 const DeltaArchiveManifest_InstallOperation& operation,
565 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700566 // Since we delete data off the beginning of the buffer as we use it,
567 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700568 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
569 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700570
571 string input_positions;
572 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
573 block_size_,
574 operation.src_length(),
575 &input_positions));
576 string output_positions;
577 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
578 block_size_,
579 operation.dst_length(),
580 &output_positions));
581
582 string temp_filename;
583 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
584 &temp_filename,
585 NULL));
586 ScopedPathUnlinker path_unlinker(temp_filename);
587 {
588 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
589 ScopedFdCloser fd_closer(&fd);
590 TEST_AND_RETURN_FALSE(
591 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
592 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700593
594 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700595 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700596
Darin Petkov45580e42010-10-08 14:02:40 -0700597 // If this is a non-idempotent operation, request a delayed exit and clear the
598 // update state in case the operation gets interrupted. Do this as late as
599 // possible.
600 if (!IsIdempotentOperation(operation)) {
601 Terminator::set_exit_blocked(true);
602 ResetUpdateProgress(prefs_, true);
603 }
604
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700605 vector<string> cmd;
606 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700607 cmd.push_back(path);
608 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700609 cmd.push_back(temp_filename);
610 cmd.push_back(input_positions);
611 cmd.push_back(output_positions);
612 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700613 TEST_AND_RETURN_FALSE(
614 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700615 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700616 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700617 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700618 TEST_AND_RETURN_FALSE(return_code == 0);
619
620 if (operation.dst_length() % block_size_) {
621 // Zero out rest of final block.
622 // TODO(adlr): build this into bspatch; it's more efficient that way.
623 const Extent& last_extent =
624 operation.dst_extents(operation.dst_extents_size() - 1);
625 const uint64_t end_byte =
626 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
627 const uint64_t begin_byte =
628 end_byte - (block_size_ - operation.dst_length() % block_size_);
629 vector<char> zeros(end_byte - begin_byte);
630 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700631 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700632 }
633
634 // Update buffer.
635 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700636 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700637 return true;
638}
639
Darin Petkovd7061ab2010-10-06 14:37:09 -0700640bool DeltaPerformer::ExtractSignatureMessage(
641 const DeltaArchiveManifest_InstallOperation& operation) {
642 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
643 !manifest_.has_signatures_offset() ||
644 manifest_.signatures_offset() != operation.data_offset()) {
645 return false;
646 }
647 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
648 manifest_.signatures_size() == operation.data_length());
649 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
650 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
651 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700652 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700653 buffer_.begin(),
654 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700655
656 // Save the signature blob because if the update is interrupted after the
657 // download phase we don't go through this path anymore. Some alternatives to
658 // consider:
659 //
660 // 1. On resume, re-download the signature blob from the server and re-verify
661 // it.
662 //
663 // 2. Verify the signature as soon as it's received and don't checkpoint the
664 // blob and the signed sha-256 context.
665 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
666 string(&signatures_message_data_[0],
667 signatures_message_data_.size())))
668 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700669 // The hash of all data consumed so far should be verified against the signed
670 // hash.
671 signed_hash_context_ = hash_calculator_.GetContext();
672 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
673 signed_hash_context_))
674 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700675 LOG(INFO) << "Extracted signature data of size "
676 << manifest_.signatures_size() << " at "
677 << manifest_.signatures_offset();
678 return true;
679}
680
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700681ActionExitCode DeltaPerformer::ValidateManifestSignature(
682 const char* protobuf, uint64_t protobuf_length) {
683
684 if (install_plan_->manifest_signature.empty()) {
685 // If this is not present, we cannot validate the manifest. This should
686 // never happen in normal circumstances, but this can be used as a
687 // release-knob to turn off the new code path that verify per-operation
688 // hashes. So, for now, we should not treat this as a failure. Once we are
689 // confident this path is bug-free, we should treat this as a failure so
690 // that we remain robust even if the connection to Omaha is subjected to
691 // any SSL attack.
692 LOG(WARNING) << "Cannot validate manifest as the signature is empty";
693 return kActionCodeSuccess;
694 }
695
696 // Convert base64-encoded signature to raw bytes.
697 vector<char> manifest_signature;
698 if (!OmahaHashCalculator::Base64Decode(install_plan_->manifest_signature,
699 &manifest_signature)) {
700 LOG(ERROR) << "Unable to decode base64 manifest signature: "
701 << install_plan_->manifest_signature;
702 return kActionCodeDownloadManifestSignatureError;
703 }
704
705 vector<char> expected_manifest_hash;
706 if (!PayloadSigner::GetRawHashFromSignature(manifest_signature,
707 public_key_path_,
708 &expected_manifest_hash)) {
709 LOG(ERROR) << "Unable to compute expected hash from manifest signature";
710 return kActionCodeDownloadManifestSignatureError;
711 }
712
713 OmahaHashCalculator manifest_hasher;
714 manifest_hasher.Update(protobuf, protobuf_length);
715 if (!manifest_hasher.Finalize()) {
716 LOG(ERROR) << "Unable to compute actual hash of manifest";
717 return kActionCodeDownloadManifestSignatureVerificationError;
718 }
719
720 vector<char> calculated_manifest_hash = manifest_hasher.raw_hash();
721 PayloadSigner::PadRSA2048SHA256Hash(&calculated_manifest_hash);
722 if (calculated_manifest_hash.empty()) {
723 LOG(ERROR) << "Computed actual hash of manifest is empty.";
724 return kActionCodeDownloadManifestSignatureVerificationError;
725 }
726
727 if (calculated_manifest_hash != expected_manifest_hash) {
728 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
729 utils::HexDumpVector(expected_manifest_hash);
730 LOG(ERROR) << "Calculated hash = ";
731 utils::HexDumpVector(calculated_manifest_hash);
732 return kActionCodeDownloadManifestSignatureMismatch;
733 }
734
735 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
736 return kActionCodeSuccess;
737}
738
739ActionExitCode DeltaPerformer::ValidateOperationHash(
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700740 const DeltaArchiveManifest_InstallOperation& operation,
741 bool should_log) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700742
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700743 if (!operation.data_sha256_hash().size()) {
744 if (!operation.data_length()) {
745 // Operations that do not have any data blob won't have any operation hash
746 // either. So, these operations are always considered validated since the
747 // manifest that contains all the non-data-blob portions of the operation
748 // has already been validated.
749 return kActionCodeSuccess;
750 }
751
752 // TODO(jaysri): Add a UMA stat here so we're aware of any
753 // man-in-the-middle attempts to bypass these checks.
754 //
755 // TODO(jaysri): VALIDATION: no hash is present for the operation. This
756 // shouldn't happen normally for any client that has this code, because the
757 // corresponding update should have been produced with the operation
758 // hashes. But if it happens it's likely that we've turned this feature off
759 // in Omaha rule for some reason. Once we make these hashes mandatory, we
760 // should return an error here.
761 // One caveat though: The last operation is a dummy signature operation
762 // that doesn't have a hash at the time the manifest is created. So we
763 // should not complaint about that operation. This operation can be
764 // recognized by the fact that it's offset is mentioned in the manifest.
765 if (manifest_.signatures_offset() &&
766 manifest_.signatures_offset() == operation.data_offset()) {
767 LOG(INFO) << "Skipping hash verification for signature operation "
768 << next_operation_num_ + 1;
769 } else {
770 // TODO(jaysri): Uncomment this logging after fixing dev server
771 // LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
772 // << " as no expected hash present";
773 }
774 return kActionCodeSuccess;
775 }
776
777 vector<char> expected_op_hash;
778 expected_op_hash.assign(operation.data_sha256_hash().data(),
779 (operation.data_sha256_hash().data() +
780 operation.data_sha256_hash().size()));
781
782 OmahaHashCalculator operation_hasher;
783 operation_hasher.Update(&buffer_[0], operation.data_length());
784 if (!operation_hasher.Finalize()) {
785 LOG(ERROR) << "Unable to compute actual hash of operation "
786 << next_operation_num_;
787 return kActionCodeDownloadOperationHashVerificationError;
788 }
789
790 vector<char> calculated_op_hash = operation_hasher.raw_hash();
791 if (calculated_op_hash != expected_op_hash) {
792 LOG(ERROR) << "Hash verification failed for operation "
793 << next_operation_num_ << ". Expected hash = ";
794 utils::HexDumpVector(expected_op_hash);
795 LOG(ERROR) << "Calculated hash over " << operation.data_length()
796 << " bytes at offset: " << operation.data_offset() << " = ";
797 utils::HexDumpVector(calculated_op_hash);
798 return kActionCodeDownloadOperationHashMismatch;
799 }
800
801 if (should_log)
802 LOG(INFO) << "Validated operation " << next_operation_num_ + 1;
803
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700804 return kActionCodeSuccess;
805}
806
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700807#define TEST_AND_RETURN_VAL(_retval, _condition) \
808 do { \
809 if (!(_condition)) { \
810 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
811 return _retval; \
812 } \
813 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700814
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700815ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700816 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700817 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700818 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700819
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700820 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700821 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700822 update_check_response_size ==
823 manifest_metadata_size_ + buffer_offset_);
824
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700825 // Verifies the payload hash.
826 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700827 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700828 !payload_hash_data.empty());
829 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
830 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700831
Darin Petkov437adc42010-10-07 13:12:24 -0700832 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700833 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700834 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700835 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700836 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700837 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
838 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700839 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700840 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
841 PayloadSigner::VerifySignature(
842 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700843 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700844 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700845 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700846 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
847 signed_hasher.SetContext(signed_hash_context_));
848 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
849 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700850 vector<char> hash_data = signed_hasher.raw_hash();
851 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700852 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
853 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700854 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700855 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700856 "Attached Signature:";
857 utils::HexDumpVector(signed_hash_data);
858 LOG(ERROR) << "Computed Signature:";
859 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700860 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700861 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700862 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700863}
864
Darin Petkov3aefa862010-12-07 14:45:00 -0800865bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
866 vector<char>* kernel_hash,
867 uint64_t* rootfs_size,
868 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700869 TEST_AND_RETURN_FALSE(manifest_valid_ &&
870 manifest_.has_new_kernel_info() &&
871 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -0800872 *kernel_size = manifest_.new_kernel_info().size();
873 *rootfs_size = manifest_.new_rootfs_info().size();
874 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
875 manifest_.new_kernel_info().hash().end());
876 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
877 manifest_.new_rootfs_info().hash().end());
878 kernel_hash->swap(new_kernel_hash);
879 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700880 return true;
881}
882
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700883namespace {
884void LogVerifyError(bool is_kern,
885 const string& local_hash,
886 const string& expected_hash) {
887 const char* type = is_kern ? "kernel" : "rootfs";
888 LOG(ERROR) << "This is a server-side error due to "
889 << "mismatched delta update image!";
890 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
891 << "update that must be applied over a " << type << " with "
892 << "a specific checksum, but the " << type << " we're starting "
893 << "with doesn't have that checksum! This means that "
894 << "the delta I've been given doesn't match my existing "
895 << "system. The " << type << " partition I have has hash: "
896 << local_hash << " but the update expected me to have "
897 << expected_hash << " .";
898 if (is_kern) {
899 LOG(INFO) << "To get the checksum of a kernel partition on a "
900 << "booted machine, run this command (change /dev/sda2 "
901 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
902 << "openssl dgst -sha256 -binary | openssl base64";
903 } else {
904 LOG(INFO) << "To get the checksum of a rootfs partition on a "
905 << "booted machine, run this command (change /dev/sda3 "
906 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
907 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
908 << "| sed 's/[^0-9]*//') / 256 )) | "
909 << "openssl dgst -sha256 -binary | openssl base64";
910 }
911 LOG(INFO) << "To get the checksum of partitions in a bin file, "
912 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
913}
914
915string StringForHashBytes(const void* bytes, size_t size) {
916 string ret;
917 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
918 ret = "<unknown>";
919 }
920 return ret;
921}
922} // namespace
923
Darin Petkov698d0412010-10-13 10:59:44 -0700924bool DeltaPerformer::VerifySourcePartitions() {
925 LOG(INFO) << "Verifying source partitions.";
926 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700927 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -0700928 if (manifest_.has_old_kernel_info()) {
929 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700930 bool valid =
931 !install_plan_->kernel_hash.empty() &&
932 install_plan_->kernel_hash.size() == info.hash().size() &&
933 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700934 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700935 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700936 if (!valid) {
937 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700938 StringForHashBytes(install_plan_->kernel_hash.data(),
939 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700940 StringForHashBytes(info.hash().data(),
941 info.hash().size()));
942 }
943 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700944 }
945 if (manifest_.has_old_rootfs_info()) {
946 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700947 bool valid =
948 !install_plan_->rootfs_hash.empty() &&
949 install_plan_->rootfs_hash.size() == info.hash().size() &&
950 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700951 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700952 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700953 if (!valid) {
954 LogVerifyError(false,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700955 StringForHashBytes(install_plan_->kernel_hash.data(),
956 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700957 StringForHashBytes(info.hash().data(),
958 info.hash().size()));
959 }
960 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700961 }
962 return true;
963}
964
Darin Petkov437adc42010-10-07 13:12:24 -0700965void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
966 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700967 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
968}
969
Darin Petkov0406e402010-10-06 21:33:11 -0700970bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
971 string update_check_response_hash) {
972 int64_t next_operation = kUpdateStateOperationInvalid;
973 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
974 &next_operation) &&
975 next_operation != kUpdateStateOperationInvalid &&
976 next_operation > 0);
977
978 string interrupted_hash;
979 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
980 &interrupted_hash) &&
981 !interrupted_hash.empty() &&
982 interrupted_hash == update_check_response_hash);
983
Darin Petkov61426142010-10-08 11:04:55 -0700984 int64_t resumed_update_failures;
985 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
986 &resumed_update_failures) ||
987 resumed_update_failures <= kMaxResumedUpdateFailures);
988
Darin Petkov0406e402010-10-06 21:33:11 -0700989 // Sanity check the rest.
990 int64_t next_data_offset = -1;
991 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
992 &next_data_offset) &&
993 next_data_offset >= 0);
994
Darin Petkov437adc42010-10-07 13:12:24 -0700995 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -0700996 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700997 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
998 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -0700999
1000 int64_t manifest_metadata_size = 0;
1001 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1002 &manifest_metadata_size) &&
1003 manifest_metadata_size > 0);
1004
1005 return true;
1006}
1007
Darin Petkov9b230572010-10-08 10:20:09 -07001008bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001009 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1010 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001011 if (!quick) {
1012 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1013 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1014 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1015 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001016 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001017 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001018 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001019 }
Darin Petkov73058b42010-10-06 16:32:19 -07001020 return true;
1021}
1022
1023bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001024 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001025 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001026 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001027 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001028 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001029 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001030 hash_calculator_.GetContext()));
1031 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1032 buffer_offset_));
1033 last_updated_buffer_offset_ = buffer_offset_;
1034 }
Darin Petkov73058b42010-10-06 16:32:19 -07001035 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1036 next_operation_num_));
1037 return true;
1038}
1039
Darin Petkov9b230572010-10-08 10:20:09 -07001040bool DeltaPerformer::PrimeUpdateState() {
1041 CHECK(manifest_valid_);
1042 block_size_ = manifest_.block_size();
1043
1044 int64_t next_operation = kUpdateStateOperationInvalid;
1045 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1046 next_operation == kUpdateStateOperationInvalid ||
1047 next_operation <= 0) {
1048 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001049 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001050 return true;
1051 }
1052 next_operation_num_ = next_operation;
1053
1054 // Resuming an update -- load the rest of the update state.
1055 int64_t next_data_offset = -1;
1056 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1057 &next_data_offset) &&
1058 next_data_offset >= 0);
1059 buffer_offset_ = next_data_offset;
1060
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001061 // The signed hash context and the signature blob may be empty if the
1062 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001063 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1064 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001065 string signature_blob;
1066 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1067 signatures_message_data_.assign(signature_blob.begin(),
1068 signature_blob.end());
1069 }
Darin Petkov9b230572010-10-08 10:20:09 -07001070
1071 string hash_context;
1072 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1073 &hash_context) &&
1074 hash_calculator_.SetContext(hash_context));
1075
1076 int64_t manifest_metadata_size = 0;
1077 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1078 &manifest_metadata_size) &&
1079 manifest_metadata_size > 0);
1080 manifest_metadata_size_ = manifest_metadata_size;
1081
Darin Petkov61426142010-10-08 11:04:55 -07001082 // Speculatively count the resume as a failure.
1083 int64_t resumed_update_failures;
1084 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1085 resumed_update_failures++;
1086 } else {
1087 resumed_update_failures = 1;
1088 }
1089 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001090 return true;
1091}
1092
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001093} // namespace chromeos_update_engine