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