blob: ce6f67a84ada0c4b9373a0e052230eb731c58da1 [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
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>
Shawn Willden7f424372021-01-10 18:06:50 -070020#include <unordered_set>
Selene Huang31ab4042020-04-29 04:22:39 -070021#include <vector>
22
23#include <android-base/logging.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080024#include <android/binder_manager.h>
Shawn Willden7c130392020-12-21 09:58:22 -070025#include <cutils/properties.h>
26#include <openssl/mem.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027
Shawn Willden7c130392020-12-21 09:58:22 -070028#include <keymint_support/attestation_record.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000029#include <keymint_support/key_param_output.h>
30#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070031#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070032
Janis Danisevskis24c04702020-12-16 18:28:39 -080033namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070034
35using namespace std::literals::chrono_literals;
36using std::endl;
37using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070038using std::unique_ptr;
39using ::testing::AssertionFailure;
40using ::testing::AssertionResult;
41using ::testing::AssertionSuccess;
Selene Huang31ab4042020-04-29 04:22:39 -070042
43::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
44 if (set.size() == 0)
45 os << "(Empty)" << ::std::endl;
46 else {
47 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070048 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070049 }
50 return os;
51}
52
53namespace test {
54
Shawn Willden7f424372021-01-10 18:06:50 -070055namespace {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000056typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070057// Predicate for testing basic characteristics validity in generation or import.
58bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
59 const vector<KeyCharacteristics>& key_characteristics) {
60 if (key_characteristics.empty()) return false;
61
62 std::unordered_set<SecurityLevel> levels_seen;
63 for (auto& entry : key_characteristics) {
64 if (entry.authorizations.empty()) return false;
65
Qi Wubeefae42021-01-28 23:16:37 +080066 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
67 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
68
Shawn Willden7f424372021-01-10 18:06:50 -070069 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
70 levels_seen.insert(entry.securityLevel);
71
72 // Generally, we should only have one entry, at the same security level as the KM
73 // instance. There is an exception: StrongBox KM can have some authorizations that are
74 // enforced by the TEE.
75 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
76 (secLevel == SecurityLevel::STRONGBOX &&
77 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
78
79 if (!isExpectedSecurityLevel) return false;
80 }
81 return true;
82}
83
Shawn Willden7c130392020-12-21 09:58:22 -070084// Extract attestation record from cert. Returned object is still part of cert; don't free it
85// separately.
86ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
87 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
88 EXPECT_TRUE(!!oid.get());
89 if (!oid.get()) return nullptr;
90
91 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
92 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
93 if (location == -1) return nullptr;
94
95 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
96 EXPECT_TRUE(!!attest_rec_ext)
97 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
98 if (!attest_rec_ext) return nullptr;
99
100 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
101 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
102 return attest_rec;
103}
104
105bool avb_verification_enabled() {
106 char value[PROPERTY_VALUE_MAX];
107 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
108}
109
110char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
111 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
112
113// Attestations don't contain everything in key authorization lists, so we need to filter the key
114// lists to produce the lists that we expect to match the attestations.
115auto kTagsToFilter = {
116 Tag::BLOB_USAGE_REQUIREMENTS, //
117 Tag::CREATION_DATETIME, //
118 Tag::EC_CURVE,
119 Tag::HARDWARE_TYPE,
120 Tag::INCLUDE_UNIQUE_ID,
121};
122
123AuthorizationSet filtered_tags(const AuthorizationSet& set) {
124 AuthorizationSet filtered;
125 std::remove_copy_if(
126 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
127 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
128 kTagsToFilter.end();
129 });
130 return filtered;
131}
132
133string x509NameToStr(X509_NAME* name) {
134 char* s = X509_NAME_oneline(name, nullptr, 0);
135 string retval(s);
136 OPENSSL_free(s);
137 return retval;
138}
139
Shawn Willden7f424372021-01-10 18:06:50 -0700140} // namespace
141
Shawn Willden7c130392020-12-21 09:58:22 -0700142bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
143bool KeyMintAidlTestBase::dump_Attestations = false;
144
Janis Danisevskis24c04702020-12-16 18:28:39 -0800145ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700146 if (result.isOk()) return ErrorCode::OK;
147
Janis Danisevskis24c04702020-12-16 18:28:39 -0800148 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
149 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700150 }
151
152 return ErrorCode::UNKNOWN_ERROR;
153}
154
Janis Danisevskis24c04702020-12-16 18:28:39 -0800155void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700156 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800157 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700158
159 KeyMintHardwareInfo info;
160 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
161
162 securityLevel_ = info.securityLevel;
163 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
164 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
165
166 os_version_ = getOsVersion();
167 os_patch_level_ = getOsPatchlevel();
168}
169
170void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800171 if (AServiceManager_isDeclared(GetParam().c_str())) {
172 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
173 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
174 } else {
175 InitializeKeyMint(nullptr);
176 }
Selene Huang31ab4042020-04-29 04:22:39 -0700177}
178
179ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700180 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700181 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700182 vector<KeyCharacteristics>* key_characteristics,
183 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700184 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
185 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700186 << "Previous characteristics not deleted before generating key. Test bug.";
187
Shawn Willden7f424372021-01-10 18:06:50 -0700188 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700189 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700190 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700191 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
192 creationResult.keyCharacteristics);
193 EXPECT_GT(creationResult.keyBlob.size(), 0);
194 *key_blob = std::move(creationResult.keyBlob);
195 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700196 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700197
198 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
199 EXPECT_TRUE(algorithm);
200 if (algorithm &&
201 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700202 EXPECT_GE(cert_chain->size(), 1);
203 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
204 if (attest_key) {
205 EXPECT_EQ(cert_chain->size(), 1);
206 } else {
207 EXPECT_GT(cert_chain->size(), 1);
208 }
209 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700210 } else {
211 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700212 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700213 }
Selene Huang31ab4042020-04-29 04:22:39 -0700214 }
215
216 return GetReturnErrorCode(result);
217}
218
Shawn Willden7c130392020-12-21 09:58:22 -0700219ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
220 const optional<AttestationKey>& attest_key) {
221 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700222}
223
224ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
225 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700226 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700227 Status result;
228
Shawn Willden7f424372021-01-10 18:06:50 -0700229 cert_chain_.clear();
230 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700231 key_blob->clear();
232
Shawn Willden7f424372021-01-10 18:06:50 -0700233 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700234 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700235 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700236 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700237
238 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700239 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
240 creationResult.keyCharacteristics);
241 EXPECT_GT(creationResult.keyBlob.size(), 0);
242
243 *key_blob = std::move(creationResult.keyBlob);
244 *key_characteristics = std::move(creationResult.keyCharacteristics);
245 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700246
247 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
248 EXPECT_TRUE(algorithm);
249 if (algorithm &&
250 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
251 EXPECT_GE(cert_chain_.size(), 1);
252 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
253 } else {
254 // For symmetric keys there should be no certificates.
255 EXPECT_EQ(cert_chain_.size(), 0);
256 }
Selene Huang31ab4042020-04-29 04:22:39 -0700257 }
258
259 return GetReturnErrorCode(result);
260}
261
262ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
263 const string& key_material) {
264 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
265}
266
267ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
268 const AuthorizationSet& wrapping_key_desc,
269 string masking_key,
270 const AuthorizationSet& unwrapping_params) {
Selene Huang31ab4042020-04-29 04:22:39 -0700271 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
272
Shawn Willden7f424372021-01-10 18:06:50 -0700273 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700274
Shawn Willden7f424372021-01-10 18:06:50 -0700275 KeyCreationResult creationResult;
276 Status result = keymint_->importWrappedKey(
277 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
278 vector<uint8_t>(masking_key.begin(), masking_key.end()),
279 unwrapping_params.vector_data(), 0 /* passwordSid */, 0 /* biometricSid */,
280 &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700281
282 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700283 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
284 creationResult.keyCharacteristics);
285 EXPECT_GT(creationResult.keyBlob.size(), 0);
286
287 key_blob_ = std::move(creationResult.keyBlob);
288 key_characteristics_ = std::move(creationResult.keyCharacteristics);
289 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700290
291 AuthorizationSet allAuths;
292 for (auto& entry : key_characteristics_) {
293 allAuths.push_back(AuthorizationSet(entry.authorizations));
294 }
295 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
296 EXPECT_TRUE(algorithm);
297 if (algorithm &&
298 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
299 EXPECT_GE(cert_chain_.size(), 1);
300 } else {
301 // For symmetric keys there should be no certificates.
302 EXPECT_EQ(cert_chain_.size(), 0);
303 }
Selene Huang31ab4042020-04-29 04:22:39 -0700304 }
305
306 return GetReturnErrorCode(result);
307}
308
309ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
310 Status result = keymint_->deleteKey(*key_blob);
311 if (!keep_key_blob) {
312 *key_blob = vector<uint8_t>();
313 }
314
Janis Danisevskis24c04702020-12-16 18:28:39 -0800315 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700316 return GetReturnErrorCode(result);
317}
318
319ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
320 return DeleteKey(&key_blob_, keep_key_blob);
321}
322
323ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
324 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800325 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700326 return GetReturnErrorCode(result);
327}
328
329void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
330 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
331 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
332}
333
334void KeyMintAidlTestBase::CheckedDeleteKey() {
335 CheckedDeleteKey(&key_blob_);
336}
337
338ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
339 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800340 AuthorizationSet* out_params,
341 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700342 SCOPED_TRACE("Begin");
343 Status result;
344 BeginResult out;
345 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
346
347 if (result.isOk()) {
348 *out_params = out.params;
349 challenge_ = out.challenge;
350 op = out.operation;
351 }
352
353 return GetReturnErrorCode(result);
354}
355
356ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
357 const AuthorizationSet& in_params,
358 AuthorizationSet* out_params) {
359 SCOPED_TRACE("Begin");
360 Status result;
361 BeginResult out;
362
363 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
364
365 if (result.isOk()) {
366 *out_params = out.params;
367 challenge_ = out.challenge;
368 op_ = out.operation;
369 }
370
371 return GetReturnErrorCode(result);
372}
373
374ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
375 AuthorizationSet* out_params) {
376 SCOPED_TRACE("Begin");
377 EXPECT_EQ(nullptr, op_);
378 return Begin(purpose, key_blob_, in_params, out_params);
379}
380
381ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
382 SCOPED_TRACE("Begin");
383 AuthorizationSet out_params;
384 ErrorCode result = Begin(purpose, in_params, &out_params);
385 EXPECT_TRUE(out_params.empty());
386 return result;
387}
388
Shawn Willden92d79c02021-02-19 07:31:55 -0700389ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
390 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
391 {} /* hardwareAuthToken */,
392 {} /* verificationToken */));
393}
394
395ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700396 SCOPED_TRACE("Update");
397
398 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700399 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700400
Shawn Willden92d79c02021-02-19 07:31:55 -0700401 std::vector<uint8_t> o_put;
402 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700403
Shawn Willden92d79c02021-02-19 07:31:55 -0700404 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700405
406 return GetReturnErrorCode(result);
407}
408
Shawn Willden92d79c02021-02-19 07:31:55 -0700409ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700410 string* output) {
411 SCOPED_TRACE("Finish");
412 Status result;
413
414 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700415 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700416
417 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700418 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
419 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
420 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
Shawn Willden92d79c02021-02-19 07:31:55 -0700422 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700423
Shawn Willden92d79c02021-02-19 07:31:55 -0700424 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700425 return GetReturnErrorCode(result);
426}
427
Janis Danisevskis24c04702020-12-16 18:28:39 -0800428ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700429 SCOPED_TRACE("Abort");
430
431 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700432 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700433
434 Status retval = op->abort();
435 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800436 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700437}
438
439ErrorCode KeyMintAidlTestBase::Abort() {
440 SCOPED_TRACE("Abort");
441
442 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700443 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700444
445 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800446 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700447}
448
449void KeyMintAidlTestBase::AbortIfNeeded() {
450 SCOPED_TRACE("AbortIfNeeded");
451 if (op_) {
452 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800453 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700454 }
455}
456
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000457auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
458 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700459 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000460 AuthorizationSet begin_out_params;
461 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700462 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000463
464 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700465 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000466}
467
Selene Huang31ab4042020-04-29 04:22:39 -0700468string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
469 const string& message, const AuthorizationSet& in_params,
470 AuthorizationSet* out_params) {
471 SCOPED_TRACE("ProcessMessage");
472 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700473 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700474 EXPECT_EQ(ErrorCode::OK, result);
475 if (result != ErrorCode::OK) {
476 return "";
477 }
478
479 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700480 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700481 return output;
482}
483
484string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
485 const AuthorizationSet& params) {
486 SCOPED_TRACE("SignMessage");
487 AuthorizationSet out_params;
488 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
489 EXPECT_TRUE(out_params.empty());
490 return signature;
491}
492
493string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
494 SCOPED_TRACE("SignMessage");
495 return SignMessage(key_blob_, message, params);
496}
497
498string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
499 SCOPED_TRACE("MacMessage");
500 return SignMessage(
501 key_blob_, message,
502 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
503}
504
505void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
506 Digest digest, const string& expected_mac) {
507 SCOPED_TRACE("CheckHmacTestVector");
508 ASSERT_EQ(ErrorCode::OK,
509 ImportKey(AuthorizationSetBuilder()
510 .Authorization(TAG_NO_AUTH_REQUIRED)
511 .HmacKey(key.size() * 8)
512 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
513 .Digest(digest),
514 KeyFormat::RAW, key));
515 string signature = MacMessage(message, digest, expected_mac.size() * 8);
516 EXPECT_EQ(expected_mac, signature)
517 << "Test vector didn't match for key of size " << key.size() << " message of size "
518 << message.size() << " and digest " << digest;
519 CheckedDeleteKey();
520}
521
522void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
523 const string& message,
524 const string& expected_ciphertext) {
525 SCOPED_TRACE("CheckAesCtrTestVector");
526 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
527 .Authorization(TAG_NO_AUTH_REQUIRED)
528 .AesEncryptionKey(key.size() * 8)
529 .BlockMode(BlockMode::CTR)
530 .Authorization(TAG_CALLER_NONCE)
531 .Padding(PaddingMode::NONE),
532 KeyFormat::RAW, key));
533
534 auto params = AuthorizationSetBuilder()
535 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
536 .BlockMode(BlockMode::CTR)
537 .Padding(PaddingMode::NONE);
538 AuthorizationSet out_params;
539 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
540 EXPECT_EQ(expected_ciphertext, ciphertext);
541}
542
543void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
544 PaddingMode padding_mode, const string& key,
545 const string& iv, const string& input,
546 const string& expected_output) {
547 auto authset = AuthorizationSetBuilder()
548 .TripleDesEncryptionKey(key.size() * 7)
549 .BlockMode(block_mode)
550 .Authorization(TAG_NO_AUTH_REQUIRED)
551 .Padding(padding_mode);
552 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
553 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
554 ASSERT_GT(key_blob_.size(), 0U);
555
556 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
557 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
558 AuthorizationSet output_params;
559 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
560 EXPECT_EQ(expected_output, output);
561}
562
563void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
564 const string& signature, const AuthorizationSet& params) {
565 SCOPED_TRACE("VerifyMessage");
566 AuthorizationSet begin_out_params;
567 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
568
569 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700570 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700571 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700572 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700573}
574
575void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
576 const AuthorizationSet& params) {
577 SCOPED_TRACE("VerifyMessage");
578 VerifyMessage(key_blob_, message, signature, params);
579}
580
581string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
582 const AuthorizationSet& in_params,
583 AuthorizationSet* out_params) {
584 SCOPED_TRACE("EncryptMessage");
585 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
586}
587
588string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
589 AuthorizationSet* out_params) {
590 SCOPED_TRACE("EncryptMessage");
591 return EncryptMessage(key_blob_, message, params, out_params);
592}
593
594string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
595 SCOPED_TRACE("EncryptMessage");
596 AuthorizationSet out_params;
597 string ciphertext = EncryptMessage(message, params, &out_params);
598 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
599 return ciphertext;
600}
601
602string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
603 PaddingMode padding) {
604 SCOPED_TRACE("EncryptMessage");
605 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
606 AuthorizationSet out_params;
607 string ciphertext = EncryptMessage(message, params, &out_params);
608 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
609 return ciphertext;
610}
611
612string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
613 PaddingMode padding, vector<uint8_t>* iv_out) {
614 SCOPED_TRACE("EncryptMessage");
615 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
616 AuthorizationSet out_params;
617 string ciphertext = EncryptMessage(message, params, &out_params);
618 EXPECT_EQ(1U, out_params.size());
619 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800620 EXPECT_TRUE(ivVal);
621 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700622 return ciphertext;
623}
624
625string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
626 PaddingMode padding, const vector<uint8_t>& iv_in) {
627 SCOPED_TRACE("EncryptMessage");
628 auto params = AuthorizationSetBuilder()
629 .BlockMode(block_mode)
630 .Padding(padding)
631 .Authorization(TAG_NONCE, iv_in);
632 AuthorizationSet out_params;
633 string ciphertext = EncryptMessage(message, params, &out_params);
634 return ciphertext;
635}
636
637string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
638 PaddingMode padding, uint8_t mac_length_bits,
639 const vector<uint8_t>& iv_in) {
640 SCOPED_TRACE("EncryptMessage");
641 auto params = AuthorizationSetBuilder()
642 .BlockMode(block_mode)
643 .Padding(padding)
644 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
645 .Authorization(TAG_NONCE, iv_in);
646 AuthorizationSet out_params;
647 string ciphertext = EncryptMessage(message, params, &out_params);
648 return ciphertext;
649}
650
651string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
652 const string& ciphertext,
653 const AuthorizationSet& params) {
654 SCOPED_TRACE("DecryptMessage");
655 AuthorizationSet out_params;
656 string plaintext =
657 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
658 EXPECT_TRUE(out_params.empty());
659 return plaintext;
660}
661
662string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
663 const AuthorizationSet& params) {
664 SCOPED_TRACE("DecryptMessage");
665 return DecryptMessage(key_blob_, ciphertext, params);
666}
667
668string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
669 PaddingMode padding_mode, const vector<uint8_t>& iv) {
670 SCOPED_TRACE("DecryptMessage");
671 auto params = AuthorizationSetBuilder()
672 .BlockMode(block_mode)
673 .Padding(padding_mode)
674 .Authorization(TAG_NONCE, iv);
675 return DecryptMessage(key_blob_, ciphertext, params);
676}
677
678std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
679 const vector<uint8_t>& key_blob) {
680 std::pair<ErrorCode, vector<uint8_t>> retval;
681 vector<uint8_t> outKeyBlob;
682 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
683 ErrorCode errorcode = GetReturnErrorCode(result);
684 retval = std::tie(errorcode, outKeyBlob);
685
686 return retval;
687}
688vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
689 switch (algorithm) {
690 case Algorithm::RSA:
691 switch (SecLevel()) {
692 case SecurityLevel::SOFTWARE:
693 case SecurityLevel::TRUSTED_ENVIRONMENT:
694 return {2048, 3072, 4096};
695 case SecurityLevel::STRONGBOX:
696 return {2048};
697 default:
698 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
699 break;
700 }
701 break;
702 case Algorithm::EC:
703 switch (SecLevel()) {
704 case SecurityLevel::SOFTWARE:
705 case SecurityLevel::TRUSTED_ENVIRONMENT:
706 return {224, 256, 384, 521};
707 case SecurityLevel::STRONGBOX:
708 return {256};
709 default:
710 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
711 break;
712 }
713 break;
714 case Algorithm::AES:
715 return {128, 256};
716 case Algorithm::TRIPLE_DES:
717 return {168};
718 case Algorithm::HMAC: {
719 vector<uint32_t> retval((512 - 64) / 8 + 1);
720 uint32_t size = 64 - 8;
721 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
722 return retval;
723 }
724 default:
725 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
726 return {};
727 }
728 ADD_FAILURE() << "Should be impossible to get here";
729 return {};
730}
731
732vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
733 if (SecLevel() == SecurityLevel::STRONGBOX) {
734 switch (algorithm) {
735 case Algorithm::RSA:
736 return {3072, 4096};
737 case Algorithm::EC:
738 return {224, 384, 521};
739 case Algorithm::AES:
740 return {192};
741 default:
742 return {};
743 }
744 }
745 return {};
746}
747
748vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
749 if (securityLevel_ == SecurityLevel::STRONGBOX) {
750 return {EcCurve::P_256};
751 } else {
752 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
753 }
754}
755
756vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
757 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
758 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
759 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
760}
761
762vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
763 switch (SecLevel()) {
764 case SecurityLevel::SOFTWARE:
765 case SecurityLevel::TRUSTED_ENVIRONMENT:
766 if (withNone) {
767 if (withMD5)
768 return {Digest::NONE, Digest::MD5, Digest::SHA1,
769 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
770 Digest::SHA_2_512};
771 else
772 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
773 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
774 } else {
775 if (withMD5)
776 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
777 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
778 else
779 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
780 Digest::SHA_2_512};
781 }
782 break;
783 case SecurityLevel::STRONGBOX:
784 if (withNone)
785 return {Digest::NONE, Digest::SHA_2_256};
786 else
787 return {Digest::SHA_2_256};
788 break;
789 default:
790 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
791 break;
792 }
793 ADD_FAILURE() << "Should be impossible to get here";
794 return {};
795}
796
Shawn Willden7f424372021-01-10 18:06:50 -0700797static const vector<KeyParameter> kEmptyAuthList{};
798
799const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
800 const vector<KeyCharacteristics>& key_characteristics) {
801 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
802 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
803 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
804}
805
Qi Wubeefae42021-01-28 23:16:37 +0800806const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
807 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
808 auto found = std::find_if(
809 key_characteristics.begin(), key_characteristics.end(),
810 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700811 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
812}
813
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000814ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700815 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000816 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
817 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
818 return result;
819}
820
821ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700822 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000823 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
824 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
825 return result;
826}
827
828ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
829 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -0700830 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000831 rsaKeyBlob, KeyPurpose::SIGN, message,
832 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
833 return result;
834}
835
836ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700837 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
838 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000839 return result;
840}
841
Shawn Willden7c130392020-12-21 09:58:22 -0700842bool verify_attestation_record(const string& challenge, //
843 const string& app_id, //
844 AuthorizationSet expected_sw_enforced, //
845 AuthorizationSet expected_hw_enforced, //
846 SecurityLevel security_level,
847 const vector<uint8_t>& attestation_cert) {
848 X509_Ptr cert(parse_cert_blob(attestation_cert));
849 EXPECT_TRUE(!!cert.get());
850 if (!cert.get()) return false;
851
852 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
853 EXPECT_TRUE(!!attest_rec);
854 if (!attest_rec) return false;
855
856 AuthorizationSet att_sw_enforced;
857 AuthorizationSet att_hw_enforced;
858 uint32_t att_attestation_version;
859 uint32_t att_keymaster_version;
860 SecurityLevel att_attestation_security_level;
861 SecurityLevel att_keymaster_security_level;
862 vector<uint8_t> att_challenge;
863 vector<uint8_t> att_unique_id;
864 vector<uint8_t> att_app_id;
865
866 auto error = parse_attestation_record(attest_rec->data, //
867 attest_rec->length, //
868 &att_attestation_version, //
869 &att_attestation_security_level, //
870 &att_keymaster_version, //
871 &att_keymaster_security_level, //
872 &att_challenge, //
873 &att_sw_enforced, //
874 &att_hw_enforced, //
875 &att_unique_id);
876 EXPECT_EQ(ErrorCode::OK, error);
877 if (error != ErrorCode::OK) return false;
878
879 EXPECT_GE(att_attestation_version, 3U);
880
881 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID,
882 vector<uint8_t>(app_id.begin(), app_id.end()));
883
884 EXPECT_GE(att_keymaster_version, 4U);
885 EXPECT_EQ(security_level, att_keymaster_security_level);
886 EXPECT_EQ(security_level, att_attestation_security_level);
887
888 EXPECT_EQ(challenge.length(), att_challenge.size());
889 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
890
891 char property_value[PROPERTY_VALUE_MAX] = {};
892 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
893 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
894 // for the BOOT_PATCH_LEVEL.
895 if (avb_verification_enabled()) {
896 for (int i = 0; i < att_hw_enforced.size(); i++) {
897 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
898 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
899 std::string date =
900 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::dateTime>());
901 // strptime seems to require delimiters, but the tag value will
902 // be YYYYMMDD
903 date.insert(6, "-");
904 date.insert(4, "-");
905 EXPECT_EQ(date.size(), 10);
906 struct tm time;
907 strptime(date.c_str(), "%Y-%m-%d", &time);
908
909 // Day of the month (0-31)
910 EXPECT_GE(time.tm_mday, 0);
911 EXPECT_LT(time.tm_mday, 32);
912 // Months since Jan (0-11)
913 EXPECT_GE(time.tm_mon, 0);
914 EXPECT_LT(time.tm_mon, 12);
915 // Years since 1900
916 EXPECT_GT(time.tm_year, 110);
917 EXPECT_LT(time.tm_year, 200);
918 }
919 }
920 }
921
922 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
923 // indicates true. A provided boolean tag that can be pulled back out of the certificate
924 // indicates correct encoding. No need to check if it's in both lists, since the
925 // AuthorizationSet compare below will handle mismatches of tags.
926 if (security_level == SecurityLevel::SOFTWARE) {
927 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
928 } else {
929 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
930 }
931
932 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
933 // the authorization list during key generation) isn't being attested to in the certificate.
934 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
935 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
936 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
937 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
938
939 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
940 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
941 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
942 att_hw_enforced.Contains(TAG_KEY_SIZE));
943 }
944
945 // Test root of trust elements
946 vector<uint8_t> verified_boot_key;
947 VerifiedBoot verified_boot_state;
948 bool device_locked;
949 vector<uint8_t> verified_boot_hash;
950 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
951 &verified_boot_state, &device_locked, &verified_boot_hash);
952 EXPECT_EQ(ErrorCode::OK, error);
953
954 if (avb_verification_enabled()) {
955 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
956 string prop_string(property_value);
957 EXPECT_EQ(prop_string.size(), 64);
958 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
959
960 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
961 if (!strcmp(property_value, "unlocked")) {
962 EXPECT_FALSE(device_locked);
963 } else {
964 EXPECT_TRUE(device_locked);
965 }
966
967 // Check that the device is locked if not debuggable, e.g., user build
968 // images in CTS. For VTS, debuggable images are used to allow adb root
969 // and the device is unlocked.
970 if (!property_get_bool("ro.debuggable", false)) {
971 EXPECT_TRUE(device_locked);
972 } else {
973 EXPECT_FALSE(device_locked);
974 }
975 }
976
977 // Verified boot key should be all 0's if the boot state is not verified or self signed
978 std::string empty_boot_key(32, '\0');
979 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
980 verified_boot_key.size());
981 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
982 if (!strcmp(property_value, "green")) {
983 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
984 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
985 verified_boot_key.size()));
986 } else if (!strcmp(property_value, "yellow")) {
987 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
988 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
989 verified_boot_key.size()));
990 } else if (!strcmp(property_value, "orange")) {
991 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
992 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
993 verified_boot_key.size()));
994 } else if (!strcmp(property_value, "red")) {
995 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
996 } else {
997 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
998 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
999 verified_boot_key.size()));
1000 }
1001
1002 att_sw_enforced.Sort();
1003 expected_sw_enforced.Sort();
1004 auto a = filtered_tags(expected_sw_enforced);
1005 auto b = filtered_tags(att_sw_enforced);
1006 EXPECT_EQ(a, b);
1007
1008 att_hw_enforced.Sort();
1009 expected_hw_enforced.Sort();
1010 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1011
1012 return true;
1013}
1014
1015string bin2hex(const vector<uint8_t>& data) {
1016 string retval;
1017 retval.reserve(data.size() * 2 + 1);
1018 for (uint8_t byte : data) {
1019 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1020 retval.push_back(nibble2hex[0x0F & byte]);
1021 }
1022 return retval;
1023}
1024
David Drysdalef0d516d2021-03-22 07:51:43 +00001025AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1026 AuthorizationSet authList;
1027 for (auto& entry : key_characteristics) {
1028 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1029 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1030 authList.push_back(AuthorizationSet(entry.authorizations));
1031 }
1032 }
1033 return authList;
1034}
1035
1036AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1037 AuthorizationSet authList;
1038 for (auto& entry : key_characteristics) {
1039 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1040 entry.securityLevel == SecurityLevel::KEYSTORE) {
1041 authList.push_back(AuthorizationSet(entry.authorizations));
1042 }
1043 }
1044 return authList;
1045}
1046
Shawn Willden7c130392020-12-21 09:58:22 -07001047AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1048 std::stringstream cert_data;
1049
1050 for (size_t i = 0; i < chain.size(); ++i) {
1051 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1052
1053 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1054 X509_Ptr signing_cert;
1055 if (i < chain.size() - 1) {
1056 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1057 } else {
1058 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1059 }
1060 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1061
1062 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1063 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1064
1065 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1066 return AssertionFailure()
1067 << "Verification of certificate " << i << " failed "
1068 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1069 << cert_data.str();
1070 }
1071
1072 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1073 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1074 if (cert_issuer != signer_subj) {
1075 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n" << cert_data.str();
1076 }
1077
1078 if (i == 0) {
1079 string cert_sub = x509NameToStr(X509_get_subject_name(key_cert.get()));
1080 if ("/CN=Android Keystore Key" != cert_sub) {
1081 return AssertionFailure()
1082 << "Leaf cert has wrong subject, should be CN=Android Keystore Key, was "
1083 << cert_sub << '\n'
1084 << cert_data.str();
1085 }
1086 }
1087 }
1088
1089 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1090 return AssertionSuccess();
1091}
1092
1093X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1094 const uint8_t* p = blob.data();
1095 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1096}
1097
David Drysdalef0d516d2021-03-22 07:51:43 +00001098vector<uint8_t> make_name_from_str(const string& name) {
1099 X509_NAME_Ptr x509_name(X509_NAME_new());
1100 EXPECT_TRUE(x509_name.get() != nullptr);
1101 if (!x509_name) return {};
1102
1103 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1104 "CN", //
1105 MBSTRING_ASC,
1106 reinterpret_cast<const uint8_t*>(name.c_str()),
1107 -1, // len
1108 -1, // loc
1109 0 /* set */));
1110
1111 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1112 EXPECT_GT(len, 0);
1113
1114 vector<uint8_t> retval(len);
1115 uint8_t* p = retval.data();
1116 i2d_X509_NAME(x509_name.get(), &p);
1117
1118 return retval;
1119}
1120
Selene Huang31ab4042020-04-29 04:22:39 -07001121} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001122
Janis Danisevskis24c04702020-12-16 18:28:39 -08001123} // namespace aidl::android::hardware::security::keymint