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 "update_engine/common/utils.h"
40 #include "update_engine/payload_consumer/file_descriptor.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.6;
81 } // namespace
82
PerformAction()83 void FilesystemVerifierAction::PerformAction() {
84 // Will tell the ActionProcessor we've failed if we return.
85 ScopedActionCompleter abort_action_completer(processor_, this);
86
87 if (!HasInputObject()) {
88 LOG(ERROR) << "FilesystemVerifierAction missing input object.";
89 return;
90 }
91 install_plan_ = GetInputObject();
92
93 if (install_plan_.partitions.empty()) {
94 LOG(INFO) << "No partitions to verify.";
95 if (HasOutputPipe())
96 SetOutputObject(install_plan_);
97 abort_action_completer.set_code(ErrorCode::kSuccess);
98 return;
99 }
100 install_plan_.Dump();
101 StartPartitionHashing();
102 abort_action_completer.set_should_complete(false);
103 }
104
TerminateProcessing()105 void FilesystemVerifierAction::TerminateProcessing() {
106 cancelled_ = true;
107 Cleanup(ErrorCode::kSuccess); // error code is ignored if canceled_ is true.
108 }
109
Cleanup(ErrorCode code)110 void FilesystemVerifierAction::Cleanup(ErrorCode code) {
111 partition_fd_.reset();
112 // This memory is not used anymore.
113 buffer_.clear();
114
115 // If we didn't write verity, partitions were maped. Releaase resource now.
116 if (!install_plan_.write_verity &&
117 dynamic_control_->UpdateUsesSnapshotCompression()) {
118 LOG(INFO) << "Not writing verity and VABC is enabled, unmapping all "
119 "partitions";
120 dynamic_control_->UnmapAllPartitions();
121 }
122
123 if (cancelled_)
124 return;
125 if (code == ErrorCode::kSuccess && HasOutputPipe())
126 SetOutputObject(install_plan_);
127 UpdateProgress(1.0);
128 processor_->ActionComplete(this, code);
129 }
130
UpdateProgress(double progress)131 void FilesystemVerifierAction::UpdateProgress(double progress) {
132 if (delegate_ != nullptr) {
133 delegate_->OnVerifyProgressUpdate(progress);
134 }
135 }
136
UpdatePartitionProgress(double progress)137 void FilesystemVerifierAction::UpdatePartitionProgress(double progress) {
138 // We don't consider sizes of each partition. Every partition
139 // has the same length on progress bar.
140 // TODO(b/186087589): Take sizes of each partition into account.
141 UpdateProgress((progress + partition_index_) /
142 install_plan_.partitions.size());
143 }
144
InitializeFdVABC(bool should_write_verity)145 bool FilesystemVerifierAction::InitializeFdVABC(bool should_write_verity) {
146 const InstallPlan::Partition& partition =
147 install_plan_.partitions[partition_index_];
148
149 if (!should_write_verity) {
150 // In VABC, we cannot map/unmap partitions w/o first closing ALL fds first.
151 // Since this function might be called inside a ScheduledTask, the closure
152 // might have a copy of partition_fd_ when executing this function. Which
153 // means even if we do |partition_fd_.reset()| here, there's a chance that
154 // underlying fd isn't closed until we return. This is unacceptable, we need
155 // to close |partition_fd| right away.
156 if (partition_fd_) {
157 partition_fd_->Close();
158 partition_fd_.reset();
159 }
160 // In VABC, if we are not writing verity, just map all partitions,
161 // and read using regular fd on |postinstall_mount_device| .
162 // All read will go through snapuserd, which provides a consistent
163 // view: device will use snapuserd to read partition during boot.
164 // b/186196758
165 // Call UnmapAllPartitions() first, because if we wrote verity before, these
166 // writes won't be visible to previously opened snapuserd daemon. To ensure
167 // that we will see the most up to date data from partitions, call Unmap()
168 // then Map() to re-spin daemon.
169 dynamic_control_->UnmapAllPartitions();
170 dynamic_control_->MapAllPartitions();
171 return InitializeFd(partition.readonly_target_path);
172 }
173 partition_fd_ =
174 dynamic_control_->OpenCowFd(partition.name, partition.source_path, true);
175 if (!partition_fd_) {
176 LOG(ERROR) << "OpenCowReader(" << partition.name << ", "
177 << partition.source_path << ") failed.";
178 return false;
179 }
180 partition_size_ = partition.target_size;
181 return true;
182 }
183
InitializeFd(const std::string & part_path)184 bool FilesystemVerifierAction::InitializeFd(const std::string& part_path) {
185 partition_fd_ = std::make_unique<EintrSafeFileDescriptor>();
186 const bool write_verity = ShouldWriteVerity();
187 int flags = write_verity ? O_RDWR : O_RDONLY;
188 if (!utils::SetBlockDeviceReadOnly(part_path, !write_verity)) {
189 LOG(WARNING) << "Failed to set block device " << part_path << " as "
190 << (write_verity ? "writable" : "readonly");
191 }
192 if (!partition_fd_->Open(part_path.c_str(), flags)) {
193 LOG(ERROR) << "Unable to open " << part_path << " for reading.";
194 return false;
195 }
196 return true;
197 }
198
WriteVerityAndHashPartition(const off64_t start_offset,const off64_t end_offset,void * buffer,const size_t buffer_size)199 void FilesystemVerifierAction::WriteVerityAndHashPartition(
200 const off64_t start_offset,
201 const off64_t end_offset,
202 void* buffer,
203 const size_t buffer_size) {
204 auto fd = partition_fd_.get();
205 TEST_AND_RETURN(fd != nullptr);
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(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 start_offset + bytes_read,
254 end_offset,
255 buffer,
256 buffer_size)));
257 }
258
HashPartition(const off64_t start_offset,const off64_t end_offset,void * buffer,const size_t buffer_size)259 void FilesystemVerifierAction::HashPartition(const off64_t start_offset,
260 const off64_t end_offset,
261 void* buffer,
262 const size_t buffer_size) {
263 auto fd = partition_fd_.get();
264 TEST_AND_RETURN(fd != nullptr);
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 start_offset + bytes_read,
300 end_offset,
301 buffer,
302 buffer_size)));
303 }
304
StartPartitionHashing()305 void FilesystemVerifierAction::StartPartitionHashing() {
306 if (partition_index_ == install_plan_.partitions.size()) {
307 if (!install_plan_.untouched_dynamic_partitions.empty()) {
308 LOG(INFO) << "Verifying extents of untouched dynamic partitions ["
309 << base::JoinString(install_plan_.untouched_dynamic_partitions,
310 ", ")
311 << "]";
312 if (!dynamic_control_->VerifyExtentsForUntouchedPartitions(
313 install_plan_.source_slot,
314 install_plan_.target_slot,
315 install_plan_.untouched_dynamic_partitions)) {
316 Cleanup(ErrorCode::kFilesystemVerifierError);
317 return;
318 }
319 }
320
321 Cleanup(ErrorCode::kSuccess);
322 return;
323 }
324 const InstallPlan::Partition& partition =
325 install_plan_.partitions[partition_index_];
326 const auto& part_path = GetPartitionPath();
327 partition_size_ = GetPartitionSize();
328
329 LOG(INFO) << "Hashing partition " << partition_index_ << " ("
330 << partition.name << ") on device " << part_path;
331 auto success = false;
332 if (IsVABC(partition)) {
333 success = InitializeFdVABC(ShouldWriteVerity());
334 } else {
335 if (part_path.empty()) {
336 if (partition_size_ == 0) {
337 LOG(INFO) << "Skip hashing partition " << partition_index_ << " ("
338 << partition.name << ") because size is 0.";
339 partition_index_++;
340 StartPartitionHashing();
341 return;
342 }
343 LOG(ERROR) << "Cannot hash partition " << partition_index_ << " ("
344 << partition.name
345 << ") because its device path cannot be determined.";
346 Cleanup(ErrorCode::kFilesystemVerifierError);
347 return;
348 }
349 success = InitializeFd(part_path);
350 }
351 if (!success) {
352 Cleanup(ErrorCode::kFilesystemVerifierError);
353 return;
354 }
355 buffer_.resize(kReadFileBufferSize);
356 hasher_ = std::make_unique<HashCalculator>();
357
358 offset_ = 0;
359 filesystem_data_end_ = partition_size_;
360 if (partition.fec_offset > 0) {
361 CHECK_LE(partition.hash_tree_offset, partition.fec_offset)
362 << " Hash tree is expected to come before FEC data";
363 }
364 CHECK_NE(partition_fd_, nullptr);
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 0, filesystem_data_end_, buffer_.data(), buffer_.size());
379 } else {
380 LOG(INFO) << "Verity writes disabled on partition " << partition.name;
381 HashPartition(0, partition_size_, buffer_.data(), buffer_.size());
382 }
383 }
384
IsVABC(const InstallPlan::Partition & partition) const385 bool FilesystemVerifierAction::IsVABC(
386 const InstallPlan::Partition& partition) const {
387 return dynamic_control_->UpdateUsesSnapshotCompression() &&
388 verifier_step_ == VerifierStep::kVerifyTargetHash &&
389 dynamic_control_->IsDynamicPartition(partition.name,
390 install_plan_.target_slot);
391 }
392
GetPartitionPath() const393 const std::string& FilesystemVerifierAction::GetPartitionPath() const {
394 const InstallPlan::Partition& partition =
395 install_plan_.partitions[partition_index_];
396 switch (verifier_step_) {
397 case VerifierStep::kVerifySourceHash:
398 return partition.source_path;
399 case VerifierStep::kVerifyTargetHash:
400 if (IsVABC(partition)) {
401 return partition.readonly_target_path;
402 } else {
403 return partition.target_path;
404 }
405 }
406 }
407
GetPartitionSize() const408 size_t FilesystemVerifierAction::GetPartitionSize() const {
409 const InstallPlan::Partition& partition =
410 install_plan_.partitions[partition_index_];
411 switch (verifier_step_) {
412 case VerifierStep::kVerifySourceHash:
413 return partition.source_size;
414 case VerifierStep::kVerifyTargetHash:
415 return partition.target_size;
416 }
417 }
418
ShouldWriteVerity()419 bool FilesystemVerifierAction::ShouldWriteVerity() {
420 const InstallPlan::Partition& partition =
421 install_plan_.partitions[partition_index_];
422 return verifier_step_ == VerifierStep::kVerifyTargetHash &&
423 install_plan_.write_verity &&
424 (partition.hash_tree_size > 0 || partition.fec_size > 0);
425 }
426
FinishPartitionHashing()427 void FilesystemVerifierAction::FinishPartitionHashing() {
428 if (!hasher_->Finalize()) {
429 LOG(ERROR) << "Unable to finalize the hash.";
430 Cleanup(ErrorCode::kError);
431 return;
432 }
433 const InstallPlan::Partition& partition =
434 install_plan_.partitions[partition_index_];
435 LOG(INFO) << "Hash of " << partition.name << ": "
436 << HexEncode(hasher_->raw_hash());
437
438 switch (verifier_step_) {
439 case VerifierStep::kVerifyTargetHash:
440 if (partition.target_hash != hasher_->raw_hash()) {
441 LOG(ERROR) << "New '" << partition.name
442 << "' partition verification failed.";
443 if (partition.source_hash.empty()) {
444 // No need to verify source if it is a full payload.
445 Cleanup(ErrorCode::kNewRootfsVerificationError);
446 return;
447 }
448 // If we have not verified source partition yet, now that the target
449 // partition does not match, and it's not a full payload, we need to
450 // switch to kVerifySourceHash step to check if it's because the
451 // source partition does not match either.
452 verifier_step_ = VerifierStep::kVerifySourceHash;
453 } else {
454 partition_index_++;
455 }
456 break;
457 case VerifierStep::kVerifySourceHash:
458 if (partition.source_hash != hasher_->raw_hash()) {
459 LOG(ERROR) << "Old '" << partition.name
460 << "' partition verification failed.";
461 LOG(ERROR) << "This is a server-side error due to mismatched delta"
462 << " update image!";
463 LOG(ERROR) << "The delta I've been given contains a " << partition.name
464 << " delta update that must be applied over a "
465 << partition.name << " with a specific checksum, but the "
466 << partition.name
467 << " we're starting with doesn't have that checksum! This"
468 " means that the delta I've been given doesn't match my"
469 " existing system. The "
470 << partition.name << " partition I have has hash: "
471 << Base64Encode(hasher_->raw_hash())
472 << " but the update expected me to have "
473 << Base64Encode(partition.source_hash) << " .";
474 LOG(INFO) << "To get the checksum of the " << partition.name
475 << " partition run this command: dd if="
476 << partition.source_path
477 << " bs=1M count=" << partition.source_size
478 << " iflag=count_bytes 2>/dev/null | openssl dgst -sha256 "
479 "-binary | openssl base64";
480 LOG(INFO) << "To get the checksum of partitions in a bin file, "
481 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
482 Cleanup(ErrorCode::kDownloadStateInitializationError);
483 return;
484 }
485 // The action will skip kVerifySourceHash step if target partition hash
486 // matches, if we are in this step, it means target hash does not match,
487 // and now that the source partition hash matches, we should set the
488 // error code to reflect the error in target partition. We only need to
489 // verify the source partition which the target hash does not match, the
490 // rest of the partitions don't matter.
491 Cleanup(ErrorCode::kNewRootfsVerificationError);
492 return;
493 }
494 // Start hashing the next partition, if any.
495 buffer_.clear();
496 if (partition_fd_) {
497 partition_fd_->Close();
498 partition_fd_.reset();
499 }
500 StartPartitionHashing();
501 }
502
503 } // namespace chromeos_update_engine
504