blob: 3e87b6b2da90273cf1abddacfbbf7b00aa5ece7e [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
Qi Wubeefae42021-01-28 23:16:37 +0800814AuthorizationSet KeyMintAidlTestBase::HwEnforcedAuthorizations(
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700815 const vector<KeyCharacteristics>& key_characteristics) {
Qi Wubeefae42021-01-28 23:16:37 +0800816 AuthorizationSet authList;
817 for (auto& entry : key_characteristics) {
818 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
819 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
820 authList.push_back(AuthorizationSet(entry.authorizations));
821 }
822 }
823 return authList;
824}
825
826AuthorizationSet KeyMintAidlTestBase::SwEnforcedAuthorizations(
827 const vector<KeyCharacteristics>& key_characteristics) {
828 AuthorizationSet authList;
829 for (auto& entry : key_characteristics) {
830 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
831 entry.securityLevel == SecurityLevel::KEYSTORE) {
832 authList.push_back(AuthorizationSet(entry.authorizations));
833 }
834 }
835 return authList;
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700836}
837
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000838ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700839 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000840 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
841 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
842 return result;
843}
844
845ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700846 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000847 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
848 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
849 return result;
850}
851
852ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
853 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -0700854 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000855 rsaKeyBlob, KeyPurpose::SIGN, message,
856 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
857 return result;
858}
859
860ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700861 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
862 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000863 return result;
864}
865
Shawn Willden7c130392020-12-21 09:58:22 -0700866bool verify_attestation_record(const string& challenge, //
867 const string& app_id, //
868 AuthorizationSet expected_sw_enforced, //
869 AuthorizationSet expected_hw_enforced, //
870 SecurityLevel security_level,
871 const vector<uint8_t>& attestation_cert) {
872 X509_Ptr cert(parse_cert_blob(attestation_cert));
873 EXPECT_TRUE(!!cert.get());
874 if (!cert.get()) return false;
875
876 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
877 EXPECT_TRUE(!!attest_rec);
878 if (!attest_rec) return false;
879
880 AuthorizationSet att_sw_enforced;
881 AuthorizationSet att_hw_enforced;
882 uint32_t att_attestation_version;
883 uint32_t att_keymaster_version;
884 SecurityLevel att_attestation_security_level;
885 SecurityLevel att_keymaster_security_level;
886 vector<uint8_t> att_challenge;
887 vector<uint8_t> att_unique_id;
888 vector<uint8_t> att_app_id;
889
890 auto error = parse_attestation_record(attest_rec->data, //
891 attest_rec->length, //
892 &att_attestation_version, //
893 &att_attestation_security_level, //
894 &att_keymaster_version, //
895 &att_keymaster_security_level, //
896 &att_challenge, //
897 &att_sw_enforced, //
898 &att_hw_enforced, //
899 &att_unique_id);
900 EXPECT_EQ(ErrorCode::OK, error);
901 if (error != ErrorCode::OK) return false;
902
903 EXPECT_GE(att_attestation_version, 3U);
904
905 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID,
906 vector<uint8_t>(app_id.begin(), app_id.end()));
907
908 EXPECT_GE(att_keymaster_version, 4U);
909 EXPECT_EQ(security_level, att_keymaster_security_level);
910 EXPECT_EQ(security_level, att_attestation_security_level);
911
912 EXPECT_EQ(challenge.length(), att_challenge.size());
913 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
914
915 char property_value[PROPERTY_VALUE_MAX] = {};
916 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
917 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
918 // for the BOOT_PATCH_LEVEL.
919 if (avb_verification_enabled()) {
920 for (int i = 0; i < att_hw_enforced.size(); i++) {
921 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
922 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
923 std::string date =
924 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::dateTime>());
925 // strptime seems to require delimiters, but the tag value will
926 // be YYYYMMDD
927 date.insert(6, "-");
928 date.insert(4, "-");
929 EXPECT_EQ(date.size(), 10);
930 struct tm time;
931 strptime(date.c_str(), "%Y-%m-%d", &time);
932
933 // Day of the month (0-31)
934 EXPECT_GE(time.tm_mday, 0);
935 EXPECT_LT(time.tm_mday, 32);
936 // Months since Jan (0-11)
937 EXPECT_GE(time.tm_mon, 0);
938 EXPECT_LT(time.tm_mon, 12);
939 // Years since 1900
940 EXPECT_GT(time.tm_year, 110);
941 EXPECT_LT(time.tm_year, 200);
942 }
943 }
944 }
945
946 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
947 // indicates true. A provided boolean tag that can be pulled back out of the certificate
948 // indicates correct encoding. No need to check if it's in both lists, since the
949 // AuthorizationSet compare below will handle mismatches of tags.
950 if (security_level == SecurityLevel::SOFTWARE) {
951 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
952 } else {
953 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
954 }
955
956 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
957 // the authorization list during key generation) isn't being attested to in the certificate.
958 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
959 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
960 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
961 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
962
963 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
964 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
965 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
966 att_hw_enforced.Contains(TAG_KEY_SIZE));
967 }
968
969 // Test root of trust elements
970 vector<uint8_t> verified_boot_key;
971 VerifiedBoot verified_boot_state;
972 bool device_locked;
973 vector<uint8_t> verified_boot_hash;
974 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
975 &verified_boot_state, &device_locked, &verified_boot_hash);
976 EXPECT_EQ(ErrorCode::OK, error);
977
978 if (avb_verification_enabled()) {
979 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
980 string prop_string(property_value);
981 EXPECT_EQ(prop_string.size(), 64);
982 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
983
984 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
985 if (!strcmp(property_value, "unlocked")) {
986 EXPECT_FALSE(device_locked);
987 } else {
988 EXPECT_TRUE(device_locked);
989 }
990
991 // Check that the device is locked if not debuggable, e.g., user build
992 // images in CTS. For VTS, debuggable images are used to allow adb root
993 // and the device is unlocked.
994 if (!property_get_bool("ro.debuggable", false)) {
995 EXPECT_TRUE(device_locked);
996 } else {
997 EXPECT_FALSE(device_locked);
998 }
999 }
1000
1001 // Verified boot key should be all 0's if the boot state is not verified or self signed
1002 std::string empty_boot_key(32, '\0');
1003 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1004 verified_boot_key.size());
1005 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1006 if (!strcmp(property_value, "green")) {
1007 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1008 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1009 verified_boot_key.size()));
1010 } else if (!strcmp(property_value, "yellow")) {
1011 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1012 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1013 verified_boot_key.size()));
1014 } else if (!strcmp(property_value, "orange")) {
1015 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1016 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1017 verified_boot_key.size()));
1018 } else if (!strcmp(property_value, "red")) {
1019 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1020 } else {
1021 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1022 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1023 verified_boot_key.size()));
1024 }
1025
1026 att_sw_enforced.Sort();
1027 expected_sw_enforced.Sort();
1028 auto a = filtered_tags(expected_sw_enforced);
1029 auto b = filtered_tags(att_sw_enforced);
1030 EXPECT_EQ(a, b);
1031
1032 att_hw_enforced.Sort();
1033 expected_hw_enforced.Sort();
1034 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1035
1036 return true;
1037}
1038
1039string bin2hex(const vector<uint8_t>& data) {
1040 string retval;
1041 retval.reserve(data.size() * 2 + 1);
1042 for (uint8_t byte : data) {
1043 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1044 retval.push_back(nibble2hex[0x0F & byte]);
1045 }
1046 return retval;
1047}
1048
1049AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1050 std::stringstream cert_data;
1051
1052 for (size_t i = 0; i < chain.size(); ++i) {
1053 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1054
1055 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1056 X509_Ptr signing_cert;
1057 if (i < chain.size() - 1) {
1058 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1059 } else {
1060 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1061 }
1062 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1063
1064 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1065 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1066
1067 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1068 return AssertionFailure()
1069 << "Verification of certificate " << i << " failed "
1070 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1071 << cert_data.str();
1072 }
1073
1074 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1075 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1076 if (cert_issuer != signer_subj) {
1077 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n" << cert_data.str();
1078 }
1079
1080 if (i == 0) {
1081 string cert_sub = x509NameToStr(X509_get_subject_name(key_cert.get()));
1082 if ("/CN=Android Keystore Key" != cert_sub) {
1083 return AssertionFailure()
1084 << "Leaf cert has wrong subject, should be CN=Android Keystore Key, was "
1085 << cert_sub << '\n'
1086 << cert_data.str();
1087 }
1088 }
1089 }
1090
1091 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1092 return AssertionSuccess();
1093}
1094
1095X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1096 const uint8_t* p = blob.data();
1097 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1098}
1099
Selene Huang31ab4042020-04-29 04:22:39 -07001100} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001101
Janis Danisevskis24c04702020-12-16 18:28:39 -08001102} // namespace aidl::android::hardware::security::keymint