xref: /aosp_15_r20/hardware/interfaces/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp (revision 4d7e907c777eeecc4c5bd7cf640a754fac206ff7)
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 #include "KeyMintAidlTestBase.h"
18 
19 #include <chrono>
20 #include <fstream>
21 #include <unordered_set>
22 #include <vector>
23 #include "aidl/android/hardware/security/keymint/AttestationKey.h"
24 #include "aidl/android/hardware/security/keymint/ErrorCode.h"
25 #include "keymint_support/authorization_set.h"
26 #include "keymint_support/keymint_tags.h"
27 
28 #include <android-base/logging.h>
29 #include <android-base/strings.h>
30 #include <android/binder_manager.h>
31 #include <android/content/pm/IPackageManagerNative.h>
32 #include <cppbor_parse.h>
33 #include <cutils/properties.h>
34 #include <gmock/gmock.h>
35 #include <openssl/evp.h>
36 #include <openssl/mem.h>
37 #include <remote_prov/remote_prov_utils.h>
38 
39 #include <keymaster/cppcose/cppcose.h>
40 #include <keymint_support/key_param_output.h>
41 #include <keymint_support/keymint_utils.h>
42 #include <keymint_support/openssl_utils.h>
43 
44 namespace aidl::android::hardware::security::keymint {
45 
46 using namespace cppcose;
47 using namespace std::literals::chrono_literals;
48 using std::endl;
49 using std::optional;
50 using std::unique_ptr;
51 using ::testing::AssertionFailure;
52 using ::testing::AssertionResult;
53 using ::testing::AssertionSuccess;
54 using ::testing::ElementsAreArray;
55 using ::testing::MatchesRegex;
56 using ::testing::Not;
57 
operator <<(::std::ostream & os,const AuthorizationSet & set)58 ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
59     if (set.size() == 0)
60         os << "(Empty)" << ::std::endl;
61     else {
62         os << "\n";
63         for (auto& entry : set) os << entry << ::std::endl;
64     }
65     return os;
66 }
67 
68 namespace test {
69 
70 namespace {
71 
72 // Possible values for the feature version.  Assumes that future KeyMint versions
73 // will continue with the 100 * AIDL_version numbering scheme.
74 //
75 // Must be kept in numerically increasing order.
76 const int32_t kFeatureVersions[] = {10,  11,  20,  30,  40,  41,  100, 200,
77                                     300, 400, 500, 600, 700, 800, 900};
78 
79 // Invalid value for a patchlevel (which is of form YYYYMMDD).
80 const uint32_t kInvalidPatchlevel = 99998877;
81 
82 // Overhead for PKCS#1 v1.5 signature padding of undigested messages.  Digested messages have
83 // additional overhead, for the digest algorithmIdentifier required by PKCS#1.
84 const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
85 
86 // Determine whether the key description is for an asymmetric key.
is_asymmetric(const AuthorizationSet & key_desc)87 bool is_asymmetric(const AuthorizationSet& key_desc) {
88     auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
89     if (algorithm && (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
90         return true;
91     } else {
92         return false;
93     }
94 }
95 
count_tag_invalid_entries(const std::vector<KeyParameter> & authorizations)96 size_t count_tag_invalid_entries(const std::vector<KeyParameter>& authorizations) {
97     return std::count_if(authorizations.begin(), authorizations.end(),
98                          [](const KeyParameter& e) -> bool { return e.tag == Tag::INVALID; });
99 }
100 
101 typedef KeyMintAidlTestBase::KeyData KeyData;
102 // Predicate for testing basic characteristics validity in generation or import.
KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,const vector<KeyCharacteristics> & key_characteristics,int32_t aidl_version)103 bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
104                                       const vector<KeyCharacteristics>& key_characteristics,
105                                       int32_t aidl_version) {
106     if (key_characteristics.empty()) return false;
107 
108     std::unordered_set<SecurityLevel> levels_seen;
109     for (auto& entry : key_characteristics) {
110         if (entry.authorizations.empty()) {
111             GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
112             return false;
113         }
114 
115         // There was no test to assert that INVALID tag should not present in authorization list
116         // before Keymint V3, so there are some Keymint implementations where asserting for INVALID
117         // tag fails(b/297306437), hence skipping for Keymint < 3.
118         if (aidl_version >= 3) {
119             EXPECT_EQ(count_tag_invalid_entries(entry.authorizations), 0);
120         }
121 
122         // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
123         if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
124 
125         if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
126             GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
127             return false;
128         }
129         levels_seen.insert(entry.securityLevel);
130 
131         // Generally, we should only have one entry, at the same security level as the KM
132         // instance.  There is an exception: StrongBox KM can have some authorizations that are
133         // enforced by the TEE.
134         bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
135                                        (secLevel == SecurityLevel::STRONGBOX &&
136                                         entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
137 
138         if (!isExpectedSecurityLevel) {
139             GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
140             return false;
141         }
142     }
143     return true;
144 }
145 
check_crl_distribution_points_extension_not_present(X509 * certificate)146 void check_crl_distribution_points_extension_not_present(X509* certificate) {
147     ASN1_OBJECT_Ptr crl_dp_oid(OBJ_txt2obj(kCrlDPOid, 1 /* dotted string format */));
148     ASSERT_TRUE(crl_dp_oid.get());
149 
150     int location =
151             X509_get_ext_by_OBJ(certificate, crl_dp_oid.get(), -1 /* search from beginning */);
152     ASSERT_EQ(location, -1);
153 }
154 
check_attestation_version(uint32_t attestation_version,int32_t aidl_version)155 void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
156     // Version numbers in attestation extensions should be a multiple of 100.
157     EXPECT_EQ(attestation_version % 100, 0);
158 
159     // The multiplier should never be higher than the AIDL version, but can be less
160     // (for example, if the implementation is from an earlier version but the HAL service
161     // uses the default libraries and so reports the current AIDL version).
162     EXPECT_LE((attestation_version / 100), aidl_version);
163 }
164 
avb_verification_enabled()165 bool avb_verification_enabled() {
166     char value[PROPERTY_VALUE_MAX];
167     return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
168 }
169 
170 char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
171                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
172 
173 // Attestations don't completely align with key authorization lists, so we need to filter the lists
174 // to include only the tags that are in both.
175 auto kTagsToFilter = {
176         Tag::CREATION_DATETIME,
177         Tag::HARDWARE_TYPE,
178         Tag::INCLUDE_UNIQUE_ID,
179         Tag::MODULE_HASH,
180 };
181 
filtered_tags(const AuthorizationSet & set)182 AuthorizationSet filtered_tags(const AuthorizationSet& set) {
183     AuthorizationSet filtered;
184     std::remove_copy_if(
185             set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
186                 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
187                        kTagsToFilter.end();
188             });
189     return filtered;
190 }
191 
192 // Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
strip_keystore_tags(vector<KeyCharacteristics> * characteristics)193 void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
194     characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
195                                           [](const auto& entry) {
196                                               return entry.securityLevel == SecurityLevel::KEYSTORE;
197                                           }),
198                            characteristics->end());
199 }
200 
x509NameToStr(X509_NAME * name)201 string x509NameToStr(X509_NAME* name) {
202     char* s = X509_NAME_oneline(name, nullptr, 0);
203     string retval(s);
204     OPENSSL_free(s);
205     return retval;
206 }
207 
208 }  // namespace
209 
210 bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
211 bool KeyMintAidlTestBase::dump_Attestations = false;
212 std::string KeyMintAidlTestBase::keyblob_dir;
213 std::optional<bool> KeyMintAidlTestBase::expect_upgrade = std::nullopt;
214 
~KeyBlobDeleter()215 KeyBlobDeleter::~KeyBlobDeleter() {
216     if (key_blob_.empty()) {
217         return;
218     }
219     Status result = keymint_->deleteKey(key_blob_);
220     key_blob_.clear();
221     EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << "\n";
222     ErrorCode rc = GetReturnErrorCode(result);
223     EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED) << result << "\n";
224 }
225 
boot_patch_level(const vector<KeyCharacteristics> & key_characteristics)226 uint32_t KeyMintAidlTestBase::boot_patch_level(
227         const vector<KeyCharacteristics>& key_characteristics) {
228     // The boot patchlevel is not available as a property, but should be present
229     // in the key characteristics of any created key.
230     AuthorizationSet allAuths;
231     for (auto& entry : key_characteristics) {
232         allAuths.push_back(AuthorizationSet(entry.authorizations));
233     }
234     auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
235     if (patchlevel.has_value()) {
236         return patchlevel.value();
237     } else {
238         // No boot patchlevel is available. Return a value that won't match anything
239         // and so will trigger test failures.
240         return kInvalidPatchlevel;
241     }
242 }
243 
boot_patch_level()244 uint32_t KeyMintAidlTestBase::boot_patch_level() {
245     return boot_patch_level(key_characteristics_);
246 }
247 
getModuleHash()248 std::optional<vector<uint8_t>> KeyMintAidlTestBase::getModuleHash() {
249     if (AidlVersion() < 4) {
250         // The `MODULE_HASH` tag was introduced in v4 of the HAL; earlier versions should never
251         // expect to encounter it.
252         return std::nullopt;
253     }
254 
255     // The KeyMint instance should already have been informed of the `MODULE_HASH` value for the
256     // currently running system. Generate a single attestation so we can find out what the value
257     // is.
258     auto challenge = "hello";
259     auto app_id = "foo";
260     auto params = AuthorizationSetBuilder()
261                           .EcdsaSigningKey(EcCurve::P_256)
262                           .Digest(Digest::NONE)
263                           .Authorization(TAG_NO_AUTH_REQUIRED)
264                           .AttestationChallenge(challenge)
265                           .AttestationApplicationId(app_id)
266                           .SetDefaultValidity();
267     vector<uint8_t> key_blob;
268     vector<KeyCharacteristics> key_characteristics;
269     vector<Certificate> chain;
270     auto result = GenerateKey(params, &key_blob, &key_characteristics, &chain);
271     if (result != ErrorCode::OK) {
272         ADD_FAILURE() << "Failed to generate attestation:" << result;
273         return std::nullopt;
274     }
275     KeyBlobDeleter deleter(keymint_, key_blob);
276     if (chain.empty()) {
277         ADD_FAILURE() << "No attestation cert";
278         return std::nullopt;
279     }
280 
281     // Parse the attestation record in the leaf cert.
282     X509_Ptr cert(parse_cert_blob(chain[0].encodedCertificate));
283     if (cert.get() == nullptr) {
284         ADD_FAILURE() << "Failed to parse attestation cert";
285         return std::nullopt;
286     }
287     ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
288     if (attest_rec == nullptr) {
289         ADD_FAILURE() << "Failed to find attestation extension";
290         return std::nullopt;
291     }
292     AuthorizationSet att_sw_enforced;
293     AuthorizationSet att_hw_enforced;
294     uint32_t att_attestation_version;
295     uint32_t att_keymint_version;
296     SecurityLevel att_attestation_security_level;
297     SecurityLevel att_keymint_security_level;
298     vector<uint8_t> att_challenge;
299     vector<uint8_t> att_unique_id;
300     vector<uint8_t> att_app_id;
301 
302     auto error = parse_attestation_record(attest_rec->data,                 //
303                                           attest_rec->length,               //
304                                           &att_attestation_version,         //
305                                           &att_attestation_security_level,  //
306                                           &att_keymint_version,             //
307                                           &att_keymint_security_level,      //
308                                           &att_challenge,                   //
309                                           &att_sw_enforced,                 //
310                                           &att_hw_enforced,                 //
311                                           &att_unique_id);
312     if (error != ErrorCode::OK) {
313         ADD_FAILURE() << "Failed to parse attestation extension";
314         return std::nullopt;
315     }
316 
317     // The module hash should be present in the software-enforced list.
318     if (!att_sw_enforced.Contains(TAG_MODULE_HASH)) {
319         ADD_FAILURE() << "No TAG_MODULE_HASH in attestation extension";
320         return std::nullopt;
321     }
322     return att_sw_enforced.GetTagValue(TAG_MODULE_HASH);
323 }
324 
325 /**
326  * An API to determine device IDs attestation is required or not,
327  * which is mandatory for KeyMint version 2 and first_api_level 33 or greater.
328  */
isDeviceIdAttestationRequired()329 bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
330     return AidlVersion() >= 2 && property_get_int32("ro.vendor.api_level", 0) >= __ANDROID_API_T__;
331 }
332 
333 /**
334  * An API to determine second IMEI ID attestation is required or not,
335  * which is supported for KeyMint version 3 or first_api_level greater than 33.
336  */
isSecondImeiIdAttestationRequired()337 bool KeyMintAidlTestBase::isSecondImeiIdAttestationRequired() {
338     return AidlVersion() >= 3 && property_get_int32("ro.vendor.api_level", 0) > __ANDROID_API_T__;
339 }
340 
isRkpOnly()341 std::optional<bool> KeyMintAidlTestBase::isRkpOnly() {
342     // GSI replaces the values for remote_prov_prop properties (since they’re system_internal_prop
343     // properties), so on GSI the properties are not reliable indicators of whether StrongBox/TEE is
344     // RKP-only or not.
345     if (is_gsi_image()) {
346         return std::nullopt;
347     }
348     if (SecLevel() == SecurityLevel::STRONGBOX) {
349         return property_get_bool("remote_provisioning.strongbox.rkp_only", false);
350     }
351     return property_get_bool("remote_provisioning.tee.rkp_only", false);
352 }
353 
Curve25519Supported()354 bool KeyMintAidlTestBase::Curve25519Supported() {
355     // Strongbox never supports curve 25519.
356     if (SecLevel() == SecurityLevel::STRONGBOX) {
357         return false;
358     }
359 
360     // Curve 25519 was included in version 2 of the KeyMint interface.
361     return AidlVersion() >= 2;
362 }
363 
InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint)364 void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
365     ASSERT_NE(keyMint, nullptr);
366     keymint_ = std::move(keyMint);
367 
368     KeyMintHardwareInfo info;
369     ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
370 
371     securityLevel_ = info.securityLevel;
372     name_.assign(info.keyMintName.begin(), info.keyMintName.end());
373     author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
374     timestamp_token_required_ = info.timestampTokenRequired;
375 
376     os_version_ = getOsVersion();
377     os_patch_level_ = getOsPatchlevel();
378     vendor_patch_level_ = getVendorPatchlevel();
379 
380     // TODO(b/369375199): temporary code, remove when apexd -> keystore2 -> KeyMint transmission
381     // of module info happens.
382     {
383         GTEST_LOG_(INFO) << "Setting MODULE_HASH to fake value as fallback";
384         // Ensure that a MODULE_HASH value is definitely present in KeyMint (if it's >= v4).
385         vector<uint8_t> fakeModuleHash = {
386                 0xf3, 0xf1, 0x1f, 0xe5, 0x13, 0x05, 0xfe, 0xfa, 0xe9, 0xc3, 0x53,
387                 0xef, 0x69, 0xdf, 0x9f, 0xd7, 0x0c, 0x1e, 0xcc, 0x2c, 0x2c, 0x62,
388                 0x1f, 0x5e, 0x2c, 0x1d, 0x19, 0xa1, 0xfd, 0xac, 0xa1, 0xb4,
389         };
390         vector<KeyParameter> info = {Authorization(TAG_MODULE_HASH, fakeModuleHash)};
391         keymint_->setAdditionalAttestationInfo(info);
392     }
393 }
394 
AidlVersion() const395 int32_t KeyMintAidlTestBase::AidlVersion() const {
396     int32_t version = 0;
397     auto status = keymint_->getInterfaceVersion(&version);
398     if (!status.isOk()) {
399         ADD_FAILURE() << "Failed to determine interface version";
400     }
401     return version;
402 }
403 
SetUp()404 void KeyMintAidlTestBase::SetUp() {
405     if (AServiceManager_isDeclared(GetParam().c_str())) {
406         ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
407         InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
408     } else {
409         InitializeKeyMint(nullptr);
410     }
411 }
412 
GenerateKey(const AuthorizationSet & key_desc)413 ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc) {
414     return GenerateKey(key_desc, &key_blob_, &key_characteristics_);
415 }
416 
GenerateKey(const AuthorizationSet & key_desc,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics)417 ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
418                                            vector<uint8_t>* key_blob,
419                                            vector<KeyCharacteristics>* key_characteristics) {
420     return GenerateKey(key_desc, key_blob, key_characteristics, &cert_chain_);
421 }
422 
GenerateKey(const AuthorizationSet & key_desc,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics,vector<Certificate> * cert_chain)423 ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
424                                            vector<uint8_t>* key_blob,
425                                            vector<KeyCharacteristics>* key_characteristics,
426                                            vector<Certificate>* cert_chain) {
427     std::optional<AttestationKey> attest_key = std::nullopt;
428     vector<Certificate> attest_cert_chain;
429     // If an attestation is requested, but the system is RKP-only, we need to supply an explicit
430     // attestation key. Else the result is a key without an attestation.
431     // - If the RKP-only value is undeterminable (i.e., when running on GSI), generate and use the
432     //   `ATTEST_KEY` anyways.
433     // - In the case that using an `ATTEST_KEY` is not supported
434     //   (shouldSkipAttestKeyTest), assume the device has factory keys (so not RKP-only).
435     // - If the key being generated is a symmetric key (from test cases that check that the
436     //   attestation parameters are correctly ignored), don't try to use an `ATTEST_KEY`.
437     if (isRkpOnly().value_or(true) && key_desc.Contains(TAG_ATTESTATION_CHALLENGE) &&
438         !shouldSkipAttestKeyTest() && is_asymmetric(key_desc)) {
439         AuthorizationSet attest_key_desc =
440                 AuthorizationSetBuilder().EcdsaKey(EcCurve::P_256).AttestKey().SetDefaultValidity();
441         attest_key.emplace();
442         vector<KeyCharacteristics> attest_key_characteristics;
443         auto error = GenerateAttestKey(attest_key_desc, std::nullopt, &attest_key.value().keyBlob,
444                                        &attest_key_characteristics, &attest_cert_chain);
445         EXPECT_EQ(error, ErrorCode::OK);
446         EXPECT_EQ(attest_cert_chain.size(), 1);
447         attest_key.value().issuerSubjectName = make_name_from_str("Android Keystore Key");
448     }
449 
450     ErrorCode error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
451 
452     if (error == ErrorCode::OK && attest_cert_chain.size() > 0) {
453         cert_chain->push_back(attest_cert_chain[0]);
454     }
455 
456     return error;
457 }
458 
GenerateKey(const AuthorizationSet & key_desc,const optional<AttestationKey> & attest_key,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics,vector<Certificate> * cert_chain)459 ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
460                                            const optional<AttestationKey>& attest_key,
461                                            vector<uint8_t>* key_blob,
462                                            vector<KeyCharacteristics>* key_characteristics,
463                                            vector<Certificate>* cert_chain) {
464     EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null.  Test bug";
465     EXPECT_NE(key_characteristics, nullptr)
466             << "Previous characteristics not deleted before generating key.  Test bug.";
467 
468     KeyCreationResult creationResult;
469     Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
470     if (result.isOk()) {
471         EXPECT_PRED3(KeyCharacteristicsBasicallyValid, SecLevel(),
472                      creationResult.keyCharacteristics, AidlVersion());
473         EXPECT_GT(creationResult.keyBlob.size(), 0);
474         *key_blob = std::move(creationResult.keyBlob);
475         *key_characteristics = std::move(creationResult.keyCharacteristics);
476         *cert_chain = std::move(creationResult.certificateChain);
477 
478         if (is_asymmetric(key_desc)) {
479             EXPECT_GE(cert_chain->size(), 1);
480             if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
481                 if (attest_key) {
482                     EXPECT_EQ(cert_chain->size(), 1);
483                 } else {
484                     EXPECT_GT(cert_chain->size(), 1);
485                 }
486             }
487         } else {
488             // For symmetric keys there should be no certificates.
489             EXPECT_EQ(cert_chain->size(), 0);
490         }
491     }
492 
493     return GetReturnErrorCode(result);
494 }
495 
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics)496 ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
497                                          const string& key_material, vector<uint8_t>* key_blob,
498                                          vector<KeyCharacteristics>* key_characteristics) {
499     Status result;
500 
501     cert_chain_.clear();
502     key_characteristics->clear();
503     key_blob->clear();
504 
505     KeyCreationResult creationResult;
506     result = keymint_->importKey(key_desc.vector_data(), format,
507                                  vector<uint8_t>(key_material.begin(), key_material.end()),
508                                  {} /* attestationSigningKeyBlob */, &creationResult);
509 
510     if (result.isOk()) {
511         EXPECT_PRED3(KeyCharacteristicsBasicallyValid, SecLevel(),
512                      creationResult.keyCharacteristics, AidlVersion());
513         EXPECT_GT(creationResult.keyBlob.size(), 0);
514 
515         *key_blob = std::move(creationResult.keyBlob);
516         *key_characteristics = std::move(creationResult.keyCharacteristics);
517         cert_chain_ = std::move(creationResult.certificateChain);
518 
519         if (is_asymmetric(key_desc)) {
520             EXPECT_GE(cert_chain_.size(), 1);
521             if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
522         } else {
523             // For symmetric keys there should be no certificates.
524             EXPECT_EQ(cert_chain_.size(), 0);
525         }
526     }
527 
528     return GetReturnErrorCode(result);
529 }
530 
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material)531 ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
532                                          const string& key_material) {
533     return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
534 }
535 
ImportWrappedKey(string wrapped_key,string wrapping_key,const AuthorizationSet & wrapping_key_desc,string masking_key,const AuthorizationSet & unwrapping_params,int64_t password_sid,int64_t biometric_sid)536 ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
537                                                 const AuthorizationSet& wrapping_key_desc,
538                                                 string masking_key,
539                                                 const AuthorizationSet& unwrapping_params,
540                                                 int64_t password_sid, int64_t biometric_sid) {
541     EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
542 
543     key_characteristics_.clear();
544 
545     KeyCreationResult creationResult;
546     Status result = keymint_->importWrappedKey(
547             vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
548             vector<uint8_t>(masking_key.begin(), masking_key.end()),
549             unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
550 
551     if (result.isOk()) {
552         EXPECT_PRED3(KeyCharacteristicsBasicallyValid, SecLevel(),
553                      creationResult.keyCharacteristics, AidlVersion());
554         EXPECT_GT(creationResult.keyBlob.size(), 0);
555 
556         key_blob_ = std::move(creationResult.keyBlob);
557         key_characteristics_ = std::move(creationResult.keyCharacteristics);
558         cert_chain_ = std::move(creationResult.certificateChain);
559 
560         AuthorizationSet allAuths;
561         for (auto& entry : key_characteristics_) {
562             allAuths.push_back(AuthorizationSet(entry.authorizations));
563         }
564         if (is_asymmetric(allAuths)) {
565             EXPECT_GE(cert_chain_.size(), 1);
566         } else {
567             // For symmetric keys there should be no certificates.
568             EXPECT_EQ(cert_chain_.size(), 0);
569         }
570     }
571 
572     return GetReturnErrorCode(result);
573 }
574 
GetCharacteristics(const vector<uint8_t> & key_blob,const vector<uint8_t> & app_id,const vector<uint8_t> & app_data,vector<KeyCharacteristics> * key_characteristics)575 ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
576                                                   const vector<uint8_t>& app_id,
577                                                   const vector<uint8_t>& app_data,
578                                                   vector<KeyCharacteristics>* key_characteristics) {
579     Status result =
580             keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
581     return GetReturnErrorCode(result);
582 }
583 
GetCharacteristics(const vector<uint8_t> & key_blob,vector<KeyCharacteristics> * key_characteristics)584 ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
585                                                   vector<KeyCharacteristics>* key_characteristics) {
586     vector<uint8_t> empty_app_id, empty_app_data;
587     return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
588 }
589 
CheckCharacteristics(const vector<uint8_t> & key_blob,const vector<KeyCharacteristics> & generate_characteristics)590 void KeyMintAidlTestBase::CheckCharacteristics(
591         const vector<uint8_t>& key_blob,
592         const vector<KeyCharacteristics>& generate_characteristics) {
593     // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
594     // generateKey() should be excluded, as KeyMint will have no record of them.
595     // This applies to CREATION_DATETIME in particular.
596     vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
597     strip_keystore_tags(&expected_characteristics);
598 
599     vector<KeyCharacteristics> retrieved;
600     ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
601     EXPECT_EQ(expected_characteristics, retrieved);
602 }
603 
CheckAppIdCharacteristics(const vector<uint8_t> & key_blob,std::string_view app_id_string,std::string_view app_data_string,const vector<KeyCharacteristics> & generate_characteristics)604 void KeyMintAidlTestBase::CheckAppIdCharacteristics(
605         const vector<uint8_t>& key_blob, std::string_view app_id_string,
606         std::string_view app_data_string,
607         const vector<KeyCharacteristics>& generate_characteristics) {
608     // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
609     vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
610     strip_keystore_tags(&expected_characteristics);
611 
612     vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
613     vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
614     vector<KeyCharacteristics> retrieved;
615     ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
616     EXPECT_EQ(expected_characteristics, retrieved);
617 
618     // Check that key characteristics can't be retrieved if the app ID or app data is missing.
619     vector<uint8_t> empty;
620     vector<KeyCharacteristics> not_retrieved;
621     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
622               GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
623     EXPECT_EQ(not_retrieved.size(), 0);
624 
625     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
626               GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
627     EXPECT_EQ(not_retrieved.size(), 0);
628 
629     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
630               GetCharacteristics(key_blob, empty, empty, &not_retrieved));
631     EXPECT_EQ(not_retrieved.size(), 0);
632 }
633 
DeleteKey(vector<uint8_t> * key_blob,bool keep_key_blob)634 ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
635     Status result = keymint_->deleteKey(*key_blob);
636     if (!keep_key_blob) {
637         *key_blob = vector<uint8_t>();
638     }
639 
640     EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
641     return GetReturnErrorCode(result);
642 }
643 
DeleteKey(bool keep_key_blob)644 ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
645     return DeleteKey(&key_blob_, keep_key_blob);
646 }
647 
DeleteAllKeys()648 ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
649     Status result = keymint_->deleteAllKeys();
650     EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
651     return GetReturnErrorCode(result);
652 }
653 
DestroyAttestationIds()654 ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
655     Status result = keymint_->destroyAttestationIds();
656     return GetReturnErrorCode(result);
657 }
658 
CheckedDeleteKey()659 void KeyMintAidlTestBase::CheckedDeleteKey() {
660     ErrorCode result = DeleteKey(&key_blob_, /* keep_key_blob = */ false);
661     EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
662 }
663 
Begin(KeyPurpose purpose,const vector<uint8_t> & key_blob,const AuthorizationSet & in_params,AuthorizationSet * out_params,std::shared_ptr<IKeyMintOperation> & op)664 ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
665                                      const AuthorizationSet& in_params,
666                                      AuthorizationSet* out_params,
667                                      std::shared_ptr<IKeyMintOperation>& op) {
668     SCOPED_TRACE("Begin");
669     Status result;
670     BeginResult out;
671     result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
672 
673     if (result.isOk()) {
674         *out_params = out.params;
675         challenge_ = out.challenge;
676         op = out.operation;
677     }
678 
679     return GetReturnErrorCode(result);
680 }
681 
Begin(KeyPurpose purpose,const vector<uint8_t> & key_blob,const AuthorizationSet & in_params,AuthorizationSet * out_params,std::optional<HardwareAuthToken> hat)682 ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
683                                      const AuthorizationSet& in_params,
684                                      AuthorizationSet* out_params,
685                                      std::optional<HardwareAuthToken> hat) {
686     SCOPED_TRACE("Begin");
687     Status result;
688     BeginResult out;
689 
690     result = keymint_->begin(purpose, key_blob, in_params.vector_data(), hat, &out);
691 
692     if (result.isOk()) {
693         *out_params = out.params;
694         challenge_ = out.challenge;
695         op_ = out.operation;
696     }
697 
698     return GetReturnErrorCode(result);
699 }
700 
Begin(KeyPurpose purpose,const AuthorizationSet & in_params,AuthorizationSet * out_params)701 ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
702                                      AuthorizationSet* out_params) {
703     SCOPED_TRACE("Begin");
704     EXPECT_EQ(nullptr, op_);
705     return Begin(purpose, key_blob_, in_params, out_params);
706 }
707 
Begin(KeyPurpose purpose,const AuthorizationSet & in_params)708 ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
709     SCOPED_TRACE("Begin");
710     AuthorizationSet out_params;
711     ErrorCode result = Begin(purpose, in_params, &out_params);
712     EXPECT_TRUE(out_params.empty());
713     return result;
714 }
715 
UpdateAad(const string & input)716 ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
717     return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
718                                              {} /* hardwareAuthToken */,
719                                              {} /* verificationToken */));
720 }
721 
Update(const string & input,string * output)722 ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
723     SCOPED_TRACE("Update");
724 
725     Status result;
726     if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
727 
728     EXPECT_NE(op_, nullptr);
729     if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
730 
731     std::vector<uint8_t> o_put;
732     result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
733 
734     if (result.isOk()) {
735         output->append(o_put.begin(), o_put.end());
736     } else {
737         // Failure always terminates the operation.
738         op_ = {};
739     }
740 
741     return GetReturnErrorCode(result);
742 }
743 
Finish(const string & input,const string & signature,string * output,std::optional<HardwareAuthToken> hat,std::optional<secureclock::TimeStampToken> time_token)744 ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, string* output,
745                                       std::optional<HardwareAuthToken> hat,
746                                       std::optional<secureclock::TimeStampToken> time_token) {
747     SCOPED_TRACE("Finish");
748     Status result;
749 
750     EXPECT_NE(op_, nullptr);
751     if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
752 
753     vector<uint8_t> oPut;
754     result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
755                          vector<uint8_t>(signature.begin(), signature.end()), hat, time_token,
756                          {} /* confirmationToken */, &oPut);
757 
758     if (result.isOk()) output->append(oPut.begin(), oPut.end());
759 
760     op_ = {};
761     return GetReturnErrorCode(result);
762 }
763 
Abort(const std::shared_ptr<IKeyMintOperation> & op)764 ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
765     SCOPED_TRACE("Abort");
766 
767     EXPECT_NE(op, nullptr);
768     if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
769 
770     Status retval = op->abort();
771     EXPECT_TRUE(retval.isOk());
772     return static_cast<ErrorCode>(retval.getServiceSpecificError());
773 }
774 
Abort()775 ErrorCode KeyMintAidlTestBase::Abort() {
776     SCOPED_TRACE("Abort");
777 
778     EXPECT_NE(op_, nullptr);
779     if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
780 
781     Status retval = op_->abort();
782     return static_cast<ErrorCode>(retval.getServiceSpecificError());
783 }
784 
AbortIfNeeded()785 void KeyMintAidlTestBase::AbortIfNeeded() {
786     SCOPED_TRACE("AbortIfNeeded");
787     if (op_) {
788         EXPECT_EQ(ErrorCode::OK, Abort());
789         op_.reset();
790     }
791 }
792 
ProcessMessage(const vector<uint8_t> & key_blob,KeyPurpose operation,const string & message,const AuthorizationSet & in_params)793 auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
794                                          const string& message, const AuthorizationSet& in_params)
795         -> std::tuple<ErrorCode, string> {
796     AuthorizationSet begin_out_params;
797     ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
798     if (result != ErrorCode::OK) return {result, {}};
799 
800     string output;
801     return {Finish(message, &output), output};
802 }
803 
ProcessMessage(const vector<uint8_t> & key_blob,KeyPurpose operation,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)804 string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
805                                            const string& message, const AuthorizationSet& in_params,
806                                            AuthorizationSet* out_params) {
807     SCOPED_TRACE("ProcessMessage");
808     AuthorizationSet begin_out_params;
809     ErrorCode result = Begin(operation, key_blob, in_params, out_params);
810     EXPECT_EQ(ErrorCode::OK, result);
811     if (result != ErrorCode::OK) {
812         return "";
813     }
814 
815     string output;
816     EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
817     return output;
818 }
819 
SignMessage(const vector<uint8_t> & key_blob,const string & message,const AuthorizationSet & params)820 string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
821                                         const AuthorizationSet& params) {
822     SCOPED_TRACE("SignMessage");
823     AuthorizationSet out_params;
824     string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
825     EXPECT_TRUE(out_params.empty());
826     return signature;
827 }
828 
SignMessage(const string & message,const AuthorizationSet & params)829 string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
830     SCOPED_TRACE("SignMessage");
831     return SignMessage(key_blob_, message, params);
832 }
833 
MacMessage(const string & message,Digest digest,size_t mac_length)834 string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
835     SCOPED_TRACE("MacMessage");
836     return SignMessage(
837             key_blob_, message,
838             AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
839 }
840 
CheckAesIncrementalEncryptOperation(BlockMode block_mode,int message_size)841 void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
842                                                               int message_size) {
843     auto builder = AuthorizationSetBuilder()
844                            .Authorization(TAG_NO_AUTH_REQUIRED)
845                            .AesEncryptionKey(128)
846                            .BlockMode(block_mode)
847                            .Padding(PaddingMode::NONE);
848     if (block_mode == BlockMode::GCM) {
849         builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
850     }
851     ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
852 
853     for (int increment = 1; increment <= message_size; ++increment) {
854         string message(message_size, 'a');
855         auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
856         if (block_mode == BlockMode::GCM) {
857             params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
858         }
859 
860         AuthorizationSet output_params;
861         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
862 
863         string ciphertext;
864         string to_send;
865         for (size_t i = 0; i < message.size(); i += increment) {
866             EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
867         }
868         EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
869                 << "Error sending " << to_send << " with block mode " << block_mode;
870 
871         switch (block_mode) {
872             case BlockMode::GCM:
873                 EXPECT_EQ(message.size() + 16, ciphertext.size());
874                 break;
875             case BlockMode::CTR:
876                 EXPECT_EQ(message.size(), ciphertext.size());
877                 break;
878             case BlockMode::CBC:
879             case BlockMode::ECB:
880                 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
881                 break;
882         }
883 
884         auto iv = output_params.GetTagValue(TAG_NONCE);
885         switch (block_mode) {
886             case BlockMode::CBC:
887             case BlockMode::GCM:
888             case BlockMode::CTR:
889                 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
890                 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
891                 params.push_back(TAG_NONCE, iv->get());
892                 break;
893 
894             case BlockMode::ECB:
895                 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
896                 break;
897         }
898 
899         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
900                 << "Decrypt begin() failed for block mode " << block_mode;
901 
902         string plaintext;
903         for (size_t i = 0; i < ciphertext.size(); i += increment) {
904             EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
905         }
906         ErrorCode error = Finish(to_send, &plaintext);
907         ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
908                                         << " and increment " << increment;
909         if (error == ErrorCode::OK) {
910             ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
911                                           << " and increment " << increment;
912         }
913     }
914 }
915 
AesCheckEncryptOneByteAtATime(const string & key,BlockMode block_mode,PaddingMode padding_mode,const string & iv,const string & plaintext,const string & exp_cipher_text)916 void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
917                                                         PaddingMode padding_mode, const string& iv,
918                                                         const string& plaintext,
919                                                         const string& exp_cipher_text) {
920     bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
921     auto auth_set = AuthorizationSetBuilder()
922                             .Authorization(TAG_NO_AUTH_REQUIRED)
923                             .AesEncryptionKey(key.size() * 8)
924                             .BlockMode(block_mode)
925                             .Padding(padding_mode);
926     if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
927     if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
928     ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
929 
930     CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
931                                exp_cipher_text);
932 }
933 
CheckEncryptOneByteAtATime(BlockMode block_mode,const int block_size,PaddingMode padding_mode,const string & iv,const string & plaintext,const string & exp_cipher_text)934 void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
935                                                      PaddingMode padding_mode, const string& iv,
936                                                      const string& plaintext,
937                                                      const string& exp_cipher_text) {
938     bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
939     bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
940     auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
941     if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
942     if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
943 
944     AuthorizationSet output_params;
945     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
946 
947     string actual_ciphertext;
948     if (is_stream_cipher) {
949         // Assert that a 1 byte of output is produced for 1 byte of input.
950         // Every input byte produces an output byte.
951         for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
952             string ciphertext;
953             EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
954             // Some StrongBox implementations cannot support 1:1 input:output lengths, so
955             // we relax this API restriction for them.
956             if (SecLevel() != SecurityLevel::STRONGBOX) {
957                 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
958             }
959             actual_ciphertext.append(ciphertext);
960         }
961         string ciphertext;
962         EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
963         if (SecLevel() != SecurityLevel::STRONGBOX) {
964             string expected_final_output;
965             if (is_authenticated_cipher) {
966                 expected_final_output = exp_cipher_text.substr(plaintext.size());
967             }
968             EXPECT_EQ(expected_final_output, ciphertext);
969         }
970         actual_ciphertext.append(ciphertext);
971     } else {
972         // Assert that a block of output is produced once a full block of input is provided.
973         // Every input block produces an output block.
974         bool compare_output = true;
975         string additional_information;
976         int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
977         if (SecLevel() == SecurityLevel::STRONGBOX) {
978             // This is known to be broken on older vendor implementations.
979             if (vendor_api_level <= __ANDROID_API_U__) {
980                 compare_output = false;
981             } else {
982                 additional_information = " (b/194134359) ";
983             }
984         }
985         for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
986             string ciphertext;
987             EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
988             if (compare_output) {
989                 if ((plaintext_index % block_size) == block_size - 1) {
990                     // Update is expected to have output a new block
991                     EXPECT_EQ(block_size, ciphertext.size())
992                             << "plaintext index: " << plaintext_index << additional_information;
993                 } else {
994                     // Update is expected to have produced no output
995                     EXPECT_EQ(0, ciphertext.size())
996                             << "plaintext index: " << plaintext_index << additional_information;
997                 }
998             }
999             actual_ciphertext.append(ciphertext);
1000         }
1001         string ciphertext;
1002         EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
1003         actual_ciphertext.append(ciphertext);
1004     }
1005     // Regardless of how the completed ciphertext got accumulated, it should match the expected
1006     // ciphertext.
1007     EXPECT_EQ(exp_cipher_text, actual_ciphertext);
1008 }
1009 
CheckHmacTestVector(const string & key,const string & message,Digest digest,const string & expected_mac)1010 void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
1011                                               Digest digest, const string& expected_mac) {
1012     SCOPED_TRACE("CheckHmacTestVector");
1013     ASSERT_EQ(ErrorCode::OK,
1014               ImportKey(AuthorizationSetBuilder()
1015                                 .Authorization(TAG_NO_AUTH_REQUIRED)
1016                                 .HmacKey(key.size() * 8)
1017                                 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
1018                                 .Digest(digest),
1019                         KeyFormat::RAW, key));
1020     string signature = MacMessage(message, digest, expected_mac.size() * 8);
1021     EXPECT_EQ(expected_mac, signature)
1022             << "Test vector didn't match for key of size " << key.size() << " message of size "
1023             << message.size() << " and digest " << digest;
1024     CheckedDeleteKey();
1025 }
1026 
CheckAesCtrTestVector(const string & key,const string & nonce,const string & message,const string & expected_ciphertext)1027 void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
1028                                                 const string& message,
1029                                                 const string& expected_ciphertext) {
1030     SCOPED_TRACE("CheckAesCtrTestVector");
1031     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1032                                                .Authorization(TAG_NO_AUTH_REQUIRED)
1033                                                .AesEncryptionKey(key.size() * 8)
1034                                                .BlockMode(BlockMode::CTR)
1035                                                .Authorization(TAG_CALLER_NONCE)
1036                                                .Padding(PaddingMode::NONE),
1037                                        KeyFormat::RAW, key));
1038 
1039     auto params = AuthorizationSetBuilder()
1040                           .Authorization(TAG_NONCE, nonce.data(), nonce.size())
1041                           .BlockMode(BlockMode::CTR)
1042                           .Padding(PaddingMode::NONE);
1043     AuthorizationSet out_params;
1044     string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
1045     EXPECT_EQ(expected_ciphertext, ciphertext);
1046 }
1047 
CheckTripleDesTestVector(KeyPurpose purpose,BlockMode block_mode,PaddingMode padding_mode,const string & key,const string & iv,const string & input,const string & expected_output)1048 void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
1049                                                    PaddingMode padding_mode, const string& key,
1050                                                    const string& iv, const string& input,
1051                                                    const string& expected_output) {
1052     auto authset = AuthorizationSetBuilder()
1053                            .TripleDesEncryptionKey(key.size() * 7)
1054                            .BlockMode(block_mode)
1055                            .Authorization(TAG_NO_AUTH_REQUIRED)
1056                            .Padding(padding_mode);
1057     if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
1058     ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
1059     ASSERT_GT(key_blob_.size(), 0U);
1060 
1061     auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
1062     if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
1063     AuthorizationSet output_params;
1064     string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
1065     EXPECT_EQ(expected_output, output);
1066 }
1067 
VerifyMessage(const vector<uint8_t> & key_blob,const string & message,const string & signature,const AuthorizationSet & params)1068 void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
1069                                         const string& signature, const AuthorizationSet& params) {
1070     SCOPED_TRACE("VerifyMessage");
1071     AuthorizationSet begin_out_params;
1072     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
1073 
1074     string output;
1075     EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
1076     EXPECT_TRUE(output.empty());
1077     op_ = {};
1078 }
1079 
VerifyMessage(const string & message,const string & signature,const AuthorizationSet & params)1080 void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
1081                                         const AuthorizationSet& params) {
1082     SCOPED_TRACE("VerifyMessage");
1083     VerifyMessage(key_blob_, message, signature, params);
1084 }
1085 
LocalVerifyMessage(const string & message,const string & signature,const AuthorizationSet & params)1086 void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
1087                                              const AuthorizationSet& params) {
1088     SCOPED_TRACE("LocalVerifyMessage");
1089 
1090     ASSERT_GT(cert_chain_.size(), 0);
1091     LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
1092 }
1093 
LocalVerifyMessage(const vector<uint8_t> & der_cert,const string & message,const string & signature,const AuthorizationSet & params)1094 void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
1095                                              const string& signature,
1096                                              const AuthorizationSet& params) {
1097     // Retrieve the public key from the leaf certificate.
1098     X509_Ptr key_cert(parse_cert_blob(der_cert));
1099     ASSERT_TRUE(key_cert.get());
1100     EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
1101     ASSERT_TRUE(pub_key.get());
1102 
1103     Digest digest = params.GetTagValue(TAG_DIGEST).value();
1104     PaddingMode padding = PaddingMode::NONE;
1105     auto tag = params.GetTagValue(TAG_PADDING);
1106     if (tag.has_value()) {
1107         padding = tag.value();
1108     }
1109 
1110     if (digest == Digest::NONE) {
1111         switch (EVP_PKEY_id(pub_key.get())) {
1112             case EVP_PKEY_ED25519: {
1113                 ASSERT_EQ(64, signature.size());
1114                 uint8_t pub_keydata[32];
1115                 size_t pub_len = sizeof(pub_keydata);
1116                 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
1117                 ASSERT_EQ(sizeof(pub_keydata), pub_len);
1118                 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
1119                                             message.size(),
1120                                             reinterpret_cast<const uint8_t*>(signature.data()),
1121                                             pub_keydata));
1122                 break;
1123             }
1124 
1125             case EVP_PKEY_EC: {
1126                 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
1127                 size_t data_size = std::min(data.size(), message.size());
1128                 memcpy(data.data(), message.data(), data_size);
1129                 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
1130                 ASSERT_TRUE(ecdsa.get());
1131                 ASSERT_EQ(1,
1132                           ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
1133                                        reinterpret_cast<const uint8_t*>(signature.data()),
1134                                        signature.size(), ecdsa.get()));
1135                 break;
1136             }
1137             case EVP_PKEY_RSA: {
1138                 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
1139                 size_t data_size = std::min(data.size(), message.size());
1140                 memcpy(data.data(), message.data(), data_size);
1141 
1142                 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1143                 ASSERT_TRUE(rsa.get());
1144 
1145                 size_t key_len = RSA_size(rsa.get());
1146                 int openssl_padding = RSA_NO_PADDING;
1147                 switch (padding) {
1148                     case PaddingMode::NONE:
1149                         ASSERT_LE(data_size, key_len);
1150                         ASSERT_EQ(key_len, signature.size());
1151                         openssl_padding = RSA_NO_PADDING;
1152                         break;
1153                     case PaddingMode::RSA_PKCS1_1_5_SIGN:
1154                         ASSERT_LE(data_size + kPkcs1UndigestedSignaturePaddingOverhead, key_len);
1155                         openssl_padding = RSA_PKCS1_PADDING;
1156                         break;
1157                     default:
1158                         ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1159                 }
1160 
1161                 vector<uint8_t> decrypted_data(key_len);
1162                 int bytes_decrypted = RSA_public_decrypt(
1163                         signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1164                         decrypted_data.data(), rsa.get(), openssl_padding);
1165                 ASSERT_GE(bytes_decrypted, 0);
1166 
1167                 const uint8_t* compare_pos = decrypted_data.data();
1168                 size_t bytes_to_compare = bytes_decrypted;
1169                 uint8_t zero_check_result = 0;
1170                 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1171                     // If the data is short, for "unpadded" signing we zero-pad to the left.  So
1172                     // during verification we should have zeros on the left of the decrypted data.
1173                     // Do a constant-time check.
1174                     const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1175                     while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1176                     ASSERT_EQ(0, zero_check_result);
1177                     bytes_to_compare = data_size;
1178                 }
1179                 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1180                 break;
1181             }
1182             default:
1183                 ADD_FAILURE() << "Unknown public key type";
1184         }
1185     } else {
1186         EVP_MD_CTX digest_ctx;
1187         EVP_MD_CTX_init(&digest_ctx);
1188         EVP_PKEY_CTX* pkey_ctx;
1189         const EVP_MD* md = openssl_digest(digest);
1190         ASSERT_NE(md, nullptr);
1191         ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1192 
1193         if (padding == PaddingMode::RSA_PSS) {
1194             EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1195             EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
1196             EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
1197         }
1198 
1199         ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1200                                             reinterpret_cast<const uint8_t*>(message.data()),
1201                                             message.size()));
1202         ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1203                                            reinterpret_cast<const uint8_t*>(signature.data()),
1204                                            signature.size()));
1205         EVP_MD_CTX_cleanup(&digest_ctx);
1206     }
1207 }
1208 
LocalRsaEncryptMessage(const string & message,const AuthorizationSet & params)1209 string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1210                                                    const AuthorizationSet& params) {
1211     SCOPED_TRACE("LocalRsaEncryptMessage");
1212 
1213     // Retrieve the public key from the leaf certificate.
1214     if (cert_chain_.empty()) {
1215         ADD_FAILURE() << "No public key available";
1216         return "Failure";
1217     }
1218     X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1219     if (key_cert.get() == nullptr) {
1220         ADD_FAILURE() << "Failed to parse cert";
1221         return "Failure";
1222     }
1223     EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
1224     if (pub_key.get() == nullptr) {
1225         ADD_FAILURE() << "Failed to retrieve public key";
1226         return "Failure";
1227     }
1228     RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1229     if (rsa.get() == nullptr) {
1230         ADD_FAILURE() << "Failed to retrieve RSA public key";
1231         return "Failure";
1232     }
1233 
1234     // Retrieve relevant tags.
1235     Digest digest = Digest::NONE;
1236     Digest mgf_digest = Digest::SHA1;
1237     PaddingMode padding = PaddingMode::NONE;
1238 
1239     auto digest_tag = params.GetTagValue(TAG_DIGEST);
1240     if (digest_tag.has_value()) digest = digest_tag.value();
1241     auto pad_tag = params.GetTagValue(TAG_PADDING);
1242     if (pad_tag.has_value()) padding = pad_tag.value();
1243     auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1244     if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1245 
1246     const EVP_MD* md = openssl_digest(digest);
1247     const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1248 
1249     // Set up encryption context.
1250     EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1251     if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1252         ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1253         return "Failure";
1254     }
1255 
1256     int rc = -1;
1257     switch (padding) {
1258         case PaddingMode::NONE:
1259             rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1260             break;
1261         case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1262             rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1263             break;
1264         case PaddingMode::RSA_OAEP:
1265             rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1266             break;
1267         default:
1268             break;
1269     }
1270     if (rc <= 0) {
1271         ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1272         return "Failure";
1273     }
1274     if (padding == PaddingMode::RSA_OAEP) {
1275         if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1276             ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1277             return "Failure";
1278         }
1279         if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1280             ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1281             return "Failure";
1282         }
1283     }
1284 
1285     // Determine output size.
1286     size_t outlen;
1287     if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1288                          reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1289         ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1290         return "Failure";
1291     }
1292 
1293     // Left-zero-pad the input if necessary.
1294     const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1295     size_t to_encrypt_len = message.size();
1296 
1297     std::unique_ptr<string> zero_padded_message;
1298     if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1299         zero_padded_message.reset(new string(outlen, '\0'));
1300         memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1301                message.size());
1302         to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1303         to_encrypt_len = outlen;
1304     }
1305 
1306     // Do the encryption.
1307     string output(outlen, '\0');
1308     if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1309                          to_encrypt_len) <= 0) {
1310         ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1311         return "Failure";
1312     }
1313     return output;
1314 }
1315 
EncryptMessage(const vector<uint8_t> & key_blob,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)1316 string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1317                                            const AuthorizationSet& in_params,
1318                                            AuthorizationSet* out_params) {
1319     SCOPED_TRACE("EncryptMessage");
1320     return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1321 }
1322 
EncryptMessage(const string & message,const AuthorizationSet & params,AuthorizationSet * out_params)1323 string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1324                                            AuthorizationSet* out_params) {
1325     SCOPED_TRACE("EncryptMessage");
1326     return EncryptMessage(key_blob_, message, params, out_params);
1327 }
1328 
EncryptMessage(const string & message,const AuthorizationSet & params)1329 string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1330     SCOPED_TRACE("EncryptMessage");
1331     AuthorizationSet out_params;
1332     string ciphertext = EncryptMessage(message, params, &out_params);
1333     EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1334     return ciphertext;
1335 }
1336 
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding)1337 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1338                                            PaddingMode padding) {
1339     SCOPED_TRACE("EncryptMessage");
1340     auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1341     AuthorizationSet out_params;
1342     string ciphertext = EncryptMessage(message, params, &out_params);
1343     EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1344     return ciphertext;
1345 }
1346 
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,vector<uint8_t> * iv_out)1347 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1348                                            PaddingMode padding, vector<uint8_t>* iv_out) {
1349     SCOPED_TRACE("EncryptMessage");
1350     auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1351     AuthorizationSet out_params;
1352     string ciphertext = EncryptMessage(message, params, &out_params);
1353     EXPECT_EQ(1U, out_params.size());
1354     auto ivVal = out_params.GetTagValue(TAG_NONCE);
1355     EXPECT_TRUE(ivVal);
1356     if (ivVal) *iv_out = *ivVal;
1357     return ciphertext;
1358 }
1359 
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,const vector<uint8_t> & iv_in)1360 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1361                                            PaddingMode padding, const vector<uint8_t>& iv_in) {
1362     SCOPED_TRACE("EncryptMessage");
1363     auto params = AuthorizationSetBuilder()
1364                           .BlockMode(block_mode)
1365                           .Padding(padding)
1366                           .Authorization(TAG_NONCE, iv_in);
1367     AuthorizationSet out_params;
1368     string ciphertext = EncryptMessage(message, params, &out_params);
1369     return ciphertext;
1370 }
1371 
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,uint8_t mac_length_bits,const vector<uint8_t> & iv_in)1372 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1373                                            PaddingMode padding, uint8_t mac_length_bits,
1374                                            const vector<uint8_t>& iv_in) {
1375     SCOPED_TRACE("EncryptMessage");
1376     auto params = AuthorizationSetBuilder()
1377                           .BlockMode(block_mode)
1378                           .Padding(padding)
1379                           .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1380                           .Authorization(TAG_NONCE, iv_in);
1381     AuthorizationSet out_params;
1382     string ciphertext = EncryptMessage(message, params, &out_params);
1383     return ciphertext;
1384 }
1385 
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,uint8_t mac_length_bits)1386 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1387                                            PaddingMode padding, uint8_t mac_length_bits) {
1388     SCOPED_TRACE("EncryptMessage");
1389     auto params = AuthorizationSetBuilder()
1390                           .BlockMode(block_mode)
1391                           .Padding(padding)
1392                           .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1393     AuthorizationSet out_params;
1394     string ciphertext = EncryptMessage(message, params, &out_params);
1395     return ciphertext;
1396 }
1397 
DecryptMessage(const vector<uint8_t> & key_blob,const string & ciphertext,const AuthorizationSet & params)1398 string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1399                                            const string& ciphertext,
1400                                            const AuthorizationSet& params) {
1401     SCOPED_TRACE("DecryptMessage");
1402     AuthorizationSet out_params;
1403     string plaintext =
1404             ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1405     EXPECT_TRUE(out_params.empty());
1406     return plaintext;
1407 }
1408 
DecryptMessage(const string & ciphertext,const AuthorizationSet & params)1409 string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1410                                            const AuthorizationSet& params) {
1411     SCOPED_TRACE("DecryptMessage");
1412     return DecryptMessage(key_blob_, ciphertext, params);
1413 }
1414 
DecryptMessage(const string & ciphertext,BlockMode block_mode,PaddingMode padding_mode,const vector<uint8_t> & iv)1415 string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1416                                            PaddingMode padding_mode, const vector<uint8_t>& iv) {
1417     SCOPED_TRACE("DecryptMessage");
1418     auto params = AuthorizationSetBuilder()
1419                           .BlockMode(block_mode)
1420                           .Padding(padding_mode)
1421                           .Authorization(TAG_NONCE, iv);
1422     return DecryptMessage(key_blob_, ciphertext, params);
1423 }
1424 
UpgradeKey(const vector<uint8_t> & key_blob)1425 std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1426         const vector<uint8_t>& key_blob) {
1427     std::pair<ErrorCode, vector<uint8_t>> retval;
1428     vector<uint8_t> outKeyBlob;
1429     Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1430     ErrorCode errorcode = GetReturnErrorCode(result);
1431     retval = std::tie(errorcode, outKeyBlob);
1432 
1433     return retval;
1434 }
1435 
IsRkpSupportRequired() const1436 bool KeyMintAidlTestBase::IsRkpSupportRequired() const {
1437     // This is technically not a match to the requirements for S chipsets,
1438     // however when S shipped there was a bug in the test that skipped the
1439     // tests if KeyMint 2 was not on the system. So we allowed many chipests
1440     // to ship without RKP support. In T we hardened the requirements around
1441     // support for RKP, so relax the test to match.
1442     return get_vsr_api_level() >= __ANDROID_API_T__;
1443 }
1444 
ValidKeySizes(Algorithm algorithm)1445 vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1446     switch (algorithm) {
1447         case Algorithm::RSA:
1448             switch (SecLevel()) {
1449                 case SecurityLevel::SOFTWARE:
1450                 case SecurityLevel::TRUSTED_ENVIRONMENT:
1451                     return {2048, 3072, 4096};
1452                 case SecurityLevel::STRONGBOX:
1453                     return {2048};
1454                 default:
1455                     ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1456                     break;
1457             }
1458             break;
1459         case Algorithm::EC:
1460             ADD_FAILURE() << "EC keys must be specified by curve not size";
1461             break;
1462         case Algorithm::AES:
1463             return {128, 256};
1464         case Algorithm::TRIPLE_DES:
1465             return {168};
1466         case Algorithm::HMAC: {
1467             vector<uint32_t> retval((512 - 64) / 8 + 1);
1468             uint32_t size = 64 - 8;
1469             std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1470             return retval;
1471         }
1472         default:
1473             ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1474             return {};
1475     }
1476     ADD_FAILURE() << "Should be impossible to get here";
1477     return {};
1478 }
1479 
InvalidKeySizes(Algorithm algorithm)1480 vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1481     if (SecLevel() == SecurityLevel::STRONGBOX) {
1482         switch (algorithm) {
1483             case Algorithm::RSA:
1484                 return {3072, 4096};
1485             case Algorithm::EC:
1486                 return {224, 384, 521};
1487             case Algorithm::AES:
1488                 return {192};
1489             case Algorithm::TRIPLE_DES:
1490                 return {56};
1491             default:
1492                 return {};
1493         }
1494     } else {
1495         switch (algorithm) {
1496             case Algorithm::AES:
1497                 return {64, 96, 131, 512};
1498             case Algorithm::TRIPLE_DES:
1499                 return {56};
1500             default:
1501                 return {};
1502         }
1503     }
1504     return {};
1505 }
1506 
ValidBlockModes(Algorithm algorithm)1507 vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1508     switch (algorithm) {
1509         case Algorithm::AES:
1510             return {
1511                     BlockMode::CBC,
1512                     BlockMode::CTR,
1513                     BlockMode::ECB,
1514                     BlockMode::GCM,
1515             };
1516         case Algorithm::TRIPLE_DES:
1517             return {
1518                     BlockMode::CBC,
1519                     BlockMode::ECB,
1520             };
1521         default:
1522             return {};
1523     }
1524 }
1525 
ValidPaddingModes(Algorithm algorithm,BlockMode blockMode)1526 vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1527                                                            BlockMode blockMode) {
1528     switch (algorithm) {
1529         case Algorithm::AES:
1530             switch (blockMode) {
1531                 case BlockMode::CBC:
1532                 case BlockMode::ECB:
1533                     return {PaddingMode::NONE, PaddingMode::PKCS7};
1534                 case BlockMode::CTR:
1535                 case BlockMode::GCM:
1536                     return {PaddingMode::NONE};
1537                 default:
1538                     return {};
1539             };
1540         case Algorithm::TRIPLE_DES:
1541             switch (blockMode) {
1542                 case BlockMode::CBC:
1543                 case BlockMode::ECB:
1544                     return {PaddingMode::NONE, PaddingMode::PKCS7};
1545                 default:
1546                     return {};
1547             };
1548         default:
1549             return {};
1550     }
1551 }
1552 
InvalidPaddingModes(Algorithm algorithm,BlockMode blockMode)1553 vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1554                                                              BlockMode blockMode) {
1555     switch (algorithm) {
1556         case Algorithm::AES:
1557             switch (blockMode) {
1558                 case BlockMode::CTR:
1559                 case BlockMode::GCM:
1560                     return {PaddingMode::PKCS7};
1561                 default:
1562                     return {};
1563             };
1564         default:
1565             return {};
1566     }
1567 }
1568 
ValidCurves()1569 vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1570     if (securityLevel_ == SecurityLevel::STRONGBOX) {
1571         return {EcCurve::P_256};
1572     } else if (Curve25519Supported()) {
1573         return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1574                 EcCurve::CURVE_25519};
1575     } else {
1576         return {
1577                 EcCurve::P_224,
1578                 EcCurve::P_256,
1579                 EcCurve::P_384,
1580                 EcCurve::P_521,
1581         };
1582     }
1583 }
1584 
InvalidCurves()1585 vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
1586     if (SecLevel() == SecurityLevel::STRONGBOX) {
1587         // Curve 25519 is not supported, either because:
1588         // - KeyMint v1: it's an unknown enum value
1589         // - KeyMint v2+: it's not supported by StrongBox.
1590         return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
1591     } else {
1592         if (Curve25519Supported()) {
1593             return {};
1594         } else {
1595             return {EcCurve::CURVE_25519};
1596         }
1597     }
1598 }
1599 
ValidExponents()1600 vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1601     if (SecLevel() == SecurityLevel::STRONGBOX) {
1602         return {65537};
1603     } else {
1604         return {3, 65537};
1605     }
1606 }
1607 
ValidDigests(bool withNone,bool withMD5)1608 vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1609     switch (SecLevel()) {
1610         case SecurityLevel::SOFTWARE:
1611         case SecurityLevel::TRUSTED_ENVIRONMENT:
1612             if (withNone) {
1613                 if (withMD5)
1614                     return {Digest::NONE,      Digest::MD5,       Digest::SHA1,
1615                             Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1616                             Digest::SHA_2_512};
1617                 else
1618                     return {Digest::NONE,      Digest::SHA1,      Digest::SHA_2_224,
1619                             Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1620             } else {
1621                 if (withMD5)
1622                     return {Digest::MD5,       Digest::SHA1,      Digest::SHA_2_224,
1623                             Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1624                 else
1625                     return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1626                             Digest::SHA_2_512};
1627             }
1628             break;
1629         case SecurityLevel::STRONGBOX:
1630             if (withNone)
1631                 return {Digest::NONE, Digest::SHA_2_256};
1632             else
1633                 return {Digest::SHA_2_256};
1634             break;
1635         default:
1636             ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1637             break;
1638     }
1639     ADD_FAILURE() << "Should be impossible to get here";
1640     return {};
1641 }
1642 
1643 static const vector<KeyParameter> kEmptyAuthList{};
1644 
SecLevelAuthorizations(const vector<KeyCharacteristics> & key_characteristics)1645 const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1646         const vector<KeyCharacteristics>& key_characteristics) {
1647     auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1648                               [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1649     return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1650 }
1651 
SecLevelAuthorizations(const vector<KeyCharacteristics> & key_characteristics,SecurityLevel securityLevel)1652 const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1653         const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1654     auto found = std::find_if(
1655             key_characteristics.begin(), key_characteristics.end(),
1656             [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
1657     return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1658 }
1659 
UseAesKey(const vector<uint8_t> & aesKeyBlob)1660 ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
1661     auto [result, ciphertext] = ProcessMessage(
1662             aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1663             AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1664     return result;
1665 }
1666 
UseHmacKey(const vector<uint8_t> & hmacKeyBlob)1667 ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
1668     auto [result, mac] = ProcessMessage(
1669             hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1670             AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1671     return result;
1672 }
1673 
UseRsaKey(const vector<uint8_t> & rsaKeyBlob)1674 ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1675     std::string message(2048 / 8, 'a');
1676     auto [result, signature] = ProcessMessage(
1677             rsaKeyBlob, KeyPurpose::SIGN, message,
1678             AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1679     return result;
1680 }
1681 
UseEcdsaKey(const vector<uint8_t> & ecdsaKeyBlob)1682 ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
1683     auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1684                                               AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1685     return result;
1686 }
1687 
GenerateAttestKey(const AuthorizationSet & key_desc,const optional<AttestationKey> & attest_key,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics,vector<Certificate> * cert_chain)1688 ErrorCode KeyMintAidlTestBase::GenerateAttestKey(const AuthorizationSet& key_desc,
1689                                                  const optional<AttestationKey>& attest_key,
1690                                                  vector<uint8_t>* key_blob,
1691                                                  vector<KeyCharacteristics>* key_characteristics,
1692                                                  vector<Certificate>* cert_chain) {
1693     // The original specification for KeyMint v1 required ATTEST_KEY not be combined
1694     // with any other key purpose, but the original VTS tests incorrectly did exactly that.
1695     // This means that a device that launched prior to Android T (API level 33) may
1696     // accept or even require KeyPurpose::SIGN too.
1697     if (get_vsr_api_level() < __ANDROID_API_T__) {
1698         AuthorizationSet key_desc_plus_sign = key_desc;
1699         key_desc_plus_sign.push_back(TAG_PURPOSE, KeyPurpose::SIGN);
1700 
1701         auto result = GenerateKey(key_desc_plus_sign, attest_key, key_blob, key_characteristics,
1702                                   cert_chain);
1703         if (result == ErrorCode::OK) {
1704             return result;
1705         }
1706         // If the key generation failed, it may be because the device is (correctly)
1707         // rejecting the combination of ATTEST_KEY+SIGN.  Fall through to try again with
1708         // just ATTEST_KEY.
1709     }
1710     return GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
1711 }
1712 
1713 // Check if ATTEST_KEY feature is disabled
is_attest_key_feature_disabled(void) const1714 bool KeyMintAidlTestBase::is_attest_key_feature_disabled(void) const {
1715     if (!check_feature(FEATURE_KEYSTORE_APP_ATTEST_KEY)) {
1716         GTEST_LOG_(INFO) << "Feature " + FEATURE_KEYSTORE_APP_ATTEST_KEY + " is disabled";
1717         return true;
1718     }
1719 
1720     return false;
1721 }
1722 
1723 // Check if StrongBox KeyStore is enabled
is_strongbox_enabled(void) const1724 bool KeyMintAidlTestBase::is_strongbox_enabled(void) const {
1725     if (check_feature(FEATURE_STRONGBOX_KEYSTORE)) {
1726         GTEST_LOG_(INFO) << "Feature " + FEATURE_STRONGBOX_KEYSTORE + " is enabled";
1727         return true;
1728     }
1729 
1730     return false;
1731 }
1732 
1733 // Check if chipset has received a waiver allowing it to be launched with Android S or T with
1734 // Keymaster 4.0 in StrongBox.
is_chipset_allowed_km4_strongbox(void) const1735 bool KeyMintAidlTestBase::is_chipset_allowed_km4_strongbox(void) const {
1736     std::array<char, PROPERTY_VALUE_MAX> buffer;
1737 
1738     const int32_t first_api_level = property_get_int32("ro.board.first_api_level", 0);
1739     if (first_api_level <= 0 || first_api_level > __ANDROID_API_T__) return false;
1740 
1741     auto res = property_get("ro.vendor.qti.soc_model", buffer.data(), nullptr);
1742     if (res <= 0) return false;
1743 
1744     const string allowed_soc_models[] = {"SM8450", "SM8475", "SM8550", "SXR2230P",
1745                                          "SM4450", "SM7450", "SM6450"};
1746 
1747     for (const string model : allowed_soc_models) {
1748         if (model.compare(buffer.data()) == 0) {
1749             GTEST_LOG_(INFO) << "QTI SOC Model " + model + " is allowed SB KM 4.0";
1750             return true;
1751         }
1752     }
1753 
1754     return false;
1755 }
1756 
1757 // Indicate whether a test that involves use of the ATTEST_KEY feature should be
1758 // skipped.
1759 //
1760 // In general, every KeyMint implementation should support ATTEST_KEY;
1761 // however, there is a waiver for some specific devices that ship with a
1762 // combination of Keymaster/StrongBox and KeyMint/TEE.  On these devices, the
1763 // ATTEST_KEY feature is disabled in the KeyMint/TEE implementation so that
1764 // the device has consistent ATTEST_KEY behavior (ie. UNIMPLEMENTED) across both
1765 // HAL implementations.
1766 //
1767 // This means that a test involving ATTEST_KEY test should be skipped if all of
1768 // the following conditions hold:
1769 // 1. The device is running one of the chipsets that have received a waiver
1770 //     allowing it to be launched with Android S or T with Keymaster 4.0
1771 //     in StrongBox
1772 // 2. The device has a STRONGBOX implementation present.
1773 // 3. ATTEST_KEY feature is advertised as disabled.
1774 //
1775 // Note that in this scenario, ATTEST_KEY tests should be skipped for both
1776 // the StrongBox implementation (which is Keymaster, therefore not tested here)
1777 // and for the TEE implementation (which is adjusted to return UNIMPLEMENTED
1778 // specifically for this waiver).
shouldSkipAttestKeyTest(void) const1779 bool KeyMintAidlTestBase::shouldSkipAttestKeyTest(void) const {
1780     // Check the chipset first as that doesn't require a round-trip to Package Manager.
1781     return (is_chipset_allowed_km4_strongbox() && is_strongbox_enabled() &&
1782             is_attest_key_feature_disabled());
1783 }
1784 
verify_serial(X509 * cert,const uint64_t expected_serial)1785 void verify_serial(X509* cert, const uint64_t expected_serial) {
1786     BIGNUM_Ptr ser(BN_new());
1787     EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1788 
1789     uint64_t serial;
1790     EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1791     EXPECT_EQ(serial, expected_serial);
1792 }
1793 
1794 // Please set self_signed to true for fake certificates or self signed
1795 // certificates
verify_subject(const X509 * cert,const string & subject,bool self_signed)1796 void verify_subject(const X509* cert,       //
1797                     const string& subject,  //
1798                     bool self_signed) {
1799     char* cert_issuer =  //
1800             X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1801 
1802     char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1803 
1804     string expected_subject("/CN=");
1805     if (subject.empty()) {
1806         expected_subject.append("Android Keystore Key");
1807     } else {
1808         expected_subject.append(subject);
1809     }
1810 
1811     EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1812 
1813     if (self_signed) {
1814         EXPECT_STREQ(cert_issuer, cert_subj)
1815                 << "Cert issuer and subject mismatch for self signed certificate.";
1816     }
1817 
1818     OPENSSL_free(cert_subj);
1819     OPENSSL_free(cert_issuer);
1820 }
1821 
get_vsr_api_level()1822 int get_vsr_api_level() {
1823     int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1824     if (vendor_api_level != -1) {
1825         return vendor_api_level;
1826     }
1827 
1828     // Android S and older devices do not define ro.vendor.api_level
1829     vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1830     if (vendor_api_level == -1) {
1831         vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
1832     }
1833 
1834     int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1835     if (product_api_level == -1) {
1836         product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1837         EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
1838     }
1839 
1840     // VSR API level is the minimum of vendor_api_level and product_api_level.
1841     if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1842         return product_api_level;
1843     }
1844     return vendor_api_level;
1845 }
1846 
is_gsi_image()1847 bool is_gsi_image() {
1848     std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1849     return ifs.good();
1850 }
1851 
build_serial_blob(const uint64_t serial_int)1852 vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1853     BIGNUM_Ptr serial(BN_new());
1854     EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1855 
1856     int len = BN_num_bytes(serial.get());
1857     vector<uint8_t> serial_blob(len);
1858     if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1859         return {};
1860     }
1861 
1862     if (serial_blob.empty() || serial_blob[0] & 0x80) {
1863         // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1864         // Top bit being set indicates a negative number in two's complement, but our input
1865         // was positive.
1866         // In either case, prepend a zero byte.
1867         serial_blob.insert(serial_blob.begin(), 0x00);
1868     }
1869 
1870     return serial_blob;
1871 }
1872 
verify_subject_and_serial(const Certificate & certificate,const uint64_t expected_serial,const string & subject,bool self_signed)1873 void verify_subject_and_serial(const Certificate& certificate,  //
1874                                const uint64_t expected_serial,  //
1875                                const string& subject, bool self_signed) {
1876     X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1877     ASSERT_TRUE(!!cert.get());
1878 
1879     verify_serial(cert.get(), expected_serial);
1880     verify_subject(cert.get(), subject, self_signed);
1881 }
1882 
verify_root_of_trust(const vector<uint8_t> & verified_boot_key,bool device_locked,VerifiedBoot verified_boot_state,const vector<uint8_t> & verified_boot_hash)1883 void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1884                           VerifiedBoot verified_boot_state,
1885                           const vector<uint8_t>& verified_boot_hash) {
1886     char property_value[PROPERTY_VALUE_MAX] = {};
1887 
1888     if (avb_verification_enabled()) {
1889         EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1890         string prop_string(property_value);
1891         EXPECT_EQ(prop_string.size(), 64);
1892         EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1893 
1894         EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1895         if (!strcmp(property_value, "unlocked")) {
1896             EXPECT_FALSE(device_locked);
1897         } else {
1898             EXPECT_TRUE(device_locked);
1899         }
1900 
1901         // Check that the device is locked if not debuggable, e.g., user build
1902         // images in CTS. For VTS, debuggable images are used to allow adb root
1903         // and the device is unlocked.
1904         if (!property_get_bool("ro.debuggable", false)) {
1905             EXPECT_TRUE(device_locked);
1906         } else {
1907             EXPECT_FALSE(device_locked);
1908         }
1909     }
1910 
1911     if (get_vsr_api_level() > __ANDROID_API_V__) {
1912         // The Verified Boot key field should be exactly 32 bytes since it
1913         // contains the SHA-256 hash of the key on locked devices or 32 bytes
1914         // of zeroes on unlocked devices. This wasn't checked for earlier
1915         // versions of the KeyMint HAL, so only only be strict for VSR-16+.
1916         EXPECT_EQ(verified_boot_key.size(), 32);
1917     } else if (get_vsr_api_level() == __ANDROID_API_V__) {
1918         // The Verified Boot key field should be:
1919         //   - Exactly 32 bytes on locked devices since it should contain
1920         //     the SHA-256 hash of the key, or
1921         //   - Up to 32 bytes of zeroes on unlocked devices (behaviour on
1922         //     unlocked devices isn't specified in the HAL interface
1923         //     specification).
1924         // Thus, we can't check for strict equality in case unlocked devices
1925         // report values with less than 32 bytes. This wasn't checked for
1926         // earlier versions of the KeyMint HAL, so only check on VSR-15.
1927         EXPECT_LE(verified_boot_key.size(), 32);
1928     }
1929 
1930     // Verified Boot key should be all zeroes if the boot state is "orange".
1931     std::string empty_boot_key(32, '\0');
1932     std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1933                                       verified_boot_key.size());
1934     EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1935     if (!strcmp(property_value, "green")) {
1936         EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1937         EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1938                             verified_boot_key.size()));
1939     } else if (!strcmp(property_value, "yellow")) {
1940         EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1941         EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1942                             verified_boot_key.size()));
1943     } else if (!strcmp(property_value, "orange")) {
1944         EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1945         EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1946                             verified_boot_key.size()));
1947     } else if (!strcmp(property_value, "red")) {
1948         EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1949     } else {
1950         EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1951         EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1952                             verified_boot_key.size()));
1953     }
1954 }
1955 
verify_attestation_record(int32_t aidl_version,const string & challenge,const string & app_id,AuthorizationSet expected_sw_enforced,AuthorizationSet expected_hw_enforced,SecurityLevel security_level,const vector<uint8_t> & attestation_cert,vector<uint8_t> * unique_id)1956 bool verify_attestation_record(int32_t aidl_version,                   //
1957                                const string& challenge,                //
1958                                const string& app_id,                   //
1959                                AuthorizationSet expected_sw_enforced,  //
1960                                AuthorizationSet expected_hw_enforced,  //
1961                                SecurityLevel security_level,
1962                                const vector<uint8_t>& attestation_cert,
1963                                vector<uint8_t>* unique_id) {
1964     X509_Ptr cert(parse_cert_blob(attestation_cert));
1965     EXPECT_TRUE(!!cert.get());
1966     if (!cert.get()) return false;
1967 
1968     // Make sure CRL Distribution Points extension is not present in a certificate
1969     // containing attestation record.
1970     check_crl_distribution_points_extension_not_present(cert.get());
1971 
1972     ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1973     EXPECT_TRUE(!!attest_rec);
1974     if (!attest_rec) return false;
1975 
1976     AuthorizationSet att_sw_enforced;
1977     AuthorizationSet att_hw_enforced;
1978     uint32_t att_attestation_version;
1979     uint32_t att_keymint_version;
1980     SecurityLevel att_attestation_security_level;
1981     SecurityLevel att_keymint_security_level;
1982     vector<uint8_t> att_challenge;
1983     vector<uint8_t> att_unique_id;
1984     vector<uint8_t> att_app_id;
1985 
1986     auto error = parse_attestation_record(attest_rec->data,                 //
1987                                           attest_rec->length,               //
1988                                           &att_attestation_version,         //
1989                                           &att_attestation_security_level,  //
1990                                           &att_keymint_version,             //
1991                                           &att_keymint_security_level,      //
1992                                           &att_challenge,                   //
1993                                           &att_sw_enforced,                 //
1994                                           &att_hw_enforced,                 //
1995                                           &att_unique_id);
1996     EXPECT_EQ(ErrorCode::OK, error);
1997     if (error != ErrorCode::OK) return false;
1998 
1999     check_attestation_version(att_attestation_version, aidl_version);
2000     vector<uint8_t> appId(app_id.begin(), app_id.end());
2001 
2002     // check challenge and app id only if we expects a non-fake certificate
2003     if (challenge.length() > 0) {
2004         EXPECT_EQ(challenge.length(), att_challenge.size());
2005         EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
2006 
2007         expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
2008     }
2009 
2010     check_attestation_version(att_keymint_version, aidl_version);
2011     EXPECT_EQ(security_level, att_keymint_security_level);
2012     EXPECT_EQ(security_level, att_attestation_security_level);
2013 
2014     for (int i = 0; i < att_hw_enforced.size(); i++) {
2015         if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
2016             att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
2017             std::string date =
2018                     std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
2019 
2020             // strptime seems to require delimiters, but the tag value will
2021             // be YYYYMMDD
2022             if (date.size() != 8) {
2023                 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
2024                               << " with invalid format (not YYYYMMDD): " << date;
2025                 return false;
2026             }
2027             date.insert(6, "-");
2028             date.insert(4, "-");
2029             struct tm time;
2030             strptime(date.c_str(), "%Y-%m-%d", &time);
2031 
2032             // Day of the month (0-31)
2033             EXPECT_GE(time.tm_mday, 0);
2034             EXPECT_LT(time.tm_mday, 32);
2035             // Months since Jan (0-11)
2036             EXPECT_GE(time.tm_mon, 0);
2037             EXPECT_LT(time.tm_mon, 12);
2038             // Years since 1900
2039             EXPECT_GT(time.tm_year, 110);
2040             EXPECT_LT(time.tm_year, 200);
2041         }
2042     }
2043 
2044     // Check to make sure boolean values are properly encoded. Presence of a boolean tag
2045     // indicates true. A provided boolean tag that can be pulled back out of the certificate
2046     // indicates correct encoding. No need to check if it's in both lists, since the
2047     // AuthorizationSet compare below will handle mismatches of tags.
2048     if (security_level == SecurityLevel::SOFTWARE) {
2049         EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
2050     } else {
2051         EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
2052     }
2053 
2054     if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
2055         // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
2056         EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
2057                     att_hw_enforced.Contains(TAG_KEY_SIZE));
2058     }
2059 
2060     // Test root of trust elements
2061     vector<uint8_t> verified_boot_key;
2062     VerifiedBoot verified_boot_state;
2063     bool device_locked;
2064     vector<uint8_t> verified_boot_hash;
2065     error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
2066                                 &verified_boot_state, &device_locked, &verified_boot_hash);
2067     EXPECT_EQ(ErrorCode::OK, error);
2068     verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
2069 
2070     att_sw_enforced.Sort();
2071     expected_sw_enforced.Sort();
2072     EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
2073 
2074     att_hw_enforced.Sort();
2075     expected_hw_enforced.Sort();
2076     EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
2077 
2078     if (unique_id != nullptr) {
2079         *unique_id = att_unique_id;
2080     }
2081 
2082     return true;
2083 }
2084 
bin2hex(const vector<uint8_t> & data)2085 string bin2hex(const vector<uint8_t>& data) {
2086     string retval;
2087     retval.reserve(data.size() * 2 + 1);
2088     for (uint8_t byte : data) {
2089         retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
2090         retval.push_back(nibble2hex[0x0F & byte]);
2091     }
2092     return retval;
2093 }
2094 
HwEnforcedAuthorizations(const vector<KeyCharacteristics> & key_characteristics)2095 AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
2096     AuthorizationSet authList;
2097     for (auto& entry : key_characteristics) {
2098         if (entry.securityLevel == SecurityLevel::STRONGBOX ||
2099             entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
2100             authList.push_back(AuthorizationSet(entry.authorizations));
2101         }
2102     }
2103     return authList;
2104 }
2105 
SwEnforcedAuthorizations(const vector<KeyCharacteristics> & key_characteristics)2106 AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
2107     AuthorizationSet authList;
2108     for (auto& entry : key_characteristics) {
2109         if (entry.securityLevel == SecurityLevel::SOFTWARE ||
2110             entry.securityLevel == SecurityLevel::KEYSTORE) {
2111             authList.push_back(AuthorizationSet(entry.authorizations));
2112         }
2113     }
2114     return authList;
2115 }
2116 
ChainSignaturesAreValid(const vector<Certificate> & chain,bool strict_issuer_check)2117 AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
2118                                         bool strict_issuer_check) {
2119     std::stringstream cert_data;
2120 
2121     for (size_t i = 0; i < chain.size(); ++i) {
2122         cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
2123 
2124         X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
2125         X509_Ptr signing_cert;
2126         if (i < chain.size() - 1) {
2127             signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
2128         } else {
2129             signing_cert = parse_cert_blob(chain[i].encodedCertificate);
2130         }
2131         if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
2132 
2133         EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
2134         if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
2135 
2136         if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
2137             return AssertionFailure()
2138                    << "Verification of certificate " << i << " failed "
2139                    << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
2140                    << cert_data.str();
2141         }
2142 
2143         string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
2144         string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
2145         if (cert_issuer != signer_subj && strict_issuer_check) {
2146             return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
2147                                       << " Signer subject is " << signer_subj
2148                                       << " Issuer subject is " << cert_issuer << endl
2149                                       << cert_data.str();
2150         }
2151     }
2152 
2153     if (KeyMintAidlTestBase::dump_Attestations) std::cout << "cert chain:\n" << cert_data.str();
2154     return AssertionSuccess();
2155 }
2156 
GetReturnErrorCode(const Status & result)2157 ErrorCode GetReturnErrorCode(const Status& result) {
2158     if (result.isOk()) return ErrorCode::OK;
2159 
2160     if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
2161         return static_cast<ErrorCode>(result.getServiceSpecificError());
2162     }
2163 
2164     return ErrorCode::UNKNOWN_ERROR;
2165 }
2166 
parse_cert_blob(const vector<uint8_t> & blob)2167 X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
2168     const uint8_t* p = blob.data();
2169     return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
2170 }
2171 
2172 // Extract attestation record from cert. Returned object is still part of cert; don't free it
2173 // separately.
get_attestation_record(X509 * certificate)2174 ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
2175     ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
2176     EXPECT_TRUE(!!oid.get());
2177     if (!oid.get()) return nullptr;
2178 
2179     int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
2180     EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
2181     if (location == -1) return nullptr;
2182 
2183     X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
2184     EXPECT_TRUE(!!attest_rec_ext)
2185             << "Found attestation extension but couldn't retrieve it?  Probably a BoringSSL bug.";
2186     if (!attest_rec_ext) return nullptr;
2187 
2188     ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
2189     EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
2190     return attest_rec;
2191 }
2192 
make_name_from_str(const string & name)2193 vector<uint8_t> make_name_from_str(const string& name) {
2194     X509_NAME_Ptr x509_name(X509_NAME_new());
2195     EXPECT_TRUE(x509_name.get() != nullptr);
2196     if (!x509_name) return {};
2197 
2198     EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(),  //
2199                                             "CN",             //
2200                                             MBSTRING_ASC,
2201                                             reinterpret_cast<const uint8_t*>(name.c_str()),
2202                                             -1,  // len
2203                                             -1,  // loc
2204                                             0 /* set */));
2205 
2206     int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
2207     EXPECT_GT(len, 0);
2208 
2209     vector<uint8_t> retval(len);
2210     uint8_t* p = retval.data();
2211     i2d_X509_NAME(x509_name.get(), &p);
2212 
2213     return retval;
2214 }
2215 
assert_mgf_digests_present_or_not_in_key_characteristics(std::vector<android::hardware::security::keymint::Digest> & expected_mgf_digests,bool is_mgf_digest_expected) const2216 void KeyMintAidlTestBase::assert_mgf_digests_present_or_not_in_key_characteristics(
2217         std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests,
2218         bool is_mgf_digest_expected) const {
2219     assert_mgf_digests_present_or_not_in_key_characteristics(
2220             key_characteristics_, expected_mgf_digests, is_mgf_digest_expected);
2221 }
2222 
assert_mgf_digests_present_or_not_in_key_characteristics(const vector<KeyCharacteristics> & key_characteristics,std::vector<android::hardware::security::keymint::Digest> & expected_mgf_digests,bool is_mgf_digest_expected) const2223 void KeyMintAidlTestBase::assert_mgf_digests_present_or_not_in_key_characteristics(
2224         const vector<KeyCharacteristics>& key_characteristics,
2225         std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests,
2226         bool is_mgf_digest_expected) const {
2227     // There was no test to assert that MGF1 digest was present in generated/imported key
2228     // characteristics before Keymint V3, so there are some Keymint implementations where
2229     // asserting for MGF1 digest fails(b/297306437), hence skipping for Keymint < 3.
2230     if (AidlVersion() < 3) {
2231         return;
2232     }
2233     AuthorizationSet auths;
2234     for (auto& entry : key_characteristics) {
2235         auths.push_back(AuthorizationSet(entry.authorizations));
2236     }
2237     for (auto digest : expected_mgf_digests) {
2238         if (is_mgf_digest_expected) {
2239             ASSERT_TRUE(auths.Contains(TAG_RSA_OAEP_MGF_DIGEST, digest));
2240         } else {
2241             ASSERT_FALSE(auths.Contains(TAG_RSA_OAEP_MGF_DIGEST, digest));
2242         }
2243     }
2244 }
2245 
2246 namespace {
2247 
validateP256Point(const std::vector<uint8_t> & x_buffer,const std::vector<uint8_t> & y_buffer)2248 std::optional<std::string> validateP256Point(const std::vector<uint8_t>& x_buffer,
2249                                              const std::vector<uint8_t>& y_buffer) {
2250     auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2251     if (group.get() == nullptr) {
2252         return "Error creating EC group by curve name for prime256v1";
2253     }
2254 
2255     auto point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2256     BIGNUM_Ptr x(BN_bin2bn(x_buffer.data(), x_buffer.size(), nullptr));
2257     BIGNUM_Ptr y(BN_bin2bn(y_buffer.data(), y_buffer.size(), nullptr));
2258     if (!EC_POINT_set_affine_coordinates_GFp(group.get(), point.get(), x.get(), y.get(), nullptr)) {
2259         return "Failed to set affine coordinates.";
2260     }
2261     if (!EC_POINT_is_on_curve(group.get(), point.get(), nullptr)) {
2262         return "Point is not on curve.";
2263     }
2264     if (EC_POINT_is_at_infinity(group.get(), point.get())) {
2265         return "Point is at infinity.";
2266     }
2267     const auto* generator = EC_GROUP_get0_generator(group.get());
2268     if (!EC_POINT_cmp(group.get(), generator, point.get(), nullptr)) {
2269         return "Point is equal to generator.";
2270     }
2271 
2272     return std::nullopt;
2273 }
2274 
check_cose_key(const vector<uint8_t> & data,bool testMode)2275 void check_cose_key(const vector<uint8_t>& data, bool testMode) {
2276     auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
2277     ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2278 
2279     // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
2280     if (testMode) {
2281         EXPECT_THAT(
2282                 cppbor::prettyPrint(parsedPayload.get()),
2283                 MatchesRegex("\\{\n"
2284                              "  1 : 2,\n"   // kty: EC2
2285                              "  3 : -7,\n"  // alg: ES256
2286                              "  -1 : 1,\n"  // EC id: P256
2287                              // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
2288                              // sequence of 32 hexadecimal bytes, enclosed in braces and
2289                              // separated by commas. In this case, some Ed25519 public key.
2290                              "  -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n"  // pub_x: data
2291                              "  -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n"  // pub_y: data
2292                              "  -70000 : null,\n"                                  // test marker
2293                              "\\}"));
2294     } else {
2295         EXPECT_THAT(
2296                 cppbor::prettyPrint(parsedPayload.get()),
2297                 MatchesRegex("\\{\n"
2298                              "  1 : 2,\n"   // kty: EC2
2299                              "  3 : -7,\n"  // alg: ES256
2300                              "  -1 : 1,\n"  // EC id: P256
2301                              // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
2302                              // sequence of 32 hexadecimal bytes, enclosed in braces and
2303                              // separated by commas. In this case, some Ed25519 public key.
2304                              "  -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n"  // pub_x: data
2305                              "  -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n"  // pub_y: data
2306                              "\\}"));
2307     }
2308 
2309     ASSERT_TRUE(parsedPayload->asMap()) << "CBOR item was not a map";
2310 
2311     ASSERT_TRUE(parsedPayload->asMap()->get(CoseKey::Label::PUBKEY_X))
2312             << "CBOR map did not contain x coordinate of public key";
2313     ASSERT_TRUE(parsedPayload->asMap()->get(CoseKey::Label::PUBKEY_X)->asBstr())
2314             << "x coordinate of public key was not a bstr";
2315     const auto& x = parsedPayload->asMap()->get(CoseKey::Label::PUBKEY_X)->asBstr()->value();
2316 
2317     ASSERT_TRUE(parsedPayload->asMap()->get(CoseKey::Label::PUBKEY_Y))
2318             << "CBOR map did not contain y coordinate of public key";
2319     ASSERT_TRUE(parsedPayload->asMap()->get(CoseKey::Label::PUBKEY_Y)->asBstr())
2320             << "y coordinate of public key was not a bstr";
2321     const auto& y = parsedPayload->asMap()->get(CoseKey::Label::PUBKEY_Y)->asBstr()->value();
2322 
2323     auto errorMessage = validateP256Point(x, y);
2324     EXPECT_EQ(errorMessage, std::nullopt)
2325             << *errorMessage << " x: " << bin2hex(x) << " y: " << bin2hex(y);
2326 }
2327 
2328 }  // namespace
2329 
check_maced_pubkey(const MacedPublicKey & macedPubKey,bool testMode,vector<uint8_t> * payload_value)2330 void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
2331                         vector<uint8_t>* payload_value) {
2332     auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
2333     ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
2334 
2335     ASSERT_NE(coseMac0->asArray(), nullptr);
2336     ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
2337 
2338     auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
2339     ASSERT_NE(protParms, nullptr);
2340 
2341     // Header label:value of 'alg': HMAC-256
2342     ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n  1 : 5,\n}");
2343 
2344     auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
2345     ASSERT_NE(unprotParms, nullptr);
2346     ASSERT_EQ(unprotParms->size(), 0);
2347 
2348     // The payload is a bstr holding an encoded COSE_Key
2349     auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
2350     ASSERT_NE(payload, nullptr);
2351     check_cose_key(payload->value(), testMode);
2352 
2353     auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
2354     ASSERT_TRUE(coseMac0Tag);
2355     auto extractedTag = coseMac0Tag->value();
2356     EXPECT_EQ(extractedTag.size(), 32U);
2357 
2358     // Compare with tag generated with kTestMacKey.  Should only match in test mode
2359     auto macFunction = [](const cppcose::bytevec& input) {
2360         return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
2361     };
2362     auto testTag =
2363             cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
2364     ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
2365 
2366     if (testMode) {
2367         EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
2368     } else {
2369         EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
2370     }
2371     if (payload_value != nullptr) {
2372         *payload_value = payload->value();
2373     }
2374 }
2375 
p256_pub_key(const vector<uint8_t> & coseKeyData,EVP_PKEY_Ptr * signingKey)2376 void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2377     // Extract x and y affine coordinates from the encoded Cose_Key.
2378     auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2379     ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2380     auto coseKey = parsedPayload->asMap();
2381     const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2382     ASSERT_NE(xItem->asBstr(), nullptr);
2383     vector<uint8_t> x = xItem->asBstr()->value();
2384     const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2385     ASSERT_NE(yItem->asBstr(), nullptr);
2386     vector<uint8_t> y = yItem->asBstr()->value();
2387 
2388     // Concatenate: 0x04 (uncompressed form marker) | x | y
2389     vector<uint8_t> pubKeyData{0x04};
2390     pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2391     pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2392 
2393     EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2394     ASSERT_NE(ecKey, nullptr);
2395     EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2396     ASSERT_NE(group, nullptr);
2397     ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2398     EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2399     ASSERT_NE(point, nullptr);
2400     ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2401                                  nullptr),
2402               1);
2403     ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2404 
2405     EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2406     ASSERT_NE(pubKey, nullptr);
2407     EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2408     *signingKey = std::move(pubKey);
2409 }
2410 
2411 // Check the error code from an attempt to perform device ID attestation with an invalid value.
device_id_attestation_check_acceptable_error(Tag tag,const ErrorCode & result)2412 void device_id_attestation_check_acceptable_error(Tag tag, const ErrorCode& result) {
2413     if (result == ErrorCode::CANNOT_ATTEST_IDS) {
2414         // Standard/default error code for ID mismatch.
2415     } else if (result == ErrorCode::INVALID_TAG) {
2416         // Depending on the situation, other error codes may be acceptable.  First, allow older
2417         // implementations to use INVALID_TAG.
2418         ASSERT_FALSE(get_vsr_api_level() > __ANDROID_API_T__)
2419                 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2420                 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2421                 << "be used for a case where updateAad() is called after update(). As of "
2422                 << "VSR-14, this is now enforced as an error.";
2423     } else if (result == ErrorCode::ATTESTATION_IDS_NOT_PROVISIONED) {
2424         // If the device is not a phone, it will not have IMEI/MEID values available.  Allow
2425         // ATTESTATION_IDS_NOT_PROVISIONED in this case.
2426         ASSERT_TRUE((tag == TAG_ATTESTATION_ID_IMEI || tag == TAG_ATTESTATION_ID_MEID ||
2427                      tag == TAG_ATTESTATION_ID_SECOND_IMEI))
2428                 << "incorrect error code on attestation ID mismatch for " << tag;
2429     } else {
2430         ADD_FAILURE() << "Error code " << result
2431                       << " returned on attestation ID mismatch, should be CANNOT_ATTEST_IDS";
2432     }
2433 }
2434 
2435 // Check whether the given named feature is available.
check_feature(const std::string & name)2436 bool check_feature(const std::string& name) {
2437     ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
2438     ::android::sp<::android::IBinder> binder(
2439         sm->waitForService(::android::String16("package_native")));
2440     if (binder == nullptr) {
2441         GTEST_LOG_(ERROR) << "waitForService package_native failed";
2442         return false;
2443     }
2444     ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2445             ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2446     if (packageMgr == nullptr) {
2447         GTEST_LOG_(ERROR) << "Cannot find package manager";
2448         return false;
2449     }
2450     bool hasFeature = false;
2451     auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2452     if (!status.isOk()) {
2453         GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2454         return false;
2455     }
2456     return hasFeature;
2457 }
2458 
2459 // Return the numeric value associated with a feature.
keymint_feature_value(bool strongbox)2460 std::optional<int32_t> keymint_feature_value(bool strongbox) {
2461     std::string name = strongbox ? FEATURE_STRONGBOX_KEYSTORE : FEATURE_HARDWARE_KEYSTORE;
2462     ::android::String16 name16(name.c_str());
2463     ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
2464     ::android::sp<::android::IBinder> binder(
2465             sm->waitForService(::android::String16("package_native")));
2466     if (binder == nullptr) {
2467         GTEST_LOG_(ERROR) << "waitForService package_native failed";
2468         return std::nullopt;
2469     }
2470     ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2471             ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2472     if (packageMgr == nullptr) {
2473         GTEST_LOG_(ERROR) << "Cannot find package manager";
2474         return std::nullopt;
2475     }
2476 
2477     // Package manager has no mechanism to retrieve the version of a feature,
2478     // only to indicate whether a certain version or above is present.
2479     std::optional<int32_t> result = std::nullopt;
2480     for (auto version : kFeatureVersions) {
2481         bool hasFeature = false;
2482         auto status = packageMgr->hasSystemFeature(name16, version, &hasFeature);
2483         if (!status.isOk()) {
2484             GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "', " << version
2485                               << ") failed: " << status;
2486             return result;
2487         } else if (hasFeature) {
2488             result = version;
2489         } else {
2490             break;
2491         }
2492     }
2493     return result;
2494 }
2495 
2496 namespace {
2497 
2498 std::string TELEPHONY_CMD_GET_IMEI = "cmd phone get-imei ";
2499 
2500 /*
2501  * Run a shell command and collect the output of it. If any error, set an empty string as the
2502  * output.
2503  */
exec_command(const std::string & command)2504 std::string exec_command(const std::string& command) {
2505     char buffer[128];
2506     std::string result = "";
2507 
2508     FILE* pipe = popen(command.c_str(), "r");
2509     if (!pipe) {
2510         GTEST_LOG_(ERROR) << "popen failed.";
2511         return result;
2512     }
2513 
2514     // read till end of process:
2515     while (!feof(pipe)) {
2516         if (fgets(buffer, 128, pipe) != NULL) {
2517             result += buffer;
2518         }
2519     }
2520 
2521     pclose(pipe);
2522     return result;
2523 }
2524 
2525 }  // namespace
2526 
2527 /*
2528  * Get IMEI using Telephony service shell command. If any error while executing the command
2529  * then empty string will be returned as output.
2530  */
get_imei(int slot)2531 std::string get_imei(int slot) {
2532     std::string cmd = TELEPHONY_CMD_GET_IMEI + std::to_string(slot);
2533     std::string output = exec_command(cmd);
2534 
2535     if (output.empty()) {
2536         GTEST_LOG_(ERROR) << "Command failed. Cmd: " << cmd;
2537         return "";
2538     }
2539 
2540     vector<std::string> out =
2541             ::android::base::Tokenize(::android::base::Trim(output), "Device IMEI:");
2542 
2543     if (out.size() != 1) {
2544         GTEST_LOG_(ERROR) << "Error in parsing the command output. Cmd: " << cmd;
2545         return "";
2546     }
2547 
2548     std::string imei = ::android::base::Trim(out[0]);
2549     if (imei.compare("null") == 0) {
2550         GTEST_LOG_(WARNING) << "Failed to get IMEI from Telephony service: value is null. Cmd: "
2551                             << cmd;
2552         return "";
2553     }
2554 
2555     return imei;
2556 }
2557 
get_attestation_id(const char * prop)2558 std::optional<std::string> get_attestation_id(const char* prop) {
2559     // The frameworks code (in AndroidKeyStoreKeyPairGeneratorSpi.java) populates device ID
2560     // values from one of 3 places, so the same logic needs to be reproduced here so the tests
2561     // check what's expected correctly.
2562     //
2563     // In order of preference, the properties checked are:
2564     //
2565     // 1) `ro.product.<device-id>_for_attestation`: This should only be set in special cases; in
2566     //     particular, AOSP builds for reference devices use a different value than the normal
2567     //     builds for the same device (e.g. model of "aosp_raven" instead of "raven").
2568     ::android::String8 prop_name =
2569             ::android::String8::format("ro.product.%s_for_attestation", prop);
2570     std::string prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
2571     if (!prop_value.empty()) {
2572         return prop_value;
2573     }
2574 
2575     // 2) `ro.product.vendor.<device-id>`: This property refers to the vendor code, and so is
2576     //    retained even in a GSI environment.
2577     prop_name = ::android::String8::format("ro.product.vendor.%s", prop);
2578     prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
2579     if (!prop_value.empty()) {
2580         return prop_value;
2581     }
2582 
2583     // 3) `ro.product.<device-id>`: Note that this property is replaced by a default value when
2584     //    running a GSI environment, and so will *not* match the value expected/used by the
2585     //    vendor code on the device.
2586     prop_name = ::android::String8::format("ro.product.%s", prop);
2587     prop_value = ::android::base::GetProperty(prop_name.c_str(), /* default= */ "");
2588     if (!prop_value.empty()) {
2589         return prop_value;
2590     }
2591 
2592     return std::nullopt;
2593 }
2594 
2595 }  // namespace test
2596 
2597 }  // namespace aidl::android::hardware::security::keymint
2598