blob: b55e609319f3519ae06e9e631ce6070c0d3b5860 [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;
Tommy Chiu025f3c52023-05-15 06:23:44 +0000177std::optional<bool> KeyMintAidlTestBase::expect_upgrade = std::nullopt;
Shawn Willden7c130392020-12-21 09:58:22 -0700178
David Drysdale37af4b32021-05-14 16:46:59 +0100179uint32_t KeyMintAidlTestBase::boot_patch_level(
180 const vector<KeyCharacteristics>& key_characteristics) {
181 // The boot patchlevel is not available as a property, but should be present
182 // in the key characteristics of any created key.
183 AuthorizationSet allAuths;
184 for (auto& entry : key_characteristics) {
185 allAuths.push_back(AuthorizationSet(entry.authorizations));
186 }
187 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
188 if (patchlevel.has_value()) {
189 return patchlevel.value();
190 } else {
191 // No boot patchlevel is available. Return a value that won't match anything
192 // and so will trigger test failures.
193 return kInvalidPatchlevel;
194 }
195}
196
197uint32_t KeyMintAidlTestBase::boot_patch_level() {
198 return boot_patch_level(key_characteristics_);
199}
200
Prashant Patil88ad1892022-03-15 16:31:02 +0000201/**
202 * An API to determine device IDs attestation is required or not,
203 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
204 */
205bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700206 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= __ANDROID_API_T__;
Prashant Patil88ad1892022-03-15 16:31:02 +0000207}
208
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000209/**
210 * An API to determine second IMEI ID attestation is required or not,
211 * which is supported for KeyMint version 3 or first_api_level greater than 33.
212 */
213bool KeyMintAidlTestBase::isSecondImeiIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700214 return AidlVersion() >= 3 && property_get_int32("ro.vendor.api_level", 0) > __ANDROID_API_T__;
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000215}
216
David Drysdale42fe1892021-10-14 14:43:46 +0100217bool KeyMintAidlTestBase::Curve25519Supported() {
218 // Strongbox never supports curve 25519.
219 if (SecLevel() == SecurityLevel::STRONGBOX) {
220 return false;
221 }
222
223 // Curve 25519 was included in version 2 of the KeyMint interface.
224 int32_t version = 0;
225 auto status = keymint_->getInterfaceVersion(&version);
226 if (!status.isOk()) {
227 ADD_FAILURE() << "Failed to determine interface version";
228 }
229 return version >= 2;
230}
231
Janis Danisevskis24c04702020-12-16 18:28:39 -0800232ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700233 if (result.isOk()) return ErrorCode::OK;
234
Janis Danisevskis24c04702020-12-16 18:28:39 -0800235 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
236 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700237 }
238
239 return ErrorCode::UNKNOWN_ERROR;
240}
241
Janis Danisevskis24c04702020-12-16 18:28:39 -0800242void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700243 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800244 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700245
246 KeyMintHardwareInfo info;
247 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
248
249 securityLevel_ = info.securityLevel;
250 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
251 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100252 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700253
254 os_version_ = getOsVersion();
255 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100256 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700257}
258
David Drysdale7dff4fc2021-12-10 10:10:52 +0000259int32_t KeyMintAidlTestBase::AidlVersion() {
260 int32_t version = 0;
261 auto status = keymint_->getInterfaceVersion(&version);
262 if (!status.isOk()) {
263 ADD_FAILURE() << "Failed to determine interface version";
264 }
265 return version;
266}
267
Selene Huang31ab4042020-04-29 04:22:39 -0700268void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800269 if (AServiceManager_isDeclared(GetParam().c_str())) {
270 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
271 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
272 } else {
273 InitializeKeyMint(nullptr);
274 }
Selene Huang31ab4042020-04-29 04:22:39 -0700275}
276
277ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700278 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700279 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700280 vector<KeyCharacteristics>* key_characteristics,
281 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700282 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
283 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700284 << "Previous characteristics not deleted before generating key. Test bug.";
285
Shawn Willden7f424372021-01-10 18:06:50 -0700286 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700287 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700288 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700289 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
290 creationResult.keyCharacteristics);
291 EXPECT_GT(creationResult.keyBlob.size(), 0);
292 *key_blob = std::move(creationResult.keyBlob);
293 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700294 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700295
296 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
297 EXPECT_TRUE(algorithm);
298 if (algorithm &&
299 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700300 EXPECT_GE(cert_chain->size(), 1);
301 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
302 if (attest_key) {
303 EXPECT_EQ(cert_chain->size(), 1);
304 } else {
305 EXPECT_GT(cert_chain->size(), 1);
306 }
307 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700308 } else {
309 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700310 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700311 }
Selene Huang31ab4042020-04-29 04:22:39 -0700312 }
313
314 return GetReturnErrorCode(result);
315}
316
Shawn Willden7c130392020-12-21 09:58:22 -0700317ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
318 const optional<AttestationKey>& attest_key) {
319 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700320}
321
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000322ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
323 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
324 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
325 vector<Certificate>* cert_chain) {
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +0000326 skipAttestKeyTest();
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000327 AttestationKey attest_key;
328 vector<Certificate> attest_cert_chain;
329 vector<KeyCharacteristics> attest_key_characteristics;
330 // Generate a key with self signed attestation.
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +0000331 auto error = GenerateAttestKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
332 &attest_key_characteristics, &attest_cert_chain);
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000333 if (error != ErrorCode::OK) {
334 return error;
335 }
336
337 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
338 // Generate a key, by passing the above self signed attestation key as attest key.
339 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
340 if (error == ErrorCode::OK) {
341 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
342 cert_chain->push_back(attest_cert_chain[0]);
343 }
344 return error;
345}
346
Selene Huang31ab4042020-04-29 04:22:39 -0700347ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
348 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700349 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700350 Status result;
351
Shawn Willden7f424372021-01-10 18:06:50 -0700352 cert_chain_.clear();
353 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700354 key_blob->clear();
355
Shawn Willden7f424372021-01-10 18:06:50 -0700356 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700357 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700358 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700359 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700360
361 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700362 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
363 creationResult.keyCharacteristics);
364 EXPECT_GT(creationResult.keyBlob.size(), 0);
365
366 *key_blob = std::move(creationResult.keyBlob);
367 *key_characteristics = std::move(creationResult.keyCharacteristics);
368 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700369
370 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
371 EXPECT_TRUE(algorithm);
372 if (algorithm &&
373 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
374 EXPECT_GE(cert_chain_.size(), 1);
375 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
376 } else {
377 // For symmetric keys there should be no certificates.
378 EXPECT_EQ(cert_chain_.size(), 0);
379 }
Selene Huang31ab4042020-04-29 04:22:39 -0700380 }
381
382 return GetReturnErrorCode(result);
383}
384
385ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
386 const string& key_material) {
387 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
388}
389
390ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
391 const AuthorizationSet& wrapping_key_desc,
392 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393 const AuthorizationSet& unwrapping_params,
394 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700395 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
396
Shawn Willden7f424372021-01-10 18:06:50 -0700397 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700398
Shawn Willden7f424372021-01-10 18:06:50 -0700399 KeyCreationResult creationResult;
400 Status result = keymint_->importWrappedKey(
401 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
402 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100403 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700404
405 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700406 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
407 creationResult.keyCharacteristics);
408 EXPECT_GT(creationResult.keyBlob.size(), 0);
409
410 key_blob_ = std::move(creationResult.keyBlob);
411 key_characteristics_ = std::move(creationResult.keyCharacteristics);
412 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700413
414 AuthorizationSet allAuths;
415 for (auto& entry : key_characteristics_) {
416 allAuths.push_back(AuthorizationSet(entry.authorizations));
417 }
418 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
419 EXPECT_TRUE(algorithm);
420 if (algorithm &&
421 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
422 EXPECT_GE(cert_chain_.size(), 1);
423 } else {
424 // For symmetric keys there should be no certificates.
425 EXPECT_EQ(cert_chain_.size(), 0);
426 }
Selene Huang31ab4042020-04-29 04:22:39 -0700427 }
428
429 return GetReturnErrorCode(result);
430}
431
David Drysdale300b5552021-05-20 12:05:26 +0100432ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
433 const vector<uint8_t>& app_id,
434 const vector<uint8_t>& app_data,
435 vector<KeyCharacteristics>* key_characteristics) {
436 Status result =
437 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
438 return GetReturnErrorCode(result);
439}
440
441ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
442 vector<KeyCharacteristics>* key_characteristics) {
443 vector<uint8_t> empty_app_id, empty_app_data;
444 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
445}
446
447void KeyMintAidlTestBase::CheckCharacteristics(
448 const vector<uint8_t>& key_blob,
449 const vector<KeyCharacteristics>& generate_characteristics) {
450 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
451 // generateKey() should be excluded, as KeyMint will have no record of them.
452 // This applies to CREATION_DATETIME in particular.
453 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
454 strip_keystore_tags(&expected_characteristics);
455
456 vector<KeyCharacteristics> retrieved;
457 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
458 EXPECT_EQ(expected_characteristics, retrieved);
459}
460
461void KeyMintAidlTestBase::CheckAppIdCharacteristics(
462 const vector<uint8_t>& key_blob, std::string_view app_id_string,
463 std::string_view app_data_string,
464 const vector<KeyCharacteristics>& generate_characteristics) {
465 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
466 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
467 strip_keystore_tags(&expected_characteristics);
468
469 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
470 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
471 vector<KeyCharacteristics> retrieved;
472 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
473 EXPECT_EQ(expected_characteristics, retrieved);
474
475 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
476 vector<uint8_t> empty;
477 vector<KeyCharacteristics> not_retrieved;
478 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
479 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
480 EXPECT_EQ(not_retrieved.size(), 0);
481
482 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
483 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
484 EXPECT_EQ(not_retrieved.size(), 0);
485
486 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
487 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
488 EXPECT_EQ(not_retrieved.size(), 0);
489}
490
Selene Huang31ab4042020-04-29 04:22:39 -0700491ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
492 Status result = keymint_->deleteKey(*key_blob);
493 if (!keep_key_blob) {
494 *key_blob = vector<uint8_t>();
495 }
496
Janis Danisevskis24c04702020-12-16 18:28:39 -0800497 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700498 return GetReturnErrorCode(result);
499}
500
501ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
502 return DeleteKey(&key_blob_, keep_key_blob);
503}
504
505ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
506 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800507 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700508 return GetReturnErrorCode(result);
509}
510
David Drysdaled2cc8c22021-04-15 13:29:45 +0100511ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
512 Status result = keymint_->destroyAttestationIds();
513 return GetReturnErrorCode(result);
514}
515
Selene Huang31ab4042020-04-29 04:22:39 -0700516void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
517 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
518 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
519}
520
521void KeyMintAidlTestBase::CheckedDeleteKey() {
522 CheckedDeleteKey(&key_blob_);
523}
524
525ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
526 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800527 AuthorizationSet* out_params,
528 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700529 SCOPED_TRACE("Begin");
530 Status result;
531 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100532 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700533
534 if (result.isOk()) {
535 *out_params = out.params;
536 challenge_ = out.challenge;
537 op = out.operation;
538 }
539
540 return GetReturnErrorCode(result);
541}
542
543ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
544 const AuthorizationSet& in_params,
David Drysdale28fa9312023-02-01 14:53:01 +0000545 AuthorizationSet* out_params,
546 std::optional<HardwareAuthToken> hat) {
Selene Huang31ab4042020-04-29 04:22:39 -0700547 SCOPED_TRACE("Begin");
548 Status result;
549 BeginResult out;
550
David Drysdale28fa9312023-02-01 14:53:01 +0000551 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), hat, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700552
553 if (result.isOk()) {
554 *out_params = out.params;
555 challenge_ = out.challenge;
556 op_ = out.operation;
557 }
558
559 return GetReturnErrorCode(result);
560}
561
562ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
563 AuthorizationSet* out_params) {
564 SCOPED_TRACE("Begin");
565 EXPECT_EQ(nullptr, op_);
566 return Begin(purpose, key_blob_, in_params, out_params);
567}
568
569ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
570 SCOPED_TRACE("Begin");
571 AuthorizationSet out_params;
572 ErrorCode result = Begin(purpose, in_params, &out_params);
573 EXPECT_TRUE(out_params.empty());
574 return result;
575}
576
Shawn Willden92d79c02021-02-19 07:31:55 -0700577ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
578 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
579 {} /* hardwareAuthToken */,
580 {} /* verificationToken */));
581}
582
583ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700584 SCOPED_TRACE("Update");
585
586 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700587 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700588
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800589 EXPECT_NE(op_, nullptr);
590 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
591
Shawn Willden92d79c02021-02-19 07:31:55 -0700592 std::vector<uint8_t> o_put;
593 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700594
David Drysdalefeab5d92022-01-06 15:46:23 +0000595 if (result.isOk()) {
596 output->append(o_put.begin(), o_put.end());
597 } else {
598 // Failure always terminates the operation.
599 op_ = {};
600 }
Selene Huang31ab4042020-04-29 04:22:39 -0700601
602 return GetReturnErrorCode(result);
603}
604
David Drysdale28fa9312023-02-01 14:53:01 +0000605ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, string* output,
606 std::optional<HardwareAuthToken> hat,
607 std::optional<secureclock::TimeStampToken> time_token) {
Selene Huang31ab4042020-04-29 04:22:39 -0700608 SCOPED_TRACE("Finish");
609 Status result;
610
611 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700612 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700613
614 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700615 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
David Drysdale28fa9312023-02-01 14:53:01 +0000616 vector<uint8_t>(signature.begin(), signature.end()), hat, time_token,
617 {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Shawn Willden92d79c02021-02-19 07:31:55 -0700619 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700620
Shawn Willden92d79c02021-02-19 07:31:55 -0700621 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700622 return GetReturnErrorCode(result);
623}
624
Janis Danisevskis24c04702020-12-16 18:28:39 -0800625ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700626 SCOPED_TRACE("Abort");
627
628 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700629 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700630
631 Status retval = op->abort();
632 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800633 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700634}
635
636ErrorCode KeyMintAidlTestBase::Abort() {
637 SCOPED_TRACE("Abort");
638
639 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700640 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700641
642 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800643 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700644}
645
646void KeyMintAidlTestBase::AbortIfNeeded() {
647 SCOPED_TRACE("AbortIfNeeded");
648 if (op_) {
649 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800650 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700651 }
652}
653
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000654auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
655 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700656 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000657 AuthorizationSet begin_out_params;
658 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700659 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000660
661 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700662 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000663}
664
Selene Huang31ab4042020-04-29 04:22:39 -0700665string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
666 const string& message, const AuthorizationSet& in_params,
667 AuthorizationSet* out_params) {
668 SCOPED_TRACE("ProcessMessage");
669 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700670 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700671 EXPECT_EQ(ErrorCode::OK, result);
672 if (result != ErrorCode::OK) {
673 return "";
674 }
675
676 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700677 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700678 return output;
679}
680
681string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
682 const AuthorizationSet& params) {
683 SCOPED_TRACE("SignMessage");
684 AuthorizationSet out_params;
685 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
686 EXPECT_TRUE(out_params.empty());
687 return signature;
688}
689
690string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
691 SCOPED_TRACE("SignMessage");
692 return SignMessage(key_blob_, message, params);
693}
694
695string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
696 SCOPED_TRACE("MacMessage");
697 return SignMessage(
698 key_blob_, message,
699 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
700}
701
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530702void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
703 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000704 auto builder = AuthorizationSetBuilder()
705 .Authorization(TAG_NO_AUTH_REQUIRED)
706 .AesEncryptionKey(128)
707 .BlockMode(block_mode)
708 .Padding(PaddingMode::NONE);
709 if (block_mode == BlockMode::GCM) {
710 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
711 }
712 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530713
714 for (int increment = 1; increment <= message_size; ++increment) {
715 string message(message_size, 'a');
716 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
717 if (block_mode == BlockMode::GCM) {
718 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
719 }
720
721 AuthorizationSet output_params;
722 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
723
724 string ciphertext;
725 string to_send;
726 for (size_t i = 0; i < message.size(); i += increment) {
727 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
728 }
729 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
730 << "Error sending " << to_send << " with block mode " << block_mode;
731
732 switch (block_mode) {
733 case BlockMode::GCM:
734 EXPECT_EQ(message.size() + 16, ciphertext.size());
735 break;
736 case BlockMode::CTR:
737 EXPECT_EQ(message.size(), ciphertext.size());
738 break;
739 case BlockMode::CBC:
740 case BlockMode::ECB:
741 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
742 break;
743 }
744
745 auto iv = output_params.GetTagValue(TAG_NONCE);
746 switch (block_mode) {
747 case BlockMode::CBC:
748 case BlockMode::GCM:
749 case BlockMode::CTR:
750 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
751 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
752 params.push_back(TAG_NONCE, iv->get());
753 break;
754
755 case BlockMode::ECB:
756 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
757 break;
758 }
759
760 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
761 << "Decrypt begin() failed for block mode " << block_mode;
762
763 string plaintext;
764 for (size_t i = 0; i < ciphertext.size(); i += increment) {
765 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
766 }
767 ErrorCode error = Finish(to_send, &plaintext);
768 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
769 << " and increment " << increment;
770 if (error == ErrorCode::OK) {
771 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
772 << " and increment " << increment;
773 }
774 }
775}
776
Prashant Patildd5f7f02022-07-06 18:58:07 +0000777void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
778 PaddingMode padding_mode, const string& iv,
779 const string& plaintext,
780 const string& exp_cipher_text) {
781 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
782 auto auth_set = AuthorizationSetBuilder()
783 .Authorization(TAG_NO_AUTH_REQUIRED)
784 .AesEncryptionKey(key.size() * 8)
785 .BlockMode(block_mode)
786 .Padding(padding_mode);
787 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
788 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
789 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
790
791 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
792 exp_cipher_text);
793}
794
795void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
796 PaddingMode padding_mode, const string& iv,
797 const string& plaintext,
798 const string& exp_cipher_text) {
799 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
800 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
801 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
802 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
803 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
804
805 AuthorizationSet output_params;
806 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
807
808 string actual_ciphertext;
809 if (is_stream_cipher) {
810 // Assert that a 1 byte of output is produced for 1 byte of input.
811 // Every input byte produces an output byte.
812 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
813 string ciphertext;
814 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
815 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
816 // we relax this API restriction for them.
817 if (SecLevel() != SecurityLevel::STRONGBOX) {
818 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
819 }
820 actual_ciphertext.append(ciphertext);
821 }
822 string ciphertext;
823 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
824 if (SecLevel() != SecurityLevel::STRONGBOX) {
825 string expected_final_output;
826 if (is_authenticated_cipher) {
827 expected_final_output = exp_cipher_text.substr(plaintext.size());
828 }
829 EXPECT_EQ(expected_final_output, ciphertext);
830 }
831 actual_ciphertext.append(ciphertext);
832 } else {
833 // Assert that a block of output is produced once a full block of input is provided.
834 // Every input block produces an output block.
835 bool compare_output = true;
836 string additional_information;
837 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
838 if (SecLevel() == SecurityLevel::STRONGBOX) {
839 // This is known to be broken on older vendor implementations.
Shawn Willden1a545db2023-02-22 14:32:33 -0700840 if (vendor_api_level < __ANDROID_API_T__) {
Prashant Patildd5f7f02022-07-06 18:58:07 +0000841 compare_output = false;
842 } else {
843 additional_information = " (b/194134359) ";
844 }
845 }
846 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
847 string ciphertext;
848 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
849 if (compare_output) {
850 if ((plaintext_index % block_size) == block_size - 1) {
851 // Update is expected to have output a new block
852 EXPECT_EQ(block_size, ciphertext.size())
853 << "plaintext index: " << plaintext_index << additional_information;
854 } else {
855 // Update is expected to have produced no output
856 EXPECT_EQ(0, ciphertext.size())
857 << "plaintext index: " << plaintext_index << additional_information;
858 }
859 }
860 actual_ciphertext.append(ciphertext);
861 }
862 string ciphertext;
863 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
864 actual_ciphertext.append(ciphertext);
865 }
866 // Regardless of how the completed ciphertext got accumulated, it should match the expected
867 // ciphertext.
868 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
869}
870
Selene Huang31ab4042020-04-29 04:22:39 -0700871void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
872 Digest digest, const string& expected_mac) {
873 SCOPED_TRACE("CheckHmacTestVector");
874 ASSERT_EQ(ErrorCode::OK,
875 ImportKey(AuthorizationSetBuilder()
876 .Authorization(TAG_NO_AUTH_REQUIRED)
877 .HmacKey(key.size() * 8)
878 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
879 .Digest(digest),
880 KeyFormat::RAW, key));
881 string signature = MacMessage(message, digest, expected_mac.size() * 8);
882 EXPECT_EQ(expected_mac, signature)
883 << "Test vector didn't match for key of size " << key.size() << " message of size "
884 << message.size() << " and digest " << digest;
885 CheckedDeleteKey();
886}
887
888void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
889 const string& message,
890 const string& expected_ciphertext) {
891 SCOPED_TRACE("CheckAesCtrTestVector");
892 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
893 .Authorization(TAG_NO_AUTH_REQUIRED)
894 .AesEncryptionKey(key.size() * 8)
895 .BlockMode(BlockMode::CTR)
896 .Authorization(TAG_CALLER_NONCE)
897 .Padding(PaddingMode::NONE),
898 KeyFormat::RAW, key));
899
900 auto params = AuthorizationSetBuilder()
901 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
902 .BlockMode(BlockMode::CTR)
903 .Padding(PaddingMode::NONE);
904 AuthorizationSet out_params;
905 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
906 EXPECT_EQ(expected_ciphertext, ciphertext);
907}
908
909void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
910 PaddingMode padding_mode, const string& key,
911 const string& iv, const string& input,
912 const string& expected_output) {
913 auto authset = AuthorizationSetBuilder()
914 .TripleDesEncryptionKey(key.size() * 7)
915 .BlockMode(block_mode)
916 .Authorization(TAG_NO_AUTH_REQUIRED)
917 .Padding(padding_mode);
918 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
919 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
920 ASSERT_GT(key_blob_.size(), 0U);
921
922 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
923 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
924 AuthorizationSet output_params;
925 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
926 EXPECT_EQ(expected_output, output);
927}
928
929void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
930 const string& signature, const AuthorizationSet& params) {
931 SCOPED_TRACE("VerifyMessage");
932 AuthorizationSet begin_out_params;
933 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
934
935 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700936 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700937 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700938 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700939}
940
941void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
942 const AuthorizationSet& params) {
943 SCOPED_TRACE("VerifyMessage");
944 VerifyMessage(key_blob_, message, signature, params);
945}
946
David Drysdaledf8f52e2021-05-06 08:10:58 +0100947void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
948 const AuthorizationSet& params) {
949 SCOPED_TRACE("LocalVerifyMessage");
950
David Drysdaledf8f52e2021-05-06 08:10:58 +0100951 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000952 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
953}
954
955void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
956 const string& signature,
957 const AuthorizationSet& params) {
958 // Retrieve the public key from the leaf certificate.
959 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100960 ASSERT_TRUE(key_cert.get());
961 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
962 ASSERT_TRUE(pub_key.get());
963
964 Digest digest = params.GetTagValue(TAG_DIGEST).value();
965 PaddingMode padding = PaddingMode::NONE;
966 auto tag = params.GetTagValue(TAG_PADDING);
967 if (tag.has_value()) {
968 padding = tag.value();
969 }
970
971 if (digest == Digest::NONE) {
972 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100973 case EVP_PKEY_ED25519: {
974 ASSERT_EQ(64, signature.size());
975 uint8_t pub_keydata[32];
976 size_t pub_len = sizeof(pub_keydata);
977 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
978 ASSERT_EQ(sizeof(pub_keydata), pub_len);
979 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
980 message.size(),
981 reinterpret_cast<const uint8_t*>(signature.data()),
982 pub_keydata));
983 break;
984 }
985
David Drysdaledf8f52e2021-05-06 08:10:58 +0100986 case EVP_PKEY_EC: {
987 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
988 size_t data_size = std::min(data.size(), message.size());
989 memcpy(data.data(), message.data(), data_size);
990 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
991 ASSERT_TRUE(ecdsa.get());
992 ASSERT_EQ(1,
993 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
994 reinterpret_cast<const uint8_t*>(signature.data()),
995 signature.size(), ecdsa.get()));
996 break;
997 }
998 case EVP_PKEY_RSA: {
999 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
1000 size_t data_size = std::min(data.size(), message.size());
1001 memcpy(data.data(), message.data(), data_size);
1002
1003 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1004 ASSERT_TRUE(rsa.get());
1005
1006 size_t key_len = RSA_size(rsa.get());
1007 int openssl_padding = RSA_NO_PADDING;
1008 switch (padding) {
1009 case PaddingMode::NONE:
1010 ASSERT_TRUE(data_size <= key_len);
1011 ASSERT_EQ(key_len, signature.size());
1012 openssl_padding = RSA_NO_PADDING;
1013 break;
1014 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1015 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1016 key_len);
1017 openssl_padding = RSA_PKCS1_PADDING;
1018 break;
1019 default:
1020 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1021 }
1022
1023 vector<uint8_t> decrypted_data(key_len);
1024 int bytes_decrypted = RSA_public_decrypt(
1025 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1026 decrypted_data.data(), rsa.get(), openssl_padding);
1027 ASSERT_GE(bytes_decrypted, 0);
1028
1029 const uint8_t* compare_pos = decrypted_data.data();
1030 size_t bytes_to_compare = bytes_decrypted;
1031 uint8_t zero_check_result = 0;
1032 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1033 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1034 // during verification we should have zeros on the left of the decrypted data.
1035 // Do a constant-time check.
1036 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1037 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1038 ASSERT_EQ(0, zero_check_result);
1039 bytes_to_compare = data_size;
1040 }
1041 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1042 break;
1043 }
1044 default:
1045 ADD_FAILURE() << "Unknown public key type";
1046 }
1047 } else {
1048 EVP_MD_CTX digest_ctx;
1049 EVP_MD_CTX_init(&digest_ctx);
1050 EVP_PKEY_CTX* pkey_ctx;
1051 const EVP_MD* md = openssl_digest(digest);
1052 ASSERT_NE(md, nullptr);
1053 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1054
1055 if (padding == PaddingMode::RSA_PSS) {
1056 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1057 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001058 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001059 }
1060
1061 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1062 reinterpret_cast<const uint8_t*>(message.data()),
1063 message.size()));
1064 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1065 reinterpret_cast<const uint8_t*>(signature.data()),
1066 signature.size()));
1067 EVP_MD_CTX_cleanup(&digest_ctx);
1068 }
1069}
1070
David Drysdale59cae642021-05-12 13:52:03 +01001071string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1072 const AuthorizationSet& params) {
1073 SCOPED_TRACE("LocalRsaEncryptMessage");
1074
1075 // Retrieve the public key from the leaf certificate.
1076 if (cert_chain_.empty()) {
1077 ADD_FAILURE() << "No public key available";
1078 return "Failure";
1079 }
1080 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001081 if (key_cert.get() == nullptr) {
1082 ADD_FAILURE() << "Failed to parse cert";
1083 return "Failure";
1084 }
David Drysdale59cae642021-05-12 13:52:03 +01001085 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001086 if (pub_key.get() == nullptr) {
1087 ADD_FAILURE() << "Failed to retrieve public key";
1088 return "Failure";
1089 }
David Drysdale59cae642021-05-12 13:52:03 +01001090 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001091 if (rsa.get() == nullptr) {
1092 ADD_FAILURE() << "Failed to retrieve RSA public key";
1093 return "Failure";
1094 }
David Drysdale59cae642021-05-12 13:52:03 +01001095
1096 // Retrieve relevant tags.
1097 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001098 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001099 PaddingMode padding = PaddingMode::NONE;
1100
1101 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1102 if (digest_tag.has_value()) digest = digest_tag.value();
1103 auto pad_tag = params.GetTagValue(TAG_PADDING);
1104 if (pad_tag.has_value()) padding = pad_tag.value();
1105 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1106 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1107
1108 const EVP_MD* md = openssl_digest(digest);
1109 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1110
1111 // Set up encryption context.
1112 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1113 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1114 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1115 return "Failure";
1116 }
1117
1118 int rc = -1;
1119 switch (padding) {
1120 case PaddingMode::NONE:
1121 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1122 break;
1123 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1124 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1125 break;
1126 case PaddingMode::RSA_OAEP:
1127 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1128 break;
1129 default:
1130 break;
1131 }
1132 if (rc <= 0) {
1133 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1134 return "Failure";
1135 }
1136 if (padding == PaddingMode::RSA_OAEP) {
1137 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1138 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1139 return "Failure";
1140 }
1141 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1142 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1143 return "Failure";
1144 }
1145 }
1146
1147 // Determine output size.
1148 size_t outlen;
1149 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1150 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1151 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1152 return "Failure";
1153 }
1154
1155 // Left-zero-pad the input if necessary.
1156 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1157 size_t to_encrypt_len = message.size();
1158
1159 std::unique_ptr<string> zero_padded_message;
1160 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1161 zero_padded_message.reset(new string(outlen, '\0'));
1162 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1163 message.size());
1164 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1165 to_encrypt_len = outlen;
1166 }
1167
1168 // Do the encryption.
1169 string output(outlen, '\0');
1170 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1171 to_encrypt_len) <= 0) {
1172 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1173 return "Failure";
1174 }
1175 return output;
1176}
1177
Selene Huang31ab4042020-04-29 04:22:39 -07001178string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1179 const AuthorizationSet& in_params,
1180 AuthorizationSet* out_params) {
1181 SCOPED_TRACE("EncryptMessage");
1182 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1183}
1184
1185string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1186 AuthorizationSet* out_params) {
1187 SCOPED_TRACE("EncryptMessage");
1188 return EncryptMessage(key_blob_, message, params, out_params);
1189}
1190
1191string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1192 SCOPED_TRACE("EncryptMessage");
1193 AuthorizationSet out_params;
1194 string ciphertext = EncryptMessage(message, params, &out_params);
1195 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1196 return ciphertext;
1197}
1198
1199string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1200 PaddingMode padding) {
1201 SCOPED_TRACE("EncryptMessage");
1202 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1203 AuthorizationSet out_params;
1204 string ciphertext = EncryptMessage(message, params, &out_params);
1205 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1206 return ciphertext;
1207}
1208
1209string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1210 PaddingMode padding, vector<uint8_t>* iv_out) {
1211 SCOPED_TRACE("EncryptMessage");
1212 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1213 AuthorizationSet out_params;
1214 string ciphertext = EncryptMessage(message, params, &out_params);
1215 EXPECT_EQ(1U, out_params.size());
1216 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001217 EXPECT_TRUE(ivVal);
1218 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001219 return ciphertext;
1220}
1221
1222string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1223 PaddingMode padding, const vector<uint8_t>& iv_in) {
1224 SCOPED_TRACE("EncryptMessage");
1225 auto params = AuthorizationSetBuilder()
1226 .BlockMode(block_mode)
1227 .Padding(padding)
1228 .Authorization(TAG_NONCE, iv_in);
1229 AuthorizationSet out_params;
1230 string ciphertext = EncryptMessage(message, params, &out_params);
1231 return ciphertext;
1232}
1233
1234string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1235 PaddingMode padding, uint8_t mac_length_bits,
1236 const vector<uint8_t>& iv_in) {
1237 SCOPED_TRACE("EncryptMessage");
1238 auto params = AuthorizationSetBuilder()
1239 .BlockMode(block_mode)
1240 .Padding(padding)
1241 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1242 .Authorization(TAG_NONCE, iv_in);
1243 AuthorizationSet out_params;
1244 string ciphertext = EncryptMessage(message, params, &out_params);
1245 return ciphertext;
1246}
1247
David Drysdaled2cc8c22021-04-15 13:29:45 +01001248string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1249 PaddingMode padding, uint8_t mac_length_bits) {
1250 SCOPED_TRACE("EncryptMessage");
1251 auto params = AuthorizationSetBuilder()
1252 .BlockMode(block_mode)
1253 .Padding(padding)
1254 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1255 AuthorizationSet out_params;
1256 string ciphertext = EncryptMessage(message, params, &out_params);
1257 return ciphertext;
1258}
1259
Selene Huang31ab4042020-04-29 04:22:39 -07001260string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1261 const string& ciphertext,
1262 const AuthorizationSet& params) {
1263 SCOPED_TRACE("DecryptMessage");
1264 AuthorizationSet out_params;
1265 string plaintext =
1266 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1267 EXPECT_TRUE(out_params.empty());
1268 return plaintext;
1269}
1270
1271string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1272 const AuthorizationSet& params) {
1273 SCOPED_TRACE("DecryptMessage");
1274 return DecryptMessage(key_blob_, ciphertext, params);
1275}
1276
1277string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1278 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1279 SCOPED_TRACE("DecryptMessage");
1280 auto params = AuthorizationSetBuilder()
1281 .BlockMode(block_mode)
1282 .Padding(padding_mode)
1283 .Authorization(TAG_NONCE, iv);
1284 return DecryptMessage(key_blob_, ciphertext, params);
1285}
1286
1287std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1288 const vector<uint8_t>& key_blob) {
1289 std::pair<ErrorCode, vector<uint8_t>> retval;
1290 vector<uint8_t> outKeyBlob;
1291 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1292 ErrorCode errorcode = GetReturnErrorCode(result);
1293 retval = std::tie(errorcode, outKeyBlob);
1294
1295 return retval;
1296}
Seth Moorea12ac742023-03-03 13:40:30 -08001297
1298bool KeyMintAidlTestBase::IsRkpSupportRequired() const {
1299 if (get_vsr_api_level() >= __ANDROID_API_T__) {
1300 return true;
1301 }
1302
1303 if (get_vsr_api_level() >= __ANDROID_API_S__) {
1304 return SecLevel() != SecurityLevel::STRONGBOX;
1305 }
1306
1307 return false;
1308}
1309
Selene Huang31ab4042020-04-29 04:22:39 -07001310vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1311 switch (algorithm) {
1312 case Algorithm::RSA:
1313 switch (SecLevel()) {
1314 case SecurityLevel::SOFTWARE:
1315 case SecurityLevel::TRUSTED_ENVIRONMENT:
1316 return {2048, 3072, 4096};
1317 case SecurityLevel::STRONGBOX:
1318 return {2048};
1319 default:
1320 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1321 break;
1322 }
1323 break;
1324 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001325 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001326 break;
1327 case Algorithm::AES:
1328 return {128, 256};
1329 case Algorithm::TRIPLE_DES:
1330 return {168};
1331 case Algorithm::HMAC: {
1332 vector<uint32_t> retval((512 - 64) / 8 + 1);
1333 uint32_t size = 64 - 8;
1334 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1335 return retval;
1336 }
1337 default:
1338 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1339 return {};
1340 }
1341 ADD_FAILURE() << "Should be impossible to get here";
1342 return {};
1343}
1344
1345vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1346 if (SecLevel() == SecurityLevel::STRONGBOX) {
1347 switch (algorithm) {
1348 case Algorithm::RSA:
1349 return {3072, 4096};
1350 case Algorithm::EC:
1351 return {224, 384, 521};
1352 case Algorithm::AES:
1353 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001354 case Algorithm::TRIPLE_DES:
1355 return {56};
1356 default:
1357 return {};
1358 }
1359 } else {
1360 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001361 case Algorithm::AES:
1362 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001363 case Algorithm::TRIPLE_DES:
1364 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001365 default:
1366 return {};
1367 }
1368 }
1369 return {};
1370}
1371
David Drysdale7de9feb2021-03-05 14:56:19 +00001372vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1373 switch (algorithm) {
1374 case Algorithm::AES:
1375 return {
1376 BlockMode::CBC,
1377 BlockMode::CTR,
1378 BlockMode::ECB,
1379 BlockMode::GCM,
1380 };
1381 case Algorithm::TRIPLE_DES:
1382 return {
1383 BlockMode::CBC,
1384 BlockMode::ECB,
1385 };
1386 default:
1387 return {};
1388 }
1389}
1390
1391vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1392 BlockMode blockMode) {
1393 switch (algorithm) {
1394 case Algorithm::AES:
1395 switch (blockMode) {
1396 case BlockMode::CBC:
1397 case BlockMode::ECB:
1398 return {PaddingMode::NONE, PaddingMode::PKCS7};
1399 case BlockMode::CTR:
1400 case BlockMode::GCM:
1401 return {PaddingMode::NONE};
1402 default:
1403 return {};
1404 };
1405 case Algorithm::TRIPLE_DES:
1406 switch (blockMode) {
1407 case BlockMode::CBC:
1408 case BlockMode::ECB:
1409 return {PaddingMode::NONE, PaddingMode::PKCS7};
1410 default:
1411 return {};
1412 };
1413 default:
1414 return {};
1415 }
1416}
1417
1418vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1419 BlockMode blockMode) {
1420 switch (algorithm) {
1421 case Algorithm::AES:
1422 switch (blockMode) {
1423 case BlockMode::CTR:
1424 case BlockMode::GCM:
1425 return {PaddingMode::PKCS7};
1426 default:
1427 return {};
1428 };
1429 default:
1430 return {};
1431 }
1432}
1433
Selene Huang31ab4042020-04-29 04:22:39 -07001434vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1435 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1436 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001437 } else if (Curve25519Supported()) {
1438 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1439 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001440 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001441 return {
1442 EcCurve::P_224,
1443 EcCurve::P_256,
1444 EcCurve::P_384,
1445 EcCurve::P_521,
1446 };
Selene Huang31ab4042020-04-29 04:22:39 -07001447 }
1448}
1449
1450vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001451 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001452 // Curve 25519 is not supported, either because:
1453 // - KeyMint v1: it's an unknown enum value
1454 // - KeyMint v2+: it's not supported by StrongBox.
1455 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001456 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001457 if (Curve25519Supported()) {
1458 return {};
1459 } else {
1460 return {EcCurve::CURVE_25519};
1461 }
David Drysdaledf09e542021-06-08 15:46:11 +01001462 }
Selene Huang31ab4042020-04-29 04:22:39 -07001463}
1464
subrahmanyaman05642492022-02-05 07:10:56 +00001465vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1466 if (SecLevel() == SecurityLevel::STRONGBOX) {
1467 return {65537};
1468 } else {
1469 return {3, 65537};
1470 }
1471}
1472
Selene Huang31ab4042020-04-29 04:22:39 -07001473vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1474 switch (SecLevel()) {
1475 case SecurityLevel::SOFTWARE:
1476 case SecurityLevel::TRUSTED_ENVIRONMENT:
1477 if (withNone) {
1478 if (withMD5)
1479 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1480 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1481 Digest::SHA_2_512};
1482 else
1483 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1484 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1485 } else {
1486 if (withMD5)
1487 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1488 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1489 else
1490 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1491 Digest::SHA_2_512};
1492 }
1493 break;
1494 case SecurityLevel::STRONGBOX:
1495 if (withNone)
1496 return {Digest::NONE, Digest::SHA_2_256};
1497 else
1498 return {Digest::SHA_2_256};
1499 break;
1500 default:
1501 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1502 break;
1503 }
1504 ADD_FAILURE() << "Should be impossible to get here";
1505 return {};
1506}
1507
Shawn Willden7f424372021-01-10 18:06:50 -07001508static const vector<KeyParameter> kEmptyAuthList{};
1509
1510const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1511 const vector<KeyCharacteristics>& key_characteristics) {
1512 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1513 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1514 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1515}
1516
Qi Wubeefae42021-01-28 23:16:37 +08001517const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1518 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1519 auto found = std::find_if(
1520 key_characteristics.begin(), key_characteristics.end(),
1521 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001522 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1523}
1524
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001525ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001526 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001527 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1528 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1529 return result;
1530}
1531
1532ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001533 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001534 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1535 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1536 return result;
1537}
1538
1539ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1540 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001541 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001542 rsaKeyBlob, KeyPurpose::SIGN, message,
1543 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1544 return result;
1545}
1546
1547ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001548 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1549 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001550 return result;
1551}
1552
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001553ErrorCode KeyMintAidlTestBase::GenerateAttestKey(const AuthorizationSet& key_desc,
1554 const optional<AttestationKey>& attest_key,
1555 vector<uint8_t>* key_blob,
1556 vector<KeyCharacteristics>* key_characteristics,
1557 vector<Certificate>* cert_chain) {
1558 // The original specification for KeyMint v1 required ATTEST_KEY not be combined
1559 // with any other key purpose, but the original VTS tests incorrectly did exactly that.
1560 // This means that a device that launched prior to Android T (API level 33) may
1561 // accept or even require KeyPurpose::SIGN too.
1562 if (property_get_int32("ro.board.first_api_level", 0) < __ANDROID_API_T__) {
1563 AuthorizationSet key_desc_plus_sign = key_desc;
1564 key_desc_plus_sign.push_back(TAG_PURPOSE, KeyPurpose::SIGN);
1565
1566 auto result = GenerateKey(key_desc_plus_sign, attest_key, key_blob, key_characteristics,
1567 cert_chain);
1568 if (result == ErrorCode::OK) {
1569 return result;
1570 }
1571 // If the key generation failed, it may be because the device is (correctly)
1572 // rejecting the combination of ATTEST_KEY+SIGN. Fall through to try again with
1573 // just ATTEST_KEY.
1574 }
1575 return GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
1576}
1577
1578// Check if ATTEST_KEY feature is disabled
1579bool KeyMintAidlTestBase::is_attest_key_feature_disabled(void) const {
1580 if (!check_feature(FEATURE_KEYSTORE_APP_ATTEST_KEY)) {
1581 GTEST_LOG_(INFO) << "Feature " + FEATURE_KEYSTORE_APP_ATTEST_KEY + " is disabled";
1582 return true;
1583 }
1584
1585 return false;
1586}
1587
1588// Check if StrongBox KeyStore is enabled
1589bool KeyMintAidlTestBase::is_strongbox_enabled(void) const {
1590 if (check_feature(FEATURE_STRONGBOX_KEYSTORE)) {
1591 GTEST_LOG_(INFO) << "Feature " + FEATURE_STRONGBOX_KEYSTORE + " is enabled";
1592 return true;
1593 }
1594
1595 return false;
1596}
1597
1598// Check if chipset has received a waiver allowing it to be launched with Android S or T with
1599// Keymaster 4.0 in StrongBox.
1600bool KeyMintAidlTestBase::is_chipset_allowed_km4_strongbox(void) const {
1601 std::array<char, PROPERTY_VALUE_MAX> buffer;
1602
1603 const int32_t first_api_level = property_get_int32("ro.board.first_api_level", 0);
1604 if (first_api_level <= 0 || first_api_level > __ANDROID_API_T__) return false;
1605
1606 auto res = property_get("ro.vendor.qti.soc_model", buffer.data(), nullptr);
1607 if (res <= 0) return false;
1608
Shawn Willden0f1b2572023-05-30 14:52:53 -06001609 const string allowed_soc_models[] = {"SM8450", "SM8475", "SM8550", "SXR2230P",
1610 "SM4450", "SM7450", "SM6450"};
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001611
1612 for (const string model : allowed_soc_models) {
1613 if (model.compare(buffer.data()) == 0) {
1614 GTEST_LOG_(INFO) << "QTI SOC Model " + model + " is allowed SB KM 4.0";
1615 return true;
1616 }
1617 }
1618
1619 return false;
1620}
1621
1622// Skip the test if all the following conditions hold:
1623// 1. ATTEST_KEY feature is disabled
1624// 2. STRONGBOX is enabled
1625// 3. The device is running one of the chipsets that have received a waiver
1626// allowing it to be launched with Android S (or later) with Keymaster 4.0
1627// in StrongBox
1628void KeyMintAidlTestBase::skipAttestKeyTest(void) const {
1629 // Check the chipset first as that doesn't require a round-trip to Package Manager.
1630 if (is_chipset_allowed_km4_strongbox() && is_strongbox_enabled() &&
1631 is_attest_key_feature_disabled()) {
1632 GTEST_SKIP() << "Test is not applicable";
1633 }
1634}
1635
Selene Huang6e46f142021-04-20 19:20:11 -07001636void verify_serial(X509* cert, const uint64_t expected_serial) {
1637 BIGNUM_Ptr ser(BN_new());
1638 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1639
1640 uint64_t serial;
1641 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1642 EXPECT_EQ(serial, expected_serial);
1643}
1644
1645// Please set self_signed to true for fake certificates or self signed
1646// certificates
1647void verify_subject(const X509* cert, //
1648 const string& subject, //
1649 bool self_signed) {
1650 char* cert_issuer = //
1651 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1652
1653 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1654
1655 string expected_subject("/CN=");
1656 if (subject.empty()) {
1657 expected_subject.append("Android Keystore Key");
1658 } else {
1659 expected_subject.append(subject);
1660 }
1661
1662 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1663
1664 if (self_signed) {
1665 EXPECT_STREQ(cert_issuer, cert_subj)
1666 << "Cert issuer and subject mismatch for self signed certificate.";
1667 }
1668
1669 OPENSSL_free(cert_subj);
1670 OPENSSL_free(cert_issuer);
1671}
1672
Shawn Willden22fb9c12022-06-02 14:04:33 -06001673int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001674 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1675 if (vendor_api_level != -1) {
1676 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001677 }
Shawn Willden35db3492022-06-16 12:50:40 -06001678
1679 // Android S and older devices do not define ro.vendor.api_level
1680 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1681 if (vendor_api_level == -1) {
1682 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001683 }
Shawn Willden35db3492022-06-16 12:50:40 -06001684
1685 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1686 if (product_api_level == -1) {
1687 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1688 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001689 }
Shawn Willden35db3492022-06-16 12:50:40 -06001690
1691 // VSR API level is the minimum of vendor_api_level and product_api_level.
1692 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1693 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001694 }
Shawn Willden35db3492022-06-16 12:50:40 -06001695 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001696}
1697
David Drysdale555ba002022-05-03 18:48:57 +01001698bool is_gsi_image() {
1699 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1700 return ifs.good();
1701}
1702
Selene Huang6e46f142021-04-20 19:20:11 -07001703vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1704 BIGNUM_Ptr serial(BN_new());
1705 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1706
1707 int len = BN_num_bytes(serial.get());
1708 vector<uint8_t> serial_blob(len);
1709 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1710 return {};
1711 }
1712
David Drysdaledb0dcf52021-05-18 11:43:31 +01001713 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1714 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1715 // Top bit being set indicates a negative number in two's complement, but our input
1716 // was positive.
1717 // In either case, prepend a zero byte.
1718 serial_blob.insert(serial_blob.begin(), 0x00);
1719 }
1720
Selene Huang6e46f142021-04-20 19:20:11 -07001721 return serial_blob;
1722}
1723
1724void verify_subject_and_serial(const Certificate& certificate, //
1725 const uint64_t expected_serial, //
1726 const string& subject, bool self_signed) {
1727 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1728 ASSERT_TRUE(!!cert.get());
1729
1730 verify_serial(cert.get(), expected_serial);
1731 verify_subject(cert.get(), subject, self_signed);
1732}
1733
Shawn Willden4315e132022-03-20 12:49:46 -06001734void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1735 VerifiedBoot verified_boot_state,
1736 const vector<uint8_t>& verified_boot_hash) {
1737 char property_value[PROPERTY_VALUE_MAX] = {};
1738
1739 if (avb_verification_enabled()) {
1740 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1741 string prop_string(property_value);
1742 EXPECT_EQ(prop_string.size(), 64);
1743 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1744
1745 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1746 if (!strcmp(property_value, "unlocked")) {
1747 EXPECT_FALSE(device_locked);
1748 } else {
1749 EXPECT_TRUE(device_locked);
1750 }
1751
1752 // Check that the device is locked if not debuggable, e.g., user build
1753 // images in CTS. For VTS, debuggable images are used to allow adb root
1754 // and the device is unlocked.
1755 if (!property_get_bool("ro.debuggable", false)) {
1756 EXPECT_TRUE(device_locked);
1757 } else {
1758 EXPECT_FALSE(device_locked);
1759 }
1760 }
1761
1762 // Verified boot key should be all 0's if the boot state is not verified or self signed
1763 std::string empty_boot_key(32, '\0');
1764 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1765 verified_boot_key.size());
1766 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1767 if (!strcmp(property_value, "green")) {
1768 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1769 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1770 verified_boot_key.size()));
1771 } else if (!strcmp(property_value, "yellow")) {
1772 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1773 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1774 verified_boot_key.size()));
1775 } else if (!strcmp(property_value, "orange")) {
1776 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1777 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1778 verified_boot_key.size()));
1779 } else if (!strcmp(property_value, "red")) {
1780 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1781 } else {
1782 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1783 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1784 verified_boot_key.size()));
1785 }
1786}
1787
David Drysdale7dff4fc2021-12-10 10:10:52 +00001788bool verify_attestation_record(int32_t aidl_version, //
1789 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001790 const string& app_id, //
1791 AuthorizationSet expected_sw_enforced, //
1792 AuthorizationSet expected_hw_enforced, //
1793 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001794 const vector<uint8_t>& attestation_cert,
1795 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001796 X509_Ptr cert(parse_cert_blob(attestation_cert));
1797 EXPECT_TRUE(!!cert.get());
1798 if (!cert.get()) return false;
1799
Rajesh Nyamagoude98263e2023-02-09 20:36:33 +00001800 // Make sure CRL Distribution Points extension is not present in a certificate
1801 // containing attestation record.
1802 check_crl_distribution_points_extension_not_present(cert.get());
1803
Shawn Willden7c130392020-12-21 09:58:22 -07001804 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1805 EXPECT_TRUE(!!attest_rec);
1806 if (!attest_rec) return false;
1807
1808 AuthorizationSet att_sw_enforced;
1809 AuthorizationSet att_hw_enforced;
1810 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001811 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001812 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001813 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001814 vector<uint8_t> att_challenge;
1815 vector<uint8_t> att_unique_id;
1816 vector<uint8_t> att_app_id;
1817
1818 auto error = parse_attestation_record(attest_rec->data, //
1819 attest_rec->length, //
1820 &att_attestation_version, //
1821 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001822 &att_keymint_version, //
1823 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001824 &att_challenge, //
1825 &att_sw_enforced, //
1826 &att_hw_enforced, //
1827 &att_unique_id);
1828 EXPECT_EQ(ErrorCode::OK, error);
1829 if (error != ErrorCode::OK) return false;
1830
David Drysdale7dff4fc2021-12-10 10:10:52 +00001831 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001832 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001833
Selene Huang4f64c222021-04-13 19:54:36 -07001834 // check challenge and app id only if we expects a non-fake certificate
1835 if (challenge.length() > 0) {
1836 EXPECT_EQ(challenge.length(), att_challenge.size());
1837 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1838
1839 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1840 }
Shawn Willden7c130392020-12-21 09:58:22 -07001841
David Drysdale7dff4fc2021-12-10 10:10:52 +00001842 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001843 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001844 EXPECT_EQ(security_level, att_attestation_security_level);
1845
Tri Vob21e6df2023-02-17 14:55:43 -08001846 for (int i = 0; i < att_hw_enforced.size(); i++) {
1847 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1848 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1849 std::string date =
1850 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001851
Tri Vob21e6df2023-02-17 14:55:43 -08001852 // strptime seems to require delimiters, but the tag value will
1853 // be YYYYMMDD
1854 if (date.size() != 8) {
1855 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1856 << " with invalid format (not YYYYMMDD): " << date;
1857 return false;
Shawn Willden7c130392020-12-21 09:58:22 -07001858 }
Tri Vob21e6df2023-02-17 14:55:43 -08001859 date.insert(6, "-");
1860 date.insert(4, "-");
1861 struct tm time;
1862 strptime(date.c_str(), "%Y-%m-%d", &time);
1863
1864 // Day of the month (0-31)
1865 EXPECT_GE(time.tm_mday, 0);
1866 EXPECT_LT(time.tm_mday, 32);
1867 // Months since Jan (0-11)
1868 EXPECT_GE(time.tm_mon, 0);
1869 EXPECT_LT(time.tm_mon, 12);
1870 // Years since 1900
1871 EXPECT_GT(time.tm_year, 110);
1872 EXPECT_LT(time.tm_year, 200);
Shawn Willden7c130392020-12-21 09:58:22 -07001873 }
1874 }
1875
1876 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1877 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1878 // indicates correct encoding. No need to check if it's in both lists, since the
1879 // AuthorizationSet compare below will handle mismatches of tags.
1880 if (security_level == SecurityLevel::SOFTWARE) {
1881 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1882 } else {
1883 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1884 }
1885
Shawn Willden7c130392020-12-21 09:58:22 -07001886 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1887 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1888 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1889 att_hw_enforced.Contains(TAG_KEY_SIZE));
1890 }
1891
1892 // Test root of trust elements
1893 vector<uint8_t> verified_boot_key;
1894 VerifiedBoot verified_boot_state;
1895 bool device_locked;
1896 vector<uint8_t> verified_boot_hash;
1897 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1898 &verified_boot_state, &device_locked, &verified_boot_hash);
1899 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001900 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001901
1902 att_sw_enforced.Sort();
1903 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001904 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001905
1906 att_hw_enforced.Sort();
1907 expected_hw_enforced.Sort();
1908 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1909
David Drysdale565ccc72021-10-11 12:49:50 +01001910 if (unique_id != nullptr) {
1911 *unique_id = att_unique_id;
1912 }
1913
Shawn Willden7c130392020-12-21 09:58:22 -07001914 return true;
1915}
1916
1917string bin2hex(const vector<uint8_t>& data) {
1918 string retval;
1919 retval.reserve(data.size() * 2 + 1);
1920 for (uint8_t byte : data) {
1921 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1922 retval.push_back(nibble2hex[0x0F & byte]);
1923 }
1924 return retval;
1925}
1926
David Drysdalef0d516d2021-03-22 07:51:43 +00001927AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1928 AuthorizationSet authList;
1929 for (auto& entry : key_characteristics) {
1930 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1931 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1932 authList.push_back(AuthorizationSet(entry.authorizations));
1933 }
1934 }
1935 return authList;
1936}
1937
1938AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1939 AuthorizationSet authList;
1940 for (auto& entry : key_characteristics) {
1941 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1942 entry.securityLevel == SecurityLevel::KEYSTORE) {
1943 authList.push_back(AuthorizationSet(entry.authorizations));
1944 }
1945 }
1946 return authList;
1947}
1948
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001949AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1950 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001951 std::stringstream cert_data;
1952
1953 for (size_t i = 0; i < chain.size(); ++i) {
1954 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1955
1956 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1957 X509_Ptr signing_cert;
1958 if (i < chain.size() - 1) {
1959 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1960 } else {
1961 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1962 }
1963 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1964
1965 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1966 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1967
1968 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1969 return AssertionFailure()
1970 << "Verification of certificate " << i << " failed "
1971 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1972 << cert_data.str();
1973 }
1974
1975 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1976 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001977 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001978 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1979 << " Signer subject is " << signer_subj
1980 << " Issuer subject is " << cert_issuer << endl
1981 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001982 }
Shawn Willden7c130392020-12-21 09:58:22 -07001983 }
1984
1985 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1986 return AssertionSuccess();
1987}
1988
1989X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1990 const uint8_t* p = blob.data();
1991 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1992}
1993
Tri Voec50ee12023-02-14 16:29:53 -08001994// Extract attestation record from cert. Returned object is still part of cert; don't free it
1995// separately.
1996ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
1997 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
1998 EXPECT_TRUE(!!oid.get());
1999 if (!oid.get()) return nullptr;
2000
2001 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
2002 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
2003 if (location == -1) return nullptr;
2004
2005 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
2006 EXPECT_TRUE(!!attest_rec_ext)
2007 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
2008 if (!attest_rec_ext) return nullptr;
2009
2010 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
2011 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
2012 return attest_rec;
2013}
2014
David Drysdalef0d516d2021-03-22 07:51:43 +00002015vector<uint8_t> make_name_from_str(const string& name) {
2016 X509_NAME_Ptr x509_name(X509_NAME_new());
2017 EXPECT_TRUE(x509_name.get() != nullptr);
2018 if (!x509_name) return {};
2019
2020 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
2021 "CN", //
2022 MBSTRING_ASC,
2023 reinterpret_cast<const uint8_t*>(name.c_str()),
2024 -1, // len
2025 -1, // loc
2026 0 /* set */));
2027
2028 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
2029 EXPECT_GT(len, 0);
2030
2031 vector<uint8_t> retval(len);
2032 uint8_t* p = retval.data();
2033 i2d_X509_NAME(x509_name.get(), &p);
2034
2035 return retval;
2036}
2037
David Drysdale4dc01072021-04-01 12:17:35 +01002038namespace {
2039
2040void check_cose_key(const vector<uint8_t>& data, bool testMode) {
2041 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
2042 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2043
2044 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
2045 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00002046 EXPECT_THAT(
2047 cppbor::prettyPrint(parsedPayload.get()),
2048 MatchesRegex("\\{\n"
2049 " 1 : 2,\n" // kty: EC2
2050 " 3 : -7,\n" // alg: ES256
2051 " -1 : 1,\n" // EC id: P256
2052 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
2053 // sequence of 32 hexadecimal bytes, enclosed in braces and
2054 // separated by commas. In this case, some Ed25519 public key.
2055 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
2056 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
2057 " -70000 : null,\n" // test marker
2058 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01002059 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00002060 EXPECT_THAT(
2061 cppbor::prettyPrint(parsedPayload.get()),
2062 MatchesRegex("\\{\n"
2063 " 1 : 2,\n" // kty: EC2
2064 " 3 : -7,\n" // alg: ES256
2065 " -1 : 1,\n" // EC id: P256
2066 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
2067 // sequence of 32 hexadecimal bytes, enclosed in braces and
2068 // separated by commas. In this case, some Ed25519 public key.
2069 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
2070 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
2071 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01002072 }
2073}
2074
2075} // namespace
2076
2077void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
2078 vector<uint8_t>* payload_value) {
2079 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
2080 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
2081
2082 ASSERT_NE(coseMac0->asArray(), nullptr);
2083 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
2084
2085 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
2086 ASSERT_NE(protParms, nullptr);
2087
2088 // Header label:value of 'alg': HMAC-256
2089 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
2090
2091 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
2092 ASSERT_NE(unprotParms, nullptr);
2093 ASSERT_EQ(unprotParms->size(), 0);
2094
2095 // The payload is a bstr holding an encoded COSE_Key
2096 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
2097 ASSERT_NE(payload, nullptr);
2098 check_cose_key(payload->value(), testMode);
2099
2100 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
2101 ASSERT_TRUE(coseMac0Tag);
2102 auto extractedTag = coseMac0Tag->value();
2103 EXPECT_EQ(extractedTag.size(), 32U);
2104
2105 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07002106 auto macFunction = [](const cppcose::bytevec& input) {
2107 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
2108 };
2109 auto testTag =
2110 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01002111 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
2112
2113 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07002114 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01002115 } else {
Seth Moore026bb742021-04-30 11:41:18 -07002116 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002117 }
2118 if (payload_value != nullptr) {
2119 *payload_value = payload->value();
2120 }
2121}
2122
2123void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2124 // Extract x and y affine coordinates from the encoded Cose_Key.
2125 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2126 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2127 auto coseKey = parsedPayload->asMap();
2128 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2129 ASSERT_NE(xItem->asBstr(), nullptr);
2130 vector<uint8_t> x = xItem->asBstr()->value();
2131 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2132 ASSERT_NE(yItem->asBstr(), nullptr);
2133 vector<uint8_t> y = yItem->asBstr()->value();
2134
2135 // Concatenate: 0x04 (uncompressed form marker) | x | y
2136 vector<uint8_t> pubKeyData{0x04};
2137 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2138 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2139
2140 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2141 ASSERT_NE(ecKey, nullptr);
2142 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2143 ASSERT_NE(group, nullptr);
2144 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2145 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2146 ASSERT_NE(point, nullptr);
2147 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2148 nullptr),
2149 1);
2150 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2151
2152 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2153 ASSERT_NE(pubKey, nullptr);
2154 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2155 *signingKey = std::move(pubKey);
2156}
2157
Max Biresa97ec692022-11-21 23:37:54 -08002158void device_id_attestation_vsr_check(const ErrorCode& result) {
Shawn Willden1a545db2023-02-22 14:32:33 -07002159 if (get_vsr_api_level() > __ANDROID_API_T__) {
Max Biresa97ec692022-11-21 23:37:54 -08002160 ASSERT_FALSE(result == ErrorCode::INVALID_TAG)
2161 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2162 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2163 << "be used for a case where updateAad() is called after update(). As of "
2164 << "VSR-14, this is now enforced as an error.";
2165 }
2166}
2167
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002168// Check whether the given named feature is available.
2169bool check_feature(const std::string& name) {
2170 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002171 ::android::sp<::android::IBinder> binder(
2172 sm->waitForService(::android::String16("package_native")));
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002173 if (binder == nullptr) {
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002174 GTEST_LOG_(ERROR) << "waitForService package_native failed";
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002175 return false;
2176 }
2177 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2178 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2179 if (packageMgr == nullptr) {
2180 GTEST_LOG_(ERROR) << "Cannot find package manager";
2181 return false;
2182 }
2183 bool hasFeature = false;
2184 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2185 if (!status.isOk()) {
2186 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2187 return false;
2188 }
2189 return hasFeature;
2190}
2191
Selene Huang31ab4042020-04-29 04:22:39 -07002192} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002193
Janis Danisevskis24c04702020-12-16 18:28:39 -08002194} // namespace aidl::android::hardware::security::keymint