blob: 687f9033cbc0b355ba69d4a6ed75c1f7350cec1f [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/payload_consumer/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070018
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019#include <endian.h>
20#include <errno.h>
Alex Deymo79715ad2015-10-02 14:27:53 -070021#include <linux/fs.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070022
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include <algorithm>
24#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070025#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include <string>
27#include <vector>
28
Sen Jiangbc3e6b02016-01-19 18:39:26 +080029#include <applypatch/imgpatch.h>
Ben Chan06c76a42014-09-05 08:21:06 -070030#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070031#include <base/format_macros.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070032#include <base/strings/string_util.h>
33#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070034#include <brillo/data_encoding.h>
35#include <brillo/make_unique_ptr.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070036#include <google/protobuf/repeated_field.h>
37
Alex Deymo39910dc2015-11-09 17:04:30 -080038#include "update_engine/common/constants.h"
39#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030040#include "update_engine/common/prefs_interface.h"
41#include "update_engine/common/subprocess.h"
42#include "update_engine/common/terminator.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080043#include "update_engine/payload_consumer/bzip_extent_writer.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030044#include "update_engine/payload_consumer/download_action.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080045#include "update_engine/payload_consumer/extent_writer.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080046#if USE_MTD
Alex Deymo39910dc2015-11-09 17:04:30 -080047#include "update_engine/payload_consumer/mtd_file_descriptor.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080048#endif
Alex Deymo39910dc2015-11-09 17:04:30 -080049#include "update_engine/payload_consumer/payload_constants.h"
50#include "update_engine/payload_consumer/payload_verifier.h"
51#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070052
Alex Deymo161c4a12014-05-16 15:56:21 -070053using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070054using std::min;
55using std::string;
56using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070057
58namespace chromeos_update_engine {
59
Sen Jiangb8060e42015-09-24 17:30:50 -070060const uint64_t DeltaPerformer::kDeltaVersionOffset = sizeof(kDeltaMagic);
Jay Srinivasanf4318702012-09-24 11:56:24 -070061const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070062const uint64_t DeltaPerformer::kDeltaManifestSizeOffset =
63 kDeltaVersionOffset + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -070064const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070065const uint64_t DeltaPerformer::kDeltaMetadataSignatureSizeSize = 4;
66const uint64_t DeltaPerformer::kMaxPayloadHeaderSize = 24;
Alex Deymo7a2c47e2015-11-04 00:47:12 -080067const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 2;
Sen Jiang889c65d2015-11-17 15:04:02 -080068const uint32_t DeltaPerformer::kSupportedMinorPayloadVersion = 3;
Don Garrett4d039442013-10-28 18:40:06 -070069
Gilad Arnold8a86fa52013-01-15 12:35:05 -080070const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
71const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
72const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
73const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080074
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070075namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070076const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070077const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080078#if USE_MTD
79const int kUbiVolumeAttachTimeout = 5 * 60;
80#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080081
82FileDescriptorPtr CreateFileDescriptor(const char* path) {
83 FileDescriptorPtr ret;
84#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080085 if (strstr(path, "/dev/ubi") == path) {
86 if (!UbiFileDescriptor::IsUbi(path)) {
87 // The volume might not have been attached at boot time.
88 int volume_no;
89 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
90 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
91 }
92 }
93 if (UbiFileDescriptor::IsUbi(path)) {
94 LOG(INFO) << path << " is a UBI device.";
95 ret.reset(new UbiFileDescriptor);
96 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080097 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080098 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080099 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800100 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800101 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800102#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800103 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800104#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700105 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800106#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800107 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700108}
109
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800110// Opens path for read/write. On success returns an open FileDescriptor
111// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700112FileDescriptorPtr OpenFile(const char* path, int mode, int* err) {
Alex Deymo5fb356c2016-03-25 18:48:22 -0700113 // Try to mark the block device read-only based on the mode. Ignore any
114 // failure since this won't work when passing regular files.
115 utils::SetBlockDeviceReadOnly(path, (mode & O_ACCMODE) == O_RDONLY);
116
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800117 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800118#if USE_MTD
119 // On NAND devices, we can either read, or write, but not both. So here we
120 // use O_WRONLY.
121 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
122 mode = O_WRONLY;
123 }
124#endif
125 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800126 *err = errno;
127 PLOG(ERROR) << "Unable to open file " << path;
128 return nullptr;
129 }
130 *err = 0;
131 return fd;
132}
Alex Deymob86787c2016-05-12 18:46:25 -0700133
134// Discard the tail of the block device referenced by |fd|, from the offset
135// |data_size| until the end of the block device. Returns whether the data was
136// discarded.
137bool DiscardPartitionTail(FileDescriptorPtr fd, uint64_t data_size) {
138 uint64_t part_size = fd->BlockDevSize();
139 if (!part_size || part_size <= data_size)
140 return false;
141
142 const vector<int> requests = {
143 BLKSECDISCARD,
144 BLKDISCARD,
145#ifdef BLKZEROOUT
146 BLKZEROOUT,
147#endif
148 };
149 for (int request : requests) {
150 int error = 0;
151 if (fd->BlkIoctl(request, data_size, part_size - data_size, &error) &&
152 error == 0) {
153 return true;
154 }
155 LOG(WARNING) << "Error discarding the last "
156 << (part_size - data_size) / 1024 << " KiB using ioctl("
157 << request << ")";
158 }
159 return false;
160}
161
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700162} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700163
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800164
165// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
166// arithmetic.
167static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
168 return part * norm / total;
169}
170
171void DeltaPerformer::LogProgress(const char* message_prefix) {
172 // Format operations total count and percentage.
173 string total_operations_str("?");
174 string completed_percentage_str("");
175 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700176 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800177 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
178 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700179 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700180 IntRatio(next_operation_num_, num_total_operations_,
181 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800182 }
183
184 // Format download total count and percentage.
185 size_t payload_size = install_plan_->payload_size;
186 string payload_size_str("?");
187 string downloaded_percentage_str("");
188 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700189 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800190 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
191 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700192 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700193 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800194 }
195
196 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
197 << "/" << total_operations_str << " operations"
198 << completed_percentage_str << ", " << total_bytes_received_
199 << "/" << payload_size_str << " bytes downloaded"
200 << downloaded_percentage_str << ", overall progress "
201 << overall_progress_ << "%";
202}
203
204void DeltaPerformer::UpdateOverallProgress(bool force_log,
205 const char* message_prefix) {
206 // Compute our download and overall progress.
207 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800208 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
209 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800210 // Only consider download progress if its total size is known; otherwise
211 // adjust the operations weight to compensate for the absence of download
212 // progress. Also, make sure to cap the download portion at
213 // kProgressDownloadWeight, in case we end up downloading more than we
214 // initially expected (this indicates a problem, but could generally happen).
215 // TODO(garnold) the correction of operations weight when we do not have the
216 // total payload size, as well as the conditional guard below, should both be
217 // eliminated once we ensure that the payload_size in the install plan is
218 // always given and is non-zero. This currently isn't the case during unit
219 // tests (see chromium-os:37969).
220 size_t payload_size = install_plan_->payload_size;
221 unsigned actual_operations_weight = kProgressOperationsWeight;
222 if (payload_size)
223 new_overall_progress += min(
224 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
225 kProgressDownloadWeight)),
226 kProgressDownloadWeight);
227 else
228 actual_operations_weight += kProgressDownloadWeight;
229
230 // Only add completed operations if their total number is known; we definitely
231 // expect an update to have at least one operation, so the expectation is that
232 // this will eventually reach |actual_operations_weight|.
233 if (num_total_operations_)
234 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
235 actual_operations_weight);
236
237 // Progress ratio cannot recede, unless our assumptions about the total
238 // payload size, total number of operations, or the monotonicity of progress
239 // is breached.
240 if (new_overall_progress < overall_progress_) {
241 LOG(WARNING) << "progress counter receded from " << overall_progress_
242 << "% down to " << new_overall_progress << "%; this is a bug";
243 force_log = true;
244 }
245 overall_progress_ = new_overall_progress;
246
247 // Update chunk index, log as needed: if forced by called, or we completed a
248 // progress chunk, or a timeout has expired.
249 base::Time curr_time = base::Time::Now();
250 unsigned curr_progress_chunk =
251 overall_progress_ * kProgressLogMaxChunks / 100;
252 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
253 curr_time > forced_progress_log_time_) {
254 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
255 LogProgress(message_prefix);
256 }
257 last_progress_chunk_ = curr_progress_chunk;
258}
259
260
Gilad Arnoldfe133932014-01-14 12:25:50 -0800261size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
262 size_t max) {
263 const size_t count = *count_p;
264 if (!count)
265 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700266 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800267 const char* bytes_start = *bytes_p;
268 const char* bytes_end = bytes_start + read_len;
269 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
270 *bytes_p = bytes_end;
271 *count_p = count - read_len;
272 return read_len;
273}
274
275
276bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
277 ErrorCode* error) {
278 if (op_result)
279 return true;
280
Alex Deymo3d009062016-05-13 15:51:25 -0700281 size_t partition_first_op_num =
282 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800283 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700284 << next_operation_num_ << ", which is the operation "
285 << next_operation_num_ - partition_first_op_num
286 << " in partition \""
287 << partitions_[current_partition_].partition_name() << "\"";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700288 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800289 return false;
290}
291
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700292int DeltaPerformer::Close() {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700293 int err = -CloseCurrentPartition();
Sen Jiangf6813802015-11-03 21:27:29 -0800294 LOG_IF(ERROR, !payload_hash_calculator_.Finalize() ||
295 !signed_hash_calculator_.Finalize())
296 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800297 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700298 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
299 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800300 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800301 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700302 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700303}
304
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700305int DeltaPerformer::CloseCurrentPartition() {
306 int err = 0;
307 if (source_fd_ && !source_fd_->Close()) {
308 err = errno;
309 PLOG(ERROR) << "Error closing source partition";
310 if (!err)
311 err = 1;
312 }
313 source_fd_.reset();
314 source_path_.clear();
315
316 if (target_fd_ && !target_fd_->Close()) {
317 err = errno;
318 PLOG(ERROR) << "Error closing target partition";
319 if (!err)
320 err = 1;
321 }
322 target_fd_.reset();
323 target_path_.clear();
324 return -err;
325}
326
327bool DeltaPerformer::OpenCurrentPartition() {
328 if (current_partition_ >= partitions_.size())
329 return false;
330
331 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiang889c65d2015-11-17 15:04:02 -0800332 // Open source fds if we have a delta payload with minor version >= 2.
Alex Deymo64d98782016-02-05 18:03:48 -0800333 if (install_plan_->payload_type == InstallPayloadType::kDelta &&
Sen Jiang889c65d2015-11-17 15:04:02 -0800334 GetMinorVersion() != kInPlaceMinorPayloadVersion) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700335 source_path_ = install_plan_->partitions[current_partition_].source_path;
336 int err;
337 source_fd_ = OpenFile(source_path_.c_str(), O_RDONLY, &err);
338 if (!source_fd_) {
339 LOG(ERROR) << "Unable to open source partition "
340 << partition.partition_name() << " on slot "
341 << BootControlInterface::SlotName(install_plan_->source_slot)
342 << ", file " << source_path_;
343 return false;
344 }
345 }
346
347 target_path_ = install_plan_->partitions[current_partition_].target_path;
348 int err;
349 target_fd_ = OpenFile(target_path_.c_str(), O_RDWR, &err);
350 if (!target_fd_) {
351 LOG(ERROR) << "Unable to open target partition "
352 << partition.partition_name() << " on slot "
353 << BootControlInterface::SlotName(install_plan_->target_slot)
354 << ", file " << target_path_;
355 return false;
356 }
Alex Deymob86787c2016-05-12 18:46:25 -0700357
358 LOG(INFO) << "Applying " << partition.operations().size()
359 << " operations to partition \"" << partition.partition_name()
360 << "\"";
361
362 // Discard the end of the partition, but ignore failures.
363 DiscardPartitionTail(
364 target_fd_, install_plan_->partitions[current_partition_].target_size);
365
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700366 return true;
367}
368
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700369namespace {
370
371void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700372 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800373 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
374 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700375}
376
Alex Deymo39910dc2015-11-09 17:04:30 -0800377void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700378 for (const PartitionUpdate& partition : partitions) {
379 LogPartitionInfoHash(partition.old_partition_info(),
380 "old " + partition.partition_name());
381 LogPartitionInfoHash(partition.new_partition_info(),
382 "new " + partition.partition_name());
383 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700384}
385
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700386} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700387
Sen Jiangb8060e42015-09-24 17:30:50 -0700388bool DeltaPerformer::GetMetadataSignatureSizeOffset(
389 uint64_t* out_offset) const {
390 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
391 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
392 return true;
393 }
394 return false;
Don Garrett4d039442013-10-28 18:40:06 -0700395}
396
Sen Jiangb8060e42015-09-24 17:30:50 -0700397bool DeltaPerformer::GetManifestOffset(uint64_t* out_offset) const {
398 // Actual manifest begins right after the manifest size field or
399 // metadata signature size field if major version >= 2.
400 if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
401 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
402 return true;
403 }
404 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
405 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize +
406 kDeltaMetadataSignatureSizeSize;
407 return true;
408 }
409 LOG(ERROR) << "Unknown major payload version: " << major_payload_version_;
410 return false;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700411}
412
Gilad Arnoldfe133932014-01-14 12:25:50 -0800413uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800414 return metadata_size_;
415}
416
Sen Jiangb8060e42015-09-24 17:30:50 -0700417uint64_t DeltaPerformer::GetMajorVersion() const {
418 return major_payload_version_;
419}
420
Allie Woodfdf00512015-03-02 13:34:55 -0800421uint32_t DeltaPerformer::GetMinorVersion() const {
422 if (manifest_.has_minor_version()) {
423 return manifest_.minor_version();
424 } else {
Alex Deymo64d98782016-02-05 18:03:48 -0800425 return install_plan_->payload_type == InstallPayloadType::kDelta
426 ? kSupportedMinorPayloadVersion
427 : kFullPayloadMinorVersion;
Allie Woodfdf00512015-03-02 13:34:55 -0800428 }
429}
430
Gilad Arnolddaa27402014-01-23 11:56:17 -0800431bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
432 if (!manifest_parsed_)
433 return false;
434 *out_manifest_p = manifest_;
435 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800436}
437
Sen Jiangb8060e42015-09-24 17:30:50 -0700438bool DeltaPerformer::IsHeaderParsed() const {
439 return metadata_size_ != 0;
440}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700441
Darin Petkov9574f7e2011-01-13 10:48:12 -0800442DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700443 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700444 *error = ErrorCode::kSuccess;
Sen Jiangb8060e42015-09-24 17:30:50 -0700445 uint64_t manifest_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700446
Sen Jiangb8060e42015-09-24 17:30:50 -0700447 if (!IsHeaderParsed()) {
448 // Ensure we have data to cover the major payload version.
449 if (payload.size() < kDeltaManifestSizeOffset)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800450 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700451
Gilad Arnoldfe133932014-01-14 12:25:50 -0800452 // Validate the magic string.
Sen Jiangb8060e42015-09-24 17:30:50 -0700453 if (memcmp(payload.data(), kDeltaMagic, sizeof(kDeltaMagic)) != 0) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800454 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700455 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800456 return kMetadataParseError;
457 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800458
459 // Extract the payload version from the metadata.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800460 static_assert(sizeof(major_payload_version_) == kDeltaVersionSize,
461 "Major payload version size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700462 memcpy(&major_payload_version_,
463 &payload[kDeltaVersionOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800464 kDeltaVersionSize);
465 // switch big endian to host
Sen Jiangb8060e42015-09-24 17:30:50 -0700466 major_payload_version_ = be64toh(major_payload_version_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800467
Alex Deymo7a2c47e2015-11-04 00:47:12 -0800468 if (major_payload_version_ != supported_major_version_ &&
469 major_payload_version_ != kChromeOSMajorPayloadVersion) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800470 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
Sen Jiangb8060e42015-09-24 17:30:50 -0700471 << major_payload_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700472 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800473 return kMetadataParseError;
474 }
475
Sen Jiangb8060e42015-09-24 17:30:50 -0700476 // Get the manifest offset now that we have payload version.
477 if (!GetManifestOffset(&manifest_offset)) {
478 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
479 return kMetadataParseError;
480 }
481 // Check again with the manifest offset.
482 if (payload.size() < manifest_offset)
483 return kMetadataParseInsufficientData;
484
Gilad Arnoldfe133932014-01-14 12:25:50 -0800485 // Next, parse the manifest size.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800486 static_assert(sizeof(manifest_size_) == kDeltaManifestSizeSize,
487 "manifest_size size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700488 memcpy(&manifest_size_,
489 &payload[kDeltaManifestSizeOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800490 kDeltaManifestSizeSize);
Sen Jiangb8060e42015-09-24 17:30:50 -0700491 manifest_size_ = be64toh(manifest_size_); // switch big endian to host
492
Sen Jiangb8060e42015-09-24 17:30:50 -0700493 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
494 // Parse the metadata signature size.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800495 static_assert(sizeof(metadata_signature_size_) ==
496 kDeltaMetadataSignatureSizeSize,
497 "metadata_signature_size size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700498 uint64_t metadata_signature_size_offset;
499 if (!GetMetadataSignatureSizeOffset(&metadata_signature_size_offset)) {
500 *error = ErrorCode::kError;
501 return kMetadataParseError;
502 }
Sen Jiang76bfa742015-10-12 17:13:26 -0700503 memcpy(&metadata_signature_size_,
Sen Jiangb8060e42015-09-24 17:30:50 -0700504 &payload[metadata_signature_size_offset],
505 kDeltaMetadataSignatureSizeSize);
Sen Jiang76bfa742015-10-12 17:13:26 -0700506 metadata_signature_size_ = be32toh(metadata_signature_size_);
Sen Jiangb8060e42015-09-24 17:30:50 -0700507 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800508
509 // If the metadata size is present in install plan, check for it immediately
510 // even before waiting for that many number of bytes to be downloaded in the
511 // payload. This will prevent any attack which relies on us downloading data
512 // beyond the expected metadata size.
Sen Jiang76bfa742015-10-12 17:13:26 -0700513 metadata_size_ = manifest_offset + manifest_size_;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800514 if (install_plan_->hash_checks_mandatory) {
515 if (install_plan_->metadata_size != metadata_size_) {
516 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
517 << install_plan_->metadata_size
518 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700519 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800520 return kMetadataParseError;
521 }
522 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700523 }
524
525 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700526 // metadata and its signature (if exist) to be read in before we can parse it.
527 if (payload.size() < metadata_size_ + metadata_signature_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800528 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700529
530 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700531 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700532 // that we just log once (instead of logging n times) if it takes n
533 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800534 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700535 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800536 } else {
537 // For mandatory-cases, we'd have already returned a kMetadataParseError
538 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
539 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
540 << install_plan_->metadata_size
541 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800542 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800543 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700544
Jay Srinivasanf4318702012-09-24 11:56:24 -0700545 // We have the full metadata in |payload|. Verify its integrity
546 // and authenticity based on the information we have in Omaha response.
Sen Jiang76bfa742015-10-12 17:13:26 -0700547 *error = ValidateMetadataSignature(payload);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700548 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800549 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800550 // The autoupdate_CatchBadSignatures test checks for this string
551 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800552 LOG(ERROR) << "Mandatory metadata signature validation failed";
553 return kMetadataParseError;
554 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700555
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800556 // For non-mandatory cases, just send a UMA stat.
557 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700558 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700559 }
560
Sen Jiangb8060e42015-09-24 17:30:50 -0700561 if (!GetManifestOffset(&manifest_offset)) {
562 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
563 return kMetadataParseError;
564 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800565 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiangb8060e42015-09-24 17:30:50 -0700566 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800567 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700568 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800569 return kMetadataParseError;
570 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800571
572 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800573 return kMetadataParseSuccess;
574}
575
Don Garrette410e0f2011-11-10 15:39:01 -0800576// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800577// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700578// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800579bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700580 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700581
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700582 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800583
584 // Update the total byte downloaded count and the progress logs.
585 total_bytes_received_ += count;
586 UpdateOverallProgress(false, "Completed ");
587
Gilad Arnoldfe133932014-01-14 12:25:50 -0800588 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700589 // Read data up to the needed limit; this is either maximium payload header
590 // size, or the full metadata size (once it becomes known).
591 const bool do_read_header = !IsHeaderParsed();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800592 CopyDataToBuffer(&c_bytes, &count,
Sen Jiangb8060e42015-09-24 17:30:50 -0700593 (do_read_header ? kMaxPayloadHeaderSize :
Sen Jiang76bfa742015-10-12 17:13:26 -0700594 metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800595
Gilad Arnolddaa27402014-01-23 11:56:17 -0800596 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700597 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800598 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800599 if (result == kMetadataParseInsufficientData) {
600 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700601 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800602 continue;
603
Don Garrette410e0f2011-11-10 15:39:01 -0800604 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800605 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700606
607 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700608 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700609 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800610 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700611
Gilad Arnoldfe133932014-01-14 12:25:50 -0800612 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800613 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700614
615 // This populates |partitions_| and the |install_plan.partitions| with the
616 // list of partitions from the manifest.
617 if (!ParseManifestPartitions(error))
618 return false;
619
620 num_total_operations_ = 0;
621 for (const auto& partition : partitions_) {
622 num_total_operations_ += partition.operations_size();
623 acc_num_operations_.push_back(num_total_operations_);
624 }
625
Darin Petkov73058b42010-10-06 16:32:19 -0700626 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800627 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700628 << "Unable to save the manifest metadata size.";
Alex Deymof25eb492016-02-26 00:20:08 -0800629 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestSignatureSize,
630 metadata_signature_size_))
631 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700632
Darin Petkov9b230572010-10-08 10:20:09 -0700633 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700634 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700635 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800636 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700637 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800638
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700639 if (!OpenCurrentPartition()) {
640 *error = ErrorCode::kInstallDeviceOpenError;
641 return false;
Allie Woodfdf00512015-03-02 13:34:55 -0800642 }
643
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800644 if (next_operation_num_ > 0)
645 UpdateOverallProgress(true, "Resuming after ");
646 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700647 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800648
649 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700650 // Check if we should cancel the current attempt for any reason.
651 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700652 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300653 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700654 return false;
655
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700656 // We know there are more operations to perform because we didn't reach the
657 // |num_total_operations_| limit yet.
658 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
659 CloseCurrentPartition();
660 current_partition_++;
661 if (!OpenCurrentPartition()) {
662 *error = ErrorCode::kInstallDeviceOpenError;
663 return false;
664 }
665 }
666 const size_t partition_operation_num = next_operation_num_ - (
667 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
668
Alex Deymoa12ee112015-08-12 22:19:32 -0700669 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700670 partitions_[current_partition_].operations(partition_operation_num);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800671
672 CopyDataToBuffer(&c_bytes, &count, op.data_length());
673
674 // Check whether we received all of the next operation's data payload.
675 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700676 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700677
Jay Srinivasanf4318702012-09-24 11:56:24 -0700678 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700679 // Otherwise, keep the old behavior. This serves as a knob to disable
680 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800681 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
682 // we would have already failed in ParsePayloadMetadata method and thus not
683 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700684 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700685 // Note: Validate must be called only if CanPerformInstallOperation is
686 // called. Otherwise, we might be failing operations before even if there
687 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800688 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700689 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800690 if (install_plan_->hash_checks_mandatory) {
691 LOG(ERROR) << "Mandatory operation hash check failed";
692 return false;
693 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700694
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800695 // For non-mandatory cases, just send a UMA stat.
696 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700697 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700698 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700699 }
700
Darin Petkov45580e42010-10-08 14:02:40 -0700701 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700702 ScopedTerminatorExitUnblocker exit_unblocker =
703 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800704
705 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700706 switch (op.type()) {
707 case InstallOperation::REPLACE:
708 case InstallOperation::REPLACE_BZ:
709 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700710 op_result = PerformReplaceOperation(op);
Alex Deymo2d621a32015-10-01 11:09:01 -0700711 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700712 case InstallOperation::ZERO:
713 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700714 op_result = PerformZeroOrDiscardOperation(op);
Alex Deymo79715ad2015-10-02 14:27:53 -0700715 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700716 case InstallOperation::MOVE:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700717 op_result = PerformMoveOperation(op);
Alex Deymo2d621a32015-10-01 11:09:01 -0700718 break;
719 case InstallOperation::BSDIFF:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700720 op_result = PerformBsdiffOperation(op);
Alex Deymo2d621a32015-10-01 11:09:01 -0700721 break;
722 case InstallOperation::SOURCE_COPY:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700723 op_result = PerformSourceCopyOperation(op);
Alex Deymo2d621a32015-10-01 11:09:01 -0700724 break;
725 case InstallOperation::SOURCE_BSDIFF:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700726 op_result = PerformSourceBsdiffOperation(op);
Alex Deymo2d621a32015-10-01 11:09:01 -0700727 break;
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800728 case InstallOperation::IMGDIFF:
729 op_result = PerformImgdiffOperation(op);
730 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700731 default:
732 op_result = false;
733 }
734 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800735 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800736
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700737 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800738 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700739 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700740 }
Sen Jiangf6813802015-11-03 21:27:29 -0800741
742 // In major version 2, we don't add dummy operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800743 // If we already extracted the signature we should skip this step.
Sen Jiangf6813802015-11-03 21:27:29 -0800744 if (major_payload_version_ == kBrilloMajorPayloadVersion &&
Alex Deymof25eb492016-02-26 00:20:08 -0800745 manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
746 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800747 if (manifest_.signatures_offset() != buffer_offset_) {
748 LOG(ERROR) << "Payload signatures offset points to blob offset "
749 << manifest_.signatures_offset()
750 << " but signatures are expected at offset "
751 << buffer_offset_;
752 *error = ErrorCode::kDownloadPayloadVerificationError;
753 return false;
754 }
755 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
756 // Needs more data to cover entire signature.
757 if (buffer_.size() < manifest_.signatures_size())
758 return true;
759 if (!ExtractSignatureMessage()) {
760 LOG(ERROR) << "Extract payload signature failed.";
761 *error = ErrorCode::kDownloadPayloadVerificationError;
762 return false;
763 }
764 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800765 // Since we extracted the SignatureMessage we need to advance the
766 // checkpoint, otherwise we would reload the signature and try to extract
767 // it again.
768 CheckpointUpdateProgress();
Sen Jiangf6813802015-11-03 21:27:29 -0800769 }
770
Don Garrette410e0f2011-11-10 15:39:01 -0800771 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700772}
773
David Zeuthen8f191b22013-08-06 12:27:50 -0700774bool DeltaPerformer::IsManifestValid() {
775 return manifest_valid_;
776}
777
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700778bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
779 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
780 partitions_.clear();
781 for (const PartitionUpdate& partition : manifest_.partitions()) {
782 partitions_.push_back(partition);
783 }
784 manifest_.clear_partitions();
785 } else if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
786 LOG(INFO) << "Converting update information from old format.";
787 PartitionUpdate root_part;
788 root_part.set_partition_name(kLegacyPartitionNameRoot);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700789#ifdef __ANDROID__
790 LOG(WARNING) << "Legacy payload major version provided to an Android "
791 "build. Assuming no post-install. Please use major version "
792 "2 or newer.";
793 root_part.set_run_postinstall(false);
794#else
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700795 root_part.set_run_postinstall(true);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700796#endif // __ANDROID__
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700797 if (manifest_.has_old_rootfs_info()) {
798 *root_part.mutable_old_partition_info() = manifest_.old_rootfs_info();
799 manifest_.clear_old_rootfs_info();
800 }
801 if (manifest_.has_new_rootfs_info()) {
802 *root_part.mutable_new_partition_info() = manifest_.new_rootfs_info();
803 manifest_.clear_new_rootfs_info();
804 }
805 *root_part.mutable_operations() = manifest_.install_operations();
806 manifest_.clear_install_operations();
807 partitions_.push_back(std::move(root_part));
808
809 PartitionUpdate kern_part;
810 kern_part.set_partition_name(kLegacyPartitionNameKernel);
811 kern_part.set_run_postinstall(false);
812 if (manifest_.has_old_kernel_info()) {
813 *kern_part.mutable_old_partition_info() = manifest_.old_kernel_info();
814 manifest_.clear_old_kernel_info();
815 }
816 if (manifest_.has_new_kernel_info()) {
817 *kern_part.mutable_new_partition_info() = manifest_.new_kernel_info();
818 manifest_.clear_new_kernel_info();
819 }
820 *kern_part.mutable_operations() = manifest_.kernel_install_operations();
821 manifest_.clear_kernel_install_operations();
822 partitions_.push_back(std::move(kern_part));
823 }
824
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700825 // Fill in the InstallPlan::partitions based on the partitions from the
826 // payload.
827 install_plan_->partitions.clear();
828 for (const auto& partition : partitions_) {
829 InstallPlan::Partition install_part;
830 install_part.name = partition.partition_name();
831 install_part.run_postinstall =
832 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800833 if (install_part.run_postinstall) {
834 install_part.postinstall_path =
835 (partition.has_postinstall_path() ? partition.postinstall_path()
836 : kPostinstallDefaultScript);
837 install_part.filesystem_type = partition.filesystem_type();
838 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700839
840 if (partition.has_old_partition_info()) {
841 const PartitionInfo& info = partition.old_partition_info();
842 install_part.source_size = info.size();
843 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
844 }
845
846 if (!partition.has_new_partition_info()) {
847 LOG(ERROR) << "Unable to get new partition hash info on partition "
848 << install_part.name << ".";
849 *error = ErrorCode::kDownloadNewPartitionInfoError;
850 return false;
851 }
852 const PartitionInfo& info = partition.new_partition_info();
853 install_part.target_size = info.size();
854 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
855
856 install_plan_->partitions.push_back(install_part);
857 }
858
Alex Deymo542c19b2015-12-03 07:43:31 -0300859 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700860 LOG(ERROR) << "Unable to determine all the partition devices.";
861 *error = ErrorCode::kInstallDeviceOpenError;
862 return false;
863 }
864 LogPartitionInfo(partitions_);
865 return true;
866}
867
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700868bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700869 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700870 // If we don't have a data blob we can apply it right away.
871 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700872 return true;
873
874 // See if we have the entire data blob in the buffer
875 if (operation.data_offset() < buffer_offset_) {
876 LOG(ERROR) << "we threw away data it seems?";
877 return false;
878 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700879
Gilad Arnoldfe133932014-01-14 12:25:50 -0800880 return (operation.data_offset() + operation.data_length() <=
881 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700882}
883
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700884bool DeltaPerformer::PerformReplaceOperation(
885 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700886 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700887 operation.type() == InstallOperation::REPLACE_BZ ||
888 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700889
890 // Since we delete data off the beginning of the buffer as we use it,
891 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700892 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
893 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700894
Darin Petkov437adc42010-10-07 13:12:24 -0700895 // Extract the signature message if it's in this operation.
Sen Jiangf6813802015-11-03 21:27:29 -0800896 if (ExtractSignatureMessageFromOperation(operation)) {
897 // If this is dummy replace operation, we ignore it after extracting the
898 // signature.
899 DiscardBuffer(true, 0);
900 return true;
901 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700902
Alex Deymo05322872015-09-30 09:50:24 -0700903 // Setup the ExtentWriter stack based on the operation type.
904 std::unique_ptr<ExtentWriter> writer =
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700905 brillo::make_unique_ptr(new ZeroPadExtentWriter(
906 brillo::make_unique_ptr(new DirectExtentWriter())));
Darin Petkovd7061ab2010-10-06 14:37:09 -0700907
Alex Deymo2d621a32015-10-01 11:09:01 -0700908 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -0700909 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -0700910 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
911 writer.reset(new XzExtentWriter(std::move(writer)));
912 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700913
914 // Create a vector of extents to pass to the ExtentWriter.
915 vector<Extent> extents;
916 for (int i = 0; i < operation.dst_extents_size(); i++) {
917 extents.push_back(operation.dst_extents(i));
918 }
919
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700920 TEST_AND_RETURN_FALSE(writer->Init(target_fd_, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800921 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700922 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700923
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700924 // Update buffer
Sen Jiangf6813802015-11-03 21:27:29 -0800925 DiscardBuffer(true, buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700926 return true;
927}
928
Alex Deymo79715ad2015-10-02 14:27:53 -0700929bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700930 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700931 CHECK(operation.type() == InstallOperation::DISCARD ||
932 operation.type() == InstallOperation::ZERO);
933
934 // These operations have no blob.
935 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
936 TEST_AND_RETURN_FALSE(!operation.has_data_length());
937
Alex Deymo05e0e382015-12-07 20:18:16 -0800938#ifdef BLKZEROOUT
939 bool attempt_ioctl = true;
Alex Deymo79715ad2015-10-02 14:27:53 -0700940 int request =
941 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
Alex Deymo05e0e382015-12-07 20:18:16 -0800942#else // !defined(BLKZEROOUT)
943 bool attempt_ioctl = false;
944 int request = 0;
945#endif // !defined(BLKZEROOUT)
Alex Deymo79715ad2015-10-02 14:27:53 -0700946
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700947 brillo::Blob zeros;
Alex Deymo79715ad2015-10-02 14:27:53 -0700948 for (int i = 0; i < operation.dst_extents_size(); i++) {
949 Extent extent = operation.dst_extents(i);
950 const uint64_t start = extent.start_block() * block_size_;
951 const uint64_t length = extent.num_blocks() * block_size_;
952 if (attempt_ioctl) {
953 int result = 0;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700954 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0)
Alex Deymo79715ad2015-10-02 14:27:53 -0700955 continue;
956 attempt_ioctl = false;
957 zeros.resize(16 * block_size_);
958 }
959 // In case of failure, we fall back to writing 0 to the selected region.
960 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Alex Deymo42791782015-10-08 11:01:28 -0700961 uint64_t chunk_length = min(length - offset,
962 static_cast<uint64_t>(zeros.size()));
Alex Deymo79715ad2015-10-02 14:27:53 -0700963 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700964 utils::PWriteAll(target_fd_, zeros.data(), chunk_length, start + offset));
Alex Deymo79715ad2015-10-02 14:27:53 -0700965 }
966 }
967 return true;
968}
969
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700970bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700971 // Calculate buffer size. Note, this function doesn't do a sliding
972 // window to copy in case the source and destination blocks overlap.
973 // If we wanted to do a sliding window, we could program the server
974 // to generate deltas that effectively did a sliding window.
975
976 uint64_t blocks_to_read = 0;
977 for (int i = 0; i < operation.src_extents_size(); i++)
978 blocks_to_read += operation.src_extents(i).num_blocks();
979
980 uint64_t blocks_to_write = 0;
981 for (int i = 0; i < operation.dst_extents_size(); i++)
982 blocks_to_write += operation.dst_extents(i).num_blocks();
983
984 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700985 brillo::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700986
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700987 // Read in bytes.
988 ssize_t bytes_read = 0;
989 for (int i = 0; i < operation.src_extents_size(); i++) {
990 ssize_t bytes_read_this_iteration = 0;
991 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200992 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700993 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700994 TEST_AND_RETURN_FALSE(utils::PReadAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -0700995 &buf[bytes_read],
996 bytes,
997 extent.start_block() * block_size_,
998 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700999 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +02001000 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001001 bytes_read += bytes_read_this_iteration;
1002 }
1003
1004 // Write bytes out.
1005 ssize_t bytes_written = 0;
1006 for (int i = 0; i < operation.dst_extents_size(); i++) {
1007 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001008 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001009 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001010 TEST_AND_RETURN_FALSE(utils::PWriteAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001011 &buf[bytes_written],
1012 bytes,
1013 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +02001014 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001015 }
1016 DCHECK_EQ(bytes_written, bytes_read);
1017 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
1018 return true;
1019}
1020
Allie Wood9f6f0a52015-03-30 11:25:47 -07001021namespace {
1022
1023// Takes |extents| and fills an empty vector |blocks| with a block index for
1024// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
1025void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
1026 vector<uint64_t>* blocks) {
1027 for (Extent ext : extents) {
1028 for (uint64_t j = 0; j < ext.num_blocks(); j++)
1029 blocks->push_back(ext.start_block() + j);
1030 }
1031}
1032
1033// Takes |extents| and returns the number of blocks in those extents.
1034uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
1035 uint64_t sum = 0;
1036 for (Extent ext : extents) {
1037 sum += ext.num_blocks();
1038 }
1039 return sum;
1040}
1041
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001042// Compare |calculated_hash| with source hash in |operation|, return false and
1043// dump hash if don't match.
1044bool ValidateSourceHash(const brillo::Blob& calculated_hash,
1045 const InstallOperation& operation) {
1046 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1047 operation.src_sha256_hash().end());
1048 if (calculated_hash != expected_source_hash) {
1049 LOG(ERROR) << "Hash verification failed. Expected hash = ";
1050 utils::HexDumpVector(expected_source_hash);
1051 LOG(ERROR) << "Calculated hash = ";
1052 utils::HexDumpVector(calculated_hash);
1053 return false;
1054 }
1055 return true;
1056}
1057
Allie Wood9f6f0a52015-03-30 11:25:47 -07001058} // namespace
1059
1060bool DeltaPerformer::PerformSourceCopyOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001061 const InstallOperation& operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001062 if (operation.has_src_length())
1063 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1064 if (operation.has_dst_length())
1065 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1066
1067 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
1068 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
1069 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
1070
1071 // Create vectors of all the individual src/dst blocks.
1072 vector<uint64_t> src_blocks;
1073 vector<uint64_t> dst_blocks;
1074 ExtentsToBlocks(operation.src_extents(), &src_blocks);
1075 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
1076 DCHECK_EQ(src_blocks.size(), blocks_to_read);
1077 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
1078
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001079 brillo::Blob buf(block_size_);
Allie Wood9f6f0a52015-03-30 11:25:47 -07001080 ssize_t bytes_read = 0;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001081 HashCalculator source_hasher;
Allie Wood9f6f0a52015-03-30 11:25:47 -07001082 // Read/write one block at a time.
1083 for (uint64_t i = 0; i < blocks_to_read; i++) {
1084 ssize_t bytes_read_this_iteration = 0;
1085 uint64_t src_block = src_blocks[i];
1086 uint64_t dst_block = dst_blocks[i];
1087
1088 // Read in bytes.
1089 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001090 utils::PReadAll(source_fd_,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001091 buf.data(),
1092 block_size_,
1093 src_block * block_size_,
1094 &bytes_read_this_iteration));
1095
1096 // Write bytes out.
1097 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001098 utils::PWriteAll(target_fd_,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001099 buf.data(),
1100 block_size_,
1101 dst_block * block_size_));
1102
1103 bytes_read += bytes_read_this_iteration;
1104 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
1105 static_cast<ssize_t>(block_size_));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001106
1107 if (operation.has_src_sha256_hash())
1108 TEST_AND_RETURN_FALSE(source_hasher.Update(buf.data(), buf.size()));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001109 }
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001110
1111 if (operation.has_src_sha256_hash()) {
1112 TEST_AND_RETURN_FALSE(source_hasher.Finalize());
1113 TEST_AND_RETURN_FALSE(
1114 ValidateSourceHash(source_hasher.raw_hash(), operation));
1115 }
1116
Allie Wood9f6f0a52015-03-30 11:25:47 -07001117 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
1118 return true;
1119}
1120
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001121bool DeltaPerformer::ExtentsToBsdiffPositionsString(
1122 const RepeatedPtrField<Extent>& extents,
1123 uint64_t block_size,
1124 uint64_t full_length,
1125 string* positions_string) {
1126 string ret;
1127 uint64_t length = 0;
1128 for (int i = 0; i < extents.size(); i++) {
1129 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -07001130 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001131 uint64_t this_length = min(full_length - length,
1132 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001133 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001134 length += this_length;
1135 }
1136 TEST_AND_RETURN_FALSE(length == full_length);
1137 if (!ret.empty())
1138 ret.resize(ret.size() - 1); // Strip trailing comma off
1139 *positions_string = ret;
1140 return true;
1141}
1142
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001143bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001144 // Since we delete data off the beginning of the buffer as we use it,
1145 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001146 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1147 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001148
1149 string input_positions;
1150 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1151 block_size_,
1152 operation.src_length(),
1153 &input_positions));
1154 string output_positions;
1155 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1156 block_size_,
1157 operation.dst_length(),
1158 &output_positions));
1159
1160 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -07001161 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001162 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001163 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001164 ScopedPathUnlinker path_unlinker(temp_filename);
1165 {
1166 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
1167 ScopedFdCloser fd_closer(&fd);
1168 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001169 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001170 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001171
Darin Petkov7f2ec752013-04-03 14:45:19 +02001172 // Update the buffer to release the patch data memory as soon as the patch
1173 // file is written out.
Sen Jiangf6813802015-11-03 21:27:29 -08001174 DiscardBuffer(true, buffer_.size());
Darin Petkov7f2ec752013-04-03 14:45:19 +02001175
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001176 vector<string> cmd{kBspatchPath, target_path_, target_path_, temp_filename,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001177 input_positions, output_positions};
1178
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001179 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -07001180 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -07001181 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
1182 &return_code, nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001183 TEST_AND_RETURN_FALSE(return_code == 0);
1184
1185 if (operation.dst_length() % block_size_) {
1186 // Zero out rest of final block.
1187 // TODO(adlr): build this into bspatch; it's more efficient that way.
1188 const Extent& last_extent =
1189 operation.dst_extents(operation.dst_extents_size() - 1);
1190 const uint64_t end_byte =
1191 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
1192 const uint64_t begin_byte =
1193 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001194 brillo::Blob zeros(end_byte - begin_byte);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001195 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001196 utils::PWriteAll(target_fd_, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001197 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001198 return true;
1199}
1200
Allie Wood9f6f0a52015-03-30 11:25:47 -07001201bool DeltaPerformer::PerformSourceBsdiffOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001202 const InstallOperation& operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001203 // Since we delete data off the beginning of the buffer as we use it,
1204 // the data we need should be exactly at the beginning of the buffer.
1205 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1206 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1207 if (operation.has_src_length())
1208 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1209 if (operation.has_dst_length())
1210 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1211
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001212 if (operation.has_src_sha256_hash()) {
1213 HashCalculator source_hasher;
1214 const uint64_t kMaxBlocksToRead = 512; // 2MB if block size is 4KB
1215 brillo::Blob buf(kMaxBlocksToRead * block_size_);
1216 for (const Extent& extent : operation.src_extents()) {
1217 for (uint64_t i = 0; i < extent.num_blocks(); i += kMaxBlocksToRead) {
1218 uint64_t blocks_to_read =
1219 min(kMaxBlocksToRead, extent.num_blocks() - i);
1220 ssize_t bytes_to_read = blocks_to_read * block_size_;
1221 ssize_t bytes_read_this_iteration = 0;
1222 TEST_AND_RETURN_FALSE(
1223 utils::PReadAll(source_fd_, buf.data(), bytes_to_read,
1224 (extent.start_block() + i) * block_size_,
1225 &bytes_read_this_iteration));
1226 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes_to_read);
1227 TEST_AND_RETURN_FALSE(source_hasher.Update(buf.data(), bytes_to_read));
1228 }
1229 }
1230 TEST_AND_RETURN_FALSE(source_hasher.Finalize());
1231 TEST_AND_RETURN_FALSE(
1232 ValidateSourceHash(source_hasher.raw_hash(), operation));
1233 }
1234
Allie Wood9f6f0a52015-03-30 11:25:47 -07001235 string input_positions;
1236 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1237 block_size_,
1238 operation.src_length(),
1239 &input_positions));
1240 string output_positions;
1241 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1242 block_size_,
1243 operation.dst_length(),
1244 &output_positions));
1245
1246 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -07001247 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Allie Wood9f6f0a52015-03-30 11:25:47 -07001248 &temp_filename,
1249 nullptr));
1250 ScopedPathUnlinker path_unlinker(temp_filename);
1251 {
1252 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
1253 ScopedFdCloser fd_closer(&fd);
1254 TEST_AND_RETURN_FALSE(
1255 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
1256 }
1257
1258 // Update the buffer to release the patch data memory as soon as the patch
1259 // file is written out.
Sen Jiangf6813802015-11-03 21:27:29 -08001260 DiscardBuffer(true, buffer_.size());
Allie Wood9f6f0a52015-03-30 11:25:47 -07001261
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001262 vector<string> cmd{kBspatchPath, source_path_, target_path_, temp_filename,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001263 input_positions, output_positions};
1264
1265 int return_code = 0;
1266 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -07001267 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
1268 &return_code, nullptr));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001269 TEST_AND_RETURN_FALSE(return_code == 0);
1270 return true;
1271}
1272
Sen Jiangbc3e6b02016-01-19 18:39:26 +08001273bool DeltaPerformer::PerformImgdiffOperation(
1274 const InstallOperation& operation) {
1275 // Since we delete data off the beginning of the buffer as we use it,
1276 // the data we need should be exactly at the beginning of the buffer.
1277 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1278 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1279
1280 uint64_t src_blocks = GetBlockCount(operation.src_extents());
1281 brillo::Blob src_data(src_blocks * block_size_);
1282
1283 ssize_t bytes_read = 0;
1284 for (const Extent& extent : operation.src_extents()) {
1285 ssize_t bytes_read_this_iteration = 0;
1286 ssize_t bytes_to_read = extent.num_blocks() * block_size_;
1287 TEST_AND_RETURN_FALSE(utils::PReadAll(source_fd_,
1288 &src_data[bytes_read],
1289 bytes_to_read,
1290 extent.start_block() * block_size_,
1291 &bytes_read_this_iteration));
1292 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes_to_read);
1293 bytes_read += bytes_read_this_iteration;
1294 }
1295
1296 if (operation.has_src_sha256_hash()) {
1297 brillo::Blob src_hash;
1298 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfData(src_data, &src_hash));
1299 TEST_AND_RETURN_FALSE(ValidateSourceHash(src_hash, operation));
1300 }
1301
1302 vector<Extent> target_extents(operation.dst_extents().begin(),
1303 operation.dst_extents().end());
1304 DirectExtentWriter writer;
1305 TEST_AND_RETURN_FALSE(writer.Init(target_fd_, target_extents, block_size_));
1306 TEST_AND_RETURN_FALSE(
1307 ApplyImagePatch(src_data.data(),
1308 src_data.size(),
1309 buffer_.data(),
1310 operation.data_length(),
1311 [](const unsigned char* data, ssize_t len, void* token) {
1312 return reinterpret_cast<ExtentWriter*>(token)
1313 ->Write(data, len)
1314 ? len
1315 : 0;
1316 },
1317 &writer) == 0);
1318 TEST_AND_RETURN_FALSE(writer.End());
1319
1320 DiscardBuffer(true, buffer_.size());
1321 return true;
1322}
1323
Sen Jiangf6813802015-11-03 21:27:29 -08001324bool DeltaPerformer::ExtractSignatureMessageFromOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -07001325 const InstallOperation& operation) {
1326 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -07001327 !manifest_.has_signatures_offset() ||
1328 manifest_.signatures_offset() != operation.data_offset()) {
1329 return false;
1330 }
1331 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1332 manifest_.signatures_size() == operation.data_length());
Sen Jiangf6813802015-11-03 21:27:29 -08001333 TEST_AND_RETURN_FALSE(ExtractSignatureMessage());
1334 return true;
1335}
1336
1337bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001338 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1339 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1340 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001341 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001342 buffer_.begin(),
1343 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001344
1345 // Save the signature blob because if the update is interrupted after the
1346 // download phase we don't go through this path anymore. Some alternatives to
1347 // consider:
1348 //
1349 // 1. On resume, re-download the signature blob from the server and re-verify
1350 // it.
1351 //
1352 // 2. Verify the signature as soon as it's received and don't checkpoint the
1353 // blob and the signed sha-256 context.
1354 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001355 string(signatures_message_data_.begin(),
1356 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001357 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -08001358
Darin Petkovd7061ab2010-10-06 14:37:09 -07001359 LOG(INFO) << "Extracted signature data of size "
1360 << manifest_.signatures_size() << " at "
1361 << manifest_.signatures_offset();
1362 return true;
1363}
1364
David Zeuthene7f89172013-10-31 10:21:04 -07001365bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
Alex Deymo542c19b2015-12-03 07:43:31 -03001366 if (hardware_->IsOfficialBuild() ||
David Zeuthene7f89172013-10-31 10:21:04 -07001367 utils::FileExists(public_key_path_.c_str()) ||
1368 install_plan_->public_key_rsa.empty())
1369 return false;
1370
1371 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1372 out_tmp_key))
1373 return false;
1374
1375 return true;
1376}
1377
David Zeuthena99981f2013-04-29 13:42:47 -07001378ErrorCode DeltaPerformer::ValidateMetadataSignature(
Sen Jiang76bfa742015-10-12 17:13:26 -07001379 const brillo::Blob& payload) {
1380 if (payload.size() < metadata_size_ + metadata_signature_size_)
1381 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001382
Sen Jiang76bfa742015-10-12 17:13:26 -07001383 brillo::Blob metadata_signature_blob, metadata_signature_protobuf_blob;
1384 if (!install_plan_->metadata_signature.empty()) {
1385 // Convert base64-encoded signature to raw bytes.
1386 if (!brillo::data_encoding::Base64Decode(
1387 install_plan_->metadata_signature, &metadata_signature_blob)) {
1388 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1389 << install_plan_->metadata_signature;
1390 return ErrorCode::kDownloadMetadataSignatureError;
1391 }
1392 } else if (major_payload_version_ == kBrilloMajorPayloadVersion) {
1393 metadata_signature_protobuf_blob.assign(payload.begin() + metadata_size_,
1394 payload.begin() + metadata_size_ +
1395 metadata_signature_size_);
1396 }
1397
1398 if (metadata_signature_blob.empty() &&
1399 metadata_signature_protobuf_blob.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001400 if (install_plan_->hash_checks_mandatory) {
Sen Jiang76bfa742015-10-12 17:13:26 -07001401 LOG(ERROR) << "Missing mandatory metadata signature in both Omaha "
1402 << "response and payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001403 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001404 }
1405
Jay Srinivasanf4318702012-09-24 11:56:24 -07001406 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001407 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001408 }
1409
David Zeuthene7f89172013-10-31 10:21:04 -07001410 // See if we should use the public RSA key in the Omaha response.
1411 base::FilePath path_to_public_key(public_key_path_);
1412 base::FilePath tmp_key;
1413 if (GetPublicKeyFromResponse(&tmp_key))
1414 path_to_public_key = tmp_key;
1415 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1416 if (tmp_key.empty())
1417 tmp_key_remover.set_should_remove(false);
1418
1419 LOG(INFO) << "Verifying metadata hash signature using public key: "
1420 << path_to_public_key.value();
1421
Alex Deymo39910dc2015-11-09 17:04:30 -08001422 HashCalculator metadata_hasher;
Sen Jiang76bfa742015-10-12 17:13:26 -07001423 metadata_hasher.Update(payload.data(), metadata_size_);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001424 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001425 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001426 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001427 }
1428
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001429 brillo::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001430 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001431 if (calculated_metadata_hash.empty()) {
1432 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001433 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001434 }
1435
Sen Jiang76bfa742015-10-12 17:13:26 -07001436 if (!metadata_signature_blob.empty()) {
1437 brillo::Blob expected_metadata_hash;
1438 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature_blob,
1439 path_to_public_key.value(),
1440 &expected_metadata_hash)) {
1441 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
1442 return ErrorCode::kDownloadMetadataSignatureError;
1443 }
1444 if (calculated_metadata_hash != expected_metadata_hash) {
1445 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
1446 utils::HexDumpVector(expected_metadata_hash);
1447 LOG(ERROR) << "Calculated hash = ";
1448 utils::HexDumpVector(calculated_metadata_hash);
1449 return ErrorCode::kDownloadMetadataSignatureMismatch;
1450 }
1451 } else {
1452 if (!PayloadVerifier::VerifySignature(metadata_signature_protobuf_blob,
1453 path_to_public_key.value(),
1454 calculated_metadata_hash)) {
1455 LOG(ERROR) << "Manifest hash verification failed.";
1456 return ErrorCode::kDownloadMetadataSignatureMismatch;
1457 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001458 }
1459
David Zeuthenbc27aac2013-11-26 11:17:48 -08001460 // The autoupdate_CatchBadSignatures test checks for this string in
1461 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001462 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001463 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001464}
1465
Gilad Arnold21504f02013-05-24 08:51:22 -07001466ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001467 // Perform assorted checks to sanity check the manifest, make sure it
1468 // matches data from other sources, and that it is a supported version.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001469
Alex Deymo64d98782016-02-05 18:03:48 -08001470 bool has_old_fields =
1471 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info());
1472 for (const PartitionUpdate& partition : manifest_.partitions()) {
1473 has_old_fields = has_old_fields || partition.has_old_partition_info();
1474 }
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001475
Alex Deymo64d98782016-02-05 18:03:48 -08001476 // The presence of an old partition hash is the sole indicator for a delta
1477 // update.
1478 InstallPayloadType actual_payload_type =
1479 has_old_fields ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
1480
1481 if (install_plan_->payload_type == InstallPayloadType::kUnknown) {
1482 LOG(INFO) << "Detected a '"
1483 << InstallPayloadTypeToString(actual_payload_type)
1484 << "' payload.";
1485 install_plan_->payload_type = actual_payload_type;
1486 } else if (install_plan_->payload_type != actual_payload_type) {
1487 LOG(ERROR) << "InstallPlan expected a '"
1488 << InstallPayloadTypeToString(install_plan_->payload_type)
1489 << "' payload but the downloaded manifest contains a '"
1490 << InstallPayloadTypeToString(actual_payload_type)
1491 << "' payload.";
1492 return ErrorCode::kPayloadMismatchedType;
1493 }
1494
1495 // Check that the minor version is compatible.
1496 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001497 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1498 LOG(ERROR) << "Manifest contains minor version "
1499 << manifest_.minor_version()
1500 << ", but all full payloads should have version "
1501 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001502 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001503 }
1504 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001505 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001506 LOG(ERROR) << "Manifest contains minor version "
1507 << manifest_.minor_version()
1508 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001509 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001510 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001511 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001512 }
1513
Sen Jiang3e728fe2015-11-05 11:37:23 -08001514 if (major_payload_version_ != kChromeOSMajorPayloadVersion) {
1515 if (manifest_.has_old_rootfs_info() ||
1516 manifest_.has_new_rootfs_info() ||
1517 manifest_.has_old_kernel_info() ||
1518 manifest_.has_new_kernel_info() ||
1519 manifest_.install_operations_size() != 0 ||
1520 manifest_.kernel_install_operations_size() != 0) {
1521 LOG(ERROR) << "Manifest contains deprecated field only supported in "
1522 << "major payload version 1, but the payload major version is "
1523 << major_payload_version_;
1524 return ErrorCode::kPayloadMismatchedType;
1525 }
1526 }
1527
Gilad Arnold21504f02013-05-24 08:51:22 -07001528 // TODO(garnold) we should be adding more and more manifest checks, such as
1529 // partition boundaries etc (see chromium-os:37661).
1530
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001531 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001532}
1533
David Zeuthena99981f2013-04-29 13:42:47 -07001534ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001535 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001536 if (!operation.data_sha256_hash().size()) {
1537 if (!operation.data_length()) {
1538 // Operations that do not have any data blob won't have any operation hash
1539 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001540 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001541 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001542 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001543 }
1544
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001545 // No hash is present for an operation that has data blobs. This shouldn't
1546 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001547 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001548 // hashes. So if it happens it means either we've turned operation hash
1549 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001550 // One caveat though: The last operation is a dummy signature operation
1551 // that doesn't have a hash at the time the manifest is created. So we
1552 // should not complaint about that operation. This operation can be
1553 // recognized by the fact that it's offset is mentioned in the manifest.
1554 if (manifest_.signatures_offset() &&
1555 manifest_.signatures_offset() == operation.data_offset()) {
1556 LOG(INFO) << "Skipping hash verification for signature operation "
1557 << next_operation_num_ + 1;
1558 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001559 if (install_plan_->hash_checks_mandatory) {
1560 LOG(ERROR) << "Missing mandatory operation hash for operation "
1561 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001562 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001563 }
1564
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001565 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1566 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001567 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001568 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001569 }
1570
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001571 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001572 expected_op_hash.assign(operation.data_sha256_hash().data(),
1573 (operation.data_sha256_hash().data() +
1574 operation.data_sha256_hash().size()));
1575
Alex Deymo39910dc2015-11-09 17:04:30 -08001576 HashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001577 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001578 if (!operation_hasher.Finalize()) {
1579 LOG(ERROR) << "Unable to compute actual hash of operation "
1580 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001581 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001582 }
1583
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001584 brillo::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001585 if (calculated_op_hash != expected_op_hash) {
1586 LOG(ERROR) << "Hash verification failed for operation "
1587 << next_operation_num_ << ". Expected hash = ";
1588 utils::HexDumpVector(expected_op_hash);
1589 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1590 << " bytes at offset: " << operation.data_offset() << " = ";
1591 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001592 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001593 }
1594
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001595 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001596}
1597
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001598#define TEST_AND_RETURN_VAL(_retval, _condition) \
1599 do { \
1600 if (!(_condition)) { \
1601 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1602 return _retval; \
1603 } \
1604 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001605
David Zeuthena99981f2013-04-29 13:42:47 -07001606ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001607 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001608 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001609
1610 // See if we should use the public RSA key in the Omaha response.
1611 base::FilePath path_to_public_key(public_key_path_);
1612 base::FilePath tmp_key;
1613 if (GetPublicKeyFromResponse(&tmp_key))
1614 path_to_public_key = tmp_key;
1615 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1616 if (tmp_key.empty())
1617 tmp_key_remover.set_should_remove(false);
1618
1619 LOG(INFO) << "Verifying payload using public key: "
1620 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001621
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001622 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001623 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001624 update_check_response_size ==
Sen Jiang76bfa742015-10-12 17:13:26 -07001625 metadata_size_ + metadata_signature_size_ +
1626 buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001627
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001628 // Verifies the payload hash.
Sen Jiangf6813802015-11-03 21:27:29 -08001629 const string& payload_hash_data = payload_hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001630 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001631 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001632 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001633 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001634
Darin Petkov437adc42010-10-07 13:12:24 -07001635 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001636 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001637 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001638 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001639 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001640 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001641 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001642 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001643 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1644 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001645 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001646 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001647
1648 if (!PayloadVerifier::VerifySignature(
1649 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001650 // The autoupdate_CatchBadSignatures test checks for this string
1651 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001652 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001653 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001654 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001655
David Zeuthene7f89172013-10-31 10:21:04 -07001656 LOG(INFO) << "Payload hash matches value in payload.";
1657
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001658 // At this point, we are guaranteed to have downloaded a full payload, i.e
1659 // the one whose size matches the size mentioned in Omaha response. If any
1660 // errors happen after this, it's likely a problem with the payload itself or
1661 // the state of the system and not a problem with the URL or network. So,
Alex Deymo542c19b2015-12-03 07:43:31 -03001662 // indicate that to the download delegate so that AU can backoff
1663 // appropriately.
1664 if (download_delegate_)
1665 download_delegate_->DownloadComplete();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001666
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001667 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001668}
1669
Sen Jiangf6813802015-11-03 21:27:29 -08001670void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1671 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001672 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001673 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001674 buffer_offset_ += buffer_.size();
1675
1676 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001677 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1678 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001679
1680 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001681 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001682}
1683
Darin Petkov0406e402010-10-06 21:33:11 -07001684bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1685 string update_check_response_hash) {
1686 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001687 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1688 next_operation != kUpdateStateOperationInvalid &&
1689 next_operation > 0))
1690 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001691
1692 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001693 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1694 !interrupted_hash.empty() &&
1695 interrupted_hash == update_check_response_hash))
1696 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001697
Darin Petkov61426142010-10-08 11:04:55 -07001698 int64_t resumed_update_failures;
Alex Deymof25eb492016-02-26 00:20:08 -08001699 // Note that storing this value is optional, but if it is there it should not
1700 // be more than the limit.
1701 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1702 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001703 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001704
Darin Petkov0406e402010-10-06 21:33:11 -07001705 // Sanity check the rest.
1706 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001707 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1708 next_data_offset >= 0))
1709 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001710
Darin Petkov437adc42010-10-07 13:12:24 -07001711 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001712 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1713 !sha256_context.empty()))
1714 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001715
1716 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001717 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1718 manifest_metadata_size > 0))
1719 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001720
Alex Deymof25eb492016-02-26 00:20:08 -08001721 int64_t manifest_signature_size = 0;
1722 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1723 &manifest_signature_size) &&
1724 manifest_signature_size >= 0))
1725 return false;
1726
Darin Petkov0406e402010-10-06 21:33:11 -07001727 return true;
1728}
1729
Darin Petkov9b230572010-10-08 10:20:09 -07001730bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001731 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1732 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001733 if (!quick) {
1734 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1735 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001736 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001737 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1738 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001739 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001740 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001741 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001742 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001743 }
Darin Petkov73058b42010-10-06 16:32:19 -07001744 return true;
1745}
1746
1747bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001748 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001749 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001750 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001751 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001752 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001753 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Sen Jiangf6813802015-11-03 21:27:29 -08001754 payload_hash_calculator_.GetContext()));
1755 TEST_AND_RETURN_FALSE(
1756 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1757 signed_hash_calculator_.GetContext()));
Darin Petkov0406e402010-10-06 21:33:11 -07001758 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1759 buffer_offset_));
1760 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001761
1762 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001763 size_t partition_index = current_partition_;
1764 while (next_operation_num_ >= acc_num_operations_[partition_index])
1765 partition_index++;
1766 const size_t partition_operation_num = next_operation_num_ - (
1767 partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001768 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001769 partitions_[partition_index].operations(partition_operation_num);
David Zeuthen41996ad2013-09-24 15:43:24 -07001770 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1771 op.data_length()));
1772 } else {
1773 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1774 0));
1775 }
Darin Petkov0406e402010-10-06 21:33:11 -07001776 }
Darin Petkov73058b42010-10-06 16:32:19 -07001777 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1778 next_operation_num_));
1779 return true;
1780}
1781
Darin Petkov9b230572010-10-08 10:20:09 -07001782bool DeltaPerformer::PrimeUpdateState() {
1783 CHECK(manifest_valid_);
1784 block_size_ = manifest_.block_size();
1785
1786 int64_t next_operation = kUpdateStateOperationInvalid;
1787 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1788 next_operation == kUpdateStateOperationInvalid ||
1789 next_operation <= 0) {
1790 // Initiating a new update, no more state needs to be initialized.
1791 return true;
1792 }
1793 next_operation_num_ = next_operation;
1794
1795 // Resuming an update -- load the rest of the update state.
1796 int64_t next_data_offset = -1;
1797 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1798 &next_data_offset) &&
1799 next_data_offset >= 0);
1800 buffer_offset_ = next_data_offset;
1801
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001802 // The signed hash context and the signature blob may be empty if the
1803 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001804 string signed_hash_context;
1805 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1806 &signed_hash_context)) {
1807 TEST_AND_RETURN_FALSE(
1808 signed_hash_calculator_.SetContext(signed_hash_context));
1809 }
1810
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001811 string signature_blob;
1812 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1813 signatures_message_data_.assign(signature_blob.begin(),
1814 signature_blob.end());
1815 }
Darin Petkov9b230572010-10-08 10:20:09 -07001816
1817 string hash_context;
1818 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1819 &hash_context) &&
Sen Jiangf6813802015-11-03 21:27:29 -08001820 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001821
1822 int64_t manifest_metadata_size = 0;
1823 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1824 &manifest_metadata_size) &&
1825 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001826 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001827
Alex Deymof25eb492016-02-26 00:20:08 -08001828 int64_t manifest_signature_size = 0;
1829 TEST_AND_RETURN_FALSE(
1830 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1831 manifest_signature_size >= 0);
1832 metadata_signature_size_ = manifest_signature_size;
1833
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001834 // Advance the download progress to reflect what doesn't need to be
1835 // re-downloaded.
1836 total_bytes_received_ += buffer_offset_;
1837
Darin Petkov61426142010-10-08 11:04:55 -07001838 // Speculatively count the resume as a failure.
1839 int64_t resumed_update_failures;
1840 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1841 resumed_update_failures++;
1842 } else {
1843 resumed_update_failures = 1;
1844 }
1845 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001846 return true;
1847}
1848
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001849} // namespace chromeos_update_engine