blob: 54730627cfa81d4639aa41e9aecc87e071c2591f [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 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
Prashant Patil88ad1892022-03-15 16:31:02 +0000210/**
211 * An API to determine device IDs attestation is required or not,
212 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
213 */
214bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
215 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= 33;
216}
217
David Drysdale42fe1892021-10-14 14:43:46 +0100218bool KeyMintAidlTestBase::Curve25519Supported() {
219 // Strongbox never supports curve 25519.
220 if (SecLevel() == SecurityLevel::STRONGBOX) {
221 return false;
222 }
223
224 // Curve 25519 was included in version 2 of the KeyMint interface.
225 int32_t version = 0;
226 auto status = keymint_->getInterfaceVersion(&version);
227 if (!status.isOk()) {
228 ADD_FAILURE() << "Failed to determine interface version";
229 }
230 return version >= 2;
231}
232
Janis Danisevskis24c04702020-12-16 18:28:39 -0800233ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700234 if (result.isOk()) return ErrorCode::OK;
235
Janis Danisevskis24c04702020-12-16 18:28:39 -0800236 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
237 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700238 }
239
240 return ErrorCode::UNKNOWN_ERROR;
241}
242
Janis Danisevskis24c04702020-12-16 18:28:39 -0800243void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700244 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800245 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700246
247 KeyMintHardwareInfo info;
248 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
249
250 securityLevel_ = info.securityLevel;
251 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
252 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100253 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700254
255 os_version_ = getOsVersion();
256 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100257 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700258}
259
David Drysdale7dff4fc2021-12-10 10:10:52 +0000260int32_t KeyMintAidlTestBase::AidlVersion() {
261 int32_t version = 0;
262 auto status = keymint_->getInterfaceVersion(&version);
263 if (!status.isOk()) {
264 ADD_FAILURE() << "Failed to determine interface version";
265 }
266 return version;
267}
268
Selene Huang31ab4042020-04-29 04:22:39 -0700269void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800270 if (AServiceManager_isDeclared(GetParam().c_str())) {
271 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
272 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
273 } else {
274 InitializeKeyMint(nullptr);
275 }
Selene Huang31ab4042020-04-29 04:22:39 -0700276}
277
278ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700279 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700280 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700281 vector<KeyCharacteristics>* key_characteristics,
282 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700283 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
284 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700285 << "Previous characteristics not deleted before generating key. Test bug.";
286
Shawn Willden7f424372021-01-10 18:06:50 -0700287 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700288 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700289 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700290 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
291 creationResult.keyCharacteristics);
292 EXPECT_GT(creationResult.keyBlob.size(), 0);
293 *key_blob = std::move(creationResult.keyBlob);
294 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700295 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700296
297 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
298 EXPECT_TRUE(algorithm);
299 if (algorithm &&
300 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700301 EXPECT_GE(cert_chain->size(), 1);
302 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
303 if (attest_key) {
304 EXPECT_EQ(cert_chain->size(), 1);
305 } else {
306 EXPECT_GT(cert_chain->size(), 1);
307 }
308 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700309 } else {
310 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700311 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700312 }
Selene Huang31ab4042020-04-29 04:22:39 -0700313 }
314
315 return GetReturnErrorCode(result);
316}
317
Shawn Willden7c130392020-12-21 09:58:22 -0700318ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
319 const optional<AttestationKey>& attest_key) {
320 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700321}
322
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000323ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
324 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
325 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
326 vector<Certificate>* cert_chain) {
327 AttestationKey attest_key;
328 vector<Certificate> attest_cert_chain;
329 vector<KeyCharacteristics> attest_key_characteristics;
330 // Generate a key with self signed attestation.
331 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
332 &attest_key_characteristics, &attest_cert_chain);
333 if (error != ErrorCode::OK) {
334 return error;
335 }
336
337 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
338 // Generate a key, by passing the above self signed attestation key as attest key.
339 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
340 if (error == ErrorCode::OK) {
341 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
342 cert_chain->push_back(attest_cert_chain[0]);
343 }
344 return error;
345}
346
Selene Huang31ab4042020-04-29 04:22:39 -0700347ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
348 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700349 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700350 Status result;
351
Shawn Willden7f424372021-01-10 18:06:50 -0700352 cert_chain_.clear();
353 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700354 key_blob->clear();
355
Shawn Willden7f424372021-01-10 18:06:50 -0700356 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700357 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700358 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700359 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700360
361 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700362 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
363 creationResult.keyCharacteristics);
364 EXPECT_GT(creationResult.keyBlob.size(), 0);
365
366 *key_blob = std::move(creationResult.keyBlob);
367 *key_characteristics = std::move(creationResult.keyCharacteristics);
368 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700369
370 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
371 EXPECT_TRUE(algorithm);
372 if (algorithm &&
373 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
374 EXPECT_GE(cert_chain_.size(), 1);
375 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
376 } else {
377 // For symmetric keys there should be no certificates.
378 EXPECT_EQ(cert_chain_.size(), 0);
379 }
Selene Huang31ab4042020-04-29 04:22:39 -0700380 }
381
382 return GetReturnErrorCode(result);
383}
384
385ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
386 const string& key_material) {
387 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
388}
389
390ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
391 const AuthorizationSet& wrapping_key_desc,
392 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393 const AuthorizationSet& unwrapping_params,
394 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700395 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
396
Shawn Willden7f424372021-01-10 18:06:50 -0700397 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700398
Shawn Willden7f424372021-01-10 18:06:50 -0700399 KeyCreationResult creationResult;
400 Status result = keymint_->importWrappedKey(
401 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
402 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100403 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700404
405 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700406 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
407 creationResult.keyCharacteristics);
408 EXPECT_GT(creationResult.keyBlob.size(), 0);
409
410 key_blob_ = std::move(creationResult.keyBlob);
411 key_characteristics_ = std::move(creationResult.keyCharacteristics);
412 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700413
414 AuthorizationSet allAuths;
415 for (auto& entry : key_characteristics_) {
416 allAuths.push_back(AuthorizationSet(entry.authorizations));
417 }
418 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
419 EXPECT_TRUE(algorithm);
420 if (algorithm &&
421 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
422 EXPECT_GE(cert_chain_.size(), 1);
423 } else {
424 // For symmetric keys there should be no certificates.
425 EXPECT_EQ(cert_chain_.size(), 0);
426 }
Selene Huang31ab4042020-04-29 04:22:39 -0700427 }
428
429 return GetReturnErrorCode(result);
430}
431
David Drysdale300b5552021-05-20 12:05:26 +0100432ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
433 const vector<uint8_t>& app_id,
434 const vector<uint8_t>& app_data,
435 vector<KeyCharacteristics>* key_characteristics) {
436 Status result =
437 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
438 return GetReturnErrorCode(result);
439}
440
441ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
442 vector<KeyCharacteristics>* key_characteristics) {
443 vector<uint8_t> empty_app_id, empty_app_data;
444 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
445}
446
447void KeyMintAidlTestBase::CheckCharacteristics(
448 const vector<uint8_t>& key_blob,
449 const vector<KeyCharacteristics>& generate_characteristics) {
450 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
451 // generateKey() should be excluded, as KeyMint will have no record of them.
452 // This applies to CREATION_DATETIME in particular.
453 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
454 strip_keystore_tags(&expected_characteristics);
455
456 vector<KeyCharacteristics> retrieved;
457 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
458 EXPECT_EQ(expected_characteristics, retrieved);
459}
460
461void KeyMintAidlTestBase::CheckAppIdCharacteristics(
462 const vector<uint8_t>& key_blob, std::string_view app_id_string,
463 std::string_view app_data_string,
464 const vector<KeyCharacteristics>& generate_characteristics) {
465 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
466 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
467 strip_keystore_tags(&expected_characteristics);
468
469 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
470 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
471 vector<KeyCharacteristics> retrieved;
472 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
473 EXPECT_EQ(expected_characteristics, retrieved);
474
475 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
476 vector<uint8_t> empty;
477 vector<KeyCharacteristics> not_retrieved;
478 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
479 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
480 EXPECT_EQ(not_retrieved.size(), 0);
481
482 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
483 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
484 EXPECT_EQ(not_retrieved.size(), 0);
485
486 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
487 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
488 EXPECT_EQ(not_retrieved.size(), 0);
489}
490
Selene Huang31ab4042020-04-29 04:22:39 -0700491ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
492 Status result = keymint_->deleteKey(*key_blob);
493 if (!keep_key_blob) {
494 *key_blob = vector<uint8_t>();
495 }
496
Janis Danisevskis24c04702020-12-16 18:28:39 -0800497 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700498 return GetReturnErrorCode(result);
499}
500
501ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
502 return DeleteKey(&key_blob_, keep_key_blob);
503}
504
505ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
506 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800507 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700508 return GetReturnErrorCode(result);
509}
510
David Drysdaled2cc8c22021-04-15 13:29:45 +0100511ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
512 Status result = keymint_->destroyAttestationIds();
513 return GetReturnErrorCode(result);
514}
515
Selene Huang31ab4042020-04-29 04:22:39 -0700516void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
517 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
518 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
519}
520
521void KeyMintAidlTestBase::CheckedDeleteKey() {
522 CheckedDeleteKey(&key_blob_);
523}
524
525ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
526 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800527 AuthorizationSet* out_params,
528 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700529 SCOPED_TRACE("Begin");
530 Status result;
531 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100532 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700533
534 if (result.isOk()) {
535 *out_params = out.params;
536 challenge_ = out.challenge;
537 op = out.operation;
538 }
539
540 return GetReturnErrorCode(result);
541}
542
543ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
544 const AuthorizationSet& in_params,
545 AuthorizationSet* out_params) {
546 SCOPED_TRACE("Begin");
547 Status result;
548 BeginResult out;
549
David Drysdale56ba9122021-04-19 19:10:47 +0100550 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700551
552 if (result.isOk()) {
553 *out_params = out.params;
554 challenge_ = out.challenge;
555 op_ = out.operation;
556 }
557
558 return GetReturnErrorCode(result);
559}
560
561ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
562 AuthorizationSet* out_params) {
563 SCOPED_TRACE("Begin");
564 EXPECT_EQ(nullptr, op_);
565 return Begin(purpose, key_blob_, in_params, out_params);
566}
567
568ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
569 SCOPED_TRACE("Begin");
570 AuthorizationSet out_params;
571 ErrorCode result = Begin(purpose, in_params, &out_params);
572 EXPECT_TRUE(out_params.empty());
573 return result;
574}
575
Shawn Willden92d79c02021-02-19 07:31:55 -0700576ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
577 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
578 {} /* hardwareAuthToken */,
579 {} /* verificationToken */));
580}
581
582ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700583 SCOPED_TRACE("Update");
584
585 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700586 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700587
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800588 EXPECT_NE(op_, nullptr);
589 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
590
Shawn Willden92d79c02021-02-19 07:31:55 -0700591 std::vector<uint8_t> o_put;
592 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700593
David Drysdalefeab5d92022-01-06 15:46:23 +0000594 if (result.isOk()) {
595 output->append(o_put.begin(), o_put.end());
596 } else {
597 // Failure always terminates the operation.
598 op_ = {};
599 }
Selene Huang31ab4042020-04-29 04:22:39 -0700600
601 return GetReturnErrorCode(result);
602}
603
Shawn Willden92d79c02021-02-19 07:31:55 -0700604ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700605 string* output) {
606 SCOPED_TRACE("Finish");
607 Status result;
608
609 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700610 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700611
612 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700613 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
614 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
615 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700616
Shawn Willden92d79c02021-02-19 07:31:55 -0700617 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Shawn Willden92d79c02021-02-19 07:31:55 -0700619 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700620 return GetReturnErrorCode(result);
621}
622
Janis Danisevskis24c04702020-12-16 18:28:39 -0800623ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700624 SCOPED_TRACE("Abort");
625
626 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700627 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700628
629 Status retval = op->abort();
630 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800631 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700632}
633
634ErrorCode KeyMintAidlTestBase::Abort() {
635 SCOPED_TRACE("Abort");
636
637 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700638 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700639
640 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800641 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700642}
643
644void KeyMintAidlTestBase::AbortIfNeeded() {
645 SCOPED_TRACE("AbortIfNeeded");
646 if (op_) {
647 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800648 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700649 }
650}
651
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000652auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
653 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700654 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000655 AuthorizationSet begin_out_params;
656 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700657 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000658
659 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700660 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000661}
662
Selene Huang31ab4042020-04-29 04:22:39 -0700663string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
664 const string& message, const AuthorizationSet& in_params,
665 AuthorizationSet* out_params) {
666 SCOPED_TRACE("ProcessMessage");
667 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700668 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700669 EXPECT_EQ(ErrorCode::OK, result);
670 if (result != ErrorCode::OK) {
671 return "";
672 }
673
674 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700675 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700676 return output;
677}
678
679string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
680 const AuthorizationSet& params) {
681 SCOPED_TRACE("SignMessage");
682 AuthorizationSet out_params;
683 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
684 EXPECT_TRUE(out_params.empty());
685 return signature;
686}
687
688string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
689 SCOPED_TRACE("SignMessage");
690 return SignMessage(key_blob_, message, params);
691}
692
693string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
694 SCOPED_TRACE("MacMessage");
695 return SignMessage(
696 key_blob_, message,
697 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
698}
699
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530700void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
701 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000702 auto builder = AuthorizationSetBuilder()
703 .Authorization(TAG_NO_AUTH_REQUIRED)
704 .AesEncryptionKey(128)
705 .BlockMode(block_mode)
706 .Padding(PaddingMode::NONE);
707 if (block_mode == BlockMode::GCM) {
708 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
709 }
710 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530711
712 for (int increment = 1; increment <= message_size; ++increment) {
713 string message(message_size, 'a');
714 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
715 if (block_mode == BlockMode::GCM) {
716 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
717 }
718
719 AuthorizationSet output_params;
720 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
721
722 string ciphertext;
723 string to_send;
724 for (size_t i = 0; i < message.size(); i += increment) {
725 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
726 }
727 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
728 << "Error sending " << to_send << " with block mode " << block_mode;
729
730 switch (block_mode) {
731 case BlockMode::GCM:
732 EXPECT_EQ(message.size() + 16, ciphertext.size());
733 break;
734 case BlockMode::CTR:
735 EXPECT_EQ(message.size(), ciphertext.size());
736 break;
737 case BlockMode::CBC:
738 case BlockMode::ECB:
739 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
740 break;
741 }
742
743 auto iv = output_params.GetTagValue(TAG_NONCE);
744 switch (block_mode) {
745 case BlockMode::CBC:
746 case BlockMode::GCM:
747 case BlockMode::CTR:
748 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
749 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
750 params.push_back(TAG_NONCE, iv->get());
751 break;
752
753 case BlockMode::ECB:
754 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
755 break;
756 }
757
758 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
759 << "Decrypt begin() failed for block mode " << block_mode;
760
761 string plaintext;
762 for (size_t i = 0; i < ciphertext.size(); i += increment) {
763 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
764 }
765 ErrorCode error = Finish(to_send, &plaintext);
766 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
767 << " and increment " << increment;
768 if (error == ErrorCode::OK) {
769 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
770 << " and increment " << increment;
771 }
772 }
773}
774
Prashant Patildd5f7f02022-07-06 18:58:07 +0000775void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
776 PaddingMode padding_mode, const string& iv,
777 const string& plaintext,
778 const string& exp_cipher_text) {
779 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
780 auto auth_set = AuthorizationSetBuilder()
781 .Authorization(TAG_NO_AUTH_REQUIRED)
782 .AesEncryptionKey(key.size() * 8)
783 .BlockMode(block_mode)
784 .Padding(padding_mode);
785 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
786 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
787 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
788
789 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
790 exp_cipher_text);
791}
792
793void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
794 PaddingMode padding_mode, const string& iv,
795 const string& plaintext,
796 const string& exp_cipher_text) {
797 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
798 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
799 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
800 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
801 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
802
803 AuthorizationSet output_params;
804 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
805
806 string actual_ciphertext;
807 if (is_stream_cipher) {
808 // Assert that a 1 byte of output is produced for 1 byte of input.
809 // Every input byte produces an output byte.
810 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
811 string ciphertext;
812 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
813 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
814 // we relax this API restriction for them.
815 if (SecLevel() != SecurityLevel::STRONGBOX) {
816 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
817 }
818 actual_ciphertext.append(ciphertext);
819 }
820 string ciphertext;
821 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
822 if (SecLevel() != SecurityLevel::STRONGBOX) {
823 string expected_final_output;
824 if (is_authenticated_cipher) {
825 expected_final_output = exp_cipher_text.substr(plaintext.size());
826 }
827 EXPECT_EQ(expected_final_output, ciphertext);
828 }
829 actual_ciphertext.append(ciphertext);
830 } else {
831 // Assert that a block of output is produced once a full block of input is provided.
832 // Every input block produces an output block.
833 bool compare_output = true;
834 string additional_information;
835 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
836 if (SecLevel() == SecurityLevel::STRONGBOX) {
837 // This is known to be broken on older vendor implementations.
838 if (vendor_api_level < 33) {
839 compare_output = false;
840 } else {
841 additional_information = " (b/194134359) ";
842 }
843 }
844 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
845 string ciphertext;
846 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
847 if (compare_output) {
848 if ((plaintext_index % block_size) == block_size - 1) {
849 // Update is expected to have output a new block
850 EXPECT_EQ(block_size, ciphertext.size())
851 << "plaintext index: " << plaintext_index << additional_information;
852 } else {
853 // Update is expected to have produced no output
854 EXPECT_EQ(0, ciphertext.size())
855 << "plaintext index: " << plaintext_index << additional_information;
856 }
857 }
858 actual_ciphertext.append(ciphertext);
859 }
860 string ciphertext;
861 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
862 actual_ciphertext.append(ciphertext);
863 }
864 // Regardless of how the completed ciphertext got accumulated, it should match the expected
865 // ciphertext.
866 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
867}
868
Selene Huang31ab4042020-04-29 04:22:39 -0700869void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
870 Digest digest, const string& expected_mac) {
871 SCOPED_TRACE("CheckHmacTestVector");
872 ASSERT_EQ(ErrorCode::OK,
873 ImportKey(AuthorizationSetBuilder()
874 .Authorization(TAG_NO_AUTH_REQUIRED)
875 .HmacKey(key.size() * 8)
876 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
877 .Digest(digest),
878 KeyFormat::RAW, key));
879 string signature = MacMessage(message, digest, expected_mac.size() * 8);
880 EXPECT_EQ(expected_mac, signature)
881 << "Test vector didn't match for key of size " << key.size() << " message of size "
882 << message.size() << " and digest " << digest;
883 CheckedDeleteKey();
884}
885
886void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
887 const string& message,
888 const string& expected_ciphertext) {
889 SCOPED_TRACE("CheckAesCtrTestVector");
890 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
891 .Authorization(TAG_NO_AUTH_REQUIRED)
892 .AesEncryptionKey(key.size() * 8)
893 .BlockMode(BlockMode::CTR)
894 .Authorization(TAG_CALLER_NONCE)
895 .Padding(PaddingMode::NONE),
896 KeyFormat::RAW, key));
897
898 auto params = AuthorizationSetBuilder()
899 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
900 .BlockMode(BlockMode::CTR)
901 .Padding(PaddingMode::NONE);
902 AuthorizationSet out_params;
903 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
904 EXPECT_EQ(expected_ciphertext, ciphertext);
905}
906
907void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
908 PaddingMode padding_mode, const string& key,
909 const string& iv, const string& input,
910 const string& expected_output) {
911 auto authset = AuthorizationSetBuilder()
912 .TripleDesEncryptionKey(key.size() * 7)
913 .BlockMode(block_mode)
914 .Authorization(TAG_NO_AUTH_REQUIRED)
915 .Padding(padding_mode);
916 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
917 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
918 ASSERT_GT(key_blob_.size(), 0U);
919
920 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
921 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
922 AuthorizationSet output_params;
923 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
924 EXPECT_EQ(expected_output, output);
925}
926
927void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
928 const string& signature, const AuthorizationSet& params) {
929 SCOPED_TRACE("VerifyMessage");
930 AuthorizationSet begin_out_params;
931 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
932
933 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700934 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700935 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700936 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700937}
938
939void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
940 const AuthorizationSet& params) {
941 SCOPED_TRACE("VerifyMessage");
942 VerifyMessage(key_blob_, message, signature, params);
943}
944
David Drysdaledf8f52e2021-05-06 08:10:58 +0100945void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
946 const AuthorizationSet& params) {
947 SCOPED_TRACE("LocalVerifyMessage");
948
949 // Retrieve the public key from the leaf certificate.
950 ASSERT_GT(cert_chain_.size(), 0);
951 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
952 ASSERT_TRUE(key_cert.get());
953 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
954 ASSERT_TRUE(pub_key.get());
955
956 Digest digest = params.GetTagValue(TAG_DIGEST).value();
957 PaddingMode padding = PaddingMode::NONE;
958 auto tag = params.GetTagValue(TAG_PADDING);
959 if (tag.has_value()) {
960 padding = tag.value();
961 }
962
963 if (digest == Digest::NONE) {
964 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100965 case EVP_PKEY_ED25519: {
966 ASSERT_EQ(64, signature.size());
967 uint8_t pub_keydata[32];
968 size_t pub_len = sizeof(pub_keydata);
969 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
970 ASSERT_EQ(sizeof(pub_keydata), pub_len);
971 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
972 message.size(),
973 reinterpret_cast<const uint8_t*>(signature.data()),
974 pub_keydata));
975 break;
976 }
977
David Drysdaledf8f52e2021-05-06 08:10:58 +0100978 case EVP_PKEY_EC: {
979 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
980 size_t data_size = std::min(data.size(), message.size());
981 memcpy(data.data(), message.data(), data_size);
982 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
983 ASSERT_TRUE(ecdsa.get());
984 ASSERT_EQ(1,
985 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
986 reinterpret_cast<const uint8_t*>(signature.data()),
987 signature.size(), ecdsa.get()));
988 break;
989 }
990 case EVP_PKEY_RSA: {
991 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
992 size_t data_size = std::min(data.size(), message.size());
993 memcpy(data.data(), message.data(), data_size);
994
995 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
996 ASSERT_TRUE(rsa.get());
997
998 size_t key_len = RSA_size(rsa.get());
999 int openssl_padding = RSA_NO_PADDING;
1000 switch (padding) {
1001 case PaddingMode::NONE:
1002 ASSERT_TRUE(data_size <= key_len);
1003 ASSERT_EQ(key_len, signature.size());
1004 openssl_padding = RSA_NO_PADDING;
1005 break;
1006 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1007 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1008 key_len);
1009 openssl_padding = RSA_PKCS1_PADDING;
1010 break;
1011 default:
1012 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1013 }
1014
1015 vector<uint8_t> decrypted_data(key_len);
1016 int bytes_decrypted = RSA_public_decrypt(
1017 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1018 decrypted_data.data(), rsa.get(), openssl_padding);
1019 ASSERT_GE(bytes_decrypted, 0);
1020
1021 const uint8_t* compare_pos = decrypted_data.data();
1022 size_t bytes_to_compare = bytes_decrypted;
1023 uint8_t zero_check_result = 0;
1024 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1025 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1026 // during verification we should have zeros on the left of the decrypted data.
1027 // Do a constant-time check.
1028 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1029 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1030 ASSERT_EQ(0, zero_check_result);
1031 bytes_to_compare = data_size;
1032 }
1033 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1034 break;
1035 }
1036 default:
1037 ADD_FAILURE() << "Unknown public key type";
1038 }
1039 } else {
1040 EVP_MD_CTX digest_ctx;
1041 EVP_MD_CTX_init(&digest_ctx);
1042 EVP_PKEY_CTX* pkey_ctx;
1043 const EVP_MD* md = openssl_digest(digest);
1044 ASSERT_NE(md, nullptr);
1045 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1046
1047 if (padding == PaddingMode::RSA_PSS) {
1048 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1049 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001050 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001051 }
1052
1053 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1054 reinterpret_cast<const uint8_t*>(message.data()),
1055 message.size()));
1056 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1057 reinterpret_cast<const uint8_t*>(signature.data()),
1058 signature.size()));
1059 EVP_MD_CTX_cleanup(&digest_ctx);
1060 }
1061}
1062
David Drysdale59cae642021-05-12 13:52:03 +01001063string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1064 const AuthorizationSet& params) {
1065 SCOPED_TRACE("LocalRsaEncryptMessage");
1066
1067 // Retrieve the public key from the leaf certificate.
1068 if (cert_chain_.empty()) {
1069 ADD_FAILURE() << "No public key available";
1070 return "Failure";
1071 }
1072 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001073 if (key_cert.get() == nullptr) {
1074 ADD_FAILURE() << "Failed to parse cert";
1075 return "Failure";
1076 }
David Drysdale59cae642021-05-12 13:52:03 +01001077 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001078 if (pub_key.get() == nullptr) {
1079 ADD_FAILURE() << "Failed to retrieve public key";
1080 return "Failure";
1081 }
David Drysdale59cae642021-05-12 13:52:03 +01001082 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001083 if (rsa.get() == nullptr) {
1084 ADD_FAILURE() << "Failed to retrieve RSA public key";
1085 return "Failure";
1086 }
David Drysdale59cae642021-05-12 13:52:03 +01001087
1088 // Retrieve relevant tags.
1089 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001090 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001091 PaddingMode padding = PaddingMode::NONE;
1092
1093 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1094 if (digest_tag.has_value()) digest = digest_tag.value();
1095 auto pad_tag = params.GetTagValue(TAG_PADDING);
1096 if (pad_tag.has_value()) padding = pad_tag.value();
1097 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1098 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1099
1100 const EVP_MD* md = openssl_digest(digest);
1101 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1102
1103 // Set up encryption context.
1104 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1105 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1106 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1107 return "Failure";
1108 }
1109
1110 int rc = -1;
1111 switch (padding) {
1112 case PaddingMode::NONE:
1113 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1114 break;
1115 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1116 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1117 break;
1118 case PaddingMode::RSA_OAEP:
1119 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1120 break;
1121 default:
1122 break;
1123 }
1124 if (rc <= 0) {
1125 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1126 return "Failure";
1127 }
1128 if (padding == PaddingMode::RSA_OAEP) {
1129 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1130 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1131 return "Failure";
1132 }
1133 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1134 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1135 return "Failure";
1136 }
1137 }
1138
1139 // Determine output size.
1140 size_t outlen;
1141 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1142 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1143 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1144 return "Failure";
1145 }
1146
1147 // Left-zero-pad the input if necessary.
1148 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1149 size_t to_encrypt_len = message.size();
1150
1151 std::unique_ptr<string> zero_padded_message;
1152 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1153 zero_padded_message.reset(new string(outlen, '\0'));
1154 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1155 message.size());
1156 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1157 to_encrypt_len = outlen;
1158 }
1159
1160 // Do the encryption.
1161 string output(outlen, '\0');
1162 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1163 to_encrypt_len) <= 0) {
1164 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1165 return "Failure";
1166 }
1167 return output;
1168}
1169
Selene Huang31ab4042020-04-29 04:22:39 -07001170string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1171 const AuthorizationSet& in_params,
1172 AuthorizationSet* out_params) {
1173 SCOPED_TRACE("EncryptMessage");
1174 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1175}
1176
1177string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1178 AuthorizationSet* out_params) {
1179 SCOPED_TRACE("EncryptMessage");
1180 return EncryptMessage(key_blob_, message, params, out_params);
1181}
1182
1183string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1184 SCOPED_TRACE("EncryptMessage");
1185 AuthorizationSet out_params;
1186 string ciphertext = EncryptMessage(message, params, &out_params);
1187 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1188 return ciphertext;
1189}
1190
1191string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1192 PaddingMode padding) {
1193 SCOPED_TRACE("EncryptMessage");
1194 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1195 AuthorizationSet out_params;
1196 string ciphertext = EncryptMessage(message, params, &out_params);
1197 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1198 return ciphertext;
1199}
1200
1201string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1202 PaddingMode padding, vector<uint8_t>* iv_out) {
1203 SCOPED_TRACE("EncryptMessage");
1204 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1205 AuthorizationSet out_params;
1206 string ciphertext = EncryptMessage(message, params, &out_params);
1207 EXPECT_EQ(1U, out_params.size());
1208 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001209 EXPECT_TRUE(ivVal);
1210 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001211 return ciphertext;
1212}
1213
1214string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1215 PaddingMode padding, const vector<uint8_t>& iv_in) {
1216 SCOPED_TRACE("EncryptMessage");
1217 auto params = AuthorizationSetBuilder()
1218 .BlockMode(block_mode)
1219 .Padding(padding)
1220 .Authorization(TAG_NONCE, iv_in);
1221 AuthorizationSet out_params;
1222 string ciphertext = EncryptMessage(message, params, &out_params);
1223 return ciphertext;
1224}
1225
1226string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1227 PaddingMode padding, uint8_t mac_length_bits,
1228 const vector<uint8_t>& iv_in) {
1229 SCOPED_TRACE("EncryptMessage");
1230 auto params = AuthorizationSetBuilder()
1231 .BlockMode(block_mode)
1232 .Padding(padding)
1233 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1234 .Authorization(TAG_NONCE, iv_in);
1235 AuthorizationSet out_params;
1236 string ciphertext = EncryptMessage(message, params, &out_params);
1237 return ciphertext;
1238}
1239
David Drysdaled2cc8c22021-04-15 13:29:45 +01001240string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1241 PaddingMode padding, uint8_t mac_length_bits) {
1242 SCOPED_TRACE("EncryptMessage");
1243 auto params = AuthorizationSetBuilder()
1244 .BlockMode(block_mode)
1245 .Padding(padding)
1246 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1247 AuthorizationSet out_params;
1248 string ciphertext = EncryptMessage(message, params, &out_params);
1249 return ciphertext;
1250}
1251
Selene Huang31ab4042020-04-29 04:22:39 -07001252string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1253 const string& ciphertext,
1254 const AuthorizationSet& params) {
1255 SCOPED_TRACE("DecryptMessage");
1256 AuthorizationSet out_params;
1257 string plaintext =
1258 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1259 EXPECT_TRUE(out_params.empty());
1260 return plaintext;
1261}
1262
1263string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1264 const AuthorizationSet& params) {
1265 SCOPED_TRACE("DecryptMessage");
1266 return DecryptMessage(key_blob_, ciphertext, params);
1267}
1268
1269string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1270 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1271 SCOPED_TRACE("DecryptMessage");
1272 auto params = AuthorizationSetBuilder()
1273 .BlockMode(block_mode)
1274 .Padding(padding_mode)
1275 .Authorization(TAG_NONCE, iv);
1276 return DecryptMessage(key_blob_, ciphertext, params);
1277}
1278
1279std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1280 const vector<uint8_t>& key_blob) {
1281 std::pair<ErrorCode, vector<uint8_t>> retval;
1282 vector<uint8_t> outKeyBlob;
1283 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1284 ErrorCode errorcode = GetReturnErrorCode(result);
1285 retval = std::tie(errorcode, outKeyBlob);
1286
1287 return retval;
1288}
1289vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1290 switch (algorithm) {
1291 case Algorithm::RSA:
1292 switch (SecLevel()) {
1293 case SecurityLevel::SOFTWARE:
1294 case SecurityLevel::TRUSTED_ENVIRONMENT:
1295 return {2048, 3072, 4096};
1296 case SecurityLevel::STRONGBOX:
1297 return {2048};
1298 default:
1299 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1300 break;
1301 }
1302 break;
1303 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001304 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001305 break;
1306 case Algorithm::AES:
1307 return {128, 256};
1308 case Algorithm::TRIPLE_DES:
1309 return {168};
1310 case Algorithm::HMAC: {
1311 vector<uint32_t> retval((512 - 64) / 8 + 1);
1312 uint32_t size = 64 - 8;
1313 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1314 return retval;
1315 }
1316 default:
1317 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1318 return {};
1319 }
1320 ADD_FAILURE() << "Should be impossible to get here";
1321 return {};
1322}
1323
1324vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1325 if (SecLevel() == SecurityLevel::STRONGBOX) {
1326 switch (algorithm) {
1327 case Algorithm::RSA:
1328 return {3072, 4096};
1329 case Algorithm::EC:
1330 return {224, 384, 521};
1331 case Algorithm::AES:
1332 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001333 case Algorithm::TRIPLE_DES:
1334 return {56};
1335 default:
1336 return {};
1337 }
1338 } else {
1339 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001340 case Algorithm::AES:
1341 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001342 case Algorithm::TRIPLE_DES:
1343 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001344 default:
1345 return {};
1346 }
1347 }
1348 return {};
1349}
1350
David Drysdale7de9feb2021-03-05 14:56:19 +00001351vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1352 switch (algorithm) {
1353 case Algorithm::AES:
1354 return {
1355 BlockMode::CBC,
1356 BlockMode::CTR,
1357 BlockMode::ECB,
1358 BlockMode::GCM,
1359 };
1360 case Algorithm::TRIPLE_DES:
1361 return {
1362 BlockMode::CBC,
1363 BlockMode::ECB,
1364 };
1365 default:
1366 return {};
1367 }
1368}
1369
1370vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1371 BlockMode blockMode) {
1372 switch (algorithm) {
1373 case Algorithm::AES:
1374 switch (blockMode) {
1375 case BlockMode::CBC:
1376 case BlockMode::ECB:
1377 return {PaddingMode::NONE, PaddingMode::PKCS7};
1378 case BlockMode::CTR:
1379 case BlockMode::GCM:
1380 return {PaddingMode::NONE};
1381 default:
1382 return {};
1383 };
1384 case Algorithm::TRIPLE_DES:
1385 switch (blockMode) {
1386 case BlockMode::CBC:
1387 case BlockMode::ECB:
1388 return {PaddingMode::NONE, PaddingMode::PKCS7};
1389 default:
1390 return {};
1391 };
1392 default:
1393 return {};
1394 }
1395}
1396
1397vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1398 BlockMode blockMode) {
1399 switch (algorithm) {
1400 case Algorithm::AES:
1401 switch (blockMode) {
1402 case BlockMode::CTR:
1403 case BlockMode::GCM:
1404 return {PaddingMode::PKCS7};
1405 default:
1406 return {};
1407 };
1408 default:
1409 return {};
1410 }
1411}
1412
Selene Huang31ab4042020-04-29 04:22:39 -07001413vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1414 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1415 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001416 } else if (Curve25519Supported()) {
1417 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1418 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001419 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001420 return {
1421 EcCurve::P_224,
1422 EcCurve::P_256,
1423 EcCurve::P_384,
1424 EcCurve::P_521,
1425 };
Selene Huang31ab4042020-04-29 04:22:39 -07001426 }
1427}
1428
1429vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001430 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001431 // Curve 25519 is not supported, either because:
1432 // - KeyMint v1: it's an unknown enum value
1433 // - KeyMint v2+: it's not supported by StrongBox.
1434 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001435 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001436 if (Curve25519Supported()) {
1437 return {};
1438 } else {
1439 return {EcCurve::CURVE_25519};
1440 }
David Drysdaledf09e542021-06-08 15:46:11 +01001441 }
Selene Huang31ab4042020-04-29 04:22:39 -07001442}
1443
subrahmanyaman05642492022-02-05 07:10:56 +00001444vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1445 if (SecLevel() == SecurityLevel::STRONGBOX) {
1446 return {65537};
1447 } else {
1448 return {3, 65537};
1449 }
1450}
1451
Selene Huang31ab4042020-04-29 04:22:39 -07001452vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1453 switch (SecLevel()) {
1454 case SecurityLevel::SOFTWARE:
1455 case SecurityLevel::TRUSTED_ENVIRONMENT:
1456 if (withNone) {
1457 if (withMD5)
1458 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1459 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1460 Digest::SHA_2_512};
1461 else
1462 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1463 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1464 } else {
1465 if (withMD5)
1466 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1467 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1468 else
1469 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1470 Digest::SHA_2_512};
1471 }
1472 break;
1473 case SecurityLevel::STRONGBOX:
1474 if (withNone)
1475 return {Digest::NONE, Digest::SHA_2_256};
1476 else
1477 return {Digest::SHA_2_256};
1478 break;
1479 default:
1480 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1481 break;
1482 }
1483 ADD_FAILURE() << "Should be impossible to get here";
1484 return {};
1485}
1486
Shawn Willden7f424372021-01-10 18:06:50 -07001487static const vector<KeyParameter> kEmptyAuthList{};
1488
1489const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1490 const vector<KeyCharacteristics>& key_characteristics) {
1491 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1492 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1493 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1494}
1495
Qi Wubeefae42021-01-28 23:16:37 +08001496const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1497 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1498 auto found = std::find_if(
1499 key_characteristics.begin(), key_characteristics.end(),
1500 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001501 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1502}
1503
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001504ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001505 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001506 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1507 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1508 return result;
1509}
1510
1511ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001512 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001513 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1514 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1515 return result;
1516}
1517
1518ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1519 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001520 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001521 rsaKeyBlob, KeyPurpose::SIGN, message,
1522 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1523 return result;
1524}
1525
1526ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001527 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1528 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001529 return result;
1530}
1531
Selene Huang6e46f142021-04-20 19:20:11 -07001532void verify_serial(X509* cert, const uint64_t expected_serial) {
1533 BIGNUM_Ptr ser(BN_new());
1534 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1535
1536 uint64_t serial;
1537 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1538 EXPECT_EQ(serial, expected_serial);
1539}
1540
1541// Please set self_signed to true for fake certificates or self signed
1542// certificates
1543void verify_subject(const X509* cert, //
1544 const string& subject, //
1545 bool self_signed) {
1546 char* cert_issuer = //
1547 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1548
1549 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1550
1551 string expected_subject("/CN=");
1552 if (subject.empty()) {
1553 expected_subject.append("Android Keystore Key");
1554 } else {
1555 expected_subject.append(subject);
1556 }
1557
1558 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1559
1560 if (self_signed) {
1561 EXPECT_STREQ(cert_issuer, cert_subj)
1562 << "Cert issuer and subject mismatch for self signed certificate.";
1563 }
1564
1565 OPENSSL_free(cert_subj);
1566 OPENSSL_free(cert_issuer);
1567}
1568
Shawn Willden22fb9c12022-06-02 14:04:33 -06001569int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001570 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1571 if (vendor_api_level != -1) {
1572 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001573 }
Shawn Willden35db3492022-06-16 12:50:40 -06001574
1575 // Android S and older devices do not define ro.vendor.api_level
1576 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1577 if (vendor_api_level == -1) {
1578 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001579 }
Shawn Willden35db3492022-06-16 12:50:40 -06001580
1581 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1582 if (product_api_level == -1) {
1583 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1584 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001585 }
Shawn Willden35db3492022-06-16 12:50:40 -06001586
1587 // VSR API level is the minimum of vendor_api_level and product_api_level.
1588 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1589 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001590 }
Shawn Willden35db3492022-06-16 12:50:40 -06001591 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001592}
1593
David Drysdale555ba002022-05-03 18:48:57 +01001594bool is_gsi_image() {
1595 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1596 return ifs.good();
1597}
1598
Selene Huang6e46f142021-04-20 19:20:11 -07001599vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1600 BIGNUM_Ptr serial(BN_new());
1601 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1602
1603 int len = BN_num_bytes(serial.get());
1604 vector<uint8_t> serial_blob(len);
1605 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1606 return {};
1607 }
1608
David Drysdaledb0dcf52021-05-18 11:43:31 +01001609 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1610 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1611 // Top bit being set indicates a negative number in two's complement, but our input
1612 // was positive.
1613 // In either case, prepend a zero byte.
1614 serial_blob.insert(serial_blob.begin(), 0x00);
1615 }
1616
Selene Huang6e46f142021-04-20 19:20:11 -07001617 return serial_blob;
1618}
1619
1620void verify_subject_and_serial(const Certificate& certificate, //
1621 const uint64_t expected_serial, //
1622 const string& subject, bool self_signed) {
1623 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1624 ASSERT_TRUE(!!cert.get());
1625
1626 verify_serial(cert.get(), expected_serial);
1627 verify_subject(cert.get(), subject, self_signed);
1628}
1629
Shawn Willden4315e132022-03-20 12:49:46 -06001630void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1631 VerifiedBoot verified_boot_state,
1632 const vector<uint8_t>& verified_boot_hash) {
1633 char property_value[PROPERTY_VALUE_MAX] = {};
1634
1635 if (avb_verification_enabled()) {
1636 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1637 string prop_string(property_value);
1638 EXPECT_EQ(prop_string.size(), 64);
1639 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1640
1641 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1642 if (!strcmp(property_value, "unlocked")) {
1643 EXPECT_FALSE(device_locked);
1644 } else {
1645 EXPECT_TRUE(device_locked);
1646 }
1647
1648 // Check that the device is locked if not debuggable, e.g., user build
1649 // images in CTS. For VTS, debuggable images are used to allow adb root
1650 // and the device is unlocked.
1651 if (!property_get_bool("ro.debuggable", false)) {
1652 EXPECT_TRUE(device_locked);
1653 } else {
1654 EXPECT_FALSE(device_locked);
1655 }
1656 }
1657
1658 // Verified boot key should be all 0's if the boot state is not verified or self signed
1659 std::string empty_boot_key(32, '\0');
1660 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1661 verified_boot_key.size());
1662 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1663 if (!strcmp(property_value, "green")) {
1664 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1665 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1666 verified_boot_key.size()));
1667 } else if (!strcmp(property_value, "yellow")) {
1668 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1669 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1670 verified_boot_key.size()));
1671 } else if (!strcmp(property_value, "orange")) {
1672 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1673 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1674 verified_boot_key.size()));
1675 } else if (!strcmp(property_value, "red")) {
1676 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1677 } else {
1678 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1679 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1680 verified_boot_key.size()));
1681 }
1682}
1683
David Drysdale7dff4fc2021-12-10 10:10:52 +00001684bool verify_attestation_record(int32_t aidl_version, //
1685 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001686 const string& app_id, //
1687 AuthorizationSet expected_sw_enforced, //
1688 AuthorizationSet expected_hw_enforced, //
1689 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001690 const vector<uint8_t>& attestation_cert,
1691 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001692 X509_Ptr cert(parse_cert_blob(attestation_cert));
1693 EXPECT_TRUE(!!cert.get());
1694 if (!cert.get()) return false;
1695
1696 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1697 EXPECT_TRUE(!!attest_rec);
1698 if (!attest_rec) return false;
1699
1700 AuthorizationSet att_sw_enforced;
1701 AuthorizationSet att_hw_enforced;
1702 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001703 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001704 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001705 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001706 vector<uint8_t> att_challenge;
1707 vector<uint8_t> att_unique_id;
1708 vector<uint8_t> att_app_id;
1709
1710 auto error = parse_attestation_record(attest_rec->data, //
1711 attest_rec->length, //
1712 &att_attestation_version, //
1713 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001714 &att_keymint_version, //
1715 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001716 &att_challenge, //
1717 &att_sw_enforced, //
1718 &att_hw_enforced, //
1719 &att_unique_id);
1720 EXPECT_EQ(ErrorCode::OK, error);
1721 if (error != ErrorCode::OK) return false;
1722
David Drysdale7dff4fc2021-12-10 10:10:52 +00001723 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001724 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001725
Selene Huang4f64c222021-04-13 19:54:36 -07001726 // check challenge and app id only if we expects a non-fake certificate
1727 if (challenge.length() > 0) {
1728 EXPECT_EQ(challenge.length(), att_challenge.size());
1729 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1730
1731 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1732 }
Shawn Willden7c130392020-12-21 09:58:22 -07001733
David Drysdale7dff4fc2021-12-10 10:10:52 +00001734 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001735 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001736 EXPECT_EQ(security_level, att_attestation_security_level);
1737
Shawn Willden7c130392020-12-21 09:58:22 -07001738 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001739 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001740 // for the BOOT_PATCH_LEVEL.
1741 if (avb_verification_enabled()) {
1742 for (int i = 0; i < att_hw_enforced.size(); i++) {
1743 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1744 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1745 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001746 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001747
Shawn Willden7c130392020-12-21 09:58:22 -07001748 // strptime seems to require delimiters, but the tag value will
1749 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001750 if (date.size() != 8) {
1751 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1752 << " with invalid format (not YYYYMMDD): " << date;
1753 return false;
1754 }
Shawn Willden7c130392020-12-21 09:58:22 -07001755 date.insert(6, "-");
1756 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001757 struct tm time;
1758 strptime(date.c_str(), "%Y-%m-%d", &time);
1759
1760 // Day of the month (0-31)
1761 EXPECT_GE(time.tm_mday, 0);
1762 EXPECT_LT(time.tm_mday, 32);
1763 // Months since Jan (0-11)
1764 EXPECT_GE(time.tm_mon, 0);
1765 EXPECT_LT(time.tm_mon, 12);
1766 // Years since 1900
1767 EXPECT_GT(time.tm_year, 110);
1768 EXPECT_LT(time.tm_year, 200);
1769 }
1770 }
1771 }
1772
1773 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1774 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1775 // indicates correct encoding. No need to check if it's in both lists, since the
1776 // AuthorizationSet compare below will handle mismatches of tags.
1777 if (security_level == SecurityLevel::SOFTWARE) {
1778 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1779 } else {
1780 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1781 }
1782
Shawn Willden7c130392020-12-21 09:58:22 -07001783 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1784 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1785 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1786 att_hw_enforced.Contains(TAG_KEY_SIZE));
1787 }
1788
1789 // Test root of trust elements
1790 vector<uint8_t> verified_boot_key;
1791 VerifiedBoot verified_boot_state;
1792 bool device_locked;
1793 vector<uint8_t> verified_boot_hash;
1794 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1795 &verified_boot_state, &device_locked, &verified_boot_hash);
1796 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001797 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001798
1799 att_sw_enforced.Sort();
1800 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001801 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001802
1803 att_hw_enforced.Sort();
1804 expected_hw_enforced.Sort();
1805 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1806
David Drysdale565ccc72021-10-11 12:49:50 +01001807 if (unique_id != nullptr) {
1808 *unique_id = att_unique_id;
1809 }
1810
Shawn Willden7c130392020-12-21 09:58:22 -07001811 return true;
1812}
1813
1814string bin2hex(const vector<uint8_t>& data) {
1815 string retval;
1816 retval.reserve(data.size() * 2 + 1);
1817 for (uint8_t byte : data) {
1818 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1819 retval.push_back(nibble2hex[0x0F & byte]);
1820 }
1821 return retval;
1822}
1823
David Drysdalef0d516d2021-03-22 07:51:43 +00001824AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1825 AuthorizationSet authList;
1826 for (auto& entry : key_characteristics) {
1827 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1828 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1829 authList.push_back(AuthorizationSet(entry.authorizations));
1830 }
1831 }
1832 return authList;
1833}
1834
1835AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1836 AuthorizationSet authList;
1837 for (auto& entry : key_characteristics) {
1838 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1839 entry.securityLevel == SecurityLevel::KEYSTORE) {
1840 authList.push_back(AuthorizationSet(entry.authorizations));
1841 }
1842 }
1843 return authList;
1844}
1845
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001846AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1847 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001848 std::stringstream cert_data;
1849
1850 for (size_t i = 0; i < chain.size(); ++i) {
1851 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1852
1853 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1854 X509_Ptr signing_cert;
1855 if (i < chain.size() - 1) {
1856 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1857 } else {
1858 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1859 }
1860 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1861
1862 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1863 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1864
1865 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1866 return AssertionFailure()
1867 << "Verification of certificate " << i << " failed "
1868 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1869 << cert_data.str();
1870 }
1871
1872 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1873 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001874 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001875 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1876 << " Signer subject is " << signer_subj
1877 << " Issuer subject is " << cert_issuer << endl
1878 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001879 }
Shawn Willden7c130392020-12-21 09:58:22 -07001880 }
1881
1882 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1883 return AssertionSuccess();
1884}
1885
1886X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1887 const uint8_t* p = blob.data();
1888 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1889}
1890
David Drysdalef0d516d2021-03-22 07:51:43 +00001891vector<uint8_t> make_name_from_str(const string& name) {
1892 X509_NAME_Ptr x509_name(X509_NAME_new());
1893 EXPECT_TRUE(x509_name.get() != nullptr);
1894 if (!x509_name) return {};
1895
1896 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1897 "CN", //
1898 MBSTRING_ASC,
1899 reinterpret_cast<const uint8_t*>(name.c_str()),
1900 -1, // len
1901 -1, // loc
1902 0 /* set */));
1903
1904 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1905 EXPECT_GT(len, 0);
1906
1907 vector<uint8_t> retval(len);
1908 uint8_t* p = retval.data();
1909 i2d_X509_NAME(x509_name.get(), &p);
1910
1911 return retval;
1912}
1913
David Drysdale4dc01072021-04-01 12:17:35 +01001914namespace {
1915
1916void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1917 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1918 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1919
1920 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1921 if (testMode) {
1922 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1923 MatchesRegex("{\n"
1924 " 1 : 2,\n" // kty: EC2
1925 " 3 : -7,\n" // alg: ES256
1926 " -1 : 1,\n" // EC id: P256
1927 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1928 // sequence of 32 hexadecimal bytes, enclosed in braces and
1929 // separated by commas. In this case, some Ed25519 public key.
1930 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1931 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1932 " -70000 : null,\n" // test marker
1933 "}"));
1934 } else {
1935 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1936 MatchesRegex("{\n"
1937 " 1 : 2,\n" // kty: EC2
1938 " 3 : -7,\n" // alg: ES256
1939 " -1 : 1,\n" // EC id: P256
1940 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1941 // sequence of 32 hexadecimal bytes, enclosed in braces and
1942 // separated by commas. In this case, some Ed25519 public key.
1943 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1944 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1945 "}"));
1946 }
1947}
1948
1949} // namespace
1950
1951void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1952 vector<uint8_t>* payload_value) {
1953 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1954 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1955
1956 ASSERT_NE(coseMac0->asArray(), nullptr);
1957 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1958
1959 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1960 ASSERT_NE(protParms, nullptr);
1961
1962 // Header label:value of 'alg': HMAC-256
1963 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1964
1965 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1966 ASSERT_NE(unprotParms, nullptr);
1967 ASSERT_EQ(unprotParms->size(), 0);
1968
1969 // The payload is a bstr holding an encoded COSE_Key
1970 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1971 ASSERT_NE(payload, nullptr);
1972 check_cose_key(payload->value(), testMode);
1973
1974 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1975 ASSERT_TRUE(coseMac0Tag);
1976 auto extractedTag = coseMac0Tag->value();
1977 EXPECT_EQ(extractedTag.size(), 32U);
1978
1979 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001980 auto macFunction = [](const cppcose::bytevec& input) {
1981 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1982 };
1983 auto testTag =
1984 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001985 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1986
1987 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001988 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001989 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001990 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001991 }
1992 if (payload_value != nullptr) {
1993 *payload_value = payload->value();
1994 }
1995}
1996
1997void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1998 // Extract x and y affine coordinates from the encoded Cose_Key.
1999 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2000 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2001 auto coseKey = parsedPayload->asMap();
2002 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2003 ASSERT_NE(xItem->asBstr(), nullptr);
2004 vector<uint8_t> x = xItem->asBstr()->value();
2005 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2006 ASSERT_NE(yItem->asBstr(), nullptr);
2007 vector<uint8_t> y = yItem->asBstr()->value();
2008
2009 // Concatenate: 0x04 (uncompressed form marker) | x | y
2010 vector<uint8_t> pubKeyData{0x04};
2011 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2012 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2013
2014 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2015 ASSERT_NE(ecKey, nullptr);
2016 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2017 ASSERT_NE(group, nullptr);
2018 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2019 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2020 ASSERT_NE(point, nullptr);
2021 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2022 nullptr),
2023 1);
2024 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2025
2026 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2027 ASSERT_NE(pubKey, nullptr);
2028 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2029 *signingKey = std::move(pubKey);
2030}
2031
Selene Huang31ab4042020-04-29 04:22:39 -07002032} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002033
Janis Danisevskis24c04702020-12-16 18:28:39 -08002034} // namespace aidl::android::hardware::security::keymint