blob: 087f7632b044dcaa95f181a641cf65c78a44794e [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 Drysdale6c9bdb82024-01-23 09:32:04 +000067// Possible values for the feature version. Assumes that future KeyMint versions
68// will continue with the 100 * AIDL_version numbering scheme.
69//
70// Must be kept in numerically increasing order.
71const int32_t kFeatureVersions[] = {10, 11, 20, 30, 40, 41, 100, 200,
72 300, 400, 500, 600, 700, 800, 900};
73
David Drysdale37af4b32021-05-14 16:46:59 +010074// Invalid value for a patchlevel (which is of form YYYYMMDD).
75const uint32_t kInvalidPatchlevel = 99998877;
76
David Drysdaledf8f52e2021-05-06 08:10:58 +010077// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
78// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
79const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
80
Shawn Willden20732262023-04-21 16:36:00 -060081size_t count_tag_invalid_entries(const std::vector<KeyParameter>& authorizations) {
82 return std::count_if(authorizations.begin(), authorizations.end(),
83 [](const KeyParameter& e) -> bool { return e.tag == Tag::INVALID; });
84}
85
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070087// Predicate for testing basic characteristics validity in generation or import.
88bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
Prashant Patil2114dca2023-09-21 14:57:10 +000089 const vector<KeyCharacteristics>& key_characteristics,
90 int32_t aidl_version) {
Shawn Willden7f424372021-01-10 18:06:50 -070091 if (key_characteristics.empty()) return false;
92
93 std::unordered_set<SecurityLevel> levels_seen;
94 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070095 if (entry.authorizations.empty()) {
96 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
97 return false;
98 }
Shawn Willden7f424372021-01-10 18:06:50 -070099
Prashant Patil2114dca2023-09-21 14:57:10 +0000100 // There was no test to assert that INVALID tag should not present in authorization list
101 // before Keymint V3, so there are some Keymint implementations where asserting for INVALID
102 // tag fails(b/297306437), hence skipping for Keymint < 3.
103 if (aidl_version >= 3) {
104 EXPECT_EQ(count_tag_invalid_entries(entry.authorizations), 0);
105 }
Shawn Willden20732262023-04-21 16:36:00 -0600106
Qi Wubeefae42021-01-28 23:16:37 +0800107 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
108 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
109
Seth Moore2a9a00e2021-08-04 16:31:52 -0700110 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
111 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
112 return false;
113 }
Shawn Willden7f424372021-01-10 18:06:50 -0700114 levels_seen.insert(entry.securityLevel);
115
116 // Generally, we should only have one entry, at the same security level as the KM
117 // instance. There is an exception: StrongBox KM can have some authorizations that are
118 // enforced by the TEE.
119 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
120 (secLevel == SecurityLevel::STRONGBOX &&
121 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
122
Seth Moore2a9a00e2021-08-04 16:31:52 -0700123 if (!isExpectedSecurityLevel) {
124 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
125 return false;
126 }
Shawn Willden7f424372021-01-10 18:06:50 -0700127 }
128 return true;
129}
130
Rajesh Nyamagoude98263e2023-02-09 20:36:33 +0000131void check_crl_distribution_points_extension_not_present(X509* certificate) {
132 ASN1_OBJECT_Ptr crl_dp_oid(OBJ_txt2obj(kCrlDPOid, 1 /* dotted string format */));
133 ASSERT_TRUE(crl_dp_oid.get());
134
135 int location =
136 X509_get_ext_by_OBJ(certificate, crl_dp_oid.get(), -1 /* search from beginning */);
137 ASSERT_EQ(location, -1);
138}
139
David Drysdale7dff4fc2021-12-10 10:10:52 +0000140void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
141 // Version numbers in attestation extensions should be a multiple of 100.
142 EXPECT_EQ(attestation_version % 100, 0);
143
144 // The multiplier should never be higher than the AIDL version, but can be less
145 // (for example, if the implementation is from an earlier version but the HAL service
146 // uses the default libraries and so reports the current AIDL version).
147 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
148}
149
Shawn Willden7c130392020-12-21 09:58:22 -0700150bool avb_verification_enabled() {
151 char value[PROPERTY_VALUE_MAX];
152 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
153}
154
155char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
156 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
157
158// Attestations don't contain everything in key authorization lists, so we need to filter the key
159// lists to produce the lists that we expect to match the attestations.
160auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100161 Tag::CREATION_DATETIME,
162 Tag::HARDWARE_TYPE,
163 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700164};
165
166AuthorizationSet filtered_tags(const AuthorizationSet& set) {
167 AuthorizationSet filtered;
168 std::remove_copy_if(
169 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
170 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
171 kTagsToFilter.end();
172 });
173 return filtered;
174}
175
David Drysdale300b5552021-05-20 12:05:26 +0100176// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
177void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
178 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
179 [](const auto& entry) {
180 return entry.securityLevel == SecurityLevel::KEYSTORE;
181 }),
182 characteristics->end());
183}
184
Shawn Willden7c130392020-12-21 09:58:22 -0700185string x509NameToStr(X509_NAME* name) {
186 char* s = X509_NAME_oneline(name, nullptr, 0);
187 string retval(s);
188 OPENSSL_free(s);
189 return retval;
190}
191
Shawn Willden7f424372021-01-10 18:06:50 -0700192} // namespace
193
Shawn Willden7c130392020-12-21 09:58:22 -0700194bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
195bool KeyMintAidlTestBase::dump_Attestations = false;
David Drysdale9f5c0c52022-11-03 15:10:16 +0000196std::string KeyMintAidlTestBase::keyblob_dir;
Tommy Chiu025f3c52023-05-15 06:23:44 +0000197std::optional<bool> KeyMintAidlTestBase::expect_upgrade = std::nullopt;
Shawn Willden7c130392020-12-21 09:58:22 -0700198
David Drysdale1b9febc2023-06-07 13:43:24 +0100199KeyBlobDeleter::~KeyBlobDeleter() {
200 if (key_blob_.empty()) {
201 return;
202 }
203 Status result = keymint_->deleteKey(key_blob_);
204 key_blob_.clear();
205 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << "\n";
206 ErrorCode rc = GetReturnErrorCode(result);
207 EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED) << result << "\n";
208}
209
David Drysdale37af4b32021-05-14 16:46:59 +0100210uint32_t KeyMintAidlTestBase::boot_patch_level(
211 const vector<KeyCharacteristics>& key_characteristics) {
212 // The boot patchlevel is not available as a property, but should be present
213 // in the key characteristics of any created key.
214 AuthorizationSet allAuths;
215 for (auto& entry : key_characteristics) {
216 allAuths.push_back(AuthorizationSet(entry.authorizations));
217 }
218 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
219 if (patchlevel.has_value()) {
220 return patchlevel.value();
221 } else {
222 // No boot patchlevel is available. Return a value that won't match anything
223 // and so will trigger test failures.
224 return kInvalidPatchlevel;
225 }
226}
227
228uint32_t KeyMintAidlTestBase::boot_patch_level() {
229 return boot_patch_level(key_characteristics_);
230}
231
Prashant Patil88ad1892022-03-15 16:31:02 +0000232/**
233 * An API to determine device IDs attestation is required or not,
234 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
235 */
236bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700237 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= __ANDROID_API_T__;
Prashant Patil88ad1892022-03-15 16:31:02 +0000238}
239
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000240/**
241 * An API to determine second IMEI ID attestation is required or not,
242 * which is supported for KeyMint version 3 or first_api_level greater than 33.
243 */
244bool KeyMintAidlTestBase::isSecondImeiIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700245 return AidlVersion() >= 3 && property_get_int32("ro.vendor.api_level", 0) > __ANDROID_API_T__;
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000246}
247
David Drysdale42fe1892021-10-14 14:43:46 +0100248bool KeyMintAidlTestBase::Curve25519Supported() {
249 // Strongbox never supports curve 25519.
250 if (SecLevel() == SecurityLevel::STRONGBOX) {
251 return false;
252 }
253
254 // Curve 25519 was included in version 2 of the KeyMint interface.
255 int32_t version = 0;
256 auto status = keymint_->getInterfaceVersion(&version);
257 if (!status.isOk()) {
258 ADD_FAILURE() << "Failed to determine interface version";
259 }
260 return version >= 2;
261}
262
Janis Danisevskis24c04702020-12-16 18:28:39 -0800263void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700264 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800265 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700266
267 KeyMintHardwareInfo info;
268 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
269
270 securityLevel_ = info.securityLevel;
271 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
272 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100273 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700274
275 os_version_ = getOsVersion();
276 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100277 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700278}
279
Prashant Patil2114dca2023-09-21 14:57:10 +0000280int32_t KeyMintAidlTestBase::AidlVersion() const {
David Drysdale7dff4fc2021-12-10 10:10:52 +0000281 int32_t version = 0;
282 auto status = keymint_->getInterfaceVersion(&version);
283 if (!status.isOk()) {
284 ADD_FAILURE() << "Failed to determine interface version";
285 }
286 return version;
287}
288
Selene Huang31ab4042020-04-29 04:22:39 -0700289void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800290 if (AServiceManager_isDeclared(GetParam().c_str())) {
291 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
292 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
293 } else {
294 InitializeKeyMint(nullptr);
295 }
Selene Huang31ab4042020-04-29 04:22:39 -0700296}
297
298ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700299 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700300 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700301 vector<KeyCharacteristics>* key_characteristics,
302 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700303 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
304 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700305 << "Previous characteristics not deleted before generating key. Test bug.";
306
Shawn Willden7f424372021-01-10 18:06:50 -0700307 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700308 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700309 if (result.isOk()) {
Prashant Patil2114dca2023-09-21 14:57:10 +0000310 EXPECT_PRED3(KeyCharacteristicsBasicallyValid, SecLevel(),
311 creationResult.keyCharacteristics, AidlVersion());
Shawn Willden7f424372021-01-10 18:06:50 -0700312 EXPECT_GT(creationResult.keyBlob.size(), 0);
313 *key_blob = std::move(creationResult.keyBlob);
314 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700315 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700316
317 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
318 EXPECT_TRUE(algorithm);
319 if (algorithm &&
320 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700321 EXPECT_GE(cert_chain->size(), 1);
322 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
323 if (attest_key) {
324 EXPECT_EQ(cert_chain->size(), 1);
325 } else {
326 EXPECT_GT(cert_chain->size(), 1);
327 }
328 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700329 } else {
330 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700331 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700332 }
Selene Huang31ab4042020-04-29 04:22:39 -0700333 }
334
335 return GetReturnErrorCode(result);
336}
337
Shawn Willden7c130392020-12-21 09:58:22 -0700338ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
339 const optional<AttestationKey>& attest_key) {
340 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700341}
342
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000343ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
344 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
345 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
346 vector<Certificate>* cert_chain) {
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +0000347 skipAttestKeyTest();
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000348 AttestationKey attest_key;
349 vector<Certificate> attest_cert_chain;
350 vector<KeyCharacteristics> attest_key_characteristics;
351 // Generate a key with self signed attestation.
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +0000352 auto error = GenerateAttestKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
353 &attest_key_characteristics, &attest_cert_chain);
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000354 if (error != ErrorCode::OK) {
355 return error;
356 }
357
358 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
359 // Generate a key, by passing the above self signed attestation key as attest key.
360 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
361 if (error == ErrorCode::OK) {
362 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
363 cert_chain->push_back(attest_cert_chain[0]);
364 }
365 return error;
366}
367
Selene Huang31ab4042020-04-29 04:22:39 -0700368ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
369 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700370 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700371 Status result;
372
Shawn Willden7f424372021-01-10 18:06:50 -0700373 cert_chain_.clear();
374 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700375 key_blob->clear();
376
Shawn Willden7f424372021-01-10 18:06:50 -0700377 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700378 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700379 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700380 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700381
382 if (result.isOk()) {
Prashant Patil2114dca2023-09-21 14:57:10 +0000383 EXPECT_PRED3(KeyCharacteristicsBasicallyValid, SecLevel(),
384 creationResult.keyCharacteristics, AidlVersion());
Shawn Willden7f424372021-01-10 18:06:50 -0700385 EXPECT_GT(creationResult.keyBlob.size(), 0);
386
387 *key_blob = std::move(creationResult.keyBlob);
388 *key_characteristics = std::move(creationResult.keyCharacteristics);
389 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700390
391 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
392 EXPECT_TRUE(algorithm);
393 if (algorithm &&
394 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
395 EXPECT_GE(cert_chain_.size(), 1);
396 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
397 } else {
398 // For symmetric keys there should be no certificates.
399 EXPECT_EQ(cert_chain_.size(), 0);
400 }
Selene Huang31ab4042020-04-29 04:22:39 -0700401 }
402
403 return GetReturnErrorCode(result);
404}
405
406ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
407 const string& key_material) {
408 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
409}
410
411ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
412 const AuthorizationSet& wrapping_key_desc,
413 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100414 const AuthorizationSet& unwrapping_params,
415 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700416 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
417
Shawn Willden7f424372021-01-10 18:06:50 -0700418 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700419
Shawn Willden7f424372021-01-10 18:06:50 -0700420 KeyCreationResult creationResult;
421 Status result = keymint_->importWrappedKey(
422 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
423 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100424 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700425
426 if (result.isOk()) {
Prashant Patil2114dca2023-09-21 14:57:10 +0000427 EXPECT_PRED3(KeyCharacteristicsBasicallyValid, SecLevel(),
428 creationResult.keyCharacteristics, AidlVersion());
Shawn Willden7f424372021-01-10 18:06:50 -0700429 EXPECT_GT(creationResult.keyBlob.size(), 0);
430
431 key_blob_ = std::move(creationResult.keyBlob);
432 key_characteristics_ = std::move(creationResult.keyCharacteristics);
433 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700434
435 AuthorizationSet allAuths;
436 for (auto& entry : key_characteristics_) {
437 allAuths.push_back(AuthorizationSet(entry.authorizations));
438 }
439 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
440 EXPECT_TRUE(algorithm);
441 if (algorithm &&
442 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
443 EXPECT_GE(cert_chain_.size(), 1);
444 } else {
445 // For symmetric keys there should be no certificates.
446 EXPECT_EQ(cert_chain_.size(), 0);
447 }
Selene Huang31ab4042020-04-29 04:22:39 -0700448 }
449
450 return GetReturnErrorCode(result);
451}
452
David Drysdale300b5552021-05-20 12:05:26 +0100453ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
454 const vector<uint8_t>& app_id,
455 const vector<uint8_t>& app_data,
456 vector<KeyCharacteristics>* key_characteristics) {
457 Status result =
458 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
459 return GetReturnErrorCode(result);
460}
461
462ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
463 vector<KeyCharacteristics>* key_characteristics) {
464 vector<uint8_t> empty_app_id, empty_app_data;
465 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
466}
467
468void KeyMintAidlTestBase::CheckCharacteristics(
469 const vector<uint8_t>& key_blob,
470 const vector<KeyCharacteristics>& generate_characteristics) {
471 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
472 // generateKey() should be excluded, as KeyMint will have no record of them.
473 // This applies to CREATION_DATETIME in particular.
474 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
475 strip_keystore_tags(&expected_characteristics);
476
477 vector<KeyCharacteristics> retrieved;
478 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
479 EXPECT_EQ(expected_characteristics, retrieved);
480}
481
482void KeyMintAidlTestBase::CheckAppIdCharacteristics(
483 const vector<uint8_t>& key_blob, std::string_view app_id_string,
484 std::string_view app_data_string,
485 const vector<KeyCharacteristics>& generate_characteristics) {
486 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
487 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
488 strip_keystore_tags(&expected_characteristics);
489
490 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
491 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
492 vector<KeyCharacteristics> retrieved;
493 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
494 EXPECT_EQ(expected_characteristics, retrieved);
495
496 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
497 vector<uint8_t> empty;
498 vector<KeyCharacteristics> not_retrieved;
499 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
500 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
501 EXPECT_EQ(not_retrieved.size(), 0);
502
503 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
504 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
505 EXPECT_EQ(not_retrieved.size(), 0);
506
507 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
508 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
509 EXPECT_EQ(not_retrieved.size(), 0);
510}
511
Selene Huang31ab4042020-04-29 04:22:39 -0700512ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
513 Status result = keymint_->deleteKey(*key_blob);
514 if (!keep_key_blob) {
515 *key_blob = vector<uint8_t>();
516 }
517
Janis Danisevskis24c04702020-12-16 18:28:39 -0800518 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700519 return GetReturnErrorCode(result);
520}
521
522ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
523 return DeleteKey(&key_blob_, keep_key_blob);
524}
525
526ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
527 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800528 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700529 return GetReturnErrorCode(result);
530}
531
David Drysdaled2cc8c22021-04-15 13:29:45 +0100532ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
533 Status result = keymint_->destroyAttestationIds();
534 return GetReturnErrorCode(result);
535}
536
Selene Huang31ab4042020-04-29 04:22:39 -0700537void KeyMintAidlTestBase::CheckedDeleteKey() {
David Drysdale1b9febc2023-06-07 13:43:24 +0100538 ErrorCode result = DeleteKey(&key_blob_, /* keep_key_blob = */ false);
539 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700540}
541
542ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
543 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800544 AuthorizationSet* out_params,
545 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700546 SCOPED_TRACE("Begin");
547 Status result;
548 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100549 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700550
551 if (result.isOk()) {
552 *out_params = out.params;
553 challenge_ = out.challenge;
554 op = out.operation;
555 }
556
557 return GetReturnErrorCode(result);
558}
559
560ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
561 const AuthorizationSet& in_params,
David Drysdale28fa9312023-02-01 14:53:01 +0000562 AuthorizationSet* out_params,
563 std::optional<HardwareAuthToken> hat) {
Selene Huang31ab4042020-04-29 04:22:39 -0700564 SCOPED_TRACE("Begin");
565 Status result;
566 BeginResult out;
567
David Drysdale28fa9312023-02-01 14:53:01 +0000568 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), hat, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700569
570 if (result.isOk()) {
571 *out_params = out.params;
572 challenge_ = out.challenge;
573 op_ = out.operation;
574 }
575
576 return GetReturnErrorCode(result);
577}
578
579ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
580 AuthorizationSet* out_params) {
581 SCOPED_TRACE("Begin");
582 EXPECT_EQ(nullptr, op_);
583 return Begin(purpose, key_blob_, in_params, out_params);
584}
585
586ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
587 SCOPED_TRACE("Begin");
588 AuthorizationSet out_params;
589 ErrorCode result = Begin(purpose, in_params, &out_params);
590 EXPECT_TRUE(out_params.empty());
591 return result;
592}
593
Shawn Willden92d79c02021-02-19 07:31:55 -0700594ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
595 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
596 {} /* hardwareAuthToken */,
597 {} /* verificationToken */));
598}
599
600ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700601 SCOPED_TRACE("Update");
602
603 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700604 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700605
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800606 EXPECT_NE(op_, nullptr);
607 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
608
Shawn Willden92d79c02021-02-19 07:31:55 -0700609 std::vector<uint8_t> o_put;
610 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700611
David Drysdalefeab5d92022-01-06 15:46:23 +0000612 if (result.isOk()) {
613 output->append(o_put.begin(), o_put.end());
614 } else {
615 // Failure always terminates the operation.
616 op_ = {};
617 }
Selene Huang31ab4042020-04-29 04:22:39 -0700618
619 return GetReturnErrorCode(result);
620}
621
David Drysdale28fa9312023-02-01 14:53:01 +0000622ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, string* output,
623 std::optional<HardwareAuthToken> hat,
624 std::optional<secureclock::TimeStampToken> time_token) {
Selene Huang31ab4042020-04-29 04:22:39 -0700625 SCOPED_TRACE("Finish");
626 Status result;
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 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700632 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
David Drysdale28fa9312023-02-01 14:53:01 +0000633 vector<uint8_t>(signature.begin(), signature.end()), hat, time_token,
634 {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700635
Shawn Willden92d79c02021-02-19 07:31:55 -0700636 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700637
Shawn Willden92d79c02021-02-19 07:31:55 -0700638 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700639 return GetReturnErrorCode(result);
640}
641
Janis Danisevskis24c04702020-12-16 18:28:39 -0800642ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700643 SCOPED_TRACE("Abort");
644
645 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700646 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700647
648 Status retval = op->abort();
649 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800650 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700651}
652
653ErrorCode KeyMintAidlTestBase::Abort() {
654 SCOPED_TRACE("Abort");
655
656 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700657 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700658
659 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800660 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700661}
662
663void KeyMintAidlTestBase::AbortIfNeeded() {
664 SCOPED_TRACE("AbortIfNeeded");
665 if (op_) {
666 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800667 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700668 }
669}
670
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000671auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
672 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700673 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000674 AuthorizationSet begin_out_params;
675 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700676 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000677
678 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700679 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000680}
681
Selene Huang31ab4042020-04-29 04:22:39 -0700682string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
683 const string& message, const AuthorizationSet& in_params,
684 AuthorizationSet* out_params) {
685 SCOPED_TRACE("ProcessMessage");
686 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700687 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700688 EXPECT_EQ(ErrorCode::OK, result);
689 if (result != ErrorCode::OK) {
690 return "";
691 }
692
693 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700694 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700695 return output;
696}
697
698string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
699 const AuthorizationSet& params) {
700 SCOPED_TRACE("SignMessage");
701 AuthorizationSet out_params;
702 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
703 EXPECT_TRUE(out_params.empty());
704 return signature;
705}
706
707string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
708 SCOPED_TRACE("SignMessage");
709 return SignMessage(key_blob_, message, params);
710}
711
712string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
713 SCOPED_TRACE("MacMessage");
714 return SignMessage(
715 key_blob_, message,
716 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
717}
718
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530719void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
720 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000721 auto builder = AuthorizationSetBuilder()
722 .Authorization(TAG_NO_AUTH_REQUIRED)
723 .AesEncryptionKey(128)
724 .BlockMode(block_mode)
725 .Padding(PaddingMode::NONE);
726 if (block_mode == BlockMode::GCM) {
727 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
728 }
729 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530730
731 for (int increment = 1; increment <= message_size; ++increment) {
732 string message(message_size, 'a');
733 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
734 if (block_mode == BlockMode::GCM) {
735 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
736 }
737
738 AuthorizationSet output_params;
739 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
740
741 string ciphertext;
742 string to_send;
743 for (size_t i = 0; i < message.size(); i += increment) {
744 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
745 }
746 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
747 << "Error sending " << to_send << " with block mode " << block_mode;
748
749 switch (block_mode) {
750 case BlockMode::GCM:
751 EXPECT_EQ(message.size() + 16, ciphertext.size());
752 break;
753 case BlockMode::CTR:
754 EXPECT_EQ(message.size(), ciphertext.size());
755 break;
756 case BlockMode::CBC:
757 case BlockMode::ECB:
758 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
759 break;
760 }
761
762 auto iv = output_params.GetTagValue(TAG_NONCE);
763 switch (block_mode) {
764 case BlockMode::CBC:
765 case BlockMode::GCM:
766 case BlockMode::CTR:
767 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
768 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
769 params.push_back(TAG_NONCE, iv->get());
770 break;
771
772 case BlockMode::ECB:
773 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
774 break;
775 }
776
777 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
778 << "Decrypt begin() failed for block mode " << block_mode;
779
780 string plaintext;
781 for (size_t i = 0; i < ciphertext.size(); i += increment) {
782 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
783 }
784 ErrorCode error = Finish(to_send, &plaintext);
785 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
786 << " and increment " << increment;
787 if (error == ErrorCode::OK) {
788 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
789 << " and increment " << increment;
790 }
791 }
792}
793
Prashant Patildd5f7f02022-07-06 18:58:07 +0000794void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
795 PaddingMode padding_mode, const string& iv,
796 const string& plaintext,
797 const string& exp_cipher_text) {
798 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
799 auto auth_set = AuthorizationSetBuilder()
800 .Authorization(TAG_NO_AUTH_REQUIRED)
801 .AesEncryptionKey(key.size() * 8)
802 .BlockMode(block_mode)
803 .Padding(padding_mode);
804 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
805 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
806 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
807
808 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
809 exp_cipher_text);
810}
811
812void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
813 PaddingMode padding_mode, const string& iv,
814 const string& plaintext,
815 const string& exp_cipher_text) {
816 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
817 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
818 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
819 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
820 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
821
822 AuthorizationSet output_params;
823 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
824
825 string actual_ciphertext;
826 if (is_stream_cipher) {
827 // Assert that a 1 byte of output is produced for 1 byte of input.
828 // Every input byte produces an output byte.
829 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
830 string ciphertext;
831 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
832 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
833 // we relax this API restriction for them.
834 if (SecLevel() != SecurityLevel::STRONGBOX) {
835 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
836 }
837 actual_ciphertext.append(ciphertext);
838 }
839 string ciphertext;
840 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
841 if (SecLevel() != SecurityLevel::STRONGBOX) {
842 string expected_final_output;
843 if (is_authenticated_cipher) {
844 expected_final_output = exp_cipher_text.substr(plaintext.size());
845 }
846 EXPECT_EQ(expected_final_output, ciphertext);
847 }
848 actual_ciphertext.append(ciphertext);
849 } else {
850 // Assert that a block of output is produced once a full block of input is provided.
851 // Every input block produces an output block.
852 bool compare_output = true;
853 string additional_information;
854 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
855 if (SecLevel() == SecurityLevel::STRONGBOX) {
856 // This is known to be broken on older vendor implementations.
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Sri2ce542d2023-07-12 02:06:33 +0000857 if (vendor_api_level <= __ANDROID_API_U__) {
Prashant Patildd5f7f02022-07-06 18:58:07 +0000858 compare_output = false;
859 } else {
860 additional_information = " (b/194134359) ";
861 }
862 }
863 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
864 string ciphertext;
865 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
866 if (compare_output) {
867 if ((plaintext_index % block_size) == block_size - 1) {
868 // Update is expected to have output a new block
869 EXPECT_EQ(block_size, ciphertext.size())
870 << "plaintext index: " << plaintext_index << additional_information;
871 } else {
872 // Update is expected to have produced no output
873 EXPECT_EQ(0, ciphertext.size())
874 << "plaintext index: " << plaintext_index << additional_information;
875 }
876 }
877 actual_ciphertext.append(ciphertext);
878 }
879 string ciphertext;
880 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
881 actual_ciphertext.append(ciphertext);
882 }
883 // Regardless of how the completed ciphertext got accumulated, it should match the expected
884 // ciphertext.
885 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
886}
887
Selene Huang31ab4042020-04-29 04:22:39 -0700888void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
889 Digest digest, const string& expected_mac) {
890 SCOPED_TRACE("CheckHmacTestVector");
891 ASSERT_EQ(ErrorCode::OK,
892 ImportKey(AuthorizationSetBuilder()
893 .Authorization(TAG_NO_AUTH_REQUIRED)
894 .HmacKey(key.size() * 8)
895 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
896 .Digest(digest),
897 KeyFormat::RAW, key));
898 string signature = MacMessage(message, digest, expected_mac.size() * 8);
899 EXPECT_EQ(expected_mac, signature)
900 << "Test vector didn't match for key of size " << key.size() << " message of size "
901 << message.size() << " and digest " << digest;
902 CheckedDeleteKey();
903}
904
905void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
906 const string& message,
907 const string& expected_ciphertext) {
908 SCOPED_TRACE("CheckAesCtrTestVector");
909 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
910 .Authorization(TAG_NO_AUTH_REQUIRED)
911 .AesEncryptionKey(key.size() * 8)
912 .BlockMode(BlockMode::CTR)
913 .Authorization(TAG_CALLER_NONCE)
914 .Padding(PaddingMode::NONE),
915 KeyFormat::RAW, key));
916
917 auto params = AuthorizationSetBuilder()
918 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
919 .BlockMode(BlockMode::CTR)
920 .Padding(PaddingMode::NONE);
921 AuthorizationSet out_params;
922 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
923 EXPECT_EQ(expected_ciphertext, ciphertext);
924}
925
926void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
927 PaddingMode padding_mode, const string& key,
928 const string& iv, const string& input,
929 const string& expected_output) {
930 auto authset = AuthorizationSetBuilder()
931 .TripleDesEncryptionKey(key.size() * 7)
932 .BlockMode(block_mode)
933 .Authorization(TAG_NO_AUTH_REQUIRED)
934 .Padding(padding_mode);
935 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
936 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
937 ASSERT_GT(key_blob_.size(), 0U);
938
939 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
940 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
941 AuthorizationSet output_params;
942 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
943 EXPECT_EQ(expected_output, output);
944}
945
946void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
947 const string& signature, const AuthorizationSet& params) {
948 SCOPED_TRACE("VerifyMessage");
949 AuthorizationSet begin_out_params;
950 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
951
952 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700953 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700954 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700955 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700956}
957
958void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
959 const AuthorizationSet& params) {
960 SCOPED_TRACE("VerifyMessage");
961 VerifyMessage(key_blob_, message, signature, params);
962}
963
David Drysdaledf8f52e2021-05-06 08:10:58 +0100964void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
965 const AuthorizationSet& params) {
966 SCOPED_TRACE("LocalVerifyMessage");
967
David Drysdaledf8f52e2021-05-06 08:10:58 +0100968 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000969 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
970}
971
972void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
973 const string& signature,
974 const AuthorizationSet& params) {
975 // Retrieve the public key from the leaf certificate.
976 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100977 ASSERT_TRUE(key_cert.get());
978 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
979 ASSERT_TRUE(pub_key.get());
980
981 Digest digest = params.GetTagValue(TAG_DIGEST).value();
982 PaddingMode padding = PaddingMode::NONE;
983 auto tag = params.GetTagValue(TAG_PADDING);
984 if (tag.has_value()) {
985 padding = tag.value();
986 }
987
988 if (digest == Digest::NONE) {
989 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100990 case EVP_PKEY_ED25519: {
991 ASSERT_EQ(64, signature.size());
992 uint8_t pub_keydata[32];
993 size_t pub_len = sizeof(pub_keydata);
994 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
995 ASSERT_EQ(sizeof(pub_keydata), pub_len);
996 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
997 message.size(),
998 reinterpret_cast<const uint8_t*>(signature.data()),
999 pub_keydata));
1000 break;
1001 }
1002
David Drysdaledf8f52e2021-05-06 08:10:58 +01001003 case EVP_PKEY_EC: {
1004 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
1005 size_t data_size = std::min(data.size(), message.size());
1006 memcpy(data.data(), message.data(), data_size);
1007 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
1008 ASSERT_TRUE(ecdsa.get());
1009 ASSERT_EQ(1,
1010 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
1011 reinterpret_cast<const uint8_t*>(signature.data()),
1012 signature.size(), ecdsa.get()));
1013 break;
1014 }
1015 case EVP_PKEY_RSA: {
1016 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
1017 size_t data_size = std::min(data.size(), message.size());
1018 memcpy(data.data(), message.data(), data_size);
1019
1020 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1021 ASSERT_TRUE(rsa.get());
1022
1023 size_t key_len = RSA_size(rsa.get());
1024 int openssl_padding = RSA_NO_PADDING;
1025 switch (padding) {
1026 case PaddingMode::NONE:
1027 ASSERT_TRUE(data_size <= key_len);
1028 ASSERT_EQ(key_len, signature.size());
1029 openssl_padding = RSA_NO_PADDING;
1030 break;
1031 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1032 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1033 key_len);
1034 openssl_padding = RSA_PKCS1_PADDING;
1035 break;
1036 default:
1037 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1038 }
1039
1040 vector<uint8_t> decrypted_data(key_len);
1041 int bytes_decrypted = RSA_public_decrypt(
1042 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1043 decrypted_data.data(), rsa.get(), openssl_padding);
1044 ASSERT_GE(bytes_decrypted, 0);
1045
1046 const uint8_t* compare_pos = decrypted_data.data();
1047 size_t bytes_to_compare = bytes_decrypted;
1048 uint8_t zero_check_result = 0;
1049 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1050 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1051 // during verification we should have zeros on the left of the decrypted data.
1052 // Do a constant-time check.
1053 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1054 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1055 ASSERT_EQ(0, zero_check_result);
1056 bytes_to_compare = data_size;
1057 }
1058 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1059 break;
1060 }
1061 default:
1062 ADD_FAILURE() << "Unknown public key type";
1063 }
1064 } else {
1065 EVP_MD_CTX digest_ctx;
1066 EVP_MD_CTX_init(&digest_ctx);
1067 EVP_PKEY_CTX* pkey_ctx;
1068 const EVP_MD* md = openssl_digest(digest);
1069 ASSERT_NE(md, nullptr);
1070 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1071
1072 if (padding == PaddingMode::RSA_PSS) {
1073 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1074 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001075 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001076 }
1077
1078 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1079 reinterpret_cast<const uint8_t*>(message.data()),
1080 message.size()));
1081 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1082 reinterpret_cast<const uint8_t*>(signature.data()),
1083 signature.size()));
1084 EVP_MD_CTX_cleanup(&digest_ctx);
1085 }
1086}
1087
David Drysdale59cae642021-05-12 13:52:03 +01001088string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1089 const AuthorizationSet& params) {
1090 SCOPED_TRACE("LocalRsaEncryptMessage");
1091
1092 // Retrieve the public key from the leaf certificate.
1093 if (cert_chain_.empty()) {
1094 ADD_FAILURE() << "No public key available";
1095 return "Failure";
1096 }
1097 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001098 if (key_cert.get() == nullptr) {
1099 ADD_FAILURE() << "Failed to parse cert";
1100 return "Failure";
1101 }
David Drysdale59cae642021-05-12 13:52:03 +01001102 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001103 if (pub_key.get() == nullptr) {
1104 ADD_FAILURE() << "Failed to retrieve public key";
1105 return "Failure";
1106 }
David Drysdale59cae642021-05-12 13:52:03 +01001107 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001108 if (rsa.get() == nullptr) {
1109 ADD_FAILURE() << "Failed to retrieve RSA public key";
1110 return "Failure";
1111 }
David Drysdale59cae642021-05-12 13:52:03 +01001112
1113 // Retrieve relevant tags.
1114 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001115 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001116 PaddingMode padding = PaddingMode::NONE;
1117
1118 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1119 if (digest_tag.has_value()) digest = digest_tag.value();
1120 auto pad_tag = params.GetTagValue(TAG_PADDING);
1121 if (pad_tag.has_value()) padding = pad_tag.value();
1122 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1123 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1124
1125 const EVP_MD* md = openssl_digest(digest);
1126 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1127
1128 // Set up encryption context.
1129 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1130 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1131 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1132 return "Failure";
1133 }
1134
1135 int rc = -1;
1136 switch (padding) {
1137 case PaddingMode::NONE:
1138 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1139 break;
1140 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1141 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1142 break;
1143 case PaddingMode::RSA_OAEP:
1144 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1145 break;
1146 default:
1147 break;
1148 }
1149 if (rc <= 0) {
1150 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1151 return "Failure";
1152 }
1153 if (padding == PaddingMode::RSA_OAEP) {
1154 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1155 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1156 return "Failure";
1157 }
1158 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1159 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1160 return "Failure";
1161 }
1162 }
1163
1164 // Determine output size.
1165 size_t outlen;
1166 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1167 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1168 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1169 return "Failure";
1170 }
1171
1172 // Left-zero-pad the input if necessary.
1173 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1174 size_t to_encrypt_len = message.size();
1175
1176 std::unique_ptr<string> zero_padded_message;
1177 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1178 zero_padded_message.reset(new string(outlen, '\0'));
1179 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1180 message.size());
1181 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1182 to_encrypt_len = outlen;
1183 }
1184
1185 // Do the encryption.
1186 string output(outlen, '\0');
1187 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1188 to_encrypt_len) <= 0) {
1189 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1190 return "Failure";
1191 }
1192 return output;
1193}
1194
Selene Huang31ab4042020-04-29 04:22:39 -07001195string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1196 const AuthorizationSet& in_params,
1197 AuthorizationSet* out_params) {
1198 SCOPED_TRACE("EncryptMessage");
1199 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1200}
1201
1202string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1203 AuthorizationSet* out_params) {
1204 SCOPED_TRACE("EncryptMessage");
1205 return EncryptMessage(key_blob_, message, params, out_params);
1206}
1207
1208string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1209 SCOPED_TRACE("EncryptMessage");
1210 AuthorizationSet out_params;
1211 string ciphertext = EncryptMessage(message, params, &out_params);
1212 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1213 return ciphertext;
1214}
1215
1216string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1217 PaddingMode padding) {
1218 SCOPED_TRACE("EncryptMessage");
1219 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1220 AuthorizationSet out_params;
1221 string ciphertext = EncryptMessage(message, params, &out_params);
1222 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1223 return ciphertext;
1224}
1225
1226string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1227 PaddingMode padding, vector<uint8_t>* iv_out) {
1228 SCOPED_TRACE("EncryptMessage");
1229 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1230 AuthorizationSet out_params;
1231 string ciphertext = EncryptMessage(message, params, &out_params);
1232 EXPECT_EQ(1U, out_params.size());
1233 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001234 EXPECT_TRUE(ivVal);
1235 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001236 return ciphertext;
1237}
1238
1239string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1240 PaddingMode padding, const vector<uint8_t>& iv_in) {
1241 SCOPED_TRACE("EncryptMessage");
1242 auto params = AuthorizationSetBuilder()
1243 .BlockMode(block_mode)
1244 .Padding(padding)
1245 .Authorization(TAG_NONCE, iv_in);
1246 AuthorizationSet out_params;
1247 string ciphertext = EncryptMessage(message, params, &out_params);
1248 return ciphertext;
1249}
1250
1251string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1252 PaddingMode padding, uint8_t mac_length_bits,
1253 const vector<uint8_t>& iv_in) {
1254 SCOPED_TRACE("EncryptMessage");
1255 auto params = AuthorizationSetBuilder()
1256 .BlockMode(block_mode)
1257 .Padding(padding)
1258 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1259 .Authorization(TAG_NONCE, iv_in);
1260 AuthorizationSet out_params;
1261 string ciphertext = EncryptMessage(message, params, &out_params);
1262 return ciphertext;
1263}
1264
David Drysdaled2cc8c22021-04-15 13:29:45 +01001265string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1266 PaddingMode padding, uint8_t mac_length_bits) {
1267 SCOPED_TRACE("EncryptMessage");
1268 auto params = AuthorizationSetBuilder()
1269 .BlockMode(block_mode)
1270 .Padding(padding)
1271 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1272 AuthorizationSet out_params;
1273 string ciphertext = EncryptMessage(message, params, &out_params);
1274 return ciphertext;
1275}
1276
Selene Huang31ab4042020-04-29 04:22:39 -07001277string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1278 const string& ciphertext,
1279 const AuthorizationSet& params) {
1280 SCOPED_TRACE("DecryptMessage");
1281 AuthorizationSet out_params;
1282 string plaintext =
1283 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1284 EXPECT_TRUE(out_params.empty());
1285 return plaintext;
1286}
1287
1288string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1289 const AuthorizationSet& params) {
1290 SCOPED_TRACE("DecryptMessage");
1291 return DecryptMessage(key_blob_, ciphertext, params);
1292}
1293
1294string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1295 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1296 SCOPED_TRACE("DecryptMessage");
1297 auto params = AuthorizationSetBuilder()
1298 .BlockMode(block_mode)
1299 .Padding(padding_mode)
1300 .Authorization(TAG_NONCE, iv);
1301 return DecryptMessage(key_blob_, ciphertext, params);
1302}
1303
1304std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1305 const vector<uint8_t>& key_blob) {
1306 std::pair<ErrorCode, vector<uint8_t>> retval;
1307 vector<uint8_t> outKeyBlob;
1308 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1309 ErrorCode errorcode = GetReturnErrorCode(result);
1310 retval = std::tie(errorcode, outKeyBlob);
1311
1312 return retval;
1313}
Seth Moorea12ac742023-03-03 13:40:30 -08001314
1315bool KeyMintAidlTestBase::IsRkpSupportRequired() const {
Seth Moore8be875e2023-08-25 11:09:05 -07001316 // This is technically not a match to the requirements for S chipsets,
1317 // however when S shipped there was a bug in the test that skipped the
1318 // tests if KeyMint 2 was not on the system. So we allowed many chipests
1319 // to ship without RKP support. In T we hardened the requirements around
1320 // support for RKP, so relax the test to match.
1321 return get_vsr_api_level() >= __ANDROID_API_T__;
Seth Moorea12ac742023-03-03 13:40:30 -08001322}
1323
Selene Huang31ab4042020-04-29 04:22:39 -07001324vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1325 switch (algorithm) {
1326 case Algorithm::RSA:
1327 switch (SecLevel()) {
1328 case SecurityLevel::SOFTWARE:
1329 case SecurityLevel::TRUSTED_ENVIRONMENT:
1330 return {2048, 3072, 4096};
1331 case SecurityLevel::STRONGBOX:
1332 return {2048};
1333 default:
1334 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1335 break;
1336 }
1337 break;
1338 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001339 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001340 break;
1341 case Algorithm::AES:
1342 return {128, 256};
1343 case Algorithm::TRIPLE_DES:
1344 return {168};
1345 case Algorithm::HMAC: {
1346 vector<uint32_t> retval((512 - 64) / 8 + 1);
1347 uint32_t size = 64 - 8;
1348 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1349 return retval;
1350 }
1351 default:
1352 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1353 return {};
1354 }
1355 ADD_FAILURE() << "Should be impossible to get here";
1356 return {};
1357}
1358
1359vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1360 if (SecLevel() == SecurityLevel::STRONGBOX) {
1361 switch (algorithm) {
1362 case Algorithm::RSA:
1363 return {3072, 4096};
1364 case Algorithm::EC:
1365 return {224, 384, 521};
1366 case Algorithm::AES:
1367 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001368 case Algorithm::TRIPLE_DES:
1369 return {56};
1370 default:
1371 return {};
1372 }
1373 } else {
1374 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001375 case Algorithm::AES:
1376 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001377 case Algorithm::TRIPLE_DES:
1378 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001379 default:
1380 return {};
1381 }
1382 }
1383 return {};
1384}
1385
David Drysdale7de9feb2021-03-05 14:56:19 +00001386vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1387 switch (algorithm) {
1388 case Algorithm::AES:
1389 return {
1390 BlockMode::CBC,
1391 BlockMode::CTR,
1392 BlockMode::ECB,
1393 BlockMode::GCM,
1394 };
1395 case Algorithm::TRIPLE_DES:
1396 return {
1397 BlockMode::CBC,
1398 BlockMode::ECB,
1399 };
1400 default:
1401 return {};
1402 }
1403}
1404
1405vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1406 BlockMode blockMode) {
1407 switch (algorithm) {
1408 case Algorithm::AES:
1409 switch (blockMode) {
1410 case BlockMode::CBC:
1411 case BlockMode::ECB:
1412 return {PaddingMode::NONE, PaddingMode::PKCS7};
1413 case BlockMode::CTR:
1414 case BlockMode::GCM:
1415 return {PaddingMode::NONE};
1416 default:
1417 return {};
1418 };
1419 case Algorithm::TRIPLE_DES:
1420 switch (blockMode) {
1421 case BlockMode::CBC:
1422 case BlockMode::ECB:
1423 return {PaddingMode::NONE, PaddingMode::PKCS7};
1424 default:
1425 return {};
1426 };
1427 default:
1428 return {};
1429 }
1430}
1431
1432vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1433 BlockMode blockMode) {
1434 switch (algorithm) {
1435 case Algorithm::AES:
1436 switch (blockMode) {
1437 case BlockMode::CTR:
1438 case BlockMode::GCM:
1439 return {PaddingMode::PKCS7};
1440 default:
1441 return {};
1442 };
1443 default:
1444 return {};
1445 }
1446}
1447
Selene Huang31ab4042020-04-29 04:22:39 -07001448vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1449 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1450 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001451 } else if (Curve25519Supported()) {
1452 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1453 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001454 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001455 return {
1456 EcCurve::P_224,
1457 EcCurve::P_256,
1458 EcCurve::P_384,
1459 EcCurve::P_521,
1460 };
Selene Huang31ab4042020-04-29 04:22:39 -07001461 }
1462}
1463
1464vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001465 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001466 // Curve 25519 is not supported, either because:
1467 // - KeyMint v1: it's an unknown enum value
1468 // - KeyMint v2+: it's not supported by StrongBox.
1469 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001470 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001471 if (Curve25519Supported()) {
1472 return {};
1473 } else {
1474 return {EcCurve::CURVE_25519};
1475 }
David Drysdaledf09e542021-06-08 15:46:11 +01001476 }
Selene Huang31ab4042020-04-29 04:22:39 -07001477}
1478
subrahmanyaman05642492022-02-05 07:10:56 +00001479vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1480 if (SecLevel() == SecurityLevel::STRONGBOX) {
1481 return {65537};
1482 } else {
1483 return {3, 65537};
1484 }
1485}
1486
Selene Huang31ab4042020-04-29 04:22:39 -07001487vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1488 switch (SecLevel()) {
1489 case SecurityLevel::SOFTWARE:
1490 case SecurityLevel::TRUSTED_ENVIRONMENT:
1491 if (withNone) {
1492 if (withMD5)
1493 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1494 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1495 Digest::SHA_2_512};
1496 else
1497 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1498 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1499 } else {
1500 if (withMD5)
1501 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1502 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1503 else
1504 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1505 Digest::SHA_2_512};
1506 }
1507 break;
1508 case SecurityLevel::STRONGBOX:
1509 if (withNone)
1510 return {Digest::NONE, Digest::SHA_2_256};
1511 else
1512 return {Digest::SHA_2_256};
1513 break;
1514 default:
1515 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1516 break;
1517 }
1518 ADD_FAILURE() << "Should be impossible to get here";
1519 return {};
1520}
1521
Shawn Willden7f424372021-01-10 18:06:50 -07001522static const vector<KeyParameter> kEmptyAuthList{};
1523
1524const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1525 const vector<KeyCharacteristics>& key_characteristics) {
1526 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1527 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1528 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1529}
1530
Qi Wubeefae42021-01-28 23:16:37 +08001531const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1532 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1533 auto found = std::find_if(
1534 key_characteristics.begin(), key_characteristics.end(),
1535 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001536 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1537}
1538
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001539ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001540 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001541 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1542 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1543 return result;
1544}
1545
1546ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001547 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001548 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1549 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1550 return result;
1551}
1552
1553ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1554 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001555 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001556 rsaKeyBlob, KeyPurpose::SIGN, message,
1557 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1558 return result;
1559}
1560
1561ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001562 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1563 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001564 return result;
1565}
1566
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001567ErrorCode KeyMintAidlTestBase::GenerateAttestKey(const AuthorizationSet& key_desc,
1568 const optional<AttestationKey>& attest_key,
1569 vector<uint8_t>* key_blob,
1570 vector<KeyCharacteristics>* key_characteristics,
1571 vector<Certificate>* cert_chain) {
1572 // The original specification for KeyMint v1 required ATTEST_KEY not be combined
1573 // with any other key purpose, but the original VTS tests incorrectly did exactly that.
1574 // This means that a device that launched prior to Android T (API level 33) may
1575 // accept or even require KeyPurpose::SIGN too.
1576 if (property_get_int32("ro.board.first_api_level", 0) < __ANDROID_API_T__) {
1577 AuthorizationSet key_desc_plus_sign = key_desc;
1578 key_desc_plus_sign.push_back(TAG_PURPOSE, KeyPurpose::SIGN);
1579
1580 auto result = GenerateKey(key_desc_plus_sign, attest_key, key_blob, key_characteristics,
1581 cert_chain);
1582 if (result == ErrorCode::OK) {
1583 return result;
1584 }
1585 // If the key generation failed, it may be because the device is (correctly)
1586 // rejecting the combination of ATTEST_KEY+SIGN. Fall through to try again with
1587 // just ATTEST_KEY.
1588 }
1589 return GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
1590}
1591
1592// Check if ATTEST_KEY feature is disabled
1593bool KeyMintAidlTestBase::is_attest_key_feature_disabled(void) const {
1594 if (!check_feature(FEATURE_KEYSTORE_APP_ATTEST_KEY)) {
1595 GTEST_LOG_(INFO) << "Feature " + FEATURE_KEYSTORE_APP_ATTEST_KEY + " is disabled";
1596 return true;
1597 }
1598
1599 return false;
1600}
1601
1602// Check if StrongBox KeyStore is enabled
1603bool KeyMintAidlTestBase::is_strongbox_enabled(void) const {
1604 if (check_feature(FEATURE_STRONGBOX_KEYSTORE)) {
1605 GTEST_LOG_(INFO) << "Feature " + FEATURE_STRONGBOX_KEYSTORE + " is enabled";
1606 return true;
1607 }
1608
1609 return false;
1610}
1611
1612// Check if chipset has received a waiver allowing it to be launched with Android S or T with
1613// Keymaster 4.0 in StrongBox.
1614bool KeyMintAidlTestBase::is_chipset_allowed_km4_strongbox(void) const {
1615 std::array<char, PROPERTY_VALUE_MAX> buffer;
1616
1617 const int32_t first_api_level = property_get_int32("ro.board.first_api_level", 0);
1618 if (first_api_level <= 0 || first_api_level > __ANDROID_API_T__) return false;
1619
1620 auto res = property_get("ro.vendor.qti.soc_model", buffer.data(), nullptr);
1621 if (res <= 0) return false;
1622
Shawn Willden0f1b2572023-05-30 14:52:53 -06001623 const string allowed_soc_models[] = {"SM8450", "SM8475", "SM8550", "SXR2230P",
1624 "SM4450", "SM7450", "SM6450"};
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001625
1626 for (const string model : allowed_soc_models) {
1627 if (model.compare(buffer.data()) == 0) {
1628 GTEST_LOG_(INFO) << "QTI SOC Model " + model + " is allowed SB KM 4.0";
1629 return true;
1630 }
1631 }
1632
1633 return false;
1634}
1635
David Drysdalec3de1ca2023-05-09 08:10:36 +01001636// Indicate whether a test that involves use of the ATTEST_KEY feature should be
1637// skipped.
1638//
1639// In general, every KeyMint implementation should support ATTEST_KEY;
1640// however, there is a waiver for some specific devices that ship with a
1641// combination of Keymaster/StrongBox and KeyMint/TEE. On these devices, the
1642// ATTEST_KEY feature is disabled in the KeyMint/TEE implementation so that
1643// the device has consistent ATTEST_KEY behavior (ie. UNIMPLEMENTED) across both
1644// HAL implementations.
1645//
1646// This means that a test involving ATTEST_KEY test should be skipped if all of
1647// the following conditions hold:
1648// 1. The device is running one of the chipsets that have received a waiver
1649// allowing it to be launched with Android S or T with Keymaster 4.0
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001650// in StrongBox
David Drysdalec3de1ca2023-05-09 08:10:36 +01001651// 2. The device has a STRONGBOX implementation present.
1652// 3. ATTEST_KEY feature is advertised as disabled.
1653//
1654// Note that in this scenario, ATTEST_KEY tests should be skipped for both
1655// the StrongBox implementation (which is Keymaster, therefore not tested here)
1656// and for the TEE implementation (which is adjusted to return UNIMPLEMENTED
1657// specifically for this waiver).
1658bool KeyMintAidlTestBase::shouldSkipAttestKeyTest(void) const {
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001659 // Check the chipset first as that doesn't require a round-trip to Package Manager.
David Drysdalec3de1ca2023-05-09 08:10:36 +01001660 return (is_chipset_allowed_km4_strongbox() && is_strongbox_enabled() &&
1661 is_attest_key_feature_disabled());
1662}
1663
1664// Skip a test that involves use of the ATTEST_KEY feature in specific configurations
1665// where ATTEST_KEY is not supported (for either StrongBox or TEE).
1666void KeyMintAidlTestBase::skipAttestKeyTest(void) const {
1667 if (shouldSkipAttestKeyTest()) {
1668 GTEST_SKIP() << "Test using ATTEST_KEY is not applicable on waivered device";
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001669 }
1670}
1671
Selene Huang6e46f142021-04-20 19:20:11 -07001672void verify_serial(X509* cert, const uint64_t expected_serial) {
1673 BIGNUM_Ptr ser(BN_new());
1674 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1675
1676 uint64_t serial;
1677 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1678 EXPECT_EQ(serial, expected_serial);
1679}
1680
1681// Please set self_signed to true for fake certificates or self signed
1682// certificates
1683void verify_subject(const X509* cert, //
1684 const string& subject, //
1685 bool self_signed) {
1686 char* cert_issuer = //
1687 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1688
1689 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1690
1691 string expected_subject("/CN=");
1692 if (subject.empty()) {
1693 expected_subject.append("Android Keystore Key");
1694 } else {
1695 expected_subject.append(subject);
1696 }
1697
1698 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1699
1700 if (self_signed) {
1701 EXPECT_STREQ(cert_issuer, cert_subj)
1702 << "Cert issuer and subject mismatch for self signed certificate.";
1703 }
1704
1705 OPENSSL_free(cert_subj);
1706 OPENSSL_free(cert_issuer);
1707}
1708
Shawn Willden22fb9c12022-06-02 14:04:33 -06001709int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001710 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1711 if (vendor_api_level != -1) {
1712 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001713 }
Shawn Willden35db3492022-06-16 12:50:40 -06001714
1715 // Android S and older devices do not define ro.vendor.api_level
1716 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1717 if (vendor_api_level == -1) {
1718 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001719 }
Shawn Willden35db3492022-06-16 12:50:40 -06001720
1721 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1722 if (product_api_level == -1) {
1723 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1724 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001725 }
Shawn Willden35db3492022-06-16 12:50:40 -06001726
1727 // VSR API level is the minimum of vendor_api_level and product_api_level.
1728 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1729 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001730 }
Shawn Willden35db3492022-06-16 12:50:40 -06001731 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001732}
1733
David Drysdale555ba002022-05-03 18:48:57 +01001734bool is_gsi_image() {
1735 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1736 return ifs.good();
1737}
1738
Selene Huang6e46f142021-04-20 19:20:11 -07001739vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1740 BIGNUM_Ptr serial(BN_new());
1741 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1742
1743 int len = BN_num_bytes(serial.get());
1744 vector<uint8_t> serial_blob(len);
1745 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1746 return {};
1747 }
1748
David Drysdaledb0dcf52021-05-18 11:43:31 +01001749 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1750 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1751 // Top bit being set indicates a negative number in two's complement, but our input
1752 // was positive.
1753 // In either case, prepend a zero byte.
1754 serial_blob.insert(serial_blob.begin(), 0x00);
1755 }
1756
Selene Huang6e46f142021-04-20 19:20:11 -07001757 return serial_blob;
1758}
1759
1760void verify_subject_and_serial(const Certificate& certificate, //
1761 const uint64_t expected_serial, //
1762 const string& subject, bool self_signed) {
1763 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1764 ASSERT_TRUE(!!cert.get());
1765
1766 verify_serial(cert.get(), expected_serial);
1767 verify_subject(cert.get(), subject, self_signed);
1768}
1769
Shawn Willden4315e132022-03-20 12:49:46 -06001770void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1771 VerifiedBoot verified_boot_state,
1772 const vector<uint8_t>& verified_boot_hash) {
1773 char property_value[PROPERTY_VALUE_MAX] = {};
1774
1775 if (avb_verification_enabled()) {
1776 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1777 string prop_string(property_value);
1778 EXPECT_EQ(prop_string.size(), 64);
1779 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1780
1781 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1782 if (!strcmp(property_value, "unlocked")) {
1783 EXPECT_FALSE(device_locked);
1784 } else {
1785 EXPECT_TRUE(device_locked);
1786 }
1787
1788 // Check that the device is locked if not debuggable, e.g., user build
1789 // images in CTS. For VTS, debuggable images are used to allow adb root
1790 // and the device is unlocked.
1791 if (!property_get_bool("ro.debuggable", false)) {
1792 EXPECT_TRUE(device_locked);
1793 } else {
1794 EXPECT_FALSE(device_locked);
1795 }
1796 }
1797
1798 // Verified boot key should be all 0's if the boot state is not verified or self signed
1799 std::string empty_boot_key(32, '\0');
1800 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1801 verified_boot_key.size());
David Drysdaled847ef92023-10-13 08:06:40 +01001802 if (get_vsr_api_level() >= __ANDROID_API_V__) {
1803 // The attestation should contain the SHA-256 hash of the verified boot
1804 // key. However, this was not checked for earlier versions of the KeyMint
1805 // HAL so only be strict for VSR-V and above.
1806 EXPECT_LE(verified_boot_key.size(), 32);
1807 }
Shawn Willden4315e132022-03-20 12:49:46 -06001808 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1809 if (!strcmp(property_value, "green")) {
1810 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1811 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1812 verified_boot_key.size()));
1813 } else if (!strcmp(property_value, "yellow")) {
1814 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1815 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1816 verified_boot_key.size()));
1817 } else if (!strcmp(property_value, "orange")) {
1818 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1819 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1820 verified_boot_key.size()));
1821 } else if (!strcmp(property_value, "red")) {
1822 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1823 } else {
1824 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1825 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1826 verified_boot_key.size()));
1827 }
1828}
1829
David Drysdale7dff4fc2021-12-10 10:10:52 +00001830bool verify_attestation_record(int32_t aidl_version, //
1831 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001832 const string& app_id, //
1833 AuthorizationSet expected_sw_enforced, //
1834 AuthorizationSet expected_hw_enforced, //
1835 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001836 const vector<uint8_t>& attestation_cert,
1837 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001838 X509_Ptr cert(parse_cert_blob(attestation_cert));
1839 EXPECT_TRUE(!!cert.get());
1840 if (!cert.get()) return false;
1841
Rajesh Nyamagoude98263e2023-02-09 20:36:33 +00001842 // Make sure CRL Distribution Points extension is not present in a certificate
1843 // containing attestation record.
1844 check_crl_distribution_points_extension_not_present(cert.get());
1845
Shawn Willden7c130392020-12-21 09:58:22 -07001846 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1847 EXPECT_TRUE(!!attest_rec);
1848 if (!attest_rec) return false;
1849
1850 AuthorizationSet att_sw_enforced;
1851 AuthorizationSet att_hw_enforced;
1852 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001853 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001854 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001855 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001856 vector<uint8_t> att_challenge;
1857 vector<uint8_t> att_unique_id;
1858 vector<uint8_t> att_app_id;
1859
1860 auto error = parse_attestation_record(attest_rec->data, //
1861 attest_rec->length, //
1862 &att_attestation_version, //
1863 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001864 &att_keymint_version, //
1865 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001866 &att_challenge, //
1867 &att_sw_enforced, //
1868 &att_hw_enforced, //
1869 &att_unique_id);
1870 EXPECT_EQ(ErrorCode::OK, error);
1871 if (error != ErrorCode::OK) return false;
1872
David Drysdale7dff4fc2021-12-10 10:10:52 +00001873 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001874 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001875
Selene Huang4f64c222021-04-13 19:54:36 -07001876 // check challenge and app id only if we expects a non-fake certificate
1877 if (challenge.length() > 0) {
1878 EXPECT_EQ(challenge.length(), att_challenge.size());
1879 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1880
1881 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1882 }
Shawn Willden7c130392020-12-21 09:58:22 -07001883
David Drysdale7dff4fc2021-12-10 10:10:52 +00001884 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001885 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001886 EXPECT_EQ(security_level, att_attestation_security_level);
1887
Tri Vob21e6df2023-02-17 14:55:43 -08001888 for (int i = 0; i < att_hw_enforced.size(); i++) {
1889 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1890 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1891 std::string date =
1892 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001893
Tri Vob21e6df2023-02-17 14:55:43 -08001894 // strptime seems to require delimiters, but the tag value will
1895 // be YYYYMMDD
1896 if (date.size() != 8) {
1897 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1898 << " with invalid format (not YYYYMMDD): " << date;
1899 return false;
Shawn Willden7c130392020-12-21 09:58:22 -07001900 }
Tri Vob21e6df2023-02-17 14:55:43 -08001901 date.insert(6, "-");
1902 date.insert(4, "-");
1903 struct tm time;
1904 strptime(date.c_str(), "%Y-%m-%d", &time);
1905
1906 // Day of the month (0-31)
1907 EXPECT_GE(time.tm_mday, 0);
1908 EXPECT_LT(time.tm_mday, 32);
1909 // Months since Jan (0-11)
1910 EXPECT_GE(time.tm_mon, 0);
1911 EXPECT_LT(time.tm_mon, 12);
1912 // Years since 1900
1913 EXPECT_GT(time.tm_year, 110);
1914 EXPECT_LT(time.tm_year, 200);
Shawn Willden7c130392020-12-21 09:58:22 -07001915 }
1916 }
1917
1918 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1919 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1920 // indicates correct encoding. No need to check if it's in both lists, since the
1921 // AuthorizationSet compare below will handle mismatches of tags.
1922 if (security_level == SecurityLevel::SOFTWARE) {
1923 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1924 } else {
1925 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1926 }
1927
Shawn Willden7c130392020-12-21 09:58:22 -07001928 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1929 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1930 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1931 att_hw_enforced.Contains(TAG_KEY_SIZE));
1932 }
1933
1934 // Test root of trust elements
1935 vector<uint8_t> verified_boot_key;
1936 VerifiedBoot verified_boot_state;
1937 bool device_locked;
1938 vector<uint8_t> verified_boot_hash;
1939 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1940 &verified_boot_state, &device_locked, &verified_boot_hash);
1941 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001942 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001943
1944 att_sw_enforced.Sort();
1945 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001946 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001947
1948 att_hw_enforced.Sort();
1949 expected_hw_enforced.Sort();
1950 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1951
David Drysdale565ccc72021-10-11 12:49:50 +01001952 if (unique_id != nullptr) {
1953 *unique_id = att_unique_id;
1954 }
1955
Shawn Willden7c130392020-12-21 09:58:22 -07001956 return true;
1957}
1958
1959string bin2hex(const vector<uint8_t>& data) {
1960 string retval;
1961 retval.reserve(data.size() * 2 + 1);
1962 for (uint8_t byte : data) {
1963 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1964 retval.push_back(nibble2hex[0x0F & byte]);
1965 }
1966 return retval;
1967}
1968
David Drysdalef0d516d2021-03-22 07:51:43 +00001969AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1970 AuthorizationSet authList;
1971 for (auto& entry : key_characteristics) {
1972 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1973 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1974 authList.push_back(AuthorizationSet(entry.authorizations));
1975 }
1976 }
1977 return authList;
1978}
1979
1980AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1981 AuthorizationSet authList;
1982 for (auto& entry : key_characteristics) {
1983 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1984 entry.securityLevel == SecurityLevel::KEYSTORE) {
1985 authList.push_back(AuthorizationSet(entry.authorizations));
1986 }
1987 }
1988 return authList;
1989}
1990
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001991AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1992 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001993 std::stringstream cert_data;
1994
1995 for (size_t i = 0; i < chain.size(); ++i) {
1996 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1997
1998 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1999 X509_Ptr signing_cert;
2000 if (i < chain.size() - 1) {
2001 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
2002 } else {
2003 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
2004 }
2005 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
2006
2007 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
2008 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
2009
2010 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
2011 return AssertionFailure()
2012 << "Verification of certificate " << i << " failed "
2013 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
2014 << cert_data.str();
2015 }
2016
2017 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
2018 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01002019 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07002020 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
2021 << " Signer subject is " << signer_subj
2022 << " Issuer subject is " << cert_issuer << endl
2023 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07002024 }
Shawn Willden7c130392020-12-21 09:58:22 -07002025 }
2026
2027 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
2028 return AssertionSuccess();
2029}
2030
David Drysdale1b9febc2023-06-07 13:43:24 +01002031ErrorCode GetReturnErrorCode(const Status& result) {
2032 if (result.isOk()) return ErrorCode::OK;
2033
2034 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
2035 return static_cast<ErrorCode>(result.getServiceSpecificError());
2036 }
2037
2038 return ErrorCode::UNKNOWN_ERROR;
2039}
2040
Shawn Willden7c130392020-12-21 09:58:22 -07002041X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
2042 const uint8_t* p = blob.data();
2043 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
2044}
2045
Tri Voec50ee12023-02-14 16:29:53 -08002046// Extract attestation record from cert. Returned object is still part of cert; don't free it
2047// separately.
2048ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
2049 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
2050 EXPECT_TRUE(!!oid.get());
2051 if (!oid.get()) return nullptr;
2052
2053 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
2054 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
2055 if (location == -1) return nullptr;
2056
2057 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
2058 EXPECT_TRUE(!!attest_rec_ext)
2059 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
2060 if (!attest_rec_ext) return nullptr;
2061
2062 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
2063 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
2064 return attest_rec;
2065}
2066
David Drysdalef0d516d2021-03-22 07:51:43 +00002067vector<uint8_t> make_name_from_str(const string& name) {
2068 X509_NAME_Ptr x509_name(X509_NAME_new());
2069 EXPECT_TRUE(x509_name.get() != nullptr);
2070 if (!x509_name) return {};
2071
2072 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
2073 "CN", //
2074 MBSTRING_ASC,
2075 reinterpret_cast<const uint8_t*>(name.c_str()),
2076 -1, // len
2077 -1, // loc
2078 0 /* set */));
2079
2080 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
2081 EXPECT_GT(len, 0);
2082
2083 vector<uint8_t> retval(len);
2084 uint8_t* p = retval.data();
2085 i2d_X509_NAME(x509_name.get(), &p);
2086
2087 return retval;
2088}
2089
Prashant Patil2114dca2023-09-21 14:57:10 +00002090void KeyMintAidlTestBase::assert_mgf_digests_present_or_not_in_key_characteristics(
2091 std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests,
2092 bool is_mgf_digest_expected) const {
2093 assert_mgf_digests_present_or_not_in_key_characteristics(
2094 key_characteristics_, expected_mgf_digests, is_mgf_digest_expected);
2095}
2096
2097void KeyMintAidlTestBase::assert_mgf_digests_present_or_not_in_key_characteristics(
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00002098 const vector<KeyCharacteristics>& key_characteristics,
Prashant Patil2114dca2023-09-21 14:57:10 +00002099 std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests,
2100 bool is_mgf_digest_expected) const {
2101 // There was no test to assert that MGF1 digest was present in generated/imported key
2102 // characteristics before Keymint V3, so there are some Keymint implementations where
2103 // asserting for MGF1 digest fails(b/297306437), hence skipping for Keymint < 3.
2104 if (AidlVersion() < 3) {
2105 return;
2106 }
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00002107 AuthorizationSet auths;
2108 for (auto& entry : key_characteristics) {
2109 auths.push_back(AuthorizationSet(entry.authorizations));
2110 }
2111 for (auto digest : expected_mgf_digests) {
Prashant Patil2114dca2023-09-21 14:57:10 +00002112 if (is_mgf_digest_expected) {
2113 ASSERT_TRUE(auths.Contains(TAG_RSA_OAEP_MGF_DIGEST, digest));
2114 } else {
2115 ASSERT_FALSE(auths.Contains(TAG_RSA_OAEP_MGF_DIGEST, digest));
2116 }
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00002117 }
2118}
2119
David Drysdale4dc01072021-04-01 12:17:35 +01002120namespace {
2121
2122void check_cose_key(const vector<uint8_t>& data, bool testMode) {
2123 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
2124 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2125
2126 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
2127 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00002128 EXPECT_THAT(
2129 cppbor::prettyPrint(parsedPayload.get()),
2130 MatchesRegex("\\{\n"
2131 " 1 : 2,\n" // kty: EC2
2132 " 3 : -7,\n" // alg: ES256
2133 " -1 : 1,\n" // EC id: P256
2134 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
2135 // sequence of 32 hexadecimal bytes, enclosed in braces and
2136 // separated by commas. In this case, some Ed25519 public key.
2137 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
2138 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
2139 " -70000 : null,\n" // test marker
2140 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01002141 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00002142 EXPECT_THAT(
2143 cppbor::prettyPrint(parsedPayload.get()),
2144 MatchesRegex("\\{\n"
2145 " 1 : 2,\n" // kty: EC2
2146 " 3 : -7,\n" // alg: ES256
2147 " -1 : 1,\n" // EC id: P256
2148 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
2149 // sequence of 32 hexadecimal bytes, enclosed in braces and
2150 // separated by commas. In this case, some Ed25519 public key.
2151 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
2152 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
2153 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01002154 }
2155}
2156
2157} // namespace
2158
2159void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
2160 vector<uint8_t>* payload_value) {
2161 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
2162 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
2163
2164 ASSERT_NE(coseMac0->asArray(), nullptr);
2165 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
2166
2167 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
2168 ASSERT_NE(protParms, nullptr);
2169
2170 // Header label:value of 'alg': HMAC-256
2171 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
2172
2173 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
2174 ASSERT_NE(unprotParms, nullptr);
2175 ASSERT_EQ(unprotParms->size(), 0);
2176
2177 // The payload is a bstr holding an encoded COSE_Key
2178 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
2179 ASSERT_NE(payload, nullptr);
2180 check_cose_key(payload->value(), testMode);
2181
2182 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
2183 ASSERT_TRUE(coseMac0Tag);
2184 auto extractedTag = coseMac0Tag->value();
2185 EXPECT_EQ(extractedTag.size(), 32U);
2186
2187 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07002188 auto macFunction = [](const cppcose::bytevec& input) {
2189 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
2190 };
2191 auto testTag =
2192 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01002193 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
2194
2195 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07002196 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01002197 } else {
Seth Moore026bb742021-04-30 11:41:18 -07002198 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002199 }
2200 if (payload_value != nullptr) {
2201 *payload_value = payload->value();
2202 }
2203}
2204
2205void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2206 // Extract x and y affine coordinates from the encoded Cose_Key.
2207 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2208 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2209 auto coseKey = parsedPayload->asMap();
2210 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2211 ASSERT_NE(xItem->asBstr(), nullptr);
2212 vector<uint8_t> x = xItem->asBstr()->value();
2213 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2214 ASSERT_NE(yItem->asBstr(), nullptr);
2215 vector<uint8_t> y = yItem->asBstr()->value();
2216
2217 // Concatenate: 0x04 (uncompressed form marker) | x | y
2218 vector<uint8_t> pubKeyData{0x04};
2219 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2220 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2221
2222 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2223 ASSERT_NE(ecKey, nullptr);
2224 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2225 ASSERT_NE(group, nullptr);
2226 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2227 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2228 ASSERT_NE(point, nullptr);
2229 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2230 nullptr),
2231 1);
2232 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2233
2234 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2235 ASSERT_NE(pubKey, nullptr);
2236 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2237 *signingKey = std::move(pubKey);
2238}
2239
David Drysdalef42238c2023-06-15 09:41:05 +01002240// Check the error code from an attempt to perform device ID attestation with an invalid value.
2241void device_id_attestation_check_acceptable_error(Tag tag, const ErrorCode& result) {
David Drysdalef42238c2023-06-15 09:41:05 +01002242 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
David Drysdale810fbcf2023-07-04 13:08:30 +01002243 // Standard/default error code for ID mismatch.
2244 } else if (result == ErrorCode::INVALID_TAG) {
2245 // Depending on the situation, other error codes may be acceptable. First, allow older
2246 // implementations to use INVALID_TAG.
David Drysdalef42238c2023-06-15 09:41:05 +01002247 ASSERT_FALSE(get_vsr_api_level() > __ANDROID_API_T__)
Max Biresa97ec692022-11-21 23:37:54 -08002248 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2249 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2250 << "be used for a case where updateAad() is called after update(). As of "
2251 << "VSR-14, this is now enforced as an error.";
David Drysdale810fbcf2023-07-04 13:08:30 +01002252 } else if (result == ErrorCode::ATTESTATION_IDS_NOT_PROVISIONED) {
2253 // If the device is not a phone, it will not have IMEI/MEID values available. Allow
2254 // ATTESTATION_IDS_NOT_PROVISIONED in this case.
David Drysdalef42238c2023-06-15 09:41:05 +01002255 ASSERT_TRUE((tag == TAG_ATTESTATION_ID_IMEI || tag == TAG_ATTESTATION_ID_MEID ||
2256 tag == TAG_ATTESTATION_ID_SECOND_IMEI))
2257 << "incorrect error code on attestation ID mismatch";
David Drysdale810fbcf2023-07-04 13:08:30 +01002258 } else {
2259 ADD_FAILURE() << "Error code " << result
2260 << " returned on attestation ID mismatch, should be CANNOT_ATTEST_IDS";
David Drysdalef42238c2023-06-15 09:41:05 +01002261 }
Max Biresa97ec692022-11-21 23:37:54 -08002262}
2263
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002264// Check whether the given named feature is available.
2265bool check_feature(const std::string& name) {
2266 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002267 ::android::sp<::android::IBinder> binder(
2268 sm->waitForService(::android::String16("package_native")));
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002269 if (binder == nullptr) {
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002270 GTEST_LOG_(ERROR) << "waitForService package_native failed";
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002271 return false;
2272 }
2273 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2274 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2275 if (packageMgr == nullptr) {
2276 GTEST_LOG_(ERROR) << "Cannot find package manager";
2277 return false;
2278 }
2279 bool hasFeature = false;
2280 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2281 if (!status.isOk()) {
2282 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2283 return false;
2284 }
2285 return hasFeature;
2286}
2287
David Drysdale6c9bdb82024-01-23 09:32:04 +00002288// Return the numeric value associated with a feature.
2289std::optional<int32_t> keymint_feature_value(bool strongbox) {
2290 std::string name = strongbox ? FEATURE_STRONGBOX_KEYSTORE : FEATURE_HARDWARE_KEYSTORE;
2291 ::android::String16 name16(name.c_str());
2292 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
2293 ::android::sp<::android::IBinder> binder(
2294 sm->waitForService(::android::String16("package_native")));
2295 if (binder == nullptr) {
2296 GTEST_LOG_(ERROR) << "waitForService package_native failed";
2297 return std::nullopt;
2298 }
2299 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2300 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2301 if (packageMgr == nullptr) {
2302 GTEST_LOG_(ERROR) << "Cannot find package manager";
2303 return std::nullopt;
2304 }
2305
2306 // Package manager has no mechanism to retrieve the version of a feature,
2307 // only to indicate whether a certain version or above is present.
2308 std::optional<int32_t> result = std::nullopt;
2309 for (auto version : kFeatureVersions) {
2310 bool hasFeature = false;
2311 auto status = packageMgr->hasSystemFeature(name16, version, &hasFeature);
2312 if (!status.isOk()) {
2313 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "', " << version
2314 << ") failed: " << status;
2315 return result;
2316 } else if (hasFeature) {
2317 result = version;
2318 } else {
2319 break;
2320 }
2321 }
2322 return result;
2323}
2324
Selene Huang31ab4042020-04-29 04:22:39 -07002325} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002326
Janis Danisevskis24c04702020-12-16 18:28:39 -08002327} // namespace aidl::android::hardware::security::keymint