blob: bcba546549b0106f577c4889925e310d59b6d121 [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
Jay Srinivasanf4318702012-09-24 11:56:24 -070037const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
38const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Darin Petkovabc7bc02011-02-23 14:39:43 -080039const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
40 "/usr/share/update_engine/update-payload-key.pub.pem";
41
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070042namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070043const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070044const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070045
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070046// Converts extents to a human-readable string, for use by DumpUpdateProto().
47string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
48 string ret;
49 for (int i = 0; i < extents.size(); i++) {
50 const Extent& extent = extents.Get(i);
51 if (extent.start_block() == kSparseHole) {
52 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
53 } else {
54 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
55 extent.start_block(), extent.num_blocks());
56 }
57 }
58 if (!ret.empty()) {
59 DCHECK_GT(ret.size(), static_cast<size_t>(1));
60 ret.resize(ret.size() - 2);
61 }
62 return ret;
63}
64
65// LOGs a DeltaArchiveManifest object. Useful for debugging.
66void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
67 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070068 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070069 for (int i = 0; i < (manifest.install_operations_size() +
70 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070071 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070072 i < manifest.install_operations_size() ?
73 manifest.install_operations(i) :
74 manifest.kernel_install_operations(
75 i - manifest.install_operations_size());
76 if (i == 0)
77 LOG(INFO) << " Rootfs ops:";
78 else if (i == manifest.install_operations_size())
79 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070080 LOG(INFO) << " operation(" << i << ")";
81 LOG(INFO) << " type: "
82 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
83 if (op.has_data_offset())
84 LOG(INFO) << " data_offset: " << op.data_offset();
85 if (op.has_data_length())
86 LOG(INFO) << " data_length: " << op.data_length();
87 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
88 if (op.has_src_length())
89 LOG(INFO) << " src_length: " << op.src_length();
90 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
91 if (op.has_dst_length())
92 LOG(INFO) << " dst_length: " << op.dst_length();
93 }
94}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070095
96// Opens path for read/write, put the fd into *fd. On success returns true
97// and sets *err to 0. On failure, returns false and sets *err to errno.
98bool OpenFile(const char* path, int* fd, int* err) {
99 if (*fd != -1) {
100 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
101 *err = EINVAL;
102 return false;
103 }
104 *fd = open(path, O_RDWR, 000);
105 if (*fd < 0) {
106 *err = errno;
107 PLOG(ERROR) << "Unable to open file " << path;
108 return false;
109 }
110 *err = 0;
111 return true;
112}
113
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700114} // namespace {}
115
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700116// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
117// it safely. Returns false otherwise.
118bool DeltaPerformer::IsIdempotentOperation(
119 const DeltaArchiveManifest_InstallOperation& op) {
120 if (op.src_extents_size() == 0) {
121 return true;
122 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700123 // When in doubt, it's safe to declare an op non-idempotent. Note that we
124 // could detect other types of idempotent operations here such as a MOVE that
125 // moves blocks onto themselves. However, we rely on the server to not send
126 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700127 ExtentRanges src_ranges;
128 src_ranges.AddRepeatedExtents(op.src_extents());
129 const uint64_t block_count = src_ranges.blocks();
130 src_ranges.SubtractRepeatedExtents(op.dst_extents());
131 return block_count == src_ranges.blocks();
132}
133
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700134int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700135 int err;
136 if (OpenFile(path, &fd_, &err))
137 path_ = path;
138 return -err;
139}
140
141bool DeltaPerformer::OpenKernel(const char* kernel_path) {
142 int err;
143 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
144 if (success)
145 kernel_path_ = kernel_path;
146 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700147}
148
149int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700150 int err = 0;
151 if (close(kernel_fd_) == -1) {
152 err = errno;
153 PLOG(ERROR) << "Unable to close kernel fd:";
154 }
155 if (close(fd_) == -1) {
156 err = errno;
157 PLOG(ERROR) << "Unable to close rootfs fd:";
158 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700159 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800160 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700161 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800162 if (!buffer_.empty()) {
163 LOG(ERROR) << "Called Close() while buffer not empty!";
164 if (err >= 0) {
165 err = 1;
166 }
167 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700168 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700169}
170
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700171namespace {
172
173void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
174 string sha256;
175 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
176 info.hash().size(),
177 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800178 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
179 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700180 } else {
181 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
182 }
183}
184
185void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
186 if (manifest.has_old_kernel_info())
187 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
188 if (manifest.has_old_rootfs_info())
189 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
190 if (manifest.has_new_kernel_info())
191 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
192 if (manifest.has_new_rootfs_info())
193 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
194}
195
196} // namespace {}
197
Jay Srinivasanf4318702012-09-24 11:56:24 -0700198uint64_t DeltaPerformer::GetManifestSizeOffset() {
199 // Manifest size is stored right after the magic string and the version.
200 return strlen(kDeltaMagic) + kDeltaVersionSize;
201}
202
203uint64_t DeltaPerformer::GetManifestOffset() {
204 // Actual manifest begins right after the manifest size field.
205 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
206}
207
208
Darin Petkov9574f7e2011-01-13 10:48:12 -0800209DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
210 const std::vector<char>& payload,
211 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700212 uint64_t* metadata_size,
213 ActionExitCode* error) {
214 *error = kActionCodeSuccess;
215
Jay Srinivasanf4318702012-09-24 11:56:24 -0700216 // manifest_offset is the byte offset where the manifest protobuf begins.
217 const uint64_t manifest_offset = GetManifestOffset();
218 if (payload.size() < manifest_offset) {
219 // Don't have enough bytes to even know the manifest size.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800220 return kMetadataParseInsufficientData;
221 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700222
Jay Srinivasanf4318702012-09-24 11:56:24 -0700223 // Validate the magic string.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800224 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
225 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700226 *error = kActionCodeDownloadInvalidMetadataMagicString;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800227 return kMetadataParseError;
228 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700229
230 // TODO(jaysri): Compare the version number and skip unknown manifest
231 // versions. We don't check the version at all today.
232
Jay Srinivasanf4318702012-09-24 11:56:24 -0700233 // Next, parse the manifest size.
234 uint64_t manifest_size;
235 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
236 manifest_size_size_mismatch);
237 memcpy(&manifest_size,
238 &payload[GetManifestSizeOffset()],
239 kDeltaManifestSizeSize);
240 manifest_size = be64toh(manifest_size); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700241
242 // Now, check if the metasize we computed matches what was passed in
243 // through Omaha Response.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700244 *metadata_size = manifest_offset + manifest_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700245
Jay Srinivasanf4318702012-09-24 11:56:24 -0700246 // If the metadata size is present in install plan, check for it immediately
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700247 // even before waiting for that many number of bytes to be downloaded
248 // in the payload. This will prevent any attack which relies on us downloading
Jay Srinivasanf4318702012-09-24 11:56:24 -0700249 // data beyond the expected metadata size.
250 if (install_plan_->metadata_size > 0 &&
251 install_plan_->metadata_size != *metadata_size) {
252 LOG(ERROR) << "Invalid metadata size. Expected = "
253 << install_plan_->metadata_size
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700254 << "Actual = " << *metadata_size;
255 // TODO(jaysri): Add a UMA Stat here to help with the decision to enforce
256 // this check in a future release, as mentioned below.
257
258 // TODO(jaysri): VALIDATION: Initially we don't want to make this a fatal
259 // error. But in the next release, we should uncomment the lines below.
260 // *error = kActionCodeDownloadInvalidManifest;
261 // return kMetadataParseError;
262 }
263
264 // Now that we have validated the metadata size, we should wait for the full
265 // metadata to be read in before we can parse it.
266 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800267 return kMetadataParseInsufficientData;
268 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700269
270 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700271 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700272 // that we just log once (instead of logging n times) if it takes n
273 // DeltaPerformer::Write calls to download the full manifest.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700274 if (install_plan_->metadata_size == 0)
275 LOG(WARNING) << "No metadata size specified in Omaha. "
276 << "Trusting metadata size in payload = " << *metadata_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700277 else
278 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
279
Jay Srinivasanf4318702012-09-24 11:56:24 -0700280 // We have the full metadata in |payload|. Verify its integrity
281 // and authenticity based on the information we have in Omaha response.
282 *error = ValidateMetadataSignature(&payload[0], *metadata_size);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700283 if (*error != kActionCodeSuccess) {
284 // TODO(jaysri): Add a UMA Stat here to help with the decision to enforce
285 // this check in a future release, as mentioned below.
286
287 // TODO(jaysri): VALIDATION: Initially we don't want to make this a fatal
288 // error. But in the next release, we should remove the line below and
289 // return an error.
290 *error = kActionCodeSuccess;
291 }
292
Jay Srinivasanf4318702012-09-24 11:56:24 -0700293 // The metadata in |payload| is deemed valid. So, it's now safe to
294 // parse the protobuf.
295 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800296 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700297 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800298 return kMetadataParseError;
299 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800300 return kMetadataParseSuccess;
301}
302
303
Don Garrette410e0f2011-11-10 15:39:01 -0800304// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700305// were written, or false on any error, reguardless of progress
306// and stores an action exit code in |error|.
307bool DeltaPerformer::Write(const void* bytes, size_t count,
308 ActionExitCode *error) {
309 *error = kActionCodeSuccess;
310
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700311 const char* c_bytes = reinterpret_cast<const char*>(bytes);
312 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700313 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800314 MetadataParseResult result = ParsePayloadMetadata(buffer_,
315 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700316 &manifest_metadata_size_,
317 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800318 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800319 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800320 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800321 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800322 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700323 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700324 // Remove protobuf and header info from buffer_, so buffer_ contains
325 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700326 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700327 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700328 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700329 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700330 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700331
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700332 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700333 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700334 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700335 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800336 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700337 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700338 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700339 ssize_t total_operations = manifest_.install_operations_size() +
340 manifest_.kernel_install_operations_size();
341 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700342 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700343 next_operation_num_ < manifest_.install_operations_size() ?
344 manifest_.install_operations(next_operation_num_) :
345 manifest_.kernel_install_operations(
346 next_operation_num_ - manifest_.install_operations_size());
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700347 if (!CanPerformInstallOperation(op)) {
348 // This means we don't have enough bytes received yet to carry out the
349 // next operation.
350 return true;
351 }
352
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700353 bool should_log = (next_operation_num_ % 1000 == 0 ||
354 next_operation_num_ == total_operations - 1);
355
Jay Srinivasanf4318702012-09-24 11:56:24 -0700356 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700357 // Otherwise, keep the old behavior. This serves as a knob to disable
358 // the validation logic in case we find some regression after rollout.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700359 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700360 // Note: Validate must be called only if CanPerformInstallOperation is
361 // called. Otherwise, we might be failing operations before even if there
362 // isn't sufficient data to compute the proper hash.
363 *error = ValidateOperationHash(op, should_log);
364 if (*error != kActionCodeSuccess) {
365 // Cannot proceed further as operation hash is invalid.
366 // Higher level code will take care of retrying appropriately.
367 //
368 // TODO(jaysri): Add a UMA stat to indicate that an operation hash
369 // was failed to be validated as expected.
370 //
371 // TODO(jaysri): VALIDATION: For now, we don't treat this as fatal.
372 // But once we're confident that the new code works fine in the field,
373 // we should uncomment the line below.
374 // return false;
375 LOG(INFO) << "Ignoring operation validation errors for now";
376 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700377 }
378
Darin Petkov45580e42010-10-08 14:02:40 -0700379 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700380 ScopedTerminatorExitUnblocker exit_unblocker =
381 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700382 // Log every thousandth operation, and also the first and last ones
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700383 if (should_log) {
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700384 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
385 << total_operations;
386 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700387 bool is_kernel_partition =
388 (next_operation_num_ >= manifest_.install_operations_size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700389 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
390 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700391 if (!PerformReplaceOperation(op, is_kernel_partition)) {
392 LOG(ERROR) << "Failed to perform replace operation "
393 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700394 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800395 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700396 }
397 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700398 if (!PerformMoveOperation(op, is_kernel_partition)) {
399 LOG(ERROR) << "Failed to perform move operation "
400 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700401 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800402 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700403 }
404 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700405 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
406 LOG(ERROR) << "Failed to perform bsdiff operation "
407 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700408 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800409 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700410 }
411 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700412 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700413 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700414 }
Don Garrette410e0f2011-11-10 15:39:01 -0800415 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700416}
417
418bool DeltaPerformer::CanPerformInstallOperation(
419 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
420 operation) {
421 // Move operations don't require any data blob, so they can always
422 // be performed
423 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
424 return true;
425
426 // See if we have the entire data blob in the buffer
427 if (operation.data_offset() < buffer_offset_) {
428 LOG(ERROR) << "we threw away data it seems?";
429 return false;
430 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700431
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700432 return (operation.data_offset() + operation.data_length()) <=
433 (buffer_offset_ + buffer_.size());
434}
435
436bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700437 const DeltaArchiveManifest_InstallOperation& operation,
438 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700439 CHECK(operation.type() == \
440 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
441 operation.type() == \
442 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
443
444 // Since we delete data off the beginning of the buffer as we use it,
445 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700446 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
447 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700448
Darin Petkov437adc42010-10-07 13:12:24 -0700449 // Extract the signature message if it's in this operation.
450 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700451
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700452 DirectExtentWriter direct_writer;
453 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
454 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700455
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700456 // Since bzip decompression is optional, we have a variable writer that will
457 // point to one of the ExtentWriter objects above.
458 ExtentWriter* writer = NULL;
459 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
460 writer = &zero_pad_writer;
461 } else if (operation.type() ==
462 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
463 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
464 writer = bzip_writer.get();
465 } else {
466 NOTREACHED();
467 }
468
469 // Create a vector of extents to pass to the ExtentWriter.
470 vector<Extent> extents;
471 for (int i = 0; i < operation.dst_extents_size(); i++) {
472 extents.push_back(operation.dst_extents(i));
473 }
474
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700475 int fd = is_kernel_partition ? kernel_fd_ : fd_;
476
477 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700478 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
479 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700480
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700481 // Update buffer
482 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700483 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700484 return true;
485}
486
487bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700488 const DeltaArchiveManifest_InstallOperation& operation,
489 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700490 // Calculate buffer size. Note, this function doesn't do a sliding
491 // window to copy in case the source and destination blocks overlap.
492 // If we wanted to do a sliding window, we could program the server
493 // to generate deltas that effectively did a sliding window.
494
495 uint64_t blocks_to_read = 0;
496 for (int i = 0; i < operation.src_extents_size(); i++)
497 blocks_to_read += operation.src_extents(i).num_blocks();
498
499 uint64_t blocks_to_write = 0;
500 for (int i = 0; i < operation.dst_extents_size(); i++)
501 blocks_to_write += operation.dst_extents(i).num_blocks();
502
503 DCHECK_EQ(blocks_to_write, blocks_to_read);
504 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700505
506 int fd = is_kernel_partition ? kernel_fd_ : fd_;
507
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700508 // Read in bytes.
509 ssize_t bytes_read = 0;
510 for (int i = 0; i < operation.src_extents_size(); i++) {
511 ssize_t bytes_read_this_iteration = 0;
512 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700513 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700514 &buf[bytes_read],
515 extent.num_blocks() * block_size_,
516 extent.start_block() * block_size_,
517 &bytes_read_this_iteration));
518 TEST_AND_RETURN_FALSE(
519 bytes_read_this_iteration ==
520 static_cast<ssize_t>(extent.num_blocks() * block_size_));
521 bytes_read += bytes_read_this_iteration;
522 }
523
Darin Petkov45580e42010-10-08 14:02:40 -0700524 // If this is a non-idempotent operation, request a delayed exit and clear the
525 // update state in case the operation gets interrupted. Do this as late as
526 // possible.
527 if (!IsIdempotentOperation(operation)) {
528 Terminator::set_exit_blocked(true);
529 ResetUpdateProgress(prefs_, true);
530 }
531
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700532 // Write bytes out.
533 ssize_t bytes_written = 0;
534 for (int i = 0; i < operation.dst_extents_size(); i++) {
535 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700536 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700537 &buf[bytes_written],
538 extent.num_blocks() * block_size_,
539 extent.start_block() * block_size_));
540 bytes_written += extent.num_blocks() * block_size_;
541 }
542 DCHECK_EQ(bytes_written, bytes_read);
543 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
544 return true;
545}
546
547bool DeltaPerformer::ExtentsToBsdiffPositionsString(
548 const RepeatedPtrField<Extent>& extents,
549 uint64_t block_size,
550 uint64_t full_length,
551 string* positions_string) {
552 string ret;
553 uint64_t length = 0;
554 for (int i = 0; i < extents.size(); i++) {
555 Extent extent = extents.Get(i);
556 int64_t start = extent.start_block();
557 uint64_t this_length = min(full_length - length,
558 extent.num_blocks() * block_size);
559 if (start == static_cast<int64_t>(kSparseHole))
560 start = -1;
561 else
562 start *= block_size;
563 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
564 length += this_length;
565 }
566 TEST_AND_RETURN_FALSE(length == full_length);
567 if (!ret.empty())
568 ret.resize(ret.size() - 1); // Strip trailing comma off
569 *positions_string = ret;
570 return true;
571}
572
573bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700574 const DeltaArchiveManifest_InstallOperation& operation,
575 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700576 // Since we delete data off the beginning of the buffer as we use it,
577 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700578 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
579 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700580
581 string input_positions;
582 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
583 block_size_,
584 operation.src_length(),
585 &input_positions));
586 string output_positions;
587 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
588 block_size_,
589 operation.dst_length(),
590 &output_positions));
591
592 string temp_filename;
593 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
594 &temp_filename,
595 NULL));
596 ScopedPathUnlinker path_unlinker(temp_filename);
597 {
598 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
599 ScopedFdCloser fd_closer(&fd);
600 TEST_AND_RETURN_FALSE(
601 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
602 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700603
604 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700605 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700606
Darin Petkov45580e42010-10-08 14:02:40 -0700607 // If this is a non-idempotent operation, request a delayed exit and clear the
608 // update state in case the operation gets interrupted. Do this as late as
609 // possible.
610 if (!IsIdempotentOperation(operation)) {
611 Terminator::set_exit_blocked(true);
612 ResetUpdateProgress(prefs_, true);
613 }
614
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700615 vector<string> cmd;
616 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700617 cmd.push_back(path);
618 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700619 cmd.push_back(temp_filename);
620 cmd.push_back(input_positions);
621 cmd.push_back(output_positions);
622 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700623 TEST_AND_RETURN_FALSE(
624 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700625 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700626 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700627 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700628 TEST_AND_RETURN_FALSE(return_code == 0);
629
630 if (operation.dst_length() % block_size_) {
631 // Zero out rest of final block.
632 // TODO(adlr): build this into bspatch; it's more efficient that way.
633 const Extent& last_extent =
634 operation.dst_extents(operation.dst_extents_size() - 1);
635 const uint64_t end_byte =
636 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
637 const uint64_t begin_byte =
638 end_byte - (block_size_ - operation.dst_length() % block_size_);
639 vector<char> zeros(end_byte - begin_byte);
640 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700641 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700642 }
643
644 // Update buffer.
645 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700646 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700647 return true;
648}
649
Darin Petkovd7061ab2010-10-06 14:37:09 -0700650bool DeltaPerformer::ExtractSignatureMessage(
651 const DeltaArchiveManifest_InstallOperation& operation) {
652 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
653 !manifest_.has_signatures_offset() ||
654 manifest_.signatures_offset() != operation.data_offset()) {
655 return false;
656 }
657 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
658 manifest_.signatures_size() == operation.data_length());
659 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
660 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
661 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700662 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700663 buffer_.begin(),
664 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700665
666 // Save the signature blob because if the update is interrupted after the
667 // download phase we don't go through this path anymore. Some alternatives to
668 // consider:
669 //
670 // 1. On resume, re-download the signature blob from the server and re-verify
671 // it.
672 //
673 // 2. Verify the signature as soon as it's received and don't checkpoint the
674 // blob and the signed sha-256 context.
675 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
676 string(&signatures_message_data_[0],
677 signatures_message_data_.size())))
678 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700679 // The hash of all data consumed so far should be verified against the signed
680 // hash.
681 signed_hash_context_ = hash_calculator_.GetContext();
682 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
683 signed_hash_context_))
684 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700685 LOG(INFO) << "Extracted signature data of size "
686 << manifest_.signatures_size() << " at "
687 << manifest_.signatures_offset();
688 return true;
689}
690
Jay Srinivasanf4318702012-09-24 11:56:24 -0700691ActionExitCode DeltaPerformer::ValidateMetadataSignature(
692 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700693
Jay Srinivasanf4318702012-09-24 11:56:24 -0700694 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700695 // If this is not present, we cannot validate the manifest. This should
696 // never happen in normal circumstances, but this can be used as a
697 // release-knob to turn off the new code path that verify per-operation
698 // hashes. So, for now, we should not treat this as a failure. Once we are
699 // confident this path is bug-free, we should treat this as a failure so
700 // that we remain robust even if the connection to Omaha is subjected to
701 // any SSL attack.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700702 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700703 return kActionCodeSuccess;
704 }
705
706 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700707 vector<char> metadata_signature;
708 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
709 &metadata_signature)) {
710 LOG(ERROR) << "Unable to decode base64 metadata signature: "
711 << install_plan_->metadata_signature;
712 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700713 }
714
Jay Srinivasanf4318702012-09-24 11:56:24 -0700715 vector<char> expected_metadata_hash;
716 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700717 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700718 &expected_metadata_hash)) {
719 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
720 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700721 }
722
Jay Srinivasanf4318702012-09-24 11:56:24 -0700723 OmahaHashCalculator metadata_hasher;
724 metadata_hasher.Update(metadata, metadata_size);
725 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700726 LOG(ERROR) << "Unable to compute actual hash of manifest";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700727 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700728 }
729
Jay Srinivasanf4318702012-09-24 11:56:24 -0700730 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
731 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
732 if (calculated_metadata_hash.empty()) {
733 LOG(ERROR) << "Computed actual hash of metadata is empty.";
734 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700735 }
736
Jay Srinivasanf4318702012-09-24 11:56:24 -0700737 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700738 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700739 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700740 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700741 utils::HexDumpVector(calculated_metadata_hash);
742 return kActionCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700743 }
744
745 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
746 return kActionCodeSuccess;
747}
748
749ActionExitCode DeltaPerformer::ValidateOperationHash(
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700750 const DeltaArchiveManifest_InstallOperation& operation,
751 bool should_log) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700752
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700753 if (!operation.data_sha256_hash().size()) {
754 if (!operation.data_length()) {
755 // Operations that do not have any data blob won't have any operation hash
756 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700757 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700758 // has already been validated.
759 return kActionCodeSuccess;
760 }
761
762 // TODO(jaysri): Add a UMA stat here so we're aware of any
763 // man-in-the-middle attempts to bypass these checks.
764 //
765 // TODO(jaysri): VALIDATION: no hash is present for the operation. This
766 // shouldn't happen normally for any client that has this code, because the
767 // corresponding update should have been produced with the operation
768 // hashes. But if it happens it's likely that we've turned this feature off
769 // in Omaha rule for some reason. Once we make these hashes mandatory, we
770 // should return an error here.
771 // One caveat though: The last operation is a dummy signature operation
772 // that doesn't have a hash at the time the manifest is created. So we
773 // should not complaint about that operation. This operation can be
774 // recognized by the fact that it's offset is mentioned in the manifest.
775 if (manifest_.signatures_offset() &&
776 manifest_.signatures_offset() == operation.data_offset()) {
777 LOG(INFO) << "Skipping hash verification for signature operation "
778 << next_operation_num_ + 1;
779 } else {
780 // TODO(jaysri): Uncomment this logging after fixing dev server
781 // LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
782 // << " as no expected hash present";
783 }
784 return kActionCodeSuccess;
785 }
786
787 vector<char> expected_op_hash;
788 expected_op_hash.assign(operation.data_sha256_hash().data(),
789 (operation.data_sha256_hash().data() +
790 operation.data_sha256_hash().size()));
791
792 OmahaHashCalculator operation_hasher;
793 operation_hasher.Update(&buffer_[0], operation.data_length());
794 if (!operation_hasher.Finalize()) {
795 LOG(ERROR) << "Unable to compute actual hash of operation "
796 << next_operation_num_;
797 return kActionCodeDownloadOperationHashVerificationError;
798 }
799
800 vector<char> calculated_op_hash = operation_hasher.raw_hash();
801 if (calculated_op_hash != expected_op_hash) {
802 LOG(ERROR) << "Hash verification failed for operation "
803 << next_operation_num_ << ". Expected hash = ";
804 utils::HexDumpVector(expected_op_hash);
805 LOG(ERROR) << "Calculated hash over " << operation.data_length()
806 << " bytes at offset: " << operation.data_offset() << " = ";
807 utils::HexDumpVector(calculated_op_hash);
808 return kActionCodeDownloadOperationHashMismatch;
809 }
810
811 if (should_log)
812 LOG(INFO) << "Validated operation " << next_operation_num_ + 1;
813
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700814 return kActionCodeSuccess;
815}
816
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700817#define TEST_AND_RETURN_VAL(_retval, _condition) \
818 do { \
819 if (!(_condition)) { \
820 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
821 return _retval; \
822 } \
823 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700824
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700825ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700826 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700827 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700828 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700829
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700830 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700831 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700832 update_check_response_size ==
833 manifest_metadata_size_ + buffer_offset_);
834
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700835 // Verifies the payload hash.
836 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700837 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700838 !payload_hash_data.empty());
839 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
840 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700841
Darin Petkov437adc42010-10-07 13:12:24 -0700842 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700843 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700844 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700845 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700846 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700847 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
848 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700849 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700850 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
851 PayloadSigner::VerifySignature(
852 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700853 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700854 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700855 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700856 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
857 signed_hasher.SetContext(signed_hash_context_));
858 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
859 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700860 vector<char> hash_data = signed_hasher.raw_hash();
861 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700862 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
863 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700864 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700865 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700866 "Attached Signature:";
867 utils::HexDumpVector(signed_hash_data);
868 LOG(ERROR) << "Computed Signature:";
869 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700870 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700871 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700872 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700873}
874
Darin Petkov3aefa862010-12-07 14:45:00 -0800875bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
876 vector<char>* kernel_hash,
877 uint64_t* rootfs_size,
878 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700879 TEST_AND_RETURN_FALSE(manifest_valid_ &&
880 manifest_.has_new_kernel_info() &&
881 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -0800882 *kernel_size = manifest_.new_kernel_info().size();
883 *rootfs_size = manifest_.new_rootfs_info().size();
884 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
885 manifest_.new_kernel_info().hash().end());
886 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
887 manifest_.new_rootfs_info().hash().end());
888 kernel_hash->swap(new_kernel_hash);
889 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700890 return true;
891}
892
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700893namespace {
894void LogVerifyError(bool is_kern,
895 const string& local_hash,
896 const string& expected_hash) {
897 const char* type = is_kern ? "kernel" : "rootfs";
898 LOG(ERROR) << "This is a server-side error due to "
899 << "mismatched delta update image!";
900 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
901 << "update that must be applied over a " << type << " with "
902 << "a specific checksum, but the " << type << " we're starting "
903 << "with doesn't have that checksum! This means that "
904 << "the delta I've been given doesn't match my existing "
905 << "system. The " << type << " partition I have has hash: "
906 << local_hash << " but the update expected me to have "
907 << expected_hash << " .";
908 if (is_kern) {
909 LOG(INFO) << "To get the checksum of a kernel partition on a "
910 << "booted machine, run this command (change /dev/sda2 "
911 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
912 << "openssl dgst -sha256 -binary | openssl base64";
913 } else {
914 LOG(INFO) << "To get the checksum of a rootfs partition on a "
915 << "booted machine, run this command (change /dev/sda3 "
916 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
917 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
918 << "| sed 's/[^0-9]*//') / 256 )) | "
919 << "openssl dgst -sha256 -binary | openssl base64";
920 }
921 LOG(INFO) << "To get the checksum of partitions in a bin file, "
922 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
923}
924
925string StringForHashBytes(const void* bytes, size_t size) {
926 string ret;
927 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
928 ret = "<unknown>";
929 }
930 return ret;
931}
932} // namespace
933
Darin Petkov698d0412010-10-13 10:59:44 -0700934bool DeltaPerformer::VerifySourcePartitions() {
935 LOG(INFO) << "Verifying source partitions.";
936 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700937 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -0700938 if (manifest_.has_old_kernel_info()) {
939 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700940 bool valid =
941 !install_plan_->kernel_hash.empty() &&
942 install_plan_->kernel_hash.size() == info.hash().size() &&
943 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700944 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700945 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700946 if (!valid) {
947 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700948 StringForHashBytes(install_plan_->kernel_hash.data(),
949 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700950 StringForHashBytes(info.hash().data(),
951 info.hash().size()));
952 }
953 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700954 }
955 if (manifest_.has_old_rootfs_info()) {
956 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700957 bool valid =
958 !install_plan_->rootfs_hash.empty() &&
959 install_plan_->rootfs_hash.size() == info.hash().size() &&
960 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700961 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700962 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700963 if (!valid) {
964 LogVerifyError(false,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700965 StringForHashBytes(install_plan_->kernel_hash.data(),
966 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700967 StringForHashBytes(info.hash().data(),
968 info.hash().size()));
969 }
970 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700971 }
972 return true;
973}
974
Darin Petkov437adc42010-10-07 13:12:24 -0700975void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
976 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700977 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
978}
979
Darin Petkov0406e402010-10-06 21:33:11 -0700980bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
981 string update_check_response_hash) {
982 int64_t next_operation = kUpdateStateOperationInvalid;
983 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
984 &next_operation) &&
985 next_operation != kUpdateStateOperationInvalid &&
986 next_operation > 0);
987
988 string interrupted_hash;
989 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
990 &interrupted_hash) &&
991 !interrupted_hash.empty() &&
992 interrupted_hash == update_check_response_hash);
993
Darin Petkov61426142010-10-08 11:04:55 -0700994 int64_t resumed_update_failures;
995 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
996 &resumed_update_failures) ||
997 resumed_update_failures <= kMaxResumedUpdateFailures);
998
Darin Petkov0406e402010-10-06 21:33:11 -0700999 // Sanity check the rest.
1000 int64_t next_data_offset = -1;
1001 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1002 &next_data_offset) &&
1003 next_data_offset >= 0);
1004
Darin Petkov437adc42010-10-07 13:12:24 -07001005 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001006 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001007 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1008 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001009
1010 int64_t manifest_metadata_size = 0;
1011 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1012 &manifest_metadata_size) &&
1013 manifest_metadata_size > 0);
1014
1015 return true;
1016}
1017
Darin Petkov9b230572010-10-08 10:20:09 -07001018bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001019 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1020 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001021 if (!quick) {
1022 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1023 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1024 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1025 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001026 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001027 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001028 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001029 }
Darin Petkov73058b42010-10-06 16:32:19 -07001030 return true;
1031}
1032
1033bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001034 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001035 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001036 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001037 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001038 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001039 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001040 hash_calculator_.GetContext()));
1041 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1042 buffer_offset_));
1043 last_updated_buffer_offset_ = buffer_offset_;
1044 }
Darin Petkov73058b42010-10-06 16:32:19 -07001045 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1046 next_operation_num_));
1047 return true;
1048}
1049
Darin Petkov9b230572010-10-08 10:20:09 -07001050bool DeltaPerformer::PrimeUpdateState() {
1051 CHECK(manifest_valid_);
1052 block_size_ = manifest_.block_size();
1053
1054 int64_t next_operation = kUpdateStateOperationInvalid;
1055 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1056 next_operation == kUpdateStateOperationInvalid ||
1057 next_operation <= 0) {
1058 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001059 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001060 return true;
1061 }
1062 next_operation_num_ = next_operation;
1063
1064 // Resuming an update -- load the rest of the update state.
1065 int64_t next_data_offset = -1;
1066 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1067 &next_data_offset) &&
1068 next_data_offset >= 0);
1069 buffer_offset_ = next_data_offset;
1070
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001071 // The signed hash context and the signature blob may be empty if the
1072 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001073 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1074 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001075 string signature_blob;
1076 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1077 signatures_message_data_.assign(signature_blob.begin(),
1078 signature_blob.end());
1079 }
Darin Petkov9b230572010-10-08 10:20:09 -07001080
1081 string hash_context;
1082 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1083 &hash_context) &&
1084 hash_calculator_.SetContext(hash_context));
1085
1086 int64_t manifest_metadata_size = 0;
1087 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1088 &manifest_metadata_size) &&
1089 manifest_metadata_size > 0);
1090 manifest_metadata_size_ = manifest_metadata_size;
1091
Darin Petkov61426142010-10-08 11:04:55 -07001092 // Speculatively count the resume as a failure.
1093 int64_t resumed_update_failures;
1094 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1095 resumed_update_failures++;
1096 } else {
1097 resumed_update_failures = 1;
1098 }
1099 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001100 return true;
1101}
1102
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001103} // namespace chromeos_update_engine