blob: 1a05ac8b118dea8a078015b1195762a1e1b5b455 [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 {
David Drysdaledf8f52e2021-05-06 08:10:58 +010062
63// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
64// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
65const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
66
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000067typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070068// Predicate for testing basic characteristics validity in generation or import.
69bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
70 const vector<KeyCharacteristics>& key_characteristics) {
71 if (key_characteristics.empty()) return false;
72
73 std::unordered_set<SecurityLevel> levels_seen;
74 for (auto& entry : key_characteristics) {
75 if (entry.authorizations.empty()) return false;
76
Qi Wubeefae42021-01-28 23:16:37 +080077 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
78 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
79
Shawn Willden7f424372021-01-10 18:06:50 -070080 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
81 levels_seen.insert(entry.securityLevel);
82
83 // Generally, we should only have one entry, at the same security level as the KM
84 // instance. There is an exception: StrongBox KM can have some authorizations that are
85 // enforced by the TEE.
86 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
87 (secLevel == SecurityLevel::STRONGBOX &&
88 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
89
90 if (!isExpectedSecurityLevel) return false;
91 }
92 return true;
93}
94
Shawn Willden7c130392020-12-21 09:58:22 -070095// Extract attestation record from cert. Returned object is still part of cert; don't free it
96// separately.
97ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
98 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
99 EXPECT_TRUE(!!oid.get());
100 if (!oid.get()) return nullptr;
101
102 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
103 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
104 if (location == -1) return nullptr;
105
106 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
107 EXPECT_TRUE(!!attest_rec_ext)
108 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
109 if (!attest_rec_ext) return nullptr;
110
111 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
112 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
113 return attest_rec;
114}
115
116bool avb_verification_enabled() {
117 char value[PROPERTY_VALUE_MAX];
118 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
119}
120
121char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
122 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
123
124// Attestations don't contain everything in key authorization lists, so we need to filter the key
125// lists to produce the lists that we expect to match the attestations.
126auto kTagsToFilter = {
Shawn Willden7c130392020-12-21 09:58:22 -0700127 Tag::CREATION_DATETIME, //
128 Tag::EC_CURVE,
129 Tag::HARDWARE_TYPE,
130 Tag::INCLUDE_UNIQUE_ID,
131};
132
133AuthorizationSet filtered_tags(const AuthorizationSet& set) {
134 AuthorizationSet filtered;
135 std::remove_copy_if(
136 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
137 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
138 kTagsToFilter.end();
139 });
140 return filtered;
141}
142
143string x509NameToStr(X509_NAME* name) {
144 char* s = X509_NAME_oneline(name, nullptr, 0);
145 string retval(s);
146 OPENSSL_free(s);
147 return retval;
148}
149
Shawn Willden7f424372021-01-10 18:06:50 -0700150} // namespace
151
Shawn Willden7c130392020-12-21 09:58:22 -0700152bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
153bool KeyMintAidlTestBase::dump_Attestations = false;
154
Janis Danisevskis24c04702020-12-16 18:28:39 -0800155ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700156 if (result.isOk()) return ErrorCode::OK;
157
Janis Danisevskis24c04702020-12-16 18:28:39 -0800158 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
159 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700160 }
161
162 return ErrorCode::UNKNOWN_ERROR;
163}
164
Janis Danisevskis24c04702020-12-16 18:28:39 -0800165void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700166 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800167 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700168
169 KeyMintHardwareInfo info;
170 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
171
172 securityLevel_ = info.securityLevel;
173 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
174 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100175 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700176
177 os_version_ = getOsVersion();
178 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100179 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700180}
181
182void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800183 if (AServiceManager_isDeclared(GetParam().c_str())) {
184 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
185 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
186 } else {
187 InitializeKeyMint(nullptr);
188 }
Selene Huang31ab4042020-04-29 04:22:39 -0700189}
190
191ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700192 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700193 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700194 vector<KeyCharacteristics>* key_characteristics,
195 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700196 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
197 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700198 << "Previous characteristics not deleted before generating key. Test bug.";
199
Shawn Willden7f424372021-01-10 18:06:50 -0700200 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700201 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700202 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700203 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
204 creationResult.keyCharacteristics);
205 EXPECT_GT(creationResult.keyBlob.size(), 0);
206 *key_blob = std::move(creationResult.keyBlob);
207 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700208 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700209
210 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
211 EXPECT_TRUE(algorithm);
212 if (algorithm &&
213 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700214 EXPECT_GE(cert_chain->size(), 1);
215 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
216 if (attest_key) {
217 EXPECT_EQ(cert_chain->size(), 1);
218 } else {
219 EXPECT_GT(cert_chain->size(), 1);
220 }
221 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700222 } else {
223 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700224 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700225 }
Selene Huang31ab4042020-04-29 04:22:39 -0700226 }
227
228 return GetReturnErrorCode(result);
229}
230
Shawn Willden7c130392020-12-21 09:58:22 -0700231ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
232 const optional<AttestationKey>& attest_key) {
233 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700234}
235
236ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
237 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700238 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700239 Status result;
240
Shawn Willden7f424372021-01-10 18:06:50 -0700241 cert_chain_.clear();
242 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700243 key_blob->clear();
244
Shawn Willden7f424372021-01-10 18:06:50 -0700245 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700246 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700247 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700248 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700249
250 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700251 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
252 creationResult.keyCharacteristics);
253 EXPECT_GT(creationResult.keyBlob.size(), 0);
254
255 *key_blob = std::move(creationResult.keyBlob);
256 *key_characteristics = std::move(creationResult.keyCharacteristics);
257 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700258
259 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
260 EXPECT_TRUE(algorithm);
261 if (algorithm &&
262 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
263 EXPECT_GE(cert_chain_.size(), 1);
264 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
265 } else {
266 // For symmetric keys there should be no certificates.
267 EXPECT_EQ(cert_chain_.size(), 0);
268 }
Selene Huang31ab4042020-04-29 04:22:39 -0700269 }
270
271 return GetReturnErrorCode(result);
272}
273
274ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
275 const string& key_material) {
276 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
277}
278
279ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
280 const AuthorizationSet& wrapping_key_desc,
281 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100282 const AuthorizationSet& unwrapping_params,
283 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700284 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
285
Shawn Willden7f424372021-01-10 18:06:50 -0700286 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700287
Shawn Willden7f424372021-01-10 18:06:50 -0700288 KeyCreationResult creationResult;
289 Status result = keymint_->importWrappedKey(
290 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
291 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100292 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700293
294 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700295 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
296 creationResult.keyCharacteristics);
297 EXPECT_GT(creationResult.keyBlob.size(), 0);
298
299 key_blob_ = std::move(creationResult.keyBlob);
300 key_characteristics_ = std::move(creationResult.keyCharacteristics);
301 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700302
303 AuthorizationSet allAuths;
304 for (auto& entry : key_characteristics_) {
305 allAuths.push_back(AuthorizationSet(entry.authorizations));
306 }
307 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
308 EXPECT_TRUE(algorithm);
309 if (algorithm &&
310 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
311 EXPECT_GE(cert_chain_.size(), 1);
312 } else {
313 // For symmetric keys there should be no certificates.
314 EXPECT_EQ(cert_chain_.size(), 0);
315 }
Selene Huang31ab4042020-04-29 04:22:39 -0700316 }
317
318 return GetReturnErrorCode(result);
319}
320
321ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
322 Status result = keymint_->deleteKey(*key_blob);
323 if (!keep_key_blob) {
324 *key_blob = vector<uint8_t>();
325 }
326
Janis Danisevskis24c04702020-12-16 18:28:39 -0800327 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700328 return GetReturnErrorCode(result);
329}
330
331ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
332 return DeleteKey(&key_blob_, keep_key_blob);
333}
334
335ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
336 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800337 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700338 return GetReturnErrorCode(result);
339}
340
David Drysdaled2cc8c22021-04-15 13:29:45 +0100341ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
342 Status result = keymint_->destroyAttestationIds();
343 return GetReturnErrorCode(result);
344}
345
Selene Huang31ab4042020-04-29 04:22:39 -0700346void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
347 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
348 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
349}
350
351void KeyMintAidlTestBase::CheckedDeleteKey() {
352 CheckedDeleteKey(&key_blob_);
353}
354
355ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
356 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800357 AuthorizationSet* out_params,
358 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700359 SCOPED_TRACE("Begin");
360 Status result;
361 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100362 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700363
364 if (result.isOk()) {
365 *out_params = out.params;
366 challenge_ = out.challenge;
367 op = out.operation;
368 }
369
370 return GetReturnErrorCode(result);
371}
372
373ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
374 const AuthorizationSet& in_params,
375 AuthorizationSet* out_params) {
376 SCOPED_TRACE("Begin");
377 Status result;
378 BeginResult out;
379
David Drysdale56ba9122021-04-19 19:10:47 +0100380 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700381
382 if (result.isOk()) {
383 *out_params = out.params;
384 challenge_ = out.challenge;
385 op_ = out.operation;
386 }
387
388 return GetReturnErrorCode(result);
389}
390
391ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
392 AuthorizationSet* out_params) {
393 SCOPED_TRACE("Begin");
394 EXPECT_EQ(nullptr, op_);
395 return Begin(purpose, key_blob_, in_params, out_params);
396}
397
398ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
399 SCOPED_TRACE("Begin");
400 AuthorizationSet out_params;
401 ErrorCode result = Begin(purpose, in_params, &out_params);
402 EXPECT_TRUE(out_params.empty());
403 return result;
404}
405
Shawn Willden92d79c02021-02-19 07:31:55 -0700406ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
407 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
408 {} /* hardwareAuthToken */,
409 {} /* verificationToken */));
410}
411
412ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700413 SCOPED_TRACE("Update");
414
415 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700416 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700417
Shawn Willden92d79c02021-02-19 07:31:55 -0700418 std::vector<uint8_t> o_put;
419 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700420
Shawn Willden92d79c02021-02-19 07:31:55 -0700421 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700422
423 return GetReturnErrorCode(result);
424}
425
Shawn Willden92d79c02021-02-19 07:31:55 -0700426ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700427 string* output) {
428 SCOPED_TRACE("Finish");
429 Status result;
430
431 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700432 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700433
434 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700435 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
436 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
437 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700438
Shawn Willden92d79c02021-02-19 07:31:55 -0700439 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700440
Shawn Willden92d79c02021-02-19 07:31:55 -0700441 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700442 return GetReturnErrorCode(result);
443}
444
Janis Danisevskis24c04702020-12-16 18:28:39 -0800445ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700446 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();
452 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800453 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700454}
455
456ErrorCode KeyMintAidlTestBase::Abort() {
457 SCOPED_TRACE("Abort");
458
459 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700460 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700461
462 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800463 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700464}
465
466void KeyMintAidlTestBase::AbortIfNeeded() {
467 SCOPED_TRACE("AbortIfNeeded");
468 if (op_) {
469 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800470 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700471 }
472}
473
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000474auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
475 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700476 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000477 AuthorizationSet begin_out_params;
478 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700479 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000480
481 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700482 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000483}
484
Selene Huang31ab4042020-04-29 04:22:39 -0700485string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
486 const string& message, const AuthorizationSet& in_params,
487 AuthorizationSet* out_params) {
488 SCOPED_TRACE("ProcessMessage");
489 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700490 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700491 EXPECT_EQ(ErrorCode::OK, result);
492 if (result != ErrorCode::OK) {
493 return "";
494 }
495
496 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700497 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700498 return output;
499}
500
501string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
502 const AuthorizationSet& params) {
503 SCOPED_TRACE("SignMessage");
504 AuthorizationSet out_params;
505 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
506 EXPECT_TRUE(out_params.empty());
507 return signature;
508}
509
510string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
511 SCOPED_TRACE("SignMessage");
512 return SignMessage(key_blob_, message, params);
513}
514
515string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
516 SCOPED_TRACE("MacMessage");
517 return SignMessage(
518 key_blob_, message,
519 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
520}
521
522void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
523 Digest digest, const string& expected_mac) {
524 SCOPED_TRACE("CheckHmacTestVector");
525 ASSERT_EQ(ErrorCode::OK,
526 ImportKey(AuthorizationSetBuilder()
527 .Authorization(TAG_NO_AUTH_REQUIRED)
528 .HmacKey(key.size() * 8)
529 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
530 .Digest(digest),
531 KeyFormat::RAW, key));
532 string signature = MacMessage(message, digest, expected_mac.size() * 8);
533 EXPECT_EQ(expected_mac, signature)
534 << "Test vector didn't match for key of size " << key.size() << " message of size "
535 << message.size() << " and digest " << digest;
536 CheckedDeleteKey();
537}
538
539void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
540 const string& message,
541 const string& expected_ciphertext) {
542 SCOPED_TRACE("CheckAesCtrTestVector");
543 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
544 .Authorization(TAG_NO_AUTH_REQUIRED)
545 .AesEncryptionKey(key.size() * 8)
546 .BlockMode(BlockMode::CTR)
547 .Authorization(TAG_CALLER_NONCE)
548 .Padding(PaddingMode::NONE),
549 KeyFormat::RAW, key));
550
551 auto params = AuthorizationSetBuilder()
552 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
553 .BlockMode(BlockMode::CTR)
554 .Padding(PaddingMode::NONE);
555 AuthorizationSet out_params;
556 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
557 EXPECT_EQ(expected_ciphertext, ciphertext);
558}
559
560void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
561 PaddingMode padding_mode, const string& key,
562 const string& iv, const string& input,
563 const string& expected_output) {
564 auto authset = AuthorizationSetBuilder()
565 .TripleDesEncryptionKey(key.size() * 7)
566 .BlockMode(block_mode)
567 .Authorization(TAG_NO_AUTH_REQUIRED)
568 .Padding(padding_mode);
569 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
570 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
571 ASSERT_GT(key_blob_.size(), 0U);
572
573 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
574 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
575 AuthorizationSet output_params;
576 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
577 EXPECT_EQ(expected_output, output);
578}
579
580void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
581 const string& signature, const AuthorizationSet& params) {
582 SCOPED_TRACE("VerifyMessage");
583 AuthorizationSet begin_out_params;
584 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
585
586 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700587 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700588 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700589 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700590}
591
592void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
593 const AuthorizationSet& params) {
594 SCOPED_TRACE("VerifyMessage");
595 VerifyMessage(key_blob_, message, signature, params);
596}
597
David Drysdaledf8f52e2021-05-06 08:10:58 +0100598void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
599 const AuthorizationSet& params) {
600 SCOPED_TRACE("LocalVerifyMessage");
601
602 // Retrieve the public key from the leaf certificate.
603 ASSERT_GT(cert_chain_.size(), 0);
604 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
605 ASSERT_TRUE(key_cert.get());
606 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
607 ASSERT_TRUE(pub_key.get());
608
609 Digest digest = params.GetTagValue(TAG_DIGEST).value();
610 PaddingMode padding = PaddingMode::NONE;
611 auto tag = params.GetTagValue(TAG_PADDING);
612 if (tag.has_value()) {
613 padding = tag.value();
614 }
615
616 if (digest == Digest::NONE) {
617 switch (EVP_PKEY_id(pub_key.get())) {
618 case EVP_PKEY_EC: {
619 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
620 size_t data_size = std::min(data.size(), message.size());
621 memcpy(data.data(), message.data(), data_size);
622 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
623 ASSERT_TRUE(ecdsa.get());
624 ASSERT_EQ(1,
625 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
626 reinterpret_cast<const uint8_t*>(signature.data()),
627 signature.size(), ecdsa.get()));
628 break;
629 }
630 case EVP_PKEY_RSA: {
631 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
632 size_t data_size = std::min(data.size(), message.size());
633 memcpy(data.data(), message.data(), data_size);
634
635 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
636 ASSERT_TRUE(rsa.get());
637
638 size_t key_len = RSA_size(rsa.get());
639 int openssl_padding = RSA_NO_PADDING;
640 switch (padding) {
641 case PaddingMode::NONE:
642 ASSERT_TRUE(data_size <= key_len);
643 ASSERT_EQ(key_len, signature.size());
644 openssl_padding = RSA_NO_PADDING;
645 break;
646 case PaddingMode::RSA_PKCS1_1_5_SIGN:
647 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
648 key_len);
649 openssl_padding = RSA_PKCS1_PADDING;
650 break;
651 default:
652 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
653 }
654
655 vector<uint8_t> decrypted_data(key_len);
656 int bytes_decrypted = RSA_public_decrypt(
657 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
658 decrypted_data.data(), rsa.get(), openssl_padding);
659 ASSERT_GE(bytes_decrypted, 0);
660
661 const uint8_t* compare_pos = decrypted_data.data();
662 size_t bytes_to_compare = bytes_decrypted;
663 uint8_t zero_check_result = 0;
664 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
665 // If the data is short, for "unpadded" signing we zero-pad to the left. So
666 // during verification we should have zeros on the left of the decrypted data.
667 // Do a constant-time check.
668 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
669 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
670 ASSERT_EQ(0, zero_check_result);
671 bytes_to_compare = data_size;
672 }
673 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
674 break;
675 }
676 default:
677 ADD_FAILURE() << "Unknown public key type";
678 }
679 } else {
680 EVP_MD_CTX digest_ctx;
681 EVP_MD_CTX_init(&digest_ctx);
682 EVP_PKEY_CTX* pkey_ctx;
683 const EVP_MD* md = openssl_digest(digest);
684 ASSERT_NE(md, nullptr);
685 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
686
687 if (padding == PaddingMode::RSA_PSS) {
688 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
689 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
690 }
691
692 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
693 reinterpret_cast<const uint8_t*>(message.data()),
694 message.size()));
695 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
696 reinterpret_cast<const uint8_t*>(signature.data()),
697 signature.size()));
698 EVP_MD_CTX_cleanup(&digest_ctx);
699 }
700}
701
Selene Huang31ab4042020-04-29 04:22:39 -0700702string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
703 const AuthorizationSet& in_params,
704 AuthorizationSet* out_params) {
705 SCOPED_TRACE("EncryptMessage");
706 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
707}
708
709string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
710 AuthorizationSet* out_params) {
711 SCOPED_TRACE("EncryptMessage");
712 return EncryptMessage(key_blob_, message, params, out_params);
713}
714
715string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
716 SCOPED_TRACE("EncryptMessage");
717 AuthorizationSet out_params;
718 string ciphertext = EncryptMessage(message, params, &out_params);
719 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
720 return ciphertext;
721}
722
723string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
724 PaddingMode padding) {
725 SCOPED_TRACE("EncryptMessage");
726 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
727 AuthorizationSet out_params;
728 string ciphertext = EncryptMessage(message, params, &out_params);
729 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
730 return ciphertext;
731}
732
733string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
734 PaddingMode padding, vector<uint8_t>* iv_out) {
735 SCOPED_TRACE("EncryptMessage");
736 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
737 AuthorizationSet out_params;
738 string ciphertext = EncryptMessage(message, params, &out_params);
739 EXPECT_EQ(1U, out_params.size());
740 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800741 EXPECT_TRUE(ivVal);
742 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700743 return ciphertext;
744}
745
746string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
747 PaddingMode padding, const vector<uint8_t>& iv_in) {
748 SCOPED_TRACE("EncryptMessage");
749 auto params = AuthorizationSetBuilder()
750 .BlockMode(block_mode)
751 .Padding(padding)
752 .Authorization(TAG_NONCE, iv_in);
753 AuthorizationSet out_params;
754 string ciphertext = EncryptMessage(message, params, &out_params);
755 return ciphertext;
756}
757
758string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
759 PaddingMode padding, uint8_t mac_length_bits,
760 const vector<uint8_t>& iv_in) {
761 SCOPED_TRACE("EncryptMessage");
762 auto params = AuthorizationSetBuilder()
763 .BlockMode(block_mode)
764 .Padding(padding)
765 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
766 .Authorization(TAG_NONCE, iv_in);
767 AuthorizationSet out_params;
768 string ciphertext = EncryptMessage(message, params, &out_params);
769 return ciphertext;
770}
771
David Drysdaled2cc8c22021-04-15 13:29:45 +0100772string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
773 PaddingMode padding, uint8_t mac_length_bits) {
774 SCOPED_TRACE("EncryptMessage");
775 auto params = AuthorizationSetBuilder()
776 .BlockMode(block_mode)
777 .Padding(padding)
778 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
779 AuthorizationSet out_params;
780 string ciphertext = EncryptMessage(message, params, &out_params);
781 return ciphertext;
782}
783
Selene Huang31ab4042020-04-29 04:22:39 -0700784string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
785 const string& ciphertext,
786 const AuthorizationSet& params) {
787 SCOPED_TRACE("DecryptMessage");
788 AuthorizationSet out_params;
789 string plaintext =
790 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
791 EXPECT_TRUE(out_params.empty());
792 return plaintext;
793}
794
795string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
796 const AuthorizationSet& params) {
797 SCOPED_TRACE("DecryptMessage");
798 return DecryptMessage(key_blob_, ciphertext, params);
799}
800
801string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
802 PaddingMode padding_mode, const vector<uint8_t>& iv) {
803 SCOPED_TRACE("DecryptMessage");
804 auto params = AuthorizationSetBuilder()
805 .BlockMode(block_mode)
806 .Padding(padding_mode)
807 .Authorization(TAG_NONCE, iv);
808 return DecryptMessage(key_blob_, ciphertext, params);
809}
810
811std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
812 const vector<uint8_t>& key_blob) {
813 std::pair<ErrorCode, vector<uint8_t>> retval;
814 vector<uint8_t> outKeyBlob;
815 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
816 ErrorCode errorcode = GetReturnErrorCode(result);
817 retval = std::tie(errorcode, outKeyBlob);
818
819 return retval;
820}
821vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
822 switch (algorithm) {
823 case Algorithm::RSA:
824 switch (SecLevel()) {
825 case SecurityLevel::SOFTWARE:
826 case SecurityLevel::TRUSTED_ENVIRONMENT:
827 return {2048, 3072, 4096};
828 case SecurityLevel::STRONGBOX:
829 return {2048};
830 default:
831 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
832 break;
833 }
834 break;
835 case Algorithm::EC:
836 switch (SecLevel()) {
837 case SecurityLevel::SOFTWARE:
838 case SecurityLevel::TRUSTED_ENVIRONMENT:
839 return {224, 256, 384, 521};
840 case SecurityLevel::STRONGBOX:
841 return {256};
842 default:
843 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
844 break;
845 }
846 break;
847 case Algorithm::AES:
848 return {128, 256};
849 case Algorithm::TRIPLE_DES:
850 return {168};
851 case Algorithm::HMAC: {
852 vector<uint32_t> retval((512 - 64) / 8 + 1);
853 uint32_t size = 64 - 8;
854 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
855 return retval;
856 }
857 default:
858 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
859 return {};
860 }
861 ADD_FAILURE() << "Should be impossible to get here";
862 return {};
863}
864
865vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
866 if (SecLevel() == SecurityLevel::STRONGBOX) {
867 switch (algorithm) {
868 case Algorithm::RSA:
869 return {3072, 4096};
870 case Algorithm::EC:
871 return {224, 384, 521};
872 case Algorithm::AES:
873 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +0000874 case Algorithm::TRIPLE_DES:
875 return {56};
876 default:
877 return {};
878 }
879 } else {
880 switch (algorithm) {
881 case Algorithm::TRIPLE_DES:
882 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -0700883 default:
884 return {};
885 }
886 }
887 return {};
888}
889
David Drysdale7de9feb2021-03-05 14:56:19 +0000890vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
891 switch (algorithm) {
892 case Algorithm::AES:
893 return {
894 BlockMode::CBC,
895 BlockMode::CTR,
896 BlockMode::ECB,
897 BlockMode::GCM,
898 };
899 case Algorithm::TRIPLE_DES:
900 return {
901 BlockMode::CBC,
902 BlockMode::ECB,
903 };
904 default:
905 return {};
906 }
907}
908
909vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
910 BlockMode blockMode) {
911 switch (algorithm) {
912 case Algorithm::AES:
913 switch (blockMode) {
914 case BlockMode::CBC:
915 case BlockMode::ECB:
916 return {PaddingMode::NONE, PaddingMode::PKCS7};
917 case BlockMode::CTR:
918 case BlockMode::GCM:
919 return {PaddingMode::NONE};
920 default:
921 return {};
922 };
923 case Algorithm::TRIPLE_DES:
924 switch (blockMode) {
925 case BlockMode::CBC:
926 case BlockMode::ECB:
927 return {PaddingMode::NONE, PaddingMode::PKCS7};
928 default:
929 return {};
930 };
931 default:
932 return {};
933 }
934}
935
936vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
937 BlockMode blockMode) {
938 switch (algorithm) {
939 case Algorithm::AES:
940 switch (blockMode) {
941 case BlockMode::CTR:
942 case BlockMode::GCM:
943 return {PaddingMode::PKCS7};
944 default:
945 return {};
946 };
947 default:
948 return {};
949 }
950}
951
Selene Huang31ab4042020-04-29 04:22:39 -0700952vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
953 if (securityLevel_ == SecurityLevel::STRONGBOX) {
954 return {EcCurve::P_256};
955 } else {
956 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
957 }
958}
959
960vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
961 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
962 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
963 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
964}
965
966vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
967 switch (SecLevel()) {
968 case SecurityLevel::SOFTWARE:
969 case SecurityLevel::TRUSTED_ENVIRONMENT:
970 if (withNone) {
971 if (withMD5)
972 return {Digest::NONE, Digest::MD5, Digest::SHA1,
973 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
974 Digest::SHA_2_512};
975 else
976 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
977 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
978 } else {
979 if (withMD5)
980 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
981 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
982 else
983 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
984 Digest::SHA_2_512};
985 }
986 break;
987 case SecurityLevel::STRONGBOX:
988 if (withNone)
989 return {Digest::NONE, Digest::SHA_2_256};
990 else
991 return {Digest::SHA_2_256};
992 break;
993 default:
994 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
995 break;
996 }
997 ADD_FAILURE() << "Should be impossible to get here";
998 return {};
999}
1000
Shawn Willden7f424372021-01-10 18:06:50 -07001001static const vector<KeyParameter> kEmptyAuthList{};
1002
1003const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1004 const vector<KeyCharacteristics>& key_characteristics) {
1005 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1006 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1007 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1008}
1009
Qi Wubeefae42021-01-28 23:16:37 +08001010const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1011 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1012 auto found = std::find_if(
1013 key_characteristics.begin(), key_characteristics.end(),
1014 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001015 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1016}
1017
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001018ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001019 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001020 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1021 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1022 return result;
1023}
1024
1025ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001026 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001027 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1028 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1029 return result;
1030}
1031
1032ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1033 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001034 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001035 rsaKeyBlob, KeyPurpose::SIGN, message,
1036 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1037 return result;
1038}
1039
1040ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001041 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1042 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001043 return result;
1044}
1045
Selene Huang6e46f142021-04-20 19:20:11 -07001046void verify_serial(X509* cert, const uint64_t expected_serial) {
1047 BIGNUM_Ptr ser(BN_new());
1048 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1049
1050 uint64_t serial;
1051 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1052 EXPECT_EQ(serial, expected_serial);
1053}
1054
1055// Please set self_signed to true for fake certificates or self signed
1056// certificates
1057void verify_subject(const X509* cert, //
1058 const string& subject, //
1059 bool self_signed) {
1060 char* cert_issuer = //
1061 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1062
1063 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1064
1065 string expected_subject("/CN=");
1066 if (subject.empty()) {
1067 expected_subject.append("Android Keystore Key");
1068 } else {
1069 expected_subject.append(subject);
1070 }
1071
1072 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1073
1074 if (self_signed) {
1075 EXPECT_STREQ(cert_issuer, cert_subj)
1076 << "Cert issuer and subject mismatch for self signed certificate.";
1077 }
1078
1079 OPENSSL_free(cert_subj);
1080 OPENSSL_free(cert_issuer);
1081}
1082
1083vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1084 BIGNUM_Ptr serial(BN_new());
1085 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1086
1087 int len = BN_num_bytes(serial.get());
1088 vector<uint8_t> serial_blob(len);
1089 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1090 return {};
1091 }
1092
1093 return serial_blob;
1094}
1095
1096void verify_subject_and_serial(const Certificate& certificate, //
1097 const uint64_t expected_serial, //
1098 const string& subject, bool self_signed) {
1099 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1100 ASSERT_TRUE(!!cert.get());
1101
1102 verify_serial(cert.get(), expected_serial);
1103 verify_subject(cert.get(), subject, self_signed);
1104}
1105
Shawn Willden7c130392020-12-21 09:58:22 -07001106bool verify_attestation_record(const string& challenge, //
1107 const string& app_id, //
1108 AuthorizationSet expected_sw_enforced, //
1109 AuthorizationSet expected_hw_enforced, //
1110 SecurityLevel security_level,
1111 const vector<uint8_t>& attestation_cert) {
1112 X509_Ptr cert(parse_cert_blob(attestation_cert));
1113 EXPECT_TRUE(!!cert.get());
1114 if (!cert.get()) return false;
1115
1116 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1117 EXPECT_TRUE(!!attest_rec);
1118 if (!attest_rec) return false;
1119
1120 AuthorizationSet att_sw_enforced;
1121 AuthorizationSet att_hw_enforced;
1122 uint32_t att_attestation_version;
1123 uint32_t att_keymaster_version;
1124 SecurityLevel att_attestation_security_level;
1125 SecurityLevel att_keymaster_security_level;
1126 vector<uint8_t> att_challenge;
1127 vector<uint8_t> att_unique_id;
1128 vector<uint8_t> att_app_id;
1129
1130 auto error = parse_attestation_record(attest_rec->data, //
1131 attest_rec->length, //
1132 &att_attestation_version, //
1133 &att_attestation_security_level, //
1134 &att_keymaster_version, //
1135 &att_keymaster_security_level, //
1136 &att_challenge, //
1137 &att_sw_enforced, //
1138 &att_hw_enforced, //
1139 &att_unique_id);
1140 EXPECT_EQ(ErrorCode::OK, error);
1141 if (error != ErrorCode::OK) return false;
1142
Shawn Willden3cb64a62021-04-05 14:39:05 -06001143 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -07001144 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001145
Selene Huang4f64c222021-04-13 19:54:36 -07001146 // check challenge and app id only if we expects a non-fake certificate
1147 if (challenge.length() > 0) {
1148 EXPECT_EQ(challenge.length(), att_challenge.size());
1149 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1150
1151 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1152 }
Shawn Willden7c130392020-12-21 09:58:22 -07001153
Shawn Willden3cb64a62021-04-05 14:39:05 -06001154 EXPECT_EQ(att_keymaster_version, 100U);
Shawn Willden7c130392020-12-21 09:58:22 -07001155 EXPECT_EQ(security_level, att_keymaster_security_level);
1156 EXPECT_EQ(security_level, att_attestation_security_level);
1157
Shawn Willden7c130392020-12-21 09:58:22 -07001158
1159 char property_value[PROPERTY_VALUE_MAX] = {};
1160 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
1161 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
1162 // for the BOOT_PATCH_LEVEL.
1163 if (avb_verification_enabled()) {
1164 for (int i = 0; i < att_hw_enforced.size(); i++) {
1165 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1166 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1167 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001168 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -07001169 // strptime seems to require delimiters, but the tag value will
1170 // be YYYYMMDD
1171 date.insert(6, "-");
1172 date.insert(4, "-");
1173 EXPECT_EQ(date.size(), 10);
1174 struct tm time;
1175 strptime(date.c_str(), "%Y-%m-%d", &time);
1176
1177 // Day of the month (0-31)
1178 EXPECT_GE(time.tm_mday, 0);
1179 EXPECT_LT(time.tm_mday, 32);
1180 // Months since Jan (0-11)
1181 EXPECT_GE(time.tm_mon, 0);
1182 EXPECT_LT(time.tm_mon, 12);
1183 // Years since 1900
1184 EXPECT_GT(time.tm_year, 110);
1185 EXPECT_LT(time.tm_year, 200);
1186 }
1187 }
1188 }
1189
1190 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1191 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1192 // indicates correct encoding. No need to check if it's in both lists, since the
1193 // AuthorizationSet compare below will handle mismatches of tags.
1194 if (security_level == SecurityLevel::SOFTWARE) {
1195 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1196 } else {
1197 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1198 }
1199
1200 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
1201 // the authorization list during key generation) isn't being attested to in the certificate.
1202 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1203 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1204 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1205 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1206
1207 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1208 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1209 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1210 att_hw_enforced.Contains(TAG_KEY_SIZE));
1211 }
1212
1213 // Test root of trust elements
1214 vector<uint8_t> verified_boot_key;
1215 VerifiedBoot verified_boot_state;
1216 bool device_locked;
1217 vector<uint8_t> verified_boot_hash;
1218 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1219 &verified_boot_state, &device_locked, &verified_boot_hash);
1220 EXPECT_EQ(ErrorCode::OK, error);
1221
1222 if (avb_verification_enabled()) {
1223 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1224 string prop_string(property_value);
1225 EXPECT_EQ(prop_string.size(), 64);
1226 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1227
1228 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1229 if (!strcmp(property_value, "unlocked")) {
1230 EXPECT_FALSE(device_locked);
1231 } else {
1232 EXPECT_TRUE(device_locked);
1233 }
1234
1235 // Check that the device is locked if not debuggable, e.g., user build
1236 // images in CTS. For VTS, debuggable images are used to allow adb root
1237 // and the device is unlocked.
1238 if (!property_get_bool("ro.debuggable", false)) {
1239 EXPECT_TRUE(device_locked);
1240 } else {
1241 EXPECT_FALSE(device_locked);
1242 }
1243 }
1244
1245 // Verified boot key should be all 0's if the boot state is not verified or self signed
1246 std::string empty_boot_key(32, '\0');
1247 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1248 verified_boot_key.size());
1249 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1250 if (!strcmp(property_value, "green")) {
1251 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1252 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1253 verified_boot_key.size()));
1254 } else if (!strcmp(property_value, "yellow")) {
1255 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1256 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1257 verified_boot_key.size()));
1258 } else if (!strcmp(property_value, "orange")) {
1259 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1260 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1261 verified_boot_key.size()));
1262 } else if (!strcmp(property_value, "red")) {
1263 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1264 } else {
1265 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1266 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1267 verified_boot_key.size()));
1268 }
1269
1270 att_sw_enforced.Sort();
1271 expected_sw_enforced.Sort();
1272 auto a = filtered_tags(expected_sw_enforced);
1273 auto b = filtered_tags(att_sw_enforced);
1274 EXPECT_EQ(a, b);
1275
1276 att_hw_enforced.Sort();
1277 expected_hw_enforced.Sort();
1278 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1279
1280 return true;
1281}
1282
1283string bin2hex(const vector<uint8_t>& data) {
1284 string retval;
1285 retval.reserve(data.size() * 2 + 1);
1286 for (uint8_t byte : data) {
1287 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1288 retval.push_back(nibble2hex[0x0F & byte]);
1289 }
1290 return retval;
1291}
1292
David Drysdalef0d516d2021-03-22 07:51:43 +00001293AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1294 AuthorizationSet authList;
1295 for (auto& entry : key_characteristics) {
1296 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1297 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1298 authList.push_back(AuthorizationSet(entry.authorizations));
1299 }
1300 }
1301 return authList;
1302}
1303
1304AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1305 AuthorizationSet authList;
1306 for (auto& entry : key_characteristics) {
1307 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1308 entry.securityLevel == SecurityLevel::KEYSTORE) {
1309 authList.push_back(AuthorizationSet(entry.authorizations));
1310 }
1311 }
1312 return authList;
1313}
1314
Shawn Willden7c130392020-12-21 09:58:22 -07001315AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1316 std::stringstream cert_data;
1317
1318 for (size_t i = 0; i < chain.size(); ++i) {
1319 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1320
1321 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1322 X509_Ptr signing_cert;
1323 if (i < chain.size() - 1) {
1324 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1325 } else {
1326 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1327 }
1328 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1329
1330 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1331 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1332
1333 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1334 return AssertionFailure()
1335 << "Verification of certificate " << i << " failed "
1336 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1337 << cert_data.str();
1338 }
1339
1340 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1341 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1342 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001343 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1344 << " Signer subject is " << signer_subj
1345 << " Issuer subject is " << cert_issuer << endl
1346 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001347 }
Shawn Willden7c130392020-12-21 09:58:22 -07001348 }
1349
1350 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1351 return AssertionSuccess();
1352}
1353
1354X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1355 const uint8_t* p = blob.data();
1356 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1357}
1358
David Drysdalef0d516d2021-03-22 07:51:43 +00001359vector<uint8_t> make_name_from_str(const string& name) {
1360 X509_NAME_Ptr x509_name(X509_NAME_new());
1361 EXPECT_TRUE(x509_name.get() != nullptr);
1362 if (!x509_name) return {};
1363
1364 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1365 "CN", //
1366 MBSTRING_ASC,
1367 reinterpret_cast<const uint8_t*>(name.c_str()),
1368 -1, // len
1369 -1, // loc
1370 0 /* set */));
1371
1372 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1373 EXPECT_GT(len, 0);
1374
1375 vector<uint8_t> retval(len);
1376 uint8_t* p = retval.data();
1377 i2d_X509_NAME(x509_name.get(), &p);
1378
1379 return retval;
1380}
1381
David Drysdale4dc01072021-04-01 12:17:35 +01001382namespace {
1383
1384void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1385 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1386 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1387
1388 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1389 if (testMode) {
1390 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1391 MatchesRegex("{\n"
1392 " 1 : 2,\n" // kty: EC2
1393 " 3 : -7,\n" // alg: ES256
1394 " -1 : 1,\n" // EC id: P256
1395 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1396 // sequence of 32 hexadecimal bytes, enclosed in braces and
1397 // separated by commas. In this case, some Ed25519 public key.
1398 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1399 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1400 " -70000 : null,\n" // test marker
1401 "}"));
1402 } else {
1403 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1404 MatchesRegex("{\n"
1405 " 1 : 2,\n" // kty: EC2
1406 " 3 : -7,\n" // alg: ES256
1407 " -1 : 1,\n" // EC id: P256
1408 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1409 // sequence of 32 hexadecimal bytes, enclosed in braces and
1410 // separated by commas. In this case, some Ed25519 public key.
1411 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1412 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1413 "}"));
1414 }
1415}
1416
1417} // namespace
1418
1419void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1420 vector<uint8_t>* payload_value) {
1421 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1422 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1423
1424 ASSERT_NE(coseMac0->asArray(), nullptr);
1425 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1426
1427 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1428 ASSERT_NE(protParms, nullptr);
1429
1430 // Header label:value of 'alg': HMAC-256
1431 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1432
1433 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1434 ASSERT_NE(unprotParms, nullptr);
1435 ASSERT_EQ(unprotParms->size(), 0);
1436
1437 // The payload is a bstr holding an encoded COSE_Key
1438 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1439 ASSERT_NE(payload, nullptr);
1440 check_cose_key(payload->value(), testMode);
1441
1442 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1443 ASSERT_TRUE(coseMac0Tag);
1444 auto extractedTag = coseMac0Tag->value();
1445 EXPECT_EQ(extractedTag.size(), 32U);
1446
1447 // Compare with tag generated with kTestMacKey. Should only match in test mode
1448 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
1449 payload->value());
1450 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1451
1452 if (testMode) {
1453 EXPECT_EQ(*testTag, extractedTag);
1454 } else {
1455 EXPECT_NE(*testTag, extractedTag);
1456 }
1457 if (payload_value != nullptr) {
1458 *payload_value = payload->value();
1459 }
1460}
1461
1462void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1463 // Extract x and y affine coordinates from the encoded Cose_Key.
1464 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1465 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1466 auto coseKey = parsedPayload->asMap();
1467 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1468 ASSERT_NE(xItem->asBstr(), nullptr);
1469 vector<uint8_t> x = xItem->asBstr()->value();
1470 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1471 ASSERT_NE(yItem->asBstr(), nullptr);
1472 vector<uint8_t> y = yItem->asBstr()->value();
1473
1474 // Concatenate: 0x04 (uncompressed form marker) | x | y
1475 vector<uint8_t> pubKeyData{0x04};
1476 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1477 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1478
1479 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1480 ASSERT_NE(ecKey, nullptr);
1481 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1482 ASSERT_NE(group, nullptr);
1483 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1484 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1485 ASSERT_NE(point, nullptr);
1486 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1487 nullptr),
1488 1);
1489 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1490
1491 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1492 ASSERT_NE(pubKey, nullptr);
1493 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1494 *signingKey = std::move(pubKey);
1495}
1496
Selene Huang31ab4042020-04-29 04:22:39 -07001497} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001498
Janis Danisevskis24c04702020-12-16 18:28:39 -08001499} // namespace aidl::android::hardware::security::keymint