blob: 3ffb6eccbf7db83c26b69e2c575f6cdf4c69e316 [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 Drysdale3d2ba0a2023-01-11 13:27:26 +000026#include <android/content/pm/IPackageManagerNative.h>
David Drysdale4dc01072021-04-01 12:17:35 +010027#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070028#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010029#include <gmock/gmock.h>
David Drysdale42fe1892021-10-14 14:43:46 +010030#include <openssl/evp.h>
Shawn Willden7c130392020-12-21 09:58:22 -070031#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070033
Max Bires9704ff62021-04-07 11:12:01 -070034#include <keymaster/cppcose/cppcose.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;
David Drysdale9f5c0c52022-11-03 15:10:16 +0000188std::string KeyMintAidlTestBase::keyblob_dir;
Shawn Willden7c130392020-12-21 09:58:22 -0700189
David Drysdale37af4b32021-05-14 16:46:59 +0100190uint32_t KeyMintAidlTestBase::boot_patch_level(
191 const vector<KeyCharacteristics>& key_characteristics) {
192 // The boot patchlevel is not available as a property, but should be present
193 // in the key characteristics of any created key.
194 AuthorizationSet allAuths;
195 for (auto& entry : key_characteristics) {
196 allAuths.push_back(AuthorizationSet(entry.authorizations));
197 }
198 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
199 if (patchlevel.has_value()) {
200 return patchlevel.value();
201 } else {
202 // No boot patchlevel is available. Return a value that won't match anything
203 // and so will trigger test failures.
204 return kInvalidPatchlevel;
205 }
206}
207
208uint32_t KeyMintAidlTestBase::boot_patch_level() {
209 return boot_patch_level(key_characteristics_);
210}
211
Prashant Patil88ad1892022-03-15 16:31:02 +0000212/**
213 * An API to determine device IDs attestation is required or not,
214 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
215 */
216bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
217 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= 33;
218}
219
David Drysdale42fe1892021-10-14 14:43:46 +0100220bool KeyMintAidlTestBase::Curve25519Supported() {
221 // Strongbox never supports curve 25519.
222 if (SecLevel() == SecurityLevel::STRONGBOX) {
223 return false;
224 }
225
226 // Curve 25519 was included in version 2 of the KeyMint interface.
227 int32_t version = 0;
228 auto status = keymint_->getInterfaceVersion(&version);
229 if (!status.isOk()) {
230 ADD_FAILURE() << "Failed to determine interface version";
231 }
232 return version >= 2;
233}
234
Janis Danisevskis24c04702020-12-16 18:28:39 -0800235ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700236 if (result.isOk()) return ErrorCode::OK;
237
Janis Danisevskis24c04702020-12-16 18:28:39 -0800238 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
239 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700240 }
241
242 return ErrorCode::UNKNOWN_ERROR;
243}
244
Janis Danisevskis24c04702020-12-16 18:28:39 -0800245void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700246 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800247 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700248
249 KeyMintHardwareInfo info;
250 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
251
252 securityLevel_ = info.securityLevel;
253 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
254 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100255 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700256
257 os_version_ = getOsVersion();
258 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100259 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700260}
261
David Drysdale7dff4fc2021-12-10 10:10:52 +0000262int32_t KeyMintAidlTestBase::AidlVersion() {
263 int32_t version = 0;
264 auto status = keymint_->getInterfaceVersion(&version);
265 if (!status.isOk()) {
266 ADD_FAILURE() << "Failed to determine interface version";
267 }
268 return version;
269}
270
Selene Huang31ab4042020-04-29 04:22:39 -0700271void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800272 if (AServiceManager_isDeclared(GetParam().c_str())) {
273 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
274 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
275 } else {
276 InitializeKeyMint(nullptr);
277 }
Selene Huang31ab4042020-04-29 04:22:39 -0700278}
279
280ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700281 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700282 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700283 vector<KeyCharacteristics>* key_characteristics,
284 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700285 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
286 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700287 << "Previous characteristics not deleted before generating key. Test bug.";
288
Shawn Willden7f424372021-01-10 18:06:50 -0700289 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700290 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700291 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700292 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
293 creationResult.keyCharacteristics);
294 EXPECT_GT(creationResult.keyBlob.size(), 0);
295 *key_blob = std::move(creationResult.keyBlob);
296 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700297 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700298
299 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
300 EXPECT_TRUE(algorithm);
301 if (algorithm &&
302 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700303 EXPECT_GE(cert_chain->size(), 1);
304 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
305 if (attest_key) {
306 EXPECT_EQ(cert_chain->size(), 1);
307 } else {
308 EXPECT_GT(cert_chain->size(), 1);
309 }
310 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700311 } else {
312 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700313 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700314 }
Selene Huang31ab4042020-04-29 04:22:39 -0700315 }
316
317 return GetReturnErrorCode(result);
318}
319
Shawn Willden7c130392020-12-21 09:58:22 -0700320ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
321 const optional<AttestationKey>& attest_key) {
322 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700323}
324
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000325ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
326 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
327 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
328 vector<Certificate>* cert_chain) {
329 AttestationKey attest_key;
330 vector<Certificate> attest_cert_chain;
331 vector<KeyCharacteristics> attest_key_characteristics;
332 // Generate a key with self signed attestation.
333 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
334 &attest_key_characteristics, &attest_cert_chain);
335 if (error != ErrorCode::OK) {
336 return error;
337 }
338
339 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
340 // Generate a key, by passing the above self signed attestation key as attest key.
341 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
342 if (error == ErrorCode::OK) {
343 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
344 cert_chain->push_back(attest_cert_chain[0]);
345 }
346 return error;
347}
348
Selene Huang31ab4042020-04-29 04:22:39 -0700349ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
350 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700351 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700352 Status result;
353
Shawn Willden7f424372021-01-10 18:06:50 -0700354 cert_chain_.clear();
355 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700356 key_blob->clear();
357
Shawn Willden7f424372021-01-10 18:06:50 -0700358 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700359 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700360 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700361 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700362
363 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700364 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
365 creationResult.keyCharacteristics);
366 EXPECT_GT(creationResult.keyBlob.size(), 0);
367
368 *key_blob = std::move(creationResult.keyBlob);
369 *key_characteristics = std::move(creationResult.keyCharacteristics);
370 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700371
372 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
373 EXPECT_TRUE(algorithm);
374 if (algorithm &&
375 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
376 EXPECT_GE(cert_chain_.size(), 1);
377 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
378 } else {
379 // For symmetric keys there should be no certificates.
380 EXPECT_EQ(cert_chain_.size(), 0);
381 }
Selene Huang31ab4042020-04-29 04:22:39 -0700382 }
383
384 return GetReturnErrorCode(result);
385}
386
387ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
388 const string& key_material) {
389 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
390}
391
392ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
393 const AuthorizationSet& wrapping_key_desc,
394 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100395 const AuthorizationSet& unwrapping_params,
396 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700397 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
398
Shawn Willden7f424372021-01-10 18:06:50 -0700399 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700400
Shawn Willden7f424372021-01-10 18:06:50 -0700401 KeyCreationResult creationResult;
402 Status result = keymint_->importWrappedKey(
403 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
404 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100405 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700406
407 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700408 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
409 creationResult.keyCharacteristics);
410 EXPECT_GT(creationResult.keyBlob.size(), 0);
411
412 key_blob_ = std::move(creationResult.keyBlob);
413 key_characteristics_ = std::move(creationResult.keyCharacteristics);
414 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700415
416 AuthorizationSet allAuths;
417 for (auto& entry : key_characteristics_) {
418 allAuths.push_back(AuthorizationSet(entry.authorizations));
419 }
420 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
421 EXPECT_TRUE(algorithm);
422 if (algorithm &&
423 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
424 EXPECT_GE(cert_chain_.size(), 1);
425 } else {
426 // For symmetric keys there should be no certificates.
427 EXPECT_EQ(cert_chain_.size(), 0);
428 }
Selene Huang31ab4042020-04-29 04:22:39 -0700429 }
430
431 return GetReturnErrorCode(result);
432}
433
David Drysdale300b5552021-05-20 12:05:26 +0100434ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
435 const vector<uint8_t>& app_id,
436 const vector<uint8_t>& app_data,
437 vector<KeyCharacteristics>* key_characteristics) {
438 Status result =
439 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
440 return GetReturnErrorCode(result);
441}
442
443ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
444 vector<KeyCharacteristics>* key_characteristics) {
445 vector<uint8_t> empty_app_id, empty_app_data;
446 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
447}
448
449void KeyMintAidlTestBase::CheckCharacteristics(
450 const vector<uint8_t>& key_blob,
451 const vector<KeyCharacteristics>& generate_characteristics) {
452 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
453 // generateKey() should be excluded, as KeyMint will have no record of them.
454 // This applies to CREATION_DATETIME in particular.
455 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
456 strip_keystore_tags(&expected_characteristics);
457
458 vector<KeyCharacteristics> retrieved;
459 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
460 EXPECT_EQ(expected_characteristics, retrieved);
461}
462
463void KeyMintAidlTestBase::CheckAppIdCharacteristics(
464 const vector<uint8_t>& key_blob, std::string_view app_id_string,
465 std::string_view app_data_string,
466 const vector<KeyCharacteristics>& generate_characteristics) {
467 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
468 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
469 strip_keystore_tags(&expected_characteristics);
470
471 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
472 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
473 vector<KeyCharacteristics> retrieved;
474 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
475 EXPECT_EQ(expected_characteristics, retrieved);
476
477 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
478 vector<uint8_t> empty;
479 vector<KeyCharacteristics> not_retrieved;
480 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
481 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
482 EXPECT_EQ(not_retrieved.size(), 0);
483
484 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
485 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
486 EXPECT_EQ(not_retrieved.size(), 0);
487
488 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
489 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
490 EXPECT_EQ(not_retrieved.size(), 0);
491}
492
Selene Huang31ab4042020-04-29 04:22:39 -0700493ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
494 Status result = keymint_->deleteKey(*key_blob);
495 if (!keep_key_blob) {
496 *key_blob = vector<uint8_t>();
497 }
498
Janis Danisevskis24c04702020-12-16 18:28:39 -0800499 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700500 return GetReturnErrorCode(result);
501}
502
503ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
504 return DeleteKey(&key_blob_, keep_key_blob);
505}
506
507ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
508 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800509 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700510 return GetReturnErrorCode(result);
511}
512
David Drysdaled2cc8c22021-04-15 13:29:45 +0100513ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
514 Status result = keymint_->destroyAttestationIds();
515 return GetReturnErrorCode(result);
516}
517
Selene Huang31ab4042020-04-29 04:22:39 -0700518void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
519 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
520 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
521}
522
523void KeyMintAidlTestBase::CheckedDeleteKey() {
524 CheckedDeleteKey(&key_blob_);
525}
526
527ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
528 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800529 AuthorizationSet* out_params,
530 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700531 SCOPED_TRACE("Begin");
532 Status result;
533 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100534 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700535
536 if (result.isOk()) {
537 *out_params = out.params;
538 challenge_ = out.challenge;
539 op = out.operation;
540 }
541
542 return GetReturnErrorCode(result);
543}
544
545ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
546 const AuthorizationSet& in_params,
David Drysdale28fa9312023-02-01 14:53:01 +0000547 AuthorizationSet* out_params,
548 std::optional<HardwareAuthToken> hat) {
Selene Huang31ab4042020-04-29 04:22:39 -0700549 SCOPED_TRACE("Begin");
550 Status result;
551 BeginResult out;
552
David Drysdale28fa9312023-02-01 14:53:01 +0000553 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), hat, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700554
555 if (result.isOk()) {
556 *out_params = out.params;
557 challenge_ = out.challenge;
558 op_ = out.operation;
559 }
560
561 return GetReturnErrorCode(result);
562}
563
564ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
565 AuthorizationSet* out_params) {
566 SCOPED_TRACE("Begin");
567 EXPECT_EQ(nullptr, op_);
568 return Begin(purpose, key_blob_, in_params, out_params);
569}
570
571ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
572 SCOPED_TRACE("Begin");
573 AuthorizationSet out_params;
574 ErrorCode result = Begin(purpose, in_params, &out_params);
575 EXPECT_TRUE(out_params.empty());
576 return result;
577}
578
Shawn Willden92d79c02021-02-19 07:31:55 -0700579ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
580 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
581 {} /* hardwareAuthToken */,
582 {} /* verificationToken */));
583}
584
585ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700586 SCOPED_TRACE("Update");
587
588 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700589 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700590
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800591 EXPECT_NE(op_, nullptr);
592 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
593
Shawn Willden92d79c02021-02-19 07:31:55 -0700594 std::vector<uint8_t> o_put;
595 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700596
David Drysdalefeab5d92022-01-06 15:46:23 +0000597 if (result.isOk()) {
598 output->append(o_put.begin(), o_put.end());
599 } else {
600 // Failure always terminates the operation.
601 op_ = {};
602 }
Selene Huang31ab4042020-04-29 04:22:39 -0700603
604 return GetReturnErrorCode(result);
605}
606
David Drysdale28fa9312023-02-01 14:53:01 +0000607ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, string* output,
608 std::optional<HardwareAuthToken> hat,
609 std::optional<secureclock::TimeStampToken> time_token) {
Selene Huang31ab4042020-04-29 04:22:39 -0700610 SCOPED_TRACE("Finish");
611 Status result;
612
613 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700614 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700615
616 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700617 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
David Drysdale28fa9312023-02-01 14:53:01 +0000618 vector<uint8_t>(signature.begin(), signature.end()), hat, time_token,
619 {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700620
Shawn Willden92d79c02021-02-19 07:31:55 -0700621 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700622
Shawn Willden92d79c02021-02-19 07:31:55 -0700623 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700624 return GetReturnErrorCode(result);
625}
626
Janis Danisevskis24c04702020-12-16 18:28:39 -0800627ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700628 SCOPED_TRACE("Abort");
629
630 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700631 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700632
633 Status retval = op->abort();
634 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800635 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700636}
637
638ErrorCode KeyMintAidlTestBase::Abort() {
639 SCOPED_TRACE("Abort");
640
641 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700642 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700643
644 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800645 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700646}
647
648void KeyMintAidlTestBase::AbortIfNeeded() {
649 SCOPED_TRACE("AbortIfNeeded");
650 if (op_) {
651 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800652 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700653 }
654}
655
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000656auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
657 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700658 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000659 AuthorizationSet begin_out_params;
660 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700661 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000662
663 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700664 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000665}
666
Selene Huang31ab4042020-04-29 04:22:39 -0700667string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
668 const string& message, const AuthorizationSet& in_params,
669 AuthorizationSet* out_params) {
670 SCOPED_TRACE("ProcessMessage");
671 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700672 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700673 EXPECT_EQ(ErrorCode::OK, result);
674 if (result != ErrorCode::OK) {
675 return "";
676 }
677
678 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700679 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700680 return output;
681}
682
683string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
684 const AuthorizationSet& params) {
685 SCOPED_TRACE("SignMessage");
686 AuthorizationSet out_params;
687 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
688 EXPECT_TRUE(out_params.empty());
689 return signature;
690}
691
692string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
693 SCOPED_TRACE("SignMessage");
694 return SignMessage(key_blob_, message, params);
695}
696
697string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
698 SCOPED_TRACE("MacMessage");
699 return SignMessage(
700 key_blob_, message,
701 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
702}
703
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530704void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
705 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000706 auto builder = AuthorizationSetBuilder()
707 .Authorization(TAG_NO_AUTH_REQUIRED)
708 .AesEncryptionKey(128)
709 .BlockMode(block_mode)
710 .Padding(PaddingMode::NONE);
711 if (block_mode == BlockMode::GCM) {
712 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
713 }
714 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530715
716 for (int increment = 1; increment <= message_size; ++increment) {
717 string message(message_size, 'a');
718 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
719 if (block_mode == BlockMode::GCM) {
720 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
721 }
722
723 AuthorizationSet output_params;
724 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
725
726 string ciphertext;
727 string to_send;
728 for (size_t i = 0; i < message.size(); i += increment) {
729 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
730 }
731 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
732 << "Error sending " << to_send << " with block mode " << block_mode;
733
734 switch (block_mode) {
735 case BlockMode::GCM:
736 EXPECT_EQ(message.size() + 16, ciphertext.size());
737 break;
738 case BlockMode::CTR:
739 EXPECT_EQ(message.size(), ciphertext.size());
740 break;
741 case BlockMode::CBC:
742 case BlockMode::ECB:
743 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
744 break;
745 }
746
747 auto iv = output_params.GetTagValue(TAG_NONCE);
748 switch (block_mode) {
749 case BlockMode::CBC:
750 case BlockMode::GCM:
751 case BlockMode::CTR:
752 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
753 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
754 params.push_back(TAG_NONCE, iv->get());
755 break;
756
757 case BlockMode::ECB:
758 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
759 break;
760 }
761
762 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
763 << "Decrypt begin() failed for block mode " << block_mode;
764
765 string plaintext;
766 for (size_t i = 0; i < ciphertext.size(); i += increment) {
767 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
768 }
769 ErrorCode error = Finish(to_send, &plaintext);
770 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
771 << " and increment " << increment;
772 if (error == ErrorCode::OK) {
773 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
774 << " and increment " << increment;
775 }
776 }
777}
778
Prashant Patildd5f7f02022-07-06 18:58:07 +0000779void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
780 PaddingMode padding_mode, const string& iv,
781 const string& plaintext,
782 const string& exp_cipher_text) {
783 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
784 auto auth_set = AuthorizationSetBuilder()
785 .Authorization(TAG_NO_AUTH_REQUIRED)
786 .AesEncryptionKey(key.size() * 8)
787 .BlockMode(block_mode)
788 .Padding(padding_mode);
789 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
790 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
791 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
792
793 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
794 exp_cipher_text);
795}
796
797void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
798 PaddingMode padding_mode, const string& iv,
799 const string& plaintext,
800 const string& exp_cipher_text) {
801 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
802 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
803 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
804 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
805 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
806
807 AuthorizationSet output_params;
808 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
809
810 string actual_ciphertext;
811 if (is_stream_cipher) {
812 // Assert that a 1 byte of output is produced for 1 byte of input.
813 // Every input byte produces an output byte.
814 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
815 string ciphertext;
816 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
817 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
818 // we relax this API restriction for them.
819 if (SecLevel() != SecurityLevel::STRONGBOX) {
820 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
821 }
822 actual_ciphertext.append(ciphertext);
823 }
824 string ciphertext;
825 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
826 if (SecLevel() != SecurityLevel::STRONGBOX) {
827 string expected_final_output;
828 if (is_authenticated_cipher) {
829 expected_final_output = exp_cipher_text.substr(plaintext.size());
830 }
831 EXPECT_EQ(expected_final_output, ciphertext);
832 }
833 actual_ciphertext.append(ciphertext);
834 } else {
835 // Assert that a block of output is produced once a full block of input is provided.
836 // Every input block produces an output block.
837 bool compare_output = true;
838 string additional_information;
839 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
840 if (SecLevel() == SecurityLevel::STRONGBOX) {
841 // This is known to be broken on older vendor implementations.
842 if (vendor_api_level < 33) {
843 compare_output = false;
844 } else {
845 additional_information = " (b/194134359) ";
846 }
847 }
848 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
849 string ciphertext;
850 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
851 if (compare_output) {
852 if ((plaintext_index % block_size) == block_size - 1) {
853 // Update is expected to have output a new block
854 EXPECT_EQ(block_size, ciphertext.size())
855 << "plaintext index: " << plaintext_index << additional_information;
856 } else {
857 // Update is expected to have produced no output
858 EXPECT_EQ(0, ciphertext.size())
859 << "plaintext index: " << plaintext_index << additional_information;
860 }
861 }
862 actual_ciphertext.append(ciphertext);
863 }
864 string ciphertext;
865 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
866 actual_ciphertext.append(ciphertext);
867 }
868 // Regardless of how the completed ciphertext got accumulated, it should match the expected
869 // ciphertext.
870 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
871}
872
Selene Huang31ab4042020-04-29 04:22:39 -0700873void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
874 Digest digest, const string& expected_mac) {
875 SCOPED_TRACE("CheckHmacTestVector");
876 ASSERT_EQ(ErrorCode::OK,
877 ImportKey(AuthorizationSetBuilder()
878 .Authorization(TAG_NO_AUTH_REQUIRED)
879 .HmacKey(key.size() * 8)
880 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
881 .Digest(digest),
882 KeyFormat::RAW, key));
883 string signature = MacMessage(message, digest, expected_mac.size() * 8);
884 EXPECT_EQ(expected_mac, signature)
885 << "Test vector didn't match for key of size " << key.size() << " message of size "
886 << message.size() << " and digest " << digest;
887 CheckedDeleteKey();
888}
889
890void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
891 const string& message,
892 const string& expected_ciphertext) {
893 SCOPED_TRACE("CheckAesCtrTestVector");
894 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
895 .Authorization(TAG_NO_AUTH_REQUIRED)
896 .AesEncryptionKey(key.size() * 8)
897 .BlockMode(BlockMode::CTR)
898 .Authorization(TAG_CALLER_NONCE)
899 .Padding(PaddingMode::NONE),
900 KeyFormat::RAW, key));
901
902 auto params = AuthorizationSetBuilder()
903 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
904 .BlockMode(BlockMode::CTR)
905 .Padding(PaddingMode::NONE);
906 AuthorizationSet out_params;
907 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
908 EXPECT_EQ(expected_ciphertext, ciphertext);
909}
910
911void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
912 PaddingMode padding_mode, const string& key,
913 const string& iv, const string& input,
914 const string& expected_output) {
915 auto authset = AuthorizationSetBuilder()
916 .TripleDesEncryptionKey(key.size() * 7)
917 .BlockMode(block_mode)
918 .Authorization(TAG_NO_AUTH_REQUIRED)
919 .Padding(padding_mode);
920 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
921 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
922 ASSERT_GT(key_blob_.size(), 0U);
923
924 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
925 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
926 AuthorizationSet output_params;
927 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
928 EXPECT_EQ(expected_output, output);
929}
930
931void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
932 const string& signature, const AuthorizationSet& params) {
933 SCOPED_TRACE("VerifyMessage");
934 AuthorizationSet begin_out_params;
935 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
936
937 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700938 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700939 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700940 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700941}
942
943void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
944 const AuthorizationSet& params) {
945 SCOPED_TRACE("VerifyMessage");
946 VerifyMessage(key_blob_, message, signature, params);
947}
948
David Drysdaledf8f52e2021-05-06 08:10:58 +0100949void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
950 const AuthorizationSet& params) {
951 SCOPED_TRACE("LocalVerifyMessage");
952
David Drysdaledf8f52e2021-05-06 08:10:58 +0100953 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000954 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
955}
956
957void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
958 const string& signature,
959 const AuthorizationSet& params) {
960 // Retrieve the public key from the leaf certificate.
961 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100962 ASSERT_TRUE(key_cert.get());
963 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
964 ASSERT_TRUE(pub_key.get());
965
966 Digest digest = params.GetTagValue(TAG_DIGEST).value();
967 PaddingMode padding = PaddingMode::NONE;
968 auto tag = params.GetTagValue(TAG_PADDING);
969 if (tag.has_value()) {
970 padding = tag.value();
971 }
972
973 if (digest == Digest::NONE) {
974 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100975 case EVP_PKEY_ED25519: {
976 ASSERT_EQ(64, signature.size());
977 uint8_t pub_keydata[32];
978 size_t pub_len = sizeof(pub_keydata);
979 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
980 ASSERT_EQ(sizeof(pub_keydata), pub_len);
981 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
982 message.size(),
983 reinterpret_cast<const uint8_t*>(signature.data()),
984 pub_keydata));
985 break;
986 }
987
David Drysdaledf8f52e2021-05-06 08:10:58 +0100988 case EVP_PKEY_EC: {
989 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
990 size_t data_size = std::min(data.size(), message.size());
991 memcpy(data.data(), message.data(), data_size);
992 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
993 ASSERT_TRUE(ecdsa.get());
994 ASSERT_EQ(1,
995 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
996 reinterpret_cast<const uint8_t*>(signature.data()),
997 signature.size(), ecdsa.get()));
998 break;
999 }
1000 case EVP_PKEY_RSA: {
1001 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
1002 size_t data_size = std::min(data.size(), message.size());
1003 memcpy(data.data(), message.data(), data_size);
1004
1005 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1006 ASSERT_TRUE(rsa.get());
1007
1008 size_t key_len = RSA_size(rsa.get());
1009 int openssl_padding = RSA_NO_PADDING;
1010 switch (padding) {
1011 case PaddingMode::NONE:
1012 ASSERT_TRUE(data_size <= key_len);
1013 ASSERT_EQ(key_len, signature.size());
1014 openssl_padding = RSA_NO_PADDING;
1015 break;
1016 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1017 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1018 key_len);
1019 openssl_padding = RSA_PKCS1_PADDING;
1020 break;
1021 default:
1022 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1023 }
1024
1025 vector<uint8_t> decrypted_data(key_len);
1026 int bytes_decrypted = RSA_public_decrypt(
1027 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1028 decrypted_data.data(), rsa.get(), openssl_padding);
1029 ASSERT_GE(bytes_decrypted, 0);
1030
1031 const uint8_t* compare_pos = decrypted_data.data();
1032 size_t bytes_to_compare = bytes_decrypted;
1033 uint8_t zero_check_result = 0;
1034 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1035 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1036 // during verification we should have zeros on the left of the decrypted data.
1037 // Do a constant-time check.
1038 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1039 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1040 ASSERT_EQ(0, zero_check_result);
1041 bytes_to_compare = data_size;
1042 }
1043 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1044 break;
1045 }
1046 default:
1047 ADD_FAILURE() << "Unknown public key type";
1048 }
1049 } else {
1050 EVP_MD_CTX digest_ctx;
1051 EVP_MD_CTX_init(&digest_ctx);
1052 EVP_PKEY_CTX* pkey_ctx;
1053 const EVP_MD* md = openssl_digest(digest);
1054 ASSERT_NE(md, nullptr);
1055 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1056
1057 if (padding == PaddingMode::RSA_PSS) {
1058 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1059 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001060 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001061 }
1062
1063 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1064 reinterpret_cast<const uint8_t*>(message.data()),
1065 message.size()));
1066 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1067 reinterpret_cast<const uint8_t*>(signature.data()),
1068 signature.size()));
1069 EVP_MD_CTX_cleanup(&digest_ctx);
1070 }
1071}
1072
David Drysdale59cae642021-05-12 13:52:03 +01001073string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1074 const AuthorizationSet& params) {
1075 SCOPED_TRACE("LocalRsaEncryptMessage");
1076
1077 // Retrieve the public key from the leaf certificate.
1078 if (cert_chain_.empty()) {
1079 ADD_FAILURE() << "No public key available";
1080 return "Failure";
1081 }
1082 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001083 if (key_cert.get() == nullptr) {
1084 ADD_FAILURE() << "Failed to parse cert";
1085 return "Failure";
1086 }
David Drysdale59cae642021-05-12 13:52:03 +01001087 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001088 if (pub_key.get() == nullptr) {
1089 ADD_FAILURE() << "Failed to retrieve public key";
1090 return "Failure";
1091 }
David Drysdale59cae642021-05-12 13:52:03 +01001092 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001093 if (rsa.get() == nullptr) {
1094 ADD_FAILURE() << "Failed to retrieve RSA public key";
1095 return "Failure";
1096 }
David Drysdale59cae642021-05-12 13:52:03 +01001097
1098 // Retrieve relevant tags.
1099 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001100 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001101 PaddingMode padding = PaddingMode::NONE;
1102
1103 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1104 if (digest_tag.has_value()) digest = digest_tag.value();
1105 auto pad_tag = params.GetTagValue(TAG_PADDING);
1106 if (pad_tag.has_value()) padding = pad_tag.value();
1107 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1108 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1109
1110 const EVP_MD* md = openssl_digest(digest);
1111 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1112
1113 // Set up encryption context.
1114 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1115 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1116 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1117 return "Failure";
1118 }
1119
1120 int rc = -1;
1121 switch (padding) {
1122 case PaddingMode::NONE:
1123 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1124 break;
1125 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1126 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1127 break;
1128 case PaddingMode::RSA_OAEP:
1129 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1130 break;
1131 default:
1132 break;
1133 }
1134 if (rc <= 0) {
1135 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1136 return "Failure";
1137 }
1138 if (padding == PaddingMode::RSA_OAEP) {
1139 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1140 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1141 return "Failure";
1142 }
1143 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1144 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1145 return "Failure";
1146 }
1147 }
1148
1149 // Determine output size.
1150 size_t outlen;
1151 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1152 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1153 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1154 return "Failure";
1155 }
1156
1157 // Left-zero-pad the input if necessary.
1158 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1159 size_t to_encrypt_len = message.size();
1160
1161 std::unique_ptr<string> zero_padded_message;
1162 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1163 zero_padded_message.reset(new string(outlen, '\0'));
1164 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1165 message.size());
1166 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1167 to_encrypt_len = outlen;
1168 }
1169
1170 // Do the encryption.
1171 string output(outlen, '\0');
1172 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1173 to_encrypt_len) <= 0) {
1174 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1175 return "Failure";
1176 }
1177 return output;
1178}
1179
Selene Huang31ab4042020-04-29 04:22:39 -07001180string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1181 const AuthorizationSet& in_params,
1182 AuthorizationSet* out_params) {
1183 SCOPED_TRACE("EncryptMessage");
1184 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1185}
1186
1187string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1188 AuthorizationSet* out_params) {
1189 SCOPED_TRACE("EncryptMessage");
1190 return EncryptMessage(key_blob_, message, params, out_params);
1191}
1192
1193string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1194 SCOPED_TRACE("EncryptMessage");
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) {
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_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1208 return ciphertext;
1209}
1210
1211string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1212 PaddingMode padding, vector<uint8_t>* iv_out) {
1213 SCOPED_TRACE("EncryptMessage");
1214 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1215 AuthorizationSet out_params;
1216 string ciphertext = EncryptMessage(message, params, &out_params);
1217 EXPECT_EQ(1U, out_params.size());
1218 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001219 EXPECT_TRUE(ivVal);
1220 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001221 return ciphertext;
1222}
1223
1224string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1225 PaddingMode padding, const vector<uint8_t>& iv_in) {
1226 SCOPED_TRACE("EncryptMessage");
1227 auto params = AuthorizationSetBuilder()
1228 .BlockMode(block_mode)
1229 .Padding(padding)
1230 .Authorization(TAG_NONCE, iv_in);
1231 AuthorizationSet out_params;
1232 string ciphertext = EncryptMessage(message, params, &out_params);
1233 return ciphertext;
1234}
1235
1236string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1237 PaddingMode padding, uint8_t mac_length_bits,
1238 const vector<uint8_t>& iv_in) {
1239 SCOPED_TRACE("EncryptMessage");
1240 auto params = AuthorizationSetBuilder()
1241 .BlockMode(block_mode)
1242 .Padding(padding)
1243 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1244 .Authorization(TAG_NONCE, iv_in);
1245 AuthorizationSet out_params;
1246 string ciphertext = EncryptMessage(message, params, &out_params);
1247 return ciphertext;
1248}
1249
David Drysdaled2cc8c22021-04-15 13:29:45 +01001250string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1251 PaddingMode padding, uint8_t mac_length_bits) {
1252 SCOPED_TRACE("EncryptMessage");
1253 auto params = AuthorizationSetBuilder()
1254 .BlockMode(block_mode)
1255 .Padding(padding)
1256 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1257 AuthorizationSet out_params;
1258 string ciphertext = EncryptMessage(message, params, &out_params);
1259 return ciphertext;
1260}
1261
Selene Huang31ab4042020-04-29 04:22:39 -07001262string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1263 const string& ciphertext,
1264 const AuthorizationSet& params) {
1265 SCOPED_TRACE("DecryptMessage");
1266 AuthorizationSet out_params;
1267 string plaintext =
1268 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1269 EXPECT_TRUE(out_params.empty());
1270 return plaintext;
1271}
1272
1273string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1274 const AuthorizationSet& params) {
1275 SCOPED_TRACE("DecryptMessage");
1276 return DecryptMessage(key_blob_, ciphertext, params);
1277}
1278
1279string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1280 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1281 SCOPED_TRACE("DecryptMessage");
1282 auto params = AuthorizationSetBuilder()
1283 .BlockMode(block_mode)
1284 .Padding(padding_mode)
1285 .Authorization(TAG_NONCE, iv);
1286 return DecryptMessage(key_blob_, ciphertext, params);
1287}
1288
1289std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1290 const vector<uint8_t>& key_blob) {
1291 std::pair<ErrorCode, vector<uint8_t>> retval;
1292 vector<uint8_t> outKeyBlob;
1293 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1294 ErrorCode errorcode = GetReturnErrorCode(result);
1295 retval = std::tie(errorcode, outKeyBlob);
1296
1297 return retval;
1298}
1299vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1300 switch (algorithm) {
1301 case Algorithm::RSA:
1302 switch (SecLevel()) {
1303 case SecurityLevel::SOFTWARE:
1304 case SecurityLevel::TRUSTED_ENVIRONMENT:
1305 return {2048, 3072, 4096};
1306 case SecurityLevel::STRONGBOX:
1307 return {2048};
1308 default:
1309 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1310 break;
1311 }
1312 break;
1313 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001314 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001315 break;
1316 case Algorithm::AES:
1317 return {128, 256};
1318 case Algorithm::TRIPLE_DES:
1319 return {168};
1320 case Algorithm::HMAC: {
1321 vector<uint32_t> retval((512 - 64) / 8 + 1);
1322 uint32_t size = 64 - 8;
1323 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1324 return retval;
1325 }
1326 default:
1327 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1328 return {};
1329 }
1330 ADD_FAILURE() << "Should be impossible to get here";
1331 return {};
1332}
1333
1334vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1335 if (SecLevel() == SecurityLevel::STRONGBOX) {
1336 switch (algorithm) {
1337 case Algorithm::RSA:
1338 return {3072, 4096};
1339 case Algorithm::EC:
1340 return {224, 384, 521};
1341 case Algorithm::AES:
1342 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001343 case Algorithm::TRIPLE_DES:
1344 return {56};
1345 default:
1346 return {};
1347 }
1348 } else {
1349 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001350 case Algorithm::AES:
1351 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001352 case Algorithm::TRIPLE_DES:
1353 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001354 default:
1355 return {};
1356 }
1357 }
1358 return {};
1359}
1360
David Drysdale7de9feb2021-03-05 14:56:19 +00001361vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1362 switch (algorithm) {
1363 case Algorithm::AES:
1364 return {
1365 BlockMode::CBC,
1366 BlockMode::CTR,
1367 BlockMode::ECB,
1368 BlockMode::GCM,
1369 };
1370 case Algorithm::TRIPLE_DES:
1371 return {
1372 BlockMode::CBC,
1373 BlockMode::ECB,
1374 };
1375 default:
1376 return {};
1377 }
1378}
1379
1380vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1381 BlockMode blockMode) {
1382 switch (algorithm) {
1383 case Algorithm::AES:
1384 switch (blockMode) {
1385 case BlockMode::CBC:
1386 case BlockMode::ECB:
1387 return {PaddingMode::NONE, PaddingMode::PKCS7};
1388 case BlockMode::CTR:
1389 case BlockMode::GCM:
1390 return {PaddingMode::NONE};
1391 default:
1392 return {};
1393 };
1394 case Algorithm::TRIPLE_DES:
1395 switch (blockMode) {
1396 case BlockMode::CBC:
1397 case BlockMode::ECB:
1398 return {PaddingMode::NONE, PaddingMode::PKCS7};
1399 default:
1400 return {};
1401 };
1402 default:
1403 return {};
1404 }
1405}
1406
1407vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1408 BlockMode blockMode) {
1409 switch (algorithm) {
1410 case Algorithm::AES:
1411 switch (blockMode) {
1412 case BlockMode::CTR:
1413 case BlockMode::GCM:
1414 return {PaddingMode::PKCS7};
1415 default:
1416 return {};
1417 };
1418 default:
1419 return {};
1420 }
1421}
1422
Selene Huang31ab4042020-04-29 04:22:39 -07001423vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1424 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1425 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001426 } else if (Curve25519Supported()) {
1427 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1428 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001429 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001430 return {
1431 EcCurve::P_224,
1432 EcCurve::P_256,
1433 EcCurve::P_384,
1434 EcCurve::P_521,
1435 };
Selene Huang31ab4042020-04-29 04:22:39 -07001436 }
1437}
1438
1439vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001440 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001441 // Curve 25519 is not supported, either because:
1442 // - KeyMint v1: it's an unknown enum value
1443 // - KeyMint v2+: it's not supported by StrongBox.
1444 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001445 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001446 if (Curve25519Supported()) {
1447 return {};
1448 } else {
1449 return {EcCurve::CURVE_25519};
1450 }
David Drysdaledf09e542021-06-08 15:46:11 +01001451 }
Selene Huang31ab4042020-04-29 04:22:39 -07001452}
1453
subrahmanyaman05642492022-02-05 07:10:56 +00001454vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1455 if (SecLevel() == SecurityLevel::STRONGBOX) {
1456 return {65537};
1457 } else {
1458 return {3, 65537};
1459 }
1460}
1461
Selene Huang31ab4042020-04-29 04:22:39 -07001462vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1463 switch (SecLevel()) {
1464 case SecurityLevel::SOFTWARE:
1465 case SecurityLevel::TRUSTED_ENVIRONMENT:
1466 if (withNone) {
1467 if (withMD5)
1468 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1469 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1470 Digest::SHA_2_512};
1471 else
1472 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1473 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1474 } else {
1475 if (withMD5)
1476 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1477 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1478 else
1479 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1480 Digest::SHA_2_512};
1481 }
1482 break;
1483 case SecurityLevel::STRONGBOX:
1484 if (withNone)
1485 return {Digest::NONE, Digest::SHA_2_256};
1486 else
1487 return {Digest::SHA_2_256};
1488 break;
1489 default:
1490 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1491 break;
1492 }
1493 ADD_FAILURE() << "Should be impossible to get here";
1494 return {};
1495}
1496
Shawn Willden7f424372021-01-10 18:06:50 -07001497static const vector<KeyParameter> kEmptyAuthList{};
1498
1499const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1500 const vector<KeyCharacteristics>& key_characteristics) {
1501 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1502 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1503 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1504}
1505
Qi Wubeefae42021-01-28 23:16:37 +08001506const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1507 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1508 auto found = std::find_if(
1509 key_characteristics.begin(), key_characteristics.end(),
1510 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001511 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1512}
1513
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001514ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001515 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001516 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1517 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1518 return result;
1519}
1520
1521ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001522 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001523 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1524 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1525 return result;
1526}
1527
1528ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1529 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001530 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001531 rsaKeyBlob, KeyPurpose::SIGN, message,
1532 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1533 return result;
1534}
1535
1536ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001537 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1538 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001539 return result;
1540}
1541
Selene Huang6e46f142021-04-20 19:20:11 -07001542void verify_serial(X509* cert, const uint64_t expected_serial) {
1543 BIGNUM_Ptr ser(BN_new());
1544 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1545
1546 uint64_t serial;
1547 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1548 EXPECT_EQ(serial, expected_serial);
1549}
1550
1551// Please set self_signed to true for fake certificates or self signed
1552// certificates
1553void verify_subject(const X509* cert, //
1554 const string& subject, //
1555 bool self_signed) {
1556 char* cert_issuer = //
1557 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1558
1559 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1560
1561 string expected_subject("/CN=");
1562 if (subject.empty()) {
1563 expected_subject.append("Android Keystore Key");
1564 } else {
1565 expected_subject.append(subject);
1566 }
1567
1568 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1569
1570 if (self_signed) {
1571 EXPECT_STREQ(cert_issuer, cert_subj)
1572 << "Cert issuer and subject mismatch for self signed certificate.";
1573 }
1574
1575 OPENSSL_free(cert_subj);
1576 OPENSSL_free(cert_issuer);
1577}
1578
Shawn Willden22fb9c12022-06-02 14:04:33 -06001579int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001580 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1581 if (vendor_api_level != -1) {
1582 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001583 }
Shawn Willden35db3492022-06-16 12:50:40 -06001584
1585 // Android S and older devices do not define ro.vendor.api_level
1586 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1587 if (vendor_api_level == -1) {
1588 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001589 }
Shawn Willden35db3492022-06-16 12:50:40 -06001590
1591 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1592 if (product_api_level == -1) {
1593 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1594 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001595 }
Shawn Willden35db3492022-06-16 12:50:40 -06001596
1597 // VSR API level is the minimum of vendor_api_level and product_api_level.
1598 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1599 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001600 }
Shawn Willden35db3492022-06-16 12:50:40 -06001601 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001602}
1603
David Drysdale555ba002022-05-03 18:48:57 +01001604bool is_gsi_image() {
1605 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1606 return ifs.good();
1607}
1608
Selene Huang6e46f142021-04-20 19:20:11 -07001609vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1610 BIGNUM_Ptr serial(BN_new());
1611 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1612
1613 int len = BN_num_bytes(serial.get());
1614 vector<uint8_t> serial_blob(len);
1615 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1616 return {};
1617 }
1618
David Drysdaledb0dcf52021-05-18 11:43:31 +01001619 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1620 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1621 // Top bit being set indicates a negative number in two's complement, but our input
1622 // was positive.
1623 // In either case, prepend a zero byte.
1624 serial_blob.insert(serial_blob.begin(), 0x00);
1625 }
1626
Selene Huang6e46f142021-04-20 19:20:11 -07001627 return serial_blob;
1628}
1629
1630void verify_subject_and_serial(const Certificate& certificate, //
1631 const uint64_t expected_serial, //
1632 const string& subject, bool self_signed) {
1633 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1634 ASSERT_TRUE(!!cert.get());
1635
1636 verify_serial(cert.get(), expected_serial);
1637 verify_subject(cert.get(), subject, self_signed);
1638}
1639
Shawn Willden4315e132022-03-20 12:49:46 -06001640void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1641 VerifiedBoot verified_boot_state,
1642 const vector<uint8_t>& verified_boot_hash) {
1643 char property_value[PROPERTY_VALUE_MAX] = {};
1644
1645 if (avb_verification_enabled()) {
1646 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1647 string prop_string(property_value);
1648 EXPECT_EQ(prop_string.size(), 64);
1649 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1650
1651 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1652 if (!strcmp(property_value, "unlocked")) {
1653 EXPECT_FALSE(device_locked);
1654 } else {
1655 EXPECT_TRUE(device_locked);
1656 }
1657
1658 // Check that the device is locked if not debuggable, e.g., user build
1659 // images in CTS. For VTS, debuggable images are used to allow adb root
1660 // and the device is unlocked.
1661 if (!property_get_bool("ro.debuggable", false)) {
1662 EXPECT_TRUE(device_locked);
1663 } else {
1664 EXPECT_FALSE(device_locked);
1665 }
1666 }
1667
1668 // Verified boot key should be all 0's if the boot state is not verified or self signed
1669 std::string empty_boot_key(32, '\0');
1670 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1671 verified_boot_key.size());
1672 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1673 if (!strcmp(property_value, "green")) {
1674 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1675 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1676 verified_boot_key.size()));
1677 } else if (!strcmp(property_value, "yellow")) {
1678 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1679 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1680 verified_boot_key.size()));
1681 } else if (!strcmp(property_value, "orange")) {
1682 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1683 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1684 verified_boot_key.size()));
1685 } else if (!strcmp(property_value, "red")) {
1686 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1687 } else {
1688 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1689 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1690 verified_boot_key.size()));
1691 }
1692}
1693
David Drysdale7dff4fc2021-12-10 10:10:52 +00001694bool verify_attestation_record(int32_t aidl_version, //
1695 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001696 const string& app_id, //
1697 AuthorizationSet expected_sw_enforced, //
1698 AuthorizationSet expected_hw_enforced, //
1699 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001700 const vector<uint8_t>& attestation_cert,
1701 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001702 X509_Ptr cert(parse_cert_blob(attestation_cert));
1703 EXPECT_TRUE(!!cert.get());
1704 if (!cert.get()) return false;
1705
1706 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1707 EXPECT_TRUE(!!attest_rec);
1708 if (!attest_rec) return false;
1709
1710 AuthorizationSet att_sw_enforced;
1711 AuthorizationSet att_hw_enforced;
1712 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001713 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001714 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001715 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001716 vector<uint8_t> att_challenge;
1717 vector<uint8_t> att_unique_id;
1718 vector<uint8_t> att_app_id;
1719
1720 auto error = parse_attestation_record(attest_rec->data, //
1721 attest_rec->length, //
1722 &att_attestation_version, //
1723 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001724 &att_keymint_version, //
1725 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001726 &att_challenge, //
1727 &att_sw_enforced, //
1728 &att_hw_enforced, //
1729 &att_unique_id);
1730 EXPECT_EQ(ErrorCode::OK, error);
1731 if (error != ErrorCode::OK) return false;
1732
David Drysdale7dff4fc2021-12-10 10:10:52 +00001733 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001734 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001735
Selene Huang4f64c222021-04-13 19:54:36 -07001736 // check challenge and app id only if we expects a non-fake certificate
1737 if (challenge.length() > 0) {
1738 EXPECT_EQ(challenge.length(), att_challenge.size());
1739 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1740
1741 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1742 }
Shawn Willden7c130392020-12-21 09:58:22 -07001743
David Drysdale7dff4fc2021-12-10 10:10:52 +00001744 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001745 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001746 EXPECT_EQ(security_level, att_attestation_security_level);
1747
Shawn Willden7c130392020-12-21 09:58:22 -07001748 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001749 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001750 // for the BOOT_PATCH_LEVEL.
1751 if (avb_verification_enabled()) {
1752 for (int i = 0; i < att_hw_enforced.size(); i++) {
1753 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1754 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1755 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001756 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001757
Shawn Willden7c130392020-12-21 09:58:22 -07001758 // strptime seems to require delimiters, but the tag value will
1759 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001760 if (date.size() != 8) {
1761 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1762 << " with invalid format (not YYYYMMDD): " << date;
1763 return false;
1764 }
Shawn Willden7c130392020-12-21 09:58:22 -07001765 date.insert(6, "-");
1766 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001767 struct tm time;
1768 strptime(date.c_str(), "%Y-%m-%d", &time);
1769
1770 // Day of the month (0-31)
1771 EXPECT_GE(time.tm_mday, 0);
1772 EXPECT_LT(time.tm_mday, 32);
1773 // Months since Jan (0-11)
1774 EXPECT_GE(time.tm_mon, 0);
1775 EXPECT_LT(time.tm_mon, 12);
1776 // Years since 1900
1777 EXPECT_GT(time.tm_year, 110);
1778 EXPECT_LT(time.tm_year, 200);
1779 }
1780 }
1781 }
1782
1783 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1784 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1785 // indicates correct encoding. No need to check if it's in both lists, since the
1786 // AuthorizationSet compare below will handle mismatches of tags.
1787 if (security_level == SecurityLevel::SOFTWARE) {
1788 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1789 } else {
1790 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1791 }
1792
Shawn Willden7c130392020-12-21 09:58:22 -07001793 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1794 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1795 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1796 att_hw_enforced.Contains(TAG_KEY_SIZE));
1797 }
1798
1799 // Test root of trust elements
1800 vector<uint8_t> verified_boot_key;
1801 VerifiedBoot verified_boot_state;
1802 bool device_locked;
1803 vector<uint8_t> verified_boot_hash;
1804 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1805 &verified_boot_state, &device_locked, &verified_boot_hash);
1806 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001807 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001808
1809 att_sw_enforced.Sort();
1810 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001811 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001812
1813 att_hw_enforced.Sort();
1814 expected_hw_enforced.Sort();
1815 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1816
David Drysdale565ccc72021-10-11 12:49:50 +01001817 if (unique_id != nullptr) {
1818 *unique_id = att_unique_id;
1819 }
1820
Shawn Willden7c130392020-12-21 09:58:22 -07001821 return true;
1822}
1823
1824string bin2hex(const vector<uint8_t>& data) {
1825 string retval;
1826 retval.reserve(data.size() * 2 + 1);
1827 for (uint8_t byte : data) {
1828 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1829 retval.push_back(nibble2hex[0x0F & byte]);
1830 }
1831 return retval;
1832}
1833
David Drysdalef0d516d2021-03-22 07:51:43 +00001834AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1835 AuthorizationSet authList;
1836 for (auto& entry : key_characteristics) {
1837 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1838 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1839 authList.push_back(AuthorizationSet(entry.authorizations));
1840 }
1841 }
1842 return authList;
1843}
1844
1845AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1846 AuthorizationSet authList;
1847 for (auto& entry : key_characteristics) {
1848 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1849 entry.securityLevel == SecurityLevel::KEYSTORE) {
1850 authList.push_back(AuthorizationSet(entry.authorizations));
1851 }
1852 }
1853 return authList;
1854}
1855
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001856AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1857 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001858 std::stringstream cert_data;
1859
1860 for (size_t i = 0; i < chain.size(); ++i) {
1861 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1862
1863 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1864 X509_Ptr signing_cert;
1865 if (i < chain.size() - 1) {
1866 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1867 } else {
1868 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1869 }
1870 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1871
1872 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1873 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1874
1875 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1876 return AssertionFailure()
1877 << "Verification of certificate " << i << " failed "
1878 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1879 << cert_data.str();
1880 }
1881
1882 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1883 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001884 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001885 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1886 << " Signer subject is " << signer_subj
1887 << " Issuer subject is " << cert_issuer << endl
1888 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001889 }
Shawn Willden7c130392020-12-21 09:58:22 -07001890 }
1891
1892 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1893 return AssertionSuccess();
1894}
1895
1896X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1897 const uint8_t* p = blob.data();
1898 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1899}
1900
David Drysdalef0d516d2021-03-22 07:51:43 +00001901vector<uint8_t> make_name_from_str(const string& name) {
1902 X509_NAME_Ptr x509_name(X509_NAME_new());
1903 EXPECT_TRUE(x509_name.get() != nullptr);
1904 if (!x509_name) return {};
1905
1906 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1907 "CN", //
1908 MBSTRING_ASC,
1909 reinterpret_cast<const uint8_t*>(name.c_str()),
1910 -1, // len
1911 -1, // loc
1912 0 /* set */));
1913
1914 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1915 EXPECT_GT(len, 0);
1916
1917 vector<uint8_t> retval(len);
1918 uint8_t* p = retval.data();
1919 i2d_X509_NAME(x509_name.get(), &p);
1920
1921 return retval;
1922}
1923
David Drysdale4dc01072021-04-01 12:17:35 +01001924namespace {
1925
1926void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1927 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1928 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1929
1930 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1931 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001932 EXPECT_THAT(
1933 cppbor::prettyPrint(parsedPayload.get()),
1934 MatchesRegex("\\{\n"
1935 " 1 : 2,\n" // kty: EC2
1936 " 3 : -7,\n" // alg: ES256
1937 " -1 : 1,\n" // EC id: P256
1938 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1939 // sequence of 32 hexadecimal bytes, enclosed in braces and
1940 // separated by commas. In this case, some Ed25519 public key.
1941 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1942 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1943 " -70000 : null,\n" // test marker
1944 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001945 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001946 EXPECT_THAT(
1947 cppbor::prettyPrint(parsedPayload.get()),
1948 MatchesRegex("\\{\n"
1949 " 1 : 2,\n" // kty: EC2
1950 " 3 : -7,\n" // alg: ES256
1951 " -1 : 1,\n" // EC id: P256
1952 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1953 // sequence of 32 hexadecimal bytes, enclosed in braces and
1954 // separated by commas. In this case, some Ed25519 public key.
1955 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1956 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1957 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001958 }
1959}
1960
1961} // namespace
1962
1963void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1964 vector<uint8_t>* payload_value) {
1965 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1966 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1967
1968 ASSERT_NE(coseMac0->asArray(), nullptr);
1969 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1970
1971 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1972 ASSERT_NE(protParms, nullptr);
1973
1974 // Header label:value of 'alg': HMAC-256
1975 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1976
1977 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1978 ASSERT_NE(unprotParms, nullptr);
1979 ASSERT_EQ(unprotParms->size(), 0);
1980
1981 // The payload is a bstr holding an encoded COSE_Key
1982 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1983 ASSERT_NE(payload, nullptr);
1984 check_cose_key(payload->value(), testMode);
1985
1986 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1987 ASSERT_TRUE(coseMac0Tag);
1988 auto extractedTag = coseMac0Tag->value();
1989 EXPECT_EQ(extractedTag.size(), 32U);
1990
1991 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001992 auto macFunction = [](const cppcose::bytevec& input) {
1993 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1994 };
1995 auto testTag =
1996 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001997 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1998
1999 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07002000 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01002001 } else {
Seth Moore026bb742021-04-30 11:41:18 -07002002 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002003 }
2004 if (payload_value != nullptr) {
2005 *payload_value = payload->value();
2006 }
2007}
2008
2009void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2010 // Extract x and y affine coordinates from the encoded Cose_Key.
2011 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2012 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2013 auto coseKey = parsedPayload->asMap();
2014 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2015 ASSERT_NE(xItem->asBstr(), nullptr);
2016 vector<uint8_t> x = xItem->asBstr()->value();
2017 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2018 ASSERT_NE(yItem->asBstr(), nullptr);
2019 vector<uint8_t> y = yItem->asBstr()->value();
2020
2021 // Concatenate: 0x04 (uncompressed form marker) | x | y
2022 vector<uint8_t> pubKeyData{0x04};
2023 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2024 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2025
2026 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2027 ASSERT_NE(ecKey, nullptr);
2028 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2029 ASSERT_NE(group, nullptr);
2030 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2031 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2032 ASSERT_NE(point, nullptr);
2033 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2034 nullptr),
2035 1);
2036 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2037
2038 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2039 ASSERT_NE(pubKey, nullptr);
2040 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2041 *signingKey = std::move(pubKey);
2042}
2043
Max Biresa97ec692022-11-21 23:37:54 -08002044void device_id_attestation_vsr_check(const ErrorCode& result) {
2045 if (get_vsr_api_level() >= 34) {
2046 ASSERT_FALSE(result == ErrorCode::INVALID_TAG)
2047 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2048 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2049 << "be used for a case where updateAad() is called after update(). As of "
2050 << "VSR-14, this is now enforced as an error.";
2051 }
2052}
2053
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002054// Check whether the given named feature is available.
2055bool check_feature(const std::string& name) {
2056 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002057 ::android::sp<::android::IBinder> binder(
2058 sm->waitForService(::android::String16("package_native")));
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002059 if (binder == nullptr) {
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002060 GTEST_LOG_(ERROR) << "waitForService package_native failed";
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002061 return false;
2062 }
2063 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2064 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2065 if (packageMgr == nullptr) {
2066 GTEST_LOG_(ERROR) << "Cannot find package manager";
2067 return false;
2068 }
2069 bool hasFeature = false;
2070 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2071 if (!status.isOk()) {
2072 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2073 return false;
2074 }
2075 return hasFeature;
2076}
2077
Selene Huang31ab4042020-04-29 04:22:39 -07002078} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002079
Janis Danisevskis24c04702020-12-16 18:28:39 -08002080} // namespace aidl::android::hardware::security::keymint