blob: e771da058da1cc1e6cd870c5a544e7c8b8b43e5f [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;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700255 // Send a UMA Stat here to help with the decision to enforce
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700256 // this check in a future release, as mentioned below.
Jay Srinivasanedce2832012-10-24 18:57:47 -0700257 SendUmaStat(kActionCodeDownloadInvalidMetadataSize);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700258
259 // TODO(jaysri): VALIDATION: Initially we don't want to make this a fatal
Jay Srinivasanedce2832012-10-24 18:57:47 -0700260 // error. But in the next release, we should uncomment the lines below
261 // and remove the SendUmaStat call above.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700262 // *error = kActionCodeDownloadInvalidManifest;
263 // return kMetadataParseError;
264 }
265
266 // Now that we have validated the metadata size, we should wait for the full
267 // metadata to be read in before we can parse it.
268 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800269 return kMetadataParseInsufficientData;
270 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700271
272 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700273 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700274 // that we just log once (instead of logging n times) if it takes n
275 // DeltaPerformer::Write calls to download the full manifest.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700276 if (install_plan_->metadata_size == 0)
277 LOG(WARNING) << "No metadata size specified in Omaha. "
278 << "Trusting metadata size in payload = " << *metadata_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700279 else
280 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
281
Jay Srinivasanf4318702012-09-24 11:56:24 -0700282 // We have the full metadata in |payload|. Verify its integrity
283 // and authenticity based on the information we have in Omaha response.
284 *error = ValidateMetadataSignature(&payload[0], *metadata_size);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700285 if (*error != kActionCodeSuccess) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700286 // Send a UMA Stat here to help with the decision to enforce
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700287 // this check in a future release, as mentioned below.
Jay Srinivasanedce2832012-10-24 18:57:47 -0700288 SendUmaStat(*error);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700289
290 // TODO(jaysri): VALIDATION: Initially we don't want to make this a fatal
291 // error. But in the next release, we should remove the line below and
Jay Srinivasanedce2832012-10-24 18:57:47 -0700292 // return an error. We should also remove the SendUmaStat call above.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700293 *error = kActionCodeSuccess;
294 }
295
Jay Srinivasanf4318702012-09-24 11:56:24 -0700296 // The metadata in |payload| is deemed valid. So, it's now safe to
297 // parse the protobuf.
298 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800299 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700300 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800301 return kMetadataParseError;
302 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800303 return kMetadataParseSuccess;
304}
305
306
Don Garrette410e0f2011-11-10 15:39:01 -0800307// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700308// were written, or false on any error, reguardless of progress
309// and stores an action exit code in |error|.
310bool DeltaPerformer::Write(const void* bytes, size_t count,
311 ActionExitCode *error) {
312 *error = kActionCodeSuccess;
313
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700314 const char* c_bytes = reinterpret_cast<const char*>(bytes);
315 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700316 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800317 MetadataParseResult result = ParsePayloadMetadata(buffer_,
318 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700319 &manifest_metadata_size_,
320 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800321 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800322 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800323 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800324 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800325 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700326 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700327 // Remove protobuf and header info from buffer_, so buffer_ contains
328 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700329 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700330 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700331 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700332 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700333 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700334
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700335 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700336 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700337 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700338 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800339 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700340 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700341 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700342 ssize_t total_operations = manifest_.install_operations_size() +
343 manifest_.kernel_install_operations_size();
344 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700345 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700346 next_operation_num_ < manifest_.install_operations_size() ?
347 manifest_.install_operations(next_operation_num_) :
348 manifest_.kernel_install_operations(
349 next_operation_num_ - manifest_.install_operations_size());
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700350 if (!CanPerformInstallOperation(op)) {
351 // This means we don't have enough bytes received yet to carry out the
352 // next operation.
353 return true;
354 }
355
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700356 bool should_log = (next_operation_num_ % 1000 == 0 ||
357 next_operation_num_ == total_operations - 1);
358
Jay Srinivasanf4318702012-09-24 11:56:24 -0700359 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700360 // Otherwise, keep the old behavior. This serves as a knob to disable
361 // the validation logic in case we find some regression after rollout.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700362 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700363 // Note: Validate must be called only if CanPerformInstallOperation is
364 // called. Otherwise, we might be failing operations before even if there
365 // isn't sufficient data to compute the proper hash.
366 *error = ValidateOperationHash(op, should_log);
367 if (*error != kActionCodeSuccess) {
368 // Cannot proceed further as operation hash is invalid.
369 // Higher level code will take care of retrying appropriately.
Jay Srinivasanf0572052012-10-23 18:12:56 -0700370
371 // Send a UMA stat to indicate that an operation hash failed to be
372 // validated as expected.
Jay Srinivasanedce2832012-10-24 18:57:47 -0700373 SendUmaStat(*error);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700374
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700375 // TODO(jaysri): VALIDATION: For now, we don't treat this as fatal.
376 // But once we're confident that the new code works fine in the field,
Jay Srinivasanedce2832012-10-24 18:57:47 -0700377 // we should uncomment the line below. We should also remove the
378 // SendUmaStat call above.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700379 // return false;
380 LOG(INFO) << "Ignoring operation validation errors for now";
381 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700382 }
383
Darin Petkov45580e42010-10-08 14:02:40 -0700384 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700385 ScopedTerminatorExitUnblocker exit_unblocker =
386 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700387 // Log every thousandth operation, and also the first and last ones
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700388 if (should_log) {
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700389 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
390 << total_operations;
391 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700392 bool is_kernel_partition =
393 (next_operation_num_ >= manifest_.install_operations_size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700394 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
395 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700396 if (!PerformReplaceOperation(op, is_kernel_partition)) {
397 LOG(ERROR) << "Failed to perform replace operation "
398 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700399 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800400 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700401 }
402 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700403 if (!PerformMoveOperation(op, is_kernel_partition)) {
404 LOG(ERROR) << "Failed to perform move operation "
405 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700406 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800407 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700408 }
409 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700410 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
411 LOG(ERROR) << "Failed to perform bsdiff operation "
412 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700413 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800414 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700415 }
416 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700417 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700418 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700419 }
Don Garrette410e0f2011-11-10 15:39:01 -0800420 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700421}
422
423bool DeltaPerformer::CanPerformInstallOperation(
424 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
425 operation) {
426 // Move operations don't require any data blob, so they can always
427 // be performed
428 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
429 return true;
430
431 // See if we have the entire data blob in the buffer
432 if (operation.data_offset() < buffer_offset_) {
433 LOG(ERROR) << "we threw away data it seems?";
434 return false;
435 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700436
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700437 return (operation.data_offset() + operation.data_length()) <=
438 (buffer_offset_ + buffer_.size());
439}
440
441bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700442 const DeltaArchiveManifest_InstallOperation& operation,
443 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700444 CHECK(operation.type() == \
445 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
446 operation.type() == \
447 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
448
449 // Since we delete data off the beginning of the buffer as we use it,
450 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700451 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
452 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700453
Darin Petkov437adc42010-10-07 13:12:24 -0700454 // Extract the signature message if it's in this operation.
455 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700456
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700457 DirectExtentWriter direct_writer;
458 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
459 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700460
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700461 // Since bzip decompression is optional, we have a variable writer that will
462 // point to one of the ExtentWriter objects above.
463 ExtentWriter* writer = NULL;
464 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
465 writer = &zero_pad_writer;
466 } else if (operation.type() ==
467 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
468 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
469 writer = bzip_writer.get();
470 } else {
471 NOTREACHED();
472 }
473
474 // Create a vector of extents to pass to the ExtentWriter.
475 vector<Extent> extents;
476 for (int i = 0; i < operation.dst_extents_size(); i++) {
477 extents.push_back(operation.dst_extents(i));
478 }
479
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700480 int fd = is_kernel_partition ? kernel_fd_ : fd_;
481
482 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700483 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
484 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700485
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700486 // Update buffer
487 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700488 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700489 return true;
490}
491
492bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700493 const DeltaArchiveManifest_InstallOperation& operation,
494 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700495 // Calculate buffer size. Note, this function doesn't do a sliding
496 // window to copy in case the source and destination blocks overlap.
497 // If we wanted to do a sliding window, we could program the server
498 // to generate deltas that effectively did a sliding window.
499
500 uint64_t blocks_to_read = 0;
501 for (int i = 0; i < operation.src_extents_size(); i++)
502 blocks_to_read += operation.src_extents(i).num_blocks();
503
504 uint64_t blocks_to_write = 0;
505 for (int i = 0; i < operation.dst_extents_size(); i++)
506 blocks_to_write += operation.dst_extents(i).num_blocks();
507
508 DCHECK_EQ(blocks_to_write, blocks_to_read);
509 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700510
511 int fd = is_kernel_partition ? kernel_fd_ : fd_;
512
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700513 // Read in bytes.
514 ssize_t bytes_read = 0;
515 for (int i = 0; i < operation.src_extents_size(); i++) {
516 ssize_t bytes_read_this_iteration = 0;
517 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700518 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700519 &buf[bytes_read],
520 extent.num_blocks() * block_size_,
521 extent.start_block() * block_size_,
522 &bytes_read_this_iteration));
523 TEST_AND_RETURN_FALSE(
524 bytes_read_this_iteration ==
525 static_cast<ssize_t>(extent.num_blocks() * block_size_));
526 bytes_read += bytes_read_this_iteration;
527 }
528
Darin Petkov45580e42010-10-08 14:02:40 -0700529 // If this is a non-idempotent operation, request a delayed exit and clear the
530 // update state in case the operation gets interrupted. Do this as late as
531 // possible.
532 if (!IsIdempotentOperation(operation)) {
533 Terminator::set_exit_blocked(true);
534 ResetUpdateProgress(prefs_, true);
535 }
536
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700537 // Write bytes out.
538 ssize_t bytes_written = 0;
539 for (int i = 0; i < operation.dst_extents_size(); i++) {
540 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700541 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700542 &buf[bytes_written],
543 extent.num_blocks() * block_size_,
544 extent.start_block() * block_size_));
545 bytes_written += extent.num_blocks() * block_size_;
546 }
547 DCHECK_EQ(bytes_written, bytes_read);
548 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
549 return true;
550}
551
552bool DeltaPerformer::ExtentsToBsdiffPositionsString(
553 const RepeatedPtrField<Extent>& extents,
554 uint64_t block_size,
555 uint64_t full_length,
556 string* positions_string) {
557 string ret;
558 uint64_t length = 0;
559 for (int i = 0; i < extents.size(); i++) {
560 Extent extent = extents.Get(i);
561 int64_t start = extent.start_block();
562 uint64_t this_length = min(full_length - length,
563 extent.num_blocks() * block_size);
564 if (start == static_cast<int64_t>(kSparseHole))
565 start = -1;
566 else
567 start *= block_size;
568 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
569 length += this_length;
570 }
571 TEST_AND_RETURN_FALSE(length == full_length);
572 if (!ret.empty())
573 ret.resize(ret.size() - 1); // Strip trailing comma off
574 *positions_string = ret;
575 return true;
576}
577
578bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700579 const DeltaArchiveManifest_InstallOperation& operation,
580 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700581 // Since we delete data off the beginning of the buffer as we use it,
582 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700583 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
584 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700585
586 string input_positions;
587 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
588 block_size_,
589 operation.src_length(),
590 &input_positions));
591 string output_positions;
592 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
593 block_size_,
594 operation.dst_length(),
595 &output_positions));
596
597 string temp_filename;
598 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
599 &temp_filename,
600 NULL));
601 ScopedPathUnlinker path_unlinker(temp_filename);
602 {
603 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
604 ScopedFdCloser fd_closer(&fd);
605 TEST_AND_RETURN_FALSE(
606 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
607 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700608
609 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700610 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700611
Darin Petkov45580e42010-10-08 14:02:40 -0700612 // If this is a non-idempotent operation, request a delayed exit and clear the
613 // update state in case the operation gets interrupted. Do this as late as
614 // possible.
615 if (!IsIdempotentOperation(operation)) {
616 Terminator::set_exit_blocked(true);
617 ResetUpdateProgress(prefs_, true);
618 }
619
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700620 vector<string> cmd;
621 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700622 cmd.push_back(path);
623 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700624 cmd.push_back(temp_filename);
625 cmd.push_back(input_positions);
626 cmd.push_back(output_positions);
627 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700628 TEST_AND_RETURN_FALSE(
629 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700630 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700631 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700632 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700633 TEST_AND_RETURN_FALSE(return_code == 0);
634
635 if (operation.dst_length() % block_size_) {
636 // Zero out rest of final block.
637 // TODO(adlr): build this into bspatch; it's more efficient that way.
638 const Extent& last_extent =
639 operation.dst_extents(operation.dst_extents_size() - 1);
640 const uint64_t end_byte =
641 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
642 const uint64_t begin_byte =
643 end_byte - (block_size_ - operation.dst_length() % block_size_);
644 vector<char> zeros(end_byte - begin_byte);
645 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700646 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700647 }
648
649 // Update buffer.
650 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700651 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700652 return true;
653}
654
Darin Petkovd7061ab2010-10-06 14:37:09 -0700655bool DeltaPerformer::ExtractSignatureMessage(
656 const DeltaArchiveManifest_InstallOperation& operation) {
657 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
658 !manifest_.has_signatures_offset() ||
659 manifest_.signatures_offset() != operation.data_offset()) {
660 return false;
661 }
662 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
663 manifest_.signatures_size() == operation.data_length());
664 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
665 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
666 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700667 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700668 buffer_.begin(),
669 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700670
671 // Save the signature blob because if the update is interrupted after the
672 // download phase we don't go through this path anymore. Some alternatives to
673 // consider:
674 //
675 // 1. On resume, re-download the signature blob from the server and re-verify
676 // it.
677 //
678 // 2. Verify the signature as soon as it's received and don't checkpoint the
679 // blob and the signed sha-256 context.
680 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
681 string(&signatures_message_data_[0],
682 signatures_message_data_.size())))
683 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700684 // The hash of all data consumed so far should be verified against the signed
685 // hash.
686 signed_hash_context_ = hash_calculator_.GetContext();
687 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
688 signed_hash_context_))
689 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700690 LOG(INFO) << "Extracted signature data of size "
691 << manifest_.signatures_size() << " at "
692 << manifest_.signatures_offset();
693 return true;
694}
695
Jay Srinivasanf4318702012-09-24 11:56:24 -0700696ActionExitCode DeltaPerformer::ValidateMetadataSignature(
697 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700698
Jay Srinivasanf4318702012-09-24 11:56:24 -0700699 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasanedce2832012-10-24 18:57:47 -0700700 // TODO(jaysri): If this is not present, we cannot validate the manifest.
701 // This should never happen in normal circumstances, but this can be used
702 // as a release-knob to turn off the new code path that verify
703 // per-operation hashes. So, for now, we should not treat this as a
704 // failure. Once we are confident this path is bug-free, we should treat
705 // this as a failure so that we remain robust even if the connection to
706 // Omaha is subjected to any SSL attack. Once we make this an error, we
707 // should remove the SendUmaStat call below.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700708 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Jay Srinivasanf0572052012-10-23 18:12:56 -0700709
710 // Send a UMA stat here so we're aware of any man-in-the-middle attempts to
711 // bypass these checks.
Jay Srinivasanedce2832012-10-24 18:57:47 -0700712 SendUmaStat(kActionCodeDownloadMetadataSignatureMissingError);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700713
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700714 return kActionCodeSuccess;
715 }
716
717 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700718 vector<char> metadata_signature;
719 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
720 &metadata_signature)) {
721 LOG(ERROR) << "Unable to decode base64 metadata signature: "
722 << install_plan_->metadata_signature;
723 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700724 }
725
Jay Srinivasanf4318702012-09-24 11:56:24 -0700726 vector<char> expected_metadata_hash;
727 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700728 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700729 &expected_metadata_hash)) {
730 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
731 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700732 }
733
Jay Srinivasanf4318702012-09-24 11:56:24 -0700734 OmahaHashCalculator metadata_hasher;
735 metadata_hasher.Update(metadata, metadata_size);
736 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700737 LOG(ERROR) << "Unable to compute actual hash of manifest";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700738 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700739 }
740
Jay Srinivasanf4318702012-09-24 11:56:24 -0700741 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
742 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
743 if (calculated_metadata_hash.empty()) {
744 LOG(ERROR) << "Computed actual hash of metadata is empty.";
745 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700746 }
747
Jay Srinivasanf4318702012-09-24 11:56:24 -0700748 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700749 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700750 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700751 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700752 utils::HexDumpVector(calculated_metadata_hash);
753 return kActionCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700754 }
755
756 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
757 return kActionCodeSuccess;
758}
759
760ActionExitCode DeltaPerformer::ValidateOperationHash(
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700761 const DeltaArchiveManifest_InstallOperation& operation,
762 bool should_log) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700763
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700764 if (!operation.data_sha256_hash().size()) {
765 if (!operation.data_length()) {
766 // Operations that do not have any data blob won't have any operation hash
767 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700768 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700769 // has already been validated.
770 return kActionCodeSuccess;
771 }
772
Jay Srinivasanf0572052012-10-23 18:12:56 -0700773 // Send a UMA stat here so we're aware of any man-in-the-middle attempts to
774 // bypass these checks.
Jay Srinivasanedce2832012-10-24 18:57:47 -0700775 SendUmaStat(kActionCodeDownloadOperationHashMissingError);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700776
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700777 // TODO(jaysri): VALIDATION: no hash is present for the operation. This
778 // shouldn't happen normally for any client that has this code, because the
779 // corresponding update should have been produced with the operation
780 // hashes. But if it happens it's likely that we've turned this feature off
781 // in Omaha rule for some reason. Once we make these hashes mandatory, we
Jay Srinivasanedce2832012-10-24 18:57:47 -0700782 // should return an error here. We should also remove the SendUmaStat call.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700783 // One caveat though: The last operation is a dummy signature operation
784 // that doesn't have a hash at the time the manifest is created. So we
785 // should not complaint about that operation. This operation can be
786 // recognized by the fact that it's offset is mentioned in the manifest.
787 if (manifest_.signatures_offset() &&
788 manifest_.signatures_offset() == operation.data_offset()) {
789 LOG(INFO) << "Skipping hash verification for signature operation "
790 << next_operation_num_ + 1;
791 } else {
792 // TODO(jaysri): Uncomment this logging after fixing dev server
793 // LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
794 // << " as no expected hash present";
795 }
796 return kActionCodeSuccess;
797 }
798
799 vector<char> expected_op_hash;
800 expected_op_hash.assign(operation.data_sha256_hash().data(),
801 (operation.data_sha256_hash().data() +
802 operation.data_sha256_hash().size()));
803
804 OmahaHashCalculator operation_hasher;
805 operation_hasher.Update(&buffer_[0], operation.data_length());
806 if (!operation_hasher.Finalize()) {
807 LOG(ERROR) << "Unable to compute actual hash of operation "
808 << next_operation_num_;
809 return kActionCodeDownloadOperationHashVerificationError;
810 }
811
812 vector<char> calculated_op_hash = operation_hasher.raw_hash();
813 if (calculated_op_hash != expected_op_hash) {
814 LOG(ERROR) << "Hash verification failed for operation "
815 << next_operation_num_ << ". Expected hash = ";
816 utils::HexDumpVector(expected_op_hash);
817 LOG(ERROR) << "Calculated hash over " << operation.data_length()
818 << " bytes at offset: " << operation.data_offset() << " = ";
819 utils::HexDumpVector(calculated_op_hash);
820 return kActionCodeDownloadOperationHashMismatch;
821 }
822
823 if (should_log)
824 LOG(INFO) << "Validated operation " << next_operation_num_ + 1;
825
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700826 return kActionCodeSuccess;
827}
828
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700829#define TEST_AND_RETURN_VAL(_retval, _condition) \
830 do { \
831 if (!(_condition)) { \
832 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
833 return _retval; \
834 } \
835 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700836
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700837ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700838 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700839 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700840 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700841
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700842 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700843 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700844 update_check_response_size ==
845 manifest_metadata_size_ + buffer_offset_);
846
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700847 // Verifies the payload hash.
848 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700849 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700850 !payload_hash_data.empty());
851 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
852 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700853
Darin Petkov437adc42010-10-07 13:12:24 -0700854 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700855 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700856 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700857 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700858 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700859 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
860 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700861 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700862 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
863 PayloadSigner::VerifySignature(
864 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700865 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700866 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700867 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700868 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
869 signed_hasher.SetContext(signed_hash_context_));
870 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
871 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700872 vector<char> hash_data = signed_hasher.raw_hash();
873 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700874 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
875 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700876 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700877 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700878 "Attached Signature:";
879 utils::HexDumpVector(signed_hash_data);
880 LOG(ERROR) << "Computed Signature:";
881 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700882 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700883 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700884 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700885}
886
Darin Petkov3aefa862010-12-07 14:45:00 -0800887bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
888 vector<char>* kernel_hash,
889 uint64_t* rootfs_size,
890 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700891 TEST_AND_RETURN_FALSE(manifest_valid_ &&
892 manifest_.has_new_kernel_info() &&
893 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -0800894 *kernel_size = manifest_.new_kernel_info().size();
895 *rootfs_size = manifest_.new_rootfs_info().size();
896 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
897 manifest_.new_kernel_info().hash().end());
898 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
899 manifest_.new_rootfs_info().hash().end());
900 kernel_hash->swap(new_kernel_hash);
901 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700902 return true;
903}
904
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700905namespace {
906void LogVerifyError(bool is_kern,
907 const string& local_hash,
908 const string& expected_hash) {
909 const char* type = is_kern ? "kernel" : "rootfs";
910 LOG(ERROR) << "This is a server-side error due to "
911 << "mismatched delta update image!";
912 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
913 << "update that must be applied over a " << type << " with "
914 << "a specific checksum, but the " << type << " we're starting "
915 << "with doesn't have that checksum! This means that "
916 << "the delta I've been given doesn't match my existing "
917 << "system. The " << type << " partition I have has hash: "
918 << local_hash << " but the update expected me to have "
919 << expected_hash << " .";
920 if (is_kern) {
921 LOG(INFO) << "To get the checksum of a kernel partition on a "
922 << "booted machine, run this command (change /dev/sda2 "
923 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
924 << "openssl dgst -sha256 -binary | openssl base64";
925 } else {
926 LOG(INFO) << "To get the checksum of a rootfs partition on a "
927 << "booted machine, run this command (change /dev/sda3 "
928 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
929 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
930 << "| sed 's/[^0-9]*//') / 256 )) | "
931 << "openssl dgst -sha256 -binary | openssl base64";
932 }
933 LOG(INFO) << "To get the checksum of partitions in a bin file, "
934 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
935}
936
937string StringForHashBytes(const void* bytes, size_t size) {
938 string ret;
939 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
940 ret = "<unknown>";
941 }
942 return ret;
943}
944} // namespace
945
Darin Petkov698d0412010-10-13 10:59:44 -0700946bool DeltaPerformer::VerifySourcePartitions() {
947 LOG(INFO) << "Verifying source partitions.";
948 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700949 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -0700950 if (manifest_.has_old_kernel_info()) {
951 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700952 bool valid =
953 !install_plan_->kernel_hash.empty() &&
954 install_plan_->kernel_hash.size() == info.hash().size() &&
955 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700956 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700957 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700958 if (!valid) {
959 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700960 StringForHashBytes(install_plan_->kernel_hash.data(),
961 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700962 StringForHashBytes(info.hash().data(),
963 info.hash().size()));
964 }
965 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700966 }
967 if (manifest_.has_old_rootfs_info()) {
968 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700969 bool valid =
970 !install_plan_->rootfs_hash.empty() &&
971 install_plan_->rootfs_hash.size() == info.hash().size() &&
972 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700973 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700974 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700975 if (!valid) {
976 LogVerifyError(false,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700977 StringForHashBytes(install_plan_->kernel_hash.data(),
978 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700979 StringForHashBytes(info.hash().data(),
980 info.hash().size()));
981 }
982 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700983 }
984 return true;
985}
986
Darin Petkov437adc42010-10-07 13:12:24 -0700987void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
988 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700989 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
990}
991
Darin Petkov0406e402010-10-06 21:33:11 -0700992bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
993 string update_check_response_hash) {
994 int64_t next_operation = kUpdateStateOperationInvalid;
995 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
996 &next_operation) &&
997 next_operation != kUpdateStateOperationInvalid &&
998 next_operation > 0);
999
1000 string interrupted_hash;
1001 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1002 &interrupted_hash) &&
1003 !interrupted_hash.empty() &&
1004 interrupted_hash == update_check_response_hash);
1005
Darin Petkov61426142010-10-08 11:04:55 -07001006 int64_t resumed_update_failures;
1007 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1008 &resumed_update_failures) ||
1009 resumed_update_failures <= kMaxResumedUpdateFailures);
1010
Darin Petkov0406e402010-10-06 21:33:11 -07001011 // Sanity check the rest.
1012 int64_t next_data_offset = -1;
1013 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1014 &next_data_offset) &&
1015 next_data_offset >= 0);
1016
Darin Petkov437adc42010-10-07 13:12:24 -07001017 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001018 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001019 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1020 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001021
1022 int64_t manifest_metadata_size = 0;
1023 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1024 &manifest_metadata_size) &&
1025 manifest_metadata_size > 0);
1026
1027 return true;
1028}
1029
Darin Petkov9b230572010-10-08 10:20:09 -07001030bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001031 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1032 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001033 if (!quick) {
1034 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1035 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1036 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1037 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001038 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001039 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001040 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001041 }
Darin Petkov73058b42010-10-06 16:32:19 -07001042 return true;
1043}
1044
1045bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001046 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001047 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001048 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001049 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001050 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001051 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001052 hash_calculator_.GetContext()));
1053 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1054 buffer_offset_));
1055 last_updated_buffer_offset_ = buffer_offset_;
1056 }
Darin Petkov73058b42010-10-06 16:32:19 -07001057 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1058 next_operation_num_));
1059 return true;
1060}
1061
Darin Petkov9b230572010-10-08 10:20:09 -07001062bool DeltaPerformer::PrimeUpdateState() {
1063 CHECK(manifest_valid_);
1064 block_size_ = manifest_.block_size();
1065
1066 int64_t next_operation = kUpdateStateOperationInvalid;
1067 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1068 next_operation == kUpdateStateOperationInvalid ||
1069 next_operation <= 0) {
1070 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001071 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001072 return true;
1073 }
1074 next_operation_num_ = next_operation;
1075
1076 // Resuming an update -- load the rest of the update state.
1077 int64_t next_data_offset = -1;
1078 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1079 &next_data_offset) &&
1080 next_data_offset >= 0);
1081 buffer_offset_ = next_data_offset;
1082
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001083 // The signed hash context and the signature blob may be empty if the
1084 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001085 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1086 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001087 string signature_blob;
1088 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1089 signatures_message_data_.assign(signature_blob.begin(),
1090 signature_blob.end());
1091 }
Darin Petkov9b230572010-10-08 10:20:09 -07001092
1093 string hash_context;
1094 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1095 &hash_context) &&
1096 hash_calculator_.SetContext(hash_context));
1097
1098 int64_t manifest_metadata_size = 0;
1099 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1100 &manifest_metadata_size) &&
1101 manifest_metadata_size > 0);
1102 manifest_metadata_size_ = manifest_metadata_size;
1103
Darin Petkov61426142010-10-08 11:04:55 -07001104 // Speculatively count the resume as a failure.
1105 int64_t resumed_update_failures;
1106 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1107 resumed_update_failures++;
1108 } else {
1109 resumed_update_failures = 1;
1110 }
1111 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001112 return true;
1113}
1114
Jay Srinivasanedce2832012-10-24 18:57:47 -07001115void DeltaPerformer::SendUmaStat(ActionExitCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001116 if (system_state_) {
Jay Srinivasanedce2832012-10-24 18:57:47 -07001117 utils::SendErrorCodeToUma(system_state_->metrics_lib(), code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001118 }
1119}
1120
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001121} // namespace chromeos_update_engine