1 /*
2  * Copyright (C) 2015 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 /*
18  * update_verifier verifies the integrity of the partitions after an A/B OTA update. It gets invoked
19  * by init, and will only perform the verification if it's the first boot post an A/B OTA update
20  * (https://source.android.com/devices/tech/ota/ab/#after_reboot).
21  *
22  * update_verifier relies on device-mapper-verity (dm-verity) to capture any corruption on the
23  * partitions being verified (https://source.android.com/security/verifiedboot). The verification
24  * will be skipped, if dm-verity is not enabled on the device.
25  *
26  * Upon detecting verification failures, the device will be rebooted, although the trigger of the
27  * reboot depends on the dm-verity mode.
28  *   enforcing mode: dm-verity reboots the device
29  *   eio mode: dm-verity fails the read and update_verifier reboots the device
30  *   other mode: not supported and update_verifier reboots the device
31  *
32  * All these reboots prevent the device from booting into a known corrupt state. If the device
33  * continuously fails to boot into the new slot, the bootloader should mark the slot as unbootable
34  * and trigger a fallback to the old slot.
35  *
36  * The current slot will be marked as having booted successfully if the verifier reaches the end
37  * after the verification.
38  */
39 
40 #include "update_verifier/update_verifier.h"
41 
42 #include <dirent.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include <algorithm>
52 #include <future>
53 #include <thread>
54 
55 #include <BootControlClient.h>
56 #include <android-base/chrono_utils.h>
57 #include <android-base/file.h>
58 #include <android-base/logging.h>
59 #include <android-base/parseint.h>
60 #include <android-base/properties.h>
61 #include <android-base/strings.h>
62 #include <android-base/unique_fd.h>
63 #include <android/os/IVold.h>
64 #include <binder/BinderService.h>
65 #include <binder/Status.h>
66 #include <cutils/android_reboot.h>
67 
68 #include "care_map.pb.h"
69 
70 // TODO(xunchang) remove the prefix and use a default path instead.
71 constexpr const char* kDefaultCareMapPrefix = "/data/ota_package/care_map";
72 
73 // Find directories in format of "/sys/block/dm-X".
dm_name_filter(const dirent * de)74 static int dm_name_filter(const dirent* de) {
75   if (android::base::StartsWith(de->d_name, "dm-")) {
76     return 1;
77   }
78   return 0;
79 }
80 
UpdateVerifier()81 UpdateVerifier::UpdateVerifier()
82     : care_map_prefix_(kDefaultCareMapPrefix),
83       property_reader_([](const std::string& id) { return android::base::GetProperty(id, ""); }) {}
84 
85 // Iterate the content of "/sys/block/dm-X/dm/name" and find all the dm-wrapped block devices.
86 // We will later read all the ("cared") blocks from "/dev/block/dm-X" to ensure the target
87 // partition's integrity.
FindDmPartitions()88 std::map<std::string, std::string> UpdateVerifier::FindDmPartitions() {
89   static constexpr auto DM_PATH_PREFIX = "/sys/block/";
90   dirent** namelist = nullptr;
91   int n = scandir(DM_PATH_PREFIX, &namelist, dm_name_filter, alphasort);
92   if (n == -1) {
93     PLOG(ERROR) << "Failed to scan dir " << DM_PATH_PREFIX;
94     return {};
95   }
96   if (n == 0) {
97     LOG(ERROR) << "No dm block device found.";
98     return {};
99   }
100 
101   static constexpr auto DM_PATH_SUFFIX = "/dm/name";
102   static constexpr auto DEV_PATH = "/dev/block/";
103   std::map<std::string, std::string> dm_block_devices;
104   while (n--) {
105     std::string path = DM_PATH_PREFIX + std::string(namelist[n]->d_name) + DM_PATH_SUFFIX;
106     std::string content;
107     if (!android::base::ReadFileToString(path, &content)) {
108       PLOG(WARNING) << "Failed to read " << path;
109     } else {
110       std::string dm_block_name = android::base::Trim(content);
111       // AVB is using 'vroot' for the root block device but we're expecting 'system'.
112       if (dm_block_name == "vroot") {
113         dm_block_name = "system";
114       } else if (android::base::EndsWith(dm_block_name, "-verity")) {
115         auto npos = dm_block_name.rfind("-verity");
116         dm_block_name = dm_block_name.substr(0, npos);
117       } else if (!android::base::GetProperty("ro.boot.avb_version", "").empty()) {
118         // Verified Boot 1.0 doesn't add a -verity suffix. On AVB 2 devices,
119         // if DAP is enabled, then a -verity suffix must be used to
120         // differentiate between dm-linear and dm-verity devices. If we get
121         // here, we're AVB 2 and looking at a non-verity partition.
122         continue;
123       }
124 
125       dm_block_devices.emplace(dm_block_name, DEV_PATH + std::string(namelist[n]->d_name));
126     }
127     free(namelist[n]);
128   }
129   free(namelist);
130 
131   return dm_block_devices;
132 }
133 
ReadBlocks(const std::string partition_name,const std::string & dm_block_device,const RangeSet & ranges)134 bool UpdateVerifier::ReadBlocks(const std::string partition_name,
135                                 const std::string& dm_block_device, const RangeSet& ranges) {
136   // RangeSet::Split() splits the ranges into multiple groups with same number of blocks (except for
137   // the last group).
138   size_t thread_num = std::thread::hardware_concurrency() ?: 4;
139   std::vector<RangeSet> groups = ranges.Split(thread_num);
140 
141   std::vector<std::future<bool>> threads;
142   for (const auto& group : groups) {
143     auto thread_func = [&group, &dm_block_device, &partition_name]() {
144       android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dm_block_device.c_str(), O_RDONLY)));
145       if (fd.get() == -1) {
146         PLOG(ERROR) << "Error reading " << dm_block_device << " for partition " << partition_name;
147         return false;
148       }
149 
150       static constexpr size_t kBlockSize = 4096;
151       std::vector<uint8_t> buf(1024 * kBlockSize);
152 
153       for (const auto& [range_start, range_end] : group) {
154         if (lseek64(fd.get(), static_cast<off64_t>(range_start) * kBlockSize, SEEK_SET) == -1) {
155           PLOG(ERROR) << "lseek to " << range_start << " failed";
156           return false;
157         }
158 
159         size_t remain = (range_end - range_start) * kBlockSize;
160         while (remain > 0) {
161           size_t to_read = std::min(remain, 1024 * kBlockSize);
162           if (!android::base::ReadFully(fd.get(), buf.data(), to_read)) {
163             PLOG(ERROR) << "Failed to read blocks " << range_start << " to " << range_end;
164             return false;
165           }
166           remain -= to_read;
167         }
168       }
169       return true;
170     };
171 
172     threads.emplace_back(std::async(std::launch::async, thread_func));
173   }
174 
175   bool ret = true;
176   for (auto& t : threads) {
177     ret = t.get() && ret;
178   }
179   LOG(INFO) << "Finished reading blocks on partition " << partition_name << " @ " << dm_block_device
180             << " with " << thread_num << " threads.";
181   return ret;
182 }
183 
CheckVerificationStatus()184 bool UpdateVerifier::CheckVerificationStatus() {
185   auto client =
186       android::snapshot::SnapuserdClient::Connect(android::snapshot::kSnapuserdSocket, 5s);
187   if (!client) {
188     LOG(ERROR) << "Unable to connect to snapuserd";
189     return false;
190   }
191 
192   return client->QueryUpdateVerification();
193 }
194 
VerifyPartitions()195 bool UpdateVerifier::VerifyPartitions() {
196   const bool userspace_snapshots =
197       android::base::GetBoolProperty("ro.virtual_ab.userspace.snapshots.enabled", false);
198 
199   if (userspace_snapshots && CheckVerificationStatus()) {
200     LOG(INFO) << "Partitions verified by snapuserd daemon";
201     return true;
202   }
203 
204   LOG(INFO) << "Partitions not verified by snapuserd daemon";
205 
206   auto dm_block_devices = FindDmPartitions();
207   if (dm_block_devices.empty()) {
208     LOG(ERROR) << "No dm-enabled block device is found.";
209     return false;
210   }
211 
212   for (const auto& [partition_name, ranges] : partition_map_) {
213     if (dm_block_devices.find(partition_name) == dm_block_devices.end()) {
214       LOG(ERROR) << "Failed to find dm block device for " << partition_name;
215       return false;
216     }
217 
218     if (!ReadBlocks(partition_name, dm_block_devices.at(partition_name), ranges)) {
219       return false;
220     }
221   }
222 
223   return true;
224 }
225 
ParseCareMap()226 bool UpdateVerifier::ParseCareMap() {
227   partition_map_.clear();
228 
229   std::string care_map_name = care_map_prefix_ + ".pb";
230   if (access(care_map_name.c_str(), R_OK) == -1) {
231     LOG(ERROR) << care_map_name << " doesn't exist";
232     return false;
233   }
234 
235   android::base::unique_fd care_map_fd(TEMP_FAILURE_RETRY(open(care_map_name.c_str(), O_RDONLY)));
236   // If the device is flashed before the current boot, it may not have care_map.txt in
237   // /data/ota_package. To allow the device to continue booting in this situation, we should
238   // print a warning and skip the block verification.
239   if (care_map_fd.get() == -1) {
240     PLOG(WARNING) << "Failed to open " << care_map_name;
241     return false;
242   }
243 
244   std::string file_content;
245   if (!android::base::ReadFdToString(care_map_fd.get(), &file_content)) {
246     PLOG(WARNING) << "Failed to read " << care_map_name;
247     return false;
248   }
249 
250   if (file_content.empty()) {
251     LOG(WARNING) << "Unexpected empty care map";
252     return false;
253   }
254 
255   recovery_update_verifier::CareMap care_map;
256   if (!care_map.ParseFromString(file_content)) {
257     LOG(WARNING) << "Failed to parse " << care_map_name << " in protobuf format.";
258     return false;
259   }
260 
261   for (const auto& partition : care_map.partitions()) {
262     if (partition.name().empty()) {
263       LOG(WARNING) << "Unexpected empty partition name.";
264       return false;
265     }
266     if (partition.ranges().empty()) {
267       LOG(WARNING) << "Unexpected block ranges for partition " << partition.name();
268       return false;
269     }
270     RangeSet ranges = RangeSet::Parse(partition.ranges());
271     if (!ranges) {
272       LOG(WARNING) << "Error parsing RangeSet string " << partition.ranges();
273       return false;
274     }
275 
276     // Continues to check other partitions if there is a fingerprint mismatch.
277     if (partition.id().empty() || partition.id() == "unknown") {
278       LOG(WARNING) << "Skip reading partition " << partition.name()
279                    << ": property_id is not provided to get fingerprint.";
280       continue;
281     }
282 
283     std::string fingerprint = property_reader_(partition.id());
284     if (fingerprint != partition.fingerprint()) {
285       LOG(WARNING) << "Skip reading partition " << partition.name() << ": fingerprint "
286                    << fingerprint << " doesn't match the expected value "
287                    << partition.fingerprint();
288       continue;
289     }
290 
291     partition_map_.emplace(partition.name(), ranges);
292   }
293 
294   if (partition_map_.empty()) {
295     LOG(WARNING) << "No partition to verify";
296     return false;
297   }
298 
299   return true;
300 }
301 
set_care_map_prefix(const std::string & prefix)302 void UpdateVerifier::set_care_map_prefix(const std::string& prefix) {
303   care_map_prefix_ = prefix;
304 }
305 
set_property_reader(const std::function<std::string (const std::string &)> & property_reader)306 void UpdateVerifier::set_property_reader(
307     const std::function<std::string(const std::string&)>& property_reader) {
308   property_reader_ = property_reader;
309 }
310 
reboot_device()311 static int reboot_device() {
312   if (android_reboot(ANDROID_RB_RESTART2, 0, nullptr) == -1) {
313     LOG(ERROR) << "Failed to reboot.";
314     return -1;
315   }
316   while (true) pause();
317 }
318 
update_verifier(int argc,char ** argv)319 int update_verifier(int argc, char** argv) {
320   for (int i = 1; i < argc; i++) {
321     LOG(INFO) << "Started with arg " << i << ": " << argv[i];
322   }
323 
324   const auto module = android::hal::BootControlClient::WaitForService();
325   if (module == nullptr) {
326     LOG(ERROR) << "Error getting bootctrl module.";
327     return reboot_device();
328   }
329 
330   uint32_t current_slot = module->GetCurrentSlot();
331   const auto is_successful = module->IsSlotMarkedSuccessful(current_slot);
332   if (!is_successful.has_value()) {
333     LOG(INFO) << "Booting slot " << current_slot << " failed";
334   } else {
335     LOG(INFO) << "Booting slot " << current_slot
336               << ": isSlotMarkedSuccessful=" << is_successful.value();
337   }
338   if (is_successful.has_value() && !is_successful.value()) {
339     // The current slot has not booted successfully.
340 
341     bool skip_verification = false;
342     std::string verity_mode = android::base::GetProperty("ro.boot.veritymode", "");
343     if (verity_mode.empty()) {
344       // Skip the verification if ro.boot.veritymode property is not set. This could be a result
345       // that device doesn't support dm-verity, or has disabled that.
346       LOG(WARNING) << "dm-verity not enabled; marking without verification.";
347       skip_verification = true;
348     } else if (android::base::EqualsIgnoreCase(verity_mode, "eio")) {
349       // We shouldn't see verity in EIO mode if the current slot hasn't booted successfully before.
350       // Continue the verification until we fail to read some blocks.
351       LOG(WARNING) << "Found dm-verity in EIO mode.";
352     } else if (android::base::EqualsIgnoreCase(verity_mode, "disabled")) {
353       LOG(WARNING) << "dm-verity in disabled mode; marking without verification.";
354       skip_verification = true;
355     } else if (verity_mode != "enforcing") {
356       LOG(ERROR) << "Unexpected dm-verity mode: " << verity_mode << ", expecting enforcing.";
357       return reboot_device();
358     }
359 
360     if (!skip_verification) {
361       UpdateVerifier verifier;
362       if (!verifier.ParseCareMap()) {
363         LOG(WARNING) << "Failed to parse the care map file, skipping verification";
364       } else if (!verifier.VerifyPartitions()) {
365         LOG(ERROR) << "Failed to verify all blocks in care map file.";
366         return reboot_device();
367       }
368     }
369 
370     bool supports_checkpoint = false;
371     auto sm = android::defaultServiceManager();
372     android::sp<android::IBinder> binder = sm->getService(android::String16("vold"));
373     if (binder) {
374       auto vold = android::interface_cast<android::os::IVold>(binder);
375       android::binder::Status status = vold->supportsCheckpoint(&supports_checkpoint);
376       if (!status.isOk()) {
377         LOG(ERROR) << "Failed to check if checkpoints supported. Continuing";
378       }
379     } else {
380       LOG(ERROR) << "Failed to obtain vold Binder. Continuing";
381     }
382 
383     if (!supports_checkpoint) {
384       const auto cr = module->MarkBootSuccessful();
385       if (!cr.success) {
386         LOG(ERROR) << "Error marking booted successfully: " << cr.errMsg;
387         return reboot_device();
388       }
389       LOG(INFO) << "Marked slot " << current_slot << " as booted successfully.";
390       // Clears the warm reset flag for next reboot.
391       if (!android::base::SetProperty("ota.warm_reset", "0")) {
392         LOG(WARNING) << "Failed to reset the warm reset flag";
393       }
394     } else {
395       LOG(INFO) << "Deferred marking slot " << current_slot << " as booted successfully.";
396     }
397   }
398 
399   LOG(INFO) << "Leaving update_verifier.";
400   return 0;
401 }
402