blob: 60d8748395fdfc06a62a8cf51f0a415e04ed66f7 [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;
Shawn Willden7c130392020-12-21 09:58:22 -0700184
David Drysdale37af4b32021-05-14 16:46:59 +0100185uint32_t KeyMintAidlTestBase::boot_patch_level(
186 const vector<KeyCharacteristics>& key_characteristics) {
187 // The boot patchlevel is not available as a property, but should be present
188 // in the key characteristics of any created key.
189 AuthorizationSet allAuths;
190 for (auto& entry : key_characteristics) {
191 allAuths.push_back(AuthorizationSet(entry.authorizations));
192 }
193 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
194 if (patchlevel.has_value()) {
195 return patchlevel.value();
196 } else {
197 // No boot patchlevel is available. Return a value that won't match anything
198 // and so will trigger test failures.
199 return kInvalidPatchlevel;
200 }
201}
202
203uint32_t KeyMintAidlTestBase::boot_patch_level() {
204 return boot_patch_level(key_characteristics_);
205}
206
Prashant Patil88ad1892022-03-15 16:31:02 +0000207/**
208 * An API to determine device IDs attestation is required or not,
209 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
210 */
211bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700212 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= __ANDROID_API_T__;
Prashant Patil88ad1892022-03-15 16:31:02 +0000213}
214
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000215/**
216 * An API to determine second IMEI ID attestation is required or not,
217 * which is supported for KeyMint version 3 or first_api_level greater than 33.
218 */
219bool KeyMintAidlTestBase::isSecondImeiIdAttestationRequired() {
Shawn Willden1a545db2023-02-22 14:32:33 -0700220 return AidlVersion() >= 3 && property_get_int32("ro.vendor.api_level", 0) > __ANDROID_API_T__;
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000221}
222
David Drysdale42fe1892021-10-14 14:43:46 +0100223bool KeyMintAidlTestBase::Curve25519Supported() {
224 // Strongbox never supports curve 25519.
225 if (SecLevel() == SecurityLevel::STRONGBOX) {
226 return false;
227 }
228
229 // Curve 25519 was included in version 2 of the KeyMint interface.
230 int32_t version = 0;
231 auto status = keymint_->getInterfaceVersion(&version);
232 if (!status.isOk()) {
233 ADD_FAILURE() << "Failed to determine interface version";
234 }
235 return version >= 2;
236}
237
Janis Danisevskis24c04702020-12-16 18:28:39 -0800238ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700239 if (result.isOk()) return ErrorCode::OK;
240
Janis Danisevskis24c04702020-12-16 18:28:39 -0800241 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
242 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700243 }
244
245 return ErrorCode::UNKNOWN_ERROR;
246}
247
Janis Danisevskis24c04702020-12-16 18:28:39 -0800248void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700249 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800250 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700251
252 KeyMintHardwareInfo info;
253 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
254
255 securityLevel_ = info.securityLevel;
256 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
257 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100258 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700259
260 os_version_ = getOsVersion();
261 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100262 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700263}
264
David Drysdale7dff4fc2021-12-10 10:10:52 +0000265int32_t KeyMintAidlTestBase::AidlVersion() {
266 int32_t version = 0;
267 auto status = keymint_->getInterfaceVersion(&version);
268 if (!status.isOk()) {
269 ADD_FAILURE() << "Failed to determine interface version";
270 }
271 return version;
272}
273
Selene Huang31ab4042020-04-29 04:22:39 -0700274void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800275 if (AServiceManager_isDeclared(GetParam().c_str())) {
276 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
277 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
278 } else {
279 InitializeKeyMint(nullptr);
280 }
Selene Huang31ab4042020-04-29 04:22:39 -0700281}
282
283ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700284 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700285 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700286 vector<KeyCharacteristics>* key_characteristics,
287 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700288 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
289 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700290 << "Previous characteristics not deleted before generating key. Test bug.";
291
Shawn Willden7f424372021-01-10 18:06:50 -0700292 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700293 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700294 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700295 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
296 creationResult.keyCharacteristics);
297 EXPECT_GT(creationResult.keyBlob.size(), 0);
298 *key_blob = std::move(creationResult.keyBlob);
299 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700300 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700301
302 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
303 EXPECT_TRUE(algorithm);
304 if (algorithm &&
305 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700306 EXPECT_GE(cert_chain->size(), 1);
307 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
308 if (attest_key) {
309 EXPECT_EQ(cert_chain->size(), 1);
310 } else {
311 EXPECT_GT(cert_chain->size(), 1);
312 }
313 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700314 } else {
315 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700316 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700317 }
Selene Huang31ab4042020-04-29 04:22:39 -0700318 }
319
320 return GetReturnErrorCode(result);
321}
322
Shawn Willden7c130392020-12-21 09:58:22 -0700323ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
324 const optional<AttestationKey>& attest_key) {
325 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700326}
327
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000328ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
329 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
330 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
331 vector<Certificate>* cert_chain) {
332 AttestationKey attest_key;
333 vector<Certificate> attest_cert_chain;
334 vector<KeyCharacteristics> attest_key_characteristics;
335 // Generate a key with self signed attestation.
336 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
337 &attest_key_characteristics, &attest_cert_chain);
338 if (error != ErrorCode::OK) {
339 return error;
340 }
341
342 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
343 // Generate a key, by passing the above self signed attestation key as attest key.
344 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
345 if (error == ErrorCode::OK) {
346 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
347 cert_chain->push_back(attest_cert_chain[0]);
348 }
349 return error;
350}
351
Selene Huang31ab4042020-04-29 04:22:39 -0700352ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
353 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700354 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700355 Status result;
356
Shawn Willden7f424372021-01-10 18:06:50 -0700357 cert_chain_.clear();
358 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700359 key_blob->clear();
360
Shawn Willden7f424372021-01-10 18:06:50 -0700361 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700362 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700363 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700364 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700365
366 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700367 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
368 creationResult.keyCharacteristics);
369 EXPECT_GT(creationResult.keyBlob.size(), 0);
370
371 *key_blob = std::move(creationResult.keyBlob);
372 *key_characteristics = std::move(creationResult.keyCharacteristics);
373 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700374
375 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
376 EXPECT_TRUE(algorithm);
377 if (algorithm &&
378 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
379 EXPECT_GE(cert_chain_.size(), 1);
380 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
381 } else {
382 // For symmetric keys there should be no certificates.
383 EXPECT_EQ(cert_chain_.size(), 0);
384 }
Selene Huang31ab4042020-04-29 04:22:39 -0700385 }
386
387 return GetReturnErrorCode(result);
388}
389
390ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
391 const string& key_material) {
392 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
393}
394
395ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
396 const AuthorizationSet& wrapping_key_desc,
397 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100398 const AuthorizationSet& unwrapping_params,
399 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700400 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
401
Shawn Willden7f424372021-01-10 18:06:50 -0700402 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700403
Shawn Willden7f424372021-01-10 18:06:50 -0700404 KeyCreationResult creationResult;
405 Status result = keymint_->importWrappedKey(
406 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
407 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100408 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700409
410 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700411 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
412 creationResult.keyCharacteristics);
413 EXPECT_GT(creationResult.keyBlob.size(), 0);
414
415 key_blob_ = std::move(creationResult.keyBlob);
416 key_characteristics_ = std::move(creationResult.keyCharacteristics);
417 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700418
419 AuthorizationSet allAuths;
420 for (auto& entry : key_characteristics_) {
421 allAuths.push_back(AuthorizationSet(entry.authorizations));
422 }
423 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
424 EXPECT_TRUE(algorithm);
425 if (algorithm &&
426 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
427 EXPECT_GE(cert_chain_.size(), 1);
428 } else {
429 // For symmetric keys there should be no certificates.
430 EXPECT_EQ(cert_chain_.size(), 0);
431 }
Selene Huang31ab4042020-04-29 04:22:39 -0700432 }
433
434 return GetReturnErrorCode(result);
435}
436
David Drysdale300b5552021-05-20 12:05:26 +0100437ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
438 const vector<uint8_t>& app_id,
439 const vector<uint8_t>& app_data,
440 vector<KeyCharacteristics>* key_characteristics) {
441 Status result =
442 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
443 return GetReturnErrorCode(result);
444}
445
446ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
447 vector<KeyCharacteristics>* key_characteristics) {
448 vector<uint8_t> empty_app_id, empty_app_data;
449 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
450}
451
452void KeyMintAidlTestBase::CheckCharacteristics(
453 const vector<uint8_t>& key_blob,
454 const vector<KeyCharacteristics>& generate_characteristics) {
455 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
456 // generateKey() should be excluded, as KeyMint will have no record of them.
457 // This applies to CREATION_DATETIME in particular.
458 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
459 strip_keystore_tags(&expected_characteristics);
460
461 vector<KeyCharacteristics> retrieved;
462 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
463 EXPECT_EQ(expected_characteristics, retrieved);
464}
465
466void KeyMintAidlTestBase::CheckAppIdCharacteristics(
467 const vector<uint8_t>& key_blob, std::string_view app_id_string,
468 std::string_view app_data_string,
469 const vector<KeyCharacteristics>& generate_characteristics) {
470 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
471 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
472 strip_keystore_tags(&expected_characteristics);
473
474 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
475 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
476 vector<KeyCharacteristics> retrieved;
477 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
478 EXPECT_EQ(expected_characteristics, retrieved);
479
480 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
481 vector<uint8_t> empty;
482 vector<KeyCharacteristics> not_retrieved;
483 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
484 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
485 EXPECT_EQ(not_retrieved.size(), 0);
486
487 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
488 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
489 EXPECT_EQ(not_retrieved.size(), 0);
490
491 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
492 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
493 EXPECT_EQ(not_retrieved.size(), 0);
494}
495
Selene Huang31ab4042020-04-29 04:22:39 -0700496ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
497 Status result = keymint_->deleteKey(*key_blob);
498 if (!keep_key_blob) {
499 *key_blob = vector<uint8_t>();
500 }
501
Janis Danisevskis24c04702020-12-16 18:28:39 -0800502 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700503 return GetReturnErrorCode(result);
504}
505
506ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
507 return DeleteKey(&key_blob_, keep_key_blob);
508}
509
510ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
511 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800512 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700513 return GetReturnErrorCode(result);
514}
515
David Drysdaled2cc8c22021-04-15 13:29:45 +0100516ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
517 Status result = keymint_->destroyAttestationIds();
518 return GetReturnErrorCode(result);
519}
520
Selene Huang31ab4042020-04-29 04:22:39 -0700521void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
522 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
523 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
524}
525
526void KeyMintAidlTestBase::CheckedDeleteKey() {
527 CheckedDeleteKey(&key_blob_);
528}
529
530ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
531 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800532 AuthorizationSet* out_params,
533 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700534 SCOPED_TRACE("Begin");
535 Status result;
536 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100537 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700538
539 if (result.isOk()) {
540 *out_params = out.params;
541 challenge_ = out.challenge;
542 op = out.operation;
543 }
544
545 return GetReturnErrorCode(result);
546}
547
548ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
549 const AuthorizationSet& in_params,
David Drysdale28fa9312023-02-01 14:53:01 +0000550 AuthorizationSet* out_params,
551 std::optional<HardwareAuthToken> hat) {
Selene Huang31ab4042020-04-29 04:22:39 -0700552 SCOPED_TRACE("Begin");
553 Status result;
554 BeginResult out;
555
David Drysdale28fa9312023-02-01 14:53:01 +0000556 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), hat, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700557
558 if (result.isOk()) {
559 *out_params = out.params;
560 challenge_ = out.challenge;
561 op_ = out.operation;
562 }
563
564 return GetReturnErrorCode(result);
565}
566
567ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
568 AuthorizationSet* out_params) {
569 SCOPED_TRACE("Begin");
570 EXPECT_EQ(nullptr, op_);
571 return Begin(purpose, key_blob_, in_params, out_params);
572}
573
574ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
575 SCOPED_TRACE("Begin");
576 AuthorizationSet out_params;
577 ErrorCode result = Begin(purpose, in_params, &out_params);
578 EXPECT_TRUE(out_params.empty());
579 return result;
580}
581
Shawn Willden92d79c02021-02-19 07:31:55 -0700582ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
583 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
584 {} /* hardwareAuthToken */,
585 {} /* verificationToken */));
586}
587
588ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700589 SCOPED_TRACE("Update");
590
591 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700592 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700593
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800594 EXPECT_NE(op_, nullptr);
595 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
596
Shawn Willden92d79c02021-02-19 07:31:55 -0700597 std::vector<uint8_t> o_put;
598 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700599
David Drysdalefeab5d92022-01-06 15:46:23 +0000600 if (result.isOk()) {
601 output->append(o_put.begin(), o_put.end());
602 } else {
603 // Failure always terminates the operation.
604 op_ = {};
605 }
Selene Huang31ab4042020-04-29 04:22:39 -0700606
607 return GetReturnErrorCode(result);
608}
609
David Drysdale28fa9312023-02-01 14:53:01 +0000610ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, string* output,
611 std::optional<HardwareAuthToken> hat,
612 std::optional<secureclock::TimeStampToken> time_token) {
Selene Huang31ab4042020-04-29 04:22:39 -0700613 SCOPED_TRACE("Finish");
614 Status result;
615
616 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700617 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700618
619 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700620 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
David Drysdale28fa9312023-02-01 14:53:01 +0000621 vector<uint8_t>(signature.begin(), signature.end()), hat, time_token,
622 {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700623
Shawn Willden92d79c02021-02-19 07:31:55 -0700624 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700625
Shawn Willden92d79c02021-02-19 07:31:55 -0700626 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700627 return GetReturnErrorCode(result);
628}
629
Janis Danisevskis24c04702020-12-16 18:28:39 -0800630ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700631 SCOPED_TRACE("Abort");
632
633 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700634 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700635
636 Status retval = op->abort();
637 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800638 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700639}
640
641ErrorCode KeyMintAidlTestBase::Abort() {
642 SCOPED_TRACE("Abort");
643
644 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700645 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700646
647 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800648 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700649}
650
651void KeyMintAidlTestBase::AbortIfNeeded() {
652 SCOPED_TRACE("AbortIfNeeded");
653 if (op_) {
654 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800655 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700656 }
657}
658
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000659auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
660 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700661 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000662 AuthorizationSet begin_out_params;
663 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700664 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000665
666 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700667 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000668}
669
Selene Huang31ab4042020-04-29 04:22:39 -0700670string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
671 const string& message, const AuthorizationSet& in_params,
672 AuthorizationSet* out_params) {
673 SCOPED_TRACE("ProcessMessage");
674 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700675 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700676 EXPECT_EQ(ErrorCode::OK, result);
677 if (result != ErrorCode::OK) {
678 return "";
679 }
680
681 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700682 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700683 return output;
684}
685
686string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
687 const AuthorizationSet& params) {
688 SCOPED_TRACE("SignMessage");
689 AuthorizationSet out_params;
690 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
691 EXPECT_TRUE(out_params.empty());
692 return signature;
693}
694
695string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
696 SCOPED_TRACE("SignMessage");
697 return SignMessage(key_blob_, message, params);
698}
699
700string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
701 SCOPED_TRACE("MacMessage");
702 return SignMessage(
703 key_blob_, message,
704 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
705}
706
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530707void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
708 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000709 auto builder = AuthorizationSetBuilder()
710 .Authorization(TAG_NO_AUTH_REQUIRED)
711 .AesEncryptionKey(128)
712 .BlockMode(block_mode)
713 .Padding(PaddingMode::NONE);
714 if (block_mode == BlockMode::GCM) {
715 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
716 }
717 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530718
719 for (int increment = 1; increment <= message_size; ++increment) {
720 string message(message_size, 'a');
721 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
722 if (block_mode == BlockMode::GCM) {
723 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
724 }
725
726 AuthorizationSet output_params;
727 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
728
729 string ciphertext;
730 string to_send;
731 for (size_t i = 0; i < message.size(); i += increment) {
732 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
733 }
734 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
735 << "Error sending " << to_send << " with block mode " << block_mode;
736
737 switch (block_mode) {
738 case BlockMode::GCM:
739 EXPECT_EQ(message.size() + 16, ciphertext.size());
740 break;
741 case BlockMode::CTR:
742 EXPECT_EQ(message.size(), ciphertext.size());
743 break;
744 case BlockMode::CBC:
745 case BlockMode::ECB:
746 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
747 break;
748 }
749
750 auto iv = output_params.GetTagValue(TAG_NONCE);
751 switch (block_mode) {
752 case BlockMode::CBC:
753 case BlockMode::GCM:
754 case BlockMode::CTR:
755 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
756 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
757 params.push_back(TAG_NONCE, iv->get());
758 break;
759
760 case BlockMode::ECB:
761 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
762 break;
763 }
764
765 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
766 << "Decrypt begin() failed for block mode " << block_mode;
767
768 string plaintext;
769 for (size_t i = 0; i < ciphertext.size(); i += increment) {
770 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
771 }
772 ErrorCode error = Finish(to_send, &plaintext);
773 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
774 << " and increment " << increment;
775 if (error == ErrorCode::OK) {
776 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
777 << " and increment " << increment;
778 }
779 }
780}
781
Prashant Patildd5f7f02022-07-06 18:58:07 +0000782void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
783 PaddingMode padding_mode, const string& iv,
784 const string& plaintext,
785 const string& exp_cipher_text) {
786 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
787 auto auth_set = AuthorizationSetBuilder()
788 .Authorization(TAG_NO_AUTH_REQUIRED)
789 .AesEncryptionKey(key.size() * 8)
790 .BlockMode(block_mode)
791 .Padding(padding_mode);
792 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
793 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
794 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
795
796 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
797 exp_cipher_text);
798}
799
800void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
801 PaddingMode padding_mode, const string& iv,
802 const string& plaintext,
803 const string& exp_cipher_text) {
804 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
805 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
806 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
807 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
808 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
809
810 AuthorizationSet output_params;
811 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
812
813 string actual_ciphertext;
814 if (is_stream_cipher) {
815 // Assert that a 1 byte of output is produced for 1 byte of input.
816 // Every input byte produces an output byte.
817 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
818 string ciphertext;
819 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
820 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
821 // we relax this API restriction for them.
822 if (SecLevel() != SecurityLevel::STRONGBOX) {
823 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
824 }
825 actual_ciphertext.append(ciphertext);
826 }
827 string ciphertext;
828 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
829 if (SecLevel() != SecurityLevel::STRONGBOX) {
830 string expected_final_output;
831 if (is_authenticated_cipher) {
832 expected_final_output = exp_cipher_text.substr(plaintext.size());
833 }
834 EXPECT_EQ(expected_final_output, ciphertext);
835 }
836 actual_ciphertext.append(ciphertext);
837 } else {
838 // Assert that a block of output is produced once a full block of input is provided.
839 // Every input block produces an output block.
840 bool compare_output = true;
841 string additional_information;
842 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
843 if (SecLevel() == SecurityLevel::STRONGBOX) {
844 // This is known to be broken on older vendor implementations.
Shawn Willden1a545db2023-02-22 14:32:33 -0700845 if (vendor_api_level < __ANDROID_API_T__) {
Prashant Patildd5f7f02022-07-06 18:58:07 +0000846 compare_output = false;
847 } else {
848 additional_information = " (b/194134359) ";
849 }
850 }
851 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
852 string ciphertext;
853 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
854 if (compare_output) {
855 if ((plaintext_index % block_size) == block_size - 1) {
856 // Update is expected to have output a new block
857 EXPECT_EQ(block_size, ciphertext.size())
858 << "plaintext index: " << plaintext_index << additional_information;
859 } else {
860 // Update is expected to have produced no output
861 EXPECT_EQ(0, ciphertext.size())
862 << "plaintext index: " << plaintext_index << additional_information;
863 }
864 }
865 actual_ciphertext.append(ciphertext);
866 }
867 string ciphertext;
868 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
869 actual_ciphertext.append(ciphertext);
870 }
871 // Regardless of how the completed ciphertext got accumulated, it should match the expected
872 // ciphertext.
873 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
874}
875
Selene Huang31ab4042020-04-29 04:22:39 -0700876void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
877 Digest digest, const string& expected_mac) {
878 SCOPED_TRACE("CheckHmacTestVector");
879 ASSERT_EQ(ErrorCode::OK,
880 ImportKey(AuthorizationSetBuilder()
881 .Authorization(TAG_NO_AUTH_REQUIRED)
882 .HmacKey(key.size() * 8)
883 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
884 .Digest(digest),
885 KeyFormat::RAW, key));
886 string signature = MacMessage(message, digest, expected_mac.size() * 8);
887 EXPECT_EQ(expected_mac, signature)
888 << "Test vector didn't match for key of size " << key.size() << " message of size "
889 << message.size() << " and digest " << digest;
890 CheckedDeleteKey();
891}
892
893void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
894 const string& message,
895 const string& expected_ciphertext) {
896 SCOPED_TRACE("CheckAesCtrTestVector");
897 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
898 .Authorization(TAG_NO_AUTH_REQUIRED)
899 .AesEncryptionKey(key.size() * 8)
900 .BlockMode(BlockMode::CTR)
901 .Authorization(TAG_CALLER_NONCE)
902 .Padding(PaddingMode::NONE),
903 KeyFormat::RAW, key));
904
905 auto params = AuthorizationSetBuilder()
906 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
907 .BlockMode(BlockMode::CTR)
908 .Padding(PaddingMode::NONE);
909 AuthorizationSet out_params;
910 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
911 EXPECT_EQ(expected_ciphertext, ciphertext);
912}
913
914void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
915 PaddingMode padding_mode, const string& key,
916 const string& iv, const string& input,
917 const string& expected_output) {
918 auto authset = AuthorizationSetBuilder()
919 .TripleDesEncryptionKey(key.size() * 7)
920 .BlockMode(block_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .Padding(padding_mode);
923 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
924 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
925 ASSERT_GT(key_blob_.size(), 0U);
926
927 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
928 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
929 AuthorizationSet output_params;
930 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
931 EXPECT_EQ(expected_output, output);
932}
933
934void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
935 const string& signature, const AuthorizationSet& params) {
936 SCOPED_TRACE("VerifyMessage");
937 AuthorizationSet begin_out_params;
938 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
939
940 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700941 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700942 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700943 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700944}
945
946void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
947 const AuthorizationSet& params) {
948 SCOPED_TRACE("VerifyMessage");
949 VerifyMessage(key_blob_, message, signature, params);
950}
951
David Drysdaledf8f52e2021-05-06 08:10:58 +0100952void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
953 const AuthorizationSet& params) {
954 SCOPED_TRACE("LocalVerifyMessage");
955
David Drysdaledf8f52e2021-05-06 08:10:58 +0100956 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000957 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
958}
959
960void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
961 const string& signature,
962 const AuthorizationSet& params) {
963 // Retrieve the public key from the leaf certificate.
964 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100965 ASSERT_TRUE(key_cert.get());
966 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
967 ASSERT_TRUE(pub_key.get());
968
969 Digest digest = params.GetTagValue(TAG_DIGEST).value();
970 PaddingMode padding = PaddingMode::NONE;
971 auto tag = params.GetTagValue(TAG_PADDING);
972 if (tag.has_value()) {
973 padding = tag.value();
974 }
975
976 if (digest == Digest::NONE) {
977 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100978 case EVP_PKEY_ED25519: {
979 ASSERT_EQ(64, signature.size());
980 uint8_t pub_keydata[32];
981 size_t pub_len = sizeof(pub_keydata);
982 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
983 ASSERT_EQ(sizeof(pub_keydata), pub_len);
984 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
985 message.size(),
986 reinterpret_cast<const uint8_t*>(signature.data()),
987 pub_keydata));
988 break;
989 }
990
David Drysdaledf8f52e2021-05-06 08:10:58 +0100991 case EVP_PKEY_EC: {
992 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
993 size_t data_size = std::min(data.size(), message.size());
994 memcpy(data.data(), message.data(), data_size);
995 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
996 ASSERT_TRUE(ecdsa.get());
997 ASSERT_EQ(1,
998 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
999 reinterpret_cast<const uint8_t*>(signature.data()),
1000 signature.size(), ecdsa.get()));
1001 break;
1002 }
1003 case EVP_PKEY_RSA: {
1004 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
1005 size_t data_size = std::min(data.size(), message.size());
1006 memcpy(data.data(), message.data(), data_size);
1007
1008 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1009 ASSERT_TRUE(rsa.get());
1010
1011 size_t key_len = RSA_size(rsa.get());
1012 int openssl_padding = RSA_NO_PADDING;
1013 switch (padding) {
1014 case PaddingMode::NONE:
1015 ASSERT_TRUE(data_size <= key_len);
1016 ASSERT_EQ(key_len, signature.size());
1017 openssl_padding = RSA_NO_PADDING;
1018 break;
1019 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1020 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1021 key_len);
1022 openssl_padding = RSA_PKCS1_PADDING;
1023 break;
1024 default:
1025 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1026 }
1027
1028 vector<uint8_t> decrypted_data(key_len);
1029 int bytes_decrypted = RSA_public_decrypt(
1030 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1031 decrypted_data.data(), rsa.get(), openssl_padding);
1032 ASSERT_GE(bytes_decrypted, 0);
1033
1034 const uint8_t* compare_pos = decrypted_data.data();
1035 size_t bytes_to_compare = bytes_decrypted;
1036 uint8_t zero_check_result = 0;
1037 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1038 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1039 // during verification we should have zeros on the left of the decrypted data.
1040 // Do a constant-time check.
1041 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1042 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1043 ASSERT_EQ(0, zero_check_result);
1044 bytes_to_compare = data_size;
1045 }
1046 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1047 break;
1048 }
1049 default:
1050 ADD_FAILURE() << "Unknown public key type";
1051 }
1052 } else {
1053 EVP_MD_CTX digest_ctx;
1054 EVP_MD_CTX_init(&digest_ctx);
1055 EVP_PKEY_CTX* pkey_ctx;
1056 const EVP_MD* md = openssl_digest(digest);
1057 ASSERT_NE(md, nullptr);
1058 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1059
1060 if (padding == PaddingMode::RSA_PSS) {
1061 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1062 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001063 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001064 }
1065
1066 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1067 reinterpret_cast<const uint8_t*>(message.data()),
1068 message.size()));
1069 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1070 reinterpret_cast<const uint8_t*>(signature.data()),
1071 signature.size()));
1072 EVP_MD_CTX_cleanup(&digest_ctx);
1073 }
1074}
1075
David Drysdale59cae642021-05-12 13:52:03 +01001076string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1077 const AuthorizationSet& params) {
1078 SCOPED_TRACE("LocalRsaEncryptMessage");
1079
1080 // Retrieve the public key from the leaf certificate.
1081 if (cert_chain_.empty()) {
1082 ADD_FAILURE() << "No public key available";
1083 return "Failure";
1084 }
1085 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001086 if (key_cert.get() == nullptr) {
1087 ADD_FAILURE() << "Failed to parse cert";
1088 return "Failure";
1089 }
David Drysdale59cae642021-05-12 13:52:03 +01001090 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001091 if (pub_key.get() == nullptr) {
1092 ADD_FAILURE() << "Failed to retrieve public key";
1093 return "Failure";
1094 }
David Drysdale59cae642021-05-12 13:52:03 +01001095 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001096 if (rsa.get() == nullptr) {
1097 ADD_FAILURE() << "Failed to retrieve RSA public key";
1098 return "Failure";
1099 }
David Drysdale59cae642021-05-12 13:52:03 +01001100
1101 // Retrieve relevant tags.
1102 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001103 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001104 PaddingMode padding = PaddingMode::NONE;
1105
1106 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1107 if (digest_tag.has_value()) digest = digest_tag.value();
1108 auto pad_tag = params.GetTagValue(TAG_PADDING);
1109 if (pad_tag.has_value()) padding = pad_tag.value();
1110 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1111 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1112
1113 const EVP_MD* md = openssl_digest(digest);
1114 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1115
1116 // Set up encryption context.
1117 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1118 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1119 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1120 return "Failure";
1121 }
1122
1123 int rc = -1;
1124 switch (padding) {
1125 case PaddingMode::NONE:
1126 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1127 break;
1128 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1129 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1130 break;
1131 case PaddingMode::RSA_OAEP:
1132 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1133 break;
1134 default:
1135 break;
1136 }
1137 if (rc <= 0) {
1138 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1139 return "Failure";
1140 }
1141 if (padding == PaddingMode::RSA_OAEP) {
1142 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1143 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1144 return "Failure";
1145 }
1146 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1147 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1148 return "Failure";
1149 }
1150 }
1151
1152 // Determine output size.
1153 size_t outlen;
1154 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1155 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1156 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1157 return "Failure";
1158 }
1159
1160 // Left-zero-pad the input if necessary.
1161 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1162 size_t to_encrypt_len = message.size();
1163
1164 std::unique_ptr<string> zero_padded_message;
1165 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1166 zero_padded_message.reset(new string(outlen, '\0'));
1167 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1168 message.size());
1169 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1170 to_encrypt_len = outlen;
1171 }
1172
1173 // Do the encryption.
1174 string output(outlen, '\0');
1175 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1176 to_encrypt_len) <= 0) {
1177 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1178 return "Failure";
1179 }
1180 return output;
1181}
1182
Selene Huang31ab4042020-04-29 04:22:39 -07001183string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1184 const AuthorizationSet& in_params,
1185 AuthorizationSet* out_params) {
1186 SCOPED_TRACE("EncryptMessage");
1187 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1188}
1189
1190string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1191 AuthorizationSet* out_params) {
1192 SCOPED_TRACE("EncryptMessage");
1193 return EncryptMessage(key_blob_, message, params, out_params);
1194}
1195
1196string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1197 SCOPED_TRACE("EncryptMessage");
1198 AuthorizationSet out_params;
1199 string ciphertext = EncryptMessage(message, params, &out_params);
1200 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1201 return ciphertext;
1202}
1203
1204string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1205 PaddingMode padding) {
1206 SCOPED_TRACE("EncryptMessage");
1207 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1208 AuthorizationSet out_params;
1209 string ciphertext = EncryptMessage(message, params, &out_params);
1210 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1211 return ciphertext;
1212}
1213
1214string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1215 PaddingMode padding, vector<uint8_t>* iv_out) {
1216 SCOPED_TRACE("EncryptMessage");
1217 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1218 AuthorizationSet out_params;
1219 string ciphertext = EncryptMessage(message, params, &out_params);
1220 EXPECT_EQ(1U, out_params.size());
1221 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001222 EXPECT_TRUE(ivVal);
1223 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001224 return ciphertext;
1225}
1226
1227string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1228 PaddingMode padding, const vector<uint8_t>& iv_in) {
1229 SCOPED_TRACE("EncryptMessage");
1230 auto params = AuthorizationSetBuilder()
1231 .BlockMode(block_mode)
1232 .Padding(padding)
1233 .Authorization(TAG_NONCE, iv_in);
1234 AuthorizationSet out_params;
1235 string ciphertext = EncryptMessage(message, params, &out_params);
1236 return ciphertext;
1237}
1238
1239string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1240 PaddingMode padding, uint8_t mac_length_bits,
1241 const vector<uint8_t>& iv_in) {
1242 SCOPED_TRACE("EncryptMessage");
1243 auto params = AuthorizationSetBuilder()
1244 .BlockMode(block_mode)
1245 .Padding(padding)
1246 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1247 .Authorization(TAG_NONCE, iv_in);
1248 AuthorizationSet out_params;
1249 string ciphertext = EncryptMessage(message, params, &out_params);
1250 return ciphertext;
1251}
1252
David Drysdaled2cc8c22021-04-15 13:29:45 +01001253string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1254 PaddingMode padding, uint8_t mac_length_bits) {
1255 SCOPED_TRACE("EncryptMessage");
1256 auto params = AuthorizationSetBuilder()
1257 .BlockMode(block_mode)
1258 .Padding(padding)
1259 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1260 AuthorizationSet out_params;
1261 string ciphertext = EncryptMessage(message, params, &out_params);
1262 return ciphertext;
1263}
1264
Selene Huang31ab4042020-04-29 04:22:39 -07001265string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1266 const string& ciphertext,
1267 const AuthorizationSet& params) {
1268 SCOPED_TRACE("DecryptMessage");
1269 AuthorizationSet out_params;
1270 string plaintext =
1271 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1272 EXPECT_TRUE(out_params.empty());
1273 return plaintext;
1274}
1275
1276string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1277 const AuthorizationSet& params) {
1278 SCOPED_TRACE("DecryptMessage");
1279 return DecryptMessage(key_blob_, ciphertext, params);
1280}
1281
1282string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1283 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1284 SCOPED_TRACE("DecryptMessage");
1285 auto params = AuthorizationSetBuilder()
1286 .BlockMode(block_mode)
1287 .Padding(padding_mode)
1288 .Authorization(TAG_NONCE, iv);
1289 return DecryptMessage(key_blob_, ciphertext, params);
1290}
1291
1292std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1293 const vector<uint8_t>& key_blob) {
1294 std::pair<ErrorCode, vector<uint8_t>> retval;
1295 vector<uint8_t> outKeyBlob;
1296 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1297 ErrorCode errorcode = GetReturnErrorCode(result);
1298 retval = std::tie(errorcode, outKeyBlob);
1299
1300 return retval;
1301}
Seth Moorea12ac742023-03-03 13:40:30 -08001302
1303bool KeyMintAidlTestBase::IsRkpSupportRequired() const {
1304 if (get_vsr_api_level() >= __ANDROID_API_T__) {
1305 return true;
1306 }
1307
1308 if (get_vsr_api_level() >= __ANDROID_API_S__) {
1309 return SecLevel() != SecurityLevel::STRONGBOX;
1310 }
1311
1312 return false;
1313}
1314
Selene Huang31ab4042020-04-29 04:22:39 -07001315vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1316 switch (algorithm) {
1317 case Algorithm::RSA:
1318 switch (SecLevel()) {
1319 case SecurityLevel::SOFTWARE:
1320 case SecurityLevel::TRUSTED_ENVIRONMENT:
1321 return {2048, 3072, 4096};
1322 case SecurityLevel::STRONGBOX:
1323 return {2048};
1324 default:
1325 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1326 break;
1327 }
1328 break;
1329 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001330 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001331 break;
1332 case Algorithm::AES:
1333 return {128, 256};
1334 case Algorithm::TRIPLE_DES:
1335 return {168};
1336 case Algorithm::HMAC: {
1337 vector<uint32_t> retval((512 - 64) / 8 + 1);
1338 uint32_t size = 64 - 8;
1339 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1340 return retval;
1341 }
1342 default:
1343 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1344 return {};
1345 }
1346 ADD_FAILURE() << "Should be impossible to get here";
1347 return {};
1348}
1349
1350vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1351 if (SecLevel() == SecurityLevel::STRONGBOX) {
1352 switch (algorithm) {
1353 case Algorithm::RSA:
1354 return {3072, 4096};
1355 case Algorithm::EC:
1356 return {224, 384, 521};
1357 case Algorithm::AES:
1358 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001359 case Algorithm::TRIPLE_DES:
1360 return {56};
1361 default:
1362 return {};
1363 }
1364 } else {
1365 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001366 case Algorithm::AES:
1367 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001368 case Algorithm::TRIPLE_DES:
1369 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001370 default:
1371 return {};
1372 }
1373 }
1374 return {};
1375}
1376
David Drysdale7de9feb2021-03-05 14:56:19 +00001377vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1378 switch (algorithm) {
1379 case Algorithm::AES:
1380 return {
1381 BlockMode::CBC,
1382 BlockMode::CTR,
1383 BlockMode::ECB,
1384 BlockMode::GCM,
1385 };
1386 case Algorithm::TRIPLE_DES:
1387 return {
1388 BlockMode::CBC,
1389 BlockMode::ECB,
1390 };
1391 default:
1392 return {};
1393 }
1394}
1395
1396vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1397 BlockMode blockMode) {
1398 switch (algorithm) {
1399 case Algorithm::AES:
1400 switch (blockMode) {
1401 case BlockMode::CBC:
1402 case BlockMode::ECB:
1403 return {PaddingMode::NONE, PaddingMode::PKCS7};
1404 case BlockMode::CTR:
1405 case BlockMode::GCM:
1406 return {PaddingMode::NONE};
1407 default:
1408 return {};
1409 };
1410 case Algorithm::TRIPLE_DES:
1411 switch (blockMode) {
1412 case BlockMode::CBC:
1413 case BlockMode::ECB:
1414 return {PaddingMode::NONE, PaddingMode::PKCS7};
1415 default:
1416 return {};
1417 };
1418 default:
1419 return {};
1420 }
1421}
1422
1423vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1424 BlockMode blockMode) {
1425 switch (algorithm) {
1426 case Algorithm::AES:
1427 switch (blockMode) {
1428 case BlockMode::CTR:
1429 case BlockMode::GCM:
1430 return {PaddingMode::PKCS7};
1431 default:
1432 return {};
1433 };
1434 default:
1435 return {};
1436 }
1437}
1438
Selene Huang31ab4042020-04-29 04:22:39 -07001439vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1440 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1441 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001442 } else if (Curve25519Supported()) {
1443 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1444 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001445 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001446 return {
1447 EcCurve::P_224,
1448 EcCurve::P_256,
1449 EcCurve::P_384,
1450 EcCurve::P_521,
1451 };
Selene Huang31ab4042020-04-29 04:22:39 -07001452 }
1453}
1454
1455vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001456 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001457 // Curve 25519 is not supported, either because:
1458 // - KeyMint v1: it's an unknown enum value
1459 // - KeyMint v2+: it's not supported by StrongBox.
1460 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001461 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001462 if (Curve25519Supported()) {
1463 return {};
1464 } else {
1465 return {EcCurve::CURVE_25519};
1466 }
David Drysdaledf09e542021-06-08 15:46:11 +01001467 }
Selene Huang31ab4042020-04-29 04:22:39 -07001468}
1469
subrahmanyaman05642492022-02-05 07:10:56 +00001470vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1471 if (SecLevel() == SecurityLevel::STRONGBOX) {
1472 return {65537};
1473 } else {
1474 return {3, 65537};
1475 }
1476}
1477
Selene Huang31ab4042020-04-29 04:22:39 -07001478vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1479 switch (SecLevel()) {
1480 case SecurityLevel::SOFTWARE:
1481 case SecurityLevel::TRUSTED_ENVIRONMENT:
1482 if (withNone) {
1483 if (withMD5)
1484 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1485 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1486 Digest::SHA_2_512};
1487 else
1488 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1489 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1490 } else {
1491 if (withMD5)
1492 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1493 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1494 else
1495 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1496 Digest::SHA_2_512};
1497 }
1498 break;
1499 case SecurityLevel::STRONGBOX:
1500 if (withNone)
1501 return {Digest::NONE, Digest::SHA_2_256};
1502 else
1503 return {Digest::SHA_2_256};
1504 break;
1505 default:
1506 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1507 break;
1508 }
1509 ADD_FAILURE() << "Should be impossible to get here";
1510 return {};
1511}
1512
Shawn Willden7f424372021-01-10 18:06:50 -07001513static const vector<KeyParameter> kEmptyAuthList{};
1514
1515const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1516 const vector<KeyCharacteristics>& key_characteristics) {
1517 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1518 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1519 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1520}
1521
Qi Wubeefae42021-01-28 23:16:37 +08001522const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1523 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1524 auto found = std::find_if(
1525 key_characteristics.begin(), key_characteristics.end(),
1526 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001527 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1528}
1529
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001530ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001531 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001532 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1533 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1534 return result;
1535}
1536
1537ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001538 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001539 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1540 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1541 return result;
1542}
1543
1544ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1545 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001546 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001547 rsaKeyBlob, KeyPurpose::SIGN, message,
1548 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1549 return result;
1550}
1551
1552ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001553 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1554 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001555 return result;
1556}
1557
Selene Huang6e46f142021-04-20 19:20:11 -07001558void verify_serial(X509* cert, const uint64_t expected_serial) {
1559 BIGNUM_Ptr ser(BN_new());
1560 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1561
1562 uint64_t serial;
1563 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1564 EXPECT_EQ(serial, expected_serial);
1565}
1566
1567// Please set self_signed to true for fake certificates or self signed
1568// certificates
1569void verify_subject(const X509* cert, //
1570 const string& subject, //
1571 bool self_signed) {
1572 char* cert_issuer = //
1573 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1574
1575 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1576
1577 string expected_subject("/CN=");
1578 if (subject.empty()) {
1579 expected_subject.append("Android Keystore Key");
1580 } else {
1581 expected_subject.append(subject);
1582 }
1583
1584 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1585
1586 if (self_signed) {
1587 EXPECT_STREQ(cert_issuer, cert_subj)
1588 << "Cert issuer and subject mismatch for self signed certificate.";
1589 }
1590
1591 OPENSSL_free(cert_subj);
1592 OPENSSL_free(cert_issuer);
1593}
1594
Shawn Willden22fb9c12022-06-02 14:04:33 -06001595int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001596 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1597 if (vendor_api_level != -1) {
1598 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001599 }
Shawn Willden35db3492022-06-16 12:50:40 -06001600
1601 // Android S and older devices do not define ro.vendor.api_level
1602 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1603 if (vendor_api_level == -1) {
1604 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001605 }
Shawn Willden35db3492022-06-16 12:50:40 -06001606
1607 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1608 if (product_api_level == -1) {
1609 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1610 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001611 }
Shawn Willden35db3492022-06-16 12:50:40 -06001612
1613 // VSR API level is the minimum of vendor_api_level and product_api_level.
1614 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1615 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001616 }
Shawn Willden35db3492022-06-16 12:50:40 -06001617 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001618}
1619
David Drysdale555ba002022-05-03 18:48:57 +01001620bool is_gsi_image() {
1621 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1622 return ifs.good();
1623}
1624
Selene Huang6e46f142021-04-20 19:20:11 -07001625vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1626 BIGNUM_Ptr serial(BN_new());
1627 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1628
1629 int len = BN_num_bytes(serial.get());
1630 vector<uint8_t> serial_blob(len);
1631 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1632 return {};
1633 }
1634
David Drysdaledb0dcf52021-05-18 11:43:31 +01001635 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1636 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1637 // Top bit being set indicates a negative number in two's complement, but our input
1638 // was positive.
1639 // In either case, prepend a zero byte.
1640 serial_blob.insert(serial_blob.begin(), 0x00);
1641 }
1642
Selene Huang6e46f142021-04-20 19:20:11 -07001643 return serial_blob;
1644}
1645
1646void verify_subject_and_serial(const Certificate& certificate, //
1647 const uint64_t expected_serial, //
1648 const string& subject, bool self_signed) {
1649 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1650 ASSERT_TRUE(!!cert.get());
1651
1652 verify_serial(cert.get(), expected_serial);
1653 verify_subject(cert.get(), subject, self_signed);
1654}
1655
Shawn Willden4315e132022-03-20 12:49:46 -06001656void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1657 VerifiedBoot verified_boot_state,
1658 const vector<uint8_t>& verified_boot_hash) {
1659 char property_value[PROPERTY_VALUE_MAX] = {};
1660
1661 if (avb_verification_enabled()) {
1662 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1663 string prop_string(property_value);
1664 EXPECT_EQ(prop_string.size(), 64);
1665 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1666
1667 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1668 if (!strcmp(property_value, "unlocked")) {
1669 EXPECT_FALSE(device_locked);
1670 } else {
1671 EXPECT_TRUE(device_locked);
1672 }
1673
1674 // Check that the device is locked if not debuggable, e.g., user build
1675 // images in CTS. For VTS, debuggable images are used to allow adb root
1676 // and the device is unlocked.
1677 if (!property_get_bool("ro.debuggable", false)) {
1678 EXPECT_TRUE(device_locked);
1679 } else {
1680 EXPECT_FALSE(device_locked);
1681 }
1682 }
1683
1684 // Verified boot key should be all 0's if the boot state is not verified or self signed
1685 std::string empty_boot_key(32, '\0');
1686 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1687 verified_boot_key.size());
1688 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1689 if (!strcmp(property_value, "green")) {
1690 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1691 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1692 verified_boot_key.size()));
1693 } else if (!strcmp(property_value, "yellow")) {
1694 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1695 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1696 verified_boot_key.size()));
1697 } else if (!strcmp(property_value, "orange")) {
1698 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1699 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1700 verified_boot_key.size()));
1701 } else if (!strcmp(property_value, "red")) {
1702 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1703 } else {
1704 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1705 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1706 verified_boot_key.size()));
1707 }
1708}
1709
David Drysdale7dff4fc2021-12-10 10:10:52 +00001710bool verify_attestation_record(int32_t aidl_version, //
1711 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001712 const string& app_id, //
1713 AuthorizationSet expected_sw_enforced, //
1714 AuthorizationSet expected_hw_enforced, //
1715 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001716 const vector<uint8_t>& attestation_cert,
1717 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001718 X509_Ptr cert(parse_cert_blob(attestation_cert));
1719 EXPECT_TRUE(!!cert.get());
1720 if (!cert.get()) return false;
1721
Rajesh Nyamagoude98263e2023-02-09 20:36:33 +00001722 // Make sure CRL Distribution Points extension is not present in a certificate
1723 // containing attestation record.
1724 check_crl_distribution_points_extension_not_present(cert.get());
1725
Shawn Willden7c130392020-12-21 09:58:22 -07001726 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1727 EXPECT_TRUE(!!attest_rec);
1728 if (!attest_rec) return false;
1729
1730 AuthorizationSet att_sw_enforced;
1731 AuthorizationSet att_hw_enforced;
1732 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001733 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001734 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001735 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001736 vector<uint8_t> att_challenge;
1737 vector<uint8_t> att_unique_id;
1738 vector<uint8_t> att_app_id;
1739
1740 auto error = parse_attestation_record(attest_rec->data, //
1741 attest_rec->length, //
1742 &att_attestation_version, //
1743 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001744 &att_keymint_version, //
1745 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001746 &att_challenge, //
1747 &att_sw_enforced, //
1748 &att_hw_enforced, //
1749 &att_unique_id);
1750 EXPECT_EQ(ErrorCode::OK, error);
1751 if (error != ErrorCode::OK) return false;
1752
David Drysdale7dff4fc2021-12-10 10:10:52 +00001753 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001754 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001755
Selene Huang4f64c222021-04-13 19:54:36 -07001756 // check challenge and app id only if we expects a non-fake certificate
1757 if (challenge.length() > 0) {
1758 EXPECT_EQ(challenge.length(), att_challenge.size());
1759 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1760
1761 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1762 }
Shawn Willden7c130392020-12-21 09:58:22 -07001763
David Drysdale7dff4fc2021-12-10 10:10:52 +00001764 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001765 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001766 EXPECT_EQ(security_level, att_attestation_security_level);
1767
Tri Vob21e6df2023-02-17 14:55:43 -08001768 for (int i = 0; i < att_hw_enforced.size(); i++) {
1769 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1770 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1771 std::string date =
1772 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001773
Tri Vob21e6df2023-02-17 14:55:43 -08001774 // strptime seems to require delimiters, but the tag value will
1775 // be YYYYMMDD
1776 if (date.size() != 8) {
1777 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1778 << " with invalid format (not YYYYMMDD): " << date;
1779 return false;
Shawn Willden7c130392020-12-21 09:58:22 -07001780 }
Tri Vob21e6df2023-02-17 14:55:43 -08001781 date.insert(6, "-");
1782 date.insert(4, "-");
1783 struct tm time;
1784 strptime(date.c_str(), "%Y-%m-%d", &time);
1785
1786 // Day of the month (0-31)
1787 EXPECT_GE(time.tm_mday, 0);
1788 EXPECT_LT(time.tm_mday, 32);
1789 // Months since Jan (0-11)
1790 EXPECT_GE(time.tm_mon, 0);
1791 EXPECT_LT(time.tm_mon, 12);
1792 // Years since 1900
1793 EXPECT_GT(time.tm_year, 110);
1794 EXPECT_LT(time.tm_year, 200);
Shawn Willden7c130392020-12-21 09:58:22 -07001795 }
1796 }
1797
1798 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1799 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1800 // indicates correct encoding. No need to check if it's in both lists, since the
1801 // AuthorizationSet compare below will handle mismatches of tags.
1802 if (security_level == SecurityLevel::SOFTWARE) {
1803 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1804 } else {
1805 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1806 }
1807
Shawn Willden7c130392020-12-21 09:58:22 -07001808 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1809 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1810 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1811 att_hw_enforced.Contains(TAG_KEY_SIZE));
1812 }
1813
1814 // Test root of trust elements
1815 vector<uint8_t> verified_boot_key;
1816 VerifiedBoot verified_boot_state;
1817 bool device_locked;
1818 vector<uint8_t> verified_boot_hash;
1819 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1820 &verified_boot_state, &device_locked, &verified_boot_hash);
1821 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001822 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001823
1824 att_sw_enforced.Sort();
1825 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001826 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001827
1828 att_hw_enforced.Sort();
1829 expected_hw_enforced.Sort();
1830 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1831
David Drysdale565ccc72021-10-11 12:49:50 +01001832 if (unique_id != nullptr) {
1833 *unique_id = att_unique_id;
1834 }
1835
Shawn Willden7c130392020-12-21 09:58:22 -07001836 return true;
1837}
1838
1839string bin2hex(const vector<uint8_t>& data) {
1840 string retval;
1841 retval.reserve(data.size() * 2 + 1);
1842 for (uint8_t byte : data) {
1843 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1844 retval.push_back(nibble2hex[0x0F & byte]);
1845 }
1846 return retval;
1847}
1848
David Drysdalef0d516d2021-03-22 07:51:43 +00001849AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1850 AuthorizationSet authList;
1851 for (auto& entry : key_characteristics) {
1852 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1853 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1854 authList.push_back(AuthorizationSet(entry.authorizations));
1855 }
1856 }
1857 return authList;
1858}
1859
1860AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1861 AuthorizationSet authList;
1862 for (auto& entry : key_characteristics) {
1863 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1864 entry.securityLevel == SecurityLevel::KEYSTORE) {
1865 authList.push_back(AuthorizationSet(entry.authorizations));
1866 }
1867 }
1868 return authList;
1869}
1870
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001871AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1872 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001873 std::stringstream cert_data;
1874
1875 for (size_t i = 0; i < chain.size(); ++i) {
1876 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1877
1878 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1879 X509_Ptr signing_cert;
1880 if (i < chain.size() - 1) {
1881 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1882 } else {
1883 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1884 }
1885 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1886
1887 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1888 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1889
1890 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1891 return AssertionFailure()
1892 << "Verification of certificate " << i << " failed "
1893 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1894 << cert_data.str();
1895 }
1896
1897 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1898 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001899 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001900 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1901 << " Signer subject is " << signer_subj
1902 << " Issuer subject is " << cert_issuer << endl
1903 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001904 }
Shawn Willden7c130392020-12-21 09:58:22 -07001905 }
1906
1907 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1908 return AssertionSuccess();
1909}
1910
1911X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1912 const uint8_t* p = blob.data();
1913 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1914}
1915
Tri Voec50ee12023-02-14 16:29:53 -08001916// Extract attestation record from cert. Returned object is still part of cert; don't free it
1917// separately.
1918ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
1919 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
1920 EXPECT_TRUE(!!oid.get());
1921 if (!oid.get()) return nullptr;
1922
1923 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
1924 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
1925 if (location == -1) return nullptr;
1926
1927 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
1928 EXPECT_TRUE(!!attest_rec_ext)
1929 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
1930 if (!attest_rec_ext) return nullptr;
1931
1932 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
1933 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
1934 return attest_rec;
1935}
1936
David Drysdalef0d516d2021-03-22 07:51:43 +00001937vector<uint8_t> make_name_from_str(const string& name) {
1938 X509_NAME_Ptr x509_name(X509_NAME_new());
1939 EXPECT_TRUE(x509_name.get() != nullptr);
1940 if (!x509_name) return {};
1941
1942 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1943 "CN", //
1944 MBSTRING_ASC,
1945 reinterpret_cast<const uint8_t*>(name.c_str()),
1946 -1, // len
1947 -1, // loc
1948 0 /* set */));
1949
1950 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1951 EXPECT_GT(len, 0);
1952
1953 vector<uint8_t> retval(len);
1954 uint8_t* p = retval.data();
1955 i2d_X509_NAME(x509_name.get(), &p);
1956
1957 return retval;
1958}
1959
David Drysdale4dc01072021-04-01 12:17:35 +01001960namespace {
1961
1962void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1963 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1964 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1965
1966 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1967 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001968 EXPECT_THAT(
1969 cppbor::prettyPrint(parsedPayload.get()),
1970 MatchesRegex("\\{\n"
1971 " 1 : 2,\n" // kty: EC2
1972 " 3 : -7,\n" // alg: ES256
1973 " -1 : 1,\n" // EC id: P256
1974 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1975 // sequence of 32 hexadecimal bytes, enclosed in braces and
1976 // separated by commas. In this case, some Ed25519 public key.
1977 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1978 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1979 " -70000 : null,\n" // test marker
1980 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001981 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001982 EXPECT_THAT(
1983 cppbor::prettyPrint(parsedPayload.get()),
1984 MatchesRegex("\\{\n"
1985 " 1 : 2,\n" // kty: EC2
1986 " 3 : -7,\n" // alg: ES256
1987 " -1 : 1,\n" // EC id: P256
1988 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1989 // sequence of 32 hexadecimal bytes, enclosed in braces and
1990 // separated by commas. In this case, some Ed25519 public key.
1991 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1992 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1993 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001994 }
1995}
1996
1997} // namespace
1998
1999void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
2000 vector<uint8_t>* payload_value) {
2001 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
2002 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
2003
2004 ASSERT_NE(coseMac0->asArray(), nullptr);
2005 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
2006
2007 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
2008 ASSERT_NE(protParms, nullptr);
2009
2010 // Header label:value of 'alg': HMAC-256
2011 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
2012
2013 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
2014 ASSERT_NE(unprotParms, nullptr);
2015 ASSERT_EQ(unprotParms->size(), 0);
2016
2017 // The payload is a bstr holding an encoded COSE_Key
2018 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
2019 ASSERT_NE(payload, nullptr);
2020 check_cose_key(payload->value(), testMode);
2021
2022 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
2023 ASSERT_TRUE(coseMac0Tag);
2024 auto extractedTag = coseMac0Tag->value();
2025 EXPECT_EQ(extractedTag.size(), 32U);
2026
2027 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07002028 auto macFunction = [](const cppcose::bytevec& input) {
2029 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
2030 };
2031 auto testTag =
2032 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01002033 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
2034
2035 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07002036 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01002037 } else {
Seth Moore026bb742021-04-30 11:41:18 -07002038 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002039 }
2040 if (payload_value != nullptr) {
2041 *payload_value = payload->value();
2042 }
2043}
2044
2045void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2046 // Extract x and y affine coordinates from the encoded Cose_Key.
2047 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2048 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2049 auto coseKey = parsedPayload->asMap();
2050 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2051 ASSERT_NE(xItem->asBstr(), nullptr);
2052 vector<uint8_t> x = xItem->asBstr()->value();
2053 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2054 ASSERT_NE(yItem->asBstr(), nullptr);
2055 vector<uint8_t> y = yItem->asBstr()->value();
2056
2057 // Concatenate: 0x04 (uncompressed form marker) | x | y
2058 vector<uint8_t> pubKeyData{0x04};
2059 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2060 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2061
2062 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2063 ASSERT_NE(ecKey, nullptr);
2064 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2065 ASSERT_NE(group, nullptr);
2066 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2067 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2068 ASSERT_NE(point, nullptr);
2069 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2070 nullptr),
2071 1);
2072 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2073
2074 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2075 ASSERT_NE(pubKey, nullptr);
2076 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2077 *signingKey = std::move(pubKey);
2078}
2079
Max Biresa97ec692022-11-21 23:37:54 -08002080void device_id_attestation_vsr_check(const ErrorCode& result) {
Shawn Willden1a545db2023-02-22 14:32:33 -07002081 if (get_vsr_api_level() > __ANDROID_API_T__) {
Max Biresa97ec692022-11-21 23:37:54 -08002082 ASSERT_FALSE(result == ErrorCode::INVALID_TAG)
2083 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2084 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2085 << "be used for a case where updateAad() is called after update(). As of "
2086 << "VSR-14, this is now enforced as an error.";
2087 }
2088}
2089
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002090// Check whether the given named feature is available.
2091bool check_feature(const std::string& name) {
2092 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002093 ::android::sp<::android::IBinder> binder(
2094 sm->waitForService(::android::String16("package_native")));
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002095 if (binder == nullptr) {
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002096 GTEST_LOG_(ERROR) << "waitForService package_native failed";
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002097 return false;
2098 }
2099 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2100 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2101 if (packageMgr == nullptr) {
2102 GTEST_LOG_(ERROR) << "Cannot find package manager";
2103 return false;
2104 }
2105 bool hasFeature = false;
2106 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2107 if (!status.isOk()) {
2108 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2109 return false;
2110 }
2111 return hasFeature;
2112}
2113
Selene Huang31ab4042020-04-29 04:22:39 -07002114} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002115
Janis Danisevskis24c04702020-12-16 18:28:39 -08002116} // namespace aidl::android::hardware::security::keymint