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