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