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