xref: /aosp_15_r20/system/core/fs_mgr/libfs_avb/fs_avb.cpp (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
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 "fs_avb/fs_avb.h"
18 
19 #include <fcntl.h>
20 #include <libgen.h>
21 #include <string.h>
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 
25 #include <algorithm>
26 #include <sstream>
27 #include <string>
28 #include <vector>
29 
30 #include <android-base/file.h>
31 #include <android-base/logging.h>
32 #include <android-base/parseint.h>
33 #include <android-base/stringprintf.h>
34 #include <android-base/strings.h>
35 #include <libavb/libavb.h>
36 #include <libdm/dm.h>
37 #include <libgsi/libgsi.h>
38 
39 #include "avb_ops.h"
40 #include "avb_util.h"
41 #include "fs_avb/fs_avb_util.h"
42 #include "sha.h"
43 #include "util.h"
44 
45 using android::base::Basename;
46 using android::base::ParseUint;
47 using android::base::ReadFileToString;
48 using android::base::Split;
49 using android::base::StringPrintf;
50 
51 namespace android {
52 namespace fs_mgr {
53 
54 template <typename Hasher>
VerifyVbmetaDigest(const std::vector<VBMetaData> & vbmeta_images,const uint8_t * expected_digest)55 std::pair<size_t, bool> VerifyVbmetaDigest(const std::vector<VBMetaData>& vbmeta_images,
56                                            const uint8_t* expected_digest) {
57     size_t total_size = 0;
58     Hasher hasher;
59     for (const auto& vbmeta : vbmeta_images) {
60         hasher.update(vbmeta.data(), vbmeta.size());
61         total_size += vbmeta.size();
62     }
63 
64     bool matched = (memcmp(hasher.finalize(), expected_digest, Hasher::DIGEST_SIZE) == 0);
65 
66     return std::make_pair(total_size, matched);
67 }
68 
69 template <typename Hasher>
CalculateVbmetaDigest(const std::vector<VBMetaData> & vbmeta_images)70 std::pair<std::string, size_t> CalculateVbmetaDigest(const std::vector<VBMetaData>& vbmeta_images) {
71     std::string digest;
72     size_t total_size = 0;
73 
74     Hasher hasher;
75     for (const auto& vbmeta : vbmeta_images) {
76         hasher.update(vbmeta.data(), vbmeta.size());
77         total_size += vbmeta.size();
78     }
79 
80     // Converts digest bytes to a hex string.
81     digest = BytesToHex(hasher.finalize(), Hasher::DIGEST_SIZE);
82     return std::make_pair(digest, total_size);
83 }
84 
85 // class AvbVerifier
86 // -----------------
87 // Reads the following values from kernel cmdline and provides the
88 // VerifyVbmetaImages() to verify AvbSlotVerifyData.
89 //   - androidboot.vbmeta.hash_alg
90 //   - androidboot.vbmeta.size
91 //   - androidboot.vbmeta.digest
92 class AvbVerifier {
93   public:
94     // The factory method to return a unique_ptr<AvbVerifier>
95     static std::unique_ptr<AvbVerifier> Create();
96     bool VerifyVbmetaImages(const std::vector<VBMetaData>& vbmeta_images);
97 
98   protected:
99     AvbVerifier() = default;
100 
101   private:
102     HashAlgorithm hash_alg_;
103     uint8_t digest_[SHA512_DIGEST_LENGTH];
104     size_t vbmeta_size_;
105 };
106 
Create()107 std::unique_ptr<AvbVerifier> AvbVerifier::Create() {
108     std::unique_ptr<AvbVerifier> avb_verifier(new AvbVerifier());
109     if (!avb_verifier) {
110         LERROR << "Failed to create unique_ptr<AvbVerifier>";
111         return nullptr;
112     }
113 
114     std::string value;
115     if (!fs_mgr_get_boot_config("vbmeta.size", &value) ||
116         !ParseUint(value.c_str(), &avb_verifier->vbmeta_size_)) {
117         LERROR << "Invalid hash size: " << value.c_str();
118         return nullptr;
119     }
120 
121     // Reads hash algorithm.
122     size_t expected_digest_size = 0;
123     std::string hash_alg;
124     fs_mgr_get_boot_config("vbmeta.hash_alg", &hash_alg);
125     if (hash_alg == "sha256") {
126         expected_digest_size = SHA256_DIGEST_LENGTH * 2;
127         avb_verifier->hash_alg_ = HashAlgorithm::kSHA256;
128     } else if (hash_alg == "sha512") {
129         expected_digest_size = SHA512_DIGEST_LENGTH * 2;
130         avb_verifier->hash_alg_ = HashAlgorithm::kSHA512;
131     } else {
132         LERROR << "Unknown hash algorithm: " << hash_alg.c_str();
133         return nullptr;
134     }
135 
136     // Reads digest.
137     std::string digest;
138     fs_mgr_get_boot_config("vbmeta.digest", &digest);
139     if (digest.size() != expected_digest_size) {
140         LERROR << "Unexpected digest size: " << digest.size()
141                << " (expected: " << expected_digest_size << ")";
142         return nullptr;
143     }
144 
145     if (!HexToBytes(avb_verifier->digest_, sizeof(avb_verifier->digest_), digest)) {
146         LERROR << "Hash digest contains non-hexidecimal character: " << digest.c_str();
147         return nullptr;
148     }
149 
150     return avb_verifier;
151 }
152 
VerifyVbmetaImages(const std::vector<VBMetaData> & vbmeta_images)153 bool AvbVerifier::VerifyVbmetaImages(const std::vector<VBMetaData>& vbmeta_images) {
154     if (vbmeta_images.empty()) {
155         LERROR << "No vbmeta images";
156         return false;
157     }
158 
159     size_t total_size = 0;
160     bool digest_matched = false;
161 
162     if (hash_alg_ == HashAlgorithm::kSHA256) {
163         std::tie(total_size, digest_matched) =
164                 VerifyVbmetaDigest<SHA256Hasher>(vbmeta_images, digest_);
165     } else if (hash_alg_ == HashAlgorithm::kSHA512) {
166         std::tie(total_size, digest_matched) =
167                 VerifyVbmetaDigest<SHA512Hasher>(vbmeta_images, digest_);
168     }
169 
170     if (total_size != vbmeta_size_) {
171         LERROR << "total vbmeta size mismatch: " << total_size << " (expected: " << vbmeta_size_
172                << ")";
173         return false;
174     }
175 
176     if (!digest_matched) {
177         LERROR << "vbmeta digest mismatch";
178         return false;
179     }
180 
181     return true;
182 }
183 
184 // class AvbHandle
185 // ---------------
AvbHandle()186 AvbHandle::AvbHandle() : status_(AvbHandleStatus::kUninitialized) {
187     slot_suffix_ = fs_mgr_get_slot_suffix();
188     other_slot_suffix_ = fs_mgr_get_other_slot_suffix();
189 }
190 
LoadAndVerifyVbmeta(const std::string & partition_name,const std::string & ab_suffix,const std::string & ab_other_suffix,const std::string & expected_public_key_path,const HashAlgorithm & hash_algorithm,bool allow_verification_error,bool load_chained_vbmeta,bool rollback_protection,std::function<std::string (const std::string &)> custom_device_path)191 AvbUniquePtr AvbHandle::LoadAndVerifyVbmeta(
192         const std::string& partition_name, const std::string& ab_suffix,
193         const std::string& ab_other_suffix, const std::string& expected_public_key_path,
194         const HashAlgorithm& hash_algorithm, bool allow_verification_error,
195         bool load_chained_vbmeta, bool rollback_protection,
196         std::function<std::string(const std::string&)> custom_device_path) {
197     AvbUniquePtr avb_handle(new AvbHandle());
198     if (!avb_handle) {
199         LERROR << "Failed to allocate AvbHandle";
200         return nullptr;
201     }
202 
203     avb_handle->slot_suffix_ = ab_suffix;
204     avb_handle->other_slot_suffix_ = ab_other_suffix;
205 
206     std::string expected_key_blob;
207     if (!expected_public_key_path.empty()) {
208         if (access(expected_public_key_path.c_str(), F_OK) != 0) {
209             LERROR << "Expected public key path doesn't exist: " << expected_public_key_path;
210             return nullptr;
211         } else if (!ReadFileToString(expected_public_key_path, &expected_key_blob)) {
212             LERROR << "Failed to load: " << expected_public_key_path;
213             return nullptr;
214         }
215     }
216 
217     auto android_by_name_symlink = [](const std::string& partition_name_with_ab) {
218         return "/dev/block/by-name/" + partition_name_with_ab;
219     };
220 
221     auto device_path = custom_device_path ? custom_device_path : android_by_name_symlink;
222 
223     auto verify_result = LoadAndVerifyVbmetaByPartition(
224         partition_name, ab_suffix, ab_other_suffix, expected_key_blob, allow_verification_error,
225         load_chained_vbmeta, rollback_protection, device_path, false,
226         /* is_chained_vbmeta */ &avb_handle->vbmeta_images_);
227     switch (verify_result) {
228         case VBMetaVerifyResult::kSuccess:
229             avb_handle->status_ = AvbHandleStatus::kSuccess;
230             break;
231         case VBMetaVerifyResult::kErrorVerification:
232             avb_handle->status_ = AvbHandleStatus::kVerificationError;
233             break;
234         default:
235             LERROR << "LoadAndVerifyVbmetaByPartition failed, result: " << verify_result;
236             return nullptr;
237     }
238 
239     // Validity check here because we have to use vbmeta_images_[0] below.
240     if (avb_handle->vbmeta_images_.size() < 1) {
241         LERROR << "LoadAndVerifyVbmetaByPartition failed, no vbmeta loaded";
242         return nullptr;
243     }
244 
245     // Sets the MAJOR.MINOR for init to set it into "ro.boot.avb_version".
246     avb_handle->avb_version_ = StringPrintf("%d.%d", AVB_VERSION_MAJOR, AVB_VERSION_MINOR);
247 
248     // Checks any disabled flag is set.
249     std::unique_ptr<AvbVBMetaImageHeader> vbmeta_header =
250             avb_handle->vbmeta_images_[0].GetVBMetaHeader();
251     bool verification_disabled = ((AvbVBMetaImageFlags)vbmeta_header->flags &
252                                   AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED);
253     bool hashtree_disabled =
254             ((AvbVBMetaImageFlags)vbmeta_header->flags & AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED);
255     if (verification_disabled) {
256         avb_handle->status_ = AvbHandleStatus::kVerificationDisabled;
257     } else if (hashtree_disabled) {
258         avb_handle->status_ = AvbHandleStatus::kHashtreeDisabled;
259     }
260 
261     // Calculates the summary info for all vbmeta_images_;
262     std::string digest;
263     size_t total_size;
264     if (hash_algorithm == HashAlgorithm::kSHA256) {
265         std::tie(digest, total_size) =
266                 CalculateVbmetaDigest<SHA256Hasher>(avb_handle->vbmeta_images_);
267     } else if (hash_algorithm == HashAlgorithm::kSHA512) {
268         std::tie(digest, total_size) =
269                 CalculateVbmetaDigest<SHA512Hasher>(avb_handle->vbmeta_images_);
270     } else {
271         LERROR << "Invalid hash algorithm";
272         return nullptr;
273     }
274     avb_handle->vbmeta_info_ = VBMetaInfo(digest, hash_algorithm, total_size);
275 
276     LINFO << "Returning avb_handle with status: " << avb_handle->status_;
277     return avb_handle;
278 }
279 
IsAvbPermissive()280 static bool IsAvbPermissive() {
281     if (IsDeviceUnlocked()) {
282         // Manually putting a file under metadata partition can enforce AVB verification.
283         if (!access(DSU_METADATA_PREFIX "avb_enforce", F_OK)) {
284             LINFO << "Enforcing AVB verification when the device is unlocked";
285             return false;
286         }
287         return true;
288     }
289     return false;
290 }
291 
IsPublicKeyMatching(const FstabEntry & fstab_entry,const std::string & public_key_data,const std::vector<std::string> & preload_avb_key_blobs)292 bool IsPublicKeyMatching(const FstabEntry& fstab_entry, const std::string& public_key_data,
293                          const std::vector<std::string>& preload_avb_key_blobs) {
294     // At least one of the following should be provided for public key matching.
295     if (preload_avb_key_blobs.empty() && fstab_entry.avb_keys.empty()) {
296         LERROR << "avb_keys=/path/to/key(s) is missing for " << fstab_entry.mount_point;
297         return false;
298     }
299 
300     // Expected key shouldn't be empty.
301     if (public_key_data.empty()) {
302         LERROR << "public key data shouldn't be empty for " << fstab_entry.mount_point;
303         return false;
304     }
305 
306     // Performs key matching for preload_avb_key_blobs first, if it is present.
307     if (!preload_avb_key_blobs.empty()) {
308         if (std::find(preload_avb_key_blobs.begin(), preload_avb_key_blobs.end(),
309                       public_key_data) != preload_avb_key_blobs.end()) {
310             return true;
311         }
312     }
313 
314     // Performs key matching for fstab_entry.avb_keys if necessary.
315     // Note that it is intentional to match both preload_avb_key_blobs and fstab_entry.avb_keys.
316     // Some keys might only be available before init chroots into /system, e.g., /avb/key1
317     // in the first-stage ramdisk, while other keys might only be available after the chroot,
318     // e.g., /system/etc/avb/key2.
319     // fstab_entry.avb_keys might be either a directory containing multiple keys,
320     // or a string indicating multiple keys separated by ':'.
321     std::vector<std::string> allowed_avb_keys;
322     auto list_avb_keys_in_dir = ListFiles(fstab_entry.avb_keys);
323     if (list_avb_keys_in_dir.ok()) {
324         std::sort(list_avb_keys_in_dir->begin(), list_avb_keys_in_dir->end());
325         allowed_avb_keys = *list_avb_keys_in_dir;
326     } else {
327         allowed_avb_keys = Split(fstab_entry.avb_keys, ":");
328     }
329     return ValidatePublicKeyBlob(public_key_data, allowed_avb_keys);
330 }
331 
IsHashtreeDescriptorRootDigestMatching(const FstabEntry & fstab_entry,const std::vector<VBMetaData> & vbmeta_images,const std::string & ab_suffix,const std::string & ab_other_suffix)332 bool IsHashtreeDescriptorRootDigestMatching(const FstabEntry& fstab_entry,
333                                             const std::vector<VBMetaData>& vbmeta_images,
334                                             const std::string& ab_suffix,
335                                             const std::string& ab_other_suffix) {
336     // Read expected value of hashtree descriptor root digest from fstab_entry.
337     std::string root_digest_expected;
338     if (!ReadFileToString(fstab_entry.avb_hashtree_digest, &root_digest_expected)) {
339         LERROR << "Failed to load expected root digest for " << fstab_entry.mount_point;
340         return false;
341     }
342 
343     // Read actual hashtree descriptor from vbmeta image.
344     std::string partition_name = DeriveAvbPartitionName(fstab_entry, ab_suffix, ab_other_suffix);
345     if (partition_name.empty()) {
346         LERROR << "Failed to find partition name for " << fstab_entry.mount_point;
347         return false;
348     }
349     std::unique_ptr<FsAvbHashtreeDescriptor> hashtree_descriptor =
350             android::fs_mgr::GetHashtreeDescriptor(partition_name, vbmeta_images);
351     if (!hashtree_descriptor) {
352         LERROR << "Not found hashtree descriptor for " << fstab_entry.mount_point;
353         return false;
354     }
355 
356     // Performs hashtree descriptor root digest matching.
357     if (hashtree_descriptor->root_digest != root_digest_expected) {
358         LERROR << "root digest (" << hashtree_descriptor->root_digest
359                << ") is different from expected value (" << root_digest_expected << ")";
360         return false;
361     }
362 
363     return true;
364 }
365 
LoadAndVerifyVbmeta(const FstabEntry & fstab_entry,const std::vector<std::string> & preload_avb_key_blobs)366 AvbUniquePtr AvbHandle::LoadAndVerifyVbmeta(const FstabEntry& fstab_entry,
367                                             const std::vector<std::string>& preload_avb_key_blobs) {
368     // Binds allow_verification_error and rollback_protection to device unlock state.
369     bool allow_verification_error = IsAvbPermissive();
370     bool rollback_protection = !allow_verification_error;
371 
372     std::string public_key_data;
373     bool verification_disabled = false;
374     VBMetaVerifyResult verify_result = VBMetaVerifyResult::kError;
375     std::unique_ptr<VBMetaData> vbmeta = LoadAndVerifyVbmetaByPath(
376             fstab_entry.blk_device, "" /* partition_name, no need for a standalone path */,
377             "" /* expected_public_key_blob, */, allow_verification_error, rollback_protection,
378             false /* not is_chained_vbmeta */, &public_key_data, &verification_disabled,
379             &verify_result);
380 
381     if (!vbmeta) {
382         LERROR << "Failed to load vbmeta: " << fstab_entry.blk_device;
383         return nullptr;
384     }
385 
386     AvbUniquePtr avb_handle(new AvbHandle());
387     if (!avb_handle) {
388         LERROR << "Failed to allocate AvbHandle";
389         return nullptr;
390     }
391     avb_handle->vbmeta_images_.emplace_back(std::move(*vbmeta));
392 
393     switch (verify_result) {
394         case VBMetaVerifyResult::kSuccess:
395             avb_handle->status_ = AvbHandleStatus::kSuccess;
396             break;
397         case VBMetaVerifyResult::kErrorVerification:
398             avb_handle->status_ = AvbHandleStatus::kVerificationError;
399             break;
400         default:
401             LERROR << "LoadAndVerifyVbmetaByPath failed, result: " << verify_result;
402             return nullptr;
403     }
404 
405     // Verify vbmeta image checking by either public key or hashtree descriptor root digest.
406     if (!preload_avb_key_blobs.empty() || !fstab_entry.avb_keys.empty()) {
407         if (!IsPublicKeyMatching(fstab_entry, public_key_data, preload_avb_key_blobs)) {
408             avb_handle->status_ = AvbHandleStatus::kVerificationError;
409             LWARNING << "Found unknown public key used to sign " << fstab_entry.mount_point;
410             if (!allow_verification_error) {
411                 LERROR << "Unknown public key is not allowed";
412                 return nullptr;
413             }
414         }
415     } else if (!IsHashtreeDescriptorRootDigestMatching(fstab_entry, avb_handle->vbmeta_images_,
416                                                        avb_handle->slot_suffix_,
417                                                        avb_handle->other_slot_suffix_)) {
418         avb_handle->status_ = AvbHandleStatus::kVerificationError;
419         LWARNING << "Found unknown hashtree descriptor root digest used on "
420                  << fstab_entry.mount_point;
421         if (!allow_verification_error) {
422             LERROR << "Verification based on root digest failed. Vbmeta image is not allowed.";
423             return nullptr;
424         }
425     }
426 
427     if (verification_disabled) {
428         LINFO << "AVB verification disabled on: " << fstab_entry.mount_point;
429         avb_handle->status_ = AvbHandleStatus::kVerificationDisabled;
430     }
431 
432     LINFO << "Returning avb_handle for '" << fstab_entry.mount_point
433           << "' with status: " << avb_handle->status_;
434     return avb_handle;
435 }
436 
LoadAndVerifyVbmeta(const std::string & slot_suffix)437 AvbUniquePtr AvbHandle::LoadAndVerifyVbmeta(const std::string& slot_suffix) {
438     // Loads inline vbmeta images, starting from /vbmeta.
439     auto suffix = slot_suffix;
440     if (suffix.empty()) {
441         suffix = fs_mgr_get_slot_suffix();
442     }
443     auto other_suffix = android::fs_mgr::OtherSlotSuffix(suffix);
444     return LoadAndVerifyVbmeta("vbmeta", suffix, other_suffix,
445                                {} /* expected_public_key, already checked by bootloader */,
446                                HashAlgorithm::kSHA256,
447                                IsAvbPermissive(), /* allow_verification_error */
448                                true,              /* load_chained_vbmeta */
449                                false, /* rollback_protection, already checked by bootloader */
450                                nullptr /* custom_device_path */);
451 }
452 
453 // TODO(b/128807537): removes this function.
Open()454 AvbUniquePtr AvbHandle::Open() {
455     bool allow_verification_error = IsAvbPermissive();
456 
457     AvbUniquePtr avb_handle(new AvbHandle());
458     if (!avb_handle) {
459         LERROR << "Failed to allocate AvbHandle";
460         return nullptr;
461     }
462 
463     FsManagerAvbOps avb_ops;
464     AvbSlotVerifyFlags flags = allow_verification_error
465                                        ? AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR
466                                        : AVB_SLOT_VERIFY_FLAGS_NONE;
467     AvbSlotVerifyResult verify_result =
468             avb_ops.AvbSlotVerify(avb_handle->slot_suffix_, flags, &avb_handle->vbmeta_images_);
469 
470     // Only allow the following verify results:
471     //   - AVB_SLOT_VERIFY_RESULT_OK.
472     //   - AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION (UNLOCKED only).
473     //     Might occur in either the top-level vbmeta or a chained vbmeta.
474     //   - AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED (UNLOCKED only).
475     //     Could only occur in a chained vbmeta. Because we have *no-op* operations in
476     //     FsManagerAvbOps such that avb_ops->validate_vbmeta_public_key() used to validate
477     //     the public key of the top-level vbmeta always pass in userspace here.
478     //
479     // The following verify result won't happen, because the *no-op* operation
480     // avb_ops->read_rollback_index() always returns the minimum value zero. So rollbacked
481     // vbmeta images, which should be caught in the bootloader stage, won't be detected here.
482     //   - AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX
483     switch (verify_result) {
484         case AVB_SLOT_VERIFY_RESULT_OK:
485             avb_handle->status_ = AvbHandleStatus::kSuccess;
486             break;
487         case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
488         case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
489             if (!allow_verification_error) {
490                 LERROR << "ERROR_VERIFICATION / PUBLIC_KEY_REJECTED isn't allowed ";
491                 return nullptr;
492             }
493             avb_handle->status_ = AvbHandleStatus::kVerificationError;
494             break;
495         default:
496             LERROR << "avb_slot_verify failed, result: " << verify_result;
497             return nullptr;
498     }
499 
500     // Sets the MAJOR.MINOR for init to set it into "ro.boot.avb_version".
501     avb_handle->avb_version_ = StringPrintf("%d.%d", AVB_VERSION_MAJOR, AVB_VERSION_MINOR);
502 
503     // Verifies vbmeta structs against the digest passed from bootloader in kernel cmdline.
504     std::unique_ptr<AvbVerifier> avb_verifier = AvbVerifier::Create();
505     if (!avb_verifier || !avb_verifier->VerifyVbmetaImages(avb_handle->vbmeta_images_)) {
506         LERROR << "Failed to verify vbmeta digest";
507         if (!allow_verification_error) {
508             LERROR << "vbmeta digest error isn't allowed ";
509             return nullptr;
510         }
511     }
512 
513     // Checks whether FLAGS_VERIFICATION_DISABLED is set:
514     //   - Only the top-level vbmeta struct is read.
515     //   - vbmeta struct in other partitions are NOT processed, including AVB HASH descriptor(s)
516     //     and AVB HASHTREE descriptor(s).
517     AvbVBMetaImageHeader vbmeta_header;
518     avb_vbmeta_image_header_to_host_byte_order(
519             (AvbVBMetaImageHeader*)avb_handle->vbmeta_images_[0].data(), &vbmeta_header);
520     bool verification_disabled = ((AvbVBMetaImageFlags)vbmeta_header.flags &
521                                   AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED);
522 
523     // Checks whether FLAGS_HASHTREE_DISABLED is set.
524     //   - vbmeta struct in all partitions are still processed, just disable
525     //     dm-verity in the user space.
526     bool hashtree_disabled =
527             ((AvbVBMetaImageFlags)vbmeta_header.flags & AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED);
528 
529     if (verification_disabled) {
530         avb_handle->status_ = AvbHandleStatus::kVerificationDisabled;
531     } else if (hashtree_disabled) {
532         avb_handle->status_ = AvbHandleStatus::kHashtreeDisabled;
533     }
534 
535     LINFO << "Returning avb_handle with status: " << avb_handle->status_;
536     return avb_handle;
537 }
538 
SetUpStandaloneAvbHashtree(FstabEntry * fstab_entry,bool wait_for_verity_dev)539 AvbHashtreeResult AvbHandle::SetUpStandaloneAvbHashtree(FstabEntry* fstab_entry,
540                                                         bool wait_for_verity_dev) {
541     auto avb_handle = LoadAndVerifyVbmeta(*fstab_entry);
542     if (!avb_handle) {
543         return AvbHashtreeResult::kFail;
544     }
545 
546     return avb_handle->SetUpAvbHashtree(fstab_entry, wait_for_verity_dev);
547 }
548 
SetUpAvbHashtree(FstabEntry * fstab_entry,bool wait_for_verity_dev)549 AvbHashtreeResult AvbHandle::SetUpAvbHashtree(FstabEntry* fstab_entry, bool wait_for_verity_dev) {
550     if (!fstab_entry || status_ == AvbHandleStatus::kUninitialized || vbmeta_images_.size() < 1) {
551         return AvbHashtreeResult::kFail;
552     }
553 
554     if (status_ == AvbHandleStatus::kHashtreeDisabled ||
555         status_ == AvbHandleStatus::kVerificationDisabled) {
556         LINFO << "AVB HASHTREE disabled on: " << fstab_entry->mount_point;
557         return AvbHashtreeResult::kDisabled;
558     }
559 
560     if (!LoadAvbHashtreeToEnableVerity(fstab_entry, wait_for_verity_dev, vbmeta_images_,
561                                        slot_suffix_, other_slot_suffix_)) {
562         return AvbHashtreeResult::kFail;
563     }
564 
565     return AvbHashtreeResult::kSuccess;
566 }
567 
TearDownAvbHashtree(FstabEntry * fstab_entry,bool wait)568 bool AvbHandle::TearDownAvbHashtree(FstabEntry* fstab_entry, bool wait) {
569     if (!fstab_entry) {
570         return false;
571     }
572 
573     const std::string device_name(GetVerityDeviceName(*fstab_entry));
574 
575     // TODO: remove duplicated code with UnmapDevice()
576     android::dm::DeviceMapper& dm = android::dm::DeviceMapper::Instance();
577     std::string path;
578     if (wait) {
579         dm.GetDmDevicePathByName(device_name, &path);
580     }
581     if (!dm.DeleteDevice(device_name)) {
582         return false;
583     }
584     if (!path.empty() && !WaitForFile(path, 1000ms, FileWaitMode::DoesNotExist)) {
585         return false;
586     }
587 
588     return true;
589 }
590 
GetSecurityPatchLevel(const FstabEntry & fstab_entry) const591 std::string AvbHandle::GetSecurityPatchLevel(const FstabEntry& fstab_entry) const {
592     if (vbmeta_images_.size() < 1) {
593         return "";
594     }
595     std::string avb_partition_name =
596             DeriveAvbPartitionName(fstab_entry, slot_suffix_, other_slot_suffix_);
597     auto avb_prop_name = "com.android.build." + avb_partition_name + ".security_patch";
598     return GetAvbPropertyDescriptor(avb_prop_name, vbmeta_images_);
599 }
600 
IsDeviceUnlocked()601 bool AvbHandle::IsDeviceUnlocked() {
602     return android::fs_mgr::IsDeviceUnlocked();
603 }
604 
605 }  // namespace fs_mgr
606 }  // namespace android
607