blob: f0dfff11a0411e9732c3d5a201314b88c7f530cc [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 = {
Shawn Willden7c130392020-12-21 09:58:22 -0700122 Tag::CREATION_DATETIME, //
123 Tag::EC_CURVE,
124 Tag::HARDWARE_TYPE,
125 Tag::INCLUDE_UNIQUE_ID,
126};
127
128AuthorizationSet filtered_tags(const AuthorizationSet& set) {
129 AuthorizationSet filtered;
130 std::remove_copy_if(
131 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
132 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
133 kTagsToFilter.end();
134 });
135 return filtered;
136}
137
138string x509NameToStr(X509_NAME* name) {
139 char* s = X509_NAME_oneline(name, nullptr, 0);
140 string retval(s);
141 OPENSSL_free(s);
142 return retval;
143}
144
Shawn Willden7f424372021-01-10 18:06:50 -0700145} // namespace
146
Shawn Willden7c130392020-12-21 09:58:22 -0700147bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
148bool KeyMintAidlTestBase::dump_Attestations = false;
149
Janis Danisevskis24c04702020-12-16 18:28:39 -0800150ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700151 if (result.isOk()) return ErrorCode::OK;
152
Janis Danisevskis24c04702020-12-16 18:28:39 -0800153 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
154 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700155 }
156
157 return ErrorCode::UNKNOWN_ERROR;
158}
159
Janis Danisevskis24c04702020-12-16 18:28:39 -0800160void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700161 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800162 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700163
164 KeyMintHardwareInfo info;
165 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
166
167 securityLevel_ = info.securityLevel;
168 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
169 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
170
171 os_version_ = getOsVersion();
172 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100173 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700174}
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;
David Drysdale56ba9122021-04-19 19:10:47 +0100351 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700352
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
David Drysdale56ba9122021-04-19 19:10:47 +0100369 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700370
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};
David Drysdale7de9feb2021-03-05 14:56:19 +0000747 case Algorithm::TRIPLE_DES:
748 return {56};
749 default:
750 return {};
751 }
752 } else {
753 switch (algorithm) {
754 case Algorithm::TRIPLE_DES:
755 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -0700756 default:
757 return {};
758 }
759 }
760 return {};
761}
762
David Drysdale7de9feb2021-03-05 14:56:19 +0000763vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
764 switch (algorithm) {
765 case Algorithm::AES:
766 return {
767 BlockMode::CBC,
768 BlockMode::CTR,
769 BlockMode::ECB,
770 BlockMode::GCM,
771 };
772 case Algorithm::TRIPLE_DES:
773 return {
774 BlockMode::CBC,
775 BlockMode::ECB,
776 };
777 default:
778 return {};
779 }
780}
781
782vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
783 BlockMode blockMode) {
784 switch (algorithm) {
785 case Algorithm::AES:
786 switch (blockMode) {
787 case BlockMode::CBC:
788 case BlockMode::ECB:
789 return {PaddingMode::NONE, PaddingMode::PKCS7};
790 case BlockMode::CTR:
791 case BlockMode::GCM:
792 return {PaddingMode::NONE};
793 default:
794 return {};
795 };
796 case Algorithm::TRIPLE_DES:
797 switch (blockMode) {
798 case BlockMode::CBC:
799 case BlockMode::ECB:
800 return {PaddingMode::NONE, PaddingMode::PKCS7};
801 default:
802 return {};
803 };
804 default:
805 return {};
806 }
807}
808
809vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
810 BlockMode blockMode) {
811 switch (algorithm) {
812 case Algorithm::AES:
813 switch (blockMode) {
814 case BlockMode::CTR:
815 case BlockMode::GCM:
816 return {PaddingMode::PKCS7};
817 default:
818 return {};
819 };
820 default:
821 return {};
822 }
823}
824
Selene Huang31ab4042020-04-29 04:22:39 -0700825vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
826 if (securityLevel_ == SecurityLevel::STRONGBOX) {
827 return {EcCurve::P_256};
828 } else {
829 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
830 }
831}
832
833vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
834 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
835 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
836 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
837}
838
839vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
840 switch (SecLevel()) {
841 case SecurityLevel::SOFTWARE:
842 case SecurityLevel::TRUSTED_ENVIRONMENT:
843 if (withNone) {
844 if (withMD5)
845 return {Digest::NONE, Digest::MD5, Digest::SHA1,
846 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
847 Digest::SHA_2_512};
848 else
849 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
850 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
851 } else {
852 if (withMD5)
853 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
854 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
855 else
856 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
857 Digest::SHA_2_512};
858 }
859 break;
860 case SecurityLevel::STRONGBOX:
861 if (withNone)
862 return {Digest::NONE, Digest::SHA_2_256};
863 else
864 return {Digest::SHA_2_256};
865 break;
866 default:
867 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
868 break;
869 }
870 ADD_FAILURE() << "Should be impossible to get here";
871 return {};
872}
873
Shawn Willden7f424372021-01-10 18:06:50 -0700874static const vector<KeyParameter> kEmptyAuthList{};
875
876const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
877 const vector<KeyCharacteristics>& key_characteristics) {
878 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
879 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
880 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
881}
882
Qi Wubeefae42021-01-28 23:16:37 +0800883const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
884 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
885 auto found = std::find_if(
886 key_characteristics.begin(), key_characteristics.end(),
887 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700888 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
889}
890
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000891ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700892 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000893 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
894 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
895 return result;
896}
897
898ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700899 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000900 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
901 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
902 return result;
903}
904
905ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
906 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -0700907 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000908 rsaKeyBlob, KeyPurpose::SIGN, message,
909 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
910 return result;
911}
912
913ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700914 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
915 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000916 return result;
917}
918
Selene Huang6e46f142021-04-20 19:20:11 -0700919void verify_serial(X509* cert, const uint64_t expected_serial) {
920 BIGNUM_Ptr ser(BN_new());
921 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
922
923 uint64_t serial;
924 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
925 EXPECT_EQ(serial, expected_serial);
926}
927
928// Please set self_signed to true for fake certificates or self signed
929// certificates
930void verify_subject(const X509* cert, //
931 const string& subject, //
932 bool self_signed) {
933 char* cert_issuer = //
934 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
935
936 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
937
938 string expected_subject("/CN=");
939 if (subject.empty()) {
940 expected_subject.append("Android Keystore Key");
941 } else {
942 expected_subject.append(subject);
943 }
944
945 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
946
947 if (self_signed) {
948 EXPECT_STREQ(cert_issuer, cert_subj)
949 << "Cert issuer and subject mismatch for self signed certificate.";
950 }
951
952 OPENSSL_free(cert_subj);
953 OPENSSL_free(cert_issuer);
954}
955
956vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
957 BIGNUM_Ptr serial(BN_new());
958 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
959
960 int len = BN_num_bytes(serial.get());
961 vector<uint8_t> serial_blob(len);
962 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
963 return {};
964 }
965
966 return serial_blob;
967}
968
969void verify_subject_and_serial(const Certificate& certificate, //
970 const uint64_t expected_serial, //
971 const string& subject, bool self_signed) {
972 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
973 ASSERT_TRUE(!!cert.get());
974
975 verify_serial(cert.get(), expected_serial);
976 verify_subject(cert.get(), subject, self_signed);
977}
978
Shawn Willden7c130392020-12-21 09:58:22 -0700979bool verify_attestation_record(const string& challenge, //
980 const string& app_id, //
981 AuthorizationSet expected_sw_enforced, //
982 AuthorizationSet expected_hw_enforced, //
983 SecurityLevel security_level,
984 const vector<uint8_t>& attestation_cert) {
985 X509_Ptr cert(parse_cert_blob(attestation_cert));
986 EXPECT_TRUE(!!cert.get());
987 if (!cert.get()) return false;
988
989 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
990 EXPECT_TRUE(!!attest_rec);
991 if (!attest_rec) return false;
992
993 AuthorizationSet att_sw_enforced;
994 AuthorizationSet att_hw_enforced;
995 uint32_t att_attestation_version;
996 uint32_t att_keymaster_version;
997 SecurityLevel att_attestation_security_level;
998 SecurityLevel att_keymaster_security_level;
999 vector<uint8_t> att_challenge;
1000 vector<uint8_t> att_unique_id;
1001 vector<uint8_t> att_app_id;
1002
1003 auto error = parse_attestation_record(attest_rec->data, //
1004 attest_rec->length, //
1005 &att_attestation_version, //
1006 &att_attestation_security_level, //
1007 &att_keymaster_version, //
1008 &att_keymaster_security_level, //
1009 &att_challenge, //
1010 &att_sw_enforced, //
1011 &att_hw_enforced, //
1012 &att_unique_id);
1013 EXPECT_EQ(ErrorCode::OK, error);
1014 if (error != ErrorCode::OK) return false;
1015
Shawn Willden3cb64a62021-04-05 14:39:05 -06001016 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -07001017 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001018
Selene Huang4f64c222021-04-13 19:54:36 -07001019 // check challenge and app id only if we expects a non-fake certificate
1020 if (challenge.length() > 0) {
1021 EXPECT_EQ(challenge.length(), att_challenge.size());
1022 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1023
1024 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1025 }
Shawn Willden7c130392020-12-21 09:58:22 -07001026
Shawn Willden3cb64a62021-04-05 14:39:05 -06001027 EXPECT_EQ(att_keymaster_version, 100U);
Shawn Willden7c130392020-12-21 09:58:22 -07001028 EXPECT_EQ(security_level, att_keymaster_security_level);
1029 EXPECT_EQ(security_level, att_attestation_security_level);
1030
Shawn Willden7c130392020-12-21 09:58:22 -07001031
1032 char property_value[PROPERTY_VALUE_MAX] = {};
1033 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
1034 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
1035 // for the BOOT_PATCH_LEVEL.
1036 if (avb_verification_enabled()) {
1037 for (int i = 0; i < att_hw_enforced.size(); i++) {
1038 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1039 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1040 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001041 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -07001042 // strptime seems to require delimiters, but the tag value will
1043 // be YYYYMMDD
1044 date.insert(6, "-");
1045 date.insert(4, "-");
1046 EXPECT_EQ(date.size(), 10);
1047 struct tm time;
1048 strptime(date.c_str(), "%Y-%m-%d", &time);
1049
1050 // Day of the month (0-31)
1051 EXPECT_GE(time.tm_mday, 0);
1052 EXPECT_LT(time.tm_mday, 32);
1053 // Months since Jan (0-11)
1054 EXPECT_GE(time.tm_mon, 0);
1055 EXPECT_LT(time.tm_mon, 12);
1056 // Years since 1900
1057 EXPECT_GT(time.tm_year, 110);
1058 EXPECT_LT(time.tm_year, 200);
1059 }
1060 }
1061 }
1062
1063 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1064 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1065 // indicates correct encoding. No need to check if it's in both lists, since the
1066 // AuthorizationSet compare below will handle mismatches of tags.
1067 if (security_level == SecurityLevel::SOFTWARE) {
1068 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1069 } else {
1070 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1071 }
1072
1073 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
1074 // the authorization list during key generation) isn't being attested to in the certificate.
1075 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1076 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1077 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1078 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1079
1080 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1081 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1082 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1083 att_hw_enforced.Contains(TAG_KEY_SIZE));
1084 }
1085
1086 // Test root of trust elements
1087 vector<uint8_t> verified_boot_key;
1088 VerifiedBoot verified_boot_state;
1089 bool device_locked;
1090 vector<uint8_t> verified_boot_hash;
1091 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1092 &verified_boot_state, &device_locked, &verified_boot_hash);
1093 EXPECT_EQ(ErrorCode::OK, error);
1094
1095 if (avb_verification_enabled()) {
1096 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1097 string prop_string(property_value);
1098 EXPECT_EQ(prop_string.size(), 64);
1099 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1100
1101 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1102 if (!strcmp(property_value, "unlocked")) {
1103 EXPECT_FALSE(device_locked);
1104 } else {
1105 EXPECT_TRUE(device_locked);
1106 }
1107
1108 // Check that the device is locked if not debuggable, e.g., user build
1109 // images in CTS. For VTS, debuggable images are used to allow adb root
1110 // and the device is unlocked.
1111 if (!property_get_bool("ro.debuggable", false)) {
1112 EXPECT_TRUE(device_locked);
1113 } else {
1114 EXPECT_FALSE(device_locked);
1115 }
1116 }
1117
1118 // Verified boot key should be all 0's if the boot state is not verified or self signed
1119 std::string empty_boot_key(32, '\0');
1120 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1121 verified_boot_key.size());
1122 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1123 if (!strcmp(property_value, "green")) {
1124 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1125 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1126 verified_boot_key.size()));
1127 } else if (!strcmp(property_value, "yellow")) {
1128 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1129 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1130 verified_boot_key.size()));
1131 } else if (!strcmp(property_value, "orange")) {
1132 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1133 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1134 verified_boot_key.size()));
1135 } else if (!strcmp(property_value, "red")) {
1136 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1137 } else {
1138 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1139 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1140 verified_boot_key.size()));
1141 }
1142
1143 att_sw_enforced.Sort();
1144 expected_sw_enforced.Sort();
1145 auto a = filtered_tags(expected_sw_enforced);
1146 auto b = filtered_tags(att_sw_enforced);
1147 EXPECT_EQ(a, b);
1148
1149 att_hw_enforced.Sort();
1150 expected_hw_enforced.Sort();
1151 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1152
1153 return true;
1154}
1155
1156string bin2hex(const vector<uint8_t>& data) {
1157 string retval;
1158 retval.reserve(data.size() * 2 + 1);
1159 for (uint8_t byte : data) {
1160 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1161 retval.push_back(nibble2hex[0x0F & byte]);
1162 }
1163 return retval;
1164}
1165
David Drysdalef0d516d2021-03-22 07:51:43 +00001166AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1167 AuthorizationSet authList;
1168 for (auto& entry : key_characteristics) {
1169 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1170 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1171 authList.push_back(AuthorizationSet(entry.authorizations));
1172 }
1173 }
1174 return authList;
1175}
1176
1177AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1178 AuthorizationSet authList;
1179 for (auto& entry : key_characteristics) {
1180 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1181 entry.securityLevel == SecurityLevel::KEYSTORE) {
1182 authList.push_back(AuthorizationSet(entry.authorizations));
1183 }
1184 }
1185 return authList;
1186}
1187
Shawn Willden7c130392020-12-21 09:58:22 -07001188AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1189 std::stringstream cert_data;
1190
1191 for (size_t i = 0; i < chain.size(); ++i) {
1192 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1193
1194 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1195 X509_Ptr signing_cert;
1196 if (i < chain.size() - 1) {
1197 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1198 } else {
1199 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1200 }
1201 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1202
1203 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1204 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1205
1206 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1207 return AssertionFailure()
1208 << "Verification of certificate " << i << " failed "
1209 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1210 << cert_data.str();
1211 }
1212
1213 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1214 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1215 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001216 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1217 << " Signer subject is " << signer_subj
1218 << " Issuer subject is " << cert_issuer << endl
1219 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001220 }
Shawn Willden7c130392020-12-21 09:58:22 -07001221 }
1222
1223 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1224 return AssertionSuccess();
1225}
1226
1227X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1228 const uint8_t* p = blob.data();
1229 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1230}
1231
David Drysdalef0d516d2021-03-22 07:51:43 +00001232vector<uint8_t> make_name_from_str(const string& name) {
1233 X509_NAME_Ptr x509_name(X509_NAME_new());
1234 EXPECT_TRUE(x509_name.get() != nullptr);
1235 if (!x509_name) return {};
1236
1237 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1238 "CN", //
1239 MBSTRING_ASC,
1240 reinterpret_cast<const uint8_t*>(name.c_str()),
1241 -1, // len
1242 -1, // loc
1243 0 /* set */));
1244
1245 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1246 EXPECT_GT(len, 0);
1247
1248 vector<uint8_t> retval(len);
1249 uint8_t* p = retval.data();
1250 i2d_X509_NAME(x509_name.get(), &p);
1251
1252 return retval;
1253}
1254
David Drysdale4dc01072021-04-01 12:17:35 +01001255namespace {
1256
1257void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1258 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1259 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1260
1261 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1262 if (testMode) {
1263 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1264 MatchesRegex("{\n"
1265 " 1 : 2,\n" // kty: EC2
1266 " 3 : -7,\n" // alg: ES256
1267 " -1 : 1,\n" // EC id: P256
1268 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1269 // sequence of 32 hexadecimal bytes, enclosed in braces and
1270 // separated by commas. In this case, some Ed25519 public key.
1271 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1272 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1273 " -70000 : null,\n" // test marker
1274 "}"));
1275 } else {
1276 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1277 MatchesRegex("{\n"
1278 " 1 : 2,\n" // kty: EC2
1279 " 3 : -7,\n" // alg: ES256
1280 " -1 : 1,\n" // EC id: P256
1281 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1282 // sequence of 32 hexadecimal bytes, enclosed in braces and
1283 // separated by commas. In this case, some Ed25519 public key.
1284 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1285 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1286 "}"));
1287 }
1288}
1289
1290} // namespace
1291
1292void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1293 vector<uint8_t>* payload_value) {
1294 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1295 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1296
1297 ASSERT_NE(coseMac0->asArray(), nullptr);
1298 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1299
1300 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1301 ASSERT_NE(protParms, nullptr);
1302
1303 // Header label:value of 'alg': HMAC-256
1304 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1305
1306 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1307 ASSERT_NE(unprotParms, nullptr);
1308 ASSERT_EQ(unprotParms->size(), 0);
1309
1310 // The payload is a bstr holding an encoded COSE_Key
1311 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1312 ASSERT_NE(payload, nullptr);
1313 check_cose_key(payload->value(), testMode);
1314
1315 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1316 ASSERT_TRUE(coseMac0Tag);
1317 auto extractedTag = coseMac0Tag->value();
1318 EXPECT_EQ(extractedTag.size(), 32U);
1319
1320 // Compare with tag generated with kTestMacKey. Should only match in test mode
1321 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
1322 payload->value());
1323 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1324
1325 if (testMode) {
1326 EXPECT_EQ(*testTag, extractedTag);
1327 } else {
1328 EXPECT_NE(*testTag, extractedTag);
1329 }
1330 if (payload_value != nullptr) {
1331 *payload_value = payload->value();
1332 }
1333}
1334
1335void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1336 // Extract x and y affine coordinates from the encoded Cose_Key.
1337 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1338 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1339 auto coseKey = parsedPayload->asMap();
1340 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1341 ASSERT_NE(xItem->asBstr(), nullptr);
1342 vector<uint8_t> x = xItem->asBstr()->value();
1343 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1344 ASSERT_NE(yItem->asBstr(), nullptr);
1345 vector<uint8_t> y = yItem->asBstr()->value();
1346
1347 // Concatenate: 0x04 (uncompressed form marker) | x | y
1348 vector<uint8_t> pubKeyData{0x04};
1349 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1350 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1351
1352 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1353 ASSERT_NE(ecKey, nullptr);
1354 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1355 ASSERT_NE(group, nullptr);
1356 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1357 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1358 ASSERT_NE(point, nullptr);
1359 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1360 nullptr),
1361 1);
1362 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1363
1364 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1365 ASSERT_NE(pubKey, nullptr);
1366 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1367 *signingKey = std::move(pubKey);
1368}
1369
Selene Huang31ab4042020-04-29 04:22:39 -07001370} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001371
Janis Danisevskis24c04702020-12-16 18:28:39 -08001372} // namespace aidl::android::hardware::security::keymint