blob: 3f549cdd55e4ac58c581123a786731be4a06d502 [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"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080026#include "update_engine/payload_state_interface.h"
Darin Petkov73058b42010-10-06 16:32:19 -070027#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070028#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070029#include "update_engine/terminator.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070030
31using std::min;
32using std::string;
33using std::vector;
34using google::protobuf::RepeatedPtrField;
35
36namespace chromeos_update_engine {
37
Jay Srinivasanf4318702012-09-24 11:56:24 -070038const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
39const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Darin Petkovabc7bc02011-02-23 14:39:43 -080040const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
41 "/usr/share/update_engine/update-payload-key.pub.pem";
42
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070043namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070044const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070045const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070046
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070047// Converts extents to a human-readable string, for use by DumpUpdateProto().
48string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
49 string ret;
50 for (int i = 0; i < extents.size(); i++) {
51 const Extent& extent = extents.Get(i);
52 if (extent.start_block() == kSparseHole) {
53 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
54 } else {
55 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
56 extent.start_block(), extent.num_blocks());
57 }
58 }
59 if (!ret.empty()) {
60 DCHECK_GT(ret.size(), static_cast<size_t>(1));
61 ret.resize(ret.size() - 2);
62 }
63 return ret;
64}
65
66// LOGs a DeltaArchiveManifest object. Useful for debugging.
67void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
68 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070069 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070070 for (int i = 0; i < (manifest.install_operations_size() +
71 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070072 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070073 i < manifest.install_operations_size() ?
74 manifest.install_operations(i) :
75 manifest.kernel_install_operations(
76 i - manifest.install_operations_size());
77 if (i == 0)
78 LOG(INFO) << " Rootfs ops:";
79 else if (i == manifest.install_operations_size())
80 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070081 LOG(INFO) << " operation(" << i << ")";
82 LOG(INFO) << " type: "
83 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
84 if (op.has_data_offset())
85 LOG(INFO) << " data_offset: " << op.data_offset();
86 if (op.has_data_length())
87 LOG(INFO) << " data_length: " << op.data_length();
88 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
89 if (op.has_src_length())
90 LOG(INFO) << " src_length: " << op.src_length();
91 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
92 if (op.has_dst_length())
93 LOG(INFO) << " dst_length: " << op.dst_length();
94 }
95}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070096
97// Opens path for read/write, put the fd into *fd. On success returns true
98// and sets *err to 0. On failure, returns false and sets *err to errno.
99bool OpenFile(const char* path, int* fd, int* err) {
100 if (*fd != -1) {
101 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
102 *err = EINVAL;
103 return false;
104 }
105 *fd = open(path, O_RDWR, 000);
106 if (*fd < 0) {
107 *err = errno;
108 PLOG(ERROR) << "Unable to open file " << path;
109 return false;
110 }
111 *err = 0;
112 return true;
113}
114
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700115} // namespace {}
116
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700117// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
118// it safely. Returns false otherwise.
119bool DeltaPerformer::IsIdempotentOperation(
120 const DeltaArchiveManifest_InstallOperation& op) {
121 if (op.src_extents_size() == 0) {
122 return true;
123 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700124 // When in doubt, it's safe to declare an op non-idempotent. Note that we
125 // could detect other types of idempotent operations here such as a MOVE that
126 // moves blocks onto themselves. However, we rely on the server to not send
127 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700128 ExtentRanges src_ranges;
129 src_ranges.AddRepeatedExtents(op.src_extents());
130 const uint64_t block_count = src_ranges.blocks();
131 src_ranges.SubtractRepeatedExtents(op.dst_extents());
132 return block_count == src_ranges.blocks();
133}
134
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700135int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700136 int err;
137 if (OpenFile(path, &fd_, &err))
138 path_ = path;
139 return -err;
140}
141
142bool DeltaPerformer::OpenKernel(const char* kernel_path) {
143 int err;
144 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
145 if (success)
146 kernel_path_ = kernel_path;
147 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700148}
149
150int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700151 int err = 0;
152 if (close(kernel_fd_) == -1) {
153 err = errno;
154 PLOG(ERROR) << "Unable to close kernel fd:";
155 }
156 if (close(fd_) == -1) {
157 err = errno;
158 PLOG(ERROR) << "Unable to close rootfs fd:";
159 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700160 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800161 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800163 if (!buffer_.empty()) {
164 LOG(ERROR) << "Called Close() while buffer not empty!";
165 if (err >= 0) {
166 err = 1;
167 }
168 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700169 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700170}
171
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700172namespace {
173
174void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
175 string sha256;
176 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
177 info.hash().size(),
178 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800179 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
180 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700181 } else {
182 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
183 }
184}
185
186void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
187 if (manifest.has_old_kernel_info())
188 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
189 if (manifest.has_old_rootfs_info())
190 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
191 if (manifest.has_new_kernel_info())
192 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
193 if (manifest.has_new_rootfs_info())
194 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
195}
196
197} // namespace {}
198
Jay Srinivasanf4318702012-09-24 11:56:24 -0700199uint64_t DeltaPerformer::GetManifestSizeOffset() {
200 // Manifest size is stored right after the magic string and the version.
201 return strlen(kDeltaMagic) + kDeltaVersionSize;
202}
203
204uint64_t DeltaPerformer::GetManifestOffset() {
205 // Actual manifest begins right after the manifest size field.
206 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
207}
208
209
Darin Petkov9574f7e2011-01-13 10:48:12 -0800210DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
211 const std::vector<char>& payload,
212 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700213 uint64_t* metadata_size,
214 ActionExitCode* error) {
215 *error = kActionCodeSuccess;
216
Jay Srinivasanf4318702012-09-24 11:56:24 -0700217 // manifest_offset is the byte offset where the manifest protobuf begins.
218 const uint64_t manifest_offset = GetManifestOffset();
219 if (payload.size() < manifest_offset) {
220 // Don't have enough bytes to even know the manifest size.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800221 return kMetadataParseInsufficientData;
222 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700223
Jay Srinivasanf4318702012-09-24 11:56:24 -0700224 // Validate the magic string.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800225 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
226 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700227 *error = kActionCodeDownloadInvalidMetadataMagicString;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800228 return kMetadataParseError;
229 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700230
231 // TODO(jaysri): Compare the version number and skip unknown manifest
232 // versions. We don't check the version at all today.
233
Jay Srinivasanf4318702012-09-24 11:56:24 -0700234 // Next, parse the manifest size.
235 uint64_t manifest_size;
236 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
237 manifest_size_size_mismatch);
238 memcpy(&manifest_size,
239 &payload[GetManifestSizeOffset()],
240 kDeltaManifestSizeSize);
241 manifest_size = be64toh(manifest_size); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700242
243 // Now, check if the metasize we computed matches what was passed in
244 // through Omaha Response.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700245 *metadata_size = manifest_offset + manifest_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700246
Jay Srinivasanf4318702012-09-24 11:56:24 -0700247 // If the metadata size is present in install plan, check for it immediately
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700248 // even before waiting for that many number of bytes to be downloaded
249 // in the payload. This will prevent any attack which relies on us downloading
Jay Srinivasanf4318702012-09-24 11:56:24 -0700250 // data beyond the expected metadata size.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800251 if (install_plan_->hash_checks_mandatory) {
252 if (install_plan_->metadata_size != *metadata_size) {
253 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
254 << install_plan_->metadata_size << ") is missing/incorrect."
255 << ", Actual = " << *metadata_size;
256 *error = kActionCodeDownloadInvalidMetadataSize;
257 return kMetadataParseError;
258 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700259 }
260
261 // Now that we have validated the metadata size, we should wait for the full
262 // metadata to be read in before we can parse it.
263 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800264 return kMetadataParseInsufficientData;
265 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700266
267 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700268 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700269 // that we just log once (instead of logging n times) if it takes n
270 // DeltaPerformer::Write calls to download the full manifest.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800271 if (install_plan_->metadata_size == *metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700272 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800273 } else {
274 // For mandatory-cases, we'd have already returned a kMetadataParseError
275 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
276 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
277 << install_plan_->metadata_size
278 << ") in Omaha response as validation is not mandatory. "
279 << "Trusting metadata size in payload = " << *metadata_size;
280 SendUmaStat(kActionCodeDownloadInvalidMetadataSize);
281 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700282
Jay Srinivasanf4318702012-09-24 11:56:24 -0700283 // We have the full metadata in |payload|. Verify its integrity
284 // and authenticity based on the information we have in Omaha response.
285 *error = ValidateMetadataSignature(&payload[0], *metadata_size);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700286 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800287 if (install_plan_->hash_checks_mandatory) {
288 LOG(ERROR) << "Mandatory metadata signature validation failed";
289 return kMetadataParseError;
290 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700291
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800292 // For non-mandatory cases, just send a UMA stat.
293 LOG(WARNING) << "Ignoring metadata signature validation failures";
294 SendUmaStat(*error);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700295 *error = kActionCodeSuccess;
296 }
297
Jay Srinivasanf4318702012-09-24 11:56:24 -0700298 // The metadata in |payload| is deemed valid. So, it's now safe to
299 // parse the protobuf.
300 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800301 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700302 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800303 return kMetadataParseError;
304 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800305 return kMetadataParseSuccess;
306}
307
308
Don Garrette410e0f2011-11-10 15:39:01 -0800309// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800310// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700311// and stores an action exit code in |error|.
312bool DeltaPerformer::Write(const void* bytes, size_t count,
313 ActionExitCode *error) {
314 *error = kActionCodeSuccess;
315
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700316 const char* c_bytes = reinterpret_cast<const char*>(bytes);
317 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800318 system_state_->payload_state()->DownloadProgress(count);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700319 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800320 MetadataParseResult result = ParsePayloadMetadata(buffer_,
321 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700322 &manifest_metadata_size_,
323 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800324 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800325 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800326 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800327 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800328 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700329 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700330 // Remove protobuf and header info from buffer_, so buffer_ contains
331 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700332 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700333 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700334 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700335 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700336 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700337
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700338 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700339 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700340 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700341 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800342 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700343 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700344 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700345 ssize_t total_operations = manifest_.install_operations_size() +
346 manifest_.kernel_install_operations_size();
347 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700348 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700349 next_operation_num_ < manifest_.install_operations_size() ?
350 manifest_.install_operations(next_operation_num_) :
351 manifest_.kernel_install_operations(
352 next_operation_num_ - manifest_.install_operations_size());
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700353 if (!CanPerformInstallOperation(op)) {
354 // This means we don't have enough bytes received yet to carry out the
355 // next operation.
356 return true;
357 }
358
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700359 bool should_log = (next_operation_num_ % 1000 == 0 ||
360 next_operation_num_ == total_operations - 1);
361
Jay Srinivasanf4318702012-09-24 11:56:24 -0700362 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700363 // Otherwise, keep the old behavior. This serves as a knob to disable
364 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800365 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
366 // we would have already failed in ParsePayloadMetadata method and thus not
367 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700368 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700369 // Note: Validate must be called only if CanPerformInstallOperation is
370 // called. Otherwise, we might be failing operations before even if there
371 // isn't sufficient data to compute the proper hash.
372 *error = ValidateOperationHash(op, should_log);
373 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800374 if (install_plan_->hash_checks_mandatory) {
375 LOG(ERROR) << "Mandatory operation hash check failed";
376 return false;
377 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700378
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800379 // For non-mandatory cases, just send a UMA stat.
380 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700381 SendUmaStat(*error);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800382 *error = kActionCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700383 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700384 }
385
Darin Petkov45580e42010-10-08 14:02:40 -0700386 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700387 ScopedTerminatorExitUnblocker exit_unblocker =
388 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700389 // Log every thousandth operation, and also the first and last ones
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700390 if (should_log) {
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700391 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
392 << total_operations;
393 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700394 bool is_kernel_partition =
395 (next_operation_num_ >= manifest_.install_operations_size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700396 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
397 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700398 if (!PerformReplaceOperation(op, is_kernel_partition)) {
399 LOG(ERROR) << "Failed to perform replace 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_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700405 if (!PerformMoveOperation(op, is_kernel_partition)) {
406 LOG(ERROR) << "Failed to perform move 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 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700412 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
413 LOG(ERROR) << "Failed to perform bsdiff operation "
414 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700415 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800416 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700417 }
418 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700419 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700420 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700421 }
Don Garrette410e0f2011-11-10 15:39:01 -0800422 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700423}
424
425bool DeltaPerformer::CanPerformInstallOperation(
426 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
427 operation) {
428 // Move operations don't require any data blob, so they can always
429 // be performed
430 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
431 return true;
432
433 // See if we have the entire data blob in the buffer
434 if (operation.data_offset() < buffer_offset_) {
435 LOG(ERROR) << "we threw away data it seems?";
436 return false;
437 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700438
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700439 return (operation.data_offset() + operation.data_length()) <=
440 (buffer_offset_ + buffer_.size());
441}
442
443bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700444 const DeltaArchiveManifest_InstallOperation& operation,
445 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700446 CHECK(operation.type() == \
447 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
448 operation.type() == \
449 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
450
451 // Since we delete data off the beginning of the buffer as we use it,
452 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700453 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
454 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700455
Darin Petkov437adc42010-10-07 13:12:24 -0700456 // Extract the signature message if it's in this operation.
457 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700458
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700459 DirectExtentWriter direct_writer;
460 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
461 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700462
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700463 // Since bzip decompression is optional, we have a variable writer that will
464 // point to one of the ExtentWriter objects above.
465 ExtentWriter* writer = NULL;
466 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
467 writer = &zero_pad_writer;
468 } else if (operation.type() ==
469 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
470 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
471 writer = bzip_writer.get();
472 } else {
473 NOTREACHED();
474 }
475
476 // Create a vector of extents to pass to the ExtentWriter.
477 vector<Extent> extents;
478 for (int i = 0; i < operation.dst_extents_size(); i++) {
479 extents.push_back(operation.dst_extents(i));
480 }
481
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700482 int fd = is_kernel_partition ? kernel_fd_ : fd_;
483
484 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700485 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
486 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700487
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700488 // Update buffer
489 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700490 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700491 return true;
492}
493
494bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700495 const DeltaArchiveManifest_InstallOperation& operation,
496 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700497 // Calculate buffer size. Note, this function doesn't do a sliding
498 // window to copy in case the source and destination blocks overlap.
499 // If we wanted to do a sliding window, we could program the server
500 // to generate deltas that effectively did a sliding window.
501
502 uint64_t blocks_to_read = 0;
503 for (int i = 0; i < operation.src_extents_size(); i++)
504 blocks_to_read += operation.src_extents(i).num_blocks();
505
506 uint64_t blocks_to_write = 0;
507 for (int i = 0; i < operation.dst_extents_size(); i++)
508 blocks_to_write += operation.dst_extents(i).num_blocks();
509
510 DCHECK_EQ(blocks_to_write, blocks_to_read);
511 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700512
513 int fd = is_kernel_partition ? kernel_fd_ : fd_;
514
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700515 // Read in bytes.
516 ssize_t bytes_read = 0;
517 for (int i = 0; i < operation.src_extents_size(); i++) {
518 ssize_t bytes_read_this_iteration = 0;
519 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700520 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700521 &buf[bytes_read],
522 extent.num_blocks() * block_size_,
523 extent.start_block() * block_size_,
524 &bytes_read_this_iteration));
525 TEST_AND_RETURN_FALSE(
526 bytes_read_this_iteration ==
527 static_cast<ssize_t>(extent.num_blocks() * block_size_));
528 bytes_read += bytes_read_this_iteration;
529 }
530
Darin Petkov45580e42010-10-08 14:02:40 -0700531 // If this is a non-idempotent operation, request a delayed exit and clear the
532 // update state in case the operation gets interrupted. Do this as late as
533 // possible.
534 if (!IsIdempotentOperation(operation)) {
535 Terminator::set_exit_blocked(true);
536 ResetUpdateProgress(prefs_, true);
537 }
538
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700539 // Write bytes out.
540 ssize_t bytes_written = 0;
541 for (int i = 0; i < operation.dst_extents_size(); i++) {
542 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700543 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700544 &buf[bytes_written],
545 extent.num_blocks() * block_size_,
546 extent.start_block() * block_size_));
547 bytes_written += extent.num_blocks() * block_size_;
548 }
549 DCHECK_EQ(bytes_written, bytes_read);
550 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
551 return true;
552}
553
554bool DeltaPerformer::ExtentsToBsdiffPositionsString(
555 const RepeatedPtrField<Extent>& extents,
556 uint64_t block_size,
557 uint64_t full_length,
558 string* positions_string) {
559 string ret;
560 uint64_t length = 0;
561 for (int i = 0; i < extents.size(); i++) {
562 Extent extent = extents.Get(i);
563 int64_t start = extent.start_block();
564 uint64_t this_length = min(full_length - length,
565 extent.num_blocks() * block_size);
566 if (start == static_cast<int64_t>(kSparseHole))
567 start = -1;
568 else
569 start *= block_size;
570 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
571 length += this_length;
572 }
573 TEST_AND_RETURN_FALSE(length == full_length);
574 if (!ret.empty())
575 ret.resize(ret.size() - 1); // Strip trailing comma off
576 *positions_string = ret;
577 return true;
578}
579
580bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700581 const DeltaArchiveManifest_InstallOperation& operation,
582 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700583 // Since we delete data off the beginning of the buffer as we use it,
584 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700585 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
586 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700587
588 string input_positions;
589 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
590 block_size_,
591 operation.src_length(),
592 &input_positions));
593 string output_positions;
594 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
595 block_size_,
596 operation.dst_length(),
597 &output_positions));
598
599 string temp_filename;
600 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
601 &temp_filename,
602 NULL));
603 ScopedPathUnlinker path_unlinker(temp_filename);
604 {
605 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
606 ScopedFdCloser fd_closer(&fd);
607 TEST_AND_RETURN_FALSE(
608 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
609 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700610
611 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700612 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700613
Darin Petkov45580e42010-10-08 14:02:40 -0700614 // If this is a non-idempotent operation, request a delayed exit and clear the
615 // update state in case the operation gets interrupted. Do this as late as
616 // possible.
617 if (!IsIdempotentOperation(operation)) {
618 Terminator::set_exit_blocked(true);
619 ResetUpdateProgress(prefs_, true);
620 }
621
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700622 vector<string> cmd;
623 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700624 cmd.push_back(path);
625 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700626 cmd.push_back(temp_filename);
627 cmd.push_back(input_positions);
628 cmd.push_back(output_positions);
629 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700630 TEST_AND_RETURN_FALSE(
631 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700632 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700633 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700634 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700635 TEST_AND_RETURN_FALSE(return_code == 0);
636
637 if (operation.dst_length() % block_size_) {
638 // Zero out rest of final block.
639 // TODO(adlr): build this into bspatch; it's more efficient that way.
640 const Extent& last_extent =
641 operation.dst_extents(operation.dst_extents_size() - 1);
642 const uint64_t end_byte =
643 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
644 const uint64_t begin_byte =
645 end_byte - (block_size_ - operation.dst_length() % block_size_);
646 vector<char> zeros(end_byte - begin_byte);
647 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700648 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700649 }
650
651 // Update buffer.
652 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700653 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654 return true;
655}
656
Darin Petkovd7061ab2010-10-06 14:37:09 -0700657bool DeltaPerformer::ExtractSignatureMessage(
658 const DeltaArchiveManifest_InstallOperation& operation) {
659 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
660 !manifest_.has_signatures_offset() ||
661 manifest_.signatures_offset() != operation.data_offset()) {
662 return false;
663 }
664 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
665 manifest_.signatures_size() == operation.data_length());
666 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
667 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
668 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700669 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700670 buffer_.begin(),
671 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700672
673 // Save the signature blob because if the update is interrupted after the
674 // download phase we don't go through this path anymore. Some alternatives to
675 // consider:
676 //
677 // 1. On resume, re-download the signature blob from the server and re-verify
678 // it.
679 //
680 // 2. Verify the signature as soon as it's received and don't checkpoint the
681 // blob and the signed sha-256 context.
682 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
683 string(&signatures_message_data_[0],
684 signatures_message_data_.size())))
685 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700686 // The hash of all data consumed so far should be verified against the signed
687 // hash.
688 signed_hash_context_ = hash_calculator_.GetContext();
689 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
690 signed_hash_context_))
691 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700692 LOG(INFO) << "Extracted signature data of size "
693 << manifest_.signatures_size() << " at "
694 << manifest_.signatures_offset();
695 return true;
696}
697
Jay Srinivasanf4318702012-09-24 11:56:24 -0700698ActionExitCode DeltaPerformer::ValidateMetadataSignature(
699 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700700
Jay Srinivasanf4318702012-09-24 11:56:24 -0700701 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800702 if (install_plan_->hash_checks_mandatory) {
703 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
704 return kActionCodeDownloadMetadataSignatureMissingError;
705 }
706
707 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700708 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700709 SendUmaStat(kActionCodeDownloadMetadataSignatureMissingError);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700710 return kActionCodeSuccess;
711 }
712
713 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700714 vector<char> metadata_signature;
715 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
716 &metadata_signature)) {
717 LOG(ERROR) << "Unable to decode base64 metadata signature: "
718 << install_plan_->metadata_signature;
719 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700720 }
721
Jay Srinivasanf4318702012-09-24 11:56:24 -0700722 vector<char> expected_metadata_hash;
723 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700724 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700725 &expected_metadata_hash)) {
726 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
727 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700728 }
729
Jay Srinivasanf4318702012-09-24 11:56:24 -0700730 OmahaHashCalculator metadata_hasher;
731 metadata_hasher.Update(metadata, metadata_size);
732 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700733 LOG(ERROR) << "Unable to compute actual hash of manifest";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700734 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700735 }
736
Jay Srinivasanf4318702012-09-24 11:56:24 -0700737 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
738 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
739 if (calculated_metadata_hash.empty()) {
740 LOG(ERROR) << "Computed actual hash of metadata is empty.";
741 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700742 }
743
Jay Srinivasanf4318702012-09-24 11:56:24 -0700744 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700745 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700746 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700747 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700748 utils::HexDumpVector(calculated_metadata_hash);
749 return kActionCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700750 }
751
752 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
753 return kActionCodeSuccess;
754}
755
756ActionExitCode DeltaPerformer::ValidateOperationHash(
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700757 const DeltaArchiveManifest_InstallOperation& operation,
758 bool should_log) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700759
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700760 if (!operation.data_sha256_hash().size()) {
761 if (!operation.data_length()) {
762 // Operations that do not have any data blob won't have any operation hash
763 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700764 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800765 // has already been validated. This is true for both HTTP and HTTPS cases.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700766 return kActionCodeSuccess;
767 }
768
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800769 // No hash is present for an operation that has data blobs. This shouldn't
770 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700771 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800772 // hashes. So if it happens it means either we've turned operation hash
773 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700774 // One caveat though: The last operation is a dummy signature operation
775 // that doesn't have a hash at the time the manifest is created. So we
776 // should not complaint about that operation. This operation can be
777 // recognized by the fact that it's offset is mentioned in the manifest.
778 if (manifest_.signatures_offset() &&
779 manifest_.signatures_offset() == operation.data_offset()) {
780 LOG(INFO) << "Skipping hash verification for signature operation "
781 << next_operation_num_ + 1;
782 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800783 if (install_plan_->hash_checks_mandatory) {
784 LOG(ERROR) << "Missing mandatory operation hash for operation "
785 << next_operation_num_ + 1;
786 return kActionCodeDownloadOperationHashMissingError;
787 }
788
789 // For non-mandatory cases, just send a UMA stat.
790 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
791 << " as there's no operation hash in manifest";
792 SendUmaStat(kActionCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700793 }
794 return kActionCodeSuccess;
795 }
796
797 vector<char> expected_op_hash;
798 expected_op_hash.assign(operation.data_sha256_hash().data(),
799 (operation.data_sha256_hash().data() +
800 operation.data_sha256_hash().size()));
801
802 OmahaHashCalculator operation_hasher;
803 operation_hasher.Update(&buffer_[0], operation.data_length());
804 if (!operation_hasher.Finalize()) {
805 LOG(ERROR) << "Unable to compute actual hash of operation "
806 << next_operation_num_;
807 return kActionCodeDownloadOperationHashVerificationError;
808 }
809
810 vector<char> calculated_op_hash = operation_hasher.raw_hash();
811 if (calculated_op_hash != expected_op_hash) {
812 LOG(ERROR) << "Hash verification failed for operation "
813 << next_operation_num_ << ". Expected hash = ";
814 utils::HexDumpVector(expected_op_hash);
815 LOG(ERROR) << "Calculated hash over " << operation.data_length()
816 << " bytes at offset: " << operation.data_offset() << " = ";
817 utils::HexDumpVector(calculated_op_hash);
818 return kActionCodeDownloadOperationHashMismatch;
819 }
820
821 if (should_log)
822 LOG(INFO) << "Validated operation " << next_operation_num_ + 1;
823
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700824 return kActionCodeSuccess;
825}
826
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700827#define TEST_AND_RETURN_VAL(_retval, _condition) \
828 do { \
829 if (!(_condition)) { \
830 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
831 return _retval; \
832 } \
833 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700834
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700835ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700836 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700837 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700838 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700839
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700840 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700841 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700842 update_check_response_size ==
843 manifest_metadata_size_ + buffer_offset_);
844
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700845 // Verifies the payload hash.
846 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700847 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700848 !payload_hash_data.empty());
849 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
850 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700851
Darin Petkov437adc42010-10-07 13:12:24 -0700852 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700853 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700854 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700855 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700856 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700857 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
858 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700859 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700860 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
861 PayloadSigner::VerifySignature(
862 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700863 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700864 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700865 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700866 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
867 signed_hasher.SetContext(signed_hash_context_));
868 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
869 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700870 vector<char> hash_data = signed_hasher.raw_hash();
871 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700872 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
873 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700874 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700875 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700876 "Attached Signature:";
877 utils::HexDumpVector(signed_hash_data);
878 LOG(ERROR) << "Computed Signature:";
879 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700880 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700881 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800882
883 // At this point, we are guaranteed to have downloaded a full payload, i.e
884 // the one whose size matches the size mentioned in Omaha response. If any
885 // errors happen after this, it's likely a problem with the payload itself or
886 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -0800887 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800888 system_state_->payload_state()->DownloadComplete();
889
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700890 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700891}
892
Darin Petkov3aefa862010-12-07 14:45:00 -0800893bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
894 vector<char>* kernel_hash,
895 uint64_t* rootfs_size,
896 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700897 TEST_AND_RETURN_FALSE(manifest_valid_ &&
898 manifest_.has_new_kernel_info() &&
899 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -0800900 *kernel_size = manifest_.new_kernel_info().size();
901 *rootfs_size = manifest_.new_rootfs_info().size();
902 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
903 manifest_.new_kernel_info().hash().end());
904 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
905 manifest_.new_rootfs_info().hash().end());
906 kernel_hash->swap(new_kernel_hash);
907 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700908 return true;
909}
910
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700911namespace {
912void LogVerifyError(bool is_kern,
913 const string& local_hash,
914 const string& expected_hash) {
915 const char* type = is_kern ? "kernel" : "rootfs";
916 LOG(ERROR) << "This is a server-side error due to "
917 << "mismatched delta update image!";
918 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
919 << "update that must be applied over a " << type << " with "
920 << "a specific checksum, but the " << type << " we're starting "
921 << "with doesn't have that checksum! This means that "
922 << "the delta I've been given doesn't match my existing "
923 << "system. The " << type << " partition I have has hash: "
924 << local_hash << " but the update expected me to have "
925 << expected_hash << " .";
926 if (is_kern) {
927 LOG(INFO) << "To get the checksum of a kernel partition on a "
928 << "booted machine, run this command (change /dev/sda2 "
929 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
930 << "openssl dgst -sha256 -binary | openssl base64";
931 } else {
932 LOG(INFO) << "To get the checksum of a rootfs partition on a "
933 << "booted machine, run this command (change /dev/sda3 "
934 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
935 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
936 << "| sed 's/[^0-9]*//') / 256 )) | "
937 << "openssl dgst -sha256 -binary | openssl base64";
938 }
939 LOG(INFO) << "To get the checksum of partitions in a bin file, "
940 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
941}
942
943string StringForHashBytes(const void* bytes, size_t size) {
944 string ret;
945 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
946 ret = "<unknown>";
947 }
948 return ret;
949}
950} // namespace
951
Darin Petkov698d0412010-10-13 10:59:44 -0700952bool DeltaPerformer::VerifySourcePartitions() {
953 LOG(INFO) << "Verifying source partitions.";
954 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700955 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -0700956 if (manifest_.has_old_kernel_info()) {
957 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700958 bool valid =
959 !install_plan_->kernel_hash.empty() &&
960 install_plan_->kernel_hash.size() == info.hash().size() &&
961 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700962 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700963 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700964 if (!valid) {
965 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700966 StringForHashBytes(install_plan_->kernel_hash.data(),
967 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700968 StringForHashBytes(info.hash().data(),
969 info.hash().size()));
970 }
971 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700972 }
973 if (manifest_.has_old_rootfs_info()) {
974 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700975 bool valid =
976 !install_plan_->rootfs_hash.empty() &&
977 install_plan_->rootfs_hash.size() == info.hash().size() &&
978 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700979 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700980 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700981 if (!valid) {
982 LogVerifyError(false,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700983 StringForHashBytes(install_plan_->kernel_hash.data(),
984 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700985 StringForHashBytes(info.hash().data(),
986 info.hash().size()));
987 }
988 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700989 }
990 return true;
991}
992
Darin Petkov437adc42010-10-07 13:12:24 -0700993void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
994 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700995 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
996}
997
Darin Petkov0406e402010-10-06 21:33:11 -0700998bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
999 string update_check_response_hash) {
1000 int64_t next_operation = kUpdateStateOperationInvalid;
1001 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1002 &next_operation) &&
1003 next_operation != kUpdateStateOperationInvalid &&
1004 next_operation > 0);
1005
1006 string interrupted_hash;
1007 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1008 &interrupted_hash) &&
1009 !interrupted_hash.empty() &&
1010 interrupted_hash == update_check_response_hash);
1011
Darin Petkov61426142010-10-08 11:04:55 -07001012 int64_t resumed_update_failures;
1013 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1014 &resumed_update_failures) ||
1015 resumed_update_failures <= kMaxResumedUpdateFailures);
1016
Darin Petkov0406e402010-10-06 21:33:11 -07001017 // Sanity check the rest.
1018 int64_t next_data_offset = -1;
1019 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1020 &next_data_offset) &&
1021 next_data_offset >= 0);
1022
Darin Petkov437adc42010-10-07 13:12:24 -07001023 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001024 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001025 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1026 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001027
1028 int64_t manifest_metadata_size = 0;
1029 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1030 &manifest_metadata_size) &&
1031 manifest_metadata_size > 0);
1032
1033 return true;
1034}
1035
Darin Petkov9b230572010-10-08 10:20:09 -07001036bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001037 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1038 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001039 if (!quick) {
1040 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1041 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1042 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1043 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001044 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001045 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001046 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001047 }
Darin Petkov73058b42010-10-06 16:32:19 -07001048 return true;
1049}
1050
1051bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001052 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001053 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001054 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001055 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001056 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001057 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001058 hash_calculator_.GetContext()));
1059 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1060 buffer_offset_));
1061 last_updated_buffer_offset_ = buffer_offset_;
1062 }
Darin Petkov73058b42010-10-06 16:32:19 -07001063 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1064 next_operation_num_));
1065 return true;
1066}
1067
Darin Petkov9b230572010-10-08 10:20:09 -07001068bool DeltaPerformer::PrimeUpdateState() {
1069 CHECK(manifest_valid_);
1070 block_size_ = manifest_.block_size();
1071
1072 int64_t next_operation = kUpdateStateOperationInvalid;
1073 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1074 next_operation == kUpdateStateOperationInvalid ||
1075 next_operation <= 0) {
1076 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001077 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001078 return true;
1079 }
1080 next_operation_num_ = next_operation;
1081
1082 // Resuming an update -- load the rest of the update state.
1083 int64_t next_data_offset = -1;
1084 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1085 &next_data_offset) &&
1086 next_data_offset >= 0);
1087 buffer_offset_ = next_data_offset;
1088
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001089 // The signed hash context and the signature blob may be empty if the
1090 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001091 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1092 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001093 string signature_blob;
1094 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1095 signatures_message_data_.assign(signature_blob.begin(),
1096 signature_blob.end());
1097 }
Darin Petkov9b230572010-10-08 10:20:09 -07001098
1099 string hash_context;
1100 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1101 &hash_context) &&
1102 hash_calculator_.SetContext(hash_context));
1103
1104 int64_t manifest_metadata_size = 0;
1105 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1106 &manifest_metadata_size) &&
1107 manifest_metadata_size > 0);
1108 manifest_metadata_size_ = manifest_metadata_size;
1109
Darin Petkov61426142010-10-08 11:04:55 -07001110 // Speculatively count the resume as a failure.
1111 int64_t resumed_update_failures;
1112 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1113 resumed_update_failures++;
1114 } else {
1115 resumed_update_failures = 1;
1116 }
1117 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001118 return true;
1119}
1120
Jay Srinivasanedce2832012-10-24 18:57:47 -07001121void DeltaPerformer::SendUmaStat(ActionExitCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001122 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001123}
1124
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001125} // namespace chromeos_update_engine