blob: f9510d3071c00a258ce7de5aba548ed39d00d08e [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>
David Drysdale42fe1892021-10-14 14:43:46 +010028#include <openssl/evp.h>
Shawn Willden7c130392020-12-21 09:58:22 -070029#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010030#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070031
Max Bires9704ff62021-04-07 11:12:01 -070032#include <keymaster/cppcose/cppcose.h>
Shawn Willden7c130392020-12-21 09:58:22 -070033#include <keymint_support/attestation_record.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000034#include <keymint_support/key_param_output.h>
35#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070036#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Janis Danisevskis24c04702020-12-16 18:28:39 -080038namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070039
David Drysdale4dc01072021-04-01 12:17:35 +010040using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070041using namespace std::literals::chrono_literals;
42using std::endl;
43using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070044using std::unique_ptr;
45using ::testing::AssertionFailure;
46using ::testing::AssertionResult;
47using ::testing::AssertionSuccess;
Seth Moore026bb742021-04-30 11:41:18 -070048using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010049using ::testing::MatchesRegex;
Seth Moore026bb742021-04-30 11:41:18 -070050using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070051
52::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
53 if (set.size() == 0)
54 os << "(Empty)" << ::std::endl;
55 else {
56 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070057 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070058 }
59 return os;
60}
61
62namespace test {
63
Shawn Willden7f424372021-01-10 18:06:50 -070064namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010065
David Drysdale37af4b32021-05-14 16:46:59 +010066// Invalid value for a patchlevel (which is of form YYYYMMDD).
67const uint32_t kInvalidPatchlevel = 99998877;
68
David Drysdaledf8f52e2021-05-06 08:10:58 +010069// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
70// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
71const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
72
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000073typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070074// Predicate for testing basic characteristics validity in generation or import.
75bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
76 const vector<KeyCharacteristics>& key_characteristics) {
77 if (key_characteristics.empty()) return false;
78
79 std::unordered_set<SecurityLevel> levels_seen;
80 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070081 if (entry.authorizations.empty()) {
82 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
83 return false;
84 }
Shawn Willden7f424372021-01-10 18:06:50 -070085
Qi Wubeefae42021-01-28 23:16:37 +080086 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
87 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
88
Seth Moore2a9a00e2021-08-04 16:31:52 -070089 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
90 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
91 return false;
92 }
Shawn Willden7f424372021-01-10 18:06:50 -070093 levels_seen.insert(entry.securityLevel);
94
95 // Generally, we should only have one entry, at the same security level as the KM
96 // instance. There is an exception: StrongBox KM can have some authorizations that are
97 // enforced by the TEE.
98 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
99 (secLevel == SecurityLevel::STRONGBOX &&
100 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
101
Seth Moore2a9a00e2021-08-04 16:31:52 -0700102 if (!isExpectedSecurityLevel) {
103 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
104 return false;
105 }
Shawn Willden7f424372021-01-10 18:06:50 -0700106 }
107 return true;
108}
109
Shawn Willden7c130392020-12-21 09:58:22 -0700110// Extract attestation record from cert. Returned object is still part of cert; don't free it
111// separately.
112ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
113 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
114 EXPECT_TRUE(!!oid.get());
115 if (!oid.get()) return nullptr;
116
117 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
118 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
119 if (location == -1) return nullptr;
120
121 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
122 EXPECT_TRUE(!!attest_rec_ext)
123 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
124 if (!attest_rec_ext) return nullptr;
125
126 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
127 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
128 return attest_rec;
129}
130
David Drysdale7dff4fc2021-12-10 10:10:52 +0000131void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
132 // Version numbers in attestation extensions should be a multiple of 100.
133 EXPECT_EQ(attestation_version % 100, 0);
134
135 // The multiplier should never be higher than the AIDL version, but can be less
136 // (for example, if the implementation is from an earlier version but the HAL service
137 // uses the default libraries and so reports the current AIDL version).
138 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
139}
140
Shawn Willden7c130392020-12-21 09:58:22 -0700141bool avb_verification_enabled() {
142 char value[PROPERTY_VALUE_MAX];
143 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
144}
145
146char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
147 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
148
149// Attestations don't contain everything in key authorization lists, so we need to filter the key
150// lists to produce the lists that we expect to match the attestations.
151auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100152 Tag::CREATION_DATETIME,
153 Tag::HARDWARE_TYPE,
154 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700155};
156
157AuthorizationSet filtered_tags(const AuthorizationSet& set) {
158 AuthorizationSet filtered;
159 std::remove_copy_if(
160 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
161 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
162 kTagsToFilter.end();
163 });
164 return filtered;
165}
166
David Drysdale300b5552021-05-20 12:05:26 +0100167// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
168void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
169 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
170 [](const auto& entry) {
171 return entry.securityLevel == SecurityLevel::KEYSTORE;
172 }),
173 characteristics->end());
174}
175
Shawn Willden7c130392020-12-21 09:58:22 -0700176string x509NameToStr(X509_NAME* name) {
177 char* s = X509_NAME_oneline(name, nullptr, 0);
178 string retval(s);
179 OPENSSL_free(s);
180 return retval;
181}
182
Shawn Willden7f424372021-01-10 18:06:50 -0700183} // namespace
184
Shawn Willden7c130392020-12-21 09:58:22 -0700185bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
186bool KeyMintAidlTestBase::dump_Attestations = false;
187
David Drysdale37af4b32021-05-14 16:46:59 +0100188uint32_t KeyMintAidlTestBase::boot_patch_level(
189 const vector<KeyCharacteristics>& key_characteristics) {
190 // The boot patchlevel is not available as a property, but should be present
191 // in the key characteristics of any created key.
192 AuthorizationSet allAuths;
193 for (auto& entry : key_characteristics) {
194 allAuths.push_back(AuthorizationSet(entry.authorizations));
195 }
196 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
197 if (patchlevel.has_value()) {
198 return patchlevel.value();
199 } else {
200 // No boot patchlevel is available. Return a value that won't match anything
201 // and so will trigger test failures.
202 return kInvalidPatchlevel;
203 }
204}
205
206uint32_t KeyMintAidlTestBase::boot_patch_level() {
207 return boot_patch_level(key_characteristics_);
208}
209
David Drysdale42fe1892021-10-14 14:43:46 +0100210bool KeyMintAidlTestBase::Curve25519Supported() {
211 // Strongbox never supports curve 25519.
212 if (SecLevel() == SecurityLevel::STRONGBOX) {
213 return false;
214 }
215
216 // Curve 25519 was included in version 2 of the KeyMint interface.
217 int32_t version = 0;
218 auto status = keymint_->getInterfaceVersion(&version);
219 if (!status.isOk()) {
220 ADD_FAILURE() << "Failed to determine interface version";
221 }
222 return version >= 2;
223}
224
Janis Danisevskis24c04702020-12-16 18:28:39 -0800225ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700226 if (result.isOk()) return ErrorCode::OK;
227
Janis Danisevskis24c04702020-12-16 18:28:39 -0800228 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
229 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700230 }
231
232 return ErrorCode::UNKNOWN_ERROR;
233}
234
Janis Danisevskis24c04702020-12-16 18:28:39 -0800235void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700236 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800237 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700238
239 KeyMintHardwareInfo info;
240 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
241
242 securityLevel_ = info.securityLevel;
243 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
244 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100245 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700246
247 os_version_ = getOsVersion();
248 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100249 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700250}
251
David Drysdale7dff4fc2021-12-10 10:10:52 +0000252int32_t KeyMintAidlTestBase::AidlVersion() {
253 int32_t version = 0;
254 auto status = keymint_->getInterfaceVersion(&version);
255 if (!status.isOk()) {
256 ADD_FAILURE() << "Failed to determine interface version";
257 }
258 return version;
259}
260
Selene Huang31ab4042020-04-29 04:22:39 -0700261void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800262 if (AServiceManager_isDeclared(GetParam().c_str())) {
263 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
264 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
265 } else {
266 InitializeKeyMint(nullptr);
267 }
Selene Huang31ab4042020-04-29 04:22:39 -0700268}
269
270ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700271 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700272 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700273 vector<KeyCharacteristics>* key_characteristics,
274 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700275 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
276 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700277 << "Previous characteristics not deleted before generating key. Test bug.";
278
Shawn Willden7f424372021-01-10 18:06:50 -0700279 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700280 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700281 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700282 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
283 creationResult.keyCharacteristics);
284 EXPECT_GT(creationResult.keyBlob.size(), 0);
285 *key_blob = std::move(creationResult.keyBlob);
286 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700287 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700288
289 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
290 EXPECT_TRUE(algorithm);
291 if (algorithm &&
292 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700293 EXPECT_GE(cert_chain->size(), 1);
294 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
295 if (attest_key) {
296 EXPECT_EQ(cert_chain->size(), 1);
297 } else {
298 EXPECT_GT(cert_chain->size(), 1);
299 }
300 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700301 } else {
302 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700303 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700304 }
Selene Huang31ab4042020-04-29 04:22:39 -0700305 }
306
307 return GetReturnErrorCode(result);
308}
309
Shawn Willden7c130392020-12-21 09:58:22 -0700310ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
311 const optional<AttestationKey>& attest_key) {
312 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700313}
314
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000315ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
316 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
317 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
318 vector<Certificate>* cert_chain) {
319 AttestationKey attest_key;
320 vector<Certificate> attest_cert_chain;
321 vector<KeyCharacteristics> attest_key_characteristics;
322 // Generate a key with self signed attestation.
323 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
324 &attest_key_characteristics, &attest_cert_chain);
325 if (error != ErrorCode::OK) {
326 return error;
327 }
328
329 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
330 // Generate a key, by passing the above self signed attestation key as attest key.
331 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
332 if (error == ErrorCode::OK) {
333 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
334 cert_chain->push_back(attest_cert_chain[0]);
335 }
336 return error;
337}
338
Selene Huang31ab4042020-04-29 04:22:39 -0700339ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
340 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700341 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700342 Status result;
343
Shawn Willden7f424372021-01-10 18:06:50 -0700344 cert_chain_.clear();
345 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700346 key_blob->clear();
347
Shawn Willden7f424372021-01-10 18:06:50 -0700348 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700349 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700350 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700351 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700352
353 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700354 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
355 creationResult.keyCharacteristics);
356 EXPECT_GT(creationResult.keyBlob.size(), 0);
357
358 *key_blob = std::move(creationResult.keyBlob);
359 *key_characteristics = std::move(creationResult.keyCharacteristics);
360 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700361
362 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
363 EXPECT_TRUE(algorithm);
364 if (algorithm &&
365 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
366 EXPECT_GE(cert_chain_.size(), 1);
367 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
368 } else {
369 // For symmetric keys there should be no certificates.
370 EXPECT_EQ(cert_chain_.size(), 0);
371 }
Selene Huang31ab4042020-04-29 04:22:39 -0700372 }
373
374 return GetReturnErrorCode(result);
375}
376
377ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
378 const string& key_material) {
379 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
380}
381
382ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
383 const AuthorizationSet& wrapping_key_desc,
384 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100385 const AuthorizationSet& unwrapping_params,
386 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700387 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
388
Shawn Willden7f424372021-01-10 18:06:50 -0700389 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700390
Shawn Willden7f424372021-01-10 18:06:50 -0700391 KeyCreationResult creationResult;
392 Status result = keymint_->importWrappedKey(
393 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
394 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100395 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700396
397 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700398 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
399 creationResult.keyCharacteristics);
400 EXPECT_GT(creationResult.keyBlob.size(), 0);
401
402 key_blob_ = std::move(creationResult.keyBlob);
403 key_characteristics_ = std::move(creationResult.keyCharacteristics);
404 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700405
406 AuthorizationSet allAuths;
407 for (auto& entry : key_characteristics_) {
408 allAuths.push_back(AuthorizationSet(entry.authorizations));
409 }
410 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
411 EXPECT_TRUE(algorithm);
412 if (algorithm &&
413 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
414 EXPECT_GE(cert_chain_.size(), 1);
415 } else {
416 // For symmetric keys there should be no certificates.
417 EXPECT_EQ(cert_chain_.size(), 0);
418 }
Selene Huang31ab4042020-04-29 04:22:39 -0700419 }
420
421 return GetReturnErrorCode(result);
422}
423
David Drysdale300b5552021-05-20 12:05:26 +0100424ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
425 const vector<uint8_t>& app_id,
426 const vector<uint8_t>& app_data,
427 vector<KeyCharacteristics>* key_characteristics) {
428 Status result =
429 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
430 return GetReturnErrorCode(result);
431}
432
433ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
434 vector<KeyCharacteristics>* key_characteristics) {
435 vector<uint8_t> empty_app_id, empty_app_data;
436 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
437}
438
439void KeyMintAidlTestBase::CheckCharacteristics(
440 const vector<uint8_t>& key_blob,
441 const vector<KeyCharacteristics>& generate_characteristics) {
442 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
443 // generateKey() should be excluded, as KeyMint will have no record of them.
444 // This applies to CREATION_DATETIME in particular.
445 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
446 strip_keystore_tags(&expected_characteristics);
447
448 vector<KeyCharacteristics> retrieved;
449 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
450 EXPECT_EQ(expected_characteristics, retrieved);
451}
452
453void KeyMintAidlTestBase::CheckAppIdCharacteristics(
454 const vector<uint8_t>& key_blob, std::string_view app_id_string,
455 std::string_view app_data_string,
456 const vector<KeyCharacteristics>& generate_characteristics) {
457 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
458 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
459 strip_keystore_tags(&expected_characteristics);
460
461 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
462 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
463 vector<KeyCharacteristics> retrieved;
464 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
465 EXPECT_EQ(expected_characteristics, retrieved);
466
467 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
468 vector<uint8_t> empty;
469 vector<KeyCharacteristics> not_retrieved;
470 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
471 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
472 EXPECT_EQ(not_retrieved.size(), 0);
473
474 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
475 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
476 EXPECT_EQ(not_retrieved.size(), 0);
477
478 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
479 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
480 EXPECT_EQ(not_retrieved.size(), 0);
481}
482
Selene Huang31ab4042020-04-29 04:22:39 -0700483ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
484 Status result = keymint_->deleteKey(*key_blob);
485 if (!keep_key_blob) {
486 *key_blob = vector<uint8_t>();
487 }
488
Janis Danisevskis24c04702020-12-16 18:28:39 -0800489 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700490 return GetReturnErrorCode(result);
491}
492
493ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
494 return DeleteKey(&key_blob_, keep_key_blob);
495}
496
497ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
498 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800499 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700500 return GetReturnErrorCode(result);
501}
502
David Drysdaled2cc8c22021-04-15 13:29:45 +0100503ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
504 Status result = keymint_->destroyAttestationIds();
505 return GetReturnErrorCode(result);
506}
507
Selene Huang31ab4042020-04-29 04:22:39 -0700508void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
509 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
510 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
511}
512
513void KeyMintAidlTestBase::CheckedDeleteKey() {
514 CheckedDeleteKey(&key_blob_);
515}
516
517ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
518 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800519 AuthorizationSet* out_params,
520 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700521 SCOPED_TRACE("Begin");
522 Status result;
523 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100524 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700525
526 if (result.isOk()) {
527 *out_params = out.params;
528 challenge_ = out.challenge;
529 op = out.operation;
530 }
531
532 return GetReturnErrorCode(result);
533}
534
535ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
536 const AuthorizationSet& in_params,
537 AuthorizationSet* out_params) {
538 SCOPED_TRACE("Begin");
539 Status result;
540 BeginResult out;
541
David Drysdale56ba9122021-04-19 19:10:47 +0100542 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700543
544 if (result.isOk()) {
545 *out_params = out.params;
546 challenge_ = out.challenge;
547 op_ = out.operation;
548 }
549
550 return GetReturnErrorCode(result);
551}
552
553ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
554 AuthorizationSet* out_params) {
555 SCOPED_TRACE("Begin");
556 EXPECT_EQ(nullptr, op_);
557 return Begin(purpose, key_blob_, in_params, out_params);
558}
559
560ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
561 SCOPED_TRACE("Begin");
562 AuthorizationSet out_params;
563 ErrorCode result = Begin(purpose, in_params, &out_params);
564 EXPECT_TRUE(out_params.empty());
565 return result;
566}
567
Shawn Willden92d79c02021-02-19 07:31:55 -0700568ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
569 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
570 {} /* hardwareAuthToken */,
571 {} /* verificationToken */));
572}
573
574ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700575 SCOPED_TRACE("Update");
576
577 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700578 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700579
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800580 EXPECT_NE(op_, nullptr);
581 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
582
Shawn Willden92d79c02021-02-19 07:31:55 -0700583 std::vector<uint8_t> o_put;
584 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700585
David Drysdalefeab5d92022-01-06 15:46:23 +0000586 if (result.isOk()) {
587 output->append(o_put.begin(), o_put.end());
588 } else {
589 // Failure always terminates the operation.
590 op_ = {};
591 }
Selene Huang31ab4042020-04-29 04:22:39 -0700592
593 return GetReturnErrorCode(result);
594}
595
Shawn Willden92d79c02021-02-19 07:31:55 -0700596ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700597 string* output) {
598 SCOPED_TRACE("Finish");
599 Status result;
600
601 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700602 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700603
604 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700605 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
606 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
607 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700608
Shawn Willden92d79c02021-02-19 07:31:55 -0700609 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700610
Shawn Willden92d79c02021-02-19 07:31:55 -0700611 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700612 return GetReturnErrorCode(result);
613}
614
Janis Danisevskis24c04702020-12-16 18:28:39 -0800615ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700616 SCOPED_TRACE("Abort");
617
618 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700619 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700620
621 Status retval = op->abort();
622 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800623 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700624}
625
626ErrorCode KeyMintAidlTestBase::Abort() {
627 SCOPED_TRACE("Abort");
628
629 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700630 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700631
632 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800633 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700634}
635
636void KeyMintAidlTestBase::AbortIfNeeded() {
637 SCOPED_TRACE("AbortIfNeeded");
638 if (op_) {
639 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800640 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700641 }
642}
643
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000644auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
645 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700646 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000647 AuthorizationSet begin_out_params;
648 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700649 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000650
651 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700652 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000653}
654
Selene Huang31ab4042020-04-29 04:22:39 -0700655string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
656 const string& message, const AuthorizationSet& in_params,
657 AuthorizationSet* out_params) {
658 SCOPED_TRACE("ProcessMessage");
659 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700660 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700661 EXPECT_EQ(ErrorCode::OK, result);
662 if (result != ErrorCode::OK) {
663 return "";
664 }
665
666 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700667 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700668 return output;
669}
670
671string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
672 const AuthorizationSet& params) {
673 SCOPED_TRACE("SignMessage");
674 AuthorizationSet out_params;
675 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
676 EXPECT_TRUE(out_params.empty());
677 return signature;
678}
679
680string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
681 SCOPED_TRACE("SignMessage");
682 return SignMessage(key_blob_, message, params);
683}
684
685string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
686 SCOPED_TRACE("MacMessage");
687 return SignMessage(
688 key_blob_, message,
689 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
690}
691
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530692void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
693 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000694 auto builder = AuthorizationSetBuilder()
695 .Authorization(TAG_NO_AUTH_REQUIRED)
696 .AesEncryptionKey(128)
697 .BlockMode(block_mode)
698 .Padding(PaddingMode::NONE);
699 if (block_mode == BlockMode::GCM) {
700 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
701 }
702 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530703
704 for (int increment = 1; increment <= message_size; ++increment) {
705 string message(message_size, 'a');
706 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
707 if (block_mode == BlockMode::GCM) {
708 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
709 }
710
711 AuthorizationSet output_params;
712 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
713
714 string ciphertext;
715 string to_send;
716 for (size_t i = 0; i < message.size(); i += increment) {
717 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
718 }
719 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
720 << "Error sending " << to_send << " with block mode " << block_mode;
721
722 switch (block_mode) {
723 case BlockMode::GCM:
724 EXPECT_EQ(message.size() + 16, ciphertext.size());
725 break;
726 case BlockMode::CTR:
727 EXPECT_EQ(message.size(), ciphertext.size());
728 break;
729 case BlockMode::CBC:
730 case BlockMode::ECB:
731 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
732 break;
733 }
734
735 auto iv = output_params.GetTagValue(TAG_NONCE);
736 switch (block_mode) {
737 case BlockMode::CBC:
738 case BlockMode::GCM:
739 case BlockMode::CTR:
740 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
741 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
742 params.push_back(TAG_NONCE, iv->get());
743 break;
744
745 case BlockMode::ECB:
746 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
747 break;
748 }
749
750 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
751 << "Decrypt begin() failed for block mode " << block_mode;
752
753 string plaintext;
754 for (size_t i = 0; i < ciphertext.size(); i += increment) {
755 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
756 }
757 ErrorCode error = Finish(to_send, &plaintext);
758 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
759 << " and increment " << increment;
760 if (error == ErrorCode::OK) {
761 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
762 << " and increment " << increment;
763 }
764 }
765}
766
Selene Huang31ab4042020-04-29 04:22:39 -0700767void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
768 Digest digest, const string& expected_mac) {
769 SCOPED_TRACE("CheckHmacTestVector");
770 ASSERT_EQ(ErrorCode::OK,
771 ImportKey(AuthorizationSetBuilder()
772 .Authorization(TAG_NO_AUTH_REQUIRED)
773 .HmacKey(key.size() * 8)
774 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
775 .Digest(digest),
776 KeyFormat::RAW, key));
777 string signature = MacMessage(message, digest, expected_mac.size() * 8);
778 EXPECT_EQ(expected_mac, signature)
779 << "Test vector didn't match for key of size " << key.size() << " message of size "
780 << message.size() << " and digest " << digest;
781 CheckedDeleteKey();
782}
783
784void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
785 const string& message,
786 const string& expected_ciphertext) {
787 SCOPED_TRACE("CheckAesCtrTestVector");
788 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
789 .Authorization(TAG_NO_AUTH_REQUIRED)
790 .AesEncryptionKey(key.size() * 8)
791 .BlockMode(BlockMode::CTR)
792 .Authorization(TAG_CALLER_NONCE)
793 .Padding(PaddingMode::NONE),
794 KeyFormat::RAW, key));
795
796 auto params = AuthorizationSetBuilder()
797 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
798 .BlockMode(BlockMode::CTR)
799 .Padding(PaddingMode::NONE);
800 AuthorizationSet out_params;
801 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
802 EXPECT_EQ(expected_ciphertext, ciphertext);
803}
804
805void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
806 PaddingMode padding_mode, const string& key,
807 const string& iv, const string& input,
808 const string& expected_output) {
809 auto authset = AuthorizationSetBuilder()
810 .TripleDesEncryptionKey(key.size() * 7)
811 .BlockMode(block_mode)
812 .Authorization(TAG_NO_AUTH_REQUIRED)
813 .Padding(padding_mode);
814 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
815 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
816 ASSERT_GT(key_blob_.size(), 0U);
817
818 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
819 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
820 AuthorizationSet output_params;
821 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
822 EXPECT_EQ(expected_output, output);
823}
824
825void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
826 const string& signature, const AuthorizationSet& params) {
827 SCOPED_TRACE("VerifyMessage");
828 AuthorizationSet begin_out_params;
829 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
830
831 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700832 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700833 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700834 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700835}
836
837void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
838 const AuthorizationSet& params) {
839 SCOPED_TRACE("VerifyMessage");
840 VerifyMessage(key_blob_, message, signature, params);
841}
842
David Drysdaledf8f52e2021-05-06 08:10:58 +0100843void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
844 const AuthorizationSet& params) {
845 SCOPED_TRACE("LocalVerifyMessage");
846
847 // Retrieve the public key from the leaf certificate.
848 ASSERT_GT(cert_chain_.size(), 0);
849 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
850 ASSERT_TRUE(key_cert.get());
851 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
852 ASSERT_TRUE(pub_key.get());
853
854 Digest digest = params.GetTagValue(TAG_DIGEST).value();
855 PaddingMode padding = PaddingMode::NONE;
856 auto tag = params.GetTagValue(TAG_PADDING);
857 if (tag.has_value()) {
858 padding = tag.value();
859 }
860
861 if (digest == Digest::NONE) {
862 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100863 case EVP_PKEY_ED25519: {
864 ASSERT_EQ(64, signature.size());
865 uint8_t pub_keydata[32];
866 size_t pub_len = sizeof(pub_keydata);
867 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
868 ASSERT_EQ(sizeof(pub_keydata), pub_len);
869 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
870 message.size(),
871 reinterpret_cast<const uint8_t*>(signature.data()),
872 pub_keydata));
873 break;
874 }
875
David Drysdaledf8f52e2021-05-06 08:10:58 +0100876 case EVP_PKEY_EC: {
877 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
878 size_t data_size = std::min(data.size(), message.size());
879 memcpy(data.data(), message.data(), data_size);
880 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
881 ASSERT_TRUE(ecdsa.get());
882 ASSERT_EQ(1,
883 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
884 reinterpret_cast<const uint8_t*>(signature.data()),
885 signature.size(), ecdsa.get()));
886 break;
887 }
888 case EVP_PKEY_RSA: {
889 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
890 size_t data_size = std::min(data.size(), message.size());
891 memcpy(data.data(), message.data(), data_size);
892
893 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
894 ASSERT_TRUE(rsa.get());
895
896 size_t key_len = RSA_size(rsa.get());
897 int openssl_padding = RSA_NO_PADDING;
898 switch (padding) {
899 case PaddingMode::NONE:
900 ASSERT_TRUE(data_size <= key_len);
901 ASSERT_EQ(key_len, signature.size());
902 openssl_padding = RSA_NO_PADDING;
903 break;
904 case PaddingMode::RSA_PKCS1_1_5_SIGN:
905 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
906 key_len);
907 openssl_padding = RSA_PKCS1_PADDING;
908 break;
909 default:
910 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
911 }
912
913 vector<uint8_t> decrypted_data(key_len);
914 int bytes_decrypted = RSA_public_decrypt(
915 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
916 decrypted_data.data(), rsa.get(), openssl_padding);
917 ASSERT_GE(bytes_decrypted, 0);
918
919 const uint8_t* compare_pos = decrypted_data.data();
920 size_t bytes_to_compare = bytes_decrypted;
921 uint8_t zero_check_result = 0;
922 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
923 // If the data is short, for "unpadded" signing we zero-pad to the left. So
924 // during verification we should have zeros on the left of the decrypted data.
925 // Do a constant-time check.
926 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
927 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
928 ASSERT_EQ(0, zero_check_result);
929 bytes_to_compare = data_size;
930 }
931 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
932 break;
933 }
934 default:
935 ADD_FAILURE() << "Unknown public key type";
936 }
937 } else {
938 EVP_MD_CTX digest_ctx;
939 EVP_MD_CTX_init(&digest_ctx);
940 EVP_PKEY_CTX* pkey_ctx;
941 const EVP_MD* md = openssl_digest(digest);
942 ASSERT_NE(md, nullptr);
943 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
944
945 if (padding == PaddingMode::RSA_PSS) {
946 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
947 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +0000948 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +0100949 }
950
951 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
952 reinterpret_cast<const uint8_t*>(message.data()),
953 message.size()));
954 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
955 reinterpret_cast<const uint8_t*>(signature.data()),
956 signature.size()));
957 EVP_MD_CTX_cleanup(&digest_ctx);
958 }
959}
960
David Drysdale59cae642021-05-12 13:52:03 +0100961string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
962 const AuthorizationSet& params) {
963 SCOPED_TRACE("LocalRsaEncryptMessage");
964
965 // Retrieve the public key from the leaf certificate.
966 if (cert_chain_.empty()) {
967 ADD_FAILURE() << "No public key available";
968 return "Failure";
969 }
970 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
971 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
972 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
973
974 // Retrieve relevant tags.
975 Digest digest = Digest::NONE;
976 Digest mgf_digest = Digest::NONE;
977 PaddingMode padding = PaddingMode::NONE;
978
979 auto digest_tag = params.GetTagValue(TAG_DIGEST);
980 if (digest_tag.has_value()) digest = digest_tag.value();
981 auto pad_tag = params.GetTagValue(TAG_PADDING);
982 if (pad_tag.has_value()) padding = pad_tag.value();
983 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
984 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
985
986 const EVP_MD* md = openssl_digest(digest);
987 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
988
989 // Set up encryption context.
990 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
991 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
992 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
993 return "Failure";
994 }
995
996 int rc = -1;
997 switch (padding) {
998 case PaddingMode::NONE:
999 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1000 break;
1001 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1002 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1003 break;
1004 case PaddingMode::RSA_OAEP:
1005 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1006 break;
1007 default:
1008 break;
1009 }
1010 if (rc <= 0) {
1011 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1012 return "Failure";
1013 }
1014 if (padding == PaddingMode::RSA_OAEP) {
1015 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1016 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1017 return "Failure";
1018 }
1019 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1020 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1021 return "Failure";
1022 }
1023 }
1024
1025 // Determine output size.
1026 size_t outlen;
1027 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1028 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1029 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1030 return "Failure";
1031 }
1032
1033 // Left-zero-pad the input if necessary.
1034 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1035 size_t to_encrypt_len = message.size();
1036
1037 std::unique_ptr<string> zero_padded_message;
1038 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1039 zero_padded_message.reset(new string(outlen, '\0'));
1040 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1041 message.size());
1042 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1043 to_encrypt_len = outlen;
1044 }
1045
1046 // Do the encryption.
1047 string output(outlen, '\0');
1048 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1049 to_encrypt_len) <= 0) {
1050 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1051 return "Failure";
1052 }
1053 return output;
1054}
1055
Selene Huang31ab4042020-04-29 04:22:39 -07001056string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1057 const AuthorizationSet& in_params,
1058 AuthorizationSet* out_params) {
1059 SCOPED_TRACE("EncryptMessage");
1060 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1061}
1062
1063string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1064 AuthorizationSet* out_params) {
1065 SCOPED_TRACE("EncryptMessage");
1066 return EncryptMessage(key_blob_, message, params, out_params);
1067}
1068
1069string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1070 SCOPED_TRACE("EncryptMessage");
1071 AuthorizationSet out_params;
1072 string ciphertext = EncryptMessage(message, params, &out_params);
1073 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1074 return ciphertext;
1075}
1076
1077string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1078 PaddingMode padding) {
1079 SCOPED_TRACE("EncryptMessage");
1080 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1081 AuthorizationSet out_params;
1082 string ciphertext = EncryptMessage(message, params, &out_params);
1083 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1084 return ciphertext;
1085}
1086
1087string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1088 PaddingMode padding, vector<uint8_t>* iv_out) {
1089 SCOPED_TRACE("EncryptMessage");
1090 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1091 AuthorizationSet out_params;
1092 string ciphertext = EncryptMessage(message, params, &out_params);
1093 EXPECT_EQ(1U, out_params.size());
1094 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001095 EXPECT_TRUE(ivVal);
1096 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001097 return ciphertext;
1098}
1099
1100string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1101 PaddingMode padding, const vector<uint8_t>& iv_in) {
1102 SCOPED_TRACE("EncryptMessage");
1103 auto params = AuthorizationSetBuilder()
1104 .BlockMode(block_mode)
1105 .Padding(padding)
1106 .Authorization(TAG_NONCE, iv_in);
1107 AuthorizationSet out_params;
1108 string ciphertext = EncryptMessage(message, params, &out_params);
1109 return ciphertext;
1110}
1111
1112string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1113 PaddingMode padding, uint8_t mac_length_bits,
1114 const vector<uint8_t>& iv_in) {
1115 SCOPED_TRACE("EncryptMessage");
1116 auto params = AuthorizationSetBuilder()
1117 .BlockMode(block_mode)
1118 .Padding(padding)
1119 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1120 .Authorization(TAG_NONCE, iv_in);
1121 AuthorizationSet out_params;
1122 string ciphertext = EncryptMessage(message, params, &out_params);
1123 return ciphertext;
1124}
1125
David Drysdaled2cc8c22021-04-15 13:29:45 +01001126string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1127 PaddingMode padding, uint8_t mac_length_bits) {
1128 SCOPED_TRACE("EncryptMessage");
1129 auto params = AuthorizationSetBuilder()
1130 .BlockMode(block_mode)
1131 .Padding(padding)
1132 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1133 AuthorizationSet out_params;
1134 string ciphertext = EncryptMessage(message, params, &out_params);
1135 return ciphertext;
1136}
1137
Selene Huang31ab4042020-04-29 04:22:39 -07001138string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1139 const string& ciphertext,
1140 const AuthorizationSet& params) {
1141 SCOPED_TRACE("DecryptMessage");
1142 AuthorizationSet out_params;
1143 string plaintext =
1144 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1145 EXPECT_TRUE(out_params.empty());
1146 return plaintext;
1147}
1148
1149string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1150 const AuthorizationSet& params) {
1151 SCOPED_TRACE("DecryptMessage");
1152 return DecryptMessage(key_blob_, ciphertext, params);
1153}
1154
1155string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1156 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1157 SCOPED_TRACE("DecryptMessage");
1158 auto params = AuthorizationSetBuilder()
1159 .BlockMode(block_mode)
1160 .Padding(padding_mode)
1161 .Authorization(TAG_NONCE, iv);
1162 return DecryptMessage(key_blob_, ciphertext, params);
1163}
1164
1165std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1166 const vector<uint8_t>& key_blob) {
1167 std::pair<ErrorCode, vector<uint8_t>> retval;
1168 vector<uint8_t> outKeyBlob;
1169 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1170 ErrorCode errorcode = GetReturnErrorCode(result);
1171 retval = std::tie(errorcode, outKeyBlob);
1172
1173 return retval;
1174}
1175vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1176 switch (algorithm) {
1177 case Algorithm::RSA:
1178 switch (SecLevel()) {
1179 case SecurityLevel::SOFTWARE:
1180 case SecurityLevel::TRUSTED_ENVIRONMENT:
1181 return {2048, 3072, 4096};
1182 case SecurityLevel::STRONGBOX:
1183 return {2048};
1184 default:
1185 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1186 break;
1187 }
1188 break;
1189 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001190 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001191 break;
1192 case Algorithm::AES:
1193 return {128, 256};
1194 case Algorithm::TRIPLE_DES:
1195 return {168};
1196 case Algorithm::HMAC: {
1197 vector<uint32_t> retval((512 - 64) / 8 + 1);
1198 uint32_t size = 64 - 8;
1199 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1200 return retval;
1201 }
1202 default:
1203 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1204 return {};
1205 }
1206 ADD_FAILURE() << "Should be impossible to get here";
1207 return {};
1208}
1209
1210vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1211 if (SecLevel() == SecurityLevel::STRONGBOX) {
1212 switch (algorithm) {
1213 case Algorithm::RSA:
1214 return {3072, 4096};
1215 case Algorithm::EC:
1216 return {224, 384, 521};
1217 case Algorithm::AES:
1218 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001219 case Algorithm::TRIPLE_DES:
1220 return {56};
1221 default:
1222 return {};
1223 }
1224 } else {
1225 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001226 case Algorithm::AES:
1227 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001228 case Algorithm::TRIPLE_DES:
1229 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001230 default:
1231 return {};
1232 }
1233 }
1234 return {};
1235}
1236
David Drysdale7de9feb2021-03-05 14:56:19 +00001237vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1238 switch (algorithm) {
1239 case Algorithm::AES:
1240 return {
1241 BlockMode::CBC,
1242 BlockMode::CTR,
1243 BlockMode::ECB,
1244 BlockMode::GCM,
1245 };
1246 case Algorithm::TRIPLE_DES:
1247 return {
1248 BlockMode::CBC,
1249 BlockMode::ECB,
1250 };
1251 default:
1252 return {};
1253 }
1254}
1255
1256vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1257 BlockMode blockMode) {
1258 switch (algorithm) {
1259 case Algorithm::AES:
1260 switch (blockMode) {
1261 case BlockMode::CBC:
1262 case BlockMode::ECB:
1263 return {PaddingMode::NONE, PaddingMode::PKCS7};
1264 case BlockMode::CTR:
1265 case BlockMode::GCM:
1266 return {PaddingMode::NONE};
1267 default:
1268 return {};
1269 };
1270 case Algorithm::TRIPLE_DES:
1271 switch (blockMode) {
1272 case BlockMode::CBC:
1273 case BlockMode::ECB:
1274 return {PaddingMode::NONE, PaddingMode::PKCS7};
1275 default:
1276 return {};
1277 };
1278 default:
1279 return {};
1280 }
1281}
1282
1283vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1284 BlockMode blockMode) {
1285 switch (algorithm) {
1286 case Algorithm::AES:
1287 switch (blockMode) {
1288 case BlockMode::CTR:
1289 case BlockMode::GCM:
1290 return {PaddingMode::PKCS7};
1291 default:
1292 return {};
1293 };
1294 default:
1295 return {};
1296 }
1297}
1298
Selene Huang31ab4042020-04-29 04:22:39 -07001299vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1300 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1301 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001302 } else if (Curve25519Supported()) {
1303 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1304 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001305 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001306 return {
1307 EcCurve::P_224,
1308 EcCurve::P_256,
1309 EcCurve::P_384,
1310 EcCurve::P_521,
1311 };
Selene Huang31ab4042020-04-29 04:22:39 -07001312 }
1313}
1314
1315vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001316 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001317 // Curve 25519 is not supported, either because:
1318 // - KeyMint v1: it's an unknown enum value
1319 // - KeyMint v2+: it's not supported by StrongBox.
1320 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001321 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001322 if (Curve25519Supported()) {
1323 return {};
1324 } else {
1325 return {EcCurve::CURVE_25519};
1326 }
David Drysdaledf09e542021-06-08 15:46:11 +01001327 }
Selene Huang31ab4042020-04-29 04:22:39 -07001328}
1329
subrahmanyaman05642492022-02-05 07:10:56 +00001330vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1331 if (SecLevel() == SecurityLevel::STRONGBOX) {
1332 return {65537};
1333 } else {
1334 return {3, 65537};
1335 }
1336}
1337
Selene Huang31ab4042020-04-29 04:22:39 -07001338vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1339 switch (SecLevel()) {
1340 case SecurityLevel::SOFTWARE:
1341 case SecurityLevel::TRUSTED_ENVIRONMENT:
1342 if (withNone) {
1343 if (withMD5)
1344 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1345 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1346 Digest::SHA_2_512};
1347 else
1348 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1349 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1350 } else {
1351 if (withMD5)
1352 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1353 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1354 else
1355 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1356 Digest::SHA_2_512};
1357 }
1358 break;
1359 case SecurityLevel::STRONGBOX:
1360 if (withNone)
1361 return {Digest::NONE, Digest::SHA_2_256};
1362 else
1363 return {Digest::SHA_2_256};
1364 break;
1365 default:
1366 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1367 break;
1368 }
1369 ADD_FAILURE() << "Should be impossible to get here";
1370 return {};
1371}
1372
Shawn Willden7f424372021-01-10 18:06:50 -07001373static const vector<KeyParameter> kEmptyAuthList{};
1374
1375const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1376 const vector<KeyCharacteristics>& key_characteristics) {
1377 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1378 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1379 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1380}
1381
Qi Wubeefae42021-01-28 23:16:37 +08001382const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1383 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1384 auto found = std::find_if(
1385 key_characteristics.begin(), key_characteristics.end(),
1386 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001387 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1388}
1389
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001390ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001391 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001392 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1393 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1394 return result;
1395}
1396
1397ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001398 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001399 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1400 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1401 return result;
1402}
1403
1404ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1405 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001406 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001407 rsaKeyBlob, KeyPurpose::SIGN, message,
1408 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1409 return result;
1410}
1411
1412ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001413 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1414 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001415 return result;
1416}
1417
Selene Huang6e46f142021-04-20 19:20:11 -07001418void verify_serial(X509* cert, const uint64_t expected_serial) {
1419 BIGNUM_Ptr ser(BN_new());
1420 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1421
1422 uint64_t serial;
1423 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1424 EXPECT_EQ(serial, expected_serial);
1425}
1426
1427// Please set self_signed to true for fake certificates or self signed
1428// certificates
1429void verify_subject(const X509* cert, //
1430 const string& subject, //
1431 bool self_signed) {
1432 char* cert_issuer = //
1433 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1434
1435 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1436
1437 string expected_subject("/CN=");
1438 if (subject.empty()) {
1439 expected_subject.append("Android Keystore Key");
1440 } else {
1441 expected_subject.append(subject);
1442 }
1443
1444 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1445
1446 if (self_signed) {
1447 EXPECT_STREQ(cert_issuer, cert_subj)
1448 << "Cert issuer and subject mismatch for self signed certificate.";
1449 }
1450
1451 OPENSSL_free(cert_subj);
1452 OPENSSL_free(cert_issuer);
1453}
1454
1455vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1456 BIGNUM_Ptr serial(BN_new());
1457 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1458
1459 int len = BN_num_bytes(serial.get());
1460 vector<uint8_t> serial_blob(len);
1461 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1462 return {};
1463 }
1464
David Drysdaledb0dcf52021-05-18 11:43:31 +01001465 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1466 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1467 // Top bit being set indicates a negative number in two's complement, but our input
1468 // was positive.
1469 // In either case, prepend a zero byte.
1470 serial_blob.insert(serial_blob.begin(), 0x00);
1471 }
1472
Selene Huang6e46f142021-04-20 19:20:11 -07001473 return serial_blob;
1474}
1475
1476void verify_subject_and_serial(const Certificate& certificate, //
1477 const uint64_t expected_serial, //
1478 const string& subject, bool self_signed) {
1479 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1480 ASSERT_TRUE(!!cert.get());
1481
1482 verify_serial(cert.get(), expected_serial);
1483 verify_subject(cert.get(), subject, self_signed);
1484}
1485
David Drysdale7dff4fc2021-12-10 10:10:52 +00001486bool verify_attestation_record(int32_t aidl_version, //
1487 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001488 const string& app_id, //
1489 AuthorizationSet expected_sw_enforced, //
1490 AuthorizationSet expected_hw_enforced, //
1491 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001492 const vector<uint8_t>& attestation_cert,
1493 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001494 X509_Ptr cert(parse_cert_blob(attestation_cert));
1495 EXPECT_TRUE(!!cert.get());
1496 if (!cert.get()) return false;
1497
1498 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1499 EXPECT_TRUE(!!attest_rec);
1500 if (!attest_rec) return false;
1501
1502 AuthorizationSet att_sw_enforced;
1503 AuthorizationSet att_hw_enforced;
1504 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001505 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001506 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001507 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001508 vector<uint8_t> att_challenge;
1509 vector<uint8_t> att_unique_id;
1510 vector<uint8_t> att_app_id;
1511
1512 auto error = parse_attestation_record(attest_rec->data, //
1513 attest_rec->length, //
1514 &att_attestation_version, //
1515 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001516 &att_keymint_version, //
1517 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001518 &att_challenge, //
1519 &att_sw_enforced, //
1520 &att_hw_enforced, //
1521 &att_unique_id);
1522 EXPECT_EQ(ErrorCode::OK, error);
1523 if (error != ErrorCode::OK) return false;
1524
David Drysdale7dff4fc2021-12-10 10:10:52 +00001525 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001526 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001527
Selene Huang4f64c222021-04-13 19:54:36 -07001528 // check challenge and app id only if we expects a non-fake certificate
1529 if (challenge.length() > 0) {
1530 EXPECT_EQ(challenge.length(), att_challenge.size());
1531 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1532
1533 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1534 }
Shawn Willden7c130392020-12-21 09:58:22 -07001535
David Drysdale7dff4fc2021-12-10 10:10:52 +00001536 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001537 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001538 EXPECT_EQ(security_level, att_attestation_security_level);
1539
Shawn Willden7c130392020-12-21 09:58:22 -07001540
1541 char property_value[PROPERTY_VALUE_MAX] = {};
1542 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001543 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001544 // for the BOOT_PATCH_LEVEL.
1545 if (avb_verification_enabled()) {
1546 for (int i = 0; i < att_hw_enforced.size(); i++) {
1547 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1548 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1549 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001550 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001551
Shawn Willden7c130392020-12-21 09:58:22 -07001552 // strptime seems to require delimiters, but the tag value will
1553 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001554 if (date.size() != 8) {
1555 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1556 << " with invalid format (not YYYYMMDD): " << date;
1557 return false;
1558 }
Shawn Willden7c130392020-12-21 09:58:22 -07001559 date.insert(6, "-");
1560 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001561 struct tm time;
1562 strptime(date.c_str(), "%Y-%m-%d", &time);
1563
1564 // Day of the month (0-31)
1565 EXPECT_GE(time.tm_mday, 0);
1566 EXPECT_LT(time.tm_mday, 32);
1567 // Months since Jan (0-11)
1568 EXPECT_GE(time.tm_mon, 0);
1569 EXPECT_LT(time.tm_mon, 12);
1570 // Years since 1900
1571 EXPECT_GT(time.tm_year, 110);
1572 EXPECT_LT(time.tm_year, 200);
1573 }
1574 }
1575 }
1576
1577 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1578 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1579 // indicates correct encoding. No need to check if it's in both lists, since the
1580 // AuthorizationSet compare below will handle mismatches of tags.
1581 if (security_level == SecurityLevel::SOFTWARE) {
1582 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1583 } else {
1584 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1585 }
1586
Shawn Willden7c130392020-12-21 09:58:22 -07001587 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1588 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1589 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1590 att_hw_enforced.Contains(TAG_KEY_SIZE));
1591 }
1592
1593 // Test root of trust elements
1594 vector<uint8_t> verified_boot_key;
1595 VerifiedBoot verified_boot_state;
1596 bool device_locked;
1597 vector<uint8_t> verified_boot_hash;
1598 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1599 &verified_boot_state, &device_locked, &verified_boot_hash);
1600 EXPECT_EQ(ErrorCode::OK, error);
1601
1602 if (avb_verification_enabled()) {
1603 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1604 string prop_string(property_value);
1605 EXPECT_EQ(prop_string.size(), 64);
1606 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1607
1608 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1609 if (!strcmp(property_value, "unlocked")) {
1610 EXPECT_FALSE(device_locked);
1611 } else {
1612 EXPECT_TRUE(device_locked);
1613 }
1614
1615 // Check that the device is locked if not debuggable, e.g., user build
1616 // images in CTS. For VTS, debuggable images are used to allow adb root
1617 // and the device is unlocked.
1618 if (!property_get_bool("ro.debuggable", false)) {
1619 EXPECT_TRUE(device_locked);
1620 } else {
1621 EXPECT_FALSE(device_locked);
1622 }
1623 }
1624
1625 // Verified boot key should be all 0's if the boot state is not verified or self signed
1626 std::string empty_boot_key(32, '\0');
1627 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1628 verified_boot_key.size());
1629 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1630 if (!strcmp(property_value, "green")) {
1631 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1632 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1633 verified_boot_key.size()));
1634 } else if (!strcmp(property_value, "yellow")) {
1635 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1636 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1637 verified_boot_key.size()));
1638 } else if (!strcmp(property_value, "orange")) {
1639 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1640 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1641 verified_boot_key.size()));
1642 } else if (!strcmp(property_value, "red")) {
1643 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1644 } else {
1645 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
Tri Voaf291412022-03-08 10:06:00 -08001646 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
Shawn Willden7c130392020-12-21 09:58:22 -07001647 verified_boot_key.size()));
1648 }
1649
1650 att_sw_enforced.Sort();
1651 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001652 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001653
1654 att_hw_enforced.Sort();
1655 expected_hw_enforced.Sort();
1656 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1657
David Drysdale565ccc72021-10-11 12:49:50 +01001658 if (unique_id != nullptr) {
1659 *unique_id = att_unique_id;
1660 }
1661
Shawn Willden7c130392020-12-21 09:58:22 -07001662 return true;
1663}
1664
1665string bin2hex(const vector<uint8_t>& data) {
1666 string retval;
1667 retval.reserve(data.size() * 2 + 1);
1668 for (uint8_t byte : data) {
1669 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1670 retval.push_back(nibble2hex[0x0F & byte]);
1671 }
1672 return retval;
1673}
1674
David Drysdalef0d516d2021-03-22 07:51:43 +00001675AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1676 AuthorizationSet authList;
1677 for (auto& entry : key_characteristics) {
1678 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1679 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1680 authList.push_back(AuthorizationSet(entry.authorizations));
1681 }
1682 }
1683 return authList;
1684}
1685
1686AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1687 AuthorizationSet authList;
1688 for (auto& entry : key_characteristics) {
1689 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1690 entry.securityLevel == SecurityLevel::KEYSTORE) {
1691 authList.push_back(AuthorizationSet(entry.authorizations));
1692 }
1693 }
1694 return authList;
1695}
1696
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001697AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1698 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001699 std::stringstream cert_data;
1700
1701 for (size_t i = 0; i < chain.size(); ++i) {
1702 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1703
1704 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1705 X509_Ptr signing_cert;
1706 if (i < chain.size() - 1) {
1707 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1708 } else {
1709 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1710 }
1711 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1712
1713 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1714 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1715
1716 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1717 return AssertionFailure()
1718 << "Verification of certificate " << i << " failed "
1719 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1720 << cert_data.str();
1721 }
1722
1723 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1724 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001725 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001726 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1727 << " Signer subject is " << signer_subj
1728 << " Issuer subject is " << cert_issuer << endl
1729 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001730 }
Shawn Willden7c130392020-12-21 09:58:22 -07001731 }
1732
1733 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1734 return AssertionSuccess();
1735}
1736
1737X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1738 const uint8_t* p = blob.data();
1739 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1740}
1741
David Drysdalef0d516d2021-03-22 07:51:43 +00001742vector<uint8_t> make_name_from_str(const string& name) {
1743 X509_NAME_Ptr x509_name(X509_NAME_new());
1744 EXPECT_TRUE(x509_name.get() != nullptr);
1745 if (!x509_name) return {};
1746
1747 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1748 "CN", //
1749 MBSTRING_ASC,
1750 reinterpret_cast<const uint8_t*>(name.c_str()),
1751 -1, // len
1752 -1, // loc
1753 0 /* set */));
1754
1755 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1756 EXPECT_GT(len, 0);
1757
1758 vector<uint8_t> retval(len);
1759 uint8_t* p = retval.data();
1760 i2d_X509_NAME(x509_name.get(), &p);
1761
1762 return retval;
1763}
1764
David Drysdale4dc01072021-04-01 12:17:35 +01001765namespace {
1766
1767void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1768 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1769 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1770
1771 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1772 if (testMode) {
1773 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1774 MatchesRegex("{\n"
1775 " 1 : 2,\n" // kty: EC2
1776 " 3 : -7,\n" // alg: ES256
1777 " -1 : 1,\n" // EC id: P256
1778 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1779 // sequence of 32 hexadecimal bytes, enclosed in braces and
1780 // separated by commas. In this case, some Ed25519 public key.
1781 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1782 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1783 " -70000 : null,\n" // test marker
1784 "}"));
1785 } else {
1786 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1787 MatchesRegex("{\n"
1788 " 1 : 2,\n" // kty: EC2
1789 " 3 : -7,\n" // alg: ES256
1790 " -1 : 1,\n" // EC id: P256
1791 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1792 // sequence of 32 hexadecimal bytes, enclosed in braces and
1793 // separated by commas. In this case, some Ed25519 public key.
1794 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1795 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1796 "}"));
1797 }
1798}
1799
1800} // namespace
1801
1802void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1803 vector<uint8_t>* payload_value) {
1804 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1805 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1806
1807 ASSERT_NE(coseMac0->asArray(), nullptr);
1808 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1809
1810 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1811 ASSERT_NE(protParms, nullptr);
1812
1813 // Header label:value of 'alg': HMAC-256
1814 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1815
1816 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1817 ASSERT_NE(unprotParms, nullptr);
1818 ASSERT_EQ(unprotParms->size(), 0);
1819
1820 // The payload is a bstr holding an encoded COSE_Key
1821 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1822 ASSERT_NE(payload, nullptr);
1823 check_cose_key(payload->value(), testMode);
1824
1825 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1826 ASSERT_TRUE(coseMac0Tag);
1827 auto extractedTag = coseMac0Tag->value();
1828 EXPECT_EQ(extractedTag.size(), 32U);
1829
1830 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001831 auto macFunction = [](const cppcose::bytevec& input) {
1832 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1833 };
1834 auto testTag =
1835 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001836 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1837
1838 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001839 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001840 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001841 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001842 }
1843 if (payload_value != nullptr) {
1844 *payload_value = payload->value();
1845 }
1846}
1847
1848void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1849 // Extract x and y affine coordinates from the encoded Cose_Key.
1850 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1851 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1852 auto coseKey = parsedPayload->asMap();
1853 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1854 ASSERT_NE(xItem->asBstr(), nullptr);
1855 vector<uint8_t> x = xItem->asBstr()->value();
1856 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1857 ASSERT_NE(yItem->asBstr(), nullptr);
1858 vector<uint8_t> y = yItem->asBstr()->value();
1859
1860 // Concatenate: 0x04 (uncompressed form marker) | x | y
1861 vector<uint8_t> pubKeyData{0x04};
1862 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1863 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1864
1865 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1866 ASSERT_NE(ecKey, nullptr);
1867 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1868 ASSERT_NE(group, nullptr);
1869 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1870 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1871 ASSERT_NE(point, nullptr);
1872 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1873 nullptr),
1874 1);
1875 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1876
1877 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1878 ASSERT_NE(pubKey, nullptr);
1879 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1880 *signingKey = std::move(pubKey);
1881}
1882
Selene Huang31ab4042020-04-29 04:22:39 -07001883} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001884
Janis Danisevskis24c04702020-12-16 18:28:39 -08001885} // namespace aidl::android::hardware::security::keymint