• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 "avb_util.h"
18 
19 #include <unistd.h>
20 
21 #include <array>
22 #include <sstream>
23 
24 #include <android-base/file.h>
25 #include <android-base/strings.h>
26 #include <android-base/unique_fd.h>
27 
28 #include "util.h"
29 
30 using android::base::Basename;
31 using android::base::ReadFileToString;
32 using android::base::StartsWith;
33 using android::base::unique_fd;
34 
35 namespace android {
36 namespace fs_mgr {
37 
GetAvbPropertyDescriptor(const std::string & key,const std::vector<VBMetaData> & vbmeta_images)38 std::string GetAvbPropertyDescriptor(const std::string& key,
39                                      const std::vector<VBMetaData>& vbmeta_images) {
40     size_t value_size;
41     for (const auto& vbmeta : vbmeta_images) {
42         const char* value = avb_property_lookup(vbmeta.data(), vbmeta.size(), key.data(),
43                                                 key.size(), &value_size);
44         if (value != nullptr) {
45             return {value, value_size};
46         }
47     }
48     return "";
49 }
50 
51 // Constructs dm-verity arguments for sending DM_TABLE_LOAD ioctl to kernel.
52 // See the following link for more details:
53 // https://gitlab.com/cryptsetup/cryptsetup/wikis/DMVerity
ConstructVerityTable(const FsAvbHashtreeDescriptor & hashtree_desc,const std::string & blk_device,android::dm::DmTable * table)54 bool ConstructVerityTable(const FsAvbHashtreeDescriptor& hashtree_desc,
55                           const std::string& blk_device, android::dm::DmTable* table) {
56     // Loads androidboot.veritymode from kernel cmdline.
57     std::string verity_mode;
58     if (!fs_mgr_get_boot_config("veritymode", &verity_mode)) {
59         verity_mode = "enforcing";  // Defaults to enforcing when it's absent.
60     }
61 
62     // Converts veritymode to the format used in kernel.
63     std::string dm_verity_mode;
64     if (verity_mode == "enforcing") {
65         dm_verity_mode = "restart_on_corruption";
66     } else if (verity_mode == "logging") {
67         dm_verity_mode = "ignore_corruption";
68     } else if (verity_mode != "eio") {  // Default dm_verity_mode is eio.
69         LERROR << "Unknown androidboot.veritymode: " << verity_mode;
70         return false;
71     }
72 
73     std::ostringstream hash_algorithm;
74     hash_algorithm << hashtree_desc.hash_algorithm;
75 
76     android::dm::DmTargetVerity target(
77             0, hashtree_desc.image_size / 512, hashtree_desc.dm_verity_version, blk_device,
78             blk_device, hashtree_desc.data_block_size, hashtree_desc.hash_block_size,
79             hashtree_desc.image_size / hashtree_desc.data_block_size,
80             hashtree_desc.tree_offset / hashtree_desc.hash_block_size, hash_algorithm.str(),
81             hashtree_desc.root_digest, hashtree_desc.salt);
82     if (hashtree_desc.fec_size > 0) {
83         target.UseFec(blk_device, hashtree_desc.fec_num_roots,
84                       hashtree_desc.fec_offset / hashtree_desc.data_block_size,
85                       hashtree_desc.fec_offset / hashtree_desc.data_block_size);
86     }
87     if (!dm_verity_mode.empty()) {
88         target.SetVerityMode(dm_verity_mode);
89     }
90     // Always use ignore_zero_blocks.
91     target.IgnoreZeroBlocks();
92 
93     LINFO << "Built verity table: '" << target.GetParameterString() << "'";
94 
95     return table->AddTarget(std::make_unique<android::dm::DmTargetVerity>(target));
96 }
97 
HashtreeDmVeritySetup(FstabEntry * fstab_entry,const FsAvbHashtreeDescriptor & hashtree_desc,bool wait_for_verity_dev)98 bool HashtreeDmVeritySetup(FstabEntry* fstab_entry, const FsAvbHashtreeDescriptor& hashtree_desc,
99                            bool wait_for_verity_dev) {
100     android::dm::DmTable table;
101     if (!ConstructVerityTable(hashtree_desc, fstab_entry->blk_device, &table) || !table.valid()) {
102         LERROR << "Failed to construct verity table.";
103         return false;
104     }
105     table.set_readonly(true);
106 
107     const std::string mount_point(Basename(fstab_entry->mount_point));
108     const std::string device_name(GetVerityDeviceName(*fstab_entry));
109     android::dm::DeviceMapper& dm = android::dm::DeviceMapper::Instance();
110     if (!dm.CreateDevice(device_name, table)) {
111         LERROR << "Couldn't create verity device!";
112         return false;
113     }
114 
115     std::string dev_path;
116     if (!dm.GetDmDevicePathByName(device_name, &dev_path)) {
117         LERROR << "Couldn't get verity device path!";
118         return false;
119     }
120 
121     // Marks the underlying block device as read-only.
122     SetBlockDeviceReadOnly(fstab_entry->blk_device);
123 
124     // Updates fstab_rec->blk_device to verity device name.
125     fstab_entry->blk_device = dev_path;
126 
127     // Makes sure we've set everything up properly.
128     if (wait_for_verity_dev && !WaitForFile(dev_path, 1s)) {
129         return false;
130     }
131 
132     return true;
133 }
134 
GetHashtreeDescriptor(const std::string & partition_name,const std::vector<VBMetaData> & vbmeta_images)135 std::unique_ptr<FsAvbHashtreeDescriptor> GetHashtreeDescriptor(
136         const std::string& partition_name, const std::vector<VBMetaData>& vbmeta_images) {
137     bool found = false;
138     const uint8_t* desc_partition_name;
139     auto hashtree_desc = std::make_unique<FsAvbHashtreeDescriptor>();
140 
141     for (const auto& vbmeta : vbmeta_images) {
142         size_t num_descriptors;
143         std::unique_ptr<const AvbDescriptor* [], decltype(&avb_free)> descriptors(
144                 avb_descriptor_get_all(vbmeta.data(), vbmeta.size(), &num_descriptors), avb_free);
145 
146         if (!descriptors || num_descriptors < 1) {
147             continue;
148         }
149 
150         for (size_t n = 0; n < num_descriptors && !found; n++) {
151             AvbDescriptor desc;
152             if (!avb_descriptor_validate_and_byteswap(descriptors[n], &desc)) {
153                 LWARNING << "Descriptor[" << n << "] is invalid";
154                 continue;
155             }
156             if (desc.tag == AVB_DESCRIPTOR_TAG_HASHTREE) {
157                 desc_partition_name =
158                         (const uint8_t*)descriptors[n] + sizeof(AvbHashtreeDescriptor);
159                 if (!avb_hashtree_descriptor_validate_and_byteswap(
160                         (AvbHashtreeDescriptor*)descriptors[n], hashtree_desc.get())) {
161                     continue;
162                 }
163                 if (hashtree_desc->partition_name_len != partition_name.length()) {
164                     continue;
165                 }
166                 // Notes that desc_partition_name is not NUL-terminated.
167                 std::string hashtree_partition_name((const char*)desc_partition_name,
168                                                     hashtree_desc->partition_name_len);
169                 if (hashtree_partition_name == partition_name) {
170                     found = true;
171                 }
172             }
173         }
174 
175         if (found) break;
176     }
177 
178     if (!found) {
179         LERROR << "Hashtree descriptor not found: " << partition_name;
180         return nullptr;
181     }
182 
183     hashtree_desc->partition_name = partition_name;
184 
185     const uint8_t* desc_salt = desc_partition_name + hashtree_desc->partition_name_len;
186     hashtree_desc->salt = BytesToHex(desc_salt, hashtree_desc->salt_len);
187 
188     const uint8_t* desc_digest = desc_salt + hashtree_desc->salt_len;
189     hashtree_desc->root_digest = BytesToHex(desc_digest, hashtree_desc->root_digest_len);
190 
191     return hashtree_desc;
192 }
193 
LoadAvbHashtreeToEnableVerity(FstabEntry * fstab_entry,bool wait_for_verity_dev,const std::vector<VBMetaData> & vbmeta_images,const std::string & ab_suffix,const std::string & ab_other_suffix)194 bool LoadAvbHashtreeToEnableVerity(FstabEntry* fstab_entry, bool wait_for_verity_dev,
195                                    const std::vector<VBMetaData>& vbmeta_images,
196                                    const std::string& ab_suffix,
197                                    const std::string& ab_other_suffix) {
198     // Derives partition_name from blk_device to query the corresponding AVB HASHTREE descriptor
199     // to setup dm-verity. The partition_names in AVB descriptors are without A/B suffix.
200     std::string partition_name = DeriveAvbPartitionName(*fstab_entry, ab_suffix, ab_other_suffix);
201 
202     if (partition_name.empty()) {
203         LERROR << "partition name is empty, cannot lookup AVB descriptors";
204         return false;
205     }
206 
207     std::unique_ptr<FsAvbHashtreeDescriptor> hashtree_descriptor =
208             GetHashtreeDescriptor(partition_name, vbmeta_images);
209     if (!hashtree_descriptor) {
210         return false;
211     }
212 
213     // Converts HASHTREE descriptor to verity table to load into kernel.
214     // When success, the new device path will be returned, e.g., /dev/block/dm-2.
215     return HashtreeDmVeritySetup(fstab_entry, *hashtree_descriptor, wait_for_verity_dev);
216 }
217 
218 // Converts a AVB partition_name (without A/B suffix) to a device partition name.
219 // e.g.,       "system" => "system_a",
220 //       "system_other" => "system_b".
221 //
222 // If the device is non-A/B, converts it to a partition name without suffix.
223 // e.g.,       "system" => "system",
224 //       "system_other" => "system".
AvbPartitionToDevicePatition(const std::string & avb_partition_name,const std::string & ab_suffix,const std::string & ab_other_suffix)225 std::string AvbPartitionToDevicePatition(const std::string& avb_partition_name,
226                                          const std::string& ab_suffix,
227                                          const std::string& ab_other_suffix) {
228     bool is_other_slot = false;
229     std::string sanitized_partition_name(avb_partition_name);
230 
231     auto other_suffix = sanitized_partition_name.rfind("_other");
232     if (other_suffix != std::string::npos) {
233         sanitized_partition_name.erase(other_suffix);  // converts system_other => system
234         is_other_slot = true;
235     }
236 
237     auto append_suffix = is_other_slot ? ab_other_suffix : ab_suffix;
238     return sanitized_partition_name + append_suffix;
239 }
240 
241 // Converts fstab_entry.blk_device (with ab_suffix) to a AVB partition name.
242 // e.g., "/dev/block/by-name/system_a", slot_select       => "system",
243 //       "/dev/block/by-name/system_b", slot_select_other => "system_other".
244 //
245 // Or for a logical partition (with ab_suffix):
246 // e.g., "system_a", slot_select       => "system",
247 //       "system_b", slot_select_other => "system_other".
DeriveAvbPartitionName(const FstabEntry & fstab_entry,const std::string & ab_suffix,const std::string & ab_other_suffix)248 std::string DeriveAvbPartitionName(const FstabEntry& fstab_entry, const std::string& ab_suffix,
249                                    const std::string& ab_other_suffix) {
250     std::string partition_name;
251     if (fstab_entry.fs_mgr_flags.logical) {
252         partition_name = fstab_entry.logical_partition_name;
253     } else {
254         partition_name = Basename(fstab_entry.blk_device);
255     }
256 
257     if (fstab_entry.fs_mgr_flags.slot_select) {
258         auto found = partition_name.rfind(ab_suffix);
259         if (found != std::string::npos) {
260             partition_name.erase(found);  // converts system_a => system
261         }
262     } else if (fstab_entry.fs_mgr_flags.slot_select_other) {
263         auto found = partition_name.rfind(ab_other_suffix);
264         if (found != std::string::npos) {
265             partition_name.erase(found);  // converts system_b => system
266         }
267         partition_name += "_other";  // converts system => system_other
268     }
269 
270     return partition_name;
271 }
272 
GetTotalSize(int fd)273 off64_t GetTotalSize(int fd) {
274     off64_t saved_current = lseek64(fd, 0, SEEK_CUR);
275     if (saved_current == -1) {
276         PERROR << "Failed to get current position";
277         return -1;
278     }
279 
280     // lseek64() returns the resulting offset location from the beginning of the file.
281     off64_t total_size = lseek64(fd, 0, SEEK_END);
282     if (total_size == -1) {
283         PERROR << "Failed to lseek64 to end of the partition";
284         return -1;
285     }
286 
287     // Restores the original offset.
288     if (lseek64(fd, saved_current, SEEK_SET) == -1) {
289         PERROR << "Failed to lseek64 to the original offset: " << saved_current;
290     }
291 
292     return total_size;
293 }
294 
GetAvbFooter(int fd)295 std::unique_ptr<AvbFooter> GetAvbFooter(int fd) {
296     std::array<uint8_t, AVB_FOOTER_SIZE> footer_buf;
297     auto footer = std::make_unique<AvbFooter>();
298 
299     off64_t footer_offset = GetTotalSize(fd) - AVB_FOOTER_SIZE;
300 
301     ssize_t num_read =
302             TEMP_FAILURE_RETRY(pread64(fd, footer_buf.data(), AVB_FOOTER_SIZE, footer_offset));
303     if (num_read < 0 || num_read != AVB_FOOTER_SIZE) {
304         PERROR << "Failed to read AVB footer at offset: " << footer_offset;
305         return nullptr;
306     }
307 
308     if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_buf.data(), footer.get())) {
309         PERROR << "AVB footer verification failed at offset " << footer_offset;
310         return nullptr;
311     }
312 
313     return footer;
314 }
315 
ValidatePublicKeyBlob(const uint8_t * key,size_t length,const std::string & expected_key_blob)316 bool ValidatePublicKeyBlob(const uint8_t* key, size_t length,
317                            const std::string& expected_key_blob) {
318     if (expected_key_blob.empty()) {  // no expectation of the key, return true.
319         return true;
320     }
321     if (expected_key_blob.size() != length) {
322         return false;
323     }
324     if (0 == memcmp(key, expected_key_blob.data(), length)) {
325         return true;
326     }
327     return false;
328 }
329 
ValidatePublicKeyBlob(const std::string & key_blob_to_validate,const std::vector<std::string> & allowed_key_paths)330 bool ValidatePublicKeyBlob(const std::string& key_blob_to_validate,
331                            const std::vector<std::string>& allowed_key_paths) {
332     std::string allowed_key_blob;
333     if (key_blob_to_validate.empty()) {
334         LWARNING << "Failed to validate an empty key";
335         return false;
336     }
337     for (const auto& path : allowed_key_paths) {
338         if (ReadFileToString(path, &allowed_key_blob)) {
339             if (key_blob_to_validate == allowed_key_blob) return true;
340         }
341     }
342     return false;
343 }
344 
VerifyVBMetaSignature(const VBMetaData & vbmeta,const std::string & expected_public_key_blob,std::string * out_public_key_data)345 VBMetaVerifyResult VerifyVBMetaSignature(const VBMetaData& vbmeta,
346                                          const std::string& expected_public_key_blob,
347                                          std::string* out_public_key_data) {
348     const uint8_t* pk_data;
349     size_t pk_len;
350     ::AvbVBMetaVerifyResult vbmeta_ret;
351 
352     vbmeta_ret = avb_vbmeta_image_verify(vbmeta.data(), vbmeta.size(), &pk_data, &pk_len);
353 
354     if (out_public_key_data != nullptr) {
355         out_public_key_data->clear();
356         if (pk_len > 0) {
357             out_public_key_data->append(reinterpret_cast<const char*>(pk_data), pk_len);
358         }
359     }
360 
361     switch (vbmeta_ret) {
362         case AVB_VBMETA_VERIFY_RESULT_OK:
363             if (pk_data == nullptr || pk_len <= 0) {
364                 LERROR << vbmeta.partition()
365                        << ": Error verifying vbmeta image: failed to get public key";
366                 return VBMetaVerifyResult::kError;
367             }
368             if (!ValidatePublicKeyBlob(pk_data, pk_len, expected_public_key_blob)) {
369                 LERROR << vbmeta.partition() << ": Error verifying vbmeta image: public key used to"
370                        << " sign data does not match key in chain descriptor";
371                 return VBMetaVerifyResult::kErrorVerification;
372             }
373             return VBMetaVerifyResult::kSuccess;
374         case AVB_VBMETA_VERIFY_RESULT_OK_NOT_SIGNED:
375         case AVB_VBMETA_VERIFY_RESULT_HASH_MISMATCH:
376         case AVB_VBMETA_VERIFY_RESULT_SIGNATURE_MISMATCH:
377             LERROR << vbmeta.partition() << ": Error verifying vbmeta image: "
378                    << avb_vbmeta_verify_result_to_string(vbmeta_ret);
379             return VBMetaVerifyResult::kErrorVerification;
380         case AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER:
381             // No way to continue this case.
382             LERROR << vbmeta.partition() << ": Error verifying vbmeta image: invalid vbmeta header";
383             break;
384         case AVB_VBMETA_VERIFY_RESULT_UNSUPPORTED_VERSION:
385             // No way to continue this case.
386             LERROR << vbmeta.partition()
387                    << ": Error verifying vbmeta image: unsupported AVB version";
388             break;
389         default:
390             LERROR << "Unknown vbmeta image verify return value: " << vbmeta_ret;
391             break;
392     }
393 
394     return VBMetaVerifyResult::kError;
395 }
396 
VerifyVBMetaData(int fd,const std::string & partition_name,const std::string & expected_public_key_blob,std::string * out_public_key_data,VBMetaVerifyResult * out_verify_result)397 std::unique_ptr<VBMetaData> VerifyVBMetaData(int fd, const std::string& partition_name,
398                                              const std::string& expected_public_key_blob,
399                                              std::string* out_public_key_data,
400                                              VBMetaVerifyResult* out_verify_result) {
401     uint64_t vbmeta_offset = 0;
402     uint64_t vbmeta_size = VBMetaData::kMaxVBMetaSize;
403     bool is_vbmeta_partition = StartsWith(partition_name, "vbmeta");
404 
405     if (out_verify_result) {
406         *out_verify_result = VBMetaVerifyResult::kError;
407     }
408 
409     if (!is_vbmeta_partition) {
410         std::unique_ptr<AvbFooter> footer = GetAvbFooter(fd);
411         if (!footer) {
412             return nullptr;
413         }
414         vbmeta_offset = footer->vbmeta_offset;
415         vbmeta_size = footer->vbmeta_size;
416     }
417 
418     if (vbmeta_size > VBMetaData::kMaxVBMetaSize) {
419         LERROR << "VbMeta size in footer exceeds kMaxVBMetaSize";
420         return nullptr;
421     }
422 
423     auto vbmeta = std::make_unique<VBMetaData>(vbmeta_size, partition_name);
424     ssize_t num_read = TEMP_FAILURE_RETRY(pread64(fd, vbmeta->data(), vbmeta_size, vbmeta_offset));
425     // Allows partial read for vbmeta partition, because its vbmeta_size is kMaxVBMetaSize.
426     if (num_read < 0 || (!is_vbmeta_partition && static_cast<uint64_t>(num_read) != vbmeta_size)) {
427         PERROR << partition_name << ": Failed to read vbmeta at offset " << vbmeta_offset
428                << " with size " << vbmeta_size;
429         return nullptr;
430     }
431 
432     auto verify_result =
433             VerifyVBMetaSignature(*vbmeta, expected_public_key_blob, out_public_key_data);
434 
435     if (out_verify_result != nullptr) {
436         *out_verify_result = verify_result;
437     }
438 
439     if (verify_result == VBMetaVerifyResult::kSuccess ||
440         verify_result == VBMetaVerifyResult::kErrorVerification) {
441         return vbmeta;
442     }
443 
444     return nullptr;
445 }
446 
RollbackDetected(const std::string & partition_name ATTRIBUTE_UNUSED,uint64_t rollback_index ATTRIBUTE_UNUSED)447 bool RollbackDetected(const std::string& partition_name ATTRIBUTE_UNUSED,
448                       uint64_t rollback_index ATTRIBUTE_UNUSED) {
449     // TODO(bowgotsai): Support rollback protection.
450     return false;
451 }
452 
GetChainPartitionInfo(const VBMetaData & vbmeta,bool * fatal_error)453 std::vector<ChainInfo> GetChainPartitionInfo(const VBMetaData& vbmeta, bool* fatal_error) {
454     CHECK(fatal_error != nullptr);
455     std::vector<ChainInfo> chain_partitions;
456 
457     size_t num_descriptors;
458     std::unique_ptr<const AvbDescriptor* [], decltype(&avb_free)> descriptors(
459             avb_descriptor_get_all(vbmeta.data(), vbmeta.size(), &num_descriptors), avb_free);
460 
461     if (!descriptors || num_descriptors < 1) {
462         return {};
463     }
464 
465     for (size_t i = 0; i < num_descriptors; i++) {
466         AvbDescriptor desc;
467         if (!avb_descriptor_validate_and_byteswap(descriptors[i], &desc)) {
468             LERROR << "Descriptor[" << i << "] is invalid in vbmeta: " << vbmeta.partition();
469             *fatal_error = true;
470             return {};
471         }
472         if (desc.tag == AVB_DESCRIPTOR_TAG_CHAIN_PARTITION) {
473             AvbChainPartitionDescriptor chain_desc;
474             if (!avb_chain_partition_descriptor_validate_and_byteswap(
475                         (AvbChainPartitionDescriptor*)descriptors[i], &chain_desc)) {
476                 LERROR << "Chain descriptor[" << i
477                        << "] is invalid in vbmeta: " << vbmeta.partition();
478                 *fatal_error = true;
479                 return {};
480             }
481             const char* chain_partition_name =
482                     ((const char*)descriptors[i]) + sizeof(AvbChainPartitionDescriptor);
483             const char* chain_public_key_blob =
484                     chain_partition_name + chain_desc.partition_name_len;
485             chain_partitions.emplace_back(
486                     std::string(chain_partition_name, chain_desc.partition_name_len),
487                     std::string(chain_public_key_blob, chain_desc.public_key_len));
488         }
489     }
490 
491     return chain_partitions;
492 }
493 
494 // Loads the vbmeta from a given path.
LoadAndVerifyVbmetaByPath(const std::string & image_path,const std::string & partition_name,const std::string & expected_public_key_blob,bool allow_verification_error,bool rollback_protection,bool is_chained_vbmeta,std::string * out_public_key_data,bool * out_verification_disabled,VBMetaVerifyResult * out_verify_result)495 std::unique_ptr<VBMetaData> LoadAndVerifyVbmetaByPath(
496         const std::string& image_path, const std::string& partition_name,
497         const std::string& expected_public_key_blob, bool allow_verification_error,
498         bool rollback_protection, bool is_chained_vbmeta, std::string* out_public_key_data,
499         bool* out_verification_disabled, VBMetaVerifyResult* out_verify_result) {
500     if (out_verify_result) {
501         *out_verify_result = VBMetaVerifyResult::kError;
502     }
503 
504     // Ensures the device path (might be a symlink created by init) is ready to access.
505     if (!WaitForFile(image_path, 1s)) {
506         PERROR << "No such path: " << image_path;
507         return nullptr;
508     }
509 
510     unique_fd fd(TEMP_FAILURE_RETRY(open(image_path.c_str(), O_RDONLY | O_CLOEXEC)));
511     if (fd < 0) {
512         PERROR << "Failed to open: " << image_path;
513         return nullptr;
514     }
515 
516     VBMetaVerifyResult verify_result;
517     std::unique_ptr<VBMetaData> vbmeta = VerifyVBMetaData(
518             fd, partition_name, expected_public_key_blob, out_public_key_data, &verify_result);
519     if (!vbmeta) {
520         LERROR << partition_name << ": Failed to load vbmeta, result: " << verify_result;
521         return nullptr;
522     }
523     vbmeta->set_vbmeta_path(image_path);
524 
525     if (!allow_verification_error && verify_result == VBMetaVerifyResult::kErrorVerification) {
526         LERROR << partition_name << ": allow verification error is not allowed";
527         return nullptr;
528     }
529 
530     std::unique_ptr<AvbVBMetaImageHeader> vbmeta_header =
531             vbmeta->GetVBMetaHeader(true /* update_vbmeta_size */);
532     if (!vbmeta_header) {
533         LERROR << partition_name << ": Failed to get vbmeta header";
534         return nullptr;
535     }
536 
537     if (rollback_protection && RollbackDetected(partition_name, vbmeta_header->rollback_index)) {
538         return nullptr;
539     }
540 
541     // vbmeta flags can only be set by the top-level vbmeta image.
542     if (is_chained_vbmeta && vbmeta_header->flags != 0) {
543         LERROR << partition_name << ": chained vbmeta image has non-zero flags";
544         return nullptr;
545     }
546 
547     // Checks if verification has been disabled by setting a bit in the image.
548     if (out_verification_disabled) {
549         if (vbmeta_header->flags & AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED) {
550             LWARNING << "VERIFICATION_DISABLED bit is set for partition: " << partition_name;
551             *out_verification_disabled = true;
552         } else {
553             *out_verification_disabled = false;
554         }
555     }
556 
557     if (out_verify_result) {
558         *out_verify_result = verify_result;
559     }
560 
561     return vbmeta;
562 }
563 
LoadAndVerifyVbmetaByPartition(const std::string & partition_name,const std::string & ab_suffix,const std::string & ab_other_suffix,const std::string & expected_public_key_blob,bool allow_verification_error,bool load_chained_vbmeta,bool rollback_protection,std::function<std::string (const std::string &)> device_path_constructor,bool is_chained_vbmeta,std::vector<VBMetaData> * out_vbmeta_images)564 VBMetaVerifyResult LoadAndVerifyVbmetaByPartition(
565     const std::string& partition_name, const std::string& ab_suffix,
566     const std::string& ab_other_suffix, const std::string& expected_public_key_blob,
567     bool allow_verification_error, bool load_chained_vbmeta, bool rollback_protection,
568     std::function<std::string(const std::string&)> device_path_constructor, bool is_chained_vbmeta,
569     std::vector<VBMetaData>* out_vbmeta_images) {
570     auto image_path = device_path_constructor(
571         AvbPartitionToDevicePatition(partition_name, ab_suffix, ab_other_suffix));
572 
573     bool verification_disabled = false;
574     VBMetaVerifyResult verify_result;
575     auto vbmeta = LoadAndVerifyVbmetaByPath(image_path, partition_name, expected_public_key_blob,
576                                             allow_verification_error, rollback_protection,
577                                             is_chained_vbmeta, nullptr /* out_public_key_data */,
578                                             &verification_disabled, &verify_result);
579 
580     if (!vbmeta) {
581         return VBMetaVerifyResult::kError;
582     }
583     if (out_vbmeta_images) {
584         out_vbmeta_images->emplace_back(std::move(*vbmeta));
585     }
586 
587     // Only loads chained vbmeta if AVB verification is NOT disabled.
588     if (!verification_disabled && load_chained_vbmeta) {
589         bool fatal_error = false;
590         auto chain_partitions = GetChainPartitionInfo(*out_vbmeta_images->rbegin(), &fatal_error);
591         if (fatal_error) {
592             return VBMetaVerifyResult::kError;
593         }
594         for (auto& chain : chain_partitions) {
595             auto sub_ret = LoadAndVerifyVbmetaByPartition(
596                 chain.partition_name, ab_suffix, ab_other_suffix, chain.public_key_blob,
597                 allow_verification_error, load_chained_vbmeta, rollback_protection,
598                 device_path_constructor, true, /* is_chained_vbmeta */
599                 out_vbmeta_images);
600             if (sub_ret != VBMetaVerifyResult::kSuccess) {
601                 verify_result = sub_ret;  // might be 'ERROR' or 'ERROR VERIFICATION'.
602                 if (verify_result == VBMetaVerifyResult::kError) {
603                     return verify_result;  // stop here if we got an 'ERROR'.
604                 }
605             }
606         }
607     }
608 
609     return verify_result;
610 }
611 
612 }  // namespace fs_mgr
613 }  // namespace android
614