fs_mgr_avb.cpp revision 1a898c25f96150787b39d9a08ebdb9ab6fcb3846
1/* 2 * Copyright (C) 2016 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 <errno.h> 18#include <fcntl.h> 19#include <inttypes.h> 20#include <libgen.h> 21#include <stdio.h> 22#include <string.h> 23#include <sys/stat.h> 24#include <sys/types.h> 25#include <unistd.h> 26#include <vector> 27 28#include <android-base/file.h> 29#include <android-base/parseint.h> 30#include <android-base/properties.h> 31#include <android-base/stringprintf.h> 32#include <android-base/strings.h> 33#include <android-base/unique_fd.h> 34#include <cutils/properties.h> 35#include <libavb/libavb.h> 36#include <openssl/sha.h> 37#include <sys/ioctl.h> 38#include <utils/Compat.h> 39 40#include "fs_mgr.h" 41#include "fs_mgr_avb.h" 42#include "fs_mgr_avb_ops.h" 43#include "fs_mgr_priv.h" 44#include "fs_mgr_priv_dm_ioctl.h" 45#include "fs_mgr_priv_sha.h" 46 47/* The format of dm-verity construction parameters: 48 * <version> <dev> <hash_dev> <data_block_size> <hash_block_size> 49 * <num_data_blocks> <hash_start_block> <algorithm> <digest> <salt> 50 */ 51#define VERITY_TABLE_FORMAT \ 52 "%u %s %s %u %u " \ 53 "%" PRIu64 " %" PRIu64 " %s %s %s " 54 55#define VERITY_TABLE_PARAMS(hashtree_desc, blk_device, digest, salt) \ 56 hashtree_desc.dm_verity_version, blk_device, blk_device, hashtree_desc.data_block_size, \ 57 hashtree_desc.hash_block_size, \ 58 hashtree_desc.image_size / hashtree_desc.data_block_size, /* num_data_blocks. */ \ 59 hashtree_desc.tree_offset / hashtree_desc.hash_block_size, /* hash_start_block. */ \ 60 (char*)hashtree_desc.hash_algorithm, digest, salt 61 62#define VERITY_TABLE_OPT_RESTART "restart_on_corruption" 63#define VERITY_TABLE_OPT_IGNZERO "ignore_zero_blocks" 64 65/* The default format of dm-verity optional parameters: 66 * <#opt_params> ignore_zero_blocks restart_on_corruption 67 */ 68#define VERITY_TABLE_OPT_DEFAULT_FORMAT "2 %s %s" 69#define VERITY_TABLE_OPT_DEFAULT_PARAMS VERITY_TABLE_OPT_IGNZERO, VERITY_TABLE_OPT_RESTART 70 71/* The FEC (forward error correction) format of dm-verity optional parameters: 72 * <#opt_params> use_fec_from_device <fec_dev> 73 * fec_roots <num> fec_blocks <num> fec_start <offset> 74 * ignore_zero_blocks restart_on_corruption 75 */ 76#define VERITY_TABLE_OPT_FEC_FORMAT \ 77 "10 use_fec_from_device %s fec_roots %u fec_blocks %" PRIu64 " fec_start %" PRIu64 " %s %s" 78 79/* Note that fec_blocks is the size that FEC covers, *not* the 80 * size of the FEC data. Since we use FEC for everything up until 81 * the FEC data, it's the same as the offset (fec_start). 82 */ 83#define VERITY_TABLE_OPT_FEC_PARAMS(hashtree_desc, blk_device) \ 84 blk_device, hashtree_desc.fec_num_roots, \ 85 hashtree_desc.fec_offset / hashtree_desc.data_block_size, /* fec_blocks */ \ 86 hashtree_desc.fec_offset / hashtree_desc.data_block_size, /* fec_start */ \ 87 VERITY_TABLE_OPT_IGNZERO, VERITY_TABLE_OPT_RESTART 88 89static inline bool nibble_value(const char& c, uint8_t* value) { 90 FS_MGR_CHECK(value != nullptr); 91 92 switch (c) { 93 case '0' ... '9': 94 *value = c - '0'; 95 break; 96 case 'a' ... 'f': 97 *value = c - 'a' + 10; 98 break; 99 case 'A' ... 'F': 100 *value = c - 'A' + 10; 101 break; 102 default: 103 return false; 104 } 105 106 return true; 107} 108 109static bool hex_to_bytes(uint8_t* bytes, size_t bytes_len, const std::string& hex) { 110 FS_MGR_CHECK(bytes != nullptr); 111 112 if (hex.size() % 2 != 0) { 113 return false; 114 } 115 if (hex.size() / 2 > bytes_len) { 116 return false; 117 } 118 for (size_t i = 0, j = 0, n = hex.size(); i < n; i += 2, ++j) { 119 uint8_t high; 120 if (!nibble_value(hex[i], &high)) { 121 return false; 122 } 123 uint8_t low; 124 if (!nibble_value(hex[i + 1], &low)) { 125 return false; 126 } 127 bytes[j] = (high << 4) | low; 128 } 129 return true; 130} 131 132static std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) { 133 FS_MGR_CHECK(bytes != nullptr); 134 135 static const char* hex_digits = "0123456789abcdef"; 136 std::string hex; 137 138 for (size_t i = 0; i < bytes_len; i++) { 139 hex.push_back(hex_digits[(bytes[i] & 0xF0) >> 4]); 140 hex.push_back(hex_digits[bytes[i] & 0x0F]); 141 } 142 return hex; 143} 144 145template <typename Hasher> 146static std::pair<size_t, bool> verify_vbmeta_digest(const AvbSlotVerifyData& verify_data, 147 const uint8_t* expected_digest) { 148 size_t total_size = 0; 149 Hasher hasher; 150 for (size_t n = 0; n < verify_data.num_vbmeta_images; n++) { 151 hasher.update(verify_data.vbmeta_images[n].vbmeta_data, 152 verify_data.vbmeta_images[n].vbmeta_size); 153 total_size += verify_data.vbmeta_images[n].vbmeta_size; 154 } 155 156 bool matched = (memcmp(hasher.finalize(), expected_digest, Hasher::DIGEST_SIZE) == 0); 157 158 return std::make_pair(total_size, matched); 159} 160 161// Reads the following values from kernel cmdline and provides the 162// VerifyVbmetaImages() to verify AvbSlotVerifyData. 163// - androidboot.vbmeta.device_state 164// - androidboot.vbmeta.hash_alg 165// - androidboot.vbmeta.size 166// - androidboot.vbmeta.digest 167class FsManagerAvbVerifier { 168 public: 169 // The factory method to return a unique_ptr<FsManagerAvbVerifier> 170 static std::unique_ptr<FsManagerAvbVerifier> Create(); 171 bool VerifyVbmetaImages(const AvbSlotVerifyData& verify_data); 172 bool IsDeviceUnlocked() { return is_device_unlocked_; } 173 174 protected: 175 FsManagerAvbVerifier() = default; 176 177 private: 178 enum HashAlgorithm { 179 kInvalid = 0, 180 kSHA256 = 1, 181 kSHA512 = 2, 182 }; 183 184 HashAlgorithm hash_alg_; 185 uint8_t digest_[SHA512_DIGEST_LENGTH]; 186 size_t vbmeta_size_; 187 bool is_device_unlocked_; 188}; 189 190std::unique_ptr<FsManagerAvbVerifier> FsManagerAvbVerifier::Create() { 191 std::string cmdline; 192 if (!android::base::ReadFileToString("/proc/cmdline", &cmdline)) { 193 LERROR << "Failed to read /proc/cmdline"; 194 return nullptr; 195 } 196 197 std::unique_ptr<FsManagerAvbVerifier> avb_verifier(new FsManagerAvbVerifier()); 198 if (!avb_verifier) { 199 LERROR << "Failed to create unique_ptr<FsManagerAvbVerifier>"; 200 return nullptr; 201 } 202 203 std::string digest; 204 std::string hash_alg; 205 for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) { 206 std::vector<std::string> pieces = android::base::Split(entry, "="); 207 const std::string& key = pieces[0]; 208 const std::string& value = pieces[1]; 209 210 if (key == "androidboot.vbmeta.device_state") { 211 avb_verifier->is_device_unlocked_ = (value == "unlocked"); 212 } else if (key == "androidboot.vbmeta.hash_alg") { 213 hash_alg = value; 214 } else if (key == "androidboot.vbmeta.size") { 215 if (!android::base::ParseUint(value.c_str(), &avb_verifier->vbmeta_size_)) { 216 return nullptr; 217 } 218 } else if (key == "androidboot.vbmeta.digest") { 219 digest = value; 220 } 221 } 222 223 // Reads hash algorithm. 224 size_t expected_digest_size = 0; 225 if (hash_alg == "sha256") { 226 expected_digest_size = SHA256_DIGEST_LENGTH * 2; 227 avb_verifier->hash_alg_ = kSHA256; 228 } else if (hash_alg == "sha512") { 229 expected_digest_size = SHA512_DIGEST_LENGTH * 2; 230 avb_verifier->hash_alg_ = kSHA512; 231 } else { 232 LERROR << "Unknown hash algorithm: " << hash_alg.c_str(); 233 return nullptr; 234 } 235 236 // Reads digest. 237 if (digest.size() != expected_digest_size) { 238 LERROR << "Unexpected digest size: " << digest.size() 239 << " (expected: " << expected_digest_size << ")"; 240 return nullptr; 241 } 242 243 if (!hex_to_bytes(avb_verifier->digest_, sizeof(avb_verifier->digest_), digest)) { 244 LERROR << "Hash digest contains non-hexidecimal character: " << digest.c_str(); 245 return nullptr; 246 } 247 248 return avb_verifier; 249} 250 251bool FsManagerAvbVerifier::VerifyVbmetaImages(const AvbSlotVerifyData& verify_data) { 252 if (verify_data.num_vbmeta_images == 0) { 253 LERROR << "No vbmeta images"; 254 return false; 255 } 256 257 size_t total_size = 0; 258 bool digest_matched = false; 259 260 if (hash_alg_ == kSHA256) { 261 std::tie(total_size, digest_matched) = 262 verify_vbmeta_digest<SHA256Hasher>(verify_data, digest_); 263 } else if (hash_alg_ == kSHA512) { 264 std::tie(total_size, digest_matched) = 265 verify_vbmeta_digest<SHA512Hasher>(verify_data, digest_); 266 } 267 268 if (total_size != vbmeta_size_) { 269 LERROR << "total vbmeta size mismatch: " << total_size << " (expected: " << vbmeta_size_ 270 << ")"; 271 return false; 272 } 273 274 if (!digest_matched) { 275 LERROR << "vbmeta digest mismatch"; 276 return false; 277 } 278 279 return true; 280} 281 282static bool hashtree_load_verity_table(struct dm_ioctl* io, const std::string& dm_device_name, 283 int fd, const std::string& blk_device, 284 const AvbHashtreeDescriptor& hashtree_desc, 285 const std::string& salt, const std::string& root_digest) { 286 fs_mgr_verity_ioctl_init(io, dm_device_name, DM_STATUS_TABLE_FLAG); 287 288 // The buffer consists of [dm_ioctl][dm_target_spec][verity_params]. 289 char* buffer = (char*)io; 290 291 // Builds the dm_target_spec arguments. 292 struct dm_target_spec* dm_target = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)]; 293 io->target_count = 1; 294 dm_target->status = 0; 295 dm_target->sector_start = 0; 296 dm_target->length = hashtree_desc.image_size / 512; 297 strcpy(dm_target->target_type, "verity"); 298 299 // Builds the verity params. 300 char* verity_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec); 301 size_t bufsize = DM_BUF_SIZE - (verity_params - buffer); 302 303 int res = 0; 304 if (hashtree_desc.fec_size > 0) { 305 res = snprintf(verity_params, bufsize, VERITY_TABLE_FORMAT VERITY_TABLE_OPT_FEC_FORMAT, 306 VERITY_TABLE_PARAMS(hashtree_desc, blk_device.c_str(), root_digest.c_str(), 307 salt.c_str()), 308 VERITY_TABLE_OPT_FEC_PARAMS(hashtree_desc, blk_device.c_str())); 309 } else { 310 res = snprintf(verity_params, bufsize, VERITY_TABLE_FORMAT VERITY_TABLE_OPT_DEFAULT_FORMAT, 311 VERITY_TABLE_PARAMS(hashtree_desc, blk_device.c_str(), root_digest.c_str(), 312 salt.c_str()), 313 VERITY_TABLE_OPT_DEFAULT_PARAMS); 314 } 315 316 if (res < 0 || (size_t)res >= bufsize) { 317 LERROR << "Error building verity table; insufficient buffer size?"; 318 return false; 319 } 320 321 LINFO << "Loading verity table: '" << verity_params << "'"; 322 323 // Sets ext target boundary. 324 verity_params += strlen(verity_params) + 1; 325 verity_params = (char*)(((unsigned long)verity_params + 7) & ~7); 326 dm_target->next = verity_params - buffer; 327 328 // Sends the ioctl to load the verity table. 329 if (ioctl(fd, DM_TABLE_LOAD, io)) { 330 PERROR << "Error loading verity table"; 331 return false; 332 } 333 334 return true; 335} 336 337static bool hashtree_dm_verity_setup(struct fstab_rec* fstab_entry, 338 const AvbHashtreeDescriptor& hashtree_desc, 339 const std::string& salt, const std::string& root_digest, 340 bool wait_for_verity_dev) { 341 // Gets the device mapper fd. 342 android::base::unique_fd fd(open("/dev/device-mapper", O_RDWR)); 343 if (fd < 0) { 344 PERROR << "Error opening device mapper"; 345 return false; 346 } 347 348 // Creates the device. 349 alignas(dm_ioctl) char buffer[DM_BUF_SIZE]; 350 struct dm_ioctl* io = (struct dm_ioctl*)buffer; 351 const std::string mount_point(basename(fstab_entry->mount_point)); 352 if (!fs_mgr_create_verity_device(io, mount_point, fd)) { 353 LERROR << "Couldn't create verity device!"; 354 return false; 355 } 356 357 // Gets the name of the device file. 358 std::string verity_blk_name; 359 if (!fs_mgr_get_verity_device_name(io, mount_point, fd, &verity_blk_name)) { 360 LERROR << "Couldn't get verity device number!"; 361 return false; 362 } 363 364 // Loads the verity mapping table. 365 if (!hashtree_load_verity_table(io, mount_point, fd, std::string(fstab_entry->blk_device), 366 hashtree_desc, salt, root_digest)) { 367 LERROR << "Couldn't load verity table!"; 368 return false; 369 } 370 371 // Activates the device. 372 if (!fs_mgr_resume_verity_table(io, mount_point, fd)) { 373 return false; 374 } 375 376 // Marks the underlying block device as read-only. 377 fs_mgr_set_blk_ro(fstab_entry->blk_device); 378 379 // Updates fstab_rec->blk_device to verity device name. 380 free(fstab_entry->blk_device); 381 fstab_entry->blk_device = strdup(verity_blk_name.c_str()); 382 383 // Makes sure we've set everything up properly. 384 if (wait_for_verity_dev && fs_mgr_test_access(verity_blk_name.c_str()) < 0) { 385 return false; 386 } 387 388 return true; 389} 390 391static bool get_hashtree_descriptor(const std::string& partition_name, 392 const AvbSlotVerifyData& verify_data, 393 AvbHashtreeDescriptor* out_hashtree_desc, std::string* out_salt, 394 std::string* out_digest) { 395 bool found = false; 396 const uint8_t* desc_partition_name; 397 398 for (size_t i = 0; i < verify_data.num_vbmeta_images && !found; i++) { 399 // Get descriptors from vbmeta_images[i]. 400 size_t num_descriptors; 401 std::unique_ptr<const AvbDescriptor* [], decltype(&avb_free)> descriptors( 402 avb_descriptor_get_all(verify_data.vbmeta_images[i].vbmeta_data, 403 verify_data.vbmeta_images[i].vbmeta_size, &num_descriptors), 404 avb_free); 405 406 if (!descriptors || num_descriptors < 1) { 407 continue; 408 } 409 410 // Ensures that hashtree descriptor is in /vbmeta or /boot or in 411 // the same partition for verity setup. 412 std::string vbmeta_partition_name(verify_data.vbmeta_images[i].partition_name); 413 if (vbmeta_partition_name != "vbmeta" && 414 vbmeta_partition_name != "boot" && // for legacy device to append top-level vbmeta 415 vbmeta_partition_name != partition_name) { 416 LWARNING << "Skip vbmeta image at " << verify_data.vbmeta_images[i].partition_name 417 << " for partition: " << partition_name.c_str(); 418 continue; 419 } 420 421 for (size_t j = 0; j < num_descriptors && !found; j++) { 422 AvbDescriptor desc; 423 if (!avb_descriptor_validate_and_byteswap(descriptors[j], &desc)) { 424 LWARNING << "Descriptor[" << j << "] is invalid"; 425 continue; 426 } 427 if (desc.tag == AVB_DESCRIPTOR_TAG_HASHTREE) { 428 desc_partition_name = (const uint8_t*)descriptors[j] + sizeof(AvbHashtreeDescriptor); 429 if (!avb_hashtree_descriptor_validate_and_byteswap( 430 (AvbHashtreeDescriptor*)descriptors[j], out_hashtree_desc)) { 431 continue; 432 } 433 if (out_hashtree_desc->partition_name_len != partition_name.length()) { 434 continue; 435 } 436 // Notes that desc_partition_name is not NUL-terminated. 437 std::string hashtree_partition_name((const char*)desc_partition_name, 438 out_hashtree_desc->partition_name_len); 439 if (hashtree_partition_name == partition_name) { 440 found = true; 441 } 442 } 443 } 444 } 445 446 if (!found) { 447 LERROR << "Partition descriptor not found: " << partition_name.c_str(); 448 return false; 449 } 450 451 const uint8_t* desc_salt = desc_partition_name + out_hashtree_desc->partition_name_len; 452 *out_salt = bytes_to_hex(desc_salt, out_hashtree_desc->salt_len); 453 454 const uint8_t* desc_digest = desc_salt + out_hashtree_desc->salt_len; 455 *out_digest = bytes_to_hex(desc_digest, out_hashtree_desc->root_digest_len); 456 457 return true; 458} 459 460FsManagerAvbUniquePtr FsManagerAvbHandle::Open(const std::string& device_file_by_name_prefix) { 461 if (device_file_by_name_prefix.empty()) { 462 LERROR << "Missing device file by-name prefix"; 463 return nullptr; 464 } 465 466 // Gets the expected hash value of vbmeta images from kernel cmdline. 467 std::unique_ptr<FsManagerAvbVerifier> avb_verifier = FsManagerAvbVerifier::Create(); 468 if (!avb_verifier) { 469 LERROR << "Failed to create FsManagerAvbVerifier"; 470 return nullptr; 471 } 472 473 FsManagerAvbUniquePtr avb_handle(new FsManagerAvbHandle()); 474 if (!avb_handle) { 475 LERROR << "Failed to allocate FsManagerAvbHandle"; 476 return nullptr; 477 } 478 479 FsManagerAvbOps avb_ops(device_file_by_name_prefix); 480 AvbSlotVerifyResult verify_result = avb_ops.AvbSlotVerify( 481 fs_mgr_get_slot_suffix(), avb_verifier->IsDeviceUnlocked(), &avb_handle->avb_slot_data_); 482 483 // Only allow two verify results: 484 // - AVB_SLOT_VERIFY_RESULT_OK. 485 // - AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION (for UNLOCKED state). 486 if (verify_result == AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION) { 487 if (!avb_verifier->IsDeviceUnlocked()) { 488 LERROR << "ERROR_VERIFICATION isn't allowed"; 489 return nullptr; 490 } 491 } else if (verify_result != AVB_SLOT_VERIFY_RESULT_OK) { 492 LERROR << "avb_slot_verify failed, result: " << verify_result; 493 return nullptr; 494 } 495 496 // Sets the MAJOR.MINOR for init to set it into "ro.boot.avb_version". 497 avb_handle->avb_version_ = 498 android::base::StringPrintf("%d.%d", AVB_VERSION_MAJOR, AVB_VERSION_MINOR); 499 500 // Verifies vbmeta images against the digest passed from bootloader. 501 if (!avb_verifier->VerifyVbmetaImages(*avb_handle->avb_slot_data_)) { 502 LERROR << "VerifyVbmetaImages failed"; 503 return nullptr; 504 } else { 505 // Checks whether FLAGS_HASHTREE_DISABLED is set. 506 AvbVBMetaImageHeader vbmeta_header; 507 avb_vbmeta_image_header_to_host_byte_order( 508 (AvbVBMetaImageHeader*)avb_handle->avb_slot_data_->vbmeta_images[0].vbmeta_data, 509 &vbmeta_header); 510 511 bool hashtree_disabled = 512 ((AvbVBMetaImageFlags)vbmeta_header.flags & AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED); 513 if (hashtree_disabled) { 514 avb_handle->status_ = kFsManagerAvbHandleHashtreeDisabled; 515 return avb_handle; 516 } 517 } 518 519 if (verify_result == AVB_SLOT_VERIFY_RESULT_OK) { 520 avb_handle->status_ = kFsManagerAvbHandleSuccess; 521 return avb_handle; 522 } 523 return nullptr; 524} 525 526bool FsManagerAvbHandle::SetUpAvb(struct fstab_rec* fstab_entry, bool wait_for_verity_dev) { 527 if (!fstab_entry) return false; 528 if (!avb_slot_data_ || avb_slot_data_->num_vbmeta_images < 1) { 529 return false; 530 } 531 if (status_ == kFsManagerAvbHandleHashtreeDisabled) { 532 LINFO << "AVB HASHTREE disabled on:" << fstab_entry->mount_point; 533 return true; 534 } 535 if (status_ != kFsManagerAvbHandleSuccess) return false; 536 537 std::string partition_name(basename(fstab_entry->mount_point)); 538 if (!avb_validate_utf8((const uint8_t*)partition_name.c_str(), partition_name.length())) { 539 LERROR << "Partition name: " << partition_name.c_str() << " is not valid UTF-8."; 540 return false; 541 } 542 543 AvbHashtreeDescriptor hashtree_descriptor; 544 std::string salt; 545 std::string root_digest; 546 if (!get_hashtree_descriptor(partition_name, *avb_slot_data_, &hashtree_descriptor, &salt, 547 &root_digest)) { 548 return false; 549 } 550 551 // Converts HASHTREE descriptor to verity_table_params. 552 if (!hashtree_dm_verity_setup(fstab_entry, hashtree_descriptor, salt, root_digest, 553 wait_for_verity_dev)) { 554 return false; 555 } 556 return true; 557} 558