blob: 5e27bd0e5be2721eb5b5349520aea93e9d7ec8ea [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
Rajesh Nyamagoude98263e2023-02-09 20:36:33 +0000111void check_crl_distribution_points_extension_not_present(X509* certificate) {
112 ASN1_OBJECT_Ptr crl_dp_oid(OBJ_txt2obj(kCrlDPOid, 1 /* dotted string format */));
113 ASSERT_TRUE(crl_dp_oid.get());
114
115 int location =
116 X509_get_ext_by_OBJ(certificate, crl_dp_oid.get(), -1 /* search from beginning */);
117 ASSERT_EQ(location, -1);
118}
119
David Drysdale7dff4fc2021-12-10 10:10:52 +0000120void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
121 // Version numbers in attestation extensions should be a multiple of 100.
122 EXPECT_EQ(attestation_version % 100, 0);
123
124 // The multiplier should never be higher than the AIDL version, but can be less
125 // (for example, if the implementation is from an earlier version but the HAL service
126 // uses the default libraries and so reports the current AIDL version).
127 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
128}
129
Shawn Willden7c130392020-12-21 09:58:22 -0700130bool avb_verification_enabled() {
131 char value[PROPERTY_VALUE_MAX];
132 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
133}
134
135char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
136 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
137
138// Attestations don't contain everything in key authorization lists, so we need to filter the key
139// lists to produce the lists that we expect to match the attestations.
140auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100141 Tag::CREATION_DATETIME,
142 Tag::HARDWARE_TYPE,
143 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700144};
145
146AuthorizationSet filtered_tags(const AuthorizationSet& set) {
147 AuthorizationSet filtered;
148 std::remove_copy_if(
149 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
150 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
151 kTagsToFilter.end();
152 });
153 return filtered;
154}
155
David Drysdale300b5552021-05-20 12:05:26 +0100156// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
157void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
158 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
159 [](const auto& entry) {
160 return entry.securityLevel == SecurityLevel::KEYSTORE;
161 }),
162 characteristics->end());
163}
164
Shawn Willden7c130392020-12-21 09:58:22 -0700165string x509NameToStr(X509_NAME* name) {
166 char* s = X509_NAME_oneline(name, nullptr, 0);
167 string retval(s);
168 OPENSSL_free(s);
169 return retval;
170}
171
Shawn Willden7f424372021-01-10 18:06:50 -0700172} // namespace
173
Shawn Willden7c130392020-12-21 09:58:22 -0700174bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
175bool KeyMintAidlTestBase::dump_Attestations = false;
David Drysdale9f5c0c52022-11-03 15:10:16 +0000176std::string KeyMintAidlTestBase::keyblob_dir;
Shawn Willden7c130392020-12-21 09:58:22 -0700177
David Drysdale37af4b32021-05-14 16:46:59 +0100178uint32_t KeyMintAidlTestBase::boot_patch_level(
179 const vector<KeyCharacteristics>& key_characteristics) {
180 // The boot patchlevel is not available as a property, but should be present
181 // in the key characteristics of any created key.
182 AuthorizationSet allAuths;
183 for (auto& entry : key_characteristics) {
184 allAuths.push_back(AuthorizationSet(entry.authorizations));
185 }
186 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
187 if (patchlevel.has_value()) {
188 return patchlevel.value();
189 } else {
190 // No boot patchlevel is available. Return a value that won't match anything
191 // and so will trigger test failures.
192 return kInvalidPatchlevel;
193 }
194}
195
196uint32_t KeyMintAidlTestBase::boot_patch_level() {
197 return boot_patch_level(key_characteristics_);
198}
199
Prashant Patil88ad1892022-03-15 16:31:02 +0000200/**
201 * An API to determine device IDs attestation is required or not,
202 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
203 */
204bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700205 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= __ANDROID_API_T__;
Prashant Patil88ad1892022-03-15 16:31:02 +0000206}
207
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000208/**
209 * An API to determine second IMEI ID attestation is required or not,
210 * which is supported for KeyMint version 3 or first_api_level greater than 33.
211 */
212bool KeyMintAidlTestBase::isSecondImeiIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700213 return AidlVersion() >= 3 && property_get_int32("ro.vendor.api_level", 0) > __ANDROID_API_T__;
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000214}
215
David Drysdale42fe1892021-10-14 14:43:46 +0100216bool KeyMintAidlTestBase::Curve25519Supported() {
217 // Strongbox never supports curve 25519.
218 if (SecLevel() == SecurityLevel::STRONGBOX) {
219 return false;
220 }
221
222 // Curve 25519 was included in version 2 of the KeyMint interface.
223 int32_t version = 0;
224 auto status = keymint_->getInterfaceVersion(&version);
225 if (!status.isOk()) {
226 ADD_FAILURE() << "Failed to determine interface version";
227 }
228 return version >= 2;
229}
230
Janis Danisevskis24c04702020-12-16 18:28:39 -0800231ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700232 if (result.isOk()) return ErrorCode::OK;
233
Janis Danisevskis24c04702020-12-16 18:28:39 -0800234 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
235 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700236 }
237
238 return ErrorCode::UNKNOWN_ERROR;
239}
240
Janis Danisevskis24c04702020-12-16 18:28:39 -0800241void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700242 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800243 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700244
245 KeyMintHardwareInfo info;
246 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
247
248 securityLevel_ = info.securityLevel;
249 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
250 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100251 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700252
253 os_version_ = getOsVersion();
254 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100255 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700256}
257
David Drysdale7dff4fc2021-12-10 10:10:52 +0000258int32_t KeyMintAidlTestBase::AidlVersion() {
259 int32_t version = 0;
260 auto status = keymint_->getInterfaceVersion(&version);
261 if (!status.isOk()) {
262 ADD_FAILURE() << "Failed to determine interface version";
263 }
264 return version;
265}
266
Selene Huang31ab4042020-04-29 04:22:39 -0700267void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800268 if (AServiceManager_isDeclared(GetParam().c_str())) {
269 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
270 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
271 } else {
272 InitializeKeyMint(nullptr);
273 }
Selene Huang31ab4042020-04-29 04:22:39 -0700274}
275
276ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700277 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700278 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700279 vector<KeyCharacteristics>* key_characteristics,
280 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700281 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
282 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700283 << "Previous characteristics not deleted before generating key. Test bug.";
284
Shawn Willden7f424372021-01-10 18:06:50 -0700285 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700286 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700287 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700288 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
289 creationResult.keyCharacteristics);
290 EXPECT_GT(creationResult.keyBlob.size(), 0);
291 *key_blob = std::move(creationResult.keyBlob);
292 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700293 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700294
295 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
296 EXPECT_TRUE(algorithm);
297 if (algorithm &&
298 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700299 EXPECT_GE(cert_chain->size(), 1);
300 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
301 if (attest_key) {
302 EXPECT_EQ(cert_chain->size(), 1);
303 } else {
304 EXPECT_GT(cert_chain->size(), 1);
305 }
306 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700307 } else {
308 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700309 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700310 }
Selene Huang31ab4042020-04-29 04:22:39 -0700311 }
312
313 return GetReturnErrorCode(result);
314}
315
Shawn Willden7c130392020-12-21 09:58:22 -0700316ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
317 const optional<AttestationKey>& attest_key) {
318 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700319}
320
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000321ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
322 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
323 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
324 vector<Certificate>* cert_chain) {
325 AttestationKey attest_key;
326 vector<Certificate> attest_cert_chain;
327 vector<KeyCharacteristics> attest_key_characteristics;
328 // Generate a key with self signed attestation.
329 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
330 &attest_key_characteristics, &attest_cert_chain);
331 if (error != ErrorCode::OK) {
332 return error;
333 }
334
335 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
336 // Generate a key, by passing the above self signed attestation key as attest key.
337 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
338 if (error == ErrorCode::OK) {
339 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
340 cert_chain->push_back(attest_cert_chain[0]);
341 }
342 return error;
343}
344
Selene Huang31ab4042020-04-29 04:22:39 -0700345ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
346 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700347 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700348 Status result;
349
Shawn Willden7f424372021-01-10 18:06:50 -0700350 cert_chain_.clear();
351 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700352 key_blob->clear();
353
Shawn Willden7f424372021-01-10 18:06:50 -0700354 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700355 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700356 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700357 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700358
359 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700360 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
361 creationResult.keyCharacteristics);
362 EXPECT_GT(creationResult.keyBlob.size(), 0);
363
364 *key_blob = std::move(creationResult.keyBlob);
365 *key_characteristics = std::move(creationResult.keyCharacteristics);
366 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700367
368 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
369 EXPECT_TRUE(algorithm);
370 if (algorithm &&
371 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
372 EXPECT_GE(cert_chain_.size(), 1);
373 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
374 } else {
375 // For symmetric keys there should be no certificates.
376 EXPECT_EQ(cert_chain_.size(), 0);
377 }
Selene Huang31ab4042020-04-29 04:22:39 -0700378 }
379
380 return GetReturnErrorCode(result);
381}
382
383ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
384 const string& key_material) {
385 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
386}
387
388ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
389 const AuthorizationSet& wrapping_key_desc,
390 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100391 const AuthorizationSet& unwrapping_params,
392 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700393 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
394
Shawn Willden7f424372021-01-10 18:06:50 -0700395 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700396
Shawn Willden7f424372021-01-10 18:06:50 -0700397 KeyCreationResult creationResult;
398 Status result = keymint_->importWrappedKey(
399 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
400 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100401 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700402
403 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700404 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
405 creationResult.keyCharacteristics);
406 EXPECT_GT(creationResult.keyBlob.size(), 0);
407
408 key_blob_ = std::move(creationResult.keyBlob);
409 key_characteristics_ = std::move(creationResult.keyCharacteristics);
410 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700411
412 AuthorizationSet allAuths;
413 for (auto& entry : key_characteristics_) {
414 allAuths.push_back(AuthorizationSet(entry.authorizations));
415 }
416 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
417 EXPECT_TRUE(algorithm);
418 if (algorithm &&
419 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
420 EXPECT_GE(cert_chain_.size(), 1);
421 } else {
422 // For symmetric keys there should be no certificates.
423 EXPECT_EQ(cert_chain_.size(), 0);
424 }
Selene Huang31ab4042020-04-29 04:22:39 -0700425 }
426
427 return GetReturnErrorCode(result);
428}
429
David Drysdale300b5552021-05-20 12:05:26 +0100430ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
431 const vector<uint8_t>& app_id,
432 const vector<uint8_t>& app_data,
433 vector<KeyCharacteristics>* key_characteristics) {
434 Status result =
435 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
436 return GetReturnErrorCode(result);
437}
438
439ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
440 vector<KeyCharacteristics>* key_characteristics) {
441 vector<uint8_t> empty_app_id, empty_app_data;
442 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
443}
444
445void KeyMintAidlTestBase::CheckCharacteristics(
446 const vector<uint8_t>& key_blob,
447 const vector<KeyCharacteristics>& generate_characteristics) {
448 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
449 // generateKey() should be excluded, as KeyMint will have no record of them.
450 // This applies to CREATION_DATETIME in particular.
451 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
452 strip_keystore_tags(&expected_characteristics);
453
454 vector<KeyCharacteristics> retrieved;
455 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
456 EXPECT_EQ(expected_characteristics, retrieved);
457}
458
459void KeyMintAidlTestBase::CheckAppIdCharacteristics(
460 const vector<uint8_t>& key_blob, std::string_view app_id_string,
461 std::string_view app_data_string,
462 const vector<KeyCharacteristics>& generate_characteristics) {
463 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
464 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
465 strip_keystore_tags(&expected_characteristics);
466
467 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
468 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
469 vector<KeyCharacteristics> retrieved;
470 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
471 EXPECT_EQ(expected_characteristics, retrieved);
472
473 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
474 vector<uint8_t> empty;
475 vector<KeyCharacteristics> not_retrieved;
476 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
477 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
478 EXPECT_EQ(not_retrieved.size(), 0);
479
480 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
481 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
482 EXPECT_EQ(not_retrieved.size(), 0);
483
484 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
485 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
486 EXPECT_EQ(not_retrieved.size(), 0);
487}
488
Selene Huang31ab4042020-04-29 04:22:39 -0700489ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
490 Status result = keymint_->deleteKey(*key_blob);
491 if (!keep_key_blob) {
492 *key_blob = vector<uint8_t>();
493 }
494
Janis Danisevskis24c04702020-12-16 18:28:39 -0800495 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700496 return GetReturnErrorCode(result);
497}
498
499ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
500 return DeleteKey(&key_blob_, keep_key_blob);
501}
502
503ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
504 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800505 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700506 return GetReturnErrorCode(result);
507}
508
David Drysdaled2cc8c22021-04-15 13:29:45 +0100509ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
510 Status result = keymint_->destroyAttestationIds();
511 return GetReturnErrorCode(result);
512}
513
Selene Huang31ab4042020-04-29 04:22:39 -0700514void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
515 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
516 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
517}
518
519void KeyMintAidlTestBase::CheckedDeleteKey() {
520 CheckedDeleteKey(&key_blob_);
521}
522
523ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
524 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800525 AuthorizationSet* out_params,
526 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700527 SCOPED_TRACE("Begin");
528 Status result;
529 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100530 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700531
532 if (result.isOk()) {
533 *out_params = out.params;
534 challenge_ = out.challenge;
535 op = out.operation;
536 }
537
538 return GetReturnErrorCode(result);
539}
540
541ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
542 const AuthorizationSet& in_params,
David Drysdale28fa9312023-02-01 14:53:01 +0000543 AuthorizationSet* out_params,
544 std::optional<HardwareAuthToken> hat) {
Selene Huang31ab4042020-04-29 04:22:39 -0700545 SCOPED_TRACE("Begin");
546 Status result;
547 BeginResult out;
548
David Drysdale28fa9312023-02-01 14:53:01 +0000549 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), hat, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700550
551 if (result.isOk()) {
552 *out_params = out.params;
553 challenge_ = out.challenge;
554 op_ = out.operation;
555 }
556
557 return GetReturnErrorCode(result);
558}
559
560ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
561 AuthorizationSet* out_params) {
562 SCOPED_TRACE("Begin");
563 EXPECT_EQ(nullptr, op_);
564 return Begin(purpose, key_blob_, in_params, out_params);
565}
566
567ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
568 SCOPED_TRACE("Begin");
569 AuthorizationSet out_params;
570 ErrorCode result = Begin(purpose, in_params, &out_params);
571 EXPECT_TRUE(out_params.empty());
572 return result;
573}
574
Shawn Willden92d79c02021-02-19 07:31:55 -0700575ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
576 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
577 {} /* hardwareAuthToken */,
578 {} /* verificationToken */));
579}
580
581ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700582 SCOPED_TRACE("Update");
583
584 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700585 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700586
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800587 EXPECT_NE(op_, nullptr);
588 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
589
Shawn Willden92d79c02021-02-19 07:31:55 -0700590 std::vector<uint8_t> o_put;
591 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700592
David Drysdalefeab5d92022-01-06 15:46:23 +0000593 if (result.isOk()) {
594 output->append(o_put.begin(), o_put.end());
595 } else {
596 // Failure always terminates the operation.
597 op_ = {};
598 }
Selene Huang31ab4042020-04-29 04:22:39 -0700599
600 return GetReturnErrorCode(result);
601}
602
David Drysdale28fa9312023-02-01 14:53:01 +0000603ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, string* output,
604 std::optional<HardwareAuthToken> hat,
605 std::optional<secureclock::TimeStampToken> time_token) {
Selene Huang31ab4042020-04-29 04:22:39 -0700606 SCOPED_TRACE("Finish");
607 Status result;
608
609 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700610 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700611
612 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700613 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
David Drysdale28fa9312023-02-01 14:53:01 +0000614 vector<uint8_t>(signature.begin(), signature.end()), hat, time_token,
615 {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700616
Shawn Willden92d79c02021-02-19 07:31:55 -0700617 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Shawn Willden92d79c02021-02-19 07:31:55 -0700619 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700620 return GetReturnErrorCode(result);
621}
622
Janis Danisevskis24c04702020-12-16 18:28:39 -0800623ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700624 SCOPED_TRACE("Abort");
625
626 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700627 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700628
629 Status retval = op->abort();
630 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800631 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700632}
633
634ErrorCode KeyMintAidlTestBase::Abort() {
635 SCOPED_TRACE("Abort");
636
637 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700638 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700639
640 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800641 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700642}
643
644void KeyMintAidlTestBase::AbortIfNeeded() {
645 SCOPED_TRACE("AbortIfNeeded");
646 if (op_) {
647 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800648 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700649 }
650}
651
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000652auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
653 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700654 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000655 AuthorizationSet begin_out_params;
656 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700657 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000658
659 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700660 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000661}
662
Selene Huang31ab4042020-04-29 04:22:39 -0700663string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
664 const string& message, const AuthorizationSet& in_params,
665 AuthorizationSet* out_params) {
666 SCOPED_TRACE("ProcessMessage");
667 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700668 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700669 EXPECT_EQ(ErrorCode::OK, result);
670 if (result != ErrorCode::OK) {
671 return "";
672 }
673
674 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700675 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700676 return output;
677}
678
679string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
680 const AuthorizationSet& params) {
681 SCOPED_TRACE("SignMessage");
682 AuthorizationSet out_params;
683 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
684 EXPECT_TRUE(out_params.empty());
685 return signature;
686}
687
688string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
689 SCOPED_TRACE("SignMessage");
690 return SignMessage(key_blob_, message, params);
691}
692
693string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
694 SCOPED_TRACE("MacMessage");
695 return SignMessage(
696 key_blob_, message,
697 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
698}
699
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530700void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
701 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000702 auto builder = AuthorizationSetBuilder()
703 .Authorization(TAG_NO_AUTH_REQUIRED)
704 .AesEncryptionKey(128)
705 .BlockMode(block_mode)
706 .Padding(PaddingMode::NONE);
707 if (block_mode == BlockMode::GCM) {
708 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
709 }
710 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530711
712 for (int increment = 1; increment <= message_size; ++increment) {
713 string message(message_size, 'a');
714 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
715 if (block_mode == BlockMode::GCM) {
716 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
717 }
718
719 AuthorizationSet output_params;
720 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
721
722 string ciphertext;
723 string to_send;
724 for (size_t i = 0; i < message.size(); i += increment) {
725 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
726 }
727 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
728 << "Error sending " << to_send << " with block mode " << block_mode;
729
730 switch (block_mode) {
731 case BlockMode::GCM:
732 EXPECT_EQ(message.size() + 16, ciphertext.size());
733 break;
734 case BlockMode::CTR:
735 EXPECT_EQ(message.size(), ciphertext.size());
736 break;
737 case BlockMode::CBC:
738 case BlockMode::ECB:
739 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
740 break;
741 }
742
743 auto iv = output_params.GetTagValue(TAG_NONCE);
744 switch (block_mode) {
745 case BlockMode::CBC:
746 case BlockMode::GCM:
747 case BlockMode::CTR:
748 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
749 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
750 params.push_back(TAG_NONCE, iv->get());
751 break;
752
753 case BlockMode::ECB:
754 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
755 break;
756 }
757
758 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
759 << "Decrypt begin() failed for block mode " << block_mode;
760
761 string plaintext;
762 for (size_t i = 0; i < ciphertext.size(); i += increment) {
763 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
764 }
765 ErrorCode error = Finish(to_send, &plaintext);
766 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
767 << " and increment " << increment;
768 if (error == ErrorCode::OK) {
769 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
770 << " and increment " << increment;
771 }
772 }
773}
774
Prashant Patildd5f7f02022-07-06 18:58:07 +0000775void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
776 PaddingMode padding_mode, const string& iv,
777 const string& plaintext,
778 const string& exp_cipher_text) {
779 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
780 auto auth_set = AuthorizationSetBuilder()
781 .Authorization(TAG_NO_AUTH_REQUIRED)
782 .AesEncryptionKey(key.size() * 8)
783 .BlockMode(block_mode)
784 .Padding(padding_mode);
785 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
786 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
787 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
788
789 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
790 exp_cipher_text);
791}
792
793void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
794 PaddingMode padding_mode, const string& iv,
795 const string& plaintext,
796 const string& exp_cipher_text) {
797 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
798 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
799 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
800 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
801 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
802
803 AuthorizationSet output_params;
804 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
805
806 string actual_ciphertext;
807 if (is_stream_cipher) {
808 // Assert that a 1 byte of output is produced for 1 byte of input.
809 // Every input byte produces an output byte.
810 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
811 string ciphertext;
812 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
813 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
814 // we relax this API restriction for them.
815 if (SecLevel() != SecurityLevel::STRONGBOX) {
816 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
817 }
818 actual_ciphertext.append(ciphertext);
819 }
820 string ciphertext;
821 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
822 if (SecLevel() != SecurityLevel::STRONGBOX) {
823 string expected_final_output;
824 if (is_authenticated_cipher) {
825 expected_final_output = exp_cipher_text.substr(plaintext.size());
826 }
827 EXPECT_EQ(expected_final_output, ciphertext);
828 }
829 actual_ciphertext.append(ciphertext);
830 } else {
831 // Assert that a block of output is produced once a full block of input is provided.
832 // Every input block produces an output block.
833 bool compare_output = true;
834 string additional_information;
835 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
836 if (SecLevel() == SecurityLevel::STRONGBOX) {
837 // This is known to be broken on older vendor implementations.
Shawn Willden1a545db2023-02-22 14:32:33 -0700838 if (vendor_api_level < __ANDROID_API_T__) {
Prashant Patildd5f7f02022-07-06 18:58:07 +0000839 compare_output = false;
840 } else {
841 additional_information = " (b/194134359) ";
842 }
843 }
844 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
845 string ciphertext;
846 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
847 if (compare_output) {
848 if ((plaintext_index % block_size) == block_size - 1) {
849 // Update is expected to have output a new block
850 EXPECT_EQ(block_size, ciphertext.size())
851 << "plaintext index: " << plaintext_index << additional_information;
852 } else {
853 // Update is expected to have produced no output
854 EXPECT_EQ(0, ciphertext.size())
855 << "plaintext index: " << plaintext_index << additional_information;
856 }
857 }
858 actual_ciphertext.append(ciphertext);
859 }
860 string ciphertext;
861 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
862 actual_ciphertext.append(ciphertext);
863 }
864 // Regardless of how the completed ciphertext got accumulated, it should match the expected
865 // ciphertext.
866 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
867}
868
Selene Huang31ab4042020-04-29 04:22:39 -0700869void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
870 Digest digest, const string& expected_mac) {
871 SCOPED_TRACE("CheckHmacTestVector");
872 ASSERT_EQ(ErrorCode::OK,
873 ImportKey(AuthorizationSetBuilder()
874 .Authorization(TAG_NO_AUTH_REQUIRED)
875 .HmacKey(key.size() * 8)
876 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
877 .Digest(digest),
878 KeyFormat::RAW, key));
879 string signature = MacMessage(message, digest, expected_mac.size() * 8);
880 EXPECT_EQ(expected_mac, signature)
881 << "Test vector didn't match for key of size " << key.size() << " message of size "
882 << message.size() << " and digest " << digest;
883 CheckedDeleteKey();
884}
885
886void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
887 const string& message,
888 const string& expected_ciphertext) {
889 SCOPED_TRACE("CheckAesCtrTestVector");
890 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
891 .Authorization(TAG_NO_AUTH_REQUIRED)
892 .AesEncryptionKey(key.size() * 8)
893 .BlockMode(BlockMode::CTR)
894 .Authorization(TAG_CALLER_NONCE)
895 .Padding(PaddingMode::NONE),
896 KeyFormat::RAW, key));
897
898 auto params = AuthorizationSetBuilder()
899 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
900 .BlockMode(BlockMode::CTR)
901 .Padding(PaddingMode::NONE);
902 AuthorizationSet out_params;
903 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
904 EXPECT_EQ(expected_ciphertext, ciphertext);
905}
906
907void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
908 PaddingMode padding_mode, const string& key,
909 const string& iv, const string& input,
910 const string& expected_output) {
911 auto authset = AuthorizationSetBuilder()
912 .TripleDesEncryptionKey(key.size() * 7)
913 .BlockMode(block_mode)
914 .Authorization(TAG_NO_AUTH_REQUIRED)
915 .Padding(padding_mode);
916 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
917 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
918 ASSERT_GT(key_blob_.size(), 0U);
919
920 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
921 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
922 AuthorizationSet output_params;
923 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
924 EXPECT_EQ(expected_output, output);
925}
926
927void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
928 const string& signature, const AuthorizationSet& params) {
929 SCOPED_TRACE("VerifyMessage");
930 AuthorizationSet begin_out_params;
931 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
932
933 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700934 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700935 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700936 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700937}
938
939void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
940 const AuthorizationSet& params) {
941 SCOPED_TRACE("VerifyMessage");
942 VerifyMessage(key_blob_, message, signature, params);
943}
944
David Drysdaledf8f52e2021-05-06 08:10:58 +0100945void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
946 const AuthorizationSet& params) {
947 SCOPED_TRACE("LocalVerifyMessage");
948
David Drysdaledf8f52e2021-05-06 08:10:58 +0100949 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000950 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
951}
952
953void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
954 const string& signature,
955 const AuthorizationSet& params) {
956 // Retrieve the public key from the leaf certificate.
957 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100958 ASSERT_TRUE(key_cert.get());
959 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
960 ASSERT_TRUE(pub_key.get());
961
962 Digest digest = params.GetTagValue(TAG_DIGEST).value();
963 PaddingMode padding = PaddingMode::NONE;
964 auto tag = params.GetTagValue(TAG_PADDING);
965 if (tag.has_value()) {
966 padding = tag.value();
967 }
968
969 if (digest == Digest::NONE) {
970 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100971 case EVP_PKEY_ED25519: {
972 ASSERT_EQ(64, signature.size());
973 uint8_t pub_keydata[32];
974 size_t pub_len = sizeof(pub_keydata);
975 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
976 ASSERT_EQ(sizeof(pub_keydata), pub_len);
977 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
978 message.size(),
979 reinterpret_cast<const uint8_t*>(signature.data()),
980 pub_keydata));
981 break;
982 }
983
David Drysdaledf8f52e2021-05-06 08:10:58 +0100984 case EVP_PKEY_EC: {
985 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
986 size_t data_size = std::min(data.size(), message.size());
987 memcpy(data.data(), message.data(), data_size);
988 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
989 ASSERT_TRUE(ecdsa.get());
990 ASSERT_EQ(1,
991 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
992 reinterpret_cast<const uint8_t*>(signature.data()),
993 signature.size(), ecdsa.get()));
994 break;
995 }
996 case EVP_PKEY_RSA: {
997 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
998 size_t data_size = std::min(data.size(), message.size());
999 memcpy(data.data(), message.data(), data_size);
1000
1001 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1002 ASSERT_TRUE(rsa.get());
1003
1004 size_t key_len = RSA_size(rsa.get());
1005 int openssl_padding = RSA_NO_PADDING;
1006 switch (padding) {
1007 case PaddingMode::NONE:
1008 ASSERT_TRUE(data_size <= key_len);
1009 ASSERT_EQ(key_len, signature.size());
1010 openssl_padding = RSA_NO_PADDING;
1011 break;
1012 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1013 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1014 key_len);
1015 openssl_padding = RSA_PKCS1_PADDING;
1016 break;
1017 default:
1018 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1019 }
1020
1021 vector<uint8_t> decrypted_data(key_len);
1022 int bytes_decrypted = RSA_public_decrypt(
1023 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1024 decrypted_data.data(), rsa.get(), openssl_padding);
1025 ASSERT_GE(bytes_decrypted, 0);
1026
1027 const uint8_t* compare_pos = decrypted_data.data();
1028 size_t bytes_to_compare = bytes_decrypted;
1029 uint8_t zero_check_result = 0;
1030 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1031 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1032 // during verification we should have zeros on the left of the decrypted data.
1033 // Do a constant-time check.
1034 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1035 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1036 ASSERT_EQ(0, zero_check_result);
1037 bytes_to_compare = data_size;
1038 }
1039 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1040 break;
1041 }
1042 default:
1043 ADD_FAILURE() << "Unknown public key type";
1044 }
1045 } else {
1046 EVP_MD_CTX digest_ctx;
1047 EVP_MD_CTX_init(&digest_ctx);
1048 EVP_PKEY_CTX* pkey_ctx;
1049 const EVP_MD* md = openssl_digest(digest);
1050 ASSERT_NE(md, nullptr);
1051 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1052
1053 if (padding == PaddingMode::RSA_PSS) {
1054 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1055 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001056 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001057 }
1058
1059 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1060 reinterpret_cast<const uint8_t*>(message.data()),
1061 message.size()));
1062 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1063 reinterpret_cast<const uint8_t*>(signature.data()),
1064 signature.size()));
1065 EVP_MD_CTX_cleanup(&digest_ctx);
1066 }
1067}
1068
David Drysdale59cae642021-05-12 13:52:03 +01001069string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1070 const AuthorizationSet& params) {
1071 SCOPED_TRACE("LocalRsaEncryptMessage");
1072
1073 // Retrieve the public key from the leaf certificate.
1074 if (cert_chain_.empty()) {
1075 ADD_FAILURE() << "No public key available";
1076 return "Failure";
1077 }
1078 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001079 if (key_cert.get() == nullptr) {
1080 ADD_FAILURE() << "Failed to parse cert";
1081 return "Failure";
1082 }
David Drysdale59cae642021-05-12 13:52:03 +01001083 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001084 if (pub_key.get() == nullptr) {
1085 ADD_FAILURE() << "Failed to retrieve public key";
1086 return "Failure";
1087 }
David Drysdale59cae642021-05-12 13:52:03 +01001088 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001089 if (rsa.get() == nullptr) {
1090 ADD_FAILURE() << "Failed to retrieve RSA public key";
1091 return "Failure";
1092 }
David Drysdale59cae642021-05-12 13:52:03 +01001093
1094 // Retrieve relevant tags.
1095 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001096 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001097 PaddingMode padding = PaddingMode::NONE;
1098
1099 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1100 if (digest_tag.has_value()) digest = digest_tag.value();
1101 auto pad_tag = params.GetTagValue(TAG_PADDING);
1102 if (pad_tag.has_value()) padding = pad_tag.value();
1103 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1104 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1105
1106 const EVP_MD* md = openssl_digest(digest);
1107 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1108
1109 // Set up encryption context.
1110 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1111 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1112 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1113 return "Failure";
1114 }
1115
1116 int rc = -1;
1117 switch (padding) {
1118 case PaddingMode::NONE:
1119 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1120 break;
1121 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1122 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1123 break;
1124 case PaddingMode::RSA_OAEP:
1125 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1126 break;
1127 default:
1128 break;
1129 }
1130 if (rc <= 0) {
1131 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1132 return "Failure";
1133 }
1134 if (padding == PaddingMode::RSA_OAEP) {
1135 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1136 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1137 return "Failure";
1138 }
1139 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1140 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1141 return "Failure";
1142 }
1143 }
1144
1145 // Determine output size.
1146 size_t outlen;
1147 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1148 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1149 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1150 return "Failure";
1151 }
1152
1153 // Left-zero-pad the input if necessary.
1154 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1155 size_t to_encrypt_len = message.size();
1156
1157 std::unique_ptr<string> zero_padded_message;
1158 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1159 zero_padded_message.reset(new string(outlen, '\0'));
1160 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1161 message.size());
1162 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1163 to_encrypt_len = outlen;
1164 }
1165
1166 // Do the encryption.
1167 string output(outlen, '\0');
1168 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1169 to_encrypt_len) <= 0) {
1170 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1171 return "Failure";
1172 }
1173 return output;
1174}
1175
Selene Huang31ab4042020-04-29 04:22:39 -07001176string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1177 const AuthorizationSet& in_params,
1178 AuthorizationSet* out_params) {
1179 SCOPED_TRACE("EncryptMessage");
1180 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1181}
1182
1183string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1184 AuthorizationSet* out_params) {
1185 SCOPED_TRACE("EncryptMessage");
1186 return EncryptMessage(key_blob_, message, params, out_params);
1187}
1188
1189string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1190 SCOPED_TRACE("EncryptMessage");
1191 AuthorizationSet out_params;
1192 string ciphertext = EncryptMessage(message, params, &out_params);
1193 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1194 return ciphertext;
1195}
1196
1197string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1198 PaddingMode padding) {
1199 SCOPED_TRACE("EncryptMessage");
1200 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1201 AuthorizationSet out_params;
1202 string ciphertext = EncryptMessage(message, params, &out_params);
1203 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1204 return ciphertext;
1205}
1206
1207string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1208 PaddingMode padding, vector<uint8_t>* iv_out) {
1209 SCOPED_TRACE("EncryptMessage");
1210 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1211 AuthorizationSet out_params;
1212 string ciphertext = EncryptMessage(message, params, &out_params);
1213 EXPECT_EQ(1U, out_params.size());
1214 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001215 EXPECT_TRUE(ivVal);
1216 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001217 return ciphertext;
1218}
1219
1220string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1221 PaddingMode padding, const vector<uint8_t>& iv_in) {
1222 SCOPED_TRACE("EncryptMessage");
1223 auto params = AuthorizationSetBuilder()
1224 .BlockMode(block_mode)
1225 .Padding(padding)
1226 .Authorization(TAG_NONCE, iv_in);
1227 AuthorizationSet out_params;
1228 string ciphertext = EncryptMessage(message, params, &out_params);
1229 return ciphertext;
1230}
1231
1232string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1233 PaddingMode padding, uint8_t mac_length_bits,
1234 const vector<uint8_t>& iv_in) {
1235 SCOPED_TRACE("EncryptMessage");
1236 auto params = AuthorizationSetBuilder()
1237 .BlockMode(block_mode)
1238 .Padding(padding)
1239 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1240 .Authorization(TAG_NONCE, iv_in);
1241 AuthorizationSet out_params;
1242 string ciphertext = EncryptMessage(message, params, &out_params);
1243 return ciphertext;
1244}
1245
David Drysdaled2cc8c22021-04-15 13:29:45 +01001246string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1247 PaddingMode padding, uint8_t mac_length_bits) {
1248 SCOPED_TRACE("EncryptMessage");
1249 auto params = AuthorizationSetBuilder()
1250 .BlockMode(block_mode)
1251 .Padding(padding)
1252 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1253 AuthorizationSet out_params;
1254 string ciphertext = EncryptMessage(message, params, &out_params);
1255 return ciphertext;
1256}
1257
Selene Huang31ab4042020-04-29 04:22:39 -07001258string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1259 const string& ciphertext,
1260 const AuthorizationSet& params) {
1261 SCOPED_TRACE("DecryptMessage");
1262 AuthorizationSet out_params;
1263 string plaintext =
1264 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1265 EXPECT_TRUE(out_params.empty());
1266 return plaintext;
1267}
1268
1269string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1270 const AuthorizationSet& params) {
1271 SCOPED_TRACE("DecryptMessage");
1272 return DecryptMessage(key_blob_, ciphertext, params);
1273}
1274
1275string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1276 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1277 SCOPED_TRACE("DecryptMessage");
1278 auto params = AuthorizationSetBuilder()
1279 .BlockMode(block_mode)
1280 .Padding(padding_mode)
1281 .Authorization(TAG_NONCE, iv);
1282 return DecryptMessage(key_blob_, ciphertext, params);
1283}
1284
1285std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1286 const vector<uint8_t>& key_blob) {
1287 std::pair<ErrorCode, vector<uint8_t>> retval;
1288 vector<uint8_t> outKeyBlob;
1289 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1290 ErrorCode errorcode = GetReturnErrorCode(result);
1291 retval = std::tie(errorcode, outKeyBlob);
1292
1293 return retval;
1294}
Seth Moorea12ac742023-03-03 13:40:30 -08001295
1296bool KeyMintAidlTestBase::IsRkpSupportRequired() const {
1297 if (get_vsr_api_level() >= __ANDROID_API_T__) {
1298 return true;
1299 }
1300
1301 if (get_vsr_api_level() >= __ANDROID_API_S__) {
1302 return SecLevel() != SecurityLevel::STRONGBOX;
1303 }
1304
1305 return false;
1306}
1307
Selene Huang31ab4042020-04-29 04:22:39 -07001308vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1309 switch (algorithm) {
1310 case Algorithm::RSA:
1311 switch (SecLevel()) {
1312 case SecurityLevel::SOFTWARE:
1313 case SecurityLevel::TRUSTED_ENVIRONMENT:
1314 return {2048, 3072, 4096};
1315 case SecurityLevel::STRONGBOX:
1316 return {2048};
1317 default:
1318 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1319 break;
1320 }
1321 break;
1322 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001323 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001324 break;
1325 case Algorithm::AES:
1326 return {128, 256};
1327 case Algorithm::TRIPLE_DES:
1328 return {168};
1329 case Algorithm::HMAC: {
1330 vector<uint32_t> retval((512 - 64) / 8 + 1);
1331 uint32_t size = 64 - 8;
1332 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1333 return retval;
1334 }
1335 default:
1336 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1337 return {};
1338 }
1339 ADD_FAILURE() << "Should be impossible to get here";
1340 return {};
1341}
1342
1343vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1344 if (SecLevel() == SecurityLevel::STRONGBOX) {
1345 switch (algorithm) {
1346 case Algorithm::RSA:
1347 return {3072, 4096};
1348 case Algorithm::EC:
1349 return {224, 384, 521};
1350 case Algorithm::AES:
1351 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001352 case Algorithm::TRIPLE_DES:
1353 return {56};
1354 default:
1355 return {};
1356 }
1357 } else {
1358 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001359 case Algorithm::AES:
1360 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001361 case Algorithm::TRIPLE_DES:
1362 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001363 default:
1364 return {};
1365 }
1366 }
1367 return {};
1368}
1369
David Drysdale7de9feb2021-03-05 14:56:19 +00001370vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1371 switch (algorithm) {
1372 case Algorithm::AES:
1373 return {
1374 BlockMode::CBC,
1375 BlockMode::CTR,
1376 BlockMode::ECB,
1377 BlockMode::GCM,
1378 };
1379 case Algorithm::TRIPLE_DES:
1380 return {
1381 BlockMode::CBC,
1382 BlockMode::ECB,
1383 };
1384 default:
1385 return {};
1386 }
1387}
1388
1389vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1390 BlockMode blockMode) {
1391 switch (algorithm) {
1392 case Algorithm::AES:
1393 switch (blockMode) {
1394 case BlockMode::CBC:
1395 case BlockMode::ECB:
1396 return {PaddingMode::NONE, PaddingMode::PKCS7};
1397 case BlockMode::CTR:
1398 case BlockMode::GCM:
1399 return {PaddingMode::NONE};
1400 default:
1401 return {};
1402 };
1403 case Algorithm::TRIPLE_DES:
1404 switch (blockMode) {
1405 case BlockMode::CBC:
1406 case BlockMode::ECB:
1407 return {PaddingMode::NONE, PaddingMode::PKCS7};
1408 default:
1409 return {};
1410 };
1411 default:
1412 return {};
1413 }
1414}
1415
1416vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1417 BlockMode blockMode) {
1418 switch (algorithm) {
1419 case Algorithm::AES:
1420 switch (blockMode) {
1421 case BlockMode::CTR:
1422 case BlockMode::GCM:
1423 return {PaddingMode::PKCS7};
1424 default:
1425 return {};
1426 };
1427 default:
1428 return {};
1429 }
1430}
1431
Selene Huang31ab4042020-04-29 04:22:39 -07001432vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1433 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1434 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001435 } else if (Curve25519Supported()) {
1436 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1437 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001438 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001439 return {
1440 EcCurve::P_224,
1441 EcCurve::P_256,
1442 EcCurve::P_384,
1443 EcCurve::P_521,
1444 };
Selene Huang31ab4042020-04-29 04:22:39 -07001445 }
1446}
1447
1448vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001449 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001450 // Curve 25519 is not supported, either because:
1451 // - KeyMint v1: it's an unknown enum value
1452 // - KeyMint v2+: it's not supported by StrongBox.
1453 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001454 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001455 if (Curve25519Supported()) {
1456 return {};
1457 } else {
1458 return {EcCurve::CURVE_25519};
1459 }
David Drysdaledf09e542021-06-08 15:46:11 +01001460 }
Selene Huang31ab4042020-04-29 04:22:39 -07001461}
1462
subrahmanyaman05642492022-02-05 07:10:56 +00001463vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1464 if (SecLevel() == SecurityLevel::STRONGBOX) {
1465 return {65537};
1466 } else {
1467 return {3, 65537};
1468 }
1469}
1470
Selene Huang31ab4042020-04-29 04:22:39 -07001471vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1472 switch (SecLevel()) {
1473 case SecurityLevel::SOFTWARE:
1474 case SecurityLevel::TRUSTED_ENVIRONMENT:
1475 if (withNone) {
1476 if (withMD5)
1477 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1478 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1479 Digest::SHA_2_512};
1480 else
1481 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1482 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1483 } else {
1484 if (withMD5)
1485 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1486 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1487 else
1488 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1489 Digest::SHA_2_512};
1490 }
1491 break;
1492 case SecurityLevel::STRONGBOX:
1493 if (withNone)
1494 return {Digest::NONE, Digest::SHA_2_256};
1495 else
1496 return {Digest::SHA_2_256};
1497 break;
1498 default:
1499 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1500 break;
1501 }
1502 ADD_FAILURE() << "Should be impossible to get here";
1503 return {};
1504}
1505
Shawn Willden7f424372021-01-10 18:06:50 -07001506static const vector<KeyParameter> kEmptyAuthList{};
1507
1508const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1509 const vector<KeyCharacteristics>& key_characteristics) {
1510 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1511 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1512 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1513}
1514
Qi Wubeefae42021-01-28 23:16:37 +08001515const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1516 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1517 auto found = std::find_if(
1518 key_characteristics.begin(), key_characteristics.end(),
1519 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001520 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1521}
1522
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001523ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001524 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001525 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1526 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1527 return result;
1528}
1529
1530ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001531 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001532 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1533 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1534 return result;
1535}
1536
1537ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1538 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001539 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001540 rsaKeyBlob, KeyPurpose::SIGN, message,
1541 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1542 return result;
1543}
1544
1545ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001546 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1547 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001548 return result;
1549}
1550
Selene Huang6e46f142021-04-20 19:20:11 -07001551void verify_serial(X509* cert, const uint64_t expected_serial) {
1552 BIGNUM_Ptr ser(BN_new());
1553 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1554
1555 uint64_t serial;
1556 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1557 EXPECT_EQ(serial, expected_serial);
1558}
1559
1560// Please set self_signed to true for fake certificates or self signed
1561// certificates
1562void verify_subject(const X509* cert, //
1563 const string& subject, //
1564 bool self_signed) {
1565 char* cert_issuer = //
1566 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1567
1568 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1569
1570 string expected_subject("/CN=");
1571 if (subject.empty()) {
1572 expected_subject.append("Android Keystore Key");
1573 } else {
1574 expected_subject.append(subject);
1575 }
1576
1577 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1578
1579 if (self_signed) {
1580 EXPECT_STREQ(cert_issuer, cert_subj)
1581 << "Cert issuer and subject mismatch for self signed certificate.";
1582 }
1583
1584 OPENSSL_free(cert_subj);
1585 OPENSSL_free(cert_issuer);
1586}
1587
Shawn Willden22fb9c12022-06-02 14:04:33 -06001588int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001589 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1590 if (vendor_api_level != -1) {
1591 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001592 }
Shawn Willden35db3492022-06-16 12:50:40 -06001593
1594 // Android S and older devices do not define ro.vendor.api_level
1595 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1596 if (vendor_api_level == -1) {
1597 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001598 }
Shawn Willden35db3492022-06-16 12:50:40 -06001599
1600 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1601 if (product_api_level == -1) {
1602 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1603 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001604 }
Shawn Willden35db3492022-06-16 12:50:40 -06001605
1606 // VSR API level is the minimum of vendor_api_level and product_api_level.
1607 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1608 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001609 }
Shawn Willden35db3492022-06-16 12:50:40 -06001610 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001611}
1612
David Drysdale555ba002022-05-03 18:48:57 +01001613bool is_gsi_image() {
1614 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1615 return ifs.good();
1616}
1617
Selene Huang6e46f142021-04-20 19:20:11 -07001618vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1619 BIGNUM_Ptr serial(BN_new());
1620 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1621
1622 int len = BN_num_bytes(serial.get());
1623 vector<uint8_t> serial_blob(len);
1624 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1625 return {};
1626 }
1627
David Drysdaledb0dcf52021-05-18 11:43:31 +01001628 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1629 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1630 // Top bit being set indicates a negative number in two's complement, but our input
1631 // was positive.
1632 // In either case, prepend a zero byte.
1633 serial_blob.insert(serial_blob.begin(), 0x00);
1634 }
1635
Selene Huang6e46f142021-04-20 19:20:11 -07001636 return serial_blob;
1637}
1638
1639void verify_subject_and_serial(const Certificate& certificate, //
1640 const uint64_t expected_serial, //
1641 const string& subject, bool self_signed) {
1642 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1643 ASSERT_TRUE(!!cert.get());
1644
1645 verify_serial(cert.get(), expected_serial);
1646 verify_subject(cert.get(), subject, self_signed);
1647}
1648
Shawn Willden4315e132022-03-20 12:49:46 -06001649void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1650 VerifiedBoot verified_boot_state,
1651 const vector<uint8_t>& verified_boot_hash) {
1652 char property_value[PROPERTY_VALUE_MAX] = {};
1653
1654 if (avb_verification_enabled()) {
1655 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1656 string prop_string(property_value);
1657 EXPECT_EQ(prop_string.size(), 64);
1658 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1659
1660 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1661 if (!strcmp(property_value, "unlocked")) {
1662 EXPECT_FALSE(device_locked);
1663 } else {
1664 EXPECT_TRUE(device_locked);
1665 }
1666
1667 // Check that the device is locked if not debuggable, e.g., user build
1668 // images in CTS. For VTS, debuggable images are used to allow adb root
1669 // and the device is unlocked.
1670 if (!property_get_bool("ro.debuggable", false)) {
1671 EXPECT_TRUE(device_locked);
1672 } else {
1673 EXPECT_FALSE(device_locked);
1674 }
1675 }
1676
1677 // Verified boot key should be all 0's if the boot state is not verified or self signed
1678 std::string empty_boot_key(32, '\0');
1679 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1680 verified_boot_key.size());
1681 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1682 if (!strcmp(property_value, "green")) {
1683 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1684 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1685 verified_boot_key.size()));
1686 } else if (!strcmp(property_value, "yellow")) {
1687 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1688 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1689 verified_boot_key.size()));
1690 } else if (!strcmp(property_value, "orange")) {
1691 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1692 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1693 verified_boot_key.size()));
1694 } else if (!strcmp(property_value, "red")) {
1695 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1696 } else {
1697 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1698 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1699 verified_boot_key.size()));
1700 }
1701}
1702
David Drysdale7dff4fc2021-12-10 10:10:52 +00001703bool verify_attestation_record(int32_t aidl_version, //
1704 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001705 const string& app_id, //
1706 AuthorizationSet expected_sw_enforced, //
1707 AuthorizationSet expected_hw_enforced, //
1708 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001709 const vector<uint8_t>& attestation_cert,
1710 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001711 X509_Ptr cert(parse_cert_blob(attestation_cert));
1712 EXPECT_TRUE(!!cert.get());
1713 if (!cert.get()) return false;
1714
Rajesh Nyamagoude98263e2023-02-09 20:36:33 +00001715 // Make sure CRL Distribution Points extension is not present in a certificate
1716 // containing attestation record.
1717 check_crl_distribution_points_extension_not_present(cert.get());
1718
Shawn Willden7c130392020-12-21 09:58:22 -07001719 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1720 EXPECT_TRUE(!!attest_rec);
1721 if (!attest_rec) return false;
1722
1723 AuthorizationSet att_sw_enforced;
1724 AuthorizationSet att_hw_enforced;
1725 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001726 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001727 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001728 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001729 vector<uint8_t> att_challenge;
1730 vector<uint8_t> att_unique_id;
1731 vector<uint8_t> att_app_id;
1732
1733 auto error = parse_attestation_record(attest_rec->data, //
1734 attest_rec->length, //
1735 &att_attestation_version, //
1736 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001737 &att_keymint_version, //
1738 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001739 &att_challenge, //
1740 &att_sw_enforced, //
1741 &att_hw_enforced, //
1742 &att_unique_id);
1743 EXPECT_EQ(ErrorCode::OK, error);
1744 if (error != ErrorCode::OK) return false;
1745
David Drysdale7dff4fc2021-12-10 10:10:52 +00001746 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001747 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001748
Selene Huang4f64c222021-04-13 19:54:36 -07001749 // check challenge and app id only if we expects a non-fake certificate
1750 if (challenge.length() > 0) {
1751 EXPECT_EQ(challenge.length(), att_challenge.size());
1752 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1753
1754 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1755 }
Shawn Willden7c130392020-12-21 09:58:22 -07001756
David Drysdale7dff4fc2021-12-10 10:10:52 +00001757 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001758 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001759 EXPECT_EQ(security_level, att_attestation_security_level);
1760
Tri Vob21e6df2023-02-17 14:55:43 -08001761 for (int i = 0; i < att_hw_enforced.size(); i++) {
1762 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1763 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1764 std::string date =
1765 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001766
Tri Vob21e6df2023-02-17 14:55:43 -08001767 // strptime seems to require delimiters, but the tag value will
1768 // be YYYYMMDD
1769 if (date.size() != 8) {
1770 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1771 << " with invalid format (not YYYYMMDD): " << date;
1772 return false;
Shawn Willden7c130392020-12-21 09:58:22 -07001773 }
Tri Vob21e6df2023-02-17 14:55:43 -08001774 date.insert(6, "-");
1775 date.insert(4, "-");
1776 struct tm time;
1777 strptime(date.c_str(), "%Y-%m-%d", &time);
1778
1779 // Day of the month (0-31)
1780 EXPECT_GE(time.tm_mday, 0);
1781 EXPECT_LT(time.tm_mday, 32);
1782 // Months since Jan (0-11)
1783 EXPECT_GE(time.tm_mon, 0);
1784 EXPECT_LT(time.tm_mon, 12);
1785 // Years since 1900
1786 EXPECT_GT(time.tm_year, 110);
1787 EXPECT_LT(time.tm_year, 200);
Shawn Willden7c130392020-12-21 09:58:22 -07001788 }
1789 }
1790
1791 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1792 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1793 // indicates correct encoding. No need to check if it's in both lists, since the
1794 // AuthorizationSet compare below will handle mismatches of tags.
1795 if (security_level == SecurityLevel::SOFTWARE) {
1796 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1797 } else {
1798 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1799 }
1800
Shawn Willden7c130392020-12-21 09:58:22 -07001801 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1802 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1803 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1804 att_hw_enforced.Contains(TAG_KEY_SIZE));
1805 }
1806
1807 // Test root of trust elements
1808 vector<uint8_t> verified_boot_key;
1809 VerifiedBoot verified_boot_state;
1810 bool device_locked;
1811 vector<uint8_t> verified_boot_hash;
1812 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1813 &verified_boot_state, &device_locked, &verified_boot_hash);
1814 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001815 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001816
1817 att_sw_enforced.Sort();
1818 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001819 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001820
1821 att_hw_enforced.Sort();
1822 expected_hw_enforced.Sort();
1823 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1824
David Drysdale565ccc72021-10-11 12:49:50 +01001825 if (unique_id != nullptr) {
1826 *unique_id = att_unique_id;
1827 }
1828
Shawn Willden7c130392020-12-21 09:58:22 -07001829 return true;
1830}
1831
1832string bin2hex(const vector<uint8_t>& data) {
1833 string retval;
1834 retval.reserve(data.size() * 2 + 1);
1835 for (uint8_t byte : data) {
1836 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1837 retval.push_back(nibble2hex[0x0F & byte]);
1838 }
1839 return retval;
1840}
1841
David Drysdalef0d516d2021-03-22 07:51:43 +00001842AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1843 AuthorizationSet authList;
1844 for (auto& entry : key_characteristics) {
1845 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1846 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1847 authList.push_back(AuthorizationSet(entry.authorizations));
1848 }
1849 }
1850 return authList;
1851}
1852
1853AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1854 AuthorizationSet authList;
1855 for (auto& entry : key_characteristics) {
1856 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1857 entry.securityLevel == SecurityLevel::KEYSTORE) {
1858 authList.push_back(AuthorizationSet(entry.authorizations));
1859 }
1860 }
1861 return authList;
1862}
1863
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001864AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1865 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001866 std::stringstream cert_data;
1867
1868 for (size_t i = 0; i < chain.size(); ++i) {
1869 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1870
1871 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1872 X509_Ptr signing_cert;
1873 if (i < chain.size() - 1) {
1874 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1875 } else {
1876 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1877 }
1878 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1879
1880 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1881 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1882
1883 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1884 return AssertionFailure()
1885 << "Verification of certificate " << i << " failed "
1886 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1887 << cert_data.str();
1888 }
1889
1890 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1891 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001892 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001893 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1894 << " Signer subject is " << signer_subj
1895 << " Issuer subject is " << cert_issuer << endl
1896 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001897 }
Shawn Willden7c130392020-12-21 09:58:22 -07001898 }
1899
1900 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1901 return AssertionSuccess();
1902}
1903
1904X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1905 const uint8_t* p = blob.data();
1906 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1907}
1908
Tri Voec50ee12023-02-14 16:29:53 -08001909// Extract attestation record from cert. Returned object is still part of cert; don't free it
1910// separately.
1911ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
1912 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
1913 EXPECT_TRUE(!!oid.get());
1914 if (!oid.get()) return nullptr;
1915
1916 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
1917 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
1918 if (location == -1) return nullptr;
1919
1920 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
1921 EXPECT_TRUE(!!attest_rec_ext)
1922 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
1923 if (!attest_rec_ext) return nullptr;
1924
1925 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
1926 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
1927 return attest_rec;
1928}
1929
David Drysdalef0d516d2021-03-22 07:51:43 +00001930vector<uint8_t> make_name_from_str(const string& name) {
1931 X509_NAME_Ptr x509_name(X509_NAME_new());
1932 EXPECT_TRUE(x509_name.get() != nullptr);
1933 if (!x509_name) return {};
1934
1935 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1936 "CN", //
1937 MBSTRING_ASC,
1938 reinterpret_cast<const uint8_t*>(name.c_str()),
1939 -1, // len
1940 -1, // loc
1941 0 /* set */));
1942
1943 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1944 EXPECT_GT(len, 0);
1945
1946 vector<uint8_t> retval(len);
1947 uint8_t* p = retval.data();
1948 i2d_X509_NAME(x509_name.get(), &p);
1949
1950 return retval;
1951}
1952
David Drysdale4dc01072021-04-01 12:17:35 +01001953namespace {
1954
1955void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1956 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1957 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1958
1959 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1960 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001961 EXPECT_THAT(
1962 cppbor::prettyPrint(parsedPayload.get()),
1963 MatchesRegex("\\{\n"
1964 " 1 : 2,\n" // kty: EC2
1965 " 3 : -7,\n" // alg: ES256
1966 " -1 : 1,\n" // EC id: P256
1967 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1968 // sequence of 32 hexadecimal bytes, enclosed in braces and
1969 // separated by commas. In this case, some Ed25519 public key.
1970 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1971 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1972 " -70000 : null,\n" // test marker
1973 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001974 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001975 EXPECT_THAT(
1976 cppbor::prettyPrint(parsedPayload.get()),
1977 MatchesRegex("\\{\n"
1978 " 1 : 2,\n" // kty: EC2
1979 " 3 : -7,\n" // alg: ES256
1980 " -1 : 1,\n" // EC id: P256
1981 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1982 // sequence of 32 hexadecimal bytes, enclosed in braces and
1983 // separated by commas. In this case, some Ed25519 public key.
1984 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1985 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1986 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001987 }
1988}
1989
1990} // namespace
1991
1992void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1993 vector<uint8_t>* payload_value) {
1994 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1995 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1996
1997 ASSERT_NE(coseMac0->asArray(), nullptr);
1998 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1999
2000 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
2001 ASSERT_NE(protParms, nullptr);
2002
2003 // Header label:value of 'alg': HMAC-256
2004 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
2005
2006 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
2007 ASSERT_NE(unprotParms, nullptr);
2008 ASSERT_EQ(unprotParms->size(), 0);
2009
2010 // The payload is a bstr holding an encoded COSE_Key
2011 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
2012 ASSERT_NE(payload, nullptr);
2013 check_cose_key(payload->value(), testMode);
2014
2015 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
2016 ASSERT_TRUE(coseMac0Tag);
2017 auto extractedTag = coseMac0Tag->value();
2018 EXPECT_EQ(extractedTag.size(), 32U);
2019
2020 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07002021 auto macFunction = [](const cppcose::bytevec& input) {
2022 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
2023 };
2024 auto testTag =
2025 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01002026 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
2027
2028 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07002029 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01002030 } else {
Seth Moore026bb742021-04-30 11:41:18 -07002031 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002032 }
2033 if (payload_value != nullptr) {
2034 *payload_value = payload->value();
2035 }
2036}
2037
2038void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2039 // Extract x and y affine coordinates from the encoded Cose_Key.
2040 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2041 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2042 auto coseKey = parsedPayload->asMap();
2043 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2044 ASSERT_NE(xItem->asBstr(), nullptr);
2045 vector<uint8_t> x = xItem->asBstr()->value();
2046 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2047 ASSERT_NE(yItem->asBstr(), nullptr);
2048 vector<uint8_t> y = yItem->asBstr()->value();
2049
2050 // Concatenate: 0x04 (uncompressed form marker) | x | y
2051 vector<uint8_t> pubKeyData{0x04};
2052 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2053 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2054
2055 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2056 ASSERT_NE(ecKey, nullptr);
2057 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2058 ASSERT_NE(group, nullptr);
2059 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2060 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2061 ASSERT_NE(point, nullptr);
2062 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2063 nullptr),
2064 1);
2065 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2066
2067 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2068 ASSERT_NE(pubKey, nullptr);
2069 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2070 *signingKey = std::move(pubKey);
2071}
2072
Max Biresa97ec692022-11-21 23:37:54 -08002073void device_id_attestation_vsr_check(const ErrorCode& result) {
Shawn Willden1a545db2023-02-22 14:32:33 -07002074 if (get_vsr_api_level() > __ANDROID_API_T__) {
Max Biresa97ec692022-11-21 23:37:54 -08002075 ASSERT_FALSE(result == ErrorCode::INVALID_TAG)
2076 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2077 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2078 << "be used for a case where updateAad() is called after update(). As of "
2079 << "VSR-14, this is now enforced as an error.";
2080 }
2081}
2082
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002083// Check whether the given named feature is available.
2084bool check_feature(const std::string& name) {
2085 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002086 ::android::sp<::android::IBinder> binder(
2087 sm->waitForService(::android::String16("package_native")));
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002088 if (binder == nullptr) {
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002089 GTEST_LOG_(ERROR) << "waitForService package_native failed";
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002090 return false;
2091 }
2092 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2093 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2094 if (packageMgr == nullptr) {
2095 GTEST_LOG_(ERROR) << "Cannot find package manager";
2096 return false;
2097 }
2098 bool hasFeature = false;
2099 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2100 if (!status.isOk()) {
2101 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2102 return false;
2103 }
2104 return hasFeature;
2105}
2106
Selene Huang31ab4042020-04-29 04:22:39 -07002107} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002108
Janis Danisevskis24c04702020-12-16 18:28:39 -08002109} // namespace aidl::android::hardware::security::keymint