blob: 9392af3ed8023566b0847972b9ba60c3fde61850 [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>
Ben Chan02f7c1d2014-10-18 15:18:02 -070012#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070013#include <string>
14#include <vector>
15
Ben Chan06c76a42014-09-05 08:21:06 -070016#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070017#include <base/format_macros.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070018#include <base/strings/string_util.h>
19#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080020#include <chromeos/data_encoding.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070021#include <google/protobuf/repeated_field.h>
22
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070024#include "update_engine/constants.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070025#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include "update_engine/extent_writer.h"
David Zeuthene7f89172013-10-31 10:21:04 -070027#include "update_engine/hardware_interface.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080028#if USE_MTD
29#include "update_engine/mtd_file_descriptor.h"
30#endif
Alex Deymo161c4a12014-05-16 15:56:21 -070031#include "update_engine/payload_constants.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080032#include "update_engine/payload_state_interface.h"
Alex Deymo923d8fa2014-07-15 17:58:51 -070033#include "update_engine/payload_verifier.h"
Darin Petkov73058b42010-10-06 16:32:19 -070034#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070035#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070036#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070037#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070038
Alex Deymo161c4a12014-05-16 15:56:21 -070039using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040using std::min;
41using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070042using std::unique_ptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070043using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070044
45namespace chromeos_update_engine {
46
Jay Srinivasanf4318702012-09-24 11:56:24 -070047const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
48const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Don Garrett4d039442013-10-28 18:40:06 -070049const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 1;
Don Garrettb8dd1d92013-11-22 17:40:02 -080050const uint64_t DeltaPerformer::kSupportedMinorPayloadVersion = 1;
51const uint64_t DeltaPerformer::kFullPayloadMinorVersion = 0;
Don Garrett4d039442013-10-28 18:40:06 -070052
Darin Petkovabc7bc02011-02-23 14:39:43 -080053const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
54 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080055const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
56const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
57const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
58const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080059
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070060namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070061const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070062const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080063
64FileDescriptorPtr CreateFileDescriptor(const char* path) {
65 FileDescriptorPtr ret;
66#if USE_MTD
67 if (UbiFileDescriptor::IsUbi(path)) {
68 ret.reset(new UbiFileDescriptor);
69 } else if (MtdFileDescriptor::IsMtd(path)) {
70 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080071 } else {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080072#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080073 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080074#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070075 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080076#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080077 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070078}
79
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080080// Opens path for read/write. On success returns an open FileDescriptor
81// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
82FileDescriptorPtr OpenFile(const char* path, int* err) {
83 FileDescriptorPtr fd = CreateFileDescriptor(path);
84 // TODO(namnguyen): If we're working with MTD or UBI, DO NOT use O_RDWR.
85 if (!fd->Open(path, O_RDWR, 000)) {
86 *err = errno;
87 PLOG(ERROR) << "Unable to open file " << path;
88 return nullptr;
89 }
90 *err = 0;
91 return fd;
92}
Alex Vakulenkod2779df2014-06-16 13:19:00 -070093} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070094
Gilad Arnold8a86fa52013-01-15 12:35:05 -080095
96// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
97// arithmetic.
98static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
99 return part * norm / total;
100}
101
102void DeltaPerformer::LogProgress(const char* message_prefix) {
103 // Format operations total count and percentage.
104 string total_operations_str("?");
105 string completed_percentage_str("");
106 if (num_total_operations_) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700107 total_operations_str = base::StringPrintf("%zu", num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800108 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
109 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700110 base::StringPrintf(" (%" PRIu64 "%%)",
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800111 IntRatio(next_operation_num_, num_total_operations_,
112 100));
113 }
114
115 // Format download total count and percentage.
116 size_t payload_size = install_plan_->payload_size;
117 string payload_size_str("?");
118 string downloaded_percentage_str("");
119 if (payload_size) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700120 payload_size_str = base::StringPrintf("%zu", payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800121 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
122 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700123 base::StringPrintf(" (%" PRIu64 "%%)",
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800124 IntRatio(total_bytes_received_, payload_size, 100));
125 }
126
127 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
128 << "/" << total_operations_str << " operations"
129 << completed_percentage_str << ", " << total_bytes_received_
130 << "/" << payload_size_str << " bytes downloaded"
131 << downloaded_percentage_str << ", overall progress "
132 << overall_progress_ << "%";
133}
134
135void DeltaPerformer::UpdateOverallProgress(bool force_log,
136 const char* message_prefix) {
137 // Compute our download and overall progress.
138 unsigned new_overall_progress = 0;
139 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
140 progress_weight_dont_add_up);
141 // Only consider download progress if its total size is known; otherwise
142 // adjust the operations weight to compensate for the absence of download
143 // progress. Also, make sure to cap the download portion at
144 // kProgressDownloadWeight, in case we end up downloading more than we
145 // initially expected (this indicates a problem, but could generally happen).
146 // TODO(garnold) the correction of operations weight when we do not have the
147 // total payload size, as well as the conditional guard below, should both be
148 // eliminated once we ensure that the payload_size in the install plan is
149 // always given and is non-zero. This currently isn't the case during unit
150 // tests (see chromium-os:37969).
151 size_t payload_size = install_plan_->payload_size;
152 unsigned actual_operations_weight = kProgressOperationsWeight;
153 if (payload_size)
154 new_overall_progress += min(
155 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
156 kProgressDownloadWeight)),
157 kProgressDownloadWeight);
158 else
159 actual_operations_weight += kProgressDownloadWeight;
160
161 // Only add completed operations if their total number is known; we definitely
162 // expect an update to have at least one operation, so the expectation is that
163 // this will eventually reach |actual_operations_weight|.
164 if (num_total_operations_)
165 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
166 actual_operations_weight);
167
168 // Progress ratio cannot recede, unless our assumptions about the total
169 // payload size, total number of operations, or the monotonicity of progress
170 // is breached.
171 if (new_overall_progress < overall_progress_) {
172 LOG(WARNING) << "progress counter receded from " << overall_progress_
173 << "% down to " << new_overall_progress << "%; this is a bug";
174 force_log = true;
175 }
176 overall_progress_ = new_overall_progress;
177
178 // Update chunk index, log as needed: if forced by called, or we completed a
179 // progress chunk, or a timeout has expired.
180 base::Time curr_time = base::Time::Now();
181 unsigned curr_progress_chunk =
182 overall_progress_ * kProgressLogMaxChunks / 100;
183 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
184 curr_time > forced_progress_log_time_) {
185 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
186 LogProgress(message_prefix);
187 }
188 last_progress_chunk_ = curr_progress_chunk;
189}
190
191
Gilad Arnoldfe133932014-01-14 12:25:50 -0800192size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
193 size_t max) {
194 const size_t count = *count_p;
195 if (!count)
196 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700197 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800198 const char* bytes_start = *bytes_p;
199 const char* bytes_end = bytes_start + read_len;
200 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
201 *bytes_p = bytes_end;
202 *count_p = count - read_len;
203 return read_len;
204}
205
206
207bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
208 ErrorCode* error) {
209 if (op_result)
210 return true;
211
212 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
213 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700214 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800215 return false;
216}
217
218
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700219// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
220// it safely. Returns false otherwise.
221bool DeltaPerformer::IsIdempotentOperation(
222 const DeltaArchiveManifest_InstallOperation& op) {
223 if (op.src_extents_size() == 0) {
224 return true;
225 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700226 // When in doubt, it's safe to declare an op non-idempotent. Note that we
227 // could detect other types of idempotent operations here such as a MOVE that
228 // moves blocks onto themselves. However, we rely on the server to not send
229 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700230 ExtentRanges src_ranges;
231 src_ranges.AddRepeatedExtents(op.src_extents());
232 const uint64_t block_count = src_ranges.blocks();
233 src_ranges.SubtractRepeatedExtents(op.dst_extents());
234 return block_count == src_ranges.blocks();
235}
236
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700237int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700238 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800239 fd_ = OpenFile(path, &err);
240 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700241 path_ = path;
242 return -err;
243}
244
245bool DeltaPerformer::OpenKernel(const char* kernel_path) {
246 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800247 kernel_fd_ = OpenFile(kernel_path, &err);
248 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700249 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800250 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700251}
252
253int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700254 int err = 0;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800255 if (!kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700256 err = errno;
257 PLOG(ERROR) << "Unable to close kernel fd:";
258 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800259 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700260 err = errno;
261 PLOG(ERROR) << "Unable to close rootfs fd:";
262 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700263 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800264 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700265 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800266 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700267 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
268 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800269 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800270 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700271 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700272}
273
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700274namespace {
275
276void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800277 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800278 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
279 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700280}
281
282void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
283 if (manifest.has_old_kernel_info())
284 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
285 if (manifest.has_old_rootfs_info())
286 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
287 if (manifest.has_new_kernel_info())
288 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
289 if (manifest.has_new_rootfs_info())
290 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
291}
292
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700293} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700294
Don Garrett4d039442013-10-28 18:40:06 -0700295uint64_t DeltaPerformer::GetVersionOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800296 // Manifest size is stored right after the magic string and the version.
297 return strlen(kDeltaMagic);
Don Garrett4d039442013-10-28 18:40:06 -0700298}
299
Jay Srinivasanf4318702012-09-24 11:56:24 -0700300uint64_t DeltaPerformer::GetManifestSizeOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800301 // Manifest size is stored right after the magic string and the version.
302 return strlen(kDeltaMagic) + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700303}
304
305uint64_t DeltaPerformer::GetManifestOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800306 // Actual manifest begins right after the manifest size field.
307 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700308}
309
Gilad Arnoldfe133932014-01-14 12:25:50 -0800310uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800311 return metadata_size_;
312}
313
314bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
315 if (!manifest_parsed_)
316 return false;
317 *out_manifest_p = manifest_;
318 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800319}
320
Jay Srinivasanf4318702012-09-24 11:56:24 -0700321
Darin Petkov9574f7e2011-01-13 10:48:12 -0800322DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800323 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700324 *error = ErrorCode::kSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700325 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800326 uint64_t manifest_size = (metadata_size_ ?
327 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700328
Gilad Arnoldfe133932014-01-14 12:25:50 -0800329 if (!manifest_size) {
330 // Ensure we have data to cover the payload header.
331 if (payload.size() < manifest_offset)
332 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700333
Gilad Arnoldfe133932014-01-14 12:25:50 -0800334 // Validate the magic string.
335 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
336 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700337 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800338 return kMetadataParseError;
339 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800340
341 // Extract the payload version from the metadata.
342 uint64_t major_payload_version;
343 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
344 major_payload_version_size_mismatch);
345 memcpy(&major_payload_version,
346 &payload[GetVersionOffset()],
347 kDeltaVersionSize);
348 // switch big endian to host
349 major_payload_version = be64toh(major_payload_version);
350
351 if (major_payload_version != kSupportedMajorPayloadVersion) {
352 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
353 << major_payload_version;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700354 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800355 return kMetadataParseError;
356 }
357
358 // Next, parse the manifest size.
359 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
360 manifest_size_size_mismatch);
361 memcpy(&manifest_size,
362 &payload[GetManifestSizeOffset()],
363 kDeltaManifestSizeSize);
364 manifest_size = be64toh(manifest_size); // switch big endian to host
365
366 // If the metadata size is present in install plan, check for it immediately
367 // even before waiting for that many number of bytes to be downloaded in the
368 // payload. This will prevent any attack which relies on us downloading data
369 // beyond the expected metadata size.
370 metadata_size_ = manifest_offset + manifest_size;
371 if (install_plan_->hash_checks_mandatory) {
372 if (install_plan_->metadata_size != metadata_size_) {
373 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
374 << install_plan_->metadata_size
375 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700376 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800377 return kMetadataParseError;
378 }
379 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700380 }
381
382 // Now that we have validated the metadata size, we should wait for the full
383 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800384 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800385 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700386
387 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700388 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700389 // that we just log once (instead of logging n times) if it takes n
390 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800391 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700392 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800393 } else {
394 // For mandatory-cases, we'd have already returned a kMetadataParseError
395 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
396 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
397 << install_plan_->metadata_size
398 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800399 << "Trusting metadata size in payload = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700400 SendUmaStat(ErrorCode::kDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800401 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700402
Jay Srinivasanf4318702012-09-24 11:56:24 -0700403 // We have the full metadata in |payload|. Verify its integrity
404 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800405 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700406 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800407 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800408 // The autoupdate_CatchBadSignatures test checks for this string
409 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800410 LOG(ERROR) << "Mandatory metadata signature validation failed";
411 return kMetadataParseError;
412 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700413
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800414 // For non-mandatory cases, just send a UMA stat.
415 LOG(WARNING) << "Ignoring metadata signature validation failures";
416 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700417 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700418 }
419
Gilad Arnolddaa27402014-01-23 11:56:17 -0800420 // The payload metadata is deemed valid, it's safe to parse the protobuf.
421 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800422 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700423 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800424 return kMetadataParseError;
425 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800426
427 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800428 return kMetadataParseSuccess;
429}
430
431
Don Garrette410e0f2011-11-10 15:39:01 -0800432// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800433// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700434// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800435bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700436 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700437
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700438 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800439 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800440
441 // Update the total byte downloaded count and the progress logs.
442 total_bytes_received_ += count;
443 UpdateOverallProgress(false, "Completed ");
444
Gilad Arnoldfe133932014-01-14 12:25:50 -0800445 while (!manifest_valid_) {
446 // Read data up to the needed limit; this is either the payload header size,
447 // or the full metadata size (once it becomes known).
448 const bool do_read_header = !metadata_size_;
449 CopyDataToBuffer(&c_bytes, &count,
450 (do_read_header ? GetManifestOffset() :
451 metadata_size_));
452
Gilad Arnolddaa27402014-01-23 11:56:17 -0800453 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700454 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800455 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800456 if (result == kMetadataParseInsufficientData) {
457 // If we just processed the header, make an attempt on the manifest.
458 if (do_read_header && metadata_size_)
459 continue;
460
Don Garrette410e0f2011-11-10 15:39:01 -0800461 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800462 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700463
464 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700465 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700466 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800467 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700468
Gilad Arnoldfe133932014-01-14 12:25:50 -0800469 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800470 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700471 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800472 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700473 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700474
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700475 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700476 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700477 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700478 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800479 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700480 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800481
482 num_rootfs_operations_ = manifest_.install_operations_size();
483 num_total_operations_ =
484 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
485 if (next_operation_num_ > 0)
486 UpdateOverallProgress(true, "Resuming after ");
487 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700488 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800489
490 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700491 // Check if we should cancel the current attempt for any reason.
492 // In this case, *error will have already been populated with the reason
493 // why we're cancelling.
494 if (system_state_->update_attempter()->ShouldCancel(error))
495 return false;
496
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800497 const bool is_kernel_partition =
498 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700499 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800500 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700501 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800502 next_operation_num_ - num_rootfs_operations_) :
503 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800504
505 CopyDataToBuffer(&c_bytes, &count, op.data_length());
506
507 // Check whether we received all of the next operation's data payload.
508 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700509 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700510
Jay Srinivasanf4318702012-09-24 11:56:24 -0700511 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700512 // Otherwise, keep the old behavior. This serves as a knob to disable
513 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800514 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
515 // we would have already failed in ParsePayloadMetadata method and thus not
516 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700517 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700518 // Note: Validate must be called only if CanPerformInstallOperation is
519 // called. Otherwise, we might be failing operations before even if there
520 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800521 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700522 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800523 if (install_plan_->hash_checks_mandatory) {
524 LOG(ERROR) << "Mandatory operation hash check failed";
525 return false;
526 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700527
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800528 // For non-mandatory cases, just send a UMA stat.
529 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700530 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700531 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700532 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700533 }
534
Darin Petkov45580e42010-10-08 14:02:40 -0700535 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700536 ScopedTerminatorExitUnblocker exit_unblocker =
537 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800538
539 bool op_result;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700540 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
Gilad Arnoldfe133932014-01-14 12:25:50 -0800541 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ)
542 op_result = HandleOpResult(
543 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
544 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
545 op_result = HandleOpResult(
546 PerformMoveOperation(op, is_kernel_partition), "move", error);
547 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF)
548 op_result = HandleOpResult(
549 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
550 else
551 op_result = HandleOpResult(false, "unknown", error);
552
553 if (!op_result)
554 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800555
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700556 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800557 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700558 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700559 }
Don Garrette410e0f2011-11-10 15:39:01 -0800560 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700561}
562
David Zeuthen8f191b22013-08-06 12:27:50 -0700563bool DeltaPerformer::IsManifestValid() {
564 return manifest_valid_;
565}
566
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700567bool DeltaPerformer::CanPerformInstallOperation(
568 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
569 operation) {
570 // Move operations don't require any data blob, so they can always
571 // be performed
572 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
573 return true;
574
575 // See if we have the entire data blob in the buffer
576 if (operation.data_offset() < buffer_offset_) {
577 LOG(ERROR) << "we threw away data it seems?";
578 return false;
579 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700580
Gilad Arnoldfe133932014-01-14 12:25:50 -0800581 return (operation.data_offset() + operation.data_length() <=
582 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700583}
584
585bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700586 const DeltaArchiveManifest_InstallOperation& operation,
587 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700588 CHECK(operation.type() == \
589 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
590 operation.type() == \
591 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
592
593 // Since we delete data off the beginning of the buffer as we use it,
594 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700595 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
596 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700597
Darin Petkov437adc42010-10-07 13:12:24 -0700598 // Extract the signature message if it's in this operation.
599 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700600
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700601 DirectExtentWriter direct_writer;
602 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700603 unique_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700604
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700605 // Since bzip decompression is optional, we have a variable writer that will
606 // point to one of the ExtentWriter objects above.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700607 ExtentWriter* writer = nullptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700608 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
609 writer = &zero_pad_writer;
610 } else if (operation.type() ==
611 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
612 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
613 writer = bzip_writer.get();
614 } else {
615 NOTREACHED();
616 }
617
618 // Create a vector of extents to pass to the ExtentWriter.
619 vector<Extent> extents;
620 for (int i = 0; i < operation.dst_extents_size(); i++) {
621 extents.push_back(operation.dst_extents(i));
622 }
623
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800624 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700625
626 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800627 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700628 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700629
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700630 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800631 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700632 return true;
633}
634
635bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700636 const DeltaArchiveManifest_InstallOperation& operation,
637 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700638 // Calculate buffer size. Note, this function doesn't do a sliding
639 // window to copy in case the source and destination blocks overlap.
640 // If we wanted to do a sliding window, we could program the server
641 // to generate deltas that effectively did a sliding window.
642
643 uint64_t blocks_to_read = 0;
644 for (int i = 0; i < operation.src_extents_size(); i++)
645 blocks_to_read += operation.src_extents(i).num_blocks();
646
647 uint64_t blocks_to_write = 0;
648 for (int i = 0; i < operation.dst_extents_size(); i++)
649 blocks_to_write += operation.dst_extents(i).num_blocks();
650
651 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800652 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700653
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800654 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700655
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700656 // Read in bytes.
657 ssize_t bytes_read = 0;
658 for (int i = 0; i < operation.src_extents_size(); i++) {
659 ssize_t bytes_read_this_iteration = 0;
660 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200661 const size_t bytes = extent.num_blocks() * block_size_;
662 if (extent.start_block() == kSparseHole) {
663 bytes_read_this_iteration = bytes;
664 memset(&buf[bytes_read], 0, bytes);
665 } else {
666 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
667 &buf[bytes_read],
668 bytes,
669 extent.start_block() * block_size_,
670 &bytes_read_this_iteration));
671 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700672 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200673 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700674 bytes_read += bytes_read_this_iteration;
675 }
676
Darin Petkov45580e42010-10-08 14:02:40 -0700677 // If this is a non-idempotent operation, request a delayed exit and clear the
678 // update state in case the operation gets interrupted. Do this as late as
679 // possible.
680 if (!IsIdempotentOperation(operation)) {
681 Terminator::set_exit_blocked(true);
682 ResetUpdateProgress(prefs_, true);
683 }
684
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700685 // Write bytes out.
686 ssize_t bytes_written = 0;
687 for (int i = 0; i < operation.dst_extents_size(); i++) {
688 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200689 const size_t bytes = extent.num_blocks() * block_size_;
690 if (extent.start_block() == kSparseHole) {
Darin Petkov741a8222013-05-02 10:02:34 +0200691 DCHECK(buf.begin() + bytes_written ==
692 std::search_n(buf.begin() + bytes_written,
693 buf.begin() + bytes_written + bytes,
694 bytes, 0));
Darin Petkov8a075a72013-04-25 14:46:09 +0200695 } else {
696 TEST_AND_RETURN_FALSE(
697 utils::PWriteAll(fd,
698 &buf[bytes_written],
699 bytes,
700 extent.start_block() * block_size_));
701 }
702 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700703 }
704 DCHECK_EQ(bytes_written, bytes_read);
705 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
706 return true;
707}
708
709bool DeltaPerformer::ExtentsToBsdiffPositionsString(
710 const RepeatedPtrField<Extent>& extents,
711 uint64_t block_size,
712 uint64_t full_length,
713 string* positions_string) {
714 string ret;
715 uint64_t length = 0;
716 for (int i = 0; i < extents.size(); i++) {
717 Extent extent = extents.Get(i);
718 int64_t start = extent.start_block();
719 uint64_t this_length = min(full_length - length,
720 extent.num_blocks() * block_size);
721 if (start == static_cast<int64_t>(kSparseHole))
722 start = -1;
723 else
724 start *= block_size;
Alex Vakulenko75039d72014-03-25 12:36:28 -0700725 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700726 length += this_length;
727 }
728 TEST_AND_RETURN_FALSE(length == full_length);
729 if (!ret.empty())
730 ret.resize(ret.size() - 1); // Strip trailing comma off
731 *positions_string = ret;
732 return true;
733}
734
735bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700736 const DeltaArchiveManifest_InstallOperation& operation,
737 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700738 // Since we delete data off the beginning of the buffer as we use it,
739 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700740 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
741 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700742
743 string input_positions;
744 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
745 block_size_,
746 operation.src_length(),
747 &input_positions));
748 string output_positions;
749 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
750 block_size_,
751 operation.dst_length(),
752 &output_positions));
753
754 string temp_filename;
755 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
756 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700757 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700758 ScopedPathUnlinker path_unlinker(temp_filename);
759 {
760 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
761 ScopedFdCloser fd_closer(&fd);
762 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800763 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700764 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700765
Darin Petkov7f2ec752013-04-03 14:45:19 +0200766 // Update the buffer to release the patch data memory as soon as the patch
767 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800768 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200769
Darin Petkov45580e42010-10-08 14:02:40 -0700770 // If this is a non-idempotent operation, request a delayed exit and clear the
771 // update state in case the operation gets interrupted. Do this as late as
772 // possible.
773 if (!IsIdempotentOperation(operation)) {
774 Terminator::set_exit_blocked(true);
775 ResetUpdateProgress(prefs_, true);
776 }
777
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700778 vector<string> cmd;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800779 const string& path = is_kernel_partition ? kernel_path_ : path_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700780 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700781 cmd.push_back(path);
782 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700783 cmd.push_back(temp_filename);
784 cmd.push_back(input_positions);
785 cmd.push_back(output_positions);
786 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700787 TEST_AND_RETURN_FALSE(
788 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700789 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700790 &return_code,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700791 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700792 TEST_AND_RETURN_FALSE(return_code == 0);
793
794 if (operation.dst_length() % block_size_) {
795 // Zero out rest of final block.
796 // TODO(adlr): build this into bspatch; it's more efficient that way.
797 const Extent& last_extent =
798 operation.dst_extents(operation.dst_extents_size() - 1);
799 const uint64_t end_byte =
800 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
801 const uint64_t begin_byte =
802 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800803 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800804 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700805 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800806 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700807 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700808 return true;
809}
810
Darin Petkovd7061ab2010-10-06 14:37:09 -0700811bool DeltaPerformer::ExtractSignatureMessage(
812 const DeltaArchiveManifest_InstallOperation& operation) {
813 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
814 !manifest_.has_signatures_offset() ||
815 manifest_.signatures_offset() != operation.data_offset()) {
816 return false;
817 }
818 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
819 manifest_.signatures_size() == operation.data_length());
820 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
821 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
822 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700823 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700824 buffer_.begin(),
825 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700826
827 // Save the signature blob because if the update is interrupted after the
828 // download phase we don't go through this path anymore. Some alternatives to
829 // consider:
830 //
831 // 1. On resume, re-download the signature blob from the server and re-verify
832 // it.
833 //
834 // 2. Verify the signature as soon as it's received and don't checkpoint the
835 // blob and the signed sha-256 context.
836 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800837 string(signatures_message_data_.begin(),
838 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700839 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700840 // The hash of all data consumed so far should be verified against the signed
841 // hash.
842 signed_hash_context_ = hash_calculator_.GetContext();
843 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
844 signed_hash_context_))
845 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700846 LOG(INFO) << "Extracted signature data of size "
847 << manifest_.signatures_size() << " at "
848 << manifest_.signatures_offset();
849 return true;
850}
851
David Zeuthene7f89172013-10-31 10:21:04 -0700852bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
853 if (system_state_->hardware()->IsOfficialBuild() ||
854 utils::FileExists(public_key_path_.c_str()) ||
855 install_plan_->public_key_rsa.empty())
856 return false;
857
858 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
859 out_tmp_key))
860 return false;
861
862 return true;
863}
864
David Zeuthena99981f2013-04-29 13:42:47 -0700865ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800866 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700867
Jay Srinivasanf4318702012-09-24 11:56:24 -0700868 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800869 if (install_plan_->hash_checks_mandatory) {
870 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700871 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800872 }
873
874 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700875 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700876 SendUmaStat(ErrorCode::kDownloadMetadataSignatureMissingError);
877 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700878 }
879
880 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800881 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800882 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800883 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -0700884 LOG(ERROR) << "Unable to decode base64 metadata signature: "
885 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700886 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700887 }
888
David Zeuthene7f89172013-10-31 10:21:04 -0700889 // See if we should use the public RSA key in the Omaha response.
890 base::FilePath path_to_public_key(public_key_path_);
891 base::FilePath tmp_key;
892 if (GetPublicKeyFromResponse(&tmp_key))
893 path_to_public_key = tmp_key;
894 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
895 if (tmp_key.empty())
896 tmp_key_remover.set_should_remove(false);
897
898 LOG(INFO) << "Verifying metadata hash signature using public key: "
899 << path_to_public_key.value();
900
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800901 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -0700902 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
903 path_to_public_key.value(),
904 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -0700905 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700906 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700907 }
908
Jay Srinivasanf4318702012-09-24 11:56:24 -0700909 OmahaHashCalculator metadata_hasher;
910 metadata_hasher.Update(metadata, metadata_size);
911 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700912 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700913 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700914 }
915
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800916 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -0700917 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -0700918 if (calculated_metadata_hash.empty()) {
919 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700920 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700921 }
922
Jay Srinivasanf4318702012-09-24 11:56:24 -0700923 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700924 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700925 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700926 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700927 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700928 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700929 }
930
David Zeuthenbc27aac2013-11-26 11:17:48 -0800931 // The autoupdate_CatchBadSignatures test checks for this string in
932 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -0700933 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700934 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700935}
936
Gilad Arnold21504f02013-05-24 08:51:22 -0700937ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -0800938 // Perform assorted checks to sanity check the manifest, make sure it
939 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -0700940 //
941 // TODO(garnold) in general, the presence of an old partition hash should be
942 // the sole indicator for a delta update, as we would generally like update
943 // payloads to be self contained and not assume an Omaha response to tell us
944 // that. However, since this requires some massive reengineering of the update
945 // flow (making filesystem copying happen conditionally only *after*
946 // downloading and parsing of the update manifest) we'll put it off for now.
947 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -0800948 if (install_plan_->is_full_update) {
949 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
950 LOG(ERROR) << "Purported full payload contains old partition "
951 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700952 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -0800953 }
954
955 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
956 LOG(ERROR) << "Manifest contains minor version "
957 << manifest_.minor_version()
958 << ", but all full payloads should have version "
959 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700960 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -0800961 }
962 } else {
963 if (manifest_.minor_version() != kSupportedMinorPayloadVersion) {
964 LOG(ERROR) << "Manifest contains minor version "
965 << manifest_.minor_version()
966 << " not the supported "
967 << kSupportedMinorPayloadVersion;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700968 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -0800969 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700970 }
971
972 // TODO(garnold) we should be adding more and more manifest checks, such as
973 // partition boundaries etc (see chromium-os:37661).
974
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700975 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -0700976}
977
David Zeuthena99981f2013-04-29 13:42:47 -0700978ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800979 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700980
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700981 if (!operation.data_sha256_hash().size()) {
982 if (!operation.data_length()) {
983 // Operations that do not have any data blob won't have any operation hash
984 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700985 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800986 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700987 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700988 }
989
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800990 // No hash is present for an operation that has data blobs. This shouldn't
991 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700992 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800993 // hashes. So if it happens it means either we've turned operation hash
994 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700995 // One caveat though: The last operation is a dummy signature operation
996 // that doesn't have a hash at the time the manifest is created. So we
997 // should not complaint about that operation. This operation can be
998 // recognized by the fact that it's offset is mentioned in the manifest.
999 if (manifest_.signatures_offset() &&
1000 manifest_.signatures_offset() == operation.data_offset()) {
1001 LOG(INFO) << "Skipping hash verification for signature operation "
1002 << next_operation_num_ + 1;
1003 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001004 if (install_plan_->hash_checks_mandatory) {
1005 LOG(ERROR) << "Missing mandatory operation hash for operation "
1006 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001007 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001008 }
1009
1010 // For non-mandatory cases, just send a UMA stat.
1011 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1012 << " as there's no operation hash in manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001013 SendUmaStat(ErrorCode::kDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001014 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001015 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001016 }
1017
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001018 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001019 expected_op_hash.assign(operation.data_sha256_hash().data(),
1020 (operation.data_sha256_hash().data() +
1021 operation.data_sha256_hash().size()));
1022
1023 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001024 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001025 if (!operation_hasher.Finalize()) {
1026 LOG(ERROR) << "Unable to compute actual hash of operation "
1027 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001028 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001029 }
1030
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001031 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001032 if (calculated_op_hash != expected_op_hash) {
1033 LOG(ERROR) << "Hash verification failed for operation "
1034 << next_operation_num_ << ". Expected hash = ";
1035 utils::HexDumpVector(expected_op_hash);
1036 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1037 << " bytes at offset: " << operation.data_offset() << " = ";
1038 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001039 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001040 }
1041
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001042 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001043}
1044
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001045#define TEST_AND_RETURN_VAL(_retval, _condition) \
1046 do { \
1047 if (!(_condition)) { \
1048 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1049 return _retval; \
1050 } \
1051 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001052
David Zeuthena99981f2013-04-29 13:42:47 -07001053ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001054 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001055 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001056
1057 // See if we should use the public RSA key in the Omaha response.
1058 base::FilePath path_to_public_key(public_key_path_);
1059 base::FilePath tmp_key;
1060 if (GetPublicKeyFromResponse(&tmp_key))
1061 path_to_public_key = tmp_key;
1062 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1063 if (tmp_key.empty())
1064 tmp_key_remover.set_should_remove(false);
1065
1066 LOG(INFO) << "Verifying payload using public key: "
1067 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001068
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001069 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001070 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001071 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001072 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001073
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001074 // Verifies the payload hash.
1075 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001076 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001077 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001078 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001079 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001080
Darin Petkov437adc42010-10-07 13:12:24 -07001081 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001082 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001083 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001084 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001085 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001086 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001087 !signatures_message_data_.empty());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001088 chromeos::Blob signed_hash_data;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001089 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Alex Deymo923d8fa2014-07-15 17:58:51 -07001090 PayloadVerifier::VerifySignature(
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001091 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001092 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001093 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001094 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001095 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001096 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001097 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001098 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001099 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001100 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001101 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001102 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001103 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001104 // The autoupdate_CatchBadSignatures test checks for this string
1105 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001106 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001107 "Attached Signature:";
1108 utils::HexDumpVector(signed_hash_data);
1109 LOG(ERROR) << "Computed Signature:";
1110 utils::HexDumpVector(hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001111 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001112 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001113
David Zeuthene7f89172013-10-31 10:21:04 -07001114 LOG(INFO) << "Payload hash matches value in payload.";
1115
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001116 // At this point, we are guaranteed to have downloaded a full payload, i.e
1117 // the one whose size matches the size mentioned in Omaha response. If any
1118 // errors happen after this, it's likely a problem with the payload itself or
1119 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001120 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001121 system_state_->payload_state()->DownloadComplete();
1122
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001123 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001124}
1125
Darin Petkov3aefa862010-12-07 14:45:00 -08001126bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001127 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001128 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001129 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001130 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1131 manifest_.has_new_kernel_info() &&
1132 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001133 *kernel_size = manifest_.new_kernel_info().size();
1134 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001135 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1136 manifest_.new_kernel_info().hash().end());
1137 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1138 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001139 kernel_hash->swap(new_kernel_hash);
1140 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001141 return true;
1142}
1143
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001144namespace {
1145void LogVerifyError(bool is_kern,
1146 const string& local_hash,
1147 const string& expected_hash) {
1148 const char* type = is_kern ? "kernel" : "rootfs";
1149 LOG(ERROR) << "This is a server-side error due to "
1150 << "mismatched delta update image!";
1151 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1152 << "update that must be applied over a " << type << " with "
1153 << "a specific checksum, but the " << type << " we're starting "
1154 << "with doesn't have that checksum! This means that "
1155 << "the delta I've been given doesn't match my existing "
1156 << "system. The " << type << " partition I have has hash: "
1157 << local_hash << " but the update expected me to have "
1158 << expected_hash << " .";
1159 if (is_kern) {
1160 LOG(INFO) << "To get the checksum of a kernel partition on a "
1161 << "booted machine, run this command (change /dev/sda2 "
1162 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1163 << "openssl dgst -sha256 -binary | openssl base64";
1164 } else {
1165 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1166 << "booted machine, run this command (change /dev/sda3 "
1167 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1168 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1169 << "| sed 's/[^0-9]*//') / 256 )) | "
1170 << "openssl dgst -sha256 -binary | openssl base64";
1171 }
1172 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1173 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1174}
1175
1176string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001177 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001178}
1179} // namespace
1180
Darin Petkov698d0412010-10-13 10:59:44 -07001181bool DeltaPerformer::VerifySourcePartitions() {
1182 LOG(INFO) << "Verifying source partitions.";
1183 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001184 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001185 if (manifest_.has_old_kernel_info()) {
1186 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001187 bool valid =
1188 !install_plan_->kernel_hash.empty() &&
1189 install_plan_->kernel_hash.size() == info.hash().size() &&
1190 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001191 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001192 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001193 if (!valid) {
1194 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001195 StringForHashBytes(install_plan_->kernel_hash.data(),
1196 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001197 StringForHashBytes(info.hash().data(),
1198 info.hash().size()));
1199 }
1200 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001201 }
1202 if (manifest_.has_old_rootfs_info()) {
1203 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001204 bool valid =
1205 !install_plan_->rootfs_hash.empty() &&
1206 install_plan_->rootfs_hash.size() == info.hash().size() &&
1207 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001208 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001209 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001210 if (!valid) {
1211 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001212 StringForHashBytes(install_plan_->rootfs_hash.data(),
1213 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001214 StringForHashBytes(info.hash().data(),
1215 info.hash().size()));
1216 }
1217 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001218 }
1219 return true;
1220}
1221
Gilad Arnolddaa27402014-01-23 11:56:17 -08001222void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001223 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001224 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001225 buffer_offset_ += buffer_.size();
1226
1227 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001228 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001229
1230 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001231 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001232}
1233
Darin Petkov0406e402010-10-06 21:33:11 -07001234bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1235 string update_check_response_hash) {
1236 int64_t next_operation = kUpdateStateOperationInvalid;
1237 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1238 &next_operation) &&
1239 next_operation != kUpdateStateOperationInvalid &&
1240 next_operation > 0);
1241
1242 string interrupted_hash;
1243 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1244 &interrupted_hash) &&
David Zeuthenc41c2282013-06-17 16:33:06 -07001245 !interrupted_hash.empty() &&
1246 interrupted_hash == update_check_response_hash);
Darin Petkov0406e402010-10-06 21:33:11 -07001247
Darin Petkov61426142010-10-08 11:04:55 -07001248 int64_t resumed_update_failures;
1249 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1250 &resumed_update_failures) ||
1251 resumed_update_failures <= kMaxResumedUpdateFailures);
1252
Darin Petkov0406e402010-10-06 21:33:11 -07001253 // Sanity check the rest.
1254 int64_t next_data_offset = -1;
1255 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1256 &next_data_offset) &&
1257 next_data_offset >= 0);
1258
Darin Petkov437adc42010-10-07 13:12:24 -07001259 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001260 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001261 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1262 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001263
1264 int64_t manifest_metadata_size = 0;
1265 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1266 &manifest_metadata_size) &&
1267 manifest_metadata_size > 0);
1268
1269 return true;
1270}
1271
Darin Petkov9b230572010-10-08 10:20:09 -07001272bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001273 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1274 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001275 if (!quick) {
1276 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1277 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001278 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001279 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1280 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001281 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001282 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001283 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001284 }
Darin Petkov73058b42010-10-06 16:32:19 -07001285 return true;
1286}
1287
1288bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001289 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001290 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001291 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001292 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001293 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001294 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001295 hash_calculator_.GetContext()));
1296 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1297 buffer_offset_));
1298 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001299
1300 if (next_operation_num_ < num_total_operations_) {
1301 const bool is_kernel_partition =
1302 next_operation_num_ >= num_rootfs_operations_;
1303 const DeltaArchiveManifest_InstallOperation &op =
1304 is_kernel_partition ?
1305 manifest_.kernel_install_operations(
1306 next_operation_num_ - num_rootfs_operations_) :
1307 manifest_.install_operations(next_operation_num_);
1308 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1309 op.data_length()));
1310 } else {
1311 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1312 0));
1313 }
Darin Petkov0406e402010-10-06 21:33:11 -07001314 }
Darin Petkov73058b42010-10-06 16:32:19 -07001315 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1316 next_operation_num_));
1317 return true;
1318}
1319
Darin Petkov9b230572010-10-08 10:20:09 -07001320bool DeltaPerformer::PrimeUpdateState() {
1321 CHECK(manifest_valid_);
1322 block_size_ = manifest_.block_size();
1323
1324 int64_t next_operation = kUpdateStateOperationInvalid;
1325 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1326 next_operation == kUpdateStateOperationInvalid ||
1327 next_operation <= 0) {
1328 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001329 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001330 return true;
1331 }
1332 next_operation_num_ = next_operation;
1333
1334 // Resuming an update -- load the rest of the update state.
1335 int64_t next_data_offset = -1;
1336 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1337 &next_data_offset) &&
1338 next_data_offset >= 0);
1339 buffer_offset_ = next_data_offset;
1340
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001341 // The signed hash context and the signature blob may be empty if the
1342 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001343 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1344 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001345 string signature_blob;
1346 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1347 signatures_message_data_.assign(signature_blob.begin(),
1348 signature_blob.end());
1349 }
Darin Petkov9b230572010-10-08 10:20:09 -07001350
1351 string hash_context;
1352 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1353 &hash_context) &&
1354 hash_calculator_.SetContext(hash_context));
1355
1356 int64_t manifest_metadata_size = 0;
1357 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1358 &manifest_metadata_size) &&
1359 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001360 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001361
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001362 // Advance the download progress to reflect what doesn't need to be
1363 // re-downloaded.
1364 total_bytes_received_ += buffer_offset_;
1365
Darin Petkov61426142010-10-08 11:04:55 -07001366 // Speculatively count the resume as a failure.
1367 int64_t resumed_update_failures;
1368 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1369 resumed_update_failures++;
1370 } else {
1371 resumed_update_failures = 1;
1372 }
1373 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001374 return true;
1375}
1376
David Zeuthena99981f2013-04-29 13:42:47 -07001377void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001378 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001379}
1380
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001381} // namespace chromeos_update_engine