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
24 #include <android-base/logging.h>
25 #include <android/binder_manager.h>
26 #include <android/content/pm/IPackageManagerNative.h>
27 #include <cppbor_parse.h>
28 #include <cutils/properties.h>
29 #include <gmock/gmock.h>
30 #include <openssl/evp.h>
31 #include <openssl/mem.h>
32 #include <remote_prov/remote_prov_utils.h>
33
34 #include <keymaster/cppcose/cppcose.h>
35 #include <keymint_support/key_param_output.h>
36 #include <keymint_support/keymint_utils.h>
37 #include <keymint_support/openssl_utils.h>
38
39 namespace aidl::android::hardware::security::keymint {
40
41 using namespace cppcose;
42 using namespace std::literals::chrono_literals;
43 using std::endl;
44 using std::optional;
45 using std::unique_ptr;
46 using ::testing::AssertionFailure;
47 using ::testing::AssertionResult;
48 using ::testing::AssertionSuccess;
49 using ::testing::ElementsAreArray;
50 using ::testing::MatchesRegex;
51 using ::testing::Not;
52
operator <<(::std::ostream & os,const AuthorizationSet & set)53 ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
54 if (set.size() == 0)
55 os << "(Empty)" << ::std::endl;
56 else {
57 os << "\n";
58 for (auto& entry : set) os << entry << ::std::endl;
59 }
60 return os;
61 }
62
63 namespace test {
64
65 namespace {
66
67 // Invalid value for a patchlevel (which is of form YYYYMMDD).
68 const uint32_t kInvalidPatchlevel = 99998877;
69
70 // Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
71 // additional overhead, for the digest algorithmIdentifier required by PKCS#1.
72 const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
73
74 typedef KeyMintAidlTestBase::KeyData KeyData;
75 // Predicate for testing basic characteristics validity in generation or import.
KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,const vector<KeyCharacteristics> & key_characteristics)76 bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
77 const vector<KeyCharacteristics>& key_characteristics) {
78 if (key_characteristics.empty()) return false;
79
80 std::unordered_set<SecurityLevel> levels_seen;
81 for (auto& entry : key_characteristics) {
82 if (entry.authorizations.empty()) {
83 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
84 return false;
85 }
86
87 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
88 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
89
90 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
91 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
92 return false;
93 }
94 levels_seen.insert(entry.securityLevel);
95
96 // Generally, we should only have one entry, at the same security level as the KM
97 // instance. There is an exception: StrongBox KM can have some authorizations that are
98 // enforced by the TEE.
99 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
100 (secLevel == SecurityLevel::STRONGBOX &&
101 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
102
103 if (!isExpectedSecurityLevel) {
104 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
105 return false;
106 }
107 }
108 return true;
109 }
110
111 // Extract attestation record from cert. Returned object is still part of cert; don't free it
112 // separately.
get_attestation_record(X509 * certificate)113 ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
114 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
115 EXPECT_TRUE(!!oid.get());
116 if (!oid.get()) return nullptr;
117
118 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
119 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
120 if (location == -1) return nullptr;
121
122 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
123 EXPECT_TRUE(!!attest_rec_ext)
124 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
125 if (!attest_rec_ext) return nullptr;
126
127 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
128 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
129 return attest_rec;
130 }
131
check_attestation_version(uint32_t attestation_version,int32_t aidl_version)132 void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
133 // Version numbers in attestation extensions should be a multiple of 100.
134 EXPECT_EQ(attestation_version % 100, 0);
135
136 // The multiplier should never be higher than the AIDL version, but can be less
137 // (for example, if the implementation is from an earlier version but the HAL service
138 // uses the default libraries and so reports the current AIDL version).
139 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
140 }
141
avb_verification_enabled()142 bool avb_verification_enabled() {
143 char value[PROPERTY_VALUE_MAX];
144 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
145 }
146
147 char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
148 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
149
150 // Attestations don't contain everything in key authorization lists, so we need to filter the key
151 // lists to produce the lists that we expect to match the attestations.
152 auto kTagsToFilter = {
153 Tag::CREATION_DATETIME,
154 Tag::HARDWARE_TYPE,
155 Tag::INCLUDE_UNIQUE_ID,
156 };
157
filtered_tags(const AuthorizationSet & set)158 AuthorizationSet filtered_tags(const AuthorizationSet& set) {
159 AuthorizationSet filtered;
160 std::remove_copy_if(
161 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
162 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
163 kTagsToFilter.end();
164 });
165 return filtered;
166 }
167
168 // Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
strip_keystore_tags(vector<KeyCharacteristics> * characteristics)169 void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
170 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
171 [](const auto& entry) {
172 return entry.securityLevel == SecurityLevel::KEYSTORE;
173 }),
174 characteristics->end());
175 }
176
x509NameToStr(X509_NAME * name)177 string x509NameToStr(X509_NAME* name) {
178 char* s = X509_NAME_oneline(name, nullptr, 0);
179 string retval(s);
180 OPENSSL_free(s);
181 return retval;
182 }
183
184 } // namespace
185
186 bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
187 bool KeyMintAidlTestBase::dump_Attestations = false;
188
boot_patch_level(const vector<KeyCharacteristics> & key_characteristics)189 uint32_t KeyMintAidlTestBase::boot_patch_level(
190 const vector<KeyCharacteristics>& key_characteristics) {
191 // The boot patchlevel is not available as a property, but should be present
192 // in the key characteristics of any created key.
193 AuthorizationSet allAuths;
194 for (auto& entry : key_characteristics) {
195 allAuths.push_back(AuthorizationSet(entry.authorizations));
196 }
197 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
198 if (patchlevel.has_value()) {
199 return patchlevel.value();
200 } else {
201 // No boot patchlevel is available. Return a value that won't match anything
202 // and so will trigger test failures.
203 return kInvalidPatchlevel;
204 }
205 }
206
boot_patch_level()207 uint32_t KeyMintAidlTestBase::boot_patch_level() {
208 return boot_patch_level(key_characteristics_);
209 }
210
211 /**
212 * An API to determine device IDs attestation is required or not,
213 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
214 */
isDeviceIdAttestationRequired()215 bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
216 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= 33;
217 }
218
Curve25519Supported()219 bool KeyMintAidlTestBase::Curve25519Supported() {
220 // Strongbox never supports curve 25519.
221 if (SecLevel() == SecurityLevel::STRONGBOX) {
222 return false;
223 }
224
225 // Curve 25519 was included in version 2 of the KeyMint interface.
226 int32_t version = 0;
227 auto status = keymint_->getInterfaceVersion(&version);
228 if (!status.isOk()) {
229 ADD_FAILURE() << "Failed to determine interface version";
230 }
231 return version >= 2;
232 }
233
GetReturnErrorCode(const Status & result)234 ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
235 if (result.isOk()) return ErrorCode::OK;
236
237 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
238 return static_cast<ErrorCode>(result.getServiceSpecificError());
239 }
240
241 return ErrorCode::UNKNOWN_ERROR;
242 }
243
InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint)244 void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
245 ASSERT_NE(keyMint, nullptr);
246 keymint_ = std::move(keyMint);
247
248 KeyMintHardwareInfo info;
249 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
250
251 securityLevel_ = info.securityLevel;
252 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
253 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
254 timestamp_token_required_ = info.timestampTokenRequired;
255
256 os_version_ = getOsVersion();
257 os_patch_level_ = getOsPatchlevel();
258 vendor_patch_level_ = getVendorPatchlevel();
259 }
260
AidlVersion()261 int32_t KeyMintAidlTestBase::AidlVersion() {
262 int32_t version = 0;
263 auto status = keymint_->getInterfaceVersion(&version);
264 if (!status.isOk()) {
265 ADD_FAILURE() << "Failed to determine interface version";
266 }
267 return version;
268 }
269
SetUp()270 void KeyMintAidlTestBase::SetUp() {
271 if (AServiceManager_isDeclared(GetParam().c_str())) {
272 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
273 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
274 } else {
275 InitializeKeyMint(nullptr);
276 }
277 }
278
GenerateKey(const AuthorizationSet & key_desc,const optional<AttestationKey> & attest_key,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics,vector<Certificate> * cert_chain)279 ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
280 const optional<AttestationKey>& attest_key,
281 vector<uint8_t>* key_blob,
282 vector<KeyCharacteristics>* key_characteristics,
283 vector<Certificate>* cert_chain) {
284 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
285 EXPECT_NE(key_characteristics, nullptr)
286 << "Previous characteristics not deleted before generating key. Test bug.";
287
288 KeyCreationResult creationResult;
289 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
290 if (result.isOk()) {
291 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
292 creationResult.keyCharacteristics);
293 EXPECT_GT(creationResult.keyBlob.size(), 0);
294 *key_blob = std::move(creationResult.keyBlob);
295 *key_characteristics = std::move(creationResult.keyCharacteristics);
296 *cert_chain = std::move(creationResult.certificateChain);
297
298 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
299 EXPECT_TRUE(algorithm);
300 if (algorithm &&
301 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
302 EXPECT_GE(cert_chain->size(), 1);
303 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
304 if (attest_key) {
305 EXPECT_EQ(cert_chain->size(), 1);
306 } else {
307 EXPECT_GT(cert_chain->size(), 1);
308 }
309 }
310 } else {
311 // For symmetric keys there should be no certificates.
312 EXPECT_EQ(cert_chain->size(), 0);
313 }
314 }
315
316 return GetReturnErrorCode(result);
317 }
318
GenerateKey(const AuthorizationSet & key_desc,const optional<AttestationKey> & attest_key)319 ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
320 const optional<AttestationKey>& attest_key) {
321 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
322 }
323
GenerateKeyWithSelfSignedAttestKey(const AuthorizationSet & attest_key_desc,const AuthorizationSet & key_desc,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics,vector<Certificate> * cert_chain)324 ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
325 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
326 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
327 vector<Certificate>* cert_chain) {
328 AttestationKey attest_key;
329 vector<Certificate> attest_cert_chain;
330 vector<KeyCharacteristics> attest_key_characteristics;
331 // Generate a key with self signed attestation.
332 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
333 &attest_key_characteristics, &attest_cert_chain);
334 if (error != ErrorCode::OK) {
335 return error;
336 }
337
338 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
339 // Generate a key, by passing the above self signed attestation key as attest key.
340 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
341 if (error == ErrorCode::OK) {
342 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
343 cert_chain->push_back(attest_cert_chain[0]);
344 }
345 return error;
346 }
347
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material,vector<uint8_t> * key_blob,vector<KeyCharacteristics> * key_characteristics)348 ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
349 const string& key_material, vector<uint8_t>* key_blob,
350 vector<KeyCharacteristics>* key_characteristics) {
351 Status result;
352
353 cert_chain_.clear();
354 key_characteristics->clear();
355 key_blob->clear();
356
357 KeyCreationResult creationResult;
358 result = keymint_->importKey(key_desc.vector_data(), format,
359 vector<uint8_t>(key_material.begin(), key_material.end()),
360 {} /* attestationSigningKeyBlob */, &creationResult);
361
362 if (result.isOk()) {
363 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
364 creationResult.keyCharacteristics);
365 EXPECT_GT(creationResult.keyBlob.size(), 0);
366
367 *key_blob = std::move(creationResult.keyBlob);
368 *key_characteristics = std::move(creationResult.keyCharacteristics);
369 cert_chain_ = std::move(creationResult.certificateChain);
370
371 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
372 EXPECT_TRUE(algorithm);
373 if (algorithm &&
374 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
375 EXPECT_GE(cert_chain_.size(), 1);
376 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
377 } else {
378 // For symmetric keys there should be no certificates.
379 EXPECT_EQ(cert_chain_.size(), 0);
380 }
381 }
382
383 return GetReturnErrorCode(result);
384 }
385
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material)386 ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
387 const string& key_material) {
388 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
389 }
390
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)391 ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
392 const AuthorizationSet& wrapping_key_desc,
393 string masking_key,
394 const AuthorizationSet& unwrapping_params,
395 int64_t password_sid, int64_t biometric_sid) {
396 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
397
398 key_characteristics_.clear();
399
400 KeyCreationResult creationResult;
401 Status result = keymint_->importWrappedKey(
402 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
403 vector<uint8_t>(masking_key.begin(), masking_key.end()),
404 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
405
406 if (result.isOk()) {
407 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
408 creationResult.keyCharacteristics);
409 EXPECT_GT(creationResult.keyBlob.size(), 0);
410
411 key_blob_ = std::move(creationResult.keyBlob);
412 key_characteristics_ = std::move(creationResult.keyCharacteristics);
413 cert_chain_ = std::move(creationResult.certificateChain);
414
415 AuthorizationSet allAuths;
416 for (auto& entry : key_characteristics_) {
417 allAuths.push_back(AuthorizationSet(entry.authorizations));
418 }
419 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
420 EXPECT_TRUE(algorithm);
421 if (algorithm &&
422 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
423 EXPECT_GE(cert_chain_.size(), 1);
424 } else {
425 // For symmetric keys there should be no certificates.
426 EXPECT_EQ(cert_chain_.size(), 0);
427 }
428 }
429
430 return GetReturnErrorCode(result);
431 }
432
GetCharacteristics(const vector<uint8_t> & key_blob,const vector<uint8_t> & app_id,const vector<uint8_t> & app_data,vector<KeyCharacteristics> * key_characteristics)433 ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
434 const vector<uint8_t>& app_id,
435 const vector<uint8_t>& app_data,
436 vector<KeyCharacteristics>* key_characteristics) {
437 Status result =
438 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
439 return GetReturnErrorCode(result);
440 }
441
GetCharacteristics(const vector<uint8_t> & key_blob,vector<KeyCharacteristics> * key_characteristics)442 ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
443 vector<KeyCharacteristics>* key_characteristics) {
444 vector<uint8_t> empty_app_id, empty_app_data;
445 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
446 }
447
CheckCharacteristics(const vector<uint8_t> & key_blob,const vector<KeyCharacteristics> & generate_characteristics)448 void KeyMintAidlTestBase::CheckCharacteristics(
449 const vector<uint8_t>& key_blob,
450 const vector<KeyCharacteristics>& generate_characteristics) {
451 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
452 // generateKey() should be excluded, as KeyMint will have no record of them.
453 // This applies to CREATION_DATETIME in particular.
454 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
455 strip_keystore_tags(&expected_characteristics);
456
457 vector<KeyCharacteristics> retrieved;
458 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
459 EXPECT_EQ(expected_characteristics, retrieved);
460 }
461
CheckAppIdCharacteristics(const vector<uint8_t> & key_blob,std::string_view app_id_string,std::string_view app_data_string,const vector<KeyCharacteristics> & generate_characteristics)462 void KeyMintAidlTestBase::CheckAppIdCharacteristics(
463 const vector<uint8_t>& key_blob, std::string_view app_id_string,
464 std::string_view app_data_string,
465 const vector<KeyCharacteristics>& generate_characteristics) {
466 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
467 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
468 strip_keystore_tags(&expected_characteristics);
469
470 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
471 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
472 vector<KeyCharacteristics> retrieved;
473 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
474 EXPECT_EQ(expected_characteristics, retrieved);
475
476 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
477 vector<uint8_t> empty;
478 vector<KeyCharacteristics> not_retrieved;
479 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
480 GetCharacteristics(key_blob, empty, app_data, ¬_retrieved));
481 EXPECT_EQ(not_retrieved.size(), 0);
482
483 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
484 GetCharacteristics(key_blob, app_id, empty, ¬_retrieved));
485 EXPECT_EQ(not_retrieved.size(), 0);
486
487 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
488 GetCharacteristics(key_blob, empty, empty, ¬_retrieved));
489 EXPECT_EQ(not_retrieved.size(), 0);
490 }
491
DeleteKey(vector<uint8_t> * key_blob,bool keep_key_blob)492 ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
493 Status result = keymint_->deleteKey(*key_blob);
494 if (!keep_key_blob) {
495 *key_blob = vector<uint8_t>();
496 }
497
498 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
499 return GetReturnErrorCode(result);
500 }
501
DeleteKey(bool keep_key_blob)502 ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
503 return DeleteKey(&key_blob_, keep_key_blob);
504 }
505
DeleteAllKeys()506 ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
507 Status result = keymint_->deleteAllKeys();
508 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
509 return GetReturnErrorCode(result);
510 }
511
DestroyAttestationIds()512 ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
513 Status result = keymint_->destroyAttestationIds();
514 return GetReturnErrorCode(result);
515 }
516
CheckedDeleteKey(vector<uint8_t> * key_blob,bool keep_key_blob)517 void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
518 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
519 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
520 }
521
CheckedDeleteKey()522 void KeyMintAidlTestBase::CheckedDeleteKey() {
523 CheckedDeleteKey(&key_blob_);
524 }
525
Begin(KeyPurpose purpose,const vector<uint8_t> & key_blob,const AuthorizationSet & in_params,AuthorizationSet * out_params,std::shared_ptr<IKeyMintOperation> & op)526 ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
527 const AuthorizationSet& in_params,
528 AuthorizationSet* out_params,
529 std::shared_ptr<IKeyMintOperation>& op) {
530 SCOPED_TRACE("Begin");
531 Status result;
532 BeginResult out;
533 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
534
535 if (result.isOk()) {
536 *out_params = out.params;
537 challenge_ = out.challenge;
538 op = out.operation;
539 }
540
541 return GetReturnErrorCode(result);
542 }
543
Begin(KeyPurpose purpose,const vector<uint8_t> & key_blob,const AuthorizationSet & in_params,AuthorizationSet * out_params)544 ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
545 const AuthorizationSet& in_params,
546 AuthorizationSet* out_params) {
547 SCOPED_TRACE("Begin");
548 Status result;
549 BeginResult out;
550
551 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
552
553 if (result.isOk()) {
554 *out_params = out.params;
555 challenge_ = out.challenge;
556 op_ = out.operation;
557 }
558
559 return GetReturnErrorCode(result);
560 }
561
Begin(KeyPurpose purpose,const AuthorizationSet & in_params,AuthorizationSet * out_params)562 ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
563 AuthorizationSet* out_params) {
564 SCOPED_TRACE("Begin");
565 EXPECT_EQ(nullptr, op_);
566 return Begin(purpose, key_blob_, in_params, out_params);
567 }
568
Begin(KeyPurpose purpose,const AuthorizationSet & in_params)569 ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
570 SCOPED_TRACE("Begin");
571 AuthorizationSet out_params;
572 ErrorCode result = Begin(purpose, in_params, &out_params);
573 EXPECT_TRUE(out_params.empty());
574 return result;
575 }
576
UpdateAad(const string & input)577 ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
578 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
579 {} /* hardwareAuthToken */,
580 {} /* verificationToken */));
581 }
582
Update(const string & input,string * output)583 ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
584 SCOPED_TRACE("Update");
585
586 Status result;
587 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
588
589 EXPECT_NE(op_, nullptr);
590 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
591
592 std::vector<uint8_t> o_put;
593 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
594
595 if (result.isOk()) {
596 output->append(o_put.begin(), o_put.end());
597 } else {
598 // Failure always terminates the operation.
599 op_ = {};
600 }
601
602 return GetReturnErrorCode(result);
603 }
604
Finish(const string & input,const string & signature,string * output)605 ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
606 string* output) {
607 SCOPED_TRACE("Finish");
608 Status result;
609
610 EXPECT_NE(op_, nullptr);
611 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
612
613 vector<uint8_t> oPut;
614 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
615 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
616 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
617
618 if (result.isOk()) output->append(oPut.begin(), oPut.end());
619
620 op_ = {};
621 return GetReturnErrorCode(result);
622 }
623
Abort(const std::shared_ptr<IKeyMintOperation> & op)624 ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
625 SCOPED_TRACE("Abort");
626
627 EXPECT_NE(op, nullptr);
628 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
629
630 Status retval = op->abort();
631 EXPECT_TRUE(retval.isOk());
632 return static_cast<ErrorCode>(retval.getServiceSpecificError());
633 }
634
Abort()635 ErrorCode KeyMintAidlTestBase::Abort() {
636 SCOPED_TRACE("Abort");
637
638 EXPECT_NE(op_, nullptr);
639 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
640
641 Status retval = op_->abort();
642 return static_cast<ErrorCode>(retval.getServiceSpecificError());
643 }
644
AbortIfNeeded()645 void KeyMintAidlTestBase::AbortIfNeeded() {
646 SCOPED_TRACE("AbortIfNeeded");
647 if (op_) {
648 EXPECT_EQ(ErrorCode::OK, Abort());
649 op_.reset();
650 }
651 }
652
ProcessMessage(const vector<uint8_t> & key_blob,KeyPurpose operation,const string & message,const AuthorizationSet & in_params)653 auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
654 const string& message, const AuthorizationSet& in_params)
655 -> std::tuple<ErrorCode, string> {
656 AuthorizationSet begin_out_params;
657 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
658 if (result != ErrorCode::OK) return {result, {}};
659
660 string output;
661 return {Finish(message, &output), output};
662 }
663
ProcessMessage(const vector<uint8_t> & key_blob,KeyPurpose operation,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)664 string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
665 const string& message, const AuthorizationSet& in_params,
666 AuthorizationSet* out_params) {
667 SCOPED_TRACE("ProcessMessage");
668 AuthorizationSet begin_out_params;
669 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
670 EXPECT_EQ(ErrorCode::OK, result);
671 if (result != ErrorCode::OK) {
672 return "";
673 }
674
675 string output;
676 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
677 return output;
678 }
679
SignMessage(const vector<uint8_t> & key_blob,const string & message,const AuthorizationSet & params)680 string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
681 const AuthorizationSet& params) {
682 SCOPED_TRACE("SignMessage");
683 AuthorizationSet out_params;
684 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
685 EXPECT_TRUE(out_params.empty());
686 return signature;
687 }
688
SignMessage(const string & message,const AuthorizationSet & params)689 string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
690 SCOPED_TRACE("SignMessage");
691 return SignMessage(key_blob_, message, params);
692 }
693
MacMessage(const string & message,Digest digest,size_t mac_length)694 string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
695 SCOPED_TRACE("MacMessage");
696 return SignMessage(
697 key_blob_, message,
698 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
699 }
700
CheckAesIncrementalEncryptOperation(BlockMode block_mode,int message_size)701 void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
702 int message_size) {
703 auto builder = AuthorizationSetBuilder()
704 .Authorization(TAG_NO_AUTH_REQUIRED)
705 .AesEncryptionKey(128)
706 .BlockMode(block_mode)
707 .Padding(PaddingMode::NONE);
708 if (block_mode == BlockMode::GCM) {
709 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
710 }
711 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
712
713 for (int increment = 1; increment <= message_size; ++increment) {
714 string message(message_size, 'a');
715 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
716 if (block_mode == BlockMode::GCM) {
717 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
718 }
719
720 AuthorizationSet output_params;
721 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
722
723 string ciphertext;
724 string to_send;
725 for (size_t i = 0; i < message.size(); i += increment) {
726 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
727 }
728 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
729 << "Error sending " << to_send << " with block mode " << block_mode;
730
731 switch (block_mode) {
732 case BlockMode::GCM:
733 EXPECT_EQ(message.size() + 16, ciphertext.size());
734 break;
735 case BlockMode::CTR:
736 EXPECT_EQ(message.size(), ciphertext.size());
737 break;
738 case BlockMode::CBC:
739 case BlockMode::ECB:
740 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
741 break;
742 }
743
744 auto iv = output_params.GetTagValue(TAG_NONCE);
745 switch (block_mode) {
746 case BlockMode::CBC:
747 case BlockMode::GCM:
748 case BlockMode::CTR:
749 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
750 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
751 params.push_back(TAG_NONCE, iv->get());
752 break;
753
754 case BlockMode::ECB:
755 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
756 break;
757 }
758
759 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
760 << "Decrypt begin() failed for block mode " << block_mode;
761
762 string plaintext;
763 for (size_t i = 0; i < ciphertext.size(); i += increment) {
764 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
765 }
766 ErrorCode error = Finish(to_send, &plaintext);
767 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
768 << " and increment " << increment;
769 if (error == ErrorCode::OK) {
770 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
771 << " and increment " << increment;
772 }
773 }
774 }
775
CheckHmacTestVector(const string & key,const string & message,Digest digest,const string & expected_mac)776 void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
777 Digest digest, const string& expected_mac) {
778 SCOPED_TRACE("CheckHmacTestVector");
779 ASSERT_EQ(ErrorCode::OK,
780 ImportKey(AuthorizationSetBuilder()
781 .Authorization(TAG_NO_AUTH_REQUIRED)
782 .HmacKey(key.size() * 8)
783 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
784 .Digest(digest),
785 KeyFormat::RAW, key));
786 string signature = MacMessage(message, digest, expected_mac.size() * 8);
787 EXPECT_EQ(expected_mac, signature)
788 << "Test vector didn't match for key of size " << key.size() << " message of size "
789 << message.size() << " and digest " << digest;
790 CheckedDeleteKey();
791 }
792
CheckAesCtrTestVector(const string & key,const string & nonce,const string & message,const string & expected_ciphertext)793 void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
794 const string& message,
795 const string& expected_ciphertext) {
796 SCOPED_TRACE("CheckAesCtrTestVector");
797 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
798 .Authorization(TAG_NO_AUTH_REQUIRED)
799 .AesEncryptionKey(key.size() * 8)
800 .BlockMode(BlockMode::CTR)
801 .Authorization(TAG_CALLER_NONCE)
802 .Padding(PaddingMode::NONE),
803 KeyFormat::RAW, key));
804
805 auto params = AuthorizationSetBuilder()
806 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
807 .BlockMode(BlockMode::CTR)
808 .Padding(PaddingMode::NONE);
809 AuthorizationSet out_params;
810 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
811 EXPECT_EQ(expected_ciphertext, ciphertext);
812 }
813
CheckTripleDesTestVector(KeyPurpose purpose,BlockMode block_mode,PaddingMode padding_mode,const string & key,const string & iv,const string & input,const string & expected_output)814 void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
815 PaddingMode padding_mode, const string& key,
816 const string& iv, const string& input,
817 const string& expected_output) {
818 auto authset = AuthorizationSetBuilder()
819 .TripleDesEncryptionKey(key.size() * 7)
820 .BlockMode(block_mode)
821 .Authorization(TAG_NO_AUTH_REQUIRED)
822 .Padding(padding_mode);
823 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
824 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
825 ASSERT_GT(key_blob_.size(), 0U);
826
827 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
828 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
829 AuthorizationSet output_params;
830 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
831 EXPECT_EQ(expected_output, output);
832 }
833
VerifyMessage(const vector<uint8_t> & key_blob,const string & message,const string & signature,const AuthorizationSet & params)834 void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
835 const string& signature, const AuthorizationSet& params) {
836 SCOPED_TRACE("VerifyMessage");
837 AuthorizationSet begin_out_params;
838 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
839
840 string output;
841 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
842 EXPECT_TRUE(output.empty());
843 op_ = {};
844 }
845
VerifyMessage(const string & message,const string & signature,const AuthorizationSet & params)846 void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
847 const AuthorizationSet& params) {
848 SCOPED_TRACE("VerifyMessage");
849 VerifyMessage(key_blob_, message, signature, params);
850 }
851
LocalVerifyMessage(const string & message,const string & signature,const AuthorizationSet & params)852 void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
853 const AuthorizationSet& params) {
854 SCOPED_TRACE("LocalVerifyMessage");
855
856 // Retrieve the public key from the leaf certificate.
857 ASSERT_GT(cert_chain_.size(), 0);
858 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
859 ASSERT_TRUE(key_cert.get());
860 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
861 ASSERT_TRUE(pub_key.get());
862
863 Digest digest = params.GetTagValue(TAG_DIGEST).value();
864 PaddingMode padding = PaddingMode::NONE;
865 auto tag = params.GetTagValue(TAG_PADDING);
866 if (tag.has_value()) {
867 padding = tag.value();
868 }
869
870 if (digest == Digest::NONE) {
871 switch (EVP_PKEY_id(pub_key.get())) {
872 case EVP_PKEY_ED25519: {
873 ASSERT_EQ(64, signature.size());
874 uint8_t pub_keydata[32];
875 size_t pub_len = sizeof(pub_keydata);
876 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
877 ASSERT_EQ(sizeof(pub_keydata), pub_len);
878 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
879 message.size(),
880 reinterpret_cast<const uint8_t*>(signature.data()),
881 pub_keydata));
882 break;
883 }
884
885 case EVP_PKEY_EC: {
886 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
887 size_t data_size = std::min(data.size(), message.size());
888 memcpy(data.data(), message.data(), data_size);
889 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
890 ASSERT_TRUE(ecdsa.get());
891 ASSERT_EQ(1,
892 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
893 reinterpret_cast<const uint8_t*>(signature.data()),
894 signature.size(), ecdsa.get()));
895 break;
896 }
897 case EVP_PKEY_RSA: {
898 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
899 size_t data_size = std::min(data.size(), message.size());
900 memcpy(data.data(), message.data(), data_size);
901
902 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
903 ASSERT_TRUE(rsa.get());
904
905 size_t key_len = RSA_size(rsa.get());
906 int openssl_padding = RSA_NO_PADDING;
907 switch (padding) {
908 case PaddingMode::NONE:
909 ASSERT_TRUE(data_size <= key_len);
910 ASSERT_EQ(key_len, signature.size());
911 openssl_padding = RSA_NO_PADDING;
912 break;
913 case PaddingMode::RSA_PKCS1_1_5_SIGN:
914 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
915 key_len);
916 openssl_padding = RSA_PKCS1_PADDING;
917 break;
918 default:
919 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
920 }
921
922 vector<uint8_t> decrypted_data(key_len);
923 int bytes_decrypted = RSA_public_decrypt(
924 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
925 decrypted_data.data(), rsa.get(), openssl_padding);
926 ASSERT_GE(bytes_decrypted, 0);
927
928 const uint8_t* compare_pos = decrypted_data.data();
929 size_t bytes_to_compare = bytes_decrypted;
930 uint8_t zero_check_result = 0;
931 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
932 // If the data is short, for "unpadded" signing we zero-pad to the left. So
933 // during verification we should have zeros on the left of the decrypted data.
934 // Do a constant-time check.
935 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
936 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
937 ASSERT_EQ(0, zero_check_result);
938 bytes_to_compare = data_size;
939 }
940 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
941 break;
942 }
943 default:
944 ADD_FAILURE() << "Unknown public key type";
945 }
946 } else {
947 EVP_MD_CTX digest_ctx;
948 EVP_MD_CTX_init(&digest_ctx);
949 EVP_PKEY_CTX* pkey_ctx;
950 const EVP_MD* md = openssl_digest(digest);
951 ASSERT_NE(md, nullptr);
952 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
953
954 if (padding == PaddingMode::RSA_PSS) {
955 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
956 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
957 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
958 }
959
960 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
961 reinterpret_cast<const uint8_t*>(message.data()),
962 message.size()));
963 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
964 reinterpret_cast<const uint8_t*>(signature.data()),
965 signature.size()));
966 EVP_MD_CTX_cleanup(&digest_ctx);
967 }
968 }
969
LocalRsaEncryptMessage(const string & message,const AuthorizationSet & params)970 string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
971 const AuthorizationSet& params) {
972 SCOPED_TRACE("LocalRsaEncryptMessage");
973
974 // Retrieve the public key from the leaf certificate.
975 if (cert_chain_.empty()) {
976 ADD_FAILURE() << "No public key available";
977 return "Failure";
978 }
979 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
980 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
981 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
982
983 // Retrieve relevant tags.
984 Digest digest = Digest::NONE;
985 Digest mgf_digest = Digest::NONE;
986 PaddingMode padding = PaddingMode::NONE;
987
988 auto digest_tag = params.GetTagValue(TAG_DIGEST);
989 if (digest_tag.has_value()) digest = digest_tag.value();
990 auto pad_tag = params.GetTagValue(TAG_PADDING);
991 if (pad_tag.has_value()) padding = pad_tag.value();
992 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
993 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
994
995 const EVP_MD* md = openssl_digest(digest);
996 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
997
998 // Set up encryption context.
999 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1000 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1001 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1002 return "Failure";
1003 }
1004
1005 int rc = -1;
1006 switch (padding) {
1007 case PaddingMode::NONE:
1008 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1009 break;
1010 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1011 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1012 break;
1013 case PaddingMode::RSA_OAEP:
1014 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1015 break;
1016 default:
1017 break;
1018 }
1019 if (rc <= 0) {
1020 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1021 return "Failure";
1022 }
1023 if (padding == PaddingMode::RSA_OAEP) {
1024 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1025 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1026 return "Failure";
1027 }
1028 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1029 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1030 return "Failure";
1031 }
1032 }
1033
1034 // Determine output size.
1035 size_t outlen;
1036 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1037 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1038 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1039 return "Failure";
1040 }
1041
1042 // Left-zero-pad the input if necessary.
1043 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1044 size_t to_encrypt_len = message.size();
1045
1046 std::unique_ptr<string> zero_padded_message;
1047 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1048 zero_padded_message.reset(new string(outlen, '\0'));
1049 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1050 message.size());
1051 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1052 to_encrypt_len = outlen;
1053 }
1054
1055 // Do the encryption.
1056 string output(outlen, '\0');
1057 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1058 to_encrypt_len) <= 0) {
1059 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1060 return "Failure";
1061 }
1062 return output;
1063 }
1064
EncryptMessage(const vector<uint8_t> & key_blob,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)1065 string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1066 const AuthorizationSet& in_params,
1067 AuthorizationSet* out_params) {
1068 SCOPED_TRACE("EncryptMessage");
1069 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1070 }
1071
EncryptMessage(const string & message,const AuthorizationSet & params,AuthorizationSet * out_params)1072 string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1073 AuthorizationSet* out_params) {
1074 SCOPED_TRACE("EncryptMessage");
1075 return EncryptMessage(key_blob_, message, params, out_params);
1076 }
1077
EncryptMessage(const string & message,const AuthorizationSet & params)1078 string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1079 SCOPED_TRACE("EncryptMessage");
1080 AuthorizationSet out_params;
1081 string ciphertext = EncryptMessage(message, params, &out_params);
1082 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1083 return ciphertext;
1084 }
1085
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding)1086 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1087 PaddingMode padding) {
1088 SCOPED_TRACE("EncryptMessage");
1089 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1090 AuthorizationSet out_params;
1091 string ciphertext = EncryptMessage(message, params, &out_params);
1092 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1093 return ciphertext;
1094 }
1095
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,vector<uint8_t> * iv_out)1096 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1097 PaddingMode padding, vector<uint8_t>* iv_out) {
1098 SCOPED_TRACE("EncryptMessage");
1099 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1100 AuthorizationSet out_params;
1101 string ciphertext = EncryptMessage(message, params, &out_params);
1102 EXPECT_EQ(1U, out_params.size());
1103 auto ivVal = out_params.GetTagValue(TAG_NONCE);
1104 EXPECT_TRUE(ivVal);
1105 if (ivVal) *iv_out = *ivVal;
1106 return ciphertext;
1107 }
1108
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,const vector<uint8_t> & iv_in)1109 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1110 PaddingMode padding, const vector<uint8_t>& iv_in) {
1111 SCOPED_TRACE("EncryptMessage");
1112 auto params = AuthorizationSetBuilder()
1113 .BlockMode(block_mode)
1114 .Padding(padding)
1115 .Authorization(TAG_NONCE, iv_in);
1116 AuthorizationSet out_params;
1117 string ciphertext = EncryptMessage(message, params, &out_params);
1118 return ciphertext;
1119 }
1120
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,uint8_t mac_length_bits,const vector<uint8_t> & iv_in)1121 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1122 PaddingMode padding, uint8_t mac_length_bits,
1123 const vector<uint8_t>& iv_in) {
1124 SCOPED_TRACE("EncryptMessage");
1125 auto params = AuthorizationSetBuilder()
1126 .BlockMode(block_mode)
1127 .Padding(padding)
1128 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1129 .Authorization(TAG_NONCE, iv_in);
1130 AuthorizationSet out_params;
1131 string ciphertext = EncryptMessage(message, params, &out_params);
1132 return ciphertext;
1133 }
1134
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,uint8_t mac_length_bits)1135 string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1136 PaddingMode padding, uint8_t mac_length_bits) {
1137 SCOPED_TRACE("EncryptMessage");
1138 auto params = AuthorizationSetBuilder()
1139 .BlockMode(block_mode)
1140 .Padding(padding)
1141 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1142 AuthorizationSet out_params;
1143 string ciphertext = EncryptMessage(message, params, &out_params);
1144 return ciphertext;
1145 }
1146
DecryptMessage(const vector<uint8_t> & key_blob,const string & ciphertext,const AuthorizationSet & params)1147 string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1148 const string& ciphertext,
1149 const AuthorizationSet& params) {
1150 SCOPED_TRACE("DecryptMessage");
1151 AuthorizationSet out_params;
1152 string plaintext =
1153 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1154 EXPECT_TRUE(out_params.empty());
1155 return plaintext;
1156 }
1157
DecryptMessage(const string & ciphertext,const AuthorizationSet & params)1158 string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1159 const AuthorizationSet& params) {
1160 SCOPED_TRACE("DecryptMessage");
1161 return DecryptMessage(key_blob_, ciphertext, params);
1162 }
1163
DecryptMessage(const string & ciphertext,BlockMode block_mode,PaddingMode padding_mode,const vector<uint8_t> & iv)1164 string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1165 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1166 SCOPED_TRACE("DecryptMessage");
1167 auto params = AuthorizationSetBuilder()
1168 .BlockMode(block_mode)
1169 .Padding(padding_mode)
1170 .Authorization(TAG_NONCE, iv);
1171 return DecryptMessage(key_blob_, ciphertext, params);
1172 }
1173
UpgradeKey(const vector<uint8_t> & key_blob)1174 std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1175 const vector<uint8_t>& key_blob) {
1176 std::pair<ErrorCode, vector<uint8_t>> retval;
1177 vector<uint8_t> outKeyBlob;
1178 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1179 ErrorCode errorcode = GetReturnErrorCode(result);
1180 retval = std::tie(errorcode, outKeyBlob);
1181
1182 return retval;
1183 }
ValidKeySizes(Algorithm algorithm)1184 vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1185 switch (algorithm) {
1186 case Algorithm::RSA:
1187 switch (SecLevel()) {
1188 case SecurityLevel::SOFTWARE:
1189 case SecurityLevel::TRUSTED_ENVIRONMENT:
1190 return {2048, 3072, 4096};
1191 case SecurityLevel::STRONGBOX:
1192 return {2048};
1193 default:
1194 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1195 break;
1196 }
1197 break;
1198 case Algorithm::EC:
1199 ADD_FAILURE() << "EC keys must be specified by curve not size";
1200 break;
1201 case Algorithm::AES:
1202 return {128, 256};
1203 case Algorithm::TRIPLE_DES:
1204 return {168};
1205 case Algorithm::HMAC: {
1206 vector<uint32_t> retval((512 - 64) / 8 + 1);
1207 uint32_t size = 64 - 8;
1208 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1209 return retval;
1210 }
1211 default:
1212 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1213 return {};
1214 }
1215 ADD_FAILURE() << "Should be impossible to get here";
1216 return {};
1217 }
1218
InvalidKeySizes(Algorithm algorithm)1219 vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1220 if (SecLevel() == SecurityLevel::STRONGBOX) {
1221 switch (algorithm) {
1222 case Algorithm::RSA:
1223 return {3072, 4096};
1224 case Algorithm::EC:
1225 return {224, 384, 521};
1226 case Algorithm::AES:
1227 return {192};
1228 case Algorithm::TRIPLE_DES:
1229 return {56};
1230 default:
1231 return {};
1232 }
1233 } else {
1234 switch (algorithm) {
1235 case Algorithm::AES:
1236 return {64, 96, 131, 512};
1237 case Algorithm::TRIPLE_DES:
1238 return {56};
1239 default:
1240 return {};
1241 }
1242 }
1243 return {};
1244 }
1245
ValidBlockModes(Algorithm algorithm)1246 vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1247 switch (algorithm) {
1248 case Algorithm::AES:
1249 return {
1250 BlockMode::CBC,
1251 BlockMode::CTR,
1252 BlockMode::ECB,
1253 BlockMode::GCM,
1254 };
1255 case Algorithm::TRIPLE_DES:
1256 return {
1257 BlockMode::CBC,
1258 BlockMode::ECB,
1259 };
1260 default:
1261 return {};
1262 }
1263 }
1264
ValidPaddingModes(Algorithm algorithm,BlockMode blockMode)1265 vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1266 BlockMode blockMode) {
1267 switch (algorithm) {
1268 case Algorithm::AES:
1269 switch (blockMode) {
1270 case BlockMode::CBC:
1271 case BlockMode::ECB:
1272 return {PaddingMode::NONE, PaddingMode::PKCS7};
1273 case BlockMode::CTR:
1274 case BlockMode::GCM:
1275 return {PaddingMode::NONE};
1276 default:
1277 return {};
1278 };
1279 case Algorithm::TRIPLE_DES:
1280 switch (blockMode) {
1281 case BlockMode::CBC:
1282 case BlockMode::ECB:
1283 return {PaddingMode::NONE, PaddingMode::PKCS7};
1284 default:
1285 return {};
1286 };
1287 default:
1288 return {};
1289 }
1290 }
1291
InvalidPaddingModes(Algorithm algorithm,BlockMode blockMode)1292 vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1293 BlockMode blockMode) {
1294 switch (algorithm) {
1295 case Algorithm::AES:
1296 switch (blockMode) {
1297 case BlockMode::CTR:
1298 case BlockMode::GCM:
1299 return {PaddingMode::PKCS7};
1300 default:
1301 return {};
1302 };
1303 default:
1304 return {};
1305 }
1306 }
1307
ValidCurves()1308 vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1309 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1310 return {EcCurve::P_256};
1311 } else if (Curve25519Supported()) {
1312 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1313 EcCurve::CURVE_25519};
1314 } else {
1315 return {
1316 EcCurve::P_224,
1317 EcCurve::P_256,
1318 EcCurve::P_384,
1319 EcCurve::P_521,
1320 };
1321 }
1322 }
1323
InvalidCurves()1324 vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
1325 if (SecLevel() == SecurityLevel::STRONGBOX) {
1326 // Curve 25519 is not supported, either because:
1327 // - KeyMint v1: it's an unknown enum value
1328 // - KeyMint v2+: it's not supported by StrongBox.
1329 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
1330 } else {
1331 if (Curve25519Supported()) {
1332 return {};
1333 } else {
1334 return {EcCurve::CURVE_25519};
1335 }
1336 }
1337 }
1338
ValidExponents()1339 vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1340 if (SecLevel() == SecurityLevel::STRONGBOX) {
1341 return {65537};
1342 } else {
1343 return {3, 65537};
1344 }
1345 }
1346
ValidDigests(bool withNone,bool withMD5)1347 vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1348 switch (SecLevel()) {
1349 case SecurityLevel::SOFTWARE:
1350 case SecurityLevel::TRUSTED_ENVIRONMENT:
1351 if (withNone) {
1352 if (withMD5)
1353 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1354 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1355 Digest::SHA_2_512};
1356 else
1357 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1358 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1359 } else {
1360 if (withMD5)
1361 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1362 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1363 else
1364 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1365 Digest::SHA_2_512};
1366 }
1367 break;
1368 case SecurityLevel::STRONGBOX:
1369 if (withNone)
1370 return {Digest::NONE, Digest::SHA_2_256};
1371 else
1372 return {Digest::SHA_2_256};
1373 break;
1374 default:
1375 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1376 break;
1377 }
1378 ADD_FAILURE() << "Should be impossible to get here";
1379 return {};
1380 }
1381
1382 static const vector<KeyParameter> kEmptyAuthList{};
1383
SecLevelAuthorizations(const vector<KeyCharacteristics> & key_characteristics)1384 const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1385 const vector<KeyCharacteristics>& key_characteristics) {
1386 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1387 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1388 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1389 }
1390
SecLevelAuthorizations(const vector<KeyCharacteristics> & key_characteristics,SecurityLevel securityLevel)1391 const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1392 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1393 auto found = std::find_if(
1394 key_characteristics.begin(), key_characteristics.end(),
1395 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
1396 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1397 }
1398
UseAesKey(const vector<uint8_t> & aesKeyBlob)1399 ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
1400 auto [result, ciphertext] = ProcessMessage(
1401 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1402 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1403 return result;
1404 }
1405
UseHmacKey(const vector<uint8_t> & hmacKeyBlob)1406 ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
1407 auto [result, mac] = ProcessMessage(
1408 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1409 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1410 return result;
1411 }
1412
UseRsaKey(const vector<uint8_t> & rsaKeyBlob)1413 ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1414 std::string message(2048 / 8, 'a');
1415 auto [result, signature] = ProcessMessage(
1416 rsaKeyBlob, KeyPurpose::SIGN, message,
1417 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1418 return result;
1419 }
1420
UseEcdsaKey(const vector<uint8_t> & ecdsaKeyBlob)1421 ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
1422 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1423 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1424 return result;
1425 }
1426
verify_serial(X509 * cert,const uint64_t expected_serial)1427 void verify_serial(X509* cert, const uint64_t expected_serial) {
1428 BIGNUM_Ptr ser(BN_new());
1429 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1430
1431 uint64_t serial;
1432 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1433 EXPECT_EQ(serial, expected_serial);
1434 }
1435
1436 // Please set self_signed to true for fake certificates or self signed
1437 // certificates
verify_subject(const X509 * cert,const string & subject,bool self_signed)1438 void verify_subject(const X509* cert, //
1439 const string& subject, //
1440 bool self_signed) {
1441 char* cert_issuer = //
1442 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1443
1444 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1445
1446 string expected_subject("/CN=");
1447 if (subject.empty()) {
1448 expected_subject.append("Android Keystore Key");
1449 } else {
1450 expected_subject.append(subject);
1451 }
1452
1453 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1454
1455 if (self_signed) {
1456 EXPECT_STREQ(cert_issuer, cert_subj)
1457 << "Cert issuer and subject mismatch for self signed certificate.";
1458 }
1459
1460 OPENSSL_free(cert_subj);
1461 OPENSSL_free(cert_issuer);
1462 }
1463
get_vsr_api_level()1464 int get_vsr_api_level() {
1465 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1466 if (vendor_api_level != -1) {
1467 return vendor_api_level;
1468 }
1469
1470 // Android S and older devices do not define ro.vendor.api_level
1471 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1472 if (vendor_api_level == -1) {
1473 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
1474 }
1475
1476 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1477 if (product_api_level == -1) {
1478 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1479 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
1480 }
1481
1482 // VSR API level is the minimum of vendor_api_level and product_api_level.
1483 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1484 return product_api_level;
1485 }
1486 return vendor_api_level;
1487 }
1488
is_gsi_image()1489 bool is_gsi_image() {
1490 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1491 return ifs.good();
1492 }
1493
build_serial_blob(const uint64_t serial_int)1494 vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1495 BIGNUM_Ptr serial(BN_new());
1496 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1497
1498 int len = BN_num_bytes(serial.get());
1499 vector<uint8_t> serial_blob(len);
1500 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1501 return {};
1502 }
1503
1504 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1505 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1506 // Top bit being set indicates a negative number in two's complement, but our input
1507 // was positive.
1508 // In either case, prepend a zero byte.
1509 serial_blob.insert(serial_blob.begin(), 0x00);
1510 }
1511
1512 return serial_blob;
1513 }
1514
verify_subject_and_serial(const Certificate & certificate,const uint64_t expected_serial,const string & subject,bool self_signed)1515 void verify_subject_and_serial(const Certificate& certificate, //
1516 const uint64_t expected_serial, //
1517 const string& subject, bool self_signed) {
1518 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1519 ASSERT_TRUE(!!cert.get());
1520
1521 verify_serial(cert.get(), expected_serial);
1522 verify_subject(cert.get(), subject, self_signed);
1523 }
1524
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)1525 void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1526 VerifiedBoot verified_boot_state,
1527 const vector<uint8_t>& verified_boot_hash) {
1528 char property_value[PROPERTY_VALUE_MAX] = {};
1529
1530 if (avb_verification_enabled()) {
1531 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1532 string prop_string(property_value);
1533 EXPECT_EQ(prop_string.size(), 64);
1534 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1535
1536 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1537 if (!strcmp(property_value, "unlocked")) {
1538 EXPECT_FALSE(device_locked);
1539 } else {
1540 EXPECT_TRUE(device_locked);
1541 }
1542
1543 // Check that the device is locked if not debuggable, e.g., user build
1544 // images in CTS. For VTS, debuggable images are used to allow adb root
1545 // and the device is unlocked.
1546 if (!property_get_bool("ro.debuggable", false)) {
1547 EXPECT_TRUE(device_locked);
1548 } else {
1549 EXPECT_FALSE(device_locked);
1550 }
1551 }
1552
1553 // Verified boot key should be all 0's if the boot state is not verified or self signed
1554 std::string empty_boot_key(32, '\0');
1555 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1556 verified_boot_key.size());
1557 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1558 if (!strcmp(property_value, "green")) {
1559 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1560 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1561 verified_boot_key.size()));
1562 } else if (!strcmp(property_value, "yellow")) {
1563 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1564 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1565 verified_boot_key.size()));
1566 } else if (!strcmp(property_value, "orange")) {
1567 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1568 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1569 verified_boot_key.size()));
1570 } else if (!strcmp(property_value, "red")) {
1571 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1572 } else {
1573 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1574 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1575 verified_boot_key.size()));
1576 }
1577 }
1578
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)1579 bool verify_attestation_record(int32_t aidl_version, //
1580 const string& challenge, //
1581 const string& app_id, //
1582 AuthorizationSet expected_sw_enforced, //
1583 AuthorizationSet expected_hw_enforced, //
1584 SecurityLevel security_level,
1585 const vector<uint8_t>& attestation_cert,
1586 vector<uint8_t>* unique_id) {
1587 X509_Ptr cert(parse_cert_blob(attestation_cert));
1588 EXPECT_TRUE(!!cert.get());
1589 if (!cert.get()) return false;
1590
1591 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1592 EXPECT_TRUE(!!attest_rec);
1593 if (!attest_rec) return false;
1594
1595 AuthorizationSet att_sw_enforced;
1596 AuthorizationSet att_hw_enforced;
1597 uint32_t att_attestation_version;
1598 uint32_t att_keymint_version;
1599 SecurityLevel att_attestation_security_level;
1600 SecurityLevel att_keymint_security_level;
1601 vector<uint8_t> att_challenge;
1602 vector<uint8_t> att_unique_id;
1603 vector<uint8_t> att_app_id;
1604
1605 auto error = parse_attestation_record(attest_rec->data, //
1606 attest_rec->length, //
1607 &att_attestation_version, //
1608 &att_attestation_security_level, //
1609 &att_keymint_version, //
1610 &att_keymint_security_level, //
1611 &att_challenge, //
1612 &att_sw_enforced, //
1613 &att_hw_enforced, //
1614 &att_unique_id);
1615 EXPECT_EQ(ErrorCode::OK, error);
1616 if (error != ErrorCode::OK) return false;
1617
1618 check_attestation_version(att_attestation_version, aidl_version);
1619 vector<uint8_t> appId(app_id.begin(), app_id.end());
1620
1621 // check challenge and app id only if we expects a non-fake certificate
1622 if (challenge.length() > 0) {
1623 EXPECT_EQ(challenge.length(), att_challenge.size());
1624 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1625
1626 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1627 }
1628
1629 check_attestation_version(att_keymint_version, aidl_version);
1630 EXPECT_EQ(security_level, att_keymint_security_level);
1631 EXPECT_EQ(security_level, att_attestation_security_level);
1632
1633 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
1634 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
1635 // for the BOOT_PATCH_LEVEL.
1636 if (avb_verification_enabled()) {
1637 for (int i = 0; i < att_hw_enforced.size(); i++) {
1638 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1639 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1640 std::string date =
1641 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
1642
1643 // strptime seems to require delimiters, but the tag value will
1644 // be YYYYMMDD
1645 if (date.size() != 8) {
1646 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1647 << " with invalid format (not YYYYMMDD): " << date;
1648 return false;
1649 }
1650 date.insert(6, "-");
1651 date.insert(4, "-");
1652 struct tm time;
1653 strptime(date.c_str(), "%Y-%m-%d", &time);
1654
1655 // Day of the month (0-31)
1656 EXPECT_GE(time.tm_mday, 0);
1657 EXPECT_LT(time.tm_mday, 32);
1658 // Months since Jan (0-11)
1659 EXPECT_GE(time.tm_mon, 0);
1660 EXPECT_LT(time.tm_mon, 12);
1661 // Years since 1900
1662 EXPECT_GT(time.tm_year, 110);
1663 EXPECT_LT(time.tm_year, 200);
1664 }
1665 }
1666 }
1667
1668 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1669 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1670 // indicates correct encoding. No need to check if it's in both lists, since the
1671 // AuthorizationSet compare below will handle mismatches of tags.
1672 if (security_level == SecurityLevel::SOFTWARE) {
1673 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1674 } else {
1675 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1676 }
1677
1678 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1679 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1680 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1681 att_hw_enforced.Contains(TAG_KEY_SIZE));
1682 }
1683
1684 // Test root of trust elements
1685 vector<uint8_t> verified_boot_key;
1686 VerifiedBoot verified_boot_state;
1687 bool device_locked;
1688 vector<uint8_t> verified_boot_hash;
1689 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1690 &verified_boot_state, &device_locked, &verified_boot_hash);
1691 EXPECT_EQ(ErrorCode::OK, error);
1692 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
1693
1694 att_sw_enforced.Sort();
1695 expected_sw_enforced.Sort();
1696 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
1697
1698 att_hw_enforced.Sort();
1699 expected_hw_enforced.Sort();
1700 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1701
1702 if (unique_id != nullptr) {
1703 *unique_id = att_unique_id;
1704 }
1705
1706 return true;
1707 }
1708
bin2hex(const vector<uint8_t> & data)1709 string bin2hex(const vector<uint8_t>& data) {
1710 string retval;
1711 retval.reserve(data.size() * 2 + 1);
1712 for (uint8_t byte : data) {
1713 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1714 retval.push_back(nibble2hex[0x0F & byte]);
1715 }
1716 return retval;
1717 }
1718
HwEnforcedAuthorizations(const vector<KeyCharacteristics> & key_characteristics)1719 AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1720 AuthorizationSet authList;
1721 for (auto& entry : key_characteristics) {
1722 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1723 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1724 authList.push_back(AuthorizationSet(entry.authorizations));
1725 }
1726 }
1727 return authList;
1728 }
1729
SwEnforcedAuthorizations(const vector<KeyCharacteristics> & key_characteristics)1730 AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1731 AuthorizationSet authList;
1732 for (auto& entry : key_characteristics) {
1733 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1734 entry.securityLevel == SecurityLevel::KEYSTORE) {
1735 authList.push_back(AuthorizationSet(entry.authorizations));
1736 }
1737 }
1738 return authList;
1739 }
1740
ChainSignaturesAreValid(const vector<Certificate> & chain,bool strict_issuer_check)1741 AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1742 bool strict_issuer_check) {
1743 std::stringstream cert_data;
1744
1745 for (size_t i = 0; i < chain.size(); ++i) {
1746 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1747
1748 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1749 X509_Ptr signing_cert;
1750 if (i < chain.size() - 1) {
1751 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1752 } else {
1753 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1754 }
1755 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1756
1757 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1758 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1759
1760 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1761 return AssertionFailure()
1762 << "Verification of certificate " << i << " failed "
1763 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1764 << cert_data.str();
1765 }
1766
1767 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1768 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1769 if (cert_issuer != signer_subj && strict_issuer_check) {
1770 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1771 << " Signer subject is " << signer_subj
1772 << " Issuer subject is " << cert_issuer << endl
1773 << cert_data.str();
1774 }
1775 }
1776
1777 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1778 return AssertionSuccess();
1779 }
1780
parse_cert_blob(const vector<uint8_t> & blob)1781 X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1782 const uint8_t* p = blob.data();
1783 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1784 }
1785
make_name_from_str(const string & name)1786 vector<uint8_t> make_name_from_str(const string& name) {
1787 X509_NAME_Ptr x509_name(X509_NAME_new());
1788 EXPECT_TRUE(x509_name.get() != nullptr);
1789 if (!x509_name) return {};
1790
1791 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1792 "CN", //
1793 MBSTRING_ASC,
1794 reinterpret_cast<const uint8_t*>(name.c_str()),
1795 -1, // len
1796 -1, // loc
1797 0 /* set */));
1798
1799 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1800 EXPECT_GT(len, 0);
1801
1802 vector<uint8_t> retval(len);
1803 uint8_t* p = retval.data();
1804 i2d_X509_NAME(x509_name.get(), &p);
1805
1806 return retval;
1807 }
1808
1809 namespace {
1810
check_cose_key(const vector<uint8_t> & data,bool testMode)1811 void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1812 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1813 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1814
1815 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1816 if (testMode) {
1817 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1818 MatchesRegex("{\n"
1819 " 1 : 2,\n" // kty: EC2
1820 " 3 : -7,\n" // alg: ES256
1821 " -1 : 1,\n" // EC id: P256
1822 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1823 // sequence of 32 hexadecimal bytes, enclosed in braces and
1824 // separated by commas. In this case, some Ed25519 public key.
1825 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1826 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1827 " -70000 : null,\n" // test marker
1828 "}"));
1829 } else {
1830 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1831 MatchesRegex("{\n"
1832 " 1 : 2,\n" // kty: EC2
1833 " 3 : -7,\n" // alg: ES256
1834 " -1 : 1,\n" // EC id: P256
1835 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1836 // sequence of 32 hexadecimal bytes, enclosed in braces and
1837 // separated by commas. In this case, some Ed25519 public key.
1838 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1839 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1840 "}"));
1841 }
1842 }
1843
1844 } // namespace
1845
check_maced_pubkey(const MacedPublicKey & macedPubKey,bool testMode,vector<uint8_t> * payload_value)1846 void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1847 vector<uint8_t>* payload_value) {
1848 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1849 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1850
1851 ASSERT_NE(coseMac0->asArray(), nullptr);
1852 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1853
1854 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1855 ASSERT_NE(protParms, nullptr);
1856
1857 // Header label:value of 'alg': HMAC-256
1858 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1859
1860 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1861 ASSERT_NE(unprotParms, nullptr);
1862 ASSERT_EQ(unprotParms->size(), 0);
1863
1864 // The payload is a bstr holding an encoded COSE_Key
1865 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1866 ASSERT_NE(payload, nullptr);
1867 check_cose_key(payload->value(), testMode);
1868
1869 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1870 ASSERT_TRUE(coseMac0Tag);
1871 auto extractedTag = coseMac0Tag->value();
1872 EXPECT_EQ(extractedTag.size(), 32U);
1873
1874 // Compare with tag generated with kTestMacKey. Should only match in test mode
1875 auto macFunction = [](const cppcose::bytevec& input) {
1876 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1877 };
1878 auto testTag =
1879 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
1880 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1881
1882 if (testMode) {
1883 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
1884 } else {
1885 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
1886 }
1887 if (payload_value != nullptr) {
1888 *payload_value = payload->value();
1889 }
1890 }
1891
p256_pub_key(const vector<uint8_t> & coseKeyData,EVP_PKEY_Ptr * signingKey)1892 void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1893 // Extract x and y affine coordinates from the encoded Cose_Key.
1894 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1895 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1896 auto coseKey = parsedPayload->asMap();
1897 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1898 ASSERT_NE(xItem->asBstr(), nullptr);
1899 vector<uint8_t> x = xItem->asBstr()->value();
1900 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1901 ASSERT_NE(yItem->asBstr(), nullptr);
1902 vector<uint8_t> y = yItem->asBstr()->value();
1903
1904 // Concatenate: 0x04 (uncompressed form marker) | x | y
1905 vector<uint8_t> pubKeyData{0x04};
1906 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1907 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1908
1909 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1910 ASSERT_NE(ecKey, nullptr);
1911 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1912 ASSERT_NE(group, nullptr);
1913 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1914 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1915 ASSERT_NE(point, nullptr);
1916 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1917 nullptr),
1918 1);
1919 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1920
1921 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1922 ASSERT_NE(pubKey, nullptr);
1923 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1924 *signingKey = std::move(pubKey);
1925 }
1926
1927 // Check whether the given named feature is available.
check_feature(const std::string & name)1928 bool check_feature(const std::string& name) {
1929 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
1930 ::android::sp<::android::IBinder> binder(sm->getService(::android::String16("package_native")));
1931 if (binder == nullptr) {
1932 GTEST_LOG_(ERROR) << "getService package_native failed";
1933 return false;
1934 }
1935 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
1936 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
1937 if (packageMgr == nullptr) {
1938 GTEST_LOG_(ERROR) << "Cannot find package manager";
1939 return false;
1940 }
1941 bool hasFeature = false;
1942 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
1943 if (!status.isOk()) {
1944 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
1945 return false;
1946 }
1947 return hasFeature;
1948 }
1949
1950 } // namespace test
1951
1952 } // namespace aidl::android::hardware::security::keymint
1953