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