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
24 #include <algorithm>
25 #include <cstdlib>
26 #include <string>
27
28 #include <base/bind.h>
29 #include <brillo/data_encoding.h>
30 #include <brillo/streams/file_stream.h>
31
32 #include "update_engine/common/boot_control_interface.h"
33 #include "update_engine/common/utils.h"
34 #include "update_engine/payload_consumer/delta_performer.h"
35 #include "update_engine/payload_consumer/payload_constants.h"
36
37 using std::string;
38
39 namespace chromeos_update_engine {
40
41 namespace {
42 const off_t kReadFileBufferSize = 128 * 1024;
43
StringForHashBytes(const brillo::Blob & hash)44 string StringForHashBytes(const brillo::Blob& hash) {
45 return brillo::data_encoding::Base64Encode(hash.data(), hash.size());
46 }
47 } // namespace
48
PerformAction()49 void FilesystemVerifierAction::PerformAction() {
50 // Will tell the ActionProcessor we've failed if we return.
51 ScopedActionCompleter abort_action_completer(processor_, this);
52
53 if (!HasInputObject()) {
54 LOG(ERROR) << "FilesystemVerifierAction missing input object.";
55 return;
56 }
57 install_plan_ = GetInputObject();
58
59 if (install_plan_.partitions.empty()) {
60 LOG(INFO) << "No partitions to verify.";
61 if (HasOutputPipe())
62 SetOutputObject(install_plan_);
63 abort_action_completer.set_code(ErrorCode::kSuccess);
64 return;
65 }
66
67 StartPartitionHashing();
68 abort_action_completer.set_should_complete(false);
69 }
70
TerminateProcessing()71 void FilesystemVerifierAction::TerminateProcessing() {
72 cancelled_ = true;
73 Cleanup(ErrorCode::kSuccess); // error code is ignored if canceled_ is true.
74 }
75
IsCleanupPending() const76 bool FilesystemVerifierAction::IsCleanupPending() const {
77 return src_stream_ != nullptr;
78 }
79
Cleanup(ErrorCode code)80 void FilesystemVerifierAction::Cleanup(ErrorCode code) {
81 src_stream_.reset();
82 // This memory is not used anymore.
83 buffer_.clear();
84
85 if (cancelled_)
86 return;
87 if (code == ErrorCode::kSuccess && HasOutputPipe())
88 SetOutputObject(install_plan_);
89 processor_->ActionComplete(this, code);
90 }
91
StartPartitionHashing()92 void FilesystemVerifierAction::StartPartitionHashing() {
93 if (partition_index_ == install_plan_.partitions.size()) {
94 Cleanup(ErrorCode::kSuccess);
95 return;
96 }
97 InstallPlan::Partition& partition =
98 install_plan_.partitions[partition_index_];
99
100 string part_path;
101 switch (verifier_step_) {
102 case VerifierStep::kVerifySourceHash:
103 part_path = partition.source_path;
104 remaining_size_ = partition.source_size;
105 break;
106 case VerifierStep::kVerifyTargetHash:
107 part_path = partition.target_path;
108 remaining_size_ = partition.target_size;
109 break;
110 }
111 LOG(INFO) << "Hashing partition " << partition_index_ << " ("
112 << partition.name << ") on device " << part_path;
113 if (part_path.empty())
114 return Cleanup(ErrorCode::kFilesystemVerifierError);
115
116 brillo::ErrorPtr error;
117 src_stream_ = brillo::FileStream::Open(
118 base::FilePath(part_path),
119 brillo::Stream::AccessMode::READ,
120 brillo::FileStream::Disposition::OPEN_EXISTING,
121 &error);
122
123 if (!src_stream_) {
124 LOG(ERROR) << "Unable to open " << part_path << " for reading";
125 return Cleanup(ErrorCode::kFilesystemVerifierError);
126 }
127
128 buffer_.resize(kReadFileBufferSize);
129 read_done_ = false;
130 hasher_.reset(new HashCalculator());
131
132 // Start the first read.
133 ScheduleRead();
134 }
135
ScheduleRead()136 void FilesystemVerifierAction::ScheduleRead() {
137 size_t bytes_to_read = std::min(static_cast<int64_t>(buffer_.size()),
138 remaining_size_);
139 if (!bytes_to_read) {
140 OnReadDoneCallback(0);
141 return;
142 }
143
144 bool read_async_ok = src_stream_->ReadAsync(
145 buffer_.data(),
146 bytes_to_read,
147 base::Bind(&FilesystemVerifierAction::OnReadDoneCallback,
148 base::Unretained(this)),
149 base::Bind(&FilesystemVerifierAction::OnReadErrorCallback,
150 base::Unretained(this)),
151 nullptr);
152
153 if (!read_async_ok) {
154 LOG(ERROR) << "Unable to schedule an asynchronous read from the stream.";
155 Cleanup(ErrorCode::kError);
156 }
157 }
158
OnReadDoneCallback(size_t bytes_read)159 void FilesystemVerifierAction::OnReadDoneCallback(size_t bytes_read) {
160 if (bytes_read == 0) {
161 read_done_ = true;
162 } else {
163 remaining_size_ -= bytes_read;
164 CHECK(!read_done_);
165 if (!hasher_->Update(buffer_.data(), bytes_read)) {
166 LOG(ERROR) << "Unable to update the hash.";
167 Cleanup(ErrorCode::kError);
168 return;
169 }
170 }
171
172 // We either terminate the current partition or have more data to read.
173 if (cancelled_)
174 return Cleanup(ErrorCode::kError);
175
176 if (read_done_ || remaining_size_ == 0) {
177 if (remaining_size_ != 0) {
178 LOG(ERROR) << "Failed to read the remaining " << remaining_size_
179 << " bytes from partition "
180 << install_plan_.partitions[partition_index_].name;
181 return Cleanup(ErrorCode::kFilesystemVerifierError);
182 }
183 return FinishPartitionHashing();
184 }
185 ScheduleRead();
186 }
187
OnReadErrorCallback(const brillo::Error * error)188 void FilesystemVerifierAction::OnReadErrorCallback(
189 const brillo::Error* error) {
190 // TODO(deymo): Transform the read-error into an specific ErrorCode.
191 LOG(ERROR) << "Asynchronous read failed.";
192 Cleanup(ErrorCode::kError);
193 }
194
FinishPartitionHashing()195 void FilesystemVerifierAction::FinishPartitionHashing() {
196 if (!hasher_->Finalize()) {
197 LOG(ERROR) << "Unable to finalize the hash.";
198 return Cleanup(ErrorCode::kError);
199 }
200 InstallPlan::Partition& partition =
201 install_plan_.partitions[partition_index_];
202 LOG(INFO) << "Hash of " << partition.name << ": " << hasher_->hash();
203
204 switch (verifier_step_) {
205 case VerifierStep::kVerifyTargetHash:
206 if (partition.target_hash != hasher_->raw_hash()) {
207 LOG(ERROR) << "New '" << partition.name
208 << "' partition verification failed.";
209 if (install_plan_.payload_type == InstallPayloadType::kFull)
210 return Cleanup(ErrorCode::kNewRootfsVerificationError);
211 // If we have not verified source partition yet, now that the target
212 // partition does not match, and it's not a full payload, we need to
213 // switch to kVerifySourceHash step to check if it's because the source
214 // partition does not match either.
215 verifier_step_ = VerifierStep::kVerifySourceHash;
216 } else {
217 partition_index_++;
218 }
219 break;
220 case VerifierStep::kVerifySourceHash:
221 if (partition.source_hash != hasher_->raw_hash()) {
222 LOG(ERROR) << "Old '" << partition.name
223 << "' partition verification failed.";
224 LOG(ERROR) << "This is a server-side error due to mismatched delta"
225 << " update image!";
226 LOG(ERROR) << "The delta I've been given contains a " << partition.name
227 << " delta update that must be applied over a "
228 << partition.name << " with a specific checksum, but the "
229 << partition.name
230 << " we're starting with doesn't have that checksum! This"
231 " means that the delta I've been given doesn't match my"
232 " existing system. The "
233 << partition.name << " partition I have has hash: "
234 << StringForHashBytes(hasher_->raw_hash())
235 << " but the update expected me to have "
236 << StringForHashBytes(partition.source_hash) << " .";
237 LOG(INFO) << "To get the checksum of the " << partition.name
238 << " partition run this command: dd if="
239 << partition.source_path
240 << " bs=1M count=" << partition.source_size
241 << " iflag=count_bytes 2>/dev/null | openssl dgst -sha256 "
242 "-binary | openssl base64";
243 LOG(INFO) << "To get the checksum of partitions in a bin file, "
244 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
245 return Cleanup(ErrorCode::kDownloadStateInitializationError);
246 }
247 // The action will skip kVerifySourceHash step if target partition hash
248 // matches, if we are in this step, it means target hash does not match,
249 // and now that the source partition hash matches, we should set the error
250 // code to reflect the error in target partition.
251 // We only need to verify the source partition which the target hash does
252 // not match, the rest of the partitions don't matter.
253 return Cleanup(ErrorCode::kNewRootfsVerificationError);
254 }
255 // Start hashing the next partition, if any.
256 hasher_.reset();
257 buffer_.clear();
258 src_stream_->CloseBlocking(nullptr);
259 StartPartitionHashing();
260 }
261
262 } // namespace chromeos_update_engine
263