blob: be219940f8d9c55d72b335de02b1ffc34703d810 [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>
David Drysdale555ba002022-05-03 18:48:57 +010020#include <fstream>
Shawn Willden7f424372021-01-10 18:06:50 -070021#include <unordered_set>
Selene Huang31ab4042020-04-29 04:22:39 -070022#include <vector>
23
24#include <android-base/logging.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080025#include <android/binder_manager.h>
David Drysdale4dc01072021-04-01 12:17:35 +010026#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070027#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010028#include <gmock/gmock.h>
David Drysdale42fe1892021-10-14 14:43:46 +010029#include <openssl/evp.h>
Shawn Willden7c130392020-12-21 09:58:22 -070030#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010031#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070032
Max Bires9704ff62021-04-07 11:12:01 -070033#include <keymaster/cppcose/cppcose.h>
Shawn Willden7c130392020-12-21 09:58:22 -070034#include <keymint_support/attestation_record.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000035#include <keymint_support/key_param_output.h>
36#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070037#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070038
Janis Danisevskis24c04702020-12-16 18:28:39 -080039namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070040
David Drysdale4dc01072021-04-01 12:17:35 +010041using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070042using namespace std::literals::chrono_literals;
43using std::endl;
44using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070045using std::unique_ptr;
46using ::testing::AssertionFailure;
47using ::testing::AssertionResult;
48using ::testing::AssertionSuccess;
Seth Moore026bb742021-04-30 11:41:18 -070049using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010050using ::testing::MatchesRegex;
Seth Moore026bb742021-04-30 11:41:18 -070051using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070052
53::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
54 if (set.size() == 0)
55 os << "(Empty)" << ::std::endl;
56 else {
57 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070058 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070059 }
60 return os;
61}
62
63namespace test {
64
Shawn Willden7f424372021-01-10 18:06:50 -070065namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010066
David Drysdale37af4b32021-05-14 16:46:59 +010067// Invalid value for a patchlevel (which is of form YYYYMMDD).
68const uint32_t kInvalidPatchlevel = 99998877;
69
David Drysdaledf8f52e2021-05-06 08:10:58 +010070// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
71// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
72const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
73
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000074typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070075// Predicate for testing basic characteristics validity in generation or import.
76bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
77 const vector<KeyCharacteristics>& key_characteristics) {
78 if (key_characteristics.empty()) return false;
79
80 std::unordered_set<SecurityLevel> levels_seen;
81 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070082 if (entry.authorizations.empty()) {
83 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
84 return false;
85 }
Shawn Willden7f424372021-01-10 18:06:50 -070086
Qi Wubeefae42021-01-28 23:16:37 +080087 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
88 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
89
Seth Moore2a9a00e2021-08-04 16:31:52 -070090 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
91 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
92 return false;
93 }
Shawn Willden7f424372021-01-10 18:06:50 -070094 levels_seen.insert(entry.securityLevel);
95
96 // Generally, we should only have one entry, at the same security level as the KM
97 // instance. There is an exception: StrongBox KM can have some authorizations that are
98 // enforced by the TEE.
99 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
100 (secLevel == SecurityLevel::STRONGBOX &&
101 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
102
Seth Moore2a9a00e2021-08-04 16:31:52 -0700103 if (!isExpectedSecurityLevel) {
104 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
105 return false;
106 }
Shawn Willden7f424372021-01-10 18:06:50 -0700107 }
108 return true;
109}
110
Shawn Willden7c130392020-12-21 09:58:22 -0700111// Extract attestation record from cert. Returned object is still part of cert; don't free it
112// separately.
113ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
114 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
115 EXPECT_TRUE(!!oid.get());
116 if (!oid.get()) return nullptr;
117
118 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
119 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
120 if (location == -1) return nullptr;
121
122 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
123 EXPECT_TRUE(!!attest_rec_ext)
124 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
125 if (!attest_rec_ext) return nullptr;
126
127 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
128 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
129 return attest_rec;
130}
131
David Drysdale7dff4fc2021-12-10 10:10:52 +0000132void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
133 // Version numbers in attestation extensions should be a multiple of 100.
134 EXPECT_EQ(attestation_version % 100, 0);
135
136 // The multiplier should never be higher than the AIDL version, but can be less
137 // (for example, if the implementation is from an earlier version but the HAL service
138 // uses the default libraries and so reports the current AIDL version).
139 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
140}
141
Shawn Willden7c130392020-12-21 09:58:22 -0700142bool avb_verification_enabled() {
143 char value[PROPERTY_VALUE_MAX];
144 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
145}
146
147char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
148 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
149
150// Attestations don't contain everything in key authorization lists, so we need to filter the key
151// lists to produce the lists that we expect to match the attestations.
152auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100153 Tag::CREATION_DATETIME,
154 Tag::HARDWARE_TYPE,
155 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700156};
157
158AuthorizationSet filtered_tags(const AuthorizationSet& set) {
159 AuthorizationSet filtered;
160 std::remove_copy_if(
161 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
162 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
163 kTagsToFilter.end();
164 });
165 return filtered;
166}
167
David Drysdale300b5552021-05-20 12:05:26 +0100168// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
169void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
170 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
171 [](const auto& entry) {
172 return entry.securityLevel == SecurityLevel::KEYSTORE;
173 }),
174 characteristics->end());
175}
176
Shawn Willden7c130392020-12-21 09:58:22 -0700177string x509NameToStr(X509_NAME* name) {
178 char* s = X509_NAME_oneline(name, nullptr, 0);
179 string retval(s);
180 OPENSSL_free(s);
181 return retval;
182}
183
Shawn Willden7f424372021-01-10 18:06:50 -0700184} // namespace
185
Shawn Willden7c130392020-12-21 09:58:22 -0700186bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
187bool KeyMintAidlTestBase::dump_Attestations = false;
188
David Drysdale37af4b32021-05-14 16:46:59 +0100189uint32_t KeyMintAidlTestBase::boot_patch_level(
190 const vector<KeyCharacteristics>& key_characteristics) {
191 // The boot patchlevel is not available as a property, but should be present
192 // in the key characteristics of any created key.
193 AuthorizationSet allAuths;
194 for (auto& entry : key_characteristics) {
195 allAuths.push_back(AuthorizationSet(entry.authorizations));
196 }
197 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
198 if (patchlevel.has_value()) {
199 return patchlevel.value();
200 } else {
201 // No boot patchlevel is available. Return a value that won't match anything
202 // and so will trigger test failures.
203 return kInvalidPatchlevel;
204 }
205}
206
207uint32_t KeyMintAidlTestBase::boot_patch_level() {
208 return boot_patch_level(key_characteristics_);
209}
210
Prashant Patil88ad1892022-03-15 16:31:02 +0000211/**
212 * An API to determine device IDs attestation is required or not,
213 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
214 */
215bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
216 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= 33;
217}
218
David Drysdale42fe1892021-10-14 14:43:46 +0100219bool KeyMintAidlTestBase::Curve25519Supported() {
220 // Strongbox never supports curve 25519.
221 if (SecLevel() == SecurityLevel::STRONGBOX) {
222 return false;
223 }
224
225 // Curve 25519 was included in version 2 of the KeyMint interface.
226 int32_t version = 0;
227 auto status = keymint_->getInterfaceVersion(&version);
228 if (!status.isOk()) {
229 ADD_FAILURE() << "Failed to determine interface version";
230 }
231 return version >= 2;
232}
233
Janis Danisevskis24c04702020-12-16 18:28:39 -0800234ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700235 if (result.isOk()) return ErrorCode::OK;
236
Janis Danisevskis24c04702020-12-16 18:28:39 -0800237 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
238 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700239 }
240
241 return ErrorCode::UNKNOWN_ERROR;
242}
243
Janis Danisevskis24c04702020-12-16 18:28:39 -0800244void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700245 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800246 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700247
248 KeyMintHardwareInfo info;
249 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
250
251 securityLevel_ = info.securityLevel;
252 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
253 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100254 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700255
256 os_version_ = getOsVersion();
257 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100258 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700259}
260
David Drysdale7dff4fc2021-12-10 10:10:52 +0000261int32_t KeyMintAidlTestBase::AidlVersion() {
262 int32_t version = 0;
263 auto status = keymint_->getInterfaceVersion(&version);
264 if (!status.isOk()) {
265 ADD_FAILURE() << "Failed to determine interface version";
266 }
267 return version;
268}
269
Selene Huang31ab4042020-04-29 04:22:39 -0700270void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800271 if (AServiceManager_isDeclared(GetParam().c_str())) {
272 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
273 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
274 } else {
275 InitializeKeyMint(nullptr);
276 }
Selene Huang31ab4042020-04-29 04:22:39 -0700277}
278
279ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700280 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700281 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700282 vector<KeyCharacteristics>* key_characteristics,
283 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700284 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
285 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700286 << "Previous characteristics not deleted before generating key. Test bug.";
287
Shawn Willden7f424372021-01-10 18:06:50 -0700288 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700289 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700290 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700291 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
292 creationResult.keyCharacteristics);
293 EXPECT_GT(creationResult.keyBlob.size(), 0);
294 *key_blob = std::move(creationResult.keyBlob);
295 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700296 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700297
298 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
299 EXPECT_TRUE(algorithm);
300 if (algorithm &&
301 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700302 EXPECT_GE(cert_chain->size(), 1);
303 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
304 if (attest_key) {
305 EXPECT_EQ(cert_chain->size(), 1);
306 } else {
307 EXPECT_GT(cert_chain->size(), 1);
308 }
309 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700310 } else {
311 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700312 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700313 }
Selene Huang31ab4042020-04-29 04:22:39 -0700314 }
315
316 return GetReturnErrorCode(result);
317}
318
Shawn Willden7c130392020-12-21 09:58:22 -0700319ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
320 const optional<AttestationKey>& attest_key) {
321 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700322}
323
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000324ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
325 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
326 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
327 vector<Certificate>* cert_chain) {
328 AttestationKey attest_key;
329 vector<Certificate> attest_cert_chain;
330 vector<KeyCharacteristics> attest_key_characteristics;
331 // Generate a key with self signed attestation.
332 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
333 &attest_key_characteristics, &attest_cert_chain);
334 if (error != ErrorCode::OK) {
335 return error;
336 }
337
338 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
339 // Generate a key, by passing the above self signed attestation key as attest key.
340 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
341 if (error == ErrorCode::OK) {
342 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
343 cert_chain->push_back(attest_cert_chain[0]);
344 }
345 return error;
346}
347
Selene Huang31ab4042020-04-29 04:22:39 -0700348ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
349 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700350 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700351 Status result;
352
Shawn Willden7f424372021-01-10 18:06:50 -0700353 cert_chain_.clear();
354 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700355 key_blob->clear();
356
Shawn Willden7f424372021-01-10 18:06:50 -0700357 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700358 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700359 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700360 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700361
362 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700363 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
364 creationResult.keyCharacteristics);
365 EXPECT_GT(creationResult.keyBlob.size(), 0);
366
367 *key_blob = std::move(creationResult.keyBlob);
368 *key_characteristics = std::move(creationResult.keyCharacteristics);
369 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700370
371 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
372 EXPECT_TRUE(algorithm);
373 if (algorithm &&
374 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
375 EXPECT_GE(cert_chain_.size(), 1);
376 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
377 } else {
378 // For symmetric keys there should be no certificates.
379 EXPECT_EQ(cert_chain_.size(), 0);
380 }
Selene Huang31ab4042020-04-29 04:22:39 -0700381 }
382
383 return GetReturnErrorCode(result);
384}
385
386ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
387 const string& key_material) {
388 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
389}
390
391ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
392 const AuthorizationSet& wrapping_key_desc,
393 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100394 const AuthorizationSet& unwrapping_params,
395 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700396 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
397
Shawn Willden7f424372021-01-10 18:06:50 -0700398 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700399
Shawn Willden7f424372021-01-10 18:06:50 -0700400 KeyCreationResult creationResult;
401 Status result = keymint_->importWrappedKey(
402 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
403 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100404 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700405
406 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700407 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
408 creationResult.keyCharacteristics);
409 EXPECT_GT(creationResult.keyBlob.size(), 0);
410
411 key_blob_ = std::move(creationResult.keyBlob);
412 key_characteristics_ = std::move(creationResult.keyCharacteristics);
413 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700414
415 AuthorizationSet allAuths;
416 for (auto& entry : key_characteristics_) {
417 allAuths.push_back(AuthorizationSet(entry.authorizations));
418 }
419 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
420 EXPECT_TRUE(algorithm);
421 if (algorithm &&
422 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
423 EXPECT_GE(cert_chain_.size(), 1);
424 } else {
425 // For symmetric keys there should be no certificates.
426 EXPECT_EQ(cert_chain_.size(), 0);
427 }
Selene Huang31ab4042020-04-29 04:22:39 -0700428 }
429
430 return GetReturnErrorCode(result);
431}
432
David Drysdale300b5552021-05-20 12:05:26 +0100433ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
434 const vector<uint8_t>& app_id,
435 const vector<uint8_t>& app_data,
436 vector<KeyCharacteristics>* key_characteristics) {
437 Status result =
438 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
439 return GetReturnErrorCode(result);
440}
441
442ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
443 vector<KeyCharacteristics>* key_characteristics) {
444 vector<uint8_t> empty_app_id, empty_app_data;
445 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
446}
447
448void KeyMintAidlTestBase::CheckCharacteristics(
449 const vector<uint8_t>& key_blob,
450 const vector<KeyCharacteristics>& generate_characteristics) {
451 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
452 // generateKey() should be excluded, as KeyMint will have no record of them.
453 // This applies to CREATION_DATETIME in particular.
454 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
455 strip_keystore_tags(&expected_characteristics);
456
457 vector<KeyCharacteristics> retrieved;
458 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
459 EXPECT_EQ(expected_characteristics, retrieved);
460}
461
462void KeyMintAidlTestBase::CheckAppIdCharacteristics(
463 const vector<uint8_t>& key_blob, std::string_view app_id_string,
464 std::string_view app_data_string,
465 const vector<KeyCharacteristics>& generate_characteristics) {
466 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
467 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
468 strip_keystore_tags(&expected_characteristics);
469
470 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
471 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
472 vector<KeyCharacteristics> retrieved;
473 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
474 EXPECT_EQ(expected_characteristics, retrieved);
475
476 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
477 vector<uint8_t> empty;
478 vector<KeyCharacteristics> not_retrieved;
479 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
480 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
481 EXPECT_EQ(not_retrieved.size(), 0);
482
483 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
484 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
485 EXPECT_EQ(not_retrieved.size(), 0);
486
487 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
488 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
489 EXPECT_EQ(not_retrieved.size(), 0);
490}
491
Selene Huang31ab4042020-04-29 04:22:39 -0700492ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
493 Status result = keymint_->deleteKey(*key_blob);
494 if (!keep_key_blob) {
495 *key_blob = vector<uint8_t>();
496 }
497
Janis Danisevskis24c04702020-12-16 18:28:39 -0800498 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700499 return GetReturnErrorCode(result);
500}
501
502ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
503 return DeleteKey(&key_blob_, keep_key_blob);
504}
505
506ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
507 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800508 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700509 return GetReturnErrorCode(result);
510}
511
David Drysdaled2cc8c22021-04-15 13:29:45 +0100512ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
513 Status result = keymint_->destroyAttestationIds();
514 return GetReturnErrorCode(result);
515}
516
Selene Huang31ab4042020-04-29 04:22:39 -0700517void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
518 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
519 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
520}
521
522void KeyMintAidlTestBase::CheckedDeleteKey() {
523 CheckedDeleteKey(&key_blob_);
524}
525
526ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
527 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800528 AuthorizationSet* out_params,
529 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700530 SCOPED_TRACE("Begin");
531 Status result;
532 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100533 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700534
535 if (result.isOk()) {
536 *out_params = out.params;
537 challenge_ = out.challenge;
538 op = out.operation;
539 }
540
541 return GetReturnErrorCode(result);
542}
543
544ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
545 const AuthorizationSet& in_params,
546 AuthorizationSet* out_params) {
547 SCOPED_TRACE("Begin");
548 Status result;
549 BeginResult out;
550
David Drysdale56ba9122021-04-19 19:10:47 +0100551 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700552
553 if (result.isOk()) {
554 *out_params = out.params;
555 challenge_ = out.challenge;
556 op_ = out.operation;
557 }
558
559 return GetReturnErrorCode(result);
560}
561
562ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
563 AuthorizationSet* out_params) {
564 SCOPED_TRACE("Begin");
565 EXPECT_EQ(nullptr, op_);
566 return Begin(purpose, key_blob_, in_params, out_params);
567}
568
569ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
570 SCOPED_TRACE("Begin");
571 AuthorizationSet out_params;
572 ErrorCode result = Begin(purpose, in_params, &out_params);
573 EXPECT_TRUE(out_params.empty());
574 return result;
575}
576
Shawn Willden92d79c02021-02-19 07:31:55 -0700577ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
578 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
579 {} /* hardwareAuthToken */,
580 {} /* verificationToken */));
581}
582
583ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700584 SCOPED_TRACE("Update");
585
586 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700587 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700588
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800589 EXPECT_NE(op_, nullptr);
590 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
591
Shawn Willden92d79c02021-02-19 07:31:55 -0700592 std::vector<uint8_t> o_put;
593 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700594
David Drysdalefeab5d92022-01-06 15:46:23 +0000595 if (result.isOk()) {
596 output->append(o_put.begin(), o_put.end());
597 } else {
598 // Failure always terminates the operation.
599 op_ = {};
600 }
Selene Huang31ab4042020-04-29 04:22:39 -0700601
602 return GetReturnErrorCode(result);
603}
604
Shawn Willden92d79c02021-02-19 07:31:55 -0700605ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700606 string* output) {
607 SCOPED_TRACE("Finish");
608 Status result;
609
610 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700611 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700612
613 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700614 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
615 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
616 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700617
Shawn Willden92d79c02021-02-19 07:31:55 -0700618 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700619
Shawn Willden92d79c02021-02-19 07:31:55 -0700620 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700621 return GetReturnErrorCode(result);
622}
623
Janis Danisevskis24c04702020-12-16 18:28:39 -0800624ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700625 SCOPED_TRACE("Abort");
626
627 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700628 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700629
630 Status retval = op->abort();
631 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800632 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700633}
634
635ErrorCode KeyMintAidlTestBase::Abort() {
636 SCOPED_TRACE("Abort");
637
638 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700639 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700640
641 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800642 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700643}
644
645void KeyMintAidlTestBase::AbortIfNeeded() {
646 SCOPED_TRACE("AbortIfNeeded");
647 if (op_) {
648 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800649 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700650 }
651}
652
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000653auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
654 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700655 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000656 AuthorizationSet begin_out_params;
657 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700658 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000659
660 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700661 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000662}
663
Selene Huang31ab4042020-04-29 04:22:39 -0700664string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
665 const string& message, const AuthorizationSet& in_params,
666 AuthorizationSet* out_params) {
667 SCOPED_TRACE("ProcessMessage");
668 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700669 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700670 EXPECT_EQ(ErrorCode::OK, result);
671 if (result != ErrorCode::OK) {
672 return "";
673 }
674
675 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700676 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700677 return output;
678}
679
680string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
681 const AuthorizationSet& params) {
682 SCOPED_TRACE("SignMessage");
683 AuthorizationSet out_params;
684 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
685 EXPECT_TRUE(out_params.empty());
686 return signature;
687}
688
689string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
690 SCOPED_TRACE("SignMessage");
691 return SignMessage(key_blob_, message, params);
692}
693
694string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
695 SCOPED_TRACE("MacMessage");
696 return SignMessage(
697 key_blob_, message,
698 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
699}
700
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530701void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
702 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000703 auto builder = AuthorizationSetBuilder()
704 .Authorization(TAG_NO_AUTH_REQUIRED)
705 .AesEncryptionKey(128)
706 .BlockMode(block_mode)
707 .Padding(PaddingMode::NONE);
708 if (block_mode == BlockMode::GCM) {
709 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
710 }
711 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530712
713 for (int increment = 1; increment <= message_size; ++increment) {
714 string message(message_size, 'a');
715 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
716 if (block_mode == BlockMode::GCM) {
717 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
718 }
719
720 AuthorizationSet output_params;
721 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
722
723 string ciphertext;
724 string to_send;
725 for (size_t i = 0; i < message.size(); i += increment) {
726 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
727 }
728 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
729 << "Error sending " << to_send << " with block mode " << block_mode;
730
731 switch (block_mode) {
732 case BlockMode::GCM:
733 EXPECT_EQ(message.size() + 16, ciphertext.size());
734 break;
735 case BlockMode::CTR:
736 EXPECT_EQ(message.size(), ciphertext.size());
737 break;
738 case BlockMode::CBC:
739 case BlockMode::ECB:
740 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
741 break;
742 }
743
744 auto iv = output_params.GetTagValue(TAG_NONCE);
745 switch (block_mode) {
746 case BlockMode::CBC:
747 case BlockMode::GCM:
748 case BlockMode::CTR:
749 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
750 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
751 params.push_back(TAG_NONCE, iv->get());
752 break;
753
754 case BlockMode::ECB:
755 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
756 break;
757 }
758
759 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
760 << "Decrypt begin() failed for block mode " << block_mode;
761
762 string plaintext;
763 for (size_t i = 0; i < ciphertext.size(); i += increment) {
764 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
765 }
766 ErrorCode error = Finish(to_send, &plaintext);
767 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
768 << " and increment " << increment;
769 if (error == ErrorCode::OK) {
770 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
771 << " and increment " << increment;
772 }
773 }
774}
775
Selene Huang31ab4042020-04-29 04:22:39 -0700776void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
777 Digest digest, const string& expected_mac) {
778 SCOPED_TRACE("CheckHmacTestVector");
779 ASSERT_EQ(ErrorCode::OK,
780 ImportKey(AuthorizationSetBuilder()
781 .Authorization(TAG_NO_AUTH_REQUIRED)
782 .HmacKey(key.size() * 8)
783 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
784 .Digest(digest),
785 KeyFormat::RAW, key));
786 string signature = MacMessage(message, digest, expected_mac.size() * 8);
787 EXPECT_EQ(expected_mac, signature)
788 << "Test vector didn't match for key of size " << key.size() << " message of size "
789 << message.size() << " and digest " << digest;
790 CheckedDeleteKey();
791}
792
793void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
794 const string& message,
795 const string& expected_ciphertext) {
796 SCOPED_TRACE("CheckAesCtrTestVector");
797 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
798 .Authorization(TAG_NO_AUTH_REQUIRED)
799 .AesEncryptionKey(key.size() * 8)
800 .BlockMode(BlockMode::CTR)
801 .Authorization(TAG_CALLER_NONCE)
802 .Padding(PaddingMode::NONE),
803 KeyFormat::RAW, key));
804
805 auto params = AuthorizationSetBuilder()
806 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
807 .BlockMode(BlockMode::CTR)
808 .Padding(PaddingMode::NONE);
809 AuthorizationSet out_params;
810 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
811 EXPECT_EQ(expected_ciphertext, ciphertext);
812}
813
814void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
815 PaddingMode padding_mode, const string& key,
816 const string& iv, const string& input,
817 const string& expected_output) {
818 auto authset = AuthorizationSetBuilder()
819 .TripleDesEncryptionKey(key.size() * 7)
820 .BlockMode(block_mode)
821 .Authorization(TAG_NO_AUTH_REQUIRED)
822 .Padding(padding_mode);
823 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
824 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
825 ASSERT_GT(key_blob_.size(), 0U);
826
827 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
828 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
829 AuthorizationSet output_params;
830 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
831 EXPECT_EQ(expected_output, output);
832}
833
834void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
835 const string& signature, const AuthorizationSet& params) {
836 SCOPED_TRACE("VerifyMessage");
837 AuthorizationSet begin_out_params;
838 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
839
840 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700841 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700842 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700843 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700844}
845
846void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
847 const AuthorizationSet& params) {
848 SCOPED_TRACE("VerifyMessage");
849 VerifyMessage(key_blob_, message, signature, params);
850}
851
David Drysdaledf8f52e2021-05-06 08:10:58 +0100852void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
853 const AuthorizationSet& params) {
854 SCOPED_TRACE("LocalVerifyMessage");
855
856 // Retrieve the public key from the leaf certificate.
857 ASSERT_GT(cert_chain_.size(), 0);
858 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
859 ASSERT_TRUE(key_cert.get());
860 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
861 ASSERT_TRUE(pub_key.get());
862
863 Digest digest = params.GetTagValue(TAG_DIGEST).value();
864 PaddingMode padding = PaddingMode::NONE;
865 auto tag = params.GetTagValue(TAG_PADDING);
866 if (tag.has_value()) {
867 padding = tag.value();
868 }
869
870 if (digest == Digest::NONE) {
871 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100872 case EVP_PKEY_ED25519: {
873 ASSERT_EQ(64, signature.size());
874 uint8_t pub_keydata[32];
875 size_t pub_len = sizeof(pub_keydata);
876 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
877 ASSERT_EQ(sizeof(pub_keydata), pub_len);
878 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
879 message.size(),
880 reinterpret_cast<const uint8_t*>(signature.data()),
881 pub_keydata));
882 break;
883 }
884
David Drysdaledf8f52e2021-05-06 08:10:58 +0100885 case EVP_PKEY_EC: {
886 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
887 size_t data_size = std::min(data.size(), message.size());
888 memcpy(data.data(), message.data(), data_size);
889 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
890 ASSERT_TRUE(ecdsa.get());
891 ASSERT_EQ(1,
892 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
893 reinterpret_cast<const uint8_t*>(signature.data()),
894 signature.size(), ecdsa.get()));
895 break;
896 }
897 case EVP_PKEY_RSA: {
898 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
899 size_t data_size = std::min(data.size(), message.size());
900 memcpy(data.data(), message.data(), data_size);
901
902 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
903 ASSERT_TRUE(rsa.get());
904
905 size_t key_len = RSA_size(rsa.get());
906 int openssl_padding = RSA_NO_PADDING;
907 switch (padding) {
908 case PaddingMode::NONE:
909 ASSERT_TRUE(data_size <= key_len);
910 ASSERT_EQ(key_len, signature.size());
911 openssl_padding = RSA_NO_PADDING;
912 break;
913 case PaddingMode::RSA_PKCS1_1_5_SIGN:
914 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
915 key_len);
916 openssl_padding = RSA_PKCS1_PADDING;
917 break;
918 default:
919 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
920 }
921
922 vector<uint8_t> decrypted_data(key_len);
923 int bytes_decrypted = RSA_public_decrypt(
924 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
925 decrypted_data.data(), rsa.get(), openssl_padding);
926 ASSERT_GE(bytes_decrypted, 0);
927
928 const uint8_t* compare_pos = decrypted_data.data();
929 size_t bytes_to_compare = bytes_decrypted;
930 uint8_t zero_check_result = 0;
931 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
932 // If the data is short, for "unpadded" signing we zero-pad to the left. So
933 // during verification we should have zeros on the left of the decrypted data.
934 // Do a constant-time check.
935 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
936 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
937 ASSERT_EQ(0, zero_check_result);
938 bytes_to_compare = data_size;
939 }
940 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
941 break;
942 }
943 default:
944 ADD_FAILURE() << "Unknown public key type";
945 }
946 } else {
947 EVP_MD_CTX digest_ctx;
948 EVP_MD_CTX_init(&digest_ctx);
949 EVP_PKEY_CTX* pkey_ctx;
950 const EVP_MD* md = openssl_digest(digest);
951 ASSERT_NE(md, nullptr);
952 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
953
954 if (padding == PaddingMode::RSA_PSS) {
955 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
956 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +0000957 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +0100958 }
959
960 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
961 reinterpret_cast<const uint8_t*>(message.data()),
962 message.size()));
963 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
964 reinterpret_cast<const uint8_t*>(signature.data()),
965 signature.size()));
966 EVP_MD_CTX_cleanup(&digest_ctx);
967 }
968}
969
David Drysdale59cae642021-05-12 13:52:03 +0100970string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
971 const AuthorizationSet& params) {
972 SCOPED_TRACE("LocalRsaEncryptMessage");
973
974 // Retrieve the public key from the leaf certificate.
975 if (cert_chain_.empty()) {
976 ADD_FAILURE() << "No public key available";
977 return "Failure";
978 }
979 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
980 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
981 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
982
983 // Retrieve relevant tags.
984 Digest digest = Digest::NONE;
985 Digest mgf_digest = Digest::NONE;
986 PaddingMode padding = PaddingMode::NONE;
987
988 auto digest_tag = params.GetTagValue(TAG_DIGEST);
989 if (digest_tag.has_value()) digest = digest_tag.value();
990 auto pad_tag = params.GetTagValue(TAG_PADDING);
991 if (pad_tag.has_value()) padding = pad_tag.value();
992 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
993 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
994
995 const EVP_MD* md = openssl_digest(digest);
996 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
997
998 // Set up encryption context.
999 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1000 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1001 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1002 return "Failure";
1003 }
1004
1005 int rc = -1;
1006 switch (padding) {
1007 case PaddingMode::NONE:
1008 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1009 break;
1010 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1011 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1012 break;
1013 case PaddingMode::RSA_OAEP:
1014 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1015 break;
1016 default:
1017 break;
1018 }
1019 if (rc <= 0) {
1020 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1021 return "Failure";
1022 }
1023 if (padding == PaddingMode::RSA_OAEP) {
1024 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1025 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1026 return "Failure";
1027 }
1028 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1029 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1030 return "Failure";
1031 }
1032 }
1033
1034 // Determine output size.
1035 size_t outlen;
1036 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1037 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1038 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1039 return "Failure";
1040 }
1041
1042 // Left-zero-pad the input if necessary.
1043 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1044 size_t to_encrypt_len = message.size();
1045
1046 std::unique_ptr<string> zero_padded_message;
1047 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1048 zero_padded_message.reset(new string(outlen, '\0'));
1049 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1050 message.size());
1051 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1052 to_encrypt_len = outlen;
1053 }
1054
1055 // Do the encryption.
1056 string output(outlen, '\0');
1057 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1058 to_encrypt_len) <= 0) {
1059 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1060 return "Failure";
1061 }
1062 return output;
1063}
1064
Selene Huang31ab4042020-04-29 04:22:39 -07001065string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1066 const AuthorizationSet& in_params,
1067 AuthorizationSet* out_params) {
1068 SCOPED_TRACE("EncryptMessage");
1069 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1070}
1071
1072string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1073 AuthorizationSet* out_params) {
1074 SCOPED_TRACE("EncryptMessage");
1075 return EncryptMessage(key_blob_, message, params, out_params);
1076}
1077
1078string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1079 SCOPED_TRACE("EncryptMessage");
1080 AuthorizationSet out_params;
1081 string ciphertext = EncryptMessage(message, params, &out_params);
1082 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1083 return ciphertext;
1084}
1085
1086string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1087 PaddingMode padding) {
1088 SCOPED_TRACE("EncryptMessage");
1089 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1090 AuthorizationSet out_params;
1091 string ciphertext = EncryptMessage(message, params, &out_params);
1092 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1093 return ciphertext;
1094}
1095
1096string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1097 PaddingMode padding, vector<uint8_t>* iv_out) {
1098 SCOPED_TRACE("EncryptMessage");
1099 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1100 AuthorizationSet out_params;
1101 string ciphertext = EncryptMessage(message, params, &out_params);
1102 EXPECT_EQ(1U, out_params.size());
1103 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001104 EXPECT_TRUE(ivVal);
1105 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001106 return ciphertext;
1107}
1108
1109string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1110 PaddingMode padding, const vector<uint8_t>& iv_in) {
1111 SCOPED_TRACE("EncryptMessage");
1112 auto params = AuthorizationSetBuilder()
1113 .BlockMode(block_mode)
1114 .Padding(padding)
1115 .Authorization(TAG_NONCE, iv_in);
1116 AuthorizationSet out_params;
1117 string ciphertext = EncryptMessage(message, params, &out_params);
1118 return ciphertext;
1119}
1120
1121string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1122 PaddingMode padding, uint8_t mac_length_bits,
1123 const vector<uint8_t>& iv_in) {
1124 SCOPED_TRACE("EncryptMessage");
1125 auto params = AuthorizationSetBuilder()
1126 .BlockMode(block_mode)
1127 .Padding(padding)
1128 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1129 .Authorization(TAG_NONCE, iv_in);
1130 AuthorizationSet out_params;
1131 string ciphertext = EncryptMessage(message, params, &out_params);
1132 return ciphertext;
1133}
1134
David Drysdaled2cc8c22021-04-15 13:29:45 +01001135string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1136 PaddingMode padding, uint8_t mac_length_bits) {
1137 SCOPED_TRACE("EncryptMessage");
1138 auto params = AuthorizationSetBuilder()
1139 .BlockMode(block_mode)
1140 .Padding(padding)
1141 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1142 AuthorizationSet out_params;
1143 string ciphertext = EncryptMessage(message, params, &out_params);
1144 return ciphertext;
1145}
1146
Selene Huang31ab4042020-04-29 04:22:39 -07001147string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1148 const string& ciphertext,
1149 const AuthorizationSet& params) {
1150 SCOPED_TRACE("DecryptMessage");
1151 AuthorizationSet out_params;
1152 string plaintext =
1153 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1154 EXPECT_TRUE(out_params.empty());
1155 return plaintext;
1156}
1157
1158string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1159 const AuthorizationSet& params) {
1160 SCOPED_TRACE("DecryptMessage");
1161 return DecryptMessage(key_blob_, ciphertext, params);
1162}
1163
1164string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1165 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1166 SCOPED_TRACE("DecryptMessage");
1167 auto params = AuthorizationSetBuilder()
1168 .BlockMode(block_mode)
1169 .Padding(padding_mode)
1170 .Authorization(TAG_NONCE, iv);
1171 return DecryptMessage(key_blob_, ciphertext, params);
1172}
1173
1174std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1175 const vector<uint8_t>& key_blob) {
1176 std::pair<ErrorCode, vector<uint8_t>> retval;
1177 vector<uint8_t> outKeyBlob;
1178 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1179 ErrorCode errorcode = GetReturnErrorCode(result);
1180 retval = std::tie(errorcode, outKeyBlob);
1181
1182 return retval;
1183}
1184vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1185 switch (algorithm) {
1186 case Algorithm::RSA:
1187 switch (SecLevel()) {
1188 case SecurityLevel::SOFTWARE:
1189 case SecurityLevel::TRUSTED_ENVIRONMENT:
1190 return {2048, 3072, 4096};
1191 case SecurityLevel::STRONGBOX:
1192 return {2048};
1193 default:
1194 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1195 break;
1196 }
1197 break;
1198 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001199 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001200 break;
1201 case Algorithm::AES:
1202 return {128, 256};
1203 case Algorithm::TRIPLE_DES:
1204 return {168};
1205 case Algorithm::HMAC: {
1206 vector<uint32_t> retval((512 - 64) / 8 + 1);
1207 uint32_t size = 64 - 8;
1208 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1209 return retval;
1210 }
1211 default:
1212 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1213 return {};
1214 }
1215 ADD_FAILURE() << "Should be impossible to get here";
1216 return {};
1217}
1218
1219vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1220 if (SecLevel() == SecurityLevel::STRONGBOX) {
1221 switch (algorithm) {
1222 case Algorithm::RSA:
1223 return {3072, 4096};
1224 case Algorithm::EC:
1225 return {224, 384, 521};
1226 case Algorithm::AES:
1227 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001228 case Algorithm::TRIPLE_DES:
1229 return {56};
1230 default:
1231 return {};
1232 }
1233 } else {
1234 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001235 case Algorithm::AES:
1236 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001237 case Algorithm::TRIPLE_DES:
1238 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001239 default:
1240 return {};
1241 }
1242 }
1243 return {};
1244}
1245
David Drysdale7de9feb2021-03-05 14:56:19 +00001246vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1247 switch (algorithm) {
1248 case Algorithm::AES:
1249 return {
1250 BlockMode::CBC,
1251 BlockMode::CTR,
1252 BlockMode::ECB,
1253 BlockMode::GCM,
1254 };
1255 case Algorithm::TRIPLE_DES:
1256 return {
1257 BlockMode::CBC,
1258 BlockMode::ECB,
1259 };
1260 default:
1261 return {};
1262 }
1263}
1264
1265vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1266 BlockMode blockMode) {
1267 switch (algorithm) {
1268 case Algorithm::AES:
1269 switch (blockMode) {
1270 case BlockMode::CBC:
1271 case BlockMode::ECB:
1272 return {PaddingMode::NONE, PaddingMode::PKCS7};
1273 case BlockMode::CTR:
1274 case BlockMode::GCM:
1275 return {PaddingMode::NONE};
1276 default:
1277 return {};
1278 };
1279 case Algorithm::TRIPLE_DES:
1280 switch (blockMode) {
1281 case BlockMode::CBC:
1282 case BlockMode::ECB:
1283 return {PaddingMode::NONE, PaddingMode::PKCS7};
1284 default:
1285 return {};
1286 };
1287 default:
1288 return {};
1289 }
1290}
1291
1292vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1293 BlockMode blockMode) {
1294 switch (algorithm) {
1295 case Algorithm::AES:
1296 switch (blockMode) {
1297 case BlockMode::CTR:
1298 case BlockMode::GCM:
1299 return {PaddingMode::PKCS7};
1300 default:
1301 return {};
1302 };
1303 default:
1304 return {};
1305 }
1306}
1307
Selene Huang31ab4042020-04-29 04:22:39 -07001308vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1309 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1310 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001311 } else if (Curve25519Supported()) {
1312 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1313 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001314 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001315 return {
1316 EcCurve::P_224,
1317 EcCurve::P_256,
1318 EcCurve::P_384,
1319 EcCurve::P_521,
1320 };
Selene Huang31ab4042020-04-29 04:22:39 -07001321 }
1322}
1323
1324vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001325 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001326 // Curve 25519 is not supported, either because:
1327 // - KeyMint v1: it's an unknown enum value
1328 // - KeyMint v2+: it's not supported by StrongBox.
1329 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001330 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001331 if (Curve25519Supported()) {
1332 return {};
1333 } else {
1334 return {EcCurve::CURVE_25519};
1335 }
David Drysdaledf09e542021-06-08 15:46:11 +01001336 }
Selene Huang31ab4042020-04-29 04:22:39 -07001337}
1338
subrahmanyaman05642492022-02-05 07:10:56 +00001339vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1340 if (SecLevel() == SecurityLevel::STRONGBOX) {
1341 return {65537};
1342 } else {
1343 return {3, 65537};
1344 }
1345}
1346
Selene Huang31ab4042020-04-29 04:22:39 -07001347vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1348 switch (SecLevel()) {
1349 case SecurityLevel::SOFTWARE:
1350 case SecurityLevel::TRUSTED_ENVIRONMENT:
1351 if (withNone) {
1352 if (withMD5)
1353 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1354 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1355 Digest::SHA_2_512};
1356 else
1357 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1358 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1359 } else {
1360 if (withMD5)
1361 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1362 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1363 else
1364 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1365 Digest::SHA_2_512};
1366 }
1367 break;
1368 case SecurityLevel::STRONGBOX:
1369 if (withNone)
1370 return {Digest::NONE, Digest::SHA_2_256};
1371 else
1372 return {Digest::SHA_2_256};
1373 break;
1374 default:
1375 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1376 break;
1377 }
1378 ADD_FAILURE() << "Should be impossible to get here";
1379 return {};
1380}
1381
Shawn Willden7f424372021-01-10 18:06:50 -07001382static const vector<KeyParameter> kEmptyAuthList{};
1383
1384const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1385 const vector<KeyCharacteristics>& key_characteristics) {
1386 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1387 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1388 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1389}
1390
Qi Wubeefae42021-01-28 23:16:37 +08001391const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1392 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1393 auto found = std::find_if(
1394 key_characteristics.begin(), key_characteristics.end(),
1395 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001396 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1397}
1398
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001399ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001400 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001401 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1402 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1403 return result;
1404}
1405
1406ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001407 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001408 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1409 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1410 return result;
1411}
1412
1413ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1414 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001415 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001416 rsaKeyBlob, KeyPurpose::SIGN, message,
1417 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1418 return result;
1419}
1420
1421ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001422 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1423 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001424 return result;
1425}
1426
Selene Huang6e46f142021-04-20 19:20:11 -07001427void verify_serial(X509* cert, const uint64_t expected_serial) {
1428 BIGNUM_Ptr ser(BN_new());
1429 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1430
1431 uint64_t serial;
1432 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1433 EXPECT_EQ(serial, expected_serial);
1434}
1435
1436// Please set self_signed to true for fake certificates or self signed
1437// certificates
1438void verify_subject(const X509* cert, //
1439 const string& subject, //
1440 bool self_signed) {
1441 char* cert_issuer = //
1442 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1443
1444 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1445
1446 string expected_subject("/CN=");
1447 if (subject.empty()) {
1448 expected_subject.append("Android Keystore Key");
1449 } else {
1450 expected_subject.append(subject);
1451 }
1452
1453 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1454
1455 if (self_signed) {
1456 EXPECT_STREQ(cert_issuer, cert_subj)
1457 << "Cert issuer and subject mismatch for self signed certificate.";
1458 }
1459
1460 OPENSSL_free(cert_subj);
1461 OPENSSL_free(cert_issuer);
1462}
1463
David Drysdale555ba002022-05-03 18:48:57 +01001464bool is_gsi_image() {
1465 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1466 return ifs.good();
1467}
1468
Selene Huang6e46f142021-04-20 19:20:11 -07001469vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1470 BIGNUM_Ptr serial(BN_new());
1471 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1472
1473 int len = BN_num_bytes(serial.get());
1474 vector<uint8_t> serial_blob(len);
1475 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1476 return {};
1477 }
1478
David Drysdaledb0dcf52021-05-18 11:43:31 +01001479 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1480 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1481 // Top bit being set indicates a negative number in two's complement, but our input
1482 // was positive.
1483 // In either case, prepend a zero byte.
1484 serial_blob.insert(serial_blob.begin(), 0x00);
1485 }
1486
Selene Huang6e46f142021-04-20 19:20:11 -07001487 return serial_blob;
1488}
1489
1490void verify_subject_and_serial(const Certificate& certificate, //
1491 const uint64_t expected_serial, //
1492 const string& subject, bool self_signed) {
1493 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1494 ASSERT_TRUE(!!cert.get());
1495
1496 verify_serial(cert.get(), expected_serial);
1497 verify_subject(cert.get(), subject, self_signed);
1498}
1499
David Drysdale7dff4fc2021-12-10 10:10:52 +00001500bool verify_attestation_record(int32_t aidl_version, //
1501 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001502 const string& app_id, //
1503 AuthorizationSet expected_sw_enforced, //
1504 AuthorizationSet expected_hw_enforced, //
1505 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001506 const vector<uint8_t>& attestation_cert,
1507 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001508 X509_Ptr cert(parse_cert_blob(attestation_cert));
1509 EXPECT_TRUE(!!cert.get());
1510 if (!cert.get()) return false;
1511
1512 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1513 EXPECT_TRUE(!!attest_rec);
1514 if (!attest_rec) return false;
1515
1516 AuthorizationSet att_sw_enforced;
1517 AuthorizationSet att_hw_enforced;
1518 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001519 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001520 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001521 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001522 vector<uint8_t> att_challenge;
1523 vector<uint8_t> att_unique_id;
1524 vector<uint8_t> att_app_id;
1525
1526 auto error = parse_attestation_record(attest_rec->data, //
1527 attest_rec->length, //
1528 &att_attestation_version, //
1529 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001530 &att_keymint_version, //
1531 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001532 &att_challenge, //
1533 &att_sw_enforced, //
1534 &att_hw_enforced, //
1535 &att_unique_id);
1536 EXPECT_EQ(ErrorCode::OK, error);
1537 if (error != ErrorCode::OK) return false;
1538
David Drysdale7dff4fc2021-12-10 10:10:52 +00001539 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001540 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001541
Selene Huang4f64c222021-04-13 19:54:36 -07001542 // check challenge and app id only if we expects a non-fake certificate
1543 if (challenge.length() > 0) {
1544 EXPECT_EQ(challenge.length(), att_challenge.size());
1545 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1546
1547 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1548 }
Shawn Willden7c130392020-12-21 09:58:22 -07001549
David Drysdale7dff4fc2021-12-10 10:10:52 +00001550 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001551 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001552 EXPECT_EQ(security_level, att_attestation_security_level);
1553
Shawn Willden7c130392020-12-21 09:58:22 -07001554
1555 char property_value[PROPERTY_VALUE_MAX] = {};
1556 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001557 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001558 // for the BOOT_PATCH_LEVEL.
1559 if (avb_verification_enabled()) {
1560 for (int i = 0; i < att_hw_enforced.size(); i++) {
1561 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1562 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1563 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001564 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001565
Shawn Willden7c130392020-12-21 09:58:22 -07001566 // strptime seems to require delimiters, but the tag value will
1567 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001568 if (date.size() != 8) {
1569 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1570 << " with invalid format (not YYYYMMDD): " << date;
1571 return false;
1572 }
Shawn Willden7c130392020-12-21 09:58:22 -07001573 date.insert(6, "-");
1574 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001575 struct tm time;
1576 strptime(date.c_str(), "%Y-%m-%d", &time);
1577
1578 // Day of the month (0-31)
1579 EXPECT_GE(time.tm_mday, 0);
1580 EXPECT_LT(time.tm_mday, 32);
1581 // Months since Jan (0-11)
1582 EXPECT_GE(time.tm_mon, 0);
1583 EXPECT_LT(time.tm_mon, 12);
1584 // Years since 1900
1585 EXPECT_GT(time.tm_year, 110);
1586 EXPECT_LT(time.tm_year, 200);
1587 }
1588 }
1589 }
1590
1591 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1592 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1593 // indicates correct encoding. No need to check if it's in both lists, since the
1594 // AuthorizationSet compare below will handle mismatches of tags.
1595 if (security_level == SecurityLevel::SOFTWARE) {
1596 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1597 } else {
1598 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1599 }
1600
Shawn Willden7c130392020-12-21 09:58:22 -07001601 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1602 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1603 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1604 att_hw_enforced.Contains(TAG_KEY_SIZE));
1605 }
1606
1607 // Test root of trust elements
1608 vector<uint8_t> verified_boot_key;
1609 VerifiedBoot verified_boot_state;
1610 bool device_locked;
1611 vector<uint8_t> verified_boot_hash;
1612 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1613 &verified_boot_state, &device_locked, &verified_boot_hash);
1614 EXPECT_EQ(ErrorCode::OK, error);
1615
1616 if (avb_verification_enabled()) {
1617 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1618 string prop_string(property_value);
1619 EXPECT_EQ(prop_string.size(), 64);
1620 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1621
1622 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1623 if (!strcmp(property_value, "unlocked")) {
1624 EXPECT_FALSE(device_locked);
1625 } else {
1626 EXPECT_TRUE(device_locked);
1627 }
1628
1629 // Check that the device is locked if not debuggable, e.g., user build
1630 // images in CTS. For VTS, debuggable images are used to allow adb root
1631 // and the device is unlocked.
1632 if (!property_get_bool("ro.debuggable", false)) {
1633 EXPECT_TRUE(device_locked);
1634 } else {
1635 EXPECT_FALSE(device_locked);
1636 }
1637 }
1638
1639 // Verified boot key should be all 0's if the boot state is not verified or self signed
1640 std::string empty_boot_key(32, '\0');
1641 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1642 verified_boot_key.size());
1643 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1644 if (!strcmp(property_value, "green")) {
1645 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1646 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1647 verified_boot_key.size()));
1648 } else if (!strcmp(property_value, "yellow")) {
1649 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1650 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1651 verified_boot_key.size()));
1652 } else if (!strcmp(property_value, "orange")) {
1653 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1654 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1655 verified_boot_key.size()));
1656 } else if (!strcmp(property_value, "red")) {
1657 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1658 } else {
1659 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
Tri Voaf291412022-03-08 10:06:00 -08001660 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
Shawn Willden7c130392020-12-21 09:58:22 -07001661 verified_boot_key.size()));
1662 }
1663
1664 att_sw_enforced.Sort();
1665 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001666 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001667
1668 att_hw_enforced.Sort();
1669 expected_hw_enforced.Sort();
1670 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1671
David Drysdale565ccc72021-10-11 12:49:50 +01001672 if (unique_id != nullptr) {
1673 *unique_id = att_unique_id;
1674 }
1675
Shawn Willden7c130392020-12-21 09:58:22 -07001676 return true;
1677}
1678
1679string bin2hex(const vector<uint8_t>& data) {
1680 string retval;
1681 retval.reserve(data.size() * 2 + 1);
1682 for (uint8_t byte : data) {
1683 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1684 retval.push_back(nibble2hex[0x0F & byte]);
1685 }
1686 return retval;
1687}
1688
David Drysdalef0d516d2021-03-22 07:51:43 +00001689AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1690 AuthorizationSet authList;
1691 for (auto& entry : key_characteristics) {
1692 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1693 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1694 authList.push_back(AuthorizationSet(entry.authorizations));
1695 }
1696 }
1697 return authList;
1698}
1699
1700AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1701 AuthorizationSet authList;
1702 for (auto& entry : key_characteristics) {
1703 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1704 entry.securityLevel == SecurityLevel::KEYSTORE) {
1705 authList.push_back(AuthorizationSet(entry.authorizations));
1706 }
1707 }
1708 return authList;
1709}
1710
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001711AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1712 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001713 std::stringstream cert_data;
1714
1715 for (size_t i = 0; i < chain.size(); ++i) {
1716 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1717
1718 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1719 X509_Ptr signing_cert;
1720 if (i < chain.size() - 1) {
1721 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1722 } else {
1723 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1724 }
1725 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1726
1727 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1728 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1729
1730 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1731 return AssertionFailure()
1732 << "Verification of certificate " << i << " failed "
1733 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1734 << cert_data.str();
1735 }
1736
1737 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1738 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001739 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001740 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1741 << " Signer subject is " << signer_subj
1742 << " Issuer subject is " << cert_issuer << endl
1743 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001744 }
Shawn Willden7c130392020-12-21 09:58:22 -07001745 }
1746
1747 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1748 return AssertionSuccess();
1749}
1750
1751X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1752 const uint8_t* p = blob.data();
1753 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1754}
1755
David Drysdalef0d516d2021-03-22 07:51:43 +00001756vector<uint8_t> make_name_from_str(const string& name) {
1757 X509_NAME_Ptr x509_name(X509_NAME_new());
1758 EXPECT_TRUE(x509_name.get() != nullptr);
1759 if (!x509_name) return {};
1760
1761 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1762 "CN", //
1763 MBSTRING_ASC,
1764 reinterpret_cast<const uint8_t*>(name.c_str()),
1765 -1, // len
1766 -1, // loc
1767 0 /* set */));
1768
1769 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1770 EXPECT_GT(len, 0);
1771
1772 vector<uint8_t> retval(len);
1773 uint8_t* p = retval.data();
1774 i2d_X509_NAME(x509_name.get(), &p);
1775
1776 return retval;
1777}
1778
David Drysdale4dc01072021-04-01 12:17:35 +01001779namespace {
1780
1781void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1782 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1783 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1784
1785 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1786 if (testMode) {
1787 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1788 MatchesRegex("{\n"
1789 " 1 : 2,\n" // kty: EC2
1790 " 3 : -7,\n" // alg: ES256
1791 " -1 : 1,\n" // EC id: P256
1792 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1793 // sequence of 32 hexadecimal bytes, enclosed in braces and
1794 // separated by commas. In this case, some Ed25519 public key.
1795 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1796 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1797 " -70000 : null,\n" // test marker
1798 "}"));
1799 } else {
1800 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1801 MatchesRegex("{\n"
1802 " 1 : 2,\n" // kty: EC2
1803 " 3 : -7,\n" // alg: ES256
1804 " -1 : 1,\n" // EC id: P256
1805 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1806 // sequence of 32 hexadecimal bytes, enclosed in braces and
1807 // separated by commas. In this case, some Ed25519 public key.
1808 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1809 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1810 "}"));
1811 }
1812}
1813
1814} // namespace
1815
1816void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1817 vector<uint8_t>* payload_value) {
1818 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1819 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1820
1821 ASSERT_NE(coseMac0->asArray(), nullptr);
1822 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1823
1824 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1825 ASSERT_NE(protParms, nullptr);
1826
1827 // Header label:value of 'alg': HMAC-256
1828 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1829
1830 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1831 ASSERT_NE(unprotParms, nullptr);
1832 ASSERT_EQ(unprotParms->size(), 0);
1833
1834 // The payload is a bstr holding an encoded COSE_Key
1835 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1836 ASSERT_NE(payload, nullptr);
1837 check_cose_key(payload->value(), testMode);
1838
1839 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1840 ASSERT_TRUE(coseMac0Tag);
1841 auto extractedTag = coseMac0Tag->value();
1842 EXPECT_EQ(extractedTag.size(), 32U);
1843
1844 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001845 auto macFunction = [](const cppcose::bytevec& input) {
1846 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1847 };
1848 auto testTag =
1849 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001850 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1851
1852 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001853 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001854 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001855 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001856 }
1857 if (payload_value != nullptr) {
1858 *payload_value = payload->value();
1859 }
1860}
1861
1862void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1863 // Extract x and y affine coordinates from the encoded Cose_Key.
1864 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1865 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1866 auto coseKey = parsedPayload->asMap();
1867 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1868 ASSERT_NE(xItem->asBstr(), nullptr);
1869 vector<uint8_t> x = xItem->asBstr()->value();
1870 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1871 ASSERT_NE(yItem->asBstr(), nullptr);
1872 vector<uint8_t> y = yItem->asBstr()->value();
1873
1874 // Concatenate: 0x04 (uncompressed form marker) | x | y
1875 vector<uint8_t> pubKeyData{0x04};
1876 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1877 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1878
1879 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1880 ASSERT_NE(ecKey, nullptr);
1881 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1882 ASSERT_NE(group, nullptr);
1883 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1884 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1885 ASSERT_NE(point, nullptr);
1886 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1887 nullptr),
1888 1);
1889 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1890
1891 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1892 ASSERT_NE(pubKey, nullptr);
1893 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1894 *signingKey = std::move(pubKey);
1895}
1896
Selene Huang31ab4042020-04-29 04:22:39 -07001897} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001898
Janis Danisevskis24c04702020-12-16 18:28:39 -08001899} // namespace aidl::android::hardware::security::keymint