1 //
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 //
16
17 #include "update_engine/payload_consumer/filesystem_verifier_action.h"
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24
25 #include <algorithm>
26 #include <cstdlib>
27 #include <functional>
28 #include <memory>
29 #include <numeric>
30 #include <string>
31 #include <utility>
32
33 #include <base/bind.h>
34 #include <brillo/data_encoding.h>
35 #include <brillo/message_loops/message_loop.h>
36 #include <brillo/secure_blob.h>
37 #include <brillo/streams/file_stream.h>
38
39 #include "update_engine/common/error_code.h"
40 #include "update_engine/common/utils.h"
41 #include "update_engine/payload_consumer/file_descriptor.h"
42 #include "update_engine/payload_consumer/install_plan.h"
43
44 using brillo::data_encoding::Base64Encode;
45 using std::string;
46
47 // On a partition with verity enabled, we expect to see the following format:
48 // ===================================================
49 // Normal Filesystem Data
50 // (this should take most of the space, like over 90%)
51 // ===================================================
52 // Hash tree
53 // ~0.8% (e.g. 16M for 2GB image)
54 // ===================================================
55 // FEC data
56 // ~0.8%
57 // ===================================================
58 // Footer
59 // 4K
60 // ===================================================
61
62 // For OTA that doesn't do on device verity computation, hash tree and fec data
63 // are written during DownloadAction as a regular InstallOp, so no special
64 // handling needed, we can just read the entire partition in 1 go.
65
66 // Verity enabled case: Only Normal FS data is written during download action.
67 // When hasing the entire partition, we will need to build the hash tree, write
68 // it to disk, then build FEC, and write it to disk. Therefore, it is important
69 // that we finish writing hash tree before we attempt to read & hash it. The
70 // same principal applies to FEC data.
71
72 // |verity_writer_| handles building and
73 // writing of FEC/HashTree, we just need to be careful when reading.
74 // Specifically, we must stop at beginning of Hash tree, let |verity_writer_|
75 // write both hash tree and FEC, then continue reading the remaining part of
76 // partition.
77
78 namespace chromeos_update_engine {
79
80 namespace {
81 const off_t kReadFileBufferSize = 128 * 1024;
82 constexpr float kVerityProgressPercent = 0.3;
83 constexpr float kEncodeFECPercent = 0.3;
84
85 } // namespace
86
PerformAction()87 void FilesystemVerifierAction::PerformAction() {
88 // Will tell the ActionProcessor we've failed if we return.
89 ScopedActionCompleter abort_action_completer(processor_, this);
90
91 if (!HasInputObject()) {
92 LOG(ERROR) << "FilesystemVerifierAction missing input object.";
93 return;
94 }
95 install_plan_ = GetInputObject();
96
97 if (install_plan_.partitions.empty()) {
98 LOG(ERROR) << "No partitions to verify.";
99 if (HasOutputPipe())
100 SetOutputObject(install_plan_);
101 abort_action_completer.set_code(ErrorCode::kFilesystemVerifierError);
102 return;
103 }
104 // partition_weight_[i] = total size of partitions before index i.
105 partition_weight_.clear();
106 partition_weight_.reserve(install_plan_.partitions.size() + 1);
107 partition_weight_.push_back(0);
108 for (const auto& part : install_plan_.partitions) {
109 partition_weight_.push_back(part.target_size);
110 }
111 std::partial_sum(partition_weight_.begin(),
112 partition_weight_.end(),
113 partition_weight_.begin(),
114 std::plus<uint64_t>());
115
116 install_plan_.Dump();
117 // If we are not writing verity, just map all partitions once at the
118 // beginning.
119 // No need to re-map for each partition, because we are not writing any new
120 // COW data.
121 if (dynamic_control_->UpdateUsesSnapshotCompression() &&
122 !install_plan_.write_verity) {
123 dynamic_control_->MapAllPartitions();
124 }
125 StartPartitionHashing();
126 abort_action_completer.set_should_complete(false);
127 }
128
TerminateProcessing()129 void FilesystemVerifierAction::TerminateProcessing() {
130 cancelled_ = true;
131 Cleanup(ErrorCode::kSuccess); // error code is ignored if canceled_ is true.
132 }
133
Cleanup(ErrorCode code)134 void FilesystemVerifierAction::Cleanup(ErrorCode code) {
135 partition_fd_.reset();
136 // This memory is not used anymore.
137 buffer_.clear();
138
139 // If we didn't write verity, partitions were maped. Releaase resource now.
140 if (!install_plan_.write_verity &&
141 dynamic_control_->UpdateUsesSnapshotCompression()) {
142 LOG(INFO) << "Not writing verity and VABC is enabled, unmapping all "
143 "partitions";
144 dynamic_control_->UnmapAllPartitions();
145 }
146
147 if (cancelled_)
148 return;
149 if (code == ErrorCode::kSuccess && HasOutputPipe())
150 SetOutputObject(install_plan_);
151 UpdateProgress(1.0);
152 processor_->ActionComplete(this, code);
153 }
154
UpdateProgress(double progress)155 void FilesystemVerifierAction::UpdateProgress(double progress) {
156 if (delegate_ != nullptr) {
157 delegate_->OnVerifyProgressUpdate(progress);
158 }
159 }
160
UpdatePartitionProgress(double progress)161 void FilesystemVerifierAction::UpdatePartitionProgress(double progress) {
162 UpdateProgress((partition_weight_[partition_index_] * (1 - progress) +
163 partition_weight_[partition_index_ + 1] * progress) /
164 partition_weight_.back());
165 }
166
InitializeFdVABC(bool should_write_verity)167 bool FilesystemVerifierAction::InitializeFdVABC(bool should_write_verity) {
168 const InstallPlan::Partition& partition =
169 install_plan_.partitions[partition_index_];
170
171 if (!should_write_verity) {
172 // In VABC, we cannot map/unmap partitions w/o first closing ALL fds first.
173 // Since this function might be called inside a ScheduledTask, the closure
174 // might have a copy of partition_fd_ when executing this function. Which
175 // means even if we do |partition_fd_.reset()| here, there's a chance that
176 // underlying fd isn't closed until we return. This is unacceptable, we need
177 // to close |partition_fd| right away.
178 if (partition_fd_) {
179 partition_fd_->Close();
180 partition_fd_.reset();
181 }
182 // In VABC, if we are not writing verity, just map all partitions,
183 // and read using regular fd on |postinstall_mount_device| .
184 // All read will go through snapuserd, which provides a consistent
185 // view: device will use snapuserd to read partition during boot.
186 // b/186196758
187 // Call UnmapAllPartitions() first, because if we wrote verity before, these
188 // writes won't be visible to previously opened snapuserd daemon. To ensure
189 // that we will see the most up to date data from partitions, call Unmap()
190 // then Map() to re-spin daemon.
191 if (install_plan_.write_verity) {
192 dynamic_control_->UnmapAllPartitions();
193 dynamic_control_->MapAllPartitions();
194 }
195 return InitializeFd(partition.readonly_target_path);
196 }
197 partition_fd_ =
198 dynamic_control_->OpenCowFd(partition.name, partition.source_path, true);
199 if (!partition_fd_) {
200 LOG(ERROR) << "OpenCowReader(" << partition.name << ", "
201 << partition.source_path << ") failed.";
202 return false;
203 }
204 partition_size_ = partition.target_size;
205 return true;
206 }
207
InitializeFd(const std::string & part_path)208 bool FilesystemVerifierAction::InitializeFd(const std::string& part_path) {
209 partition_fd_ = std::make_unique<EintrSafeFileDescriptor>();
210 const bool write_verity = ShouldWriteVerity();
211 int flags = write_verity ? O_RDWR : O_RDONLY;
212 if (!utils::SetBlockDeviceReadOnly(part_path, !write_verity)) {
213 LOG(WARNING) << "Failed to set block device " << part_path << " as "
214 << (write_verity ? "writable" : "readonly");
215 }
216 if (!partition_fd_->Open(part_path.c_str(), flags)) {
217 LOG(ERROR) << "Unable to open " << part_path << " for reading.";
218 return false;
219 }
220 return true;
221 }
222
WriteVerityData(FileDescriptor * fd,void * buffer,const size_t buffer_size)223 void FilesystemVerifierAction::WriteVerityData(FileDescriptor* fd,
224 void* buffer,
225 const size_t buffer_size) {
226 if (verity_writer_->FECFinished()) {
227 LOG(INFO) << "EncodeFEC is completed. Resuming other tasks";
228 if (dynamic_control_->UpdateUsesSnapshotCompression()) {
229 // Spin up snapuserd to read fs.
230 if (!InitializeFdVABC(false)) {
231 LOG(ERROR) << "Failed to map all partitions";
232 Cleanup(ErrorCode::kFilesystemVerifierError);
233 return;
234 }
235 }
236 HashPartition(0, partition_size_, buffer, buffer_size);
237 return;
238 }
239 if (!verity_writer_->IncrementalFinalize(fd, fd)) {
240 LOG(ERROR) << "Failed to write verity data";
241 Cleanup(ErrorCode::kVerityCalculationError);
242 }
243 UpdatePartitionProgress(kVerityProgressPercent +
244 verity_writer_->GetProgress() * kEncodeFECPercent);
245 CHECK(pending_task_id_.PostTask(
246 FROM_HERE,
247 base::BindOnce(&FilesystemVerifierAction::WriteVerityData,
248 base::Unretained(this),
249 fd,
250 buffer,
251 buffer_size)));
252 }
253
WriteVerityAndHashPartition(const off64_t start_offset,const off64_t end_offset,void * buffer,const size_t buffer_size)254 void FilesystemVerifierAction::WriteVerityAndHashPartition(
255 const off64_t start_offset,
256 const off64_t end_offset,
257 void* buffer,
258 const size_t buffer_size) {
259 auto fd = partition_fd_.get();
260 TEST_AND_RETURN(fd != nullptr);
261 if (start_offset >= end_offset) {
262 LOG_IF(WARNING, start_offset > end_offset)
263 << "start_offset is greater than end_offset : " << start_offset << " > "
264 << end_offset;
265 WriteVerityData(fd, buffer, buffer_size);
266 return;
267 }
268 const auto cur_offset = fd->Seek(start_offset, SEEK_SET);
269 if (cur_offset != start_offset) {
270 PLOG(ERROR) << "Failed to seek to offset: " << start_offset;
271 Cleanup(ErrorCode::kVerityCalculationError);
272 return;
273 }
274 const auto read_size =
275 std::min<uint64_t>(buffer_size, end_offset - start_offset);
276 const auto bytes_read = fd->Read(buffer, read_size);
277 if (bytes_read < 0 || static_cast<size_t>(bytes_read) != read_size) {
278 PLOG(ERROR) << "Failed to read offset " << start_offset << " expected "
279 << read_size << " bytes, actual: " << bytes_read;
280 Cleanup(ErrorCode::kVerityCalculationError);
281 return;
282 }
283 if (!verity_writer_->Update(
284 start_offset, static_cast<const uint8_t*>(buffer), read_size)) {
285 LOG(ERROR) << "VerityWriter::Update() failed";
286 Cleanup(ErrorCode::kVerityCalculationError);
287 return;
288 }
289 UpdatePartitionProgress((start_offset + bytes_read) * 1.0f / partition_size_ *
290 kVerityProgressPercent);
291 CHECK(pending_task_id_.PostTask(
292 FROM_HERE,
293 base::BindOnce(&FilesystemVerifierAction::WriteVerityAndHashPartition,
294 base::Unretained(this),
295 start_offset + bytes_read,
296 end_offset,
297 buffer,
298 buffer_size)));
299 }
300
HashPartition(const off64_t start_offset,const off64_t end_offset,void * buffer,const size_t buffer_size)301 void FilesystemVerifierAction::HashPartition(const off64_t start_offset,
302 const off64_t end_offset,
303 void* buffer,
304 const size_t buffer_size) {
305 auto fd = partition_fd_.get();
306 TEST_AND_RETURN(fd != nullptr);
307 if (start_offset >= end_offset) {
308 LOG_IF(WARNING, start_offset > end_offset)
309 << "start_offset is greater than end_offset : " << start_offset << " > "
310 << end_offset;
311 FinishPartitionHashing();
312 return;
313 }
314 const auto cur_offset = fd->Seek(start_offset, SEEK_SET);
315 if (cur_offset != start_offset) {
316 PLOG(ERROR) << "Failed to seek to offset: " << start_offset;
317 Cleanup(ErrorCode::kFilesystemVerifierError);
318 return;
319 }
320 const auto read_size =
321 std::min<uint64_t>(buffer_size, end_offset - start_offset);
322 const auto bytes_read = fd->Read(buffer, read_size);
323 if (bytes_read < 0 || static_cast<size_t>(bytes_read) != read_size) {
324 PLOG(ERROR) << "Failed to read offset " << start_offset << " expected "
325 << read_size << " bytes, actual: " << bytes_read;
326 Cleanup(ErrorCode::kFilesystemVerifierError);
327 return;
328 }
329 if (!hasher_->Update(buffer, read_size)) {
330 LOG(ERROR) << "Hasher updated failed on offset" << start_offset;
331 Cleanup(ErrorCode::kFilesystemVerifierError);
332 return;
333 }
334 const auto progress = (start_offset + bytes_read) * 1.0f / partition_size_;
335 // If we are writing verity, then the progress bar will be split between
336 // verity writes and partition hashing. Otherwise, the entire progress bar is
337 // dedicated to partition hashing for smooth progress.
338 if (ShouldWriteVerity()) {
339 UpdatePartitionProgress(
340 progress * (1 - (kVerityProgressPercent + kEncodeFECPercent)) +
341 kVerityProgressPercent + kEncodeFECPercent);
342 } else {
343 UpdatePartitionProgress(progress);
344 }
345 CHECK(pending_task_id_.PostTask(
346 FROM_HERE,
347 base::BindOnce(&FilesystemVerifierAction::HashPartition,
348 base::Unretained(this),
349 start_offset + bytes_read,
350 end_offset,
351 buffer,
352 buffer_size)));
353 }
354
StartPartitionHashing()355 void FilesystemVerifierAction::StartPartitionHashing() {
356 if (partition_index_ == install_plan_.partitions.size()) {
357 if (!install_plan_.untouched_dynamic_partitions.empty()) {
358 LOG(INFO) << "Verifying extents of untouched dynamic partitions ["
359 << android::base::Join(
360 install_plan_.untouched_dynamic_partitions, ", ")
361 << "]";
362 if (!dynamic_control_->VerifyExtentsForUntouchedPartitions(
363 install_plan_.source_slot,
364 install_plan_.target_slot,
365 install_plan_.untouched_dynamic_partitions)) {
366 Cleanup(ErrorCode::kFilesystemVerifierError);
367 return;
368 }
369 }
370
371 Cleanup(ErrorCode::kSuccess);
372 return;
373 }
374 const InstallPlan::Partition& partition =
375 install_plan_.partitions[partition_index_];
376 const auto& part_path = GetPartitionPath();
377 partition_size_ = GetPartitionSize();
378
379 LOG(INFO) << "Hashing partition " << partition_index_ << " ("
380 << partition.name << ") on device " << part_path;
381 auto success = false;
382 if (IsVABC(partition)) {
383 success = InitializeFdVABC(ShouldWriteVerity());
384 } else {
385 if (part_path.empty()) {
386 if (partition_size_ == 0) {
387 LOG(INFO) << "Skip hashing partition " << partition_index_ << " ("
388 << partition.name << ") because size is 0.";
389 partition_index_++;
390 StartPartitionHashing();
391 return;
392 }
393 LOG(ERROR) << "Cannot hash partition " << partition_index_ << " ("
394 << partition.name
395 << ") because its device path cannot be determined.";
396 Cleanup(ErrorCode::kFilesystemVerifierError);
397 return;
398 }
399 success = InitializeFd(part_path);
400 }
401 if (!success) {
402 Cleanup(ErrorCode::kFilesystemVerifierError);
403 return;
404 }
405 buffer_.resize(kReadFileBufferSize);
406 hasher_ = std::make_unique<HashCalculator>();
407
408 filesystem_data_end_ = partition_size_;
409 if (partition.fec_offset > 0) {
410 CHECK_LE(partition.hash_tree_offset, partition.fec_offset)
411 << " Hash tree is expected to come before FEC data";
412 }
413 CHECK_NE(partition_fd_, nullptr);
414 if (partition.hash_tree_offset != 0) {
415 filesystem_data_end_ = partition.hash_tree_offset;
416 } else if (partition.fec_offset != 0) {
417 filesystem_data_end_ = partition.fec_offset;
418 }
419 if (ShouldWriteVerity()) {
420 LOG(INFO) << "Verity writes enabled on partition " << partition.name;
421 if (!verity_writer_->Init(partition)) {
422 LOG(INFO) << "Verity writes enabled on partition " << partition.name;
423 Cleanup(ErrorCode::kVerityCalculationError);
424 return;
425 }
426 WriteVerityAndHashPartition(
427 0, filesystem_data_end_, buffer_.data(), buffer_.size());
428 } else {
429 LOG(INFO) << "Verity writes disabled on partition " << partition.name;
430 HashPartition(0, partition_size_, buffer_.data(), buffer_.size());
431 }
432 }
433
IsVABC(const InstallPlan::Partition & partition) const434 bool FilesystemVerifierAction::IsVABC(
435 const InstallPlan::Partition& partition) const {
436 return dynamic_control_->UpdateUsesSnapshotCompression() &&
437 verifier_step_ == VerifierStep::kVerifyTargetHash &&
438 dynamic_control_->IsDynamicPartition(partition.name,
439 install_plan_.target_slot);
440 }
441
GetPartitionPath() const442 const std::string& FilesystemVerifierAction::GetPartitionPath() const {
443 const InstallPlan::Partition& partition =
444 install_plan_.partitions[partition_index_];
445 switch (verifier_step_) {
446 case VerifierStep::kVerifySourceHash:
447 return partition.source_path;
448 case VerifierStep::kVerifyTargetHash:
449 if (IsVABC(partition)) {
450 return partition.readonly_target_path;
451 } else {
452 return partition.target_path;
453 }
454 }
455 }
456
GetPartitionSize() const457 uint64_t FilesystemVerifierAction::GetPartitionSize() const {
458 const InstallPlan::Partition& partition =
459 install_plan_.partitions[partition_index_];
460 switch (verifier_step_) {
461 case VerifierStep::kVerifySourceHash:
462 return partition.source_size;
463 case VerifierStep::kVerifyTargetHash:
464 return partition.target_size;
465 }
466 }
467
ShouldWriteVerity()468 bool FilesystemVerifierAction::ShouldWriteVerity() {
469 const InstallPlan::Partition& partition =
470 install_plan_.partitions[partition_index_];
471 return verifier_step_ == VerifierStep::kVerifyTargetHash &&
472 install_plan_.write_verity &&
473 (partition.hash_tree_size > 0 || partition.fec_size > 0);
474 }
475
FinishPartitionHashing()476 void FilesystemVerifierAction::FinishPartitionHashing() {
477 if (!hasher_->Finalize()) {
478 LOG(ERROR) << "Unable to finalize the hash.";
479 Cleanup(ErrorCode::kError);
480 return;
481 }
482 const InstallPlan::Partition& partition =
483 install_plan_.partitions[partition_index_];
484 LOG(INFO) << "Hash of " << partition.name << ": "
485 << HexEncode(hasher_->raw_hash());
486
487 switch (verifier_step_) {
488 case VerifierStep::kVerifyTargetHash:
489 if (partition.target_hash != hasher_->raw_hash()) {
490 LOG(ERROR) << "New '" << partition.name
491 << "' partition verification failed.";
492 if (partition.source_hash.empty()) {
493 // No need to verify source if it is a full payload.
494 Cleanup(ErrorCode::kNewRootfsVerificationError);
495 return;
496 }
497 // If we have not verified source partition yet, now that the target
498 // partition does not match, and it's not a full payload, we need to
499 // switch to kVerifySourceHash step to check if it's because the
500 // source partition does not match either.
501 verifier_step_ = VerifierStep::kVerifySourceHash;
502 } else {
503 partition_index_++;
504 }
505 break;
506 case VerifierStep::kVerifySourceHash:
507 if (partition.source_hash != hasher_->raw_hash()) {
508 LOG(ERROR) << "Old '" << partition.name
509 << "' partition verification failed.";
510 LOG(ERROR) << "This is a server-side error due to mismatched delta"
511 << " update image!";
512 LOG(ERROR) << "The delta I've been given contains a " << partition.name
513 << " delta update that must be applied over a "
514 << partition.name << " with a specific checksum, but the "
515 << partition.name
516 << " we're starting with doesn't have that checksum! This"
517 " means that the delta I've been given doesn't match my"
518 " existing system. The "
519 << partition.name << " partition I have has hash: "
520 << Base64Encode(hasher_->raw_hash())
521 << " but the update expected me to have "
522 << Base64Encode(partition.source_hash) << " .";
523 LOG(INFO) << "To get the checksum of the " << partition.name
524 << " partition run this command: dd if="
525 << partition.source_path
526 << " bs=1M count=" << partition.source_size
527 << " iflag=count_bytes 2>/dev/null | openssl dgst -sha256 "
528 "-binary | openssl base64";
529 LOG(INFO) << "To get the checksum of partitions in a bin file, "
530 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
531 Cleanup(ErrorCode::kDownloadStateInitializationError);
532 return;
533 }
534 // The action will skip kVerifySourceHash step if target partition hash
535 // matches, if we are in this step, it means target hash does not match,
536 // and now that the source partition hash matches, we should set the
537 // error code to reflect the error in target partition. We only need to
538 // verify the source partition which the target hash does not match, the
539 // rest of the partitions don't matter.
540 Cleanup(ErrorCode::kNewRootfsVerificationError);
541 return;
542 }
543 // Start hashing the next partition, if any.
544 buffer_.clear();
545 if (partition_fd_) {
546 partition_fd_->Close();
547 partition_fd_.reset();
548 }
549 StartPartitionHashing();
550 }
551
552 } // namespace chromeos_update_engine
553