1 /*
2  * Copyright (C) 2023 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 #define LOG_TAG "keymint_1_bootloader_test"
18 
19 #include <memory>
20 #include <optional>
21 #include <string>
22 #include <vector>
23 
24 #include <android-base/properties.h>
25 #include <android/binder_manager.h>
26 #include <fstab/fstab.h>
27 #include <libavb/libavb.h>
28 #include <libavb_user/avb_ops_user.h>
29 #include <remote_prov/remote_prov_utils.h>
30 
31 #include "KeyMintAidlTestBase.h"
32 
33 namespace aidl::android::hardware::security::keymint::test {
34 
35 using ::android::getAidlHalInstanceNames;
36 using ::std::string;
37 using ::std::vector;
38 
39 // Since this test needs to talk to KeyMint HAL, it can only run as root. Thus,
40 // bootloader can not be locked.
41 class BootloaderStateTest : public KeyMintAidlTestBase {
42   public:
SetUp()43     virtual void SetUp() override {
44         KeyMintAidlTestBase::SetUp();
45 
46         // Generate a key with attestation.
47         vector<uint8_t> key_blob;
48         vector<KeyCharacteristics> key_characteristics;
49         AuthorizationSet keyDesc = AuthorizationSetBuilder()
50                                            .Authorization(TAG_NO_AUTH_REQUIRED)
51                                            .EcdsaSigningKey(EcCurve::P_256)
52                                            .AttestationChallenge("foo")
53                                            .AttestationApplicationId("bar")
54                                            .Digest(Digest::NONE)
55                                            .SetDefaultValidity();
56         auto result = GenerateKey(keyDesc, &key_blob, &key_characteristics);
57         ASSERT_EQ(ErrorCode::OK, result);
58 
59         // Parse attested AVB values.
60         X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
61         ASSERT_TRUE(cert.get());
62 
63         ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
64         ASSERT_TRUE(attest_rec);
65 
66         auto error = parse_root_of_trust(attest_rec->data, attest_rec->length, &attestedVbKey_,
67                                          &attestedVbState_, &attestedBootloaderState_,
68                                          &attestedVbmetaDigest_);
69         ASSERT_EQ(error, ErrorCode::OK);
70     }
71 
72     vector<uint8_t> attestedVbKey_;
73     VerifiedBoot attestedVbState_;
74     bool attestedBootloaderState_;
75     vector<uint8_t> attestedVbmetaDigest_;
76 };
77 
78 // Check that attested bootloader state is set to unlocked.
TEST_P(BootloaderStateTest,BootloaderIsUnlocked)79 TEST_P(BootloaderStateTest, BootloaderIsUnlocked) {
80     ASSERT_FALSE(attestedBootloaderState_)
81             << "This test runs as root. Bootloader must be unlocked.";
82 }
83 
84 // Check that verified boot state is set to "unverified", i.e. "orange".
TEST_P(BootloaderStateTest,VbStateIsUnverified)85 TEST_P(BootloaderStateTest, VbStateIsUnverified) {
86     // Unlocked bootloader implies that verified boot state must be "unverified".
87     ASSERT_EQ(attestedVbState_, VerifiedBoot::UNVERIFIED)
88             << "Verified boot state must be \"UNVERIFIED\" aka \"orange\".";
89 
90     // AVB spec stipulates that bootloader must set "androidboot.verifiedbootstate" parameter
91     // on the kernel command-line. This parameter is exposed to userspace as
92     // "ro.boot.verifiedbootstate" property.
93     auto vbStateProp = ::android::base::GetProperty("ro.boot.verifiedbootstate", "");
94     ASSERT_EQ(vbStateProp, "orange")
95             << "Verified boot state must be \"UNVERIFIED\" aka \"orange\".";
96 }
97 
98 // Following error codes from avb_slot_data() mean that slot data was loaded
99 // (even if verification failed).
avb_slot_data_loaded(AvbSlotVerifyResult result)100 static inline bool avb_slot_data_loaded(AvbSlotVerifyResult result) {
101     switch (result) {
102         case AVB_SLOT_VERIFY_RESULT_OK:
103         case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
104         case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
105         case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
106             return true;
107         default:
108             return false;
109     }
110 }
111 
112 // Check that attested vbmeta digest is correct.
TEST_P(BootloaderStateTest,VbmetaDigest)113 TEST_P(BootloaderStateTest, VbmetaDigest) {
114     AvbSlotVerifyData* avbSlotData;
115     auto suffix = fs_mgr_get_slot_suffix();
116     const char* partitions[] = {nullptr};
117     auto avbOps = avb_ops_user_new();
118 
119     // For VTS, devices run with vendor_boot-debug.img, which is not release key
120     // signed. Use AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR to bypass avb
121     // verification errors. This is OK since we only care about the digest for
122     // this test case.
123     auto result = avb_slot_verify(avbOps, partitions, suffix.c_str(),
124                                   AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR,
125                                   AVB_HASHTREE_ERROR_MODE_EIO, &avbSlotData);
126     ASSERT_TRUE(avb_slot_data_loaded(result)) << "Failed to load avb slot data";
127 
128     // Unfortunately, bootloader is not required to report the algorithm used
129     // to calculate the digest. There are only two supported options though,
130     // SHA256 and SHA512. Attested VBMeta digest must match one of these.
131     vector<uint8_t> digest256(AVB_SHA256_DIGEST_SIZE);
132     vector<uint8_t> digest512(AVB_SHA512_DIGEST_SIZE);
133 
134     avb_slot_verify_data_calculate_vbmeta_digest(avbSlotData, AVB_DIGEST_TYPE_SHA256,
135                                                  digest256.data());
136     avb_slot_verify_data_calculate_vbmeta_digest(avbSlotData, AVB_DIGEST_TYPE_SHA512,
137                                                  digest512.data());
138 
139     ASSERT_TRUE((attestedVbmetaDigest_ == digest256) || (attestedVbmetaDigest_ == digest512))
140             << "Attested vbmeta digest (" << bin2hex(attestedVbmetaDigest_)
141             << ") does not match computed digest (sha256: " << bin2hex(digest256)
142             << ", sha512: " << bin2hex(digest512) << ").";
143 }
144 
145 INSTANTIATE_KEYMINT_AIDL_TEST(BootloaderStateTest);
146 
147 }  // namespace aidl::android::hardware::security::keymint::test
148