blob: d280c7111eb2e1e7a458f382e0d9654a1285bf4a [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "KeyMintAidlTestBase.h"
18
19#include <chrono>
David Drysdale555ba002022-05-03 18:48:57 +010020#include <fstream>
Shawn Willden7f424372021-01-10 18:06:50 -070021#include <unordered_set>
Selene Huang31ab4042020-04-29 04:22:39 -070022#include <vector>
23
24#include <android-base/logging.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080025#include <android/binder_manager.h>
David Drysdale3d2ba0a2023-01-11 13:27:26 +000026#include <android/content/pm/IPackageManagerNative.h>
David Drysdale4dc01072021-04-01 12:17:35 +010027#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070028#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010029#include <gmock/gmock.h>
David Drysdale42fe1892021-10-14 14:43:46 +010030#include <openssl/evp.h>
Shawn Willden7c130392020-12-21 09:58:22 -070031#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070033
Max Bires9704ff62021-04-07 11:12:01 -070034#include <keymaster/cppcose/cppcose.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000035#include <keymint_support/key_param_output.h>
36#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070037#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070038
Janis Danisevskis24c04702020-12-16 18:28:39 -080039namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070040
David Drysdale4dc01072021-04-01 12:17:35 +010041using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070042using namespace std::literals::chrono_literals;
43using std::endl;
44using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070045using std::unique_ptr;
46using ::testing::AssertionFailure;
47using ::testing::AssertionResult;
48using ::testing::AssertionSuccess;
Seth Moore026bb742021-04-30 11:41:18 -070049using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010050using ::testing::MatchesRegex;
Seth Moore026bb742021-04-30 11:41:18 -070051using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070052
53::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
54 if (set.size() == 0)
55 os << "(Empty)" << ::std::endl;
56 else {
57 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070058 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070059 }
60 return os;
61}
62
63namespace test {
64
Shawn Willden7f424372021-01-10 18:06:50 -070065namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010066
David Drysdale37af4b32021-05-14 16:46:59 +010067// Invalid value for a patchlevel (which is of form YYYYMMDD).
68const uint32_t kInvalidPatchlevel = 99998877;
69
David Drysdaledf8f52e2021-05-06 08:10:58 +010070// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
71// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
72const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
73
Shawn Willden20732262023-04-21 16:36:00 -060074size_t count_tag_invalid_entries(const std::vector<KeyParameter>& authorizations) {
75 return std::count_if(authorizations.begin(), authorizations.end(),
76 [](const KeyParameter& e) -> bool { return e.tag == Tag::INVALID; });
77}
78
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000079typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070080// Predicate for testing basic characteristics validity in generation or import.
81bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
82 const vector<KeyCharacteristics>& key_characteristics) {
83 if (key_characteristics.empty()) return false;
84
85 std::unordered_set<SecurityLevel> levels_seen;
86 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070087 if (entry.authorizations.empty()) {
88 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
89 return false;
90 }
Shawn Willden7f424372021-01-10 18:06:50 -070091
Shawn Willden20732262023-04-21 16:36:00 -060092 EXPECT_EQ(count_tag_invalid_entries(entry.authorizations), 0);
93
Qi Wubeefae42021-01-28 23:16:37 +080094 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
95 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
96
Seth Moore2a9a00e2021-08-04 16:31:52 -070097 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
98 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
99 return false;
100 }
Shawn Willden7f424372021-01-10 18:06:50 -0700101 levels_seen.insert(entry.securityLevel);
102
103 // Generally, we should only have one entry, at the same security level as the KM
104 // instance. There is an exception: StrongBox KM can have some authorizations that are
105 // enforced by the TEE.
106 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
107 (secLevel == SecurityLevel::STRONGBOX &&
108 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
109
Seth Moore2a9a00e2021-08-04 16:31:52 -0700110 if (!isExpectedSecurityLevel) {
111 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
112 return false;
113 }
Shawn Willden7f424372021-01-10 18:06:50 -0700114 }
115 return true;
116}
117
Rajesh Nyamagoude98263e2023-02-09 20:36:33 +0000118void check_crl_distribution_points_extension_not_present(X509* certificate) {
119 ASN1_OBJECT_Ptr crl_dp_oid(OBJ_txt2obj(kCrlDPOid, 1 /* dotted string format */));
120 ASSERT_TRUE(crl_dp_oid.get());
121
122 int location =
123 X509_get_ext_by_OBJ(certificate, crl_dp_oid.get(), -1 /* search from beginning */);
124 ASSERT_EQ(location, -1);
125}
126
David Drysdale7dff4fc2021-12-10 10:10:52 +0000127void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
128 // Version numbers in attestation extensions should be a multiple of 100.
129 EXPECT_EQ(attestation_version % 100, 0);
130
131 // The multiplier should never be higher than the AIDL version, but can be less
132 // (for example, if the implementation is from an earlier version but the HAL service
133 // uses the default libraries and so reports the current AIDL version).
134 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
135}
136
Shawn Willden7c130392020-12-21 09:58:22 -0700137bool avb_verification_enabled() {
138 char value[PROPERTY_VALUE_MAX];
139 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
140}
141
142char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
143 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
144
145// Attestations don't contain everything in key authorization lists, so we need to filter the key
146// lists to produce the lists that we expect to match the attestations.
147auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100148 Tag::CREATION_DATETIME,
149 Tag::HARDWARE_TYPE,
150 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700151};
152
153AuthorizationSet filtered_tags(const AuthorizationSet& set) {
154 AuthorizationSet filtered;
155 std::remove_copy_if(
156 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
157 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
158 kTagsToFilter.end();
159 });
160 return filtered;
161}
162
David Drysdale300b5552021-05-20 12:05:26 +0100163// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
164void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
165 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
166 [](const auto& entry) {
167 return entry.securityLevel == SecurityLevel::KEYSTORE;
168 }),
169 characteristics->end());
170}
171
Shawn Willden7c130392020-12-21 09:58:22 -0700172string x509NameToStr(X509_NAME* name) {
173 char* s = X509_NAME_oneline(name, nullptr, 0);
174 string retval(s);
175 OPENSSL_free(s);
176 return retval;
177}
178
Shawn Willden7f424372021-01-10 18:06:50 -0700179} // namespace
180
Shawn Willden7c130392020-12-21 09:58:22 -0700181bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
182bool KeyMintAidlTestBase::dump_Attestations = false;
David Drysdale9f5c0c52022-11-03 15:10:16 +0000183std::string KeyMintAidlTestBase::keyblob_dir;
Tommy Chiu025f3c52023-05-15 06:23:44 +0000184std::optional<bool> KeyMintAidlTestBase::expect_upgrade = std::nullopt;
Shawn Willden7c130392020-12-21 09:58:22 -0700185
David Drysdale1b9febc2023-06-07 13:43:24 +0100186KeyBlobDeleter::~KeyBlobDeleter() {
187 if (key_blob_.empty()) {
188 return;
189 }
190 Status result = keymint_->deleteKey(key_blob_);
191 key_blob_.clear();
192 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << "\n";
193 ErrorCode rc = GetReturnErrorCode(result);
194 EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED) << result << "\n";
195}
196
David Drysdale37af4b32021-05-14 16:46:59 +0100197uint32_t KeyMintAidlTestBase::boot_patch_level(
198 const vector<KeyCharacteristics>& key_characteristics) {
199 // The boot patchlevel is not available as a property, but should be present
200 // in the key characteristics of any created key.
201 AuthorizationSet allAuths;
202 for (auto& entry : key_characteristics) {
203 allAuths.push_back(AuthorizationSet(entry.authorizations));
204 }
205 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
206 if (patchlevel.has_value()) {
207 return patchlevel.value();
208 } else {
209 // No boot patchlevel is available. Return a value that won't match anything
210 // and so will trigger test failures.
211 return kInvalidPatchlevel;
212 }
213}
214
215uint32_t KeyMintAidlTestBase::boot_patch_level() {
216 return boot_patch_level(key_characteristics_);
217}
218
Prashant Patil88ad1892022-03-15 16:31:02 +0000219/**
220 * An API to determine device IDs attestation is required or not,
221 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
222 */
223bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700224 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= __ANDROID_API_T__;
Prashant Patil88ad1892022-03-15 16:31:02 +0000225}
226
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000227/**
228 * An API to determine second IMEI ID attestation is required or not,
229 * which is supported for KeyMint version 3 or first_api_level greater than 33.
230 */
231bool KeyMintAidlTestBase::isSecondImeiIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700232 return AidlVersion() >= 3 && property_get_int32("ro.vendor.api_level", 0) > __ANDROID_API_T__;
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000233}
234
David Drysdale42fe1892021-10-14 14:43:46 +0100235bool KeyMintAidlTestBase::Curve25519Supported() {
236 // Strongbox never supports curve 25519.
237 if (SecLevel() == SecurityLevel::STRONGBOX) {
238 return false;
239 }
240
241 // Curve 25519 was included in version 2 of the KeyMint interface.
242 int32_t version = 0;
243 auto status = keymint_->getInterfaceVersion(&version);
244 if (!status.isOk()) {
245 ADD_FAILURE() << "Failed to determine interface version";
246 }
247 return version >= 2;
248}
249
Janis Danisevskis24c04702020-12-16 18:28:39 -0800250void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700251 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800252 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700253
254 KeyMintHardwareInfo info;
255 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
256
257 securityLevel_ = info.securityLevel;
258 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
259 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100260 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700261
262 os_version_ = getOsVersion();
263 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100264 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700265}
266
David Drysdale7dff4fc2021-12-10 10:10:52 +0000267int32_t KeyMintAidlTestBase::AidlVersion() {
268 int32_t version = 0;
269 auto status = keymint_->getInterfaceVersion(&version);
270 if (!status.isOk()) {
271 ADD_FAILURE() << "Failed to determine interface version";
272 }
273 return version;
274}
275
Selene Huang31ab4042020-04-29 04:22:39 -0700276void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800277 if (AServiceManager_isDeclared(GetParam().c_str())) {
278 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
279 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
280 } else {
281 InitializeKeyMint(nullptr);
282 }
Selene Huang31ab4042020-04-29 04:22:39 -0700283}
284
285ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700286 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700287 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700288 vector<KeyCharacteristics>* key_characteristics,
289 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700290 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
291 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700292 << "Previous characteristics not deleted before generating key. Test bug.";
293
Shawn Willden7f424372021-01-10 18:06:50 -0700294 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700295 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700296 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700297 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
298 creationResult.keyCharacteristics);
299 EXPECT_GT(creationResult.keyBlob.size(), 0);
300 *key_blob = std::move(creationResult.keyBlob);
301 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700302 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700303
304 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
305 EXPECT_TRUE(algorithm);
306 if (algorithm &&
307 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700308 EXPECT_GE(cert_chain->size(), 1);
309 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
310 if (attest_key) {
311 EXPECT_EQ(cert_chain->size(), 1);
312 } else {
313 EXPECT_GT(cert_chain->size(), 1);
314 }
315 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700316 } else {
317 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700318 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700319 }
Selene Huang31ab4042020-04-29 04:22:39 -0700320 }
321
322 return GetReturnErrorCode(result);
323}
324
Shawn Willden7c130392020-12-21 09:58:22 -0700325ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
326 const optional<AttestationKey>& attest_key) {
327 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700328}
329
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000330ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
331 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
332 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
333 vector<Certificate>* cert_chain) {
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +0000334 skipAttestKeyTest();
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000335 AttestationKey attest_key;
336 vector<Certificate> attest_cert_chain;
337 vector<KeyCharacteristics> attest_key_characteristics;
338 // Generate a key with self signed attestation.
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +0000339 auto error = GenerateAttestKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
340 &attest_key_characteristics, &attest_cert_chain);
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000341 if (error != ErrorCode::OK) {
342 return error;
343 }
344
345 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
346 // Generate a key, by passing the above self signed attestation key as attest key.
347 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
348 if (error == ErrorCode::OK) {
349 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
350 cert_chain->push_back(attest_cert_chain[0]);
351 }
352 return error;
353}
354
Selene Huang31ab4042020-04-29 04:22:39 -0700355ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
356 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700357 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700358 Status result;
359
Shawn Willden7f424372021-01-10 18:06:50 -0700360 cert_chain_.clear();
361 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700362 key_blob->clear();
363
Shawn Willden7f424372021-01-10 18:06:50 -0700364 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700365 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700366 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700367 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700368
369 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700370 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
371 creationResult.keyCharacteristics);
372 EXPECT_GT(creationResult.keyBlob.size(), 0);
373
374 *key_blob = std::move(creationResult.keyBlob);
375 *key_characteristics = std::move(creationResult.keyCharacteristics);
376 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700377
378 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
379 EXPECT_TRUE(algorithm);
380 if (algorithm &&
381 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
382 EXPECT_GE(cert_chain_.size(), 1);
383 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
384 } else {
385 // For symmetric keys there should be no certificates.
386 EXPECT_EQ(cert_chain_.size(), 0);
387 }
Selene Huang31ab4042020-04-29 04:22:39 -0700388 }
389
390 return GetReturnErrorCode(result);
391}
392
393ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
394 const string& key_material) {
395 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
396}
397
398ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
399 const AuthorizationSet& wrapping_key_desc,
400 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100401 const AuthorizationSet& unwrapping_params,
402 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700403 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
404
Shawn Willden7f424372021-01-10 18:06:50 -0700405 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700406
Shawn Willden7f424372021-01-10 18:06:50 -0700407 KeyCreationResult creationResult;
408 Status result = keymint_->importWrappedKey(
409 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
410 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100411 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700412
413 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700414 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
415 creationResult.keyCharacteristics);
416 EXPECT_GT(creationResult.keyBlob.size(), 0);
417
418 key_blob_ = std::move(creationResult.keyBlob);
419 key_characteristics_ = std::move(creationResult.keyCharacteristics);
420 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700421
422 AuthorizationSet allAuths;
423 for (auto& entry : key_characteristics_) {
424 allAuths.push_back(AuthorizationSet(entry.authorizations));
425 }
426 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
427 EXPECT_TRUE(algorithm);
428 if (algorithm &&
429 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
430 EXPECT_GE(cert_chain_.size(), 1);
431 } else {
432 // For symmetric keys there should be no certificates.
433 EXPECT_EQ(cert_chain_.size(), 0);
434 }
Selene Huang31ab4042020-04-29 04:22:39 -0700435 }
436
437 return GetReturnErrorCode(result);
438}
439
David Drysdale300b5552021-05-20 12:05:26 +0100440ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
441 const vector<uint8_t>& app_id,
442 const vector<uint8_t>& app_data,
443 vector<KeyCharacteristics>* key_characteristics) {
444 Status result =
445 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
446 return GetReturnErrorCode(result);
447}
448
449ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
450 vector<KeyCharacteristics>* key_characteristics) {
451 vector<uint8_t> empty_app_id, empty_app_data;
452 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
453}
454
455void KeyMintAidlTestBase::CheckCharacteristics(
456 const vector<uint8_t>& key_blob,
457 const vector<KeyCharacteristics>& generate_characteristics) {
458 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
459 // generateKey() should be excluded, as KeyMint will have no record of them.
460 // This applies to CREATION_DATETIME in particular.
461 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
462 strip_keystore_tags(&expected_characteristics);
463
464 vector<KeyCharacteristics> retrieved;
465 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
466 EXPECT_EQ(expected_characteristics, retrieved);
467}
468
469void KeyMintAidlTestBase::CheckAppIdCharacteristics(
470 const vector<uint8_t>& key_blob, std::string_view app_id_string,
471 std::string_view app_data_string,
472 const vector<KeyCharacteristics>& generate_characteristics) {
473 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
474 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
475 strip_keystore_tags(&expected_characteristics);
476
477 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
478 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
479 vector<KeyCharacteristics> retrieved;
480 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
481 EXPECT_EQ(expected_characteristics, retrieved);
482
483 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
484 vector<uint8_t> empty;
485 vector<KeyCharacteristics> not_retrieved;
486 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
487 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
488 EXPECT_EQ(not_retrieved.size(), 0);
489
490 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
491 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
492 EXPECT_EQ(not_retrieved.size(), 0);
493
494 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
495 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
496 EXPECT_EQ(not_retrieved.size(), 0);
497}
498
Selene Huang31ab4042020-04-29 04:22:39 -0700499ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
500 Status result = keymint_->deleteKey(*key_blob);
501 if (!keep_key_blob) {
502 *key_blob = vector<uint8_t>();
503 }
504
Janis Danisevskis24c04702020-12-16 18:28:39 -0800505 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700506 return GetReturnErrorCode(result);
507}
508
509ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
510 return DeleteKey(&key_blob_, keep_key_blob);
511}
512
513ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
514 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800515 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700516 return GetReturnErrorCode(result);
517}
518
David Drysdaled2cc8c22021-04-15 13:29:45 +0100519ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
520 Status result = keymint_->destroyAttestationIds();
521 return GetReturnErrorCode(result);
522}
523
Selene Huang31ab4042020-04-29 04:22:39 -0700524void KeyMintAidlTestBase::CheckedDeleteKey() {
David Drysdale1b9febc2023-06-07 13:43:24 +0100525 ErrorCode result = DeleteKey(&key_blob_, /* keep_key_blob = */ false);
526 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700527}
528
529ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
530 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800531 AuthorizationSet* out_params,
532 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700533 SCOPED_TRACE("Begin");
534 Status result;
535 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100536 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700537
538 if (result.isOk()) {
539 *out_params = out.params;
540 challenge_ = out.challenge;
541 op = out.operation;
542 }
543
544 return GetReturnErrorCode(result);
545}
546
547ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
548 const AuthorizationSet& in_params,
David Drysdale28fa9312023-02-01 14:53:01 +0000549 AuthorizationSet* out_params,
550 std::optional<HardwareAuthToken> hat) {
Selene Huang31ab4042020-04-29 04:22:39 -0700551 SCOPED_TRACE("Begin");
552 Status result;
553 BeginResult out;
554
David Drysdale28fa9312023-02-01 14:53:01 +0000555 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), hat, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700556
557 if (result.isOk()) {
558 *out_params = out.params;
559 challenge_ = out.challenge;
560 op_ = out.operation;
561 }
562
563 return GetReturnErrorCode(result);
564}
565
566ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
567 AuthorizationSet* out_params) {
568 SCOPED_TRACE("Begin");
569 EXPECT_EQ(nullptr, op_);
570 return Begin(purpose, key_blob_, in_params, out_params);
571}
572
573ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
574 SCOPED_TRACE("Begin");
575 AuthorizationSet out_params;
576 ErrorCode result = Begin(purpose, in_params, &out_params);
577 EXPECT_TRUE(out_params.empty());
578 return result;
579}
580
Shawn Willden92d79c02021-02-19 07:31:55 -0700581ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
582 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
583 {} /* hardwareAuthToken */,
584 {} /* verificationToken */));
585}
586
587ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700588 SCOPED_TRACE("Update");
589
590 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700591 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700592
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800593 EXPECT_NE(op_, nullptr);
594 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
595
Shawn Willden92d79c02021-02-19 07:31:55 -0700596 std::vector<uint8_t> o_put;
597 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700598
David Drysdalefeab5d92022-01-06 15:46:23 +0000599 if (result.isOk()) {
600 output->append(o_put.begin(), o_put.end());
601 } else {
602 // Failure always terminates the operation.
603 op_ = {};
604 }
Selene Huang31ab4042020-04-29 04:22:39 -0700605
606 return GetReturnErrorCode(result);
607}
608
David Drysdale28fa9312023-02-01 14:53:01 +0000609ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, string* output,
610 std::optional<HardwareAuthToken> hat,
611 std::optional<secureclock::TimeStampToken> time_token) {
Selene Huang31ab4042020-04-29 04:22:39 -0700612 SCOPED_TRACE("Finish");
613 Status result;
614
615 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700616 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700617
618 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700619 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
David Drysdale28fa9312023-02-01 14:53:01 +0000620 vector<uint8_t>(signature.begin(), signature.end()), hat, time_token,
621 {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700622
Shawn Willden92d79c02021-02-19 07:31:55 -0700623 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700624
Shawn Willden92d79c02021-02-19 07:31:55 -0700625 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700626 return GetReturnErrorCode(result);
627}
628
Janis Danisevskis24c04702020-12-16 18:28:39 -0800629ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700630 SCOPED_TRACE("Abort");
631
632 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700633 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700634
635 Status retval = op->abort();
636 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800637 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700638}
639
640ErrorCode KeyMintAidlTestBase::Abort() {
641 SCOPED_TRACE("Abort");
642
643 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700644 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700645
646 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800647 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700648}
649
650void KeyMintAidlTestBase::AbortIfNeeded() {
651 SCOPED_TRACE("AbortIfNeeded");
652 if (op_) {
653 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800654 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700655 }
656}
657
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000658auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
659 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700660 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000661 AuthorizationSet begin_out_params;
662 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700663 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000664
665 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700666 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000667}
668
Selene Huang31ab4042020-04-29 04:22:39 -0700669string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
670 const string& message, const AuthorizationSet& in_params,
671 AuthorizationSet* out_params) {
672 SCOPED_TRACE("ProcessMessage");
673 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700674 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700675 EXPECT_EQ(ErrorCode::OK, result);
676 if (result != ErrorCode::OK) {
677 return "";
678 }
679
680 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700681 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700682 return output;
683}
684
685string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
686 const AuthorizationSet& params) {
687 SCOPED_TRACE("SignMessage");
688 AuthorizationSet out_params;
689 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
690 EXPECT_TRUE(out_params.empty());
691 return signature;
692}
693
694string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
695 SCOPED_TRACE("SignMessage");
696 return SignMessage(key_blob_, message, params);
697}
698
699string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
700 SCOPED_TRACE("MacMessage");
701 return SignMessage(
702 key_blob_, message,
703 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
704}
705
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530706void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
707 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000708 auto builder = AuthorizationSetBuilder()
709 .Authorization(TAG_NO_AUTH_REQUIRED)
710 .AesEncryptionKey(128)
711 .BlockMode(block_mode)
712 .Padding(PaddingMode::NONE);
713 if (block_mode == BlockMode::GCM) {
714 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
715 }
716 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530717
718 for (int increment = 1; increment <= message_size; ++increment) {
719 string message(message_size, 'a');
720 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
721 if (block_mode == BlockMode::GCM) {
722 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
723 }
724
725 AuthorizationSet output_params;
726 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
727
728 string ciphertext;
729 string to_send;
730 for (size_t i = 0; i < message.size(); i += increment) {
731 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
732 }
733 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
734 << "Error sending " << to_send << " with block mode " << block_mode;
735
736 switch (block_mode) {
737 case BlockMode::GCM:
738 EXPECT_EQ(message.size() + 16, ciphertext.size());
739 break;
740 case BlockMode::CTR:
741 EXPECT_EQ(message.size(), ciphertext.size());
742 break;
743 case BlockMode::CBC:
744 case BlockMode::ECB:
745 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
746 break;
747 }
748
749 auto iv = output_params.GetTagValue(TAG_NONCE);
750 switch (block_mode) {
751 case BlockMode::CBC:
752 case BlockMode::GCM:
753 case BlockMode::CTR:
754 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
755 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
756 params.push_back(TAG_NONCE, iv->get());
757 break;
758
759 case BlockMode::ECB:
760 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
761 break;
762 }
763
764 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
765 << "Decrypt begin() failed for block mode " << block_mode;
766
767 string plaintext;
768 for (size_t i = 0; i < ciphertext.size(); i += increment) {
769 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
770 }
771 ErrorCode error = Finish(to_send, &plaintext);
772 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
773 << " and increment " << increment;
774 if (error == ErrorCode::OK) {
775 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
776 << " and increment " << increment;
777 }
778 }
779}
780
Prashant Patildd5f7f02022-07-06 18:58:07 +0000781void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
782 PaddingMode padding_mode, const string& iv,
783 const string& plaintext,
784 const string& exp_cipher_text) {
785 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
786 auto auth_set = AuthorizationSetBuilder()
787 .Authorization(TAG_NO_AUTH_REQUIRED)
788 .AesEncryptionKey(key.size() * 8)
789 .BlockMode(block_mode)
790 .Padding(padding_mode);
791 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
792 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
793 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
794
795 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
796 exp_cipher_text);
797}
798
799void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
800 PaddingMode padding_mode, const string& iv,
801 const string& plaintext,
802 const string& exp_cipher_text) {
803 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
804 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
805 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
806 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
807 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
808
809 AuthorizationSet output_params;
810 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
811
812 string actual_ciphertext;
813 if (is_stream_cipher) {
814 // Assert that a 1 byte of output is produced for 1 byte of input.
815 // Every input byte produces an output byte.
816 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
817 string ciphertext;
818 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
819 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
820 // we relax this API restriction for them.
821 if (SecLevel() != SecurityLevel::STRONGBOX) {
822 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
823 }
824 actual_ciphertext.append(ciphertext);
825 }
826 string ciphertext;
827 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
828 if (SecLevel() != SecurityLevel::STRONGBOX) {
829 string expected_final_output;
830 if (is_authenticated_cipher) {
831 expected_final_output = exp_cipher_text.substr(plaintext.size());
832 }
833 EXPECT_EQ(expected_final_output, ciphertext);
834 }
835 actual_ciphertext.append(ciphertext);
836 } else {
837 // Assert that a block of output is produced once a full block of input is provided.
838 // Every input block produces an output block.
839 bool compare_output = true;
840 string additional_information;
841 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
842 if (SecLevel() == SecurityLevel::STRONGBOX) {
843 // This is known to be broken on older vendor implementations.
Shawn Willden1a545db2023-02-22 14:32:33 -0700844 if (vendor_api_level < __ANDROID_API_T__) {
Prashant Patildd5f7f02022-07-06 18:58:07 +0000845 compare_output = false;
846 } else {
847 additional_information = " (b/194134359) ";
848 }
849 }
850 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
851 string ciphertext;
852 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
853 if (compare_output) {
854 if ((plaintext_index % block_size) == block_size - 1) {
855 // Update is expected to have output a new block
856 EXPECT_EQ(block_size, ciphertext.size())
857 << "plaintext index: " << plaintext_index << additional_information;
858 } else {
859 // Update is expected to have produced no output
860 EXPECT_EQ(0, ciphertext.size())
861 << "plaintext index: " << plaintext_index << additional_information;
862 }
863 }
864 actual_ciphertext.append(ciphertext);
865 }
866 string ciphertext;
867 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
868 actual_ciphertext.append(ciphertext);
869 }
870 // Regardless of how the completed ciphertext got accumulated, it should match the expected
871 // ciphertext.
872 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
873}
874
Selene Huang31ab4042020-04-29 04:22:39 -0700875void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
876 Digest digest, const string& expected_mac) {
877 SCOPED_TRACE("CheckHmacTestVector");
878 ASSERT_EQ(ErrorCode::OK,
879 ImportKey(AuthorizationSetBuilder()
880 .Authorization(TAG_NO_AUTH_REQUIRED)
881 .HmacKey(key.size() * 8)
882 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
883 .Digest(digest),
884 KeyFormat::RAW, key));
885 string signature = MacMessage(message, digest, expected_mac.size() * 8);
886 EXPECT_EQ(expected_mac, signature)
887 << "Test vector didn't match for key of size " << key.size() << " message of size "
888 << message.size() << " and digest " << digest;
889 CheckedDeleteKey();
890}
891
892void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
893 const string& message,
894 const string& expected_ciphertext) {
895 SCOPED_TRACE("CheckAesCtrTestVector");
896 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
897 .Authorization(TAG_NO_AUTH_REQUIRED)
898 .AesEncryptionKey(key.size() * 8)
899 .BlockMode(BlockMode::CTR)
900 .Authorization(TAG_CALLER_NONCE)
901 .Padding(PaddingMode::NONE),
902 KeyFormat::RAW, key));
903
904 auto params = AuthorizationSetBuilder()
905 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
906 .BlockMode(BlockMode::CTR)
907 .Padding(PaddingMode::NONE);
908 AuthorizationSet out_params;
909 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
910 EXPECT_EQ(expected_ciphertext, ciphertext);
911}
912
913void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
914 PaddingMode padding_mode, const string& key,
915 const string& iv, const string& input,
916 const string& expected_output) {
917 auto authset = AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key.size() * 7)
919 .BlockMode(block_mode)
920 .Authorization(TAG_NO_AUTH_REQUIRED)
921 .Padding(padding_mode);
922 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
923 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
924 ASSERT_GT(key_blob_.size(), 0U);
925
926 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
927 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
928 AuthorizationSet output_params;
929 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
930 EXPECT_EQ(expected_output, output);
931}
932
933void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
934 const string& signature, const AuthorizationSet& params) {
935 SCOPED_TRACE("VerifyMessage");
936 AuthorizationSet begin_out_params;
937 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
938
939 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700940 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700941 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700942 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700943}
944
945void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
946 const AuthorizationSet& params) {
947 SCOPED_TRACE("VerifyMessage");
948 VerifyMessage(key_blob_, message, signature, params);
949}
950
David Drysdaledf8f52e2021-05-06 08:10:58 +0100951void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
952 const AuthorizationSet& params) {
953 SCOPED_TRACE("LocalVerifyMessage");
954
David Drysdaledf8f52e2021-05-06 08:10:58 +0100955 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000956 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
957}
958
959void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
960 const string& signature,
961 const AuthorizationSet& params) {
962 // Retrieve the public key from the leaf certificate.
963 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100964 ASSERT_TRUE(key_cert.get());
965 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
966 ASSERT_TRUE(pub_key.get());
967
968 Digest digest = params.GetTagValue(TAG_DIGEST).value();
969 PaddingMode padding = PaddingMode::NONE;
970 auto tag = params.GetTagValue(TAG_PADDING);
971 if (tag.has_value()) {
972 padding = tag.value();
973 }
974
975 if (digest == Digest::NONE) {
976 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100977 case EVP_PKEY_ED25519: {
978 ASSERT_EQ(64, signature.size());
979 uint8_t pub_keydata[32];
980 size_t pub_len = sizeof(pub_keydata);
981 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
982 ASSERT_EQ(sizeof(pub_keydata), pub_len);
983 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
984 message.size(),
985 reinterpret_cast<const uint8_t*>(signature.data()),
986 pub_keydata));
987 break;
988 }
989
David Drysdaledf8f52e2021-05-06 08:10:58 +0100990 case EVP_PKEY_EC: {
991 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
992 size_t data_size = std::min(data.size(), message.size());
993 memcpy(data.data(), message.data(), data_size);
994 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
995 ASSERT_TRUE(ecdsa.get());
996 ASSERT_EQ(1,
997 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
998 reinterpret_cast<const uint8_t*>(signature.data()),
999 signature.size(), ecdsa.get()));
1000 break;
1001 }
1002 case EVP_PKEY_RSA: {
1003 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
1004 size_t data_size = std::min(data.size(), message.size());
1005 memcpy(data.data(), message.data(), data_size);
1006
1007 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1008 ASSERT_TRUE(rsa.get());
1009
1010 size_t key_len = RSA_size(rsa.get());
1011 int openssl_padding = RSA_NO_PADDING;
1012 switch (padding) {
1013 case PaddingMode::NONE:
1014 ASSERT_TRUE(data_size <= key_len);
1015 ASSERT_EQ(key_len, signature.size());
1016 openssl_padding = RSA_NO_PADDING;
1017 break;
1018 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1019 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1020 key_len);
1021 openssl_padding = RSA_PKCS1_PADDING;
1022 break;
1023 default:
1024 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1025 }
1026
1027 vector<uint8_t> decrypted_data(key_len);
1028 int bytes_decrypted = RSA_public_decrypt(
1029 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1030 decrypted_data.data(), rsa.get(), openssl_padding);
1031 ASSERT_GE(bytes_decrypted, 0);
1032
1033 const uint8_t* compare_pos = decrypted_data.data();
1034 size_t bytes_to_compare = bytes_decrypted;
1035 uint8_t zero_check_result = 0;
1036 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1037 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1038 // during verification we should have zeros on the left of the decrypted data.
1039 // Do a constant-time check.
1040 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1041 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1042 ASSERT_EQ(0, zero_check_result);
1043 bytes_to_compare = data_size;
1044 }
1045 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1046 break;
1047 }
1048 default:
1049 ADD_FAILURE() << "Unknown public key type";
1050 }
1051 } else {
1052 EVP_MD_CTX digest_ctx;
1053 EVP_MD_CTX_init(&digest_ctx);
1054 EVP_PKEY_CTX* pkey_ctx;
1055 const EVP_MD* md = openssl_digest(digest);
1056 ASSERT_NE(md, nullptr);
1057 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1058
1059 if (padding == PaddingMode::RSA_PSS) {
1060 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1061 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001062 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001063 }
1064
1065 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1066 reinterpret_cast<const uint8_t*>(message.data()),
1067 message.size()));
1068 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1069 reinterpret_cast<const uint8_t*>(signature.data()),
1070 signature.size()));
1071 EVP_MD_CTX_cleanup(&digest_ctx);
1072 }
1073}
1074
David Drysdale59cae642021-05-12 13:52:03 +01001075string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1076 const AuthorizationSet& params) {
1077 SCOPED_TRACE("LocalRsaEncryptMessage");
1078
1079 // Retrieve the public key from the leaf certificate.
1080 if (cert_chain_.empty()) {
1081 ADD_FAILURE() << "No public key available";
1082 return "Failure";
1083 }
1084 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001085 if (key_cert.get() == nullptr) {
1086 ADD_FAILURE() << "Failed to parse cert";
1087 return "Failure";
1088 }
David Drysdale59cae642021-05-12 13:52:03 +01001089 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001090 if (pub_key.get() == nullptr) {
1091 ADD_FAILURE() << "Failed to retrieve public key";
1092 return "Failure";
1093 }
David Drysdale59cae642021-05-12 13:52:03 +01001094 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001095 if (rsa.get() == nullptr) {
1096 ADD_FAILURE() << "Failed to retrieve RSA public key";
1097 return "Failure";
1098 }
David Drysdale59cae642021-05-12 13:52:03 +01001099
1100 // Retrieve relevant tags.
1101 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001102 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001103 PaddingMode padding = PaddingMode::NONE;
1104
1105 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1106 if (digest_tag.has_value()) digest = digest_tag.value();
1107 auto pad_tag = params.GetTagValue(TAG_PADDING);
1108 if (pad_tag.has_value()) padding = pad_tag.value();
1109 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1110 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1111
1112 const EVP_MD* md = openssl_digest(digest);
1113 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1114
1115 // Set up encryption context.
1116 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1117 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1118 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1119 return "Failure";
1120 }
1121
1122 int rc = -1;
1123 switch (padding) {
1124 case PaddingMode::NONE:
1125 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1126 break;
1127 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1128 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1129 break;
1130 case PaddingMode::RSA_OAEP:
1131 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1132 break;
1133 default:
1134 break;
1135 }
1136 if (rc <= 0) {
1137 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1138 return "Failure";
1139 }
1140 if (padding == PaddingMode::RSA_OAEP) {
1141 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1142 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1143 return "Failure";
1144 }
1145 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1146 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1147 return "Failure";
1148 }
1149 }
1150
1151 // Determine output size.
1152 size_t outlen;
1153 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1154 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1155 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1156 return "Failure";
1157 }
1158
1159 // Left-zero-pad the input if necessary.
1160 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1161 size_t to_encrypt_len = message.size();
1162
1163 std::unique_ptr<string> zero_padded_message;
1164 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1165 zero_padded_message.reset(new string(outlen, '\0'));
1166 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1167 message.size());
1168 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1169 to_encrypt_len = outlen;
1170 }
1171
1172 // Do the encryption.
1173 string output(outlen, '\0');
1174 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1175 to_encrypt_len) <= 0) {
1176 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1177 return "Failure";
1178 }
1179 return output;
1180}
1181
Selene Huang31ab4042020-04-29 04:22:39 -07001182string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1183 const AuthorizationSet& in_params,
1184 AuthorizationSet* out_params) {
1185 SCOPED_TRACE("EncryptMessage");
1186 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1187}
1188
1189string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1190 AuthorizationSet* out_params) {
1191 SCOPED_TRACE("EncryptMessage");
1192 return EncryptMessage(key_blob_, message, params, out_params);
1193}
1194
1195string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1196 SCOPED_TRACE("EncryptMessage");
1197 AuthorizationSet out_params;
1198 string ciphertext = EncryptMessage(message, params, &out_params);
1199 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1200 return ciphertext;
1201}
1202
1203string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1204 PaddingMode padding) {
1205 SCOPED_TRACE("EncryptMessage");
1206 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1207 AuthorizationSet out_params;
1208 string ciphertext = EncryptMessage(message, params, &out_params);
1209 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1210 return ciphertext;
1211}
1212
1213string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1214 PaddingMode padding, vector<uint8_t>* iv_out) {
1215 SCOPED_TRACE("EncryptMessage");
1216 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1217 AuthorizationSet out_params;
1218 string ciphertext = EncryptMessage(message, params, &out_params);
1219 EXPECT_EQ(1U, out_params.size());
1220 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001221 EXPECT_TRUE(ivVal);
1222 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001223 return ciphertext;
1224}
1225
1226string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1227 PaddingMode padding, const vector<uint8_t>& iv_in) {
1228 SCOPED_TRACE("EncryptMessage");
1229 auto params = AuthorizationSetBuilder()
1230 .BlockMode(block_mode)
1231 .Padding(padding)
1232 .Authorization(TAG_NONCE, iv_in);
1233 AuthorizationSet out_params;
1234 string ciphertext = EncryptMessage(message, params, &out_params);
1235 return ciphertext;
1236}
1237
1238string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1239 PaddingMode padding, uint8_t mac_length_bits,
1240 const vector<uint8_t>& iv_in) {
1241 SCOPED_TRACE("EncryptMessage");
1242 auto params = AuthorizationSetBuilder()
1243 .BlockMode(block_mode)
1244 .Padding(padding)
1245 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1246 .Authorization(TAG_NONCE, iv_in);
1247 AuthorizationSet out_params;
1248 string ciphertext = EncryptMessage(message, params, &out_params);
1249 return ciphertext;
1250}
1251
David Drysdaled2cc8c22021-04-15 13:29:45 +01001252string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1253 PaddingMode padding, uint8_t mac_length_bits) {
1254 SCOPED_TRACE("EncryptMessage");
1255 auto params = AuthorizationSetBuilder()
1256 .BlockMode(block_mode)
1257 .Padding(padding)
1258 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1259 AuthorizationSet out_params;
1260 string ciphertext = EncryptMessage(message, params, &out_params);
1261 return ciphertext;
1262}
1263
Selene Huang31ab4042020-04-29 04:22:39 -07001264string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1265 const string& ciphertext,
1266 const AuthorizationSet& params) {
1267 SCOPED_TRACE("DecryptMessage");
1268 AuthorizationSet out_params;
1269 string plaintext =
1270 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1271 EXPECT_TRUE(out_params.empty());
1272 return plaintext;
1273}
1274
1275string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1276 const AuthorizationSet& params) {
1277 SCOPED_TRACE("DecryptMessage");
1278 return DecryptMessage(key_blob_, ciphertext, params);
1279}
1280
1281string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1282 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1283 SCOPED_TRACE("DecryptMessage");
1284 auto params = AuthorizationSetBuilder()
1285 .BlockMode(block_mode)
1286 .Padding(padding_mode)
1287 .Authorization(TAG_NONCE, iv);
1288 return DecryptMessage(key_blob_, ciphertext, params);
1289}
1290
1291std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1292 const vector<uint8_t>& key_blob) {
1293 std::pair<ErrorCode, vector<uint8_t>> retval;
1294 vector<uint8_t> outKeyBlob;
1295 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1296 ErrorCode errorcode = GetReturnErrorCode(result);
1297 retval = std::tie(errorcode, outKeyBlob);
1298
1299 return retval;
1300}
Seth Moorea12ac742023-03-03 13:40:30 -08001301
1302bool KeyMintAidlTestBase::IsRkpSupportRequired() const {
1303 if (get_vsr_api_level() >= __ANDROID_API_T__) {
1304 return true;
1305 }
1306
1307 if (get_vsr_api_level() >= __ANDROID_API_S__) {
1308 return SecLevel() != SecurityLevel::STRONGBOX;
1309 }
1310
1311 return false;
1312}
1313
Selene Huang31ab4042020-04-29 04:22:39 -07001314vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1315 switch (algorithm) {
1316 case Algorithm::RSA:
1317 switch (SecLevel()) {
1318 case SecurityLevel::SOFTWARE:
1319 case SecurityLevel::TRUSTED_ENVIRONMENT:
1320 return {2048, 3072, 4096};
1321 case SecurityLevel::STRONGBOX:
1322 return {2048};
1323 default:
1324 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1325 break;
1326 }
1327 break;
1328 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001329 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001330 break;
1331 case Algorithm::AES:
1332 return {128, 256};
1333 case Algorithm::TRIPLE_DES:
1334 return {168};
1335 case Algorithm::HMAC: {
1336 vector<uint32_t> retval((512 - 64) / 8 + 1);
1337 uint32_t size = 64 - 8;
1338 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1339 return retval;
1340 }
1341 default:
1342 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1343 return {};
1344 }
1345 ADD_FAILURE() << "Should be impossible to get here";
1346 return {};
1347}
1348
1349vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1350 if (SecLevel() == SecurityLevel::STRONGBOX) {
1351 switch (algorithm) {
1352 case Algorithm::RSA:
1353 return {3072, 4096};
1354 case Algorithm::EC:
1355 return {224, 384, 521};
1356 case Algorithm::AES:
1357 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001358 case Algorithm::TRIPLE_DES:
1359 return {56};
1360 default:
1361 return {};
1362 }
1363 } else {
1364 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001365 case Algorithm::AES:
1366 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001367 case Algorithm::TRIPLE_DES:
1368 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001369 default:
1370 return {};
1371 }
1372 }
1373 return {};
1374}
1375
David Drysdale7de9feb2021-03-05 14:56:19 +00001376vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1377 switch (algorithm) {
1378 case Algorithm::AES:
1379 return {
1380 BlockMode::CBC,
1381 BlockMode::CTR,
1382 BlockMode::ECB,
1383 BlockMode::GCM,
1384 };
1385 case Algorithm::TRIPLE_DES:
1386 return {
1387 BlockMode::CBC,
1388 BlockMode::ECB,
1389 };
1390 default:
1391 return {};
1392 }
1393}
1394
1395vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1396 BlockMode blockMode) {
1397 switch (algorithm) {
1398 case Algorithm::AES:
1399 switch (blockMode) {
1400 case BlockMode::CBC:
1401 case BlockMode::ECB:
1402 return {PaddingMode::NONE, PaddingMode::PKCS7};
1403 case BlockMode::CTR:
1404 case BlockMode::GCM:
1405 return {PaddingMode::NONE};
1406 default:
1407 return {};
1408 };
1409 case Algorithm::TRIPLE_DES:
1410 switch (blockMode) {
1411 case BlockMode::CBC:
1412 case BlockMode::ECB:
1413 return {PaddingMode::NONE, PaddingMode::PKCS7};
1414 default:
1415 return {};
1416 };
1417 default:
1418 return {};
1419 }
1420}
1421
1422vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1423 BlockMode blockMode) {
1424 switch (algorithm) {
1425 case Algorithm::AES:
1426 switch (blockMode) {
1427 case BlockMode::CTR:
1428 case BlockMode::GCM:
1429 return {PaddingMode::PKCS7};
1430 default:
1431 return {};
1432 };
1433 default:
1434 return {};
1435 }
1436}
1437
Selene Huang31ab4042020-04-29 04:22:39 -07001438vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1439 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1440 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001441 } else if (Curve25519Supported()) {
1442 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1443 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001444 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001445 return {
1446 EcCurve::P_224,
1447 EcCurve::P_256,
1448 EcCurve::P_384,
1449 EcCurve::P_521,
1450 };
Selene Huang31ab4042020-04-29 04:22:39 -07001451 }
1452}
1453
1454vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001455 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001456 // Curve 25519 is not supported, either because:
1457 // - KeyMint v1: it's an unknown enum value
1458 // - KeyMint v2+: it's not supported by StrongBox.
1459 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001460 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001461 if (Curve25519Supported()) {
1462 return {};
1463 } else {
1464 return {EcCurve::CURVE_25519};
1465 }
David Drysdaledf09e542021-06-08 15:46:11 +01001466 }
Selene Huang31ab4042020-04-29 04:22:39 -07001467}
1468
subrahmanyaman05642492022-02-05 07:10:56 +00001469vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1470 if (SecLevel() == SecurityLevel::STRONGBOX) {
1471 return {65537};
1472 } else {
1473 return {3, 65537};
1474 }
1475}
1476
Selene Huang31ab4042020-04-29 04:22:39 -07001477vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1478 switch (SecLevel()) {
1479 case SecurityLevel::SOFTWARE:
1480 case SecurityLevel::TRUSTED_ENVIRONMENT:
1481 if (withNone) {
1482 if (withMD5)
1483 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1484 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1485 Digest::SHA_2_512};
1486 else
1487 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1488 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1489 } else {
1490 if (withMD5)
1491 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1492 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1493 else
1494 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1495 Digest::SHA_2_512};
1496 }
1497 break;
1498 case SecurityLevel::STRONGBOX:
1499 if (withNone)
1500 return {Digest::NONE, Digest::SHA_2_256};
1501 else
1502 return {Digest::SHA_2_256};
1503 break;
1504 default:
1505 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1506 break;
1507 }
1508 ADD_FAILURE() << "Should be impossible to get here";
1509 return {};
1510}
1511
Shawn Willden7f424372021-01-10 18:06:50 -07001512static const vector<KeyParameter> kEmptyAuthList{};
1513
1514const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1515 const vector<KeyCharacteristics>& key_characteristics) {
1516 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1517 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1518 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1519}
1520
Qi Wubeefae42021-01-28 23:16:37 +08001521const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1522 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1523 auto found = std::find_if(
1524 key_characteristics.begin(), key_characteristics.end(),
1525 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001526 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1527}
1528
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001529ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001530 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001531 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1532 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1533 return result;
1534}
1535
1536ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001537 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001538 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1539 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1540 return result;
1541}
1542
1543ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1544 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001545 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001546 rsaKeyBlob, KeyPurpose::SIGN, message,
1547 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1548 return result;
1549}
1550
1551ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001552 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1553 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001554 return result;
1555}
1556
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001557ErrorCode KeyMintAidlTestBase::GenerateAttestKey(const AuthorizationSet& key_desc,
1558 const optional<AttestationKey>& attest_key,
1559 vector<uint8_t>* key_blob,
1560 vector<KeyCharacteristics>* key_characteristics,
1561 vector<Certificate>* cert_chain) {
1562 // The original specification for KeyMint v1 required ATTEST_KEY not be combined
1563 // with any other key purpose, but the original VTS tests incorrectly did exactly that.
1564 // This means that a device that launched prior to Android T (API level 33) may
1565 // accept or even require KeyPurpose::SIGN too.
1566 if (property_get_int32("ro.board.first_api_level", 0) < __ANDROID_API_T__) {
1567 AuthorizationSet key_desc_plus_sign = key_desc;
1568 key_desc_plus_sign.push_back(TAG_PURPOSE, KeyPurpose::SIGN);
1569
1570 auto result = GenerateKey(key_desc_plus_sign, attest_key, key_blob, key_characteristics,
1571 cert_chain);
1572 if (result == ErrorCode::OK) {
1573 return result;
1574 }
1575 // If the key generation failed, it may be because the device is (correctly)
1576 // rejecting the combination of ATTEST_KEY+SIGN. Fall through to try again with
1577 // just ATTEST_KEY.
1578 }
1579 return GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
1580}
1581
1582// Check if ATTEST_KEY feature is disabled
1583bool KeyMintAidlTestBase::is_attest_key_feature_disabled(void) const {
1584 if (!check_feature(FEATURE_KEYSTORE_APP_ATTEST_KEY)) {
1585 GTEST_LOG_(INFO) << "Feature " + FEATURE_KEYSTORE_APP_ATTEST_KEY + " is disabled";
1586 return true;
1587 }
1588
1589 return false;
1590}
1591
1592// Check if StrongBox KeyStore is enabled
1593bool KeyMintAidlTestBase::is_strongbox_enabled(void) const {
1594 if (check_feature(FEATURE_STRONGBOX_KEYSTORE)) {
1595 GTEST_LOG_(INFO) << "Feature " + FEATURE_STRONGBOX_KEYSTORE + " is enabled";
1596 return true;
1597 }
1598
1599 return false;
1600}
1601
1602// Check if chipset has received a waiver allowing it to be launched with Android S or T with
1603// Keymaster 4.0 in StrongBox.
1604bool KeyMintAidlTestBase::is_chipset_allowed_km4_strongbox(void) const {
1605 std::array<char, PROPERTY_VALUE_MAX> buffer;
1606
1607 const int32_t first_api_level = property_get_int32("ro.board.first_api_level", 0);
1608 if (first_api_level <= 0 || first_api_level > __ANDROID_API_T__) return false;
1609
1610 auto res = property_get("ro.vendor.qti.soc_model", buffer.data(), nullptr);
1611 if (res <= 0) return false;
1612
Shawn Willden0f1b2572023-05-30 14:52:53 -06001613 const string allowed_soc_models[] = {"SM8450", "SM8475", "SM8550", "SXR2230P",
1614 "SM4450", "SM7450", "SM6450"};
Subrahmanyaman50fcf7d2023-04-20 22:48:39 +00001615
1616 for (const string model : allowed_soc_models) {
1617 if (model.compare(buffer.data()) == 0) {
1618 GTEST_LOG_(INFO) << "QTI SOC Model " + model + " is allowed SB KM 4.0";
1619 return true;
1620 }
1621 }
1622
1623 return false;
1624}
1625
1626// Skip the test if all the following conditions hold:
1627// 1. ATTEST_KEY feature is disabled
1628// 2. STRONGBOX is enabled
1629// 3. The device is running one of the chipsets that have received a waiver
1630// allowing it to be launched with Android S (or later) with Keymaster 4.0
1631// in StrongBox
1632void KeyMintAidlTestBase::skipAttestKeyTest(void) const {
1633 // Check the chipset first as that doesn't require a round-trip to Package Manager.
1634 if (is_chipset_allowed_km4_strongbox() && is_strongbox_enabled() &&
1635 is_attest_key_feature_disabled()) {
1636 GTEST_SKIP() << "Test is not applicable";
1637 }
1638}
1639
Selene Huang6e46f142021-04-20 19:20:11 -07001640void verify_serial(X509* cert, const uint64_t expected_serial) {
1641 BIGNUM_Ptr ser(BN_new());
1642 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1643
1644 uint64_t serial;
1645 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1646 EXPECT_EQ(serial, expected_serial);
1647}
1648
1649// Please set self_signed to true for fake certificates or self signed
1650// certificates
1651void verify_subject(const X509* cert, //
1652 const string& subject, //
1653 bool self_signed) {
1654 char* cert_issuer = //
1655 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1656
1657 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1658
1659 string expected_subject("/CN=");
1660 if (subject.empty()) {
1661 expected_subject.append("Android Keystore Key");
1662 } else {
1663 expected_subject.append(subject);
1664 }
1665
1666 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1667
1668 if (self_signed) {
1669 EXPECT_STREQ(cert_issuer, cert_subj)
1670 << "Cert issuer and subject mismatch for self signed certificate.";
1671 }
1672
1673 OPENSSL_free(cert_subj);
1674 OPENSSL_free(cert_issuer);
1675}
1676
Shawn Willden22fb9c12022-06-02 14:04:33 -06001677int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001678 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1679 if (vendor_api_level != -1) {
1680 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001681 }
Shawn Willden35db3492022-06-16 12:50:40 -06001682
1683 // Android S and older devices do not define ro.vendor.api_level
1684 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1685 if (vendor_api_level == -1) {
1686 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001687 }
Shawn Willden35db3492022-06-16 12:50:40 -06001688
1689 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1690 if (product_api_level == -1) {
1691 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1692 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001693 }
Shawn Willden35db3492022-06-16 12:50:40 -06001694
1695 // VSR API level is the minimum of vendor_api_level and product_api_level.
1696 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1697 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001698 }
Shawn Willden35db3492022-06-16 12:50:40 -06001699 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001700}
1701
David Drysdale555ba002022-05-03 18:48:57 +01001702bool is_gsi_image() {
1703 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1704 return ifs.good();
1705}
1706
Selene Huang6e46f142021-04-20 19:20:11 -07001707vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1708 BIGNUM_Ptr serial(BN_new());
1709 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1710
1711 int len = BN_num_bytes(serial.get());
1712 vector<uint8_t> serial_blob(len);
1713 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1714 return {};
1715 }
1716
David Drysdaledb0dcf52021-05-18 11:43:31 +01001717 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1718 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1719 // Top bit being set indicates a negative number in two's complement, but our input
1720 // was positive.
1721 // In either case, prepend a zero byte.
1722 serial_blob.insert(serial_blob.begin(), 0x00);
1723 }
1724
Selene Huang6e46f142021-04-20 19:20:11 -07001725 return serial_blob;
1726}
1727
1728void verify_subject_and_serial(const Certificate& certificate, //
1729 const uint64_t expected_serial, //
1730 const string& subject, bool self_signed) {
1731 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1732 ASSERT_TRUE(!!cert.get());
1733
1734 verify_serial(cert.get(), expected_serial);
1735 verify_subject(cert.get(), subject, self_signed);
1736}
1737
Shawn Willden4315e132022-03-20 12:49:46 -06001738void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1739 VerifiedBoot verified_boot_state,
1740 const vector<uint8_t>& verified_boot_hash) {
1741 char property_value[PROPERTY_VALUE_MAX] = {};
1742
1743 if (avb_verification_enabled()) {
1744 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1745 string prop_string(property_value);
1746 EXPECT_EQ(prop_string.size(), 64);
1747 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1748
1749 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1750 if (!strcmp(property_value, "unlocked")) {
1751 EXPECT_FALSE(device_locked);
1752 } else {
1753 EXPECT_TRUE(device_locked);
1754 }
1755
1756 // Check that the device is locked if not debuggable, e.g., user build
1757 // images in CTS. For VTS, debuggable images are used to allow adb root
1758 // and the device is unlocked.
1759 if (!property_get_bool("ro.debuggable", false)) {
1760 EXPECT_TRUE(device_locked);
1761 } else {
1762 EXPECT_FALSE(device_locked);
1763 }
1764 }
1765
1766 // Verified boot key should be all 0's if the boot state is not verified or self signed
1767 std::string empty_boot_key(32, '\0');
1768 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1769 verified_boot_key.size());
1770 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1771 if (!strcmp(property_value, "green")) {
1772 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1773 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1774 verified_boot_key.size()));
1775 } else if (!strcmp(property_value, "yellow")) {
1776 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1777 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1778 verified_boot_key.size()));
1779 } else if (!strcmp(property_value, "orange")) {
1780 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1781 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1782 verified_boot_key.size()));
1783 } else if (!strcmp(property_value, "red")) {
1784 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1785 } else {
1786 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1787 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1788 verified_boot_key.size()));
1789 }
1790}
1791
David Drysdale7dff4fc2021-12-10 10:10:52 +00001792bool verify_attestation_record(int32_t aidl_version, //
1793 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001794 const string& app_id, //
1795 AuthorizationSet expected_sw_enforced, //
1796 AuthorizationSet expected_hw_enforced, //
1797 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001798 const vector<uint8_t>& attestation_cert,
1799 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001800 X509_Ptr cert(parse_cert_blob(attestation_cert));
1801 EXPECT_TRUE(!!cert.get());
1802 if (!cert.get()) return false;
1803
Rajesh Nyamagoude98263e2023-02-09 20:36:33 +00001804 // Make sure CRL Distribution Points extension is not present in a certificate
1805 // containing attestation record.
1806 check_crl_distribution_points_extension_not_present(cert.get());
1807
Shawn Willden7c130392020-12-21 09:58:22 -07001808 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1809 EXPECT_TRUE(!!attest_rec);
1810 if (!attest_rec) return false;
1811
1812 AuthorizationSet att_sw_enforced;
1813 AuthorizationSet att_hw_enforced;
1814 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001815 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001816 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001817 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001818 vector<uint8_t> att_challenge;
1819 vector<uint8_t> att_unique_id;
1820 vector<uint8_t> att_app_id;
1821
1822 auto error = parse_attestation_record(attest_rec->data, //
1823 attest_rec->length, //
1824 &att_attestation_version, //
1825 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001826 &att_keymint_version, //
1827 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001828 &att_challenge, //
1829 &att_sw_enforced, //
1830 &att_hw_enforced, //
1831 &att_unique_id);
1832 EXPECT_EQ(ErrorCode::OK, error);
1833 if (error != ErrorCode::OK) return false;
1834
David Drysdale7dff4fc2021-12-10 10:10:52 +00001835 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001836 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001837
Selene Huang4f64c222021-04-13 19:54:36 -07001838 // check challenge and app id only if we expects a non-fake certificate
1839 if (challenge.length() > 0) {
1840 EXPECT_EQ(challenge.length(), att_challenge.size());
1841 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1842
1843 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1844 }
Shawn Willden7c130392020-12-21 09:58:22 -07001845
David Drysdale7dff4fc2021-12-10 10:10:52 +00001846 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001847 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001848 EXPECT_EQ(security_level, att_attestation_security_level);
1849
Tri Vob21e6df2023-02-17 14:55:43 -08001850 for (int i = 0; i < att_hw_enforced.size(); i++) {
1851 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1852 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1853 std::string date =
1854 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001855
Tri Vob21e6df2023-02-17 14:55:43 -08001856 // strptime seems to require delimiters, but the tag value will
1857 // be YYYYMMDD
1858 if (date.size() != 8) {
1859 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1860 << " with invalid format (not YYYYMMDD): " << date;
1861 return false;
Shawn Willden7c130392020-12-21 09:58:22 -07001862 }
Tri Vob21e6df2023-02-17 14:55:43 -08001863 date.insert(6, "-");
1864 date.insert(4, "-");
1865 struct tm time;
1866 strptime(date.c_str(), "%Y-%m-%d", &time);
1867
1868 // Day of the month (0-31)
1869 EXPECT_GE(time.tm_mday, 0);
1870 EXPECT_LT(time.tm_mday, 32);
1871 // Months since Jan (0-11)
1872 EXPECT_GE(time.tm_mon, 0);
1873 EXPECT_LT(time.tm_mon, 12);
1874 // Years since 1900
1875 EXPECT_GT(time.tm_year, 110);
1876 EXPECT_LT(time.tm_year, 200);
Shawn Willden7c130392020-12-21 09:58:22 -07001877 }
1878 }
1879
1880 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1881 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1882 // indicates correct encoding. No need to check if it's in both lists, since the
1883 // AuthorizationSet compare below will handle mismatches of tags.
1884 if (security_level == SecurityLevel::SOFTWARE) {
1885 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1886 } else {
1887 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1888 }
1889
Shawn Willden7c130392020-12-21 09:58:22 -07001890 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1891 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1892 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1893 att_hw_enforced.Contains(TAG_KEY_SIZE));
1894 }
1895
1896 // Test root of trust elements
1897 vector<uint8_t> verified_boot_key;
1898 VerifiedBoot verified_boot_state;
1899 bool device_locked;
1900 vector<uint8_t> verified_boot_hash;
1901 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1902 &verified_boot_state, &device_locked, &verified_boot_hash);
1903 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001904 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001905
1906 att_sw_enforced.Sort();
1907 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001908 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001909
1910 att_hw_enforced.Sort();
1911 expected_hw_enforced.Sort();
1912 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1913
David Drysdale565ccc72021-10-11 12:49:50 +01001914 if (unique_id != nullptr) {
1915 *unique_id = att_unique_id;
1916 }
1917
Shawn Willden7c130392020-12-21 09:58:22 -07001918 return true;
1919}
1920
1921string bin2hex(const vector<uint8_t>& data) {
1922 string retval;
1923 retval.reserve(data.size() * 2 + 1);
1924 for (uint8_t byte : data) {
1925 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1926 retval.push_back(nibble2hex[0x0F & byte]);
1927 }
1928 return retval;
1929}
1930
David Drysdalef0d516d2021-03-22 07:51:43 +00001931AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1932 AuthorizationSet authList;
1933 for (auto& entry : key_characteristics) {
1934 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1935 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1936 authList.push_back(AuthorizationSet(entry.authorizations));
1937 }
1938 }
1939 return authList;
1940}
1941
1942AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1943 AuthorizationSet authList;
1944 for (auto& entry : key_characteristics) {
1945 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1946 entry.securityLevel == SecurityLevel::KEYSTORE) {
1947 authList.push_back(AuthorizationSet(entry.authorizations));
1948 }
1949 }
1950 return authList;
1951}
1952
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001953AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1954 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001955 std::stringstream cert_data;
1956
1957 for (size_t i = 0; i < chain.size(); ++i) {
1958 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1959
1960 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1961 X509_Ptr signing_cert;
1962 if (i < chain.size() - 1) {
1963 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1964 } else {
1965 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1966 }
1967 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1968
1969 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1970 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1971
1972 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1973 return AssertionFailure()
1974 << "Verification of certificate " << i << " failed "
1975 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1976 << cert_data.str();
1977 }
1978
1979 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1980 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001981 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001982 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1983 << " Signer subject is " << signer_subj
1984 << " Issuer subject is " << cert_issuer << endl
1985 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001986 }
Shawn Willden7c130392020-12-21 09:58:22 -07001987 }
1988
1989 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1990 return AssertionSuccess();
1991}
1992
David Drysdale1b9febc2023-06-07 13:43:24 +01001993ErrorCode GetReturnErrorCode(const Status& result) {
1994 if (result.isOk()) return ErrorCode::OK;
1995
1996 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
1997 return static_cast<ErrorCode>(result.getServiceSpecificError());
1998 }
1999
2000 return ErrorCode::UNKNOWN_ERROR;
2001}
2002
Shawn Willden7c130392020-12-21 09:58:22 -07002003X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
2004 const uint8_t* p = blob.data();
2005 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
2006}
2007
Tri Voec50ee12023-02-14 16:29:53 -08002008// Extract attestation record from cert. Returned object is still part of cert; don't free it
2009// separately.
2010ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
2011 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
2012 EXPECT_TRUE(!!oid.get());
2013 if (!oid.get()) return nullptr;
2014
2015 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
2016 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
2017 if (location == -1) return nullptr;
2018
2019 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
2020 EXPECT_TRUE(!!attest_rec_ext)
2021 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
2022 if (!attest_rec_ext) return nullptr;
2023
2024 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
2025 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
2026 return attest_rec;
2027}
2028
David Drysdalef0d516d2021-03-22 07:51:43 +00002029vector<uint8_t> make_name_from_str(const string& name) {
2030 X509_NAME_Ptr x509_name(X509_NAME_new());
2031 EXPECT_TRUE(x509_name.get() != nullptr);
2032 if (!x509_name) return {};
2033
2034 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
2035 "CN", //
2036 MBSTRING_ASC,
2037 reinterpret_cast<const uint8_t*>(name.c_str()),
2038 -1, // len
2039 -1, // loc
2040 0 /* set */));
2041
2042 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
2043 EXPECT_GT(len, 0);
2044
2045 vector<uint8_t> retval(len);
2046 uint8_t* p = retval.data();
2047 i2d_X509_NAME(x509_name.get(), &p);
2048
2049 return retval;
2050}
2051
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00002052void assert_mgf_digests_present_in_key_characteristics(
2053 const vector<KeyCharacteristics>& key_characteristics,
2054 std::vector<android::hardware::security::keymint::Digest>& expected_mgf_digests) {
2055 AuthorizationSet auths;
2056 for (auto& entry : key_characteristics) {
2057 auths.push_back(AuthorizationSet(entry.authorizations));
2058 }
2059 for (auto digest : expected_mgf_digests) {
2060 ASSERT_TRUE(auths.Contains(TAG_RSA_OAEP_MGF_DIGEST, digest));
2061 }
2062}
2063
2064bool is_mgf_digest_present(const vector<KeyCharacteristics>& key_characteristics,
2065 android::hardware::security::keymint::Digest expected_mgf_digest) {
2066 AuthorizationSet auths;
2067 for (auto& entry : key_characteristics) {
2068 auths.push_back(AuthorizationSet(entry.authorizations));
2069 }
2070 return auths.Contains(TAG_RSA_OAEP_MGF_DIGEST, expected_mgf_digest);
2071}
2072
David Drysdale4dc01072021-04-01 12:17:35 +01002073namespace {
2074
2075void check_cose_key(const vector<uint8_t>& data, bool testMode) {
2076 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
2077 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2078
2079 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
2080 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00002081 EXPECT_THAT(
2082 cppbor::prettyPrint(parsedPayload.get()),
2083 MatchesRegex("\\{\n"
2084 " 1 : 2,\n" // kty: EC2
2085 " 3 : -7,\n" // alg: ES256
2086 " -1 : 1,\n" // EC id: P256
2087 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
2088 // sequence of 32 hexadecimal bytes, enclosed in braces and
2089 // separated by commas. In this case, some Ed25519 public key.
2090 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
2091 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
2092 " -70000 : null,\n" // test marker
2093 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01002094 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00002095 EXPECT_THAT(
2096 cppbor::prettyPrint(parsedPayload.get()),
2097 MatchesRegex("\\{\n"
2098 " 1 : 2,\n" // kty: EC2
2099 " 3 : -7,\n" // alg: ES256
2100 " -1 : 1,\n" // EC id: P256
2101 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
2102 // sequence of 32 hexadecimal bytes, enclosed in braces and
2103 // separated by commas. In this case, some Ed25519 public key.
2104 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
2105 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
2106 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01002107 }
2108}
2109
2110} // namespace
2111
2112void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
2113 vector<uint8_t>* payload_value) {
2114 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
2115 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
2116
2117 ASSERT_NE(coseMac0->asArray(), nullptr);
2118 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
2119
2120 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
2121 ASSERT_NE(protParms, nullptr);
2122
2123 // Header label:value of 'alg': HMAC-256
2124 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
2125
2126 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
2127 ASSERT_NE(unprotParms, nullptr);
2128 ASSERT_EQ(unprotParms->size(), 0);
2129
2130 // The payload is a bstr holding an encoded COSE_Key
2131 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
2132 ASSERT_NE(payload, nullptr);
2133 check_cose_key(payload->value(), testMode);
2134
2135 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
2136 ASSERT_TRUE(coseMac0Tag);
2137 auto extractedTag = coseMac0Tag->value();
2138 EXPECT_EQ(extractedTag.size(), 32U);
2139
2140 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07002141 auto macFunction = [](const cppcose::bytevec& input) {
2142 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
2143 };
2144 auto testTag =
2145 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01002146 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
2147
2148 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07002149 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01002150 } else {
Seth Moore026bb742021-04-30 11:41:18 -07002151 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002152 }
2153 if (payload_value != nullptr) {
2154 *payload_value = payload->value();
2155 }
2156}
2157
2158void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2159 // Extract x and y affine coordinates from the encoded Cose_Key.
2160 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2161 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2162 auto coseKey = parsedPayload->asMap();
2163 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2164 ASSERT_NE(xItem->asBstr(), nullptr);
2165 vector<uint8_t> x = xItem->asBstr()->value();
2166 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2167 ASSERT_NE(yItem->asBstr(), nullptr);
2168 vector<uint8_t> y = yItem->asBstr()->value();
2169
2170 // Concatenate: 0x04 (uncompressed form marker) | x | y
2171 vector<uint8_t> pubKeyData{0x04};
2172 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2173 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2174
2175 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2176 ASSERT_NE(ecKey, nullptr);
2177 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2178 ASSERT_NE(group, nullptr);
2179 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2180 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2181 ASSERT_NE(point, nullptr);
2182 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2183 nullptr),
2184 1);
2185 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2186
2187 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2188 ASSERT_NE(pubKey, nullptr);
2189 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2190 *signingKey = std::move(pubKey);
2191}
2192
David Drysdalef42238c2023-06-15 09:41:05 +01002193// Check the error code from an attempt to perform device ID attestation with an invalid value.
2194void device_id_attestation_check_acceptable_error(Tag tag, const ErrorCode& result) {
David Drysdalef42238c2023-06-15 09:41:05 +01002195 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
David Drysdale810fbcf2023-07-04 13:08:30 +01002196 // Standard/default error code for ID mismatch.
2197 } else if (result == ErrorCode::INVALID_TAG) {
2198 // Depending on the situation, other error codes may be acceptable. First, allow older
2199 // implementations to use INVALID_TAG.
David Drysdalef42238c2023-06-15 09:41:05 +01002200 ASSERT_FALSE(get_vsr_api_level() > __ANDROID_API_T__)
Max Biresa97ec692022-11-21 23:37:54 -08002201 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2202 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2203 << "be used for a case where updateAad() is called after update(). As of "
2204 << "VSR-14, this is now enforced as an error.";
David Drysdale810fbcf2023-07-04 13:08:30 +01002205 } else if (result == ErrorCode::ATTESTATION_IDS_NOT_PROVISIONED) {
2206 // If the device is not a phone, it will not have IMEI/MEID values available. Allow
2207 // ATTESTATION_IDS_NOT_PROVISIONED in this case.
David Drysdalef42238c2023-06-15 09:41:05 +01002208 ASSERT_TRUE((tag == TAG_ATTESTATION_ID_IMEI || tag == TAG_ATTESTATION_ID_MEID ||
2209 tag == TAG_ATTESTATION_ID_SECOND_IMEI))
2210 << "incorrect error code on attestation ID mismatch";
David Drysdale810fbcf2023-07-04 13:08:30 +01002211 } else {
2212 ADD_FAILURE() << "Error code " << result
2213 << " returned on attestation ID mismatch, should be CANNOT_ATTEST_IDS";
David Drysdalef42238c2023-06-15 09:41:05 +01002214 }
Max Biresa97ec692022-11-21 23:37:54 -08002215}
2216
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002217// Check whether the given named feature is available.
2218bool check_feature(const std::string& name) {
2219 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002220 ::android::sp<::android::IBinder> binder(
2221 sm->waitForService(::android::String16("package_native")));
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002222 if (binder == nullptr) {
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002223 GTEST_LOG_(ERROR) << "waitForService package_native failed";
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002224 return false;
2225 }
2226 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2227 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2228 if (packageMgr == nullptr) {
2229 GTEST_LOG_(ERROR) << "Cannot find package manager";
2230 return false;
2231 }
2232 bool hasFeature = false;
2233 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2234 if (!status.isOk()) {
2235 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2236 return false;
2237 }
2238 return hasFeature;
2239}
2240
Selene Huang31ab4042020-04-29 04:22:39 -07002241} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002242
Janis Danisevskis24c04702020-12-16 18:28:39 -08002243} // namespace aidl::android::hardware::security::keymint