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