blob: ce23f7088d71a770c9469b18f32de56fb4012d02 [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>
David Drysdale4dc01072021-04-01 12:17:35 +010025#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070026#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010027#include <gmock/gmock.h>
Shawn Willden7c130392020-12-21 09:58:22 -070028#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010029#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
Max Bires9704ff62021-04-07 11:12:01 -070031#include <keymaster/cppcose/cppcose.h>
Shawn Willden7c130392020-12-21 09:58:22 -070032#include <keymint_support/attestation_record.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000033#include <keymint_support/key_param_output.h>
34#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070035#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Janis Danisevskis24c04702020-12-16 18:28:39 -080037namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070038
David Drysdale4dc01072021-04-01 12:17:35 +010039using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070040using namespace std::literals::chrono_literals;
41using std::endl;
42using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070043using std::unique_ptr;
44using ::testing::AssertionFailure;
45using ::testing::AssertionResult;
46using ::testing::AssertionSuccess;
David Drysdale4dc01072021-04-01 12:17:35 +010047using ::testing::MatchesRegex;
Selene Huang31ab4042020-04-29 04:22:39 -070048
49::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
50 if (set.size() == 0)
51 os << "(Empty)" << ::std::endl;
52 else {
53 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070054 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070055 }
56 return os;
57}
58
59namespace test {
60
Shawn Willden7f424372021-01-10 18:06:50 -070061namespace {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000062typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070063// Predicate for testing basic characteristics validity in generation or import.
64bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
65 const vector<KeyCharacteristics>& key_characteristics) {
66 if (key_characteristics.empty()) return false;
67
68 std::unordered_set<SecurityLevel> levels_seen;
69 for (auto& entry : key_characteristics) {
70 if (entry.authorizations.empty()) return false;
71
Qi Wubeefae42021-01-28 23:16:37 +080072 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
73 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
74
Shawn Willden7f424372021-01-10 18:06:50 -070075 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
76 levels_seen.insert(entry.securityLevel);
77
78 // Generally, we should only have one entry, at the same security level as the KM
79 // instance. There is an exception: StrongBox KM can have some authorizations that are
80 // enforced by the TEE.
81 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
82 (secLevel == SecurityLevel::STRONGBOX &&
83 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
84
85 if (!isExpectedSecurityLevel) return false;
86 }
87 return true;
88}
89
Shawn Willden7c130392020-12-21 09:58:22 -070090// Extract attestation record from cert. Returned object is still part of cert; don't free it
91// separately.
92ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
93 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
94 EXPECT_TRUE(!!oid.get());
95 if (!oid.get()) return nullptr;
96
97 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
98 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
99 if (location == -1) return nullptr;
100
101 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
102 EXPECT_TRUE(!!attest_rec_ext)
103 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
104 if (!attest_rec_ext) return nullptr;
105
106 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
107 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
108 return attest_rec;
109}
110
111bool avb_verification_enabled() {
112 char value[PROPERTY_VALUE_MAX];
113 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
114}
115
116char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
117 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
118
119// Attestations don't contain everything in key authorization lists, so we need to filter the key
120// lists to produce the lists that we expect to match the attestations.
121auto kTagsToFilter = {
122 Tag::BLOB_USAGE_REQUIREMENTS, //
123 Tag::CREATION_DATETIME, //
124 Tag::EC_CURVE,
125 Tag::HARDWARE_TYPE,
126 Tag::INCLUDE_UNIQUE_ID,
127};
128
129AuthorizationSet filtered_tags(const AuthorizationSet& set) {
130 AuthorizationSet filtered;
131 std::remove_copy_if(
132 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
133 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
134 kTagsToFilter.end();
135 });
136 return filtered;
137}
138
139string x509NameToStr(X509_NAME* name) {
140 char* s = X509_NAME_oneline(name, nullptr, 0);
141 string retval(s);
142 OPENSSL_free(s);
143 return retval;
144}
145
Shawn Willden7f424372021-01-10 18:06:50 -0700146} // namespace
147
Shawn Willden7c130392020-12-21 09:58:22 -0700148bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
149bool KeyMintAidlTestBase::dump_Attestations = false;
150
Janis Danisevskis24c04702020-12-16 18:28:39 -0800151ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700152 if (result.isOk()) return ErrorCode::OK;
153
Janis Danisevskis24c04702020-12-16 18:28:39 -0800154 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
155 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700156 }
157
158 return ErrorCode::UNKNOWN_ERROR;
159}
160
Janis Danisevskis24c04702020-12-16 18:28:39 -0800161void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700162 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800163 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700164
165 KeyMintHardwareInfo info;
166 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
167
168 securityLevel_ = info.securityLevel;
169 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
170 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
171
172 os_version_ = getOsVersion();
173 os_patch_level_ = getOsPatchlevel();
174}
175
176void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800177 if (AServiceManager_isDeclared(GetParam().c_str())) {
178 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
179 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
180 } else {
181 InitializeKeyMint(nullptr);
182 }
Selene Huang31ab4042020-04-29 04:22:39 -0700183}
184
185ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700186 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700187 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700188 vector<KeyCharacteristics>* key_characteristics,
189 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700190 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
191 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700192 << "Previous characteristics not deleted before generating key. Test bug.";
193
Shawn Willden7f424372021-01-10 18:06:50 -0700194 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700195 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700196 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700197 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
198 creationResult.keyCharacteristics);
199 EXPECT_GT(creationResult.keyBlob.size(), 0);
200 *key_blob = std::move(creationResult.keyBlob);
201 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700202 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700203
204 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
205 EXPECT_TRUE(algorithm);
206 if (algorithm &&
207 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700208 EXPECT_GE(cert_chain->size(), 1);
209 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
210 if (attest_key) {
211 EXPECT_EQ(cert_chain->size(), 1);
212 } else {
213 EXPECT_GT(cert_chain->size(), 1);
214 }
215 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700216 } else {
217 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700218 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700219 }
Selene Huang31ab4042020-04-29 04:22:39 -0700220 }
221
222 return GetReturnErrorCode(result);
223}
224
Shawn Willden7c130392020-12-21 09:58:22 -0700225ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
226 const optional<AttestationKey>& attest_key) {
227 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700228}
229
230ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
231 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700232 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700233 Status result;
234
Shawn Willden7f424372021-01-10 18:06:50 -0700235 cert_chain_.clear();
236 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700237 key_blob->clear();
238
Shawn Willden7f424372021-01-10 18:06:50 -0700239 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700240 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700241 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700242 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700243
244 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700245 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
246 creationResult.keyCharacteristics);
247 EXPECT_GT(creationResult.keyBlob.size(), 0);
248
249 *key_blob = std::move(creationResult.keyBlob);
250 *key_characteristics = std::move(creationResult.keyCharacteristics);
251 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700252
253 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
254 EXPECT_TRUE(algorithm);
255 if (algorithm &&
256 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
257 EXPECT_GE(cert_chain_.size(), 1);
258 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
259 } else {
260 // For symmetric keys there should be no certificates.
261 EXPECT_EQ(cert_chain_.size(), 0);
262 }
Selene Huang31ab4042020-04-29 04:22:39 -0700263 }
264
265 return GetReturnErrorCode(result);
266}
267
268ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
269 const string& key_material) {
270 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
271}
272
273ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
274 const AuthorizationSet& wrapping_key_desc,
275 string masking_key,
276 const AuthorizationSet& unwrapping_params) {
Selene Huang31ab4042020-04-29 04:22:39 -0700277 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
278
Shawn Willden7f424372021-01-10 18:06:50 -0700279 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700280
Shawn Willden7f424372021-01-10 18:06:50 -0700281 KeyCreationResult creationResult;
282 Status result = keymint_->importWrappedKey(
283 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
284 vector<uint8_t>(masking_key.begin(), masking_key.end()),
285 unwrapping_params.vector_data(), 0 /* passwordSid */, 0 /* biometricSid */,
286 &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700287
288 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700289 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
290 creationResult.keyCharacteristics);
291 EXPECT_GT(creationResult.keyBlob.size(), 0);
292
293 key_blob_ = std::move(creationResult.keyBlob);
294 key_characteristics_ = std::move(creationResult.keyCharacteristics);
295 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700296
297 AuthorizationSet allAuths;
298 for (auto& entry : key_characteristics_) {
299 allAuths.push_back(AuthorizationSet(entry.authorizations));
300 }
301 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
302 EXPECT_TRUE(algorithm);
303 if (algorithm &&
304 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
305 EXPECT_GE(cert_chain_.size(), 1);
306 } else {
307 // For symmetric keys there should be no certificates.
308 EXPECT_EQ(cert_chain_.size(), 0);
309 }
Selene Huang31ab4042020-04-29 04:22:39 -0700310 }
311
312 return GetReturnErrorCode(result);
313}
314
315ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
316 Status result = keymint_->deleteKey(*key_blob);
317 if (!keep_key_blob) {
318 *key_blob = vector<uint8_t>();
319 }
320
Janis Danisevskis24c04702020-12-16 18:28:39 -0800321 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700322 return GetReturnErrorCode(result);
323}
324
325ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
326 return DeleteKey(&key_blob_, keep_key_blob);
327}
328
329ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
330 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800331 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700332 return GetReturnErrorCode(result);
333}
334
335void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
336 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
337 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
338}
339
340void KeyMintAidlTestBase::CheckedDeleteKey() {
341 CheckedDeleteKey(&key_blob_);
342}
343
344ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
345 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800346 AuthorizationSet* out_params,
347 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700348 SCOPED_TRACE("Begin");
349 Status result;
350 BeginResult out;
351 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
352
353 if (result.isOk()) {
354 *out_params = out.params;
355 challenge_ = out.challenge;
356 op = out.operation;
357 }
358
359 return GetReturnErrorCode(result);
360}
361
362ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
363 const AuthorizationSet& in_params,
364 AuthorizationSet* out_params) {
365 SCOPED_TRACE("Begin");
366 Status result;
367 BeginResult out;
368
369 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
370
371 if (result.isOk()) {
372 *out_params = out.params;
373 challenge_ = out.challenge;
374 op_ = out.operation;
375 }
376
377 return GetReturnErrorCode(result);
378}
379
380ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
381 AuthorizationSet* out_params) {
382 SCOPED_TRACE("Begin");
383 EXPECT_EQ(nullptr, op_);
384 return Begin(purpose, key_blob_, in_params, out_params);
385}
386
387ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
388 SCOPED_TRACE("Begin");
389 AuthorizationSet out_params;
390 ErrorCode result = Begin(purpose, in_params, &out_params);
391 EXPECT_TRUE(out_params.empty());
392 return result;
393}
394
Shawn Willden92d79c02021-02-19 07:31:55 -0700395ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
396 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
397 {} /* hardwareAuthToken */,
398 {} /* verificationToken */));
399}
400
401ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700402 SCOPED_TRACE("Update");
403
404 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700405 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700406
Shawn Willden92d79c02021-02-19 07:31:55 -0700407 std::vector<uint8_t> o_put;
408 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700409
Shawn Willden92d79c02021-02-19 07:31:55 -0700410 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700411
412 return GetReturnErrorCode(result);
413}
414
Shawn Willden92d79c02021-02-19 07:31:55 -0700415ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700416 string* output) {
417 SCOPED_TRACE("Finish");
418 Status result;
419
420 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700421 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700422
423 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700424 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
425 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
426 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700427
Shawn Willden92d79c02021-02-19 07:31:55 -0700428 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700429
Shawn Willden92d79c02021-02-19 07:31:55 -0700430 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700431 return GetReturnErrorCode(result);
432}
433
Janis Danisevskis24c04702020-12-16 18:28:39 -0800434ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700435 SCOPED_TRACE("Abort");
436
437 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700438 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700439
440 Status retval = op->abort();
441 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800442 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700443}
444
445ErrorCode KeyMintAidlTestBase::Abort() {
446 SCOPED_TRACE("Abort");
447
448 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700449 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700450
451 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800452 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700453}
454
455void KeyMintAidlTestBase::AbortIfNeeded() {
456 SCOPED_TRACE("AbortIfNeeded");
457 if (op_) {
458 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800459 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700460 }
461}
462
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000463auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
464 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700465 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000466 AuthorizationSet begin_out_params;
467 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700468 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000469
470 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700471 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000472}
473
Selene Huang31ab4042020-04-29 04:22:39 -0700474string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
475 const string& message, const AuthorizationSet& in_params,
476 AuthorizationSet* out_params) {
477 SCOPED_TRACE("ProcessMessage");
478 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700479 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700480 EXPECT_EQ(ErrorCode::OK, result);
481 if (result != ErrorCode::OK) {
482 return "";
483 }
484
485 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700486 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700487 return output;
488}
489
490string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
491 const AuthorizationSet& params) {
492 SCOPED_TRACE("SignMessage");
493 AuthorizationSet out_params;
494 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
495 EXPECT_TRUE(out_params.empty());
496 return signature;
497}
498
499string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
500 SCOPED_TRACE("SignMessage");
501 return SignMessage(key_blob_, message, params);
502}
503
504string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
505 SCOPED_TRACE("MacMessage");
506 return SignMessage(
507 key_blob_, message,
508 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
509}
510
511void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
512 Digest digest, const string& expected_mac) {
513 SCOPED_TRACE("CheckHmacTestVector");
514 ASSERT_EQ(ErrorCode::OK,
515 ImportKey(AuthorizationSetBuilder()
516 .Authorization(TAG_NO_AUTH_REQUIRED)
517 .HmacKey(key.size() * 8)
518 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
519 .Digest(digest),
520 KeyFormat::RAW, key));
521 string signature = MacMessage(message, digest, expected_mac.size() * 8);
522 EXPECT_EQ(expected_mac, signature)
523 << "Test vector didn't match for key of size " << key.size() << " message of size "
524 << message.size() << " and digest " << digest;
525 CheckedDeleteKey();
526}
527
528void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
529 const string& message,
530 const string& expected_ciphertext) {
531 SCOPED_TRACE("CheckAesCtrTestVector");
532 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
533 .Authorization(TAG_NO_AUTH_REQUIRED)
534 .AesEncryptionKey(key.size() * 8)
535 .BlockMode(BlockMode::CTR)
536 .Authorization(TAG_CALLER_NONCE)
537 .Padding(PaddingMode::NONE),
538 KeyFormat::RAW, key));
539
540 auto params = AuthorizationSetBuilder()
541 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
542 .BlockMode(BlockMode::CTR)
543 .Padding(PaddingMode::NONE);
544 AuthorizationSet out_params;
545 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
546 EXPECT_EQ(expected_ciphertext, ciphertext);
547}
548
549void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
550 PaddingMode padding_mode, const string& key,
551 const string& iv, const string& input,
552 const string& expected_output) {
553 auto authset = AuthorizationSetBuilder()
554 .TripleDesEncryptionKey(key.size() * 7)
555 .BlockMode(block_mode)
556 .Authorization(TAG_NO_AUTH_REQUIRED)
557 .Padding(padding_mode);
558 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
559 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
560 ASSERT_GT(key_blob_.size(), 0U);
561
562 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
563 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
564 AuthorizationSet output_params;
565 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
566 EXPECT_EQ(expected_output, output);
567}
568
569void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
570 const string& signature, const AuthorizationSet& params) {
571 SCOPED_TRACE("VerifyMessage");
572 AuthorizationSet begin_out_params;
573 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
574
575 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700576 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700577 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700578 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700579}
580
581void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
582 const AuthorizationSet& params) {
583 SCOPED_TRACE("VerifyMessage");
584 VerifyMessage(key_blob_, message, signature, params);
585}
586
587string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
588 const AuthorizationSet& in_params,
589 AuthorizationSet* out_params) {
590 SCOPED_TRACE("EncryptMessage");
591 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
592}
593
594string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
595 AuthorizationSet* out_params) {
596 SCOPED_TRACE("EncryptMessage");
597 return EncryptMessage(key_blob_, message, params, out_params);
598}
599
600string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
601 SCOPED_TRACE("EncryptMessage");
602 AuthorizationSet out_params;
603 string ciphertext = EncryptMessage(message, params, &out_params);
604 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
605 return ciphertext;
606}
607
608string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
609 PaddingMode padding) {
610 SCOPED_TRACE("EncryptMessage");
611 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
612 AuthorizationSet out_params;
613 string ciphertext = EncryptMessage(message, params, &out_params);
614 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
615 return ciphertext;
616}
617
618string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
619 PaddingMode padding, vector<uint8_t>* iv_out) {
620 SCOPED_TRACE("EncryptMessage");
621 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
622 AuthorizationSet out_params;
623 string ciphertext = EncryptMessage(message, params, &out_params);
624 EXPECT_EQ(1U, out_params.size());
625 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800626 EXPECT_TRUE(ivVal);
627 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700628 return ciphertext;
629}
630
631string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
632 PaddingMode padding, const vector<uint8_t>& iv_in) {
633 SCOPED_TRACE("EncryptMessage");
634 auto params = AuthorizationSetBuilder()
635 .BlockMode(block_mode)
636 .Padding(padding)
637 .Authorization(TAG_NONCE, iv_in);
638 AuthorizationSet out_params;
639 string ciphertext = EncryptMessage(message, params, &out_params);
640 return ciphertext;
641}
642
643string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
644 PaddingMode padding, uint8_t mac_length_bits,
645 const vector<uint8_t>& iv_in) {
646 SCOPED_TRACE("EncryptMessage");
647 auto params = AuthorizationSetBuilder()
648 .BlockMode(block_mode)
649 .Padding(padding)
650 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
651 .Authorization(TAG_NONCE, iv_in);
652 AuthorizationSet out_params;
653 string ciphertext = EncryptMessage(message, params, &out_params);
654 return ciphertext;
655}
656
657string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
658 const string& ciphertext,
659 const AuthorizationSet& params) {
660 SCOPED_TRACE("DecryptMessage");
661 AuthorizationSet out_params;
662 string plaintext =
663 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
664 EXPECT_TRUE(out_params.empty());
665 return plaintext;
666}
667
668string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
669 const AuthorizationSet& params) {
670 SCOPED_TRACE("DecryptMessage");
671 return DecryptMessage(key_blob_, ciphertext, params);
672}
673
674string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
675 PaddingMode padding_mode, const vector<uint8_t>& iv) {
676 SCOPED_TRACE("DecryptMessage");
677 auto params = AuthorizationSetBuilder()
678 .BlockMode(block_mode)
679 .Padding(padding_mode)
680 .Authorization(TAG_NONCE, iv);
681 return DecryptMessage(key_blob_, ciphertext, params);
682}
683
684std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
685 const vector<uint8_t>& key_blob) {
686 std::pair<ErrorCode, vector<uint8_t>> retval;
687 vector<uint8_t> outKeyBlob;
688 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
689 ErrorCode errorcode = GetReturnErrorCode(result);
690 retval = std::tie(errorcode, outKeyBlob);
691
692 return retval;
693}
694vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
695 switch (algorithm) {
696 case Algorithm::RSA:
697 switch (SecLevel()) {
698 case SecurityLevel::SOFTWARE:
699 case SecurityLevel::TRUSTED_ENVIRONMENT:
700 return {2048, 3072, 4096};
701 case SecurityLevel::STRONGBOX:
702 return {2048};
703 default:
704 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
705 break;
706 }
707 break;
708 case Algorithm::EC:
709 switch (SecLevel()) {
710 case SecurityLevel::SOFTWARE:
711 case SecurityLevel::TRUSTED_ENVIRONMENT:
712 return {224, 256, 384, 521};
713 case SecurityLevel::STRONGBOX:
714 return {256};
715 default:
716 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
717 break;
718 }
719 break;
720 case Algorithm::AES:
721 return {128, 256};
722 case Algorithm::TRIPLE_DES:
723 return {168};
724 case Algorithm::HMAC: {
725 vector<uint32_t> retval((512 - 64) / 8 + 1);
726 uint32_t size = 64 - 8;
727 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
728 return retval;
729 }
730 default:
731 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
732 return {};
733 }
734 ADD_FAILURE() << "Should be impossible to get here";
735 return {};
736}
737
738vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
739 if (SecLevel() == SecurityLevel::STRONGBOX) {
740 switch (algorithm) {
741 case Algorithm::RSA:
742 return {3072, 4096};
743 case Algorithm::EC:
744 return {224, 384, 521};
745 case Algorithm::AES:
746 return {192};
747 default:
748 return {};
749 }
750 }
751 return {};
752}
753
754vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
755 if (securityLevel_ == SecurityLevel::STRONGBOX) {
756 return {EcCurve::P_256};
757 } else {
758 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
759 }
760}
761
762vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
763 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
764 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
765 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
766}
767
768vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
769 switch (SecLevel()) {
770 case SecurityLevel::SOFTWARE:
771 case SecurityLevel::TRUSTED_ENVIRONMENT:
772 if (withNone) {
773 if (withMD5)
774 return {Digest::NONE, Digest::MD5, Digest::SHA1,
775 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
776 Digest::SHA_2_512};
777 else
778 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
779 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
780 } else {
781 if (withMD5)
782 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
783 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
784 else
785 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
786 Digest::SHA_2_512};
787 }
788 break;
789 case SecurityLevel::STRONGBOX:
790 if (withNone)
791 return {Digest::NONE, Digest::SHA_2_256};
792 else
793 return {Digest::SHA_2_256};
794 break;
795 default:
796 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
797 break;
798 }
799 ADD_FAILURE() << "Should be impossible to get here";
800 return {};
801}
802
Shawn Willden7f424372021-01-10 18:06:50 -0700803static const vector<KeyParameter> kEmptyAuthList{};
804
805const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
806 const vector<KeyCharacteristics>& key_characteristics) {
807 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
808 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
809 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
810}
811
Qi Wubeefae42021-01-28 23:16:37 +0800812const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
813 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
814 auto found = std::find_if(
815 key_characteristics.begin(), key_characteristics.end(),
816 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700817 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
818}
819
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000820ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700821 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000822 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
823 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
824 return result;
825}
826
827ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700828 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000829 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
830 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
831 return result;
832}
833
834ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
835 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -0700836 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000837 rsaKeyBlob, KeyPurpose::SIGN, message,
838 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
839 return result;
840}
841
842ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700843 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
844 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000845 return result;
846}
847
Selene Huang6e46f142021-04-20 19:20:11 -0700848void verify_serial(X509* cert, const uint64_t expected_serial) {
849 BIGNUM_Ptr ser(BN_new());
850 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
851
852 uint64_t serial;
853 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
854 EXPECT_EQ(serial, expected_serial);
855}
856
857// Please set self_signed to true for fake certificates or self signed
858// certificates
859void verify_subject(const X509* cert, //
860 const string& subject, //
861 bool self_signed) {
862 char* cert_issuer = //
863 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
864
865 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
866
867 string expected_subject("/CN=");
868 if (subject.empty()) {
869 expected_subject.append("Android Keystore Key");
870 } else {
871 expected_subject.append(subject);
872 }
873
874 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
875
876 if (self_signed) {
877 EXPECT_STREQ(cert_issuer, cert_subj)
878 << "Cert issuer and subject mismatch for self signed certificate.";
879 }
880
881 OPENSSL_free(cert_subj);
882 OPENSSL_free(cert_issuer);
883}
884
885vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
886 BIGNUM_Ptr serial(BN_new());
887 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
888
889 int len = BN_num_bytes(serial.get());
890 vector<uint8_t> serial_blob(len);
891 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
892 return {};
893 }
894
895 return serial_blob;
896}
897
898void verify_subject_and_serial(const Certificate& certificate, //
899 const uint64_t expected_serial, //
900 const string& subject, bool self_signed) {
901 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
902 ASSERT_TRUE(!!cert.get());
903
904 verify_serial(cert.get(), expected_serial);
905 verify_subject(cert.get(), subject, self_signed);
906}
907
Shawn Willden7c130392020-12-21 09:58:22 -0700908bool verify_attestation_record(const string& challenge, //
909 const string& app_id, //
910 AuthorizationSet expected_sw_enforced, //
911 AuthorizationSet expected_hw_enforced, //
912 SecurityLevel security_level,
913 const vector<uint8_t>& attestation_cert) {
914 X509_Ptr cert(parse_cert_blob(attestation_cert));
915 EXPECT_TRUE(!!cert.get());
916 if (!cert.get()) return false;
917
918 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
919 EXPECT_TRUE(!!attest_rec);
920 if (!attest_rec) return false;
921
922 AuthorizationSet att_sw_enforced;
923 AuthorizationSet att_hw_enforced;
924 uint32_t att_attestation_version;
925 uint32_t att_keymaster_version;
926 SecurityLevel att_attestation_security_level;
927 SecurityLevel att_keymaster_security_level;
928 vector<uint8_t> att_challenge;
929 vector<uint8_t> att_unique_id;
930 vector<uint8_t> att_app_id;
931
932 auto error = parse_attestation_record(attest_rec->data, //
933 attest_rec->length, //
934 &att_attestation_version, //
935 &att_attestation_security_level, //
936 &att_keymaster_version, //
937 &att_keymaster_security_level, //
938 &att_challenge, //
939 &att_sw_enforced, //
940 &att_hw_enforced, //
941 &att_unique_id);
942 EXPECT_EQ(ErrorCode::OK, error);
943 if (error != ErrorCode::OK) return false;
944
Shawn Willden3cb64a62021-04-05 14:39:05 -0600945 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -0700946 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -0700947
Selene Huang4f64c222021-04-13 19:54:36 -0700948 // check challenge and app id only if we expects a non-fake certificate
949 if (challenge.length() > 0) {
950 EXPECT_EQ(challenge.length(), att_challenge.size());
951 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
952
953 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
954 }
Shawn Willden7c130392020-12-21 09:58:22 -0700955
Shawn Willden3cb64a62021-04-05 14:39:05 -0600956 EXPECT_EQ(att_keymaster_version, 100U);
Shawn Willden7c130392020-12-21 09:58:22 -0700957 EXPECT_EQ(security_level, att_keymaster_security_level);
958 EXPECT_EQ(security_level, att_attestation_security_level);
959
Shawn Willden7c130392020-12-21 09:58:22 -0700960
961 char property_value[PROPERTY_VALUE_MAX] = {};
962 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
963 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
964 // for the BOOT_PATCH_LEVEL.
965 if (avb_verification_enabled()) {
966 for (int i = 0; i < att_hw_enforced.size(); i++) {
967 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
968 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
969 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +0800970 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -0700971 // strptime seems to require delimiters, but the tag value will
972 // be YYYYMMDD
973 date.insert(6, "-");
974 date.insert(4, "-");
975 EXPECT_EQ(date.size(), 10);
976 struct tm time;
977 strptime(date.c_str(), "%Y-%m-%d", &time);
978
979 // Day of the month (0-31)
980 EXPECT_GE(time.tm_mday, 0);
981 EXPECT_LT(time.tm_mday, 32);
982 // Months since Jan (0-11)
983 EXPECT_GE(time.tm_mon, 0);
984 EXPECT_LT(time.tm_mon, 12);
985 // Years since 1900
986 EXPECT_GT(time.tm_year, 110);
987 EXPECT_LT(time.tm_year, 200);
988 }
989 }
990 }
991
992 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
993 // indicates true. A provided boolean tag that can be pulled back out of the certificate
994 // indicates correct encoding. No need to check if it's in both lists, since the
995 // AuthorizationSet compare below will handle mismatches of tags.
996 if (security_level == SecurityLevel::SOFTWARE) {
997 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
998 } else {
999 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1000 }
1001
1002 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
1003 // the authorization list during key generation) isn't being attested to in the certificate.
1004 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1005 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1006 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1007 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1008
1009 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1010 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1011 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1012 att_hw_enforced.Contains(TAG_KEY_SIZE));
1013 }
1014
1015 // Test root of trust elements
1016 vector<uint8_t> verified_boot_key;
1017 VerifiedBoot verified_boot_state;
1018 bool device_locked;
1019 vector<uint8_t> verified_boot_hash;
1020 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1021 &verified_boot_state, &device_locked, &verified_boot_hash);
1022 EXPECT_EQ(ErrorCode::OK, error);
1023
1024 if (avb_verification_enabled()) {
1025 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1026 string prop_string(property_value);
1027 EXPECT_EQ(prop_string.size(), 64);
1028 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1029
1030 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1031 if (!strcmp(property_value, "unlocked")) {
1032 EXPECT_FALSE(device_locked);
1033 } else {
1034 EXPECT_TRUE(device_locked);
1035 }
1036
1037 // Check that the device is locked if not debuggable, e.g., user build
1038 // images in CTS. For VTS, debuggable images are used to allow adb root
1039 // and the device is unlocked.
1040 if (!property_get_bool("ro.debuggable", false)) {
1041 EXPECT_TRUE(device_locked);
1042 } else {
1043 EXPECT_FALSE(device_locked);
1044 }
1045 }
1046
1047 // Verified boot key should be all 0's if the boot state is not verified or self signed
1048 std::string empty_boot_key(32, '\0');
1049 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1050 verified_boot_key.size());
1051 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1052 if (!strcmp(property_value, "green")) {
1053 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1054 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1055 verified_boot_key.size()));
1056 } else if (!strcmp(property_value, "yellow")) {
1057 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1058 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1059 verified_boot_key.size()));
1060 } else if (!strcmp(property_value, "orange")) {
1061 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1062 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1063 verified_boot_key.size()));
1064 } else if (!strcmp(property_value, "red")) {
1065 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1066 } else {
1067 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1068 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1069 verified_boot_key.size()));
1070 }
1071
1072 att_sw_enforced.Sort();
1073 expected_sw_enforced.Sort();
1074 auto a = filtered_tags(expected_sw_enforced);
1075 auto b = filtered_tags(att_sw_enforced);
1076 EXPECT_EQ(a, b);
1077
1078 att_hw_enforced.Sort();
1079 expected_hw_enforced.Sort();
1080 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1081
1082 return true;
1083}
1084
1085string bin2hex(const vector<uint8_t>& data) {
1086 string retval;
1087 retval.reserve(data.size() * 2 + 1);
1088 for (uint8_t byte : data) {
1089 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1090 retval.push_back(nibble2hex[0x0F & byte]);
1091 }
1092 return retval;
1093}
1094
David Drysdalef0d516d2021-03-22 07:51:43 +00001095AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1096 AuthorizationSet authList;
1097 for (auto& entry : key_characteristics) {
1098 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1099 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1100 authList.push_back(AuthorizationSet(entry.authorizations));
1101 }
1102 }
1103 return authList;
1104}
1105
1106AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1107 AuthorizationSet authList;
1108 for (auto& entry : key_characteristics) {
1109 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1110 entry.securityLevel == SecurityLevel::KEYSTORE) {
1111 authList.push_back(AuthorizationSet(entry.authorizations));
1112 }
1113 }
1114 return authList;
1115}
1116
Shawn Willden7c130392020-12-21 09:58:22 -07001117AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1118 std::stringstream cert_data;
1119
1120 for (size_t i = 0; i < chain.size(); ++i) {
1121 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1122
1123 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1124 X509_Ptr signing_cert;
1125 if (i < chain.size() - 1) {
1126 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1127 } else {
1128 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1129 }
1130 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1131
1132 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1133 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1134
1135 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1136 return AssertionFailure()
1137 << "Verification of certificate " << i << " failed "
1138 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1139 << cert_data.str();
1140 }
1141
1142 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1143 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1144 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001145 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1146 << " Signer subject is " << signer_subj
1147 << " Issuer subject is " << cert_issuer << endl
1148 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001149 }
Shawn Willden7c130392020-12-21 09:58:22 -07001150 }
1151
1152 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1153 return AssertionSuccess();
1154}
1155
1156X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1157 const uint8_t* p = blob.data();
1158 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1159}
1160
David Drysdalef0d516d2021-03-22 07:51:43 +00001161vector<uint8_t> make_name_from_str(const string& name) {
1162 X509_NAME_Ptr x509_name(X509_NAME_new());
1163 EXPECT_TRUE(x509_name.get() != nullptr);
1164 if (!x509_name) return {};
1165
1166 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1167 "CN", //
1168 MBSTRING_ASC,
1169 reinterpret_cast<const uint8_t*>(name.c_str()),
1170 -1, // len
1171 -1, // loc
1172 0 /* set */));
1173
1174 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1175 EXPECT_GT(len, 0);
1176
1177 vector<uint8_t> retval(len);
1178 uint8_t* p = retval.data();
1179 i2d_X509_NAME(x509_name.get(), &p);
1180
1181 return retval;
1182}
1183
David Drysdale4dc01072021-04-01 12:17:35 +01001184namespace {
1185
1186void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1187 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1188 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1189
1190 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1191 if (testMode) {
1192 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1193 MatchesRegex("{\n"
1194 " 1 : 2,\n" // kty: EC2
1195 " 3 : -7,\n" // alg: ES256
1196 " -1 : 1,\n" // EC id: P256
1197 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1198 // sequence of 32 hexadecimal bytes, enclosed in braces and
1199 // separated by commas. In this case, some Ed25519 public key.
1200 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1201 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1202 " -70000 : null,\n" // test marker
1203 "}"));
1204 } else {
1205 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1206 MatchesRegex("{\n"
1207 " 1 : 2,\n" // kty: EC2
1208 " 3 : -7,\n" // alg: ES256
1209 " -1 : 1,\n" // EC id: P256
1210 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1211 // sequence of 32 hexadecimal bytes, enclosed in braces and
1212 // separated by commas. In this case, some Ed25519 public key.
1213 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1214 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1215 "}"));
1216 }
1217}
1218
1219} // namespace
1220
1221void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1222 vector<uint8_t>* payload_value) {
1223 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1224 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1225
1226 ASSERT_NE(coseMac0->asArray(), nullptr);
1227 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1228
1229 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1230 ASSERT_NE(protParms, nullptr);
1231
1232 // Header label:value of 'alg': HMAC-256
1233 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1234
1235 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1236 ASSERT_NE(unprotParms, nullptr);
1237 ASSERT_EQ(unprotParms->size(), 0);
1238
1239 // The payload is a bstr holding an encoded COSE_Key
1240 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1241 ASSERT_NE(payload, nullptr);
1242 check_cose_key(payload->value(), testMode);
1243
1244 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1245 ASSERT_TRUE(coseMac0Tag);
1246 auto extractedTag = coseMac0Tag->value();
1247 EXPECT_EQ(extractedTag.size(), 32U);
1248
1249 // Compare with tag generated with kTestMacKey. Should only match in test mode
1250 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
1251 payload->value());
1252 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1253
1254 if (testMode) {
1255 EXPECT_EQ(*testTag, extractedTag);
1256 } else {
1257 EXPECT_NE(*testTag, extractedTag);
1258 }
1259 if (payload_value != nullptr) {
1260 *payload_value = payload->value();
1261 }
1262}
1263
1264void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1265 // Extract x and y affine coordinates from the encoded Cose_Key.
1266 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1267 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1268 auto coseKey = parsedPayload->asMap();
1269 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1270 ASSERT_NE(xItem->asBstr(), nullptr);
1271 vector<uint8_t> x = xItem->asBstr()->value();
1272 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1273 ASSERT_NE(yItem->asBstr(), nullptr);
1274 vector<uint8_t> y = yItem->asBstr()->value();
1275
1276 // Concatenate: 0x04 (uncompressed form marker) | x | y
1277 vector<uint8_t> pubKeyData{0x04};
1278 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1279 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1280
1281 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1282 ASSERT_NE(ecKey, nullptr);
1283 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1284 ASSERT_NE(group, nullptr);
1285 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1286 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1287 ASSERT_NE(point, nullptr);
1288 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1289 nullptr),
1290 1);
1291 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1292
1293 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1294 ASSERT_NE(pubKey, nullptr);
1295 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1296 *signingKey = std::move(pubKey);
1297}
1298
Selene Huang31ab4042020-04-29 04:22:39 -07001299} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001300
Janis Danisevskis24c04702020-12-16 18:28:39 -08001301} // namespace aidl::android::hardware::security::keymint