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 * This program verifies the integrity of the partitions after an A/B OTA
19 * update. It gets invoked by init, and will only perform the verification if
20 * it's the first boot post an A/B OTA update.
21 *
22 * Update_verifier relies on dm-verity to capture any corruption on the partitions
23 * being verified. And its behavior varies depending on the dm-verity mode.
24 * Upon detection of failures:
25 *   enforcing mode: dm-verity reboots the device
26 *   eio mode: dm-verity fails the read and update_verifier reboots the device
27 *   other mode: not supported and update_verifier reboots the device
28 *
29 * After a predefined number of failing boot attempts, the bootloader should
30 * mark the slot as unbootable and stops trying. Other dm-verity modes (
31 * for example, veritymode=EIO) are not accepted and simply lead to a
32 * verification failure.
33 *
34 * The current slot will be marked as having booted successfully if the
35 * verifier reaches the end after the verification.
36 */
37
38#include "update_verifier/update_verifier.h"
39
40#include <dirent.h>
41#include <errno.h>
42#include <fcntl.h>
43#include <stdio.h>
44#include <string.h>
45#include <unistd.h>
46
47#include <algorithm>
48#include <future>
49#include <string>
50#include <vector>
51
52#include <android-base/file.h>
53#include <android-base/logging.h>
54#include <android-base/parseint.h>
55#include <android-base/properties.h>
56#include <android-base/strings.h>
57#include <android-base/unique_fd.h>
58#include <android/hardware/boot/1.0/IBootControl.h>
59#include <cutils/android_reboot.h>
60
61#include "otautil/rangeset.h"
62
63using android::sp;
64using android::hardware::boot::V1_0::IBootControl;
65using android::hardware::boot::V1_0::BoolResult;
66using android::hardware::boot::V1_0::CommandResult;
67
68// Find directories in format of "/sys/block/dm-X".
69static int dm_name_filter(const dirent* de) {
70  if (android::base::StartsWith(de->d_name, "dm-")) {
71    return 1;
72  }
73  return 0;
74}
75
76static bool read_blocks(const std::string& partition, const std::string& range_str) {
77  if (partition != "system" && partition != "vendor" && partition != "product") {
78    LOG(ERROR) << "Invalid partition name \"" << partition << "\"";
79    return false;
80  }
81  // Iterate the content of "/sys/block/dm-X/dm/name". If it matches one of "system", "vendor" or
82  // "product", then dm-X is a dm-wrapped device for that target. We will later read all the
83  // ("cared") blocks from "/dev/block/dm-X" to ensure the target partition's integrity.
84  static constexpr auto DM_PATH_PREFIX = "/sys/block/";
85  dirent** namelist;
86  int n = scandir(DM_PATH_PREFIX, &namelist, dm_name_filter, alphasort);
87  if (n == -1) {
88    PLOG(ERROR) << "Failed to scan dir " << DM_PATH_PREFIX;
89    return false;
90  }
91  if (n == 0) {
92    LOG(ERROR) << "dm block device not found for " << partition;
93    return false;
94  }
95
96  static constexpr auto DM_PATH_SUFFIX = "/dm/name";
97  static constexpr auto DEV_PATH = "/dev/block/";
98  std::string dm_block_device;
99  while (n--) {
100    std::string path = DM_PATH_PREFIX + std::string(namelist[n]->d_name) + DM_PATH_SUFFIX;
101    std::string content;
102    if (!android::base::ReadFileToString(path, &content)) {
103      PLOG(WARNING) << "Failed to read " << path;
104    } else {
105      std::string dm_block_name = android::base::Trim(content);
106#ifdef BOARD_AVB_ENABLE
107      // AVB is using 'vroot' for the root block device but we're expecting 'system'.
108      if (dm_block_name == "vroot") {
109        dm_block_name = "system";
110      }
111#endif
112      if (dm_block_name == partition) {
113        dm_block_device = DEV_PATH + std::string(namelist[n]->d_name);
114        while (n--) {
115          free(namelist[n]);
116        }
117        break;
118      }
119    }
120    free(namelist[n]);
121  }
122  free(namelist);
123
124  if (dm_block_device.empty()) {
125    LOG(ERROR) << "Failed to find dm block device for " << partition;
126    return false;
127  }
128
129  // For block range string, first integer 'count' equals 2 * total number of valid ranges,
130  // followed by 'count' number comma separated integers. Every two integers reprensent a
131  // block range with the first number included in range but second number not included.
132  // For example '4,64536,65343,74149,74150' represents: [64536,65343) and [74149,74150).
133  RangeSet ranges = RangeSet::Parse(range_str);
134  if (!ranges) {
135    LOG(ERROR) << "Error parsing RangeSet string " << range_str;
136    return false;
137  }
138
139  // RangeSet::Split() splits the ranges into multiple groups with same number of blocks (except for
140  // the last group).
141  size_t thread_num = std::thread::hardware_concurrency() ?: 4;
142  std::vector<RangeSet> groups = ranges.Split(thread_num);
143
144  std::vector<std::future<bool>> threads;
145  for (const auto& group : groups) {
146    auto thread_func = [&group, &dm_block_device, &partition]() {
147      android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dm_block_device.c_str(), O_RDONLY)));
148      if (fd.get() == -1) {
149        PLOG(ERROR) << "Error reading " << dm_block_device << " for partition " << partition;
150        return false;
151      }
152
153      static constexpr size_t kBlockSize = 4096;
154      std::vector<uint8_t> buf(1024 * kBlockSize);
155
156      size_t block_count = 0;
157      for (const auto& range : group) {
158        size_t range_start = range.first;
159        size_t range_end = range.second;
160        if (lseek64(fd.get(), static_cast<off64_t>(range_start) * kBlockSize, SEEK_SET) == -1) {
161          PLOG(ERROR) << "lseek to " << range_start << " failed";
162          return false;
163        }
164
165        size_t remain = (range_end - range_start) * kBlockSize;
166        while (remain > 0) {
167          size_t to_read = std::min(remain, 1024 * kBlockSize);
168          if (!android::base::ReadFully(fd.get(), buf.data(), to_read)) {
169            PLOG(ERROR) << "Failed to read blocks " << range_start << " to " << range_end;
170            return false;
171          }
172          remain -= to_read;
173        }
174        block_count += (range_end - range_start);
175      }
176      LOG(INFO) << "Finished reading " << block_count << " blocks on " << dm_block_device;
177      return true;
178    };
179
180    threads.emplace_back(std::async(std::launch::async, thread_func));
181  }
182
183  bool ret = true;
184  for (auto& t : threads) {
185    ret = t.get() && ret;
186  }
187  LOG(INFO) << "Finished reading blocks on " << dm_block_device << " with " << thread_num
188            << " threads.";
189  return ret;
190}
191
192// Returns true to indicate a passing verification (or the error should be ignored); Otherwise
193// returns false on fatal errors, where we should reject the current boot and trigger a fallback.
194// Note that update_verifier should be backward compatible to not reject care_map.txt from old
195// releases, which could otherwise fail to boot into the new release. For example, we've changed
196// the care_map format between N and O. An O update_verifier would fail to work with N
197// care_map.txt. This could be a result of sideloading an O OTA while the device having a pending N
198// update.
199bool verify_image(const std::string& care_map_name) {
200  android::base::unique_fd care_map_fd(TEMP_FAILURE_RETRY(open(care_map_name.c_str(), O_RDONLY)));
201  // If the device is flashed before the current boot, it may not have care_map.txt
202  // in /data/ota_package. To allow the device to continue booting in this situation,
203  // we should print a warning and skip the block verification.
204  if (care_map_fd.get() == -1) {
205    PLOG(WARNING) << "Failed to open " << care_map_name;
206    return true;
207  }
208  // care_map file has up to six lines, where every two lines make a pair. Within each pair, the
209  // first line has the partition name (e.g. "system"), while the second line holds the ranges of
210  // all the blocks to verify.
211  std::string file_content;
212  if (!android::base::ReadFdToString(care_map_fd.get(), &file_content)) {
213    LOG(ERROR) << "Error reading care map contents to string.";
214    return false;
215  }
216
217  std::vector<std::string> lines;
218  lines = android::base::Split(android::base::Trim(file_content), "\n");
219  if (lines.size() != 2 && lines.size() != 4 && lines.size() != 6) {
220    LOG(ERROR) << "Invalid lines in care_map: found " << lines.size()
221               << " lines, expecting 2 or 4 or 6 lines.";
222    return false;
223  }
224
225  for (size_t i = 0; i < lines.size(); i += 2) {
226    // We're seeing an N care_map.txt. Skip the verification since it's not compatible with O
227    // update_verifier (the last few metadata blocks can't be read via device mapper).
228    if (android::base::StartsWith(lines[i], "/dev/block/")) {
229      LOG(WARNING) << "Found legacy care_map.txt; skipped.";
230      return true;
231    }
232    if (!read_blocks(lines[i], lines[i+1])) {
233      return false;
234    }
235  }
236
237  return true;
238}
239
240static int reboot_device() {
241  if (android_reboot(ANDROID_RB_RESTART2, 0, nullptr) == -1) {
242    LOG(ERROR) << "Failed to reboot.";
243    return -1;
244  }
245  while (true) pause();
246}
247
248int update_verifier(int argc, char** argv) {
249  for (int i = 1; i < argc; i++) {
250    LOG(INFO) << "Started with arg " << i << ": " << argv[i];
251  }
252
253  sp<IBootControl> module = IBootControl::getService();
254  if (module == nullptr) {
255    LOG(ERROR) << "Error getting bootctrl module.";
256    return reboot_device();
257  }
258
259  uint32_t current_slot = module->getCurrentSlot();
260  BoolResult is_successful = module->isSlotMarkedSuccessful(current_slot);
261  LOG(INFO) << "Booting slot " << current_slot << ": isSlotMarkedSuccessful="
262            << static_cast<int32_t>(is_successful);
263
264  if (is_successful == BoolResult::FALSE) {
265    // The current slot has not booted successfully.
266
267#if defined(PRODUCT_SUPPORTS_VERITY) || defined(BOARD_AVB_ENABLE)
268    bool skip_verification = false;
269    std::string verity_mode = android::base::GetProperty("ro.boot.veritymode", "");
270    if (verity_mode.empty()) {
271      // With AVB it's possible to disable verification entirely and
272      // in this case ro.boot.veritymode is empty.
273#if defined(BOARD_AVB_ENABLE)
274      LOG(WARNING) << "verification has been disabled; marking without verification.";
275      skip_verification = true;
276#else
277      LOG(ERROR) << "Failed to get dm-verity mode.";
278      return reboot_device();
279#endif
280    } else if (android::base::EqualsIgnoreCase(verity_mode, "eio")) {
281      // We shouldn't see verity in EIO mode if the current slot hasn't booted successfully before.
282      // Continue the verification until we fail to read some blocks.
283      LOG(WARNING) << "Found dm-verity in EIO mode.";
284    } else if (android::base::EqualsIgnoreCase(verity_mode, "disabled")) {
285      LOG(WARNING) << "dm-verity in disabled mode; marking without verification.";
286      skip_verification = true;
287    } else if (verity_mode != "enforcing") {
288      LOG(ERROR) << "Unexpected dm-verity mode : " << verity_mode << ", expecting enforcing.";
289      return reboot_device();
290    }
291
292    if (!skip_verification) {
293      static constexpr auto CARE_MAP_FILE = "/data/ota_package/care_map.txt";
294      if (!verify_image(CARE_MAP_FILE)) {
295        LOG(ERROR) << "Failed to verify all blocks in care map file.";
296        return reboot_device();
297      }
298    }
299#else
300    LOG(WARNING) << "dm-verity not enabled; marking without verification.";
301#endif
302
303    CommandResult cr;
304    module->markBootSuccessful([&cr](CommandResult result) { cr = result; });
305    if (!cr.success) {
306      LOG(ERROR) << "Error marking booted successfully: " << cr.errMsg;
307      return reboot_device();
308    }
309    LOG(INFO) << "Marked slot " << current_slot << " as booted successfully.";
310  }
311
312  LOG(INFO) << "Leaving update_verifier.";
313  return 0;
314}
315