• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 "keymaster_hidl_hal_test"
18 #include <cutils/log.h>
19 
20 #include "Keymaster4_1HidlTest.h"
21 
22 #include <cutils/properties.h>
23 
24 #include <openssl/x509.h>
25 
26 #include <keymasterV4_1/attestation_record.h>
27 #include <keymasterV4_1/authorization_set.h>
28 
29 // Not to dump the attestation by default. Can enable by specify the parameter
30 // "--dump_attestations" on lunching VTS
31 static bool dumpAttestations = false;
32 
33 namespace android::hardware::keymaster::V4_0 {
34 
operator ==(const AuthorizationSet & a,const AuthorizationSet & b)35 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
36     return std::equal(a.begin(), a.end(), b.begin(), b.end());
37 }
38 
39 }  // namespace android::hardware::keymaster::V4_0
40 
41 namespace android::hardware::keymaster::V4_1 {
42 
operator <<(::std::ostream & os,Tag tag)43 inline ::std::ostream& operator<<(::std::ostream& os, Tag tag) {
44     return os << toString(tag);
45 }
46 
47 namespace test {
48 
49 using std::string;
50 using std::tuple;
51 
52 namespace {
53 
54 char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
55                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
56 
bin2hex(const hidl_vec<uint8_t> & data)57 string bin2hex(const hidl_vec<uint8_t>& data) {
58     string retval;
59     retval.reserve(data.size() * 2 + 1);
60     for (uint8_t byte : data) {
61         retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
62         retval.push_back(nibble2hex[0x0F & byte]);
63     }
64     return retval;
65 }
66 
dumpContent(string content)67 inline void dumpContent(string content) {
68     std::cout << content << std::endl;
69 }
70 
71 struct AuthorizationSetDifferences {
72     string aName;
73     string bName;
74     AuthorizationSet aWhackB;
75     AuthorizationSet bWhackA;
76 };
77 
operator <<(std::ostream & o,const AuthorizationSetDifferences & diffs)78 std::ostream& operator<<(std::ostream& o, const AuthorizationSetDifferences& diffs) {
79     if (!diffs.aWhackB.empty()) {
80         o << "Set " << diffs.aName << " contains the following that " << diffs.bName << " does not"
81           << diffs.aWhackB;
82         if (!diffs.bWhackA.empty()) o << std::endl;
83     }
84 
85     if (!diffs.bWhackA.empty()) {
86         o << "Set " << diffs.bName << " contains the following that " << diffs.aName << " does not"
87           << diffs.bWhackA;
88     }
89     return o;
90 }
91 
92 // Computes and returns a \ b and b \ a ('\' is the set-difference operator, a \ b means all the
93 // elements that are in a but not b, i.e. take a and whack all the elements in b) to the provided
94 // stream.  The sets must be sorted.
95 //
96 // This provides a simple and clear view of how the two sets differ, generally much
97 // easier than scrutinizing printouts of the two sets.
difference(string aName,const AuthorizationSet & a,string bName,const AuthorizationSet & b)98 AuthorizationSetDifferences difference(string aName, const AuthorizationSet& a, string bName,
99                                        const AuthorizationSet& b) {
100     AuthorizationSetDifferences diffs = {std::move(aName), std::move(bName), {}, {}};
101     std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(diffs.aWhackB));
102     std::set_difference(b.begin(), b.end(), a.begin(), a.end(), std::back_inserter(diffs.bWhackA));
103     return diffs;
104 }
105 
106 #define DIFFERENCE(a, b) difference(#a, a, #b, b)
107 
check_root_of_trust(const RootOfTrust & root_of_trust)108 void check_root_of_trust(const RootOfTrust& root_of_trust) {
109     char vb_meta_device_state[PROPERTY_VALUE_MAX];
110     if (property_get("ro.boot.vbmeta.device_state", vb_meta_device_state, "") == 0) return;
111 
112     char vb_meta_digest[PROPERTY_VALUE_MAX];
113     EXPECT_GT(property_get("ro.boot.vbmeta.digest", vb_meta_digest, ""), 0);
114     EXPECT_EQ(vb_meta_digest, bin2hex(root_of_trust.verified_boot_hash));
115 
116     // Verified boot key should be all 0's if the boot state is not verified or self signed
117     HidlBuf empty_boot_key(string(32, '\0'));
118 
119     char vb_meta_bootstate[PROPERTY_VALUE_MAX];
120     auto& verified_boot_key = root_of_trust.verified_boot_key;
121     auto& verified_boot_state = root_of_trust.verified_boot_state;
122     EXPECT_GT(property_get("ro.boot.verifiedbootstate", vb_meta_bootstate, ""), 0);
123     if (!strcmp(vb_meta_bootstate, "green")) {
124         EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_VERIFIED);
125         EXPECT_NE(verified_boot_key, empty_boot_key);
126     } else if (!strcmp(vb_meta_bootstate, "yellow")) {
127         EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_SELF_SIGNED);
128         EXPECT_NE(verified_boot_key, empty_boot_key);
129     } else if (!strcmp(vb_meta_bootstate, "orange")) {
130         EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_UNVERIFIED);
131         EXPECT_EQ(verified_boot_key, empty_boot_key);
132     } else if (!strcmp(vb_meta_bootstate, "red")) {
133         EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_FAILED);
134     } else {
135         EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_UNVERIFIED);
136         EXPECT_EQ(verified_boot_key, empty_boot_key);
137     }
138 }
139 
tag_in_list(const KeyParameter & entry)140 bool tag_in_list(const KeyParameter& entry) {
141     // Attestations don't contain everything in key authorization lists, so we need to filter
142     // the key lists to produce the lists that we expect to match the attestations.
143     auto tag_list = {
144             Tag::INCLUDE_UNIQUE_ID, Tag::BLOB_USAGE_REQUIREMENTS, Tag::EC_CURVE,
145             Tag::HARDWARE_TYPE,     Tag::VENDOR_PATCHLEVEL,       Tag::BOOT_PATCHLEVEL,
146             Tag::CREATION_DATETIME,
147     };
148     return std::find(tag_list.begin(), tag_list.end(), (V4_1::Tag)entry.tag) != tag_list.end();
149 }
150 
filter_tags(const AuthorizationSet & set)151 AuthorizationSet filter_tags(const AuthorizationSet& set) {
152     AuthorizationSet filtered;
153     std::remove_copy_if(set.begin(), set.end(), std::back_inserter(filtered), tag_in_list);
154     return filtered;
155 }
156 
check_attestation_record(AttestationRecord attestation,const HidlBuf & challenge,AuthorizationSet expected_sw_enforced,AuthorizationSet expected_hw_enforced,SecurityLevel expected_security_level)157 void check_attestation_record(AttestationRecord attestation, const HidlBuf& challenge,
158                               AuthorizationSet expected_sw_enforced,
159                               AuthorizationSet expected_hw_enforced,
160                               SecurityLevel expected_security_level) {
161     EXPECT_EQ(41U, attestation.keymaster_version);
162     EXPECT_EQ(4U, attestation.attestation_version);
163     EXPECT_EQ(expected_security_level, attestation.attestation_security_level);
164     EXPECT_EQ(expected_security_level, attestation.keymaster_security_level);
165     EXPECT_EQ(challenge, attestation.attestation_challenge);
166 
167     check_root_of_trust(attestation.root_of_trust);
168 
169     // Sort all of the authorization lists, so that equality matching works.
170     expected_sw_enforced.Sort();
171     expected_hw_enforced.Sort();
172     attestation.software_enforced.Sort();
173     attestation.hardware_enforced.Sort();
174 
175     EXPECT_EQ(filter_tags(expected_sw_enforced), filter_tags(attestation.software_enforced))
176             << DIFFERENCE(expected_sw_enforced, attestation.software_enforced);
177     EXPECT_EQ(filter_tags(expected_hw_enforced), filter_tags(attestation.hardware_enforced))
178             << DIFFERENCE(expected_hw_enforced, attestation.hardware_enforced);
179 }
180 
181 }  // namespace
182 
183 using std::string;
184 using DeviceUniqueAttestationTest = Keymaster4_1HidlTest;
185 
TEST_P(DeviceUniqueAttestationTest,NonStrongBoxOnly)186 TEST_P(DeviceUniqueAttestationTest, NonStrongBoxOnly) {
187     if (SecLevel() == SecurityLevel::STRONGBOX) return;
188 
189     ASSERT_EQ(ErrorCode::OK, convert(GenerateKey(AuthorizationSetBuilder()
190                                                          .Authorization(TAG_NO_AUTH_REQUIRED)
191                                                          .RsaSigningKey(2048, 65537)
192                                                          .Digest(Digest::SHA_2_256)
193                                                          .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
194                                                          .Authorization(TAG_INCLUDE_UNIQUE_ID))));
195 
196     hidl_vec<hidl_vec<uint8_t>> cert_chain;
197     EXPECT_EQ(ErrorCode::UNIMPLEMENTED,
198               convert(AttestKey(
199                       AuthorizationSetBuilder()
200                               .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
201                               .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
202                               .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
203                       &cert_chain)));
204     CheckedDeleteKey();
205 
206     ASSERT_EQ(ErrorCode::OK, convert(GenerateKey(AuthorizationSetBuilder()
207                                                          .Authorization(TAG_NO_AUTH_REQUIRED)
208                                                          .EcdsaSigningKey(EcCurve::P_256)
209                                                          .Digest(Digest::SHA_2_256)
210                                                          .Authorization(TAG_INCLUDE_UNIQUE_ID))));
211 
212     EXPECT_EQ(ErrorCode::UNIMPLEMENTED,
213               convert(AttestKey(
214                       AuthorizationSetBuilder()
215                               .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
216                               .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
217                               .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
218                       &cert_chain)));
219     CheckedDeleteKey();
220 }
221 
TEST_P(DeviceUniqueAttestationTest,Rsa)222 TEST_P(DeviceUniqueAttestationTest, Rsa) {
223     if (SecLevel() != SecurityLevel::STRONGBOX) return;
224     ASSERT_EQ(ErrorCode::OK,
225               convert(GenerateKey(AuthorizationSetBuilder()
226                                   .Authorization(TAG_NO_AUTH_REQUIRED)
227                                   .RsaSigningKey(2048, 65537)
228                                   .Digest(Digest::SHA_2_256)
229                                   .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
230                                   .Authorization(TAG_INCLUDE_UNIQUE_ID))));
231 
232     hidl_vec<hidl_vec<uint8_t>> cert_chain;
233     HidlBuf challenge("challenge");
234     HidlBuf app_id("foo");
235     EXPECT_EQ(ErrorCode::OK,
236               convert(AttestKey(AuthorizationSetBuilder()
237                                         .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
238                                         .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
239                                         .Authorization(TAG_ATTESTATION_APPLICATION_ID, app_id),
240                                 &cert_chain)));
241 
242     EXPECT_EQ(2U, cert_chain.size());
243     if (dumpAttestations) dumpContent(bin2hex(cert_chain[0]));
244     auto [err, attestation] = parse_attestation_record(cert_chain[0]);
245     ASSERT_EQ(ErrorCode::OK, err);
246 
247     check_attestation_record(attestation, challenge,
248                              /* sw_enforced */
249                              AuthorizationSetBuilder()
250                                      .Authorization(TAG_ATTESTATION_APPLICATION_ID, app_id),
251                              /* hw_enforced */
252                              AuthorizationSetBuilder()
253                                      .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
254                                      .Authorization(TAG_NO_AUTH_REQUIRED)
255                                      .RsaSigningKey(2048, 65537)
256                                      .Digest(Digest::SHA_2_256)
257                                      .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
258                                      .Authorization(TAG_ORIGIN, KeyOrigin::GENERATED)
259                                      .Authorization(TAG_OS_VERSION, os_version())
260                                      .Authorization(TAG_OS_PATCHLEVEL, os_patch_level()),
261                              SecLevel());
262 }
263 
TEST_P(DeviceUniqueAttestationTest,Ecdsa)264 TEST_P(DeviceUniqueAttestationTest, Ecdsa) {
265     if (SecLevel() != SecurityLevel::STRONGBOX) return;
266     ASSERT_EQ(ErrorCode::OK,
267               convert(GenerateKey(AuthorizationSetBuilder()
268                                           .Authorization(TAG_NO_AUTH_REQUIRED)
269                                           .EcdsaSigningKey(256)
270                                           .Digest(Digest::SHA_2_256)
271                                           .Authorization(TAG_INCLUDE_UNIQUE_ID))));
272 
273     hidl_vec<hidl_vec<uint8_t>> cert_chain;
274     HidlBuf challenge("challenge");
275     HidlBuf app_id("foo");
276     EXPECT_EQ(ErrorCode::OK,
277               convert(AttestKey(AuthorizationSetBuilder()
278                                         .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
279                                         .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
280                                         .Authorization(TAG_ATTESTATION_APPLICATION_ID, app_id),
281                                 &cert_chain)));
282 
283     EXPECT_EQ(2U, cert_chain.size());
284     if (dumpAttestations) dumpContent(bin2hex(cert_chain[0]));
285     auto [err, attestation] = parse_attestation_record(cert_chain[0]);
286     ASSERT_EQ(ErrorCode::OK, err);
287 
288     check_attestation_record(attestation, challenge,
289             /* sw_enforced */
290             AuthorizationSetBuilder().Authorization(TAG_ATTESTATION_APPLICATION_ID, app_id),
291             /* hw_enforced */
292             AuthorizationSetBuilder()
293                     .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
294                     .Authorization(TAG_NO_AUTH_REQUIRED)
295                     .EcdsaSigningKey(256)
296                     .Digest(Digest::SHA_2_256)
297                     .Authorization(TAG_EC_CURVE, EcCurve::P_256)
298                     .Authorization(TAG_ORIGIN, KeyOrigin::GENERATED)
299                     .Authorization(TAG_OS_VERSION, os_version())
300                     .Authorization(TAG_OS_PATCHLEVEL, os_patch_level()),
301             SecLevel());
302 }
303 
304 INSTANTIATE_KEYMASTER_4_1_HIDL_TEST(DeviceUniqueAttestationTest);
305 
306 }  // namespace test
307 }  // namespace android::hardware::keymaster::V4_1
308 
main(int argc,char ** argv)309 int main(int argc, char** argv) {
310     ::testing::InitGoogleTest(&argc, argv);
311     for (int i = 1; i < argc; ++i) {
312         if (argv[i][0] == '-') {
313             if (std::string(argv[i]) == "--dump_attestations") {
314                 dumpAttestations = true;
315             }
316         }
317     }
318     int status = RUN_ALL_TESTS();
319     ALOGI("Test result = %d", status);
320     return status;
321 }
322