blob: e05867de230e8ea112cd454169d4c8e623d10c04 [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "KeyMintAidlTestBase.h"
18
19#include <chrono>
David Drysdale555ba002022-05-03 18:48:57 +010020#include <fstream>
Shawn Willden7f424372021-01-10 18:06:50 -070021#include <unordered_set>
Selene Huang31ab4042020-04-29 04:22:39 -070022#include <vector>
23
24#include <android-base/logging.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080025#include <android/binder_manager.h>
David Drysdale3d2ba0a2023-01-11 13:27:26 +000026#include <android/content/pm/IPackageManagerNative.h>
David Drysdale4dc01072021-04-01 12:17:35 +010027#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070028#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010029#include <gmock/gmock.h>
David Drysdale42fe1892021-10-14 14:43:46 +010030#include <openssl/evp.h>
Shawn Willden7c130392020-12-21 09:58:22 -070031#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070033
Max Bires9704ff62021-04-07 11:12:01 -070034#include <keymaster/cppcose/cppcose.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000035#include <keymint_support/key_param_output.h>
36#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070037#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070038
Janis Danisevskis24c04702020-12-16 18:28:39 -080039namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070040
David Drysdale4dc01072021-04-01 12:17:35 +010041using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070042using namespace std::literals::chrono_literals;
43using std::endl;
44using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070045using std::unique_ptr;
46using ::testing::AssertionFailure;
47using ::testing::AssertionResult;
48using ::testing::AssertionSuccess;
Seth Moore026bb742021-04-30 11:41:18 -070049using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010050using ::testing::MatchesRegex;
Seth Moore026bb742021-04-30 11:41:18 -070051using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070052
53::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
54 if (set.size() == 0)
55 os << "(Empty)" << ::std::endl;
56 else {
57 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070058 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070059 }
60 return os;
61}
62
63namespace test {
64
Shawn Willden7f424372021-01-10 18:06:50 -070065namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010066
David Drysdale37af4b32021-05-14 16:46:59 +010067// Invalid value for a patchlevel (which is of form YYYYMMDD).
68const uint32_t kInvalidPatchlevel = 99998877;
69
David Drysdaledf8f52e2021-05-06 08:10:58 +010070// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
71// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
72const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
73
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000074typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070075// Predicate for testing basic characteristics validity in generation or import.
76bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
77 const vector<KeyCharacteristics>& key_characteristics) {
78 if (key_characteristics.empty()) return false;
79
80 std::unordered_set<SecurityLevel> levels_seen;
81 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070082 if (entry.authorizations.empty()) {
83 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
84 return false;
85 }
Shawn Willden7f424372021-01-10 18:06:50 -070086
Qi Wubeefae42021-01-28 23:16:37 +080087 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
88 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
89
Seth Moore2a9a00e2021-08-04 16:31:52 -070090 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
91 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
92 return false;
93 }
Shawn Willden7f424372021-01-10 18:06:50 -070094 levels_seen.insert(entry.securityLevel);
95
96 // Generally, we should only have one entry, at the same security level as the KM
97 // instance. There is an exception: StrongBox KM can have some authorizations that are
98 // enforced by the TEE.
99 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
100 (secLevel == SecurityLevel::STRONGBOX &&
101 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
102
Seth Moore2a9a00e2021-08-04 16:31:52 -0700103 if (!isExpectedSecurityLevel) {
104 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
105 return false;
106 }
Shawn Willden7f424372021-01-10 18:06:50 -0700107 }
108 return true;
109}
110
David Drysdale7dff4fc2021-12-10 10:10:52 +0000111void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
112 // Version numbers in attestation extensions should be a multiple of 100.
113 EXPECT_EQ(attestation_version % 100, 0);
114
115 // The multiplier should never be higher than the AIDL version, but can be less
116 // (for example, if the implementation is from an earlier version but the HAL service
117 // uses the default libraries and so reports the current AIDL version).
118 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
119}
120
Shawn Willden7c130392020-12-21 09:58:22 -0700121bool avb_verification_enabled() {
122 char value[PROPERTY_VALUE_MAX];
123 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
124}
125
126char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
127 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
128
129// Attestations don't contain everything in key authorization lists, so we need to filter the key
130// lists to produce the lists that we expect to match the attestations.
131auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100132 Tag::CREATION_DATETIME,
133 Tag::HARDWARE_TYPE,
134 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700135};
136
137AuthorizationSet filtered_tags(const AuthorizationSet& set) {
138 AuthorizationSet filtered;
139 std::remove_copy_if(
140 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
141 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
142 kTagsToFilter.end();
143 });
144 return filtered;
145}
146
David Drysdale300b5552021-05-20 12:05:26 +0100147// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
148void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
149 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
150 [](const auto& entry) {
151 return entry.securityLevel == SecurityLevel::KEYSTORE;
152 }),
153 characteristics->end());
154}
155
Shawn Willden7c130392020-12-21 09:58:22 -0700156string x509NameToStr(X509_NAME* name) {
157 char* s = X509_NAME_oneline(name, nullptr, 0);
158 string retval(s);
159 OPENSSL_free(s);
160 return retval;
161}
162
Shawn Willden7f424372021-01-10 18:06:50 -0700163} // namespace
164
Shawn Willden7c130392020-12-21 09:58:22 -0700165bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
166bool KeyMintAidlTestBase::dump_Attestations = false;
David Drysdale9f5c0c52022-11-03 15:10:16 +0000167std::string KeyMintAidlTestBase::keyblob_dir;
Shawn Willden7c130392020-12-21 09:58:22 -0700168
David Drysdale37af4b32021-05-14 16:46:59 +0100169uint32_t KeyMintAidlTestBase::boot_patch_level(
170 const vector<KeyCharacteristics>& key_characteristics) {
171 // The boot patchlevel is not available as a property, but should be present
172 // in the key characteristics of any created key.
173 AuthorizationSet allAuths;
174 for (auto& entry : key_characteristics) {
175 allAuths.push_back(AuthorizationSet(entry.authorizations));
176 }
177 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
178 if (patchlevel.has_value()) {
179 return patchlevel.value();
180 } else {
181 // No boot patchlevel is available. Return a value that won't match anything
182 // and so will trigger test failures.
183 return kInvalidPatchlevel;
184 }
185}
186
187uint32_t KeyMintAidlTestBase::boot_patch_level() {
188 return boot_patch_level(key_characteristics_);
189}
190
Prashant Patil88ad1892022-03-15 16:31:02 +0000191/**
192 * An API to determine device IDs attestation is required or not,
193 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
194 */
195bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
196 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= 33;
197}
198
David Drysdale42fe1892021-10-14 14:43:46 +0100199bool KeyMintAidlTestBase::Curve25519Supported() {
200 // Strongbox never supports curve 25519.
201 if (SecLevel() == SecurityLevel::STRONGBOX) {
202 return false;
203 }
204
205 // Curve 25519 was included in version 2 of the KeyMint interface.
206 int32_t version = 0;
207 auto status = keymint_->getInterfaceVersion(&version);
208 if (!status.isOk()) {
209 ADD_FAILURE() << "Failed to determine interface version";
210 }
211 return version >= 2;
212}
213
Janis Danisevskis24c04702020-12-16 18:28:39 -0800214ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700215 if (result.isOk()) return ErrorCode::OK;
216
Janis Danisevskis24c04702020-12-16 18:28:39 -0800217 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
218 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700219 }
220
221 return ErrorCode::UNKNOWN_ERROR;
222}
223
Janis Danisevskis24c04702020-12-16 18:28:39 -0800224void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700225 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800226 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700227
228 KeyMintHardwareInfo info;
229 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
230
231 securityLevel_ = info.securityLevel;
232 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
233 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100234 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700235
236 os_version_ = getOsVersion();
237 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100238 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700239}
240
David Drysdale7dff4fc2021-12-10 10:10:52 +0000241int32_t KeyMintAidlTestBase::AidlVersion() {
242 int32_t version = 0;
243 auto status = keymint_->getInterfaceVersion(&version);
244 if (!status.isOk()) {
245 ADD_FAILURE() << "Failed to determine interface version";
246 }
247 return version;
248}
249
Selene Huang31ab4042020-04-29 04:22:39 -0700250void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800251 if (AServiceManager_isDeclared(GetParam().c_str())) {
252 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
253 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
254 } else {
255 InitializeKeyMint(nullptr);
256 }
Selene Huang31ab4042020-04-29 04:22:39 -0700257}
258
259ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700260 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700261 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700262 vector<KeyCharacteristics>* key_characteristics,
263 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700264 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
265 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700266 << "Previous characteristics not deleted before generating key. Test bug.";
267
Shawn Willden7f424372021-01-10 18:06:50 -0700268 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700269 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700270 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700271 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
272 creationResult.keyCharacteristics);
273 EXPECT_GT(creationResult.keyBlob.size(), 0);
274 *key_blob = std::move(creationResult.keyBlob);
275 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700276 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700277
278 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
279 EXPECT_TRUE(algorithm);
280 if (algorithm &&
281 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700282 EXPECT_GE(cert_chain->size(), 1);
283 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
284 if (attest_key) {
285 EXPECT_EQ(cert_chain->size(), 1);
286 } else {
287 EXPECT_GT(cert_chain->size(), 1);
288 }
289 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700290 } else {
291 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700292 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700293 }
Selene Huang31ab4042020-04-29 04:22:39 -0700294 }
295
296 return GetReturnErrorCode(result);
297}
298
Shawn Willden7c130392020-12-21 09:58:22 -0700299ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
300 const optional<AttestationKey>& attest_key) {
301 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700302}
303
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000304ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
305 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
306 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
307 vector<Certificate>* cert_chain) {
308 AttestationKey attest_key;
309 vector<Certificate> attest_cert_chain;
310 vector<KeyCharacteristics> attest_key_characteristics;
311 // Generate a key with self signed attestation.
312 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
313 &attest_key_characteristics, &attest_cert_chain);
314 if (error != ErrorCode::OK) {
315 return error;
316 }
317
318 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
319 // Generate a key, by passing the above self signed attestation key as attest key.
320 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
321 if (error == ErrorCode::OK) {
322 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
323 cert_chain->push_back(attest_cert_chain[0]);
324 }
325 return error;
326}
327
Selene Huang31ab4042020-04-29 04:22:39 -0700328ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
329 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700330 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700331 Status result;
332
Shawn Willden7f424372021-01-10 18:06:50 -0700333 cert_chain_.clear();
334 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700335 key_blob->clear();
336
Shawn Willden7f424372021-01-10 18:06:50 -0700337 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700338 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700339 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700340 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700341
342 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700343 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
344 creationResult.keyCharacteristics);
345 EXPECT_GT(creationResult.keyBlob.size(), 0);
346
347 *key_blob = std::move(creationResult.keyBlob);
348 *key_characteristics = std::move(creationResult.keyCharacteristics);
349 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700350
351 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
352 EXPECT_TRUE(algorithm);
353 if (algorithm &&
354 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
355 EXPECT_GE(cert_chain_.size(), 1);
356 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
357 } else {
358 // For symmetric keys there should be no certificates.
359 EXPECT_EQ(cert_chain_.size(), 0);
360 }
Selene Huang31ab4042020-04-29 04:22:39 -0700361 }
362
363 return GetReturnErrorCode(result);
364}
365
366ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
367 const string& key_material) {
368 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
369}
370
371ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
372 const AuthorizationSet& wrapping_key_desc,
373 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100374 const AuthorizationSet& unwrapping_params,
375 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700376 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
377
Shawn Willden7f424372021-01-10 18:06:50 -0700378 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700379
Shawn Willden7f424372021-01-10 18:06:50 -0700380 KeyCreationResult creationResult;
381 Status result = keymint_->importWrappedKey(
382 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
383 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100384 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700385
386 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700387 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
388 creationResult.keyCharacteristics);
389 EXPECT_GT(creationResult.keyBlob.size(), 0);
390
391 key_blob_ = std::move(creationResult.keyBlob);
392 key_characteristics_ = std::move(creationResult.keyCharacteristics);
393 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700394
395 AuthorizationSet allAuths;
396 for (auto& entry : key_characteristics_) {
397 allAuths.push_back(AuthorizationSet(entry.authorizations));
398 }
399 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
400 EXPECT_TRUE(algorithm);
401 if (algorithm &&
402 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
403 EXPECT_GE(cert_chain_.size(), 1);
404 } else {
405 // For symmetric keys there should be no certificates.
406 EXPECT_EQ(cert_chain_.size(), 0);
407 }
Selene Huang31ab4042020-04-29 04:22:39 -0700408 }
409
410 return GetReturnErrorCode(result);
411}
412
David Drysdale300b5552021-05-20 12:05:26 +0100413ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
414 const vector<uint8_t>& app_id,
415 const vector<uint8_t>& app_data,
416 vector<KeyCharacteristics>* key_characteristics) {
417 Status result =
418 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
419 return GetReturnErrorCode(result);
420}
421
422ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
423 vector<KeyCharacteristics>* key_characteristics) {
424 vector<uint8_t> empty_app_id, empty_app_data;
425 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
426}
427
428void KeyMintAidlTestBase::CheckCharacteristics(
429 const vector<uint8_t>& key_blob,
430 const vector<KeyCharacteristics>& generate_characteristics) {
431 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
432 // generateKey() should be excluded, as KeyMint will have no record of them.
433 // This applies to CREATION_DATETIME in particular.
434 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
435 strip_keystore_tags(&expected_characteristics);
436
437 vector<KeyCharacteristics> retrieved;
438 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
439 EXPECT_EQ(expected_characteristics, retrieved);
440}
441
442void KeyMintAidlTestBase::CheckAppIdCharacteristics(
443 const vector<uint8_t>& key_blob, std::string_view app_id_string,
444 std::string_view app_data_string,
445 const vector<KeyCharacteristics>& generate_characteristics) {
446 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
447 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
448 strip_keystore_tags(&expected_characteristics);
449
450 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
451 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
452 vector<KeyCharacteristics> retrieved;
453 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
454 EXPECT_EQ(expected_characteristics, retrieved);
455
456 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
457 vector<uint8_t> empty;
458 vector<KeyCharacteristics> not_retrieved;
459 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
460 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
461 EXPECT_EQ(not_retrieved.size(), 0);
462
463 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
464 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
465 EXPECT_EQ(not_retrieved.size(), 0);
466
467 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
468 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
469 EXPECT_EQ(not_retrieved.size(), 0);
470}
471
Selene Huang31ab4042020-04-29 04:22:39 -0700472ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
473 Status result = keymint_->deleteKey(*key_blob);
474 if (!keep_key_blob) {
475 *key_blob = vector<uint8_t>();
476 }
477
Janis Danisevskis24c04702020-12-16 18:28:39 -0800478 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700479 return GetReturnErrorCode(result);
480}
481
482ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
483 return DeleteKey(&key_blob_, keep_key_blob);
484}
485
486ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
487 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800488 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700489 return GetReturnErrorCode(result);
490}
491
David Drysdaled2cc8c22021-04-15 13:29:45 +0100492ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
493 Status result = keymint_->destroyAttestationIds();
494 return GetReturnErrorCode(result);
495}
496
Selene Huang31ab4042020-04-29 04:22:39 -0700497void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
498 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
499 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
500}
501
502void KeyMintAidlTestBase::CheckedDeleteKey() {
503 CheckedDeleteKey(&key_blob_);
504}
505
506ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
507 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800508 AuthorizationSet* out_params,
509 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700510 SCOPED_TRACE("Begin");
511 Status result;
512 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100513 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700514
515 if (result.isOk()) {
516 *out_params = out.params;
517 challenge_ = out.challenge;
518 op = out.operation;
519 }
520
521 return GetReturnErrorCode(result);
522}
523
524ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
525 const AuthorizationSet& in_params,
526 AuthorizationSet* out_params) {
527 SCOPED_TRACE("Begin");
528 Status result;
529 BeginResult out;
530
David Drysdale56ba9122021-04-19 19:10:47 +0100531 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700532
533 if (result.isOk()) {
534 *out_params = out.params;
535 challenge_ = out.challenge;
536 op_ = out.operation;
537 }
538
539 return GetReturnErrorCode(result);
540}
541
542ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
543 AuthorizationSet* out_params) {
544 SCOPED_TRACE("Begin");
545 EXPECT_EQ(nullptr, op_);
546 return Begin(purpose, key_blob_, in_params, out_params);
547}
548
549ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
550 SCOPED_TRACE("Begin");
551 AuthorizationSet out_params;
552 ErrorCode result = Begin(purpose, in_params, &out_params);
553 EXPECT_TRUE(out_params.empty());
554 return result;
555}
556
Shawn Willden92d79c02021-02-19 07:31:55 -0700557ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
558 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
559 {} /* hardwareAuthToken */,
560 {} /* verificationToken */));
561}
562
563ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700564 SCOPED_TRACE("Update");
565
566 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700567 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700568
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800569 EXPECT_NE(op_, nullptr);
570 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
571
Shawn Willden92d79c02021-02-19 07:31:55 -0700572 std::vector<uint8_t> o_put;
573 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700574
David Drysdalefeab5d92022-01-06 15:46:23 +0000575 if (result.isOk()) {
576 output->append(o_put.begin(), o_put.end());
577 } else {
578 // Failure always terminates the operation.
579 op_ = {};
580 }
Selene Huang31ab4042020-04-29 04:22:39 -0700581
582 return GetReturnErrorCode(result);
583}
584
Shawn Willden92d79c02021-02-19 07:31:55 -0700585ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700586 string* output) {
587 SCOPED_TRACE("Finish");
588 Status result;
589
590 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700591 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700592
593 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700594 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
595 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
596 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700597
Shawn Willden92d79c02021-02-19 07:31:55 -0700598 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700599
Shawn Willden92d79c02021-02-19 07:31:55 -0700600 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700601 return GetReturnErrorCode(result);
602}
603
Janis Danisevskis24c04702020-12-16 18:28:39 -0800604ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700605 SCOPED_TRACE("Abort");
606
607 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700608 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700609
610 Status retval = op->abort();
611 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800612 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700613}
614
615ErrorCode KeyMintAidlTestBase::Abort() {
616 SCOPED_TRACE("Abort");
617
618 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700619 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700620
621 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800622 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700623}
624
625void KeyMintAidlTestBase::AbortIfNeeded() {
626 SCOPED_TRACE("AbortIfNeeded");
627 if (op_) {
628 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800629 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700630 }
631}
632
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000633auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
634 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700635 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000636 AuthorizationSet begin_out_params;
637 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700638 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000639
640 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700641 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000642}
643
Selene Huang31ab4042020-04-29 04:22:39 -0700644string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
645 const string& message, const AuthorizationSet& in_params,
646 AuthorizationSet* out_params) {
647 SCOPED_TRACE("ProcessMessage");
648 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700649 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700650 EXPECT_EQ(ErrorCode::OK, result);
651 if (result != ErrorCode::OK) {
652 return "";
653 }
654
655 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700656 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700657 return output;
658}
659
660string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
661 const AuthorizationSet& params) {
662 SCOPED_TRACE("SignMessage");
663 AuthorizationSet out_params;
664 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
665 EXPECT_TRUE(out_params.empty());
666 return signature;
667}
668
669string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
670 SCOPED_TRACE("SignMessage");
671 return SignMessage(key_blob_, message, params);
672}
673
674string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
675 SCOPED_TRACE("MacMessage");
676 return SignMessage(
677 key_blob_, message,
678 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
679}
680
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530681void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
682 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000683 auto builder = AuthorizationSetBuilder()
684 .Authorization(TAG_NO_AUTH_REQUIRED)
685 .AesEncryptionKey(128)
686 .BlockMode(block_mode)
687 .Padding(PaddingMode::NONE);
688 if (block_mode == BlockMode::GCM) {
689 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
690 }
691 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530692
693 for (int increment = 1; increment <= message_size; ++increment) {
694 string message(message_size, 'a');
695 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
696 if (block_mode == BlockMode::GCM) {
697 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
698 }
699
700 AuthorizationSet output_params;
701 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
702
703 string ciphertext;
704 string to_send;
705 for (size_t i = 0; i < message.size(); i += increment) {
706 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
707 }
708 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
709 << "Error sending " << to_send << " with block mode " << block_mode;
710
711 switch (block_mode) {
712 case BlockMode::GCM:
713 EXPECT_EQ(message.size() + 16, ciphertext.size());
714 break;
715 case BlockMode::CTR:
716 EXPECT_EQ(message.size(), ciphertext.size());
717 break;
718 case BlockMode::CBC:
719 case BlockMode::ECB:
720 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
721 break;
722 }
723
724 auto iv = output_params.GetTagValue(TAG_NONCE);
725 switch (block_mode) {
726 case BlockMode::CBC:
727 case BlockMode::GCM:
728 case BlockMode::CTR:
729 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
730 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
731 params.push_back(TAG_NONCE, iv->get());
732 break;
733
734 case BlockMode::ECB:
735 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
736 break;
737 }
738
739 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
740 << "Decrypt begin() failed for block mode " << block_mode;
741
742 string plaintext;
743 for (size_t i = 0; i < ciphertext.size(); i += increment) {
744 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
745 }
746 ErrorCode error = Finish(to_send, &plaintext);
747 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
748 << " and increment " << increment;
749 if (error == ErrorCode::OK) {
750 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
751 << " and increment " << increment;
752 }
753 }
754}
755
Prashant Patildd5f7f02022-07-06 18:58:07 +0000756void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
757 PaddingMode padding_mode, const string& iv,
758 const string& plaintext,
759 const string& exp_cipher_text) {
760 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
761 auto auth_set = AuthorizationSetBuilder()
762 .Authorization(TAG_NO_AUTH_REQUIRED)
763 .AesEncryptionKey(key.size() * 8)
764 .BlockMode(block_mode)
765 .Padding(padding_mode);
766 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
767 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
768 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
769
770 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
771 exp_cipher_text);
772}
773
774void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
775 PaddingMode padding_mode, const string& iv,
776 const string& plaintext,
777 const string& exp_cipher_text) {
778 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
779 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
780 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
781 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
782 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
783
784 AuthorizationSet output_params;
785 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
786
787 string actual_ciphertext;
788 if (is_stream_cipher) {
789 // Assert that a 1 byte of output is produced for 1 byte of input.
790 // Every input byte produces an output byte.
791 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
792 string ciphertext;
793 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
794 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
795 // we relax this API restriction for them.
796 if (SecLevel() != SecurityLevel::STRONGBOX) {
797 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
798 }
799 actual_ciphertext.append(ciphertext);
800 }
801 string ciphertext;
802 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
803 if (SecLevel() != SecurityLevel::STRONGBOX) {
804 string expected_final_output;
805 if (is_authenticated_cipher) {
806 expected_final_output = exp_cipher_text.substr(plaintext.size());
807 }
808 EXPECT_EQ(expected_final_output, ciphertext);
809 }
810 actual_ciphertext.append(ciphertext);
811 } else {
812 // Assert that a block of output is produced once a full block of input is provided.
813 // Every input block produces an output block.
814 bool compare_output = true;
815 string additional_information;
816 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
817 if (SecLevel() == SecurityLevel::STRONGBOX) {
818 // This is known to be broken on older vendor implementations.
819 if (vendor_api_level < 33) {
820 compare_output = false;
821 } else {
822 additional_information = " (b/194134359) ";
823 }
824 }
825 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
826 string ciphertext;
827 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
828 if (compare_output) {
829 if ((plaintext_index % block_size) == block_size - 1) {
830 // Update is expected to have output a new block
831 EXPECT_EQ(block_size, ciphertext.size())
832 << "plaintext index: " << plaintext_index << additional_information;
833 } else {
834 // Update is expected to have produced no output
835 EXPECT_EQ(0, ciphertext.size())
836 << "plaintext index: " << plaintext_index << additional_information;
837 }
838 }
839 actual_ciphertext.append(ciphertext);
840 }
841 string ciphertext;
842 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
843 actual_ciphertext.append(ciphertext);
844 }
845 // Regardless of how the completed ciphertext got accumulated, it should match the expected
846 // ciphertext.
847 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
848}
849
Selene Huang31ab4042020-04-29 04:22:39 -0700850void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
851 Digest digest, const string& expected_mac) {
852 SCOPED_TRACE("CheckHmacTestVector");
853 ASSERT_EQ(ErrorCode::OK,
854 ImportKey(AuthorizationSetBuilder()
855 .Authorization(TAG_NO_AUTH_REQUIRED)
856 .HmacKey(key.size() * 8)
857 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
858 .Digest(digest),
859 KeyFormat::RAW, key));
860 string signature = MacMessage(message, digest, expected_mac.size() * 8);
861 EXPECT_EQ(expected_mac, signature)
862 << "Test vector didn't match for key of size " << key.size() << " message of size "
863 << message.size() << " and digest " << digest;
864 CheckedDeleteKey();
865}
866
867void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
868 const string& message,
869 const string& expected_ciphertext) {
870 SCOPED_TRACE("CheckAesCtrTestVector");
871 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
872 .Authorization(TAG_NO_AUTH_REQUIRED)
873 .AesEncryptionKey(key.size() * 8)
874 .BlockMode(BlockMode::CTR)
875 .Authorization(TAG_CALLER_NONCE)
876 .Padding(PaddingMode::NONE),
877 KeyFormat::RAW, key));
878
879 auto params = AuthorizationSetBuilder()
880 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
881 .BlockMode(BlockMode::CTR)
882 .Padding(PaddingMode::NONE);
883 AuthorizationSet out_params;
884 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
885 EXPECT_EQ(expected_ciphertext, ciphertext);
886}
887
888void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
889 PaddingMode padding_mode, const string& key,
890 const string& iv, const string& input,
891 const string& expected_output) {
892 auto authset = AuthorizationSetBuilder()
893 .TripleDesEncryptionKey(key.size() * 7)
894 .BlockMode(block_mode)
895 .Authorization(TAG_NO_AUTH_REQUIRED)
896 .Padding(padding_mode);
897 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
898 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
899 ASSERT_GT(key_blob_.size(), 0U);
900
901 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
902 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
903 AuthorizationSet output_params;
904 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
905 EXPECT_EQ(expected_output, output);
906}
907
908void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
909 const string& signature, const AuthorizationSet& params) {
910 SCOPED_TRACE("VerifyMessage");
911 AuthorizationSet begin_out_params;
912 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
913
914 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700915 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700916 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700917 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700918}
919
920void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
921 const AuthorizationSet& params) {
922 SCOPED_TRACE("VerifyMessage");
923 VerifyMessage(key_blob_, message, signature, params);
924}
925
David Drysdaledf8f52e2021-05-06 08:10:58 +0100926void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
927 const AuthorizationSet& params) {
928 SCOPED_TRACE("LocalVerifyMessage");
929
David Drysdaledf8f52e2021-05-06 08:10:58 +0100930 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000931 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
932}
933
934void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
935 const string& signature,
936 const AuthorizationSet& params) {
937 // Retrieve the public key from the leaf certificate.
938 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100939 ASSERT_TRUE(key_cert.get());
940 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
941 ASSERT_TRUE(pub_key.get());
942
943 Digest digest = params.GetTagValue(TAG_DIGEST).value();
944 PaddingMode padding = PaddingMode::NONE;
945 auto tag = params.GetTagValue(TAG_PADDING);
946 if (tag.has_value()) {
947 padding = tag.value();
948 }
949
950 if (digest == Digest::NONE) {
951 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100952 case EVP_PKEY_ED25519: {
953 ASSERT_EQ(64, signature.size());
954 uint8_t pub_keydata[32];
955 size_t pub_len = sizeof(pub_keydata);
956 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
957 ASSERT_EQ(sizeof(pub_keydata), pub_len);
958 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
959 message.size(),
960 reinterpret_cast<const uint8_t*>(signature.data()),
961 pub_keydata));
962 break;
963 }
964
David Drysdaledf8f52e2021-05-06 08:10:58 +0100965 case EVP_PKEY_EC: {
966 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
967 size_t data_size = std::min(data.size(), message.size());
968 memcpy(data.data(), message.data(), data_size);
969 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
970 ASSERT_TRUE(ecdsa.get());
971 ASSERT_EQ(1,
972 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
973 reinterpret_cast<const uint8_t*>(signature.data()),
974 signature.size(), ecdsa.get()));
975 break;
976 }
977 case EVP_PKEY_RSA: {
978 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
979 size_t data_size = std::min(data.size(), message.size());
980 memcpy(data.data(), message.data(), data_size);
981
982 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
983 ASSERT_TRUE(rsa.get());
984
985 size_t key_len = RSA_size(rsa.get());
986 int openssl_padding = RSA_NO_PADDING;
987 switch (padding) {
988 case PaddingMode::NONE:
989 ASSERT_TRUE(data_size <= key_len);
990 ASSERT_EQ(key_len, signature.size());
991 openssl_padding = RSA_NO_PADDING;
992 break;
993 case PaddingMode::RSA_PKCS1_1_5_SIGN:
994 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
995 key_len);
996 openssl_padding = RSA_PKCS1_PADDING;
997 break;
998 default:
999 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1000 }
1001
1002 vector<uint8_t> decrypted_data(key_len);
1003 int bytes_decrypted = RSA_public_decrypt(
1004 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1005 decrypted_data.data(), rsa.get(), openssl_padding);
1006 ASSERT_GE(bytes_decrypted, 0);
1007
1008 const uint8_t* compare_pos = decrypted_data.data();
1009 size_t bytes_to_compare = bytes_decrypted;
1010 uint8_t zero_check_result = 0;
1011 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1012 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1013 // during verification we should have zeros on the left of the decrypted data.
1014 // Do a constant-time check.
1015 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1016 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1017 ASSERT_EQ(0, zero_check_result);
1018 bytes_to_compare = data_size;
1019 }
1020 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1021 break;
1022 }
1023 default:
1024 ADD_FAILURE() << "Unknown public key type";
1025 }
1026 } else {
1027 EVP_MD_CTX digest_ctx;
1028 EVP_MD_CTX_init(&digest_ctx);
1029 EVP_PKEY_CTX* pkey_ctx;
1030 const EVP_MD* md = openssl_digest(digest);
1031 ASSERT_NE(md, nullptr);
1032 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1033
1034 if (padding == PaddingMode::RSA_PSS) {
1035 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1036 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001037 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001038 }
1039
1040 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1041 reinterpret_cast<const uint8_t*>(message.data()),
1042 message.size()));
1043 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1044 reinterpret_cast<const uint8_t*>(signature.data()),
1045 signature.size()));
1046 EVP_MD_CTX_cleanup(&digest_ctx);
1047 }
1048}
1049
David Drysdale59cae642021-05-12 13:52:03 +01001050string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1051 const AuthorizationSet& params) {
1052 SCOPED_TRACE("LocalRsaEncryptMessage");
1053
1054 // Retrieve the public key from the leaf certificate.
1055 if (cert_chain_.empty()) {
1056 ADD_FAILURE() << "No public key available";
1057 return "Failure";
1058 }
1059 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001060 if (key_cert.get() == nullptr) {
1061 ADD_FAILURE() << "Failed to parse cert";
1062 return "Failure";
1063 }
David Drysdale59cae642021-05-12 13:52:03 +01001064 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001065 if (pub_key.get() == nullptr) {
1066 ADD_FAILURE() << "Failed to retrieve public key";
1067 return "Failure";
1068 }
David Drysdale59cae642021-05-12 13:52:03 +01001069 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001070 if (rsa.get() == nullptr) {
1071 ADD_FAILURE() << "Failed to retrieve RSA public key";
1072 return "Failure";
1073 }
David Drysdale59cae642021-05-12 13:52:03 +01001074
1075 // Retrieve relevant tags.
1076 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001077 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001078 PaddingMode padding = PaddingMode::NONE;
1079
1080 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1081 if (digest_tag.has_value()) digest = digest_tag.value();
1082 auto pad_tag = params.GetTagValue(TAG_PADDING);
1083 if (pad_tag.has_value()) padding = pad_tag.value();
1084 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1085 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1086
1087 const EVP_MD* md = openssl_digest(digest);
1088 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1089
1090 // Set up encryption context.
1091 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1092 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1093 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1094 return "Failure";
1095 }
1096
1097 int rc = -1;
1098 switch (padding) {
1099 case PaddingMode::NONE:
1100 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1101 break;
1102 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1103 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1104 break;
1105 case PaddingMode::RSA_OAEP:
1106 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1107 break;
1108 default:
1109 break;
1110 }
1111 if (rc <= 0) {
1112 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1113 return "Failure";
1114 }
1115 if (padding == PaddingMode::RSA_OAEP) {
1116 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1117 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1118 return "Failure";
1119 }
1120 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1121 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1122 return "Failure";
1123 }
1124 }
1125
1126 // Determine output size.
1127 size_t outlen;
1128 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1129 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1130 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1131 return "Failure";
1132 }
1133
1134 // Left-zero-pad the input if necessary.
1135 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1136 size_t to_encrypt_len = message.size();
1137
1138 std::unique_ptr<string> zero_padded_message;
1139 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1140 zero_padded_message.reset(new string(outlen, '\0'));
1141 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1142 message.size());
1143 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1144 to_encrypt_len = outlen;
1145 }
1146
1147 // Do the encryption.
1148 string output(outlen, '\0');
1149 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1150 to_encrypt_len) <= 0) {
1151 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1152 return "Failure";
1153 }
1154 return output;
1155}
1156
Selene Huang31ab4042020-04-29 04:22:39 -07001157string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1158 const AuthorizationSet& in_params,
1159 AuthorizationSet* out_params) {
1160 SCOPED_TRACE("EncryptMessage");
1161 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1162}
1163
1164string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1165 AuthorizationSet* out_params) {
1166 SCOPED_TRACE("EncryptMessage");
1167 return EncryptMessage(key_blob_, message, params, out_params);
1168}
1169
1170string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1171 SCOPED_TRACE("EncryptMessage");
1172 AuthorizationSet out_params;
1173 string ciphertext = EncryptMessage(message, params, &out_params);
1174 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1175 return ciphertext;
1176}
1177
1178string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1179 PaddingMode padding) {
1180 SCOPED_TRACE("EncryptMessage");
1181 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1182 AuthorizationSet out_params;
1183 string ciphertext = EncryptMessage(message, params, &out_params);
1184 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1185 return ciphertext;
1186}
1187
1188string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1189 PaddingMode padding, vector<uint8_t>* iv_out) {
1190 SCOPED_TRACE("EncryptMessage");
1191 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1192 AuthorizationSet out_params;
1193 string ciphertext = EncryptMessage(message, params, &out_params);
1194 EXPECT_EQ(1U, out_params.size());
1195 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001196 EXPECT_TRUE(ivVal);
1197 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001198 return ciphertext;
1199}
1200
1201string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1202 PaddingMode padding, const vector<uint8_t>& iv_in) {
1203 SCOPED_TRACE("EncryptMessage");
1204 auto params = AuthorizationSetBuilder()
1205 .BlockMode(block_mode)
1206 .Padding(padding)
1207 .Authorization(TAG_NONCE, iv_in);
1208 AuthorizationSet out_params;
1209 string ciphertext = EncryptMessage(message, params, &out_params);
1210 return ciphertext;
1211}
1212
1213string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1214 PaddingMode padding, uint8_t mac_length_bits,
1215 const vector<uint8_t>& iv_in) {
1216 SCOPED_TRACE("EncryptMessage");
1217 auto params = AuthorizationSetBuilder()
1218 .BlockMode(block_mode)
1219 .Padding(padding)
1220 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1221 .Authorization(TAG_NONCE, iv_in);
1222 AuthorizationSet out_params;
1223 string ciphertext = EncryptMessage(message, params, &out_params);
1224 return ciphertext;
1225}
1226
David Drysdaled2cc8c22021-04-15 13:29:45 +01001227string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1228 PaddingMode padding, uint8_t mac_length_bits) {
1229 SCOPED_TRACE("EncryptMessage");
1230 auto params = AuthorizationSetBuilder()
1231 .BlockMode(block_mode)
1232 .Padding(padding)
1233 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1234 AuthorizationSet out_params;
1235 string ciphertext = EncryptMessage(message, params, &out_params);
1236 return ciphertext;
1237}
1238
Selene Huang31ab4042020-04-29 04:22:39 -07001239string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1240 const string& ciphertext,
1241 const AuthorizationSet& params) {
1242 SCOPED_TRACE("DecryptMessage");
1243 AuthorizationSet out_params;
1244 string plaintext =
1245 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1246 EXPECT_TRUE(out_params.empty());
1247 return plaintext;
1248}
1249
1250string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1251 const AuthorizationSet& params) {
1252 SCOPED_TRACE("DecryptMessage");
1253 return DecryptMessage(key_blob_, ciphertext, params);
1254}
1255
1256string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1257 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1258 SCOPED_TRACE("DecryptMessage");
1259 auto params = AuthorizationSetBuilder()
1260 .BlockMode(block_mode)
1261 .Padding(padding_mode)
1262 .Authorization(TAG_NONCE, iv);
1263 return DecryptMessage(key_blob_, ciphertext, params);
1264}
1265
1266std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1267 const vector<uint8_t>& key_blob) {
1268 std::pair<ErrorCode, vector<uint8_t>> retval;
1269 vector<uint8_t> outKeyBlob;
1270 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1271 ErrorCode errorcode = GetReturnErrorCode(result);
1272 retval = std::tie(errorcode, outKeyBlob);
1273
1274 return retval;
1275}
1276vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1277 switch (algorithm) {
1278 case Algorithm::RSA:
1279 switch (SecLevel()) {
1280 case SecurityLevel::SOFTWARE:
1281 case SecurityLevel::TRUSTED_ENVIRONMENT:
1282 return {2048, 3072, 4096};
1283 case SecurityLevel::STRONGBOX:
1284 return {2048};
1285 default:
1286 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1287 break;
1288 }
1289 break;
1290 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001291 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001292 break;
1293 case Algorithm::AES:
1294 return {128, 256};
1295 case Algorithm::TRIPLE_DES:
1296 return {168};
1297 case Algorithm::HMAC: {
1298 vector<uint32_t> retval((512 - 64) / 8 + 1);
1299 uint32_t size = 64 - 8;
1300 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1301 return retval;
1302 }
1303 default:
1304 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1305 return {};
1306 }
1307 ADD_FAILURE() << "Should be impossible to get here";
1308 return {};
1309}
1310
1311vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1312 if (SecLevel() == SecurityLevel::STRONGBOX) {
1313 switch (algorithm) {
1314 case Algorithm::RSA:
1315 return {3072, 4096};
1316 case Algorithm::EC:
1317 return {224, 384, 521};
1318 case Algorithm::AES:
1319 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001320 case Algorithm::TRIPLE_DES:
1321 return {56};
1322 default:
1323 return {};
1324 }
1325 } else {
1326 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001327 case Algorithm::AES:
1328 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001329 case Algorithm::TRIPLE_DES:
1330 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001331 default:
1332 return {};
1333 }
1334 }
1335 return {};
1336}
1337
David Drysdale7de9feb2021-03-05 14:56:19 +00001338vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1339 switch (algorithm) {
1340 case Algorithm::AES:
1341 return {
1342 BlockMode::CBC,
1343 BlockMode::CTR,
1344 BlockMode::ECB,
1345 BlockMode::GCM,
1346 };
1347 case Algorithm::TRIPLE_DES:
1348 return {
1349 BlockMode::CBC,
1350 BlockMode::ECB,
1351 };
1352 default:
1353 return {};
1354 }
1355}
1356
1357vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1358 BlockMode blockMode) {
1359 switch (algorithm) {
1360 case Algorithm::AES:
1361 switch (blockMode) {
1362 case BlockMode::CBC:
1363 case BlockMode::ECB:
1364 return {PaddingMode::NONE, PaddingMode::PKCS7};
1365 case BlockMode::CTR:
1366 case BlockMode::GCM:
1367 return {PaddingMode::NONE};
1368 default:
1369 return {};
1370 };
1371 case Algorithm::TRIPLE_DES:
1372 switch (blockMode) {
1373 case BlockMode::CBC:
1374 case BlockMode::ECB:
1375 return {PaddingMode::NONE, PaddingMode::PKCS7};
1376 default:
1377 return {};
1378 };
1379 default:
1380 return {};
1381 }
1382}
1383
1384vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1385 BlockMode blockMode) {
1386 switch (algorithm) {
1387 case Algorithm::AES:
1388 switch (blockMode) {
1389 case BlockMode::CTR:
1390 case BlockMode::GCM:
1391 return {PaddingMode::PKCS7};
1392 default:
1393 return {};
1394 };
1395 default:
1396 return {};
1397 }
1398}
1399
Selene Huang31ab4042020-04-29 04:22:39 -07001400vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1401 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1402 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001403 } else if (Curve25519Supported()) {
1404 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1405 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001406 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001407 return {
1408 EcCurve::P_224,
1409 EcCurve::P_256,
1410 EcCurve::P_384,
1411 EcCurve::P_521,
1412 };
Selene Huang31ab4042020-04-29 04:22:39 -07001413 }
1414}
1415
1416vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001417 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001418 // Curve 25519 is not supported, either because:
1419 // - KeyMint v1: it's an unknown enum value
1420 // - KeyMint v2+: it's not supported by StrongBox.
1421 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001422 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001423 if (Curve25519Supported()) {
1424 return {};
1425 } else {
1426 return {EcCurve::CURVE_25519};
1427 }
David Drysdaledf09e542021-06-08 15:46:11 +01001428 }
Selene Huang31ab4042020-04-29 04:22:39 -07001429}
1430
subrahmanyaman05642492022-02-05 07:10:56 +00001431vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1432 if (SecLevel() == SecurityLevel::STRONGBOX) {
1433 return {65537};
1434 } else {
1435 return {3, 65537};
1436 }
1437}
1438
Selene Huang31ab4042020-04-29 04:22:39 -07001439vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1440 switch (SecLevel()) {
1441 case SecurityLevel::SOFTWARE:
1442 case SecurityLevel::TRUSTED_ENVIRONMENT:
1443 if (withNone) {
1444 if (withMD5)
1445 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1446 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1447 Digest::SHA_2_512};
1448 else
1449 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1450 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1451 } else {
1452 if (withMD5)
1453 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1454 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1455 else
1456 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1457 Digest::SHA_2_512};
1458 }
1459 break;
1460 case SecurityLevel::STRONGBOX:
1461 if (withNone)
1462 return {Digest::NONE, Digest::SHA_2_256};
1463 else
1464 return {Digest::SHA_2_256};
1465 break;
1466 default:
1467 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1468 break;
1469 }
1470 ADD_FAILURE() << "Should be impossible to get here";
1471 return {};
1472}
1473
Shawn Willden7f424372021-01-10 18:06:50 -07001474static const vector<KeyParameter> kEmptyAuthList{};
1475
1476const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1477 const vector<KeyCharacteristics>& key_characteristics) {
1478 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1479 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1480 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1481}
1482
Qi Wubeefae42021-01-28 23:16:37 +08001483const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1484 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1485 auto found = std::find_if(
1486 key_characteristics.begin(), key_characteristics.end(),
1487 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001488 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1489}
1490
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001491ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001492 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001493 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1494 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1495 return result;
1496}
1497
1498ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001499 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001500 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1501 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1502 return result;
1503}
1504
1505ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1506 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001507 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001508 rsaKeyBlob, KeyPurpose::SIGN, message,
1509 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1510 return result;
1511}
1512
1513ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001514 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1515 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001516 return result;
1517}
1518
Selene Huang6e46f142021-04-20 19:20:11 -07001519void verify_serial(X509* cert, const uint64_t expected_serial) {
1520 BIGNUM_Ptr ser(BN_new());
1521 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1522
1523 uint64_t serial;
1524 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1525 EXPECT_EQ(serial, expected_serial);
1526}
1527
1528// Please set self_signed to true for fake certificates or self signed
1529// certificates
1530void verify_subject(const X509* cert, //
1531 const string& subject, //
1532 bool self_signed) {
1533 char* cert_issuer = //
1534 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1535
1536 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1537
1538 string expected_subject("/CN=");
1539 if (subject.empty()) {
1540 expected_subject.append("Android Keystore Key");
1541 } else {
1542 expected_subject.append(subject);
1543 }
1544
1545 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1546
1547 if (self_signed) {
1548 EXPECT_STREQ(cert_issuer, cert_subj)
1549 << "Cert issuer and subject mismatch for self signed certificate.";
1550 }
1551
1552 OPENSSL_free(cert_subj);
1553 OPENSSL_free(cert_issuer);
1554}
1555
Shawn Willden22fb9c12022-06-02 14:04:33 -06001556int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001557 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1558 if (vendor_api_level != -1) {
1559 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001560 }
Shawn Willden35db3492022-06-16 12:50:40 -06001561
1562 // Android S and older devices do not define ro.vendor.api_level
1563 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1564 if (vendor_api_level == -1) {
1565 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001566 }
Shawn Willden35db3492022-06-16 12:50:40 -06001567
1568 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1569 if (product_api_level == -1) {
1570 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1571 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001572 }
Shawn Willden35db3492022-06-16 12:50:40 -06001573
1574 // VSR API level is the minimum of vendor_api_level and product_api_level.
1575 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1576 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001577 }
Shawn Willden35db3492022-06-16 12:50:40 -06001578 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001579}
1580
David Drysdale555ba002022-05-03 18:48:57 +01001581bool is_gsi_image() {
1582 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1583 return ifs.good();
1584}
1585
Selene Huang6e46f142021-04-20 19:20:11 -07001586vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1587 BIGNUM_Ptr serial(BN_new());
1588 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1589
1590 int len = BN_num_bytes(serial.get());
1591 vector<uint8_t> serial_blob(len);
1592 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1593 return {};
1594 }
1595
David Drysdaledb0dcf52021-05-18 11:43:31 +01001596 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1597 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1598 // Top bit being set indicates a negative number in two's complement, but our input
1599 // was positive.
1600 // In either case, prepend a zero byte.
1601 serial_blob.insert(serial_blob.begin(), 0x00);
1602 }
1603
Selene Huang6e46f142021-04-20 19:20:11 -07001604 return serial_blob;
1605}
1606
1607void verify_subject_and_serial(const Certificate& certificate, //
1608 const uint64_t expected_serial, //
1609 const string& subject, bool self_signed) {
1610 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1611 ASSERT_TRUE(!!cert.get());
1612
1613 verify_serial(cert.get(), expected_serial);
1614 verify_subject(cert.get(), subject, self_signed);
1615}
1616
Shawn Willden4315e132022-03-20 12:49:46 -06001617void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1618 VerifiedBoot verified_boot_state,
1619 const vector<uint8_t>& verified_boot_hash) {
1620 char property_value[PROPERTY_VALUE_MAX] = {};
1621
1622 if (avb_verification_enabled()) {
1623 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1624 string prop_string(property_value);
1625 EXPECT_EQ(prop_string.size(), 64);
1626 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1627
1628 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1629 if (!strcmp(property_value, "unlocked")) {
1630 EXPECT_FALSE(device_locked);
1631 } else {
1632 EXPECT_TRUE(device_locked);
1633 }
1634
1635 // Check that the device is locked if not debuggable, e.g., user build
1636 // images in CTS. For VTS, debuggable images are used to allow adb root
1637 // and the device is unlocked.
1638 if (!property_get_bool("ro.debuggable", false)) {
1639 EXPECT_TRUE(device_locked);
1640 } else {
1641 EXPECT_FALSE(device_locked);
1642 }
1643 }
1644
1645 // Verified boot key should be all 0's if the boot state is not verified or self signed
1646 std::string empty_boot_key(32, '\0');
1647 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1648 verified_boot_key.size());
1649 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1650 if (!strcmp(property_value, "green")) {
1651 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1652 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1653 verified_boot_key.size()));
1654 } else if (!strcmp(property_value, "yellow")) {
1655 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1656 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1657 verified_boot_key.size()));
1658 } else if (!strcmp(property_value, "orange")) {
1659 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1660 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1661 verified_boot_key.size()));
1662 } else if (!strcmp(property_value, "red")) {
1663 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1664 } else {
1665 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1666 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1667 verified_boot_key.size()));
1668 }
1669}
1670
David Drysdale7dff4fc2021-12-10 10:10:52 +00001671bool verify_attestation_record(int32_t aidl_version, //
1672 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001673 const string& app_id, //
1674 AuthorizationSet expected_sw_enforced, //
1675 AuthorizationSet expected_hw_enforced, //
1676 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001677 const vector<uint8_t>& attestation_cert,
1678 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001679 X509_Ptr cert(parse_cert_blob(attestation_cert));
1680 EXPECT_TRUE(!!cert.get());
1681 if (!cert.get()) return false;
1682
1683 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1684 EXPECT_TRUE(!!attest_rec);
1685 if (!attest_rec) return false;
1686
1687 AuthorizationSet att_sw_enforced;
1688 AuthorizationSet att_hw_enforced;
1689 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001690 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001691 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001692 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001693 vector<uint8_t> att_challenge;
1694 vector<uint8_t> att_unique_id;
1695 vector<uint8_t> att_app_id;
1696
1697 auto error = parse_attestation_record(attest_rec->data, //
1698 attest_rec->length, //
1699 &att_attestation_version, //
1700 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001701 &att_keymint_version, //
1702 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001703 &att_challenge, //
1704 &att_sw_enforced, //
1705 &att_hw_enforced, //
1706 &att_unique_id);
1707 EXPECT_EQ(ErrorCode::OK, error);
1708 if (error != ErrorCode::OK) return false;
1709
David Drysdale7dff4fc2021-12-10 10:10:52 +00001710 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001711 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001712
Selene Huang4f64c222021-04-13 19:54:36 -07001713 // check challenge and app id only if we expects a non-fake certificate
1714 if (challenge.length() > 0) {
1715 EXPECT_EQ(challenge.length(), att_challenge.size());
1716 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1717
1718 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1719 }
Shawn Willden7c130392020-12-21 09:58:22 -07001720
David Drysdale7dff4fc2021-12-10 10:10:52 +00001721 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001722 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001723 EXPECT_EQ(security_level, att_attestation_security_level);
1724
Shawn Willden7c130392020-12-21 09:58:22 -07001725 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001726 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001727 // for the BOOT_PATCH_LEVEL.
1728 if (avb_verification_enabled()) {
1729 for (int i = 0; i < att_hw_enforced.size(); i++) {
1730 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1731 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1732 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001733 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001734
Shawn Willden7c130392020-12-21 09:58:22 -07001735 // strptime seems to require delimiters, but the tag value will
1736 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001737 if (date.size() != 8) {
1738 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1739 << " with invalid format (not YYYYMMDD): " << date;
1740 return false;
1741 }
Shawn Willden7c130392020-12-21 09:58:22 -07001742 date.insert(6, "-");
1743 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001744 struct tm time;
1745 strptime(date.c_str(), "%Y-%m-%d", &time);
1746
1747 // Day of the month (0-31)
1748 EXPECT_GE(time.tm_mday, 0);
1749 EXPECT_LT(time.tm_mday, 32);
1750 // Months since Jan (0-11)
1751 EXPECT_GE(time.tm_mon, 0);
1752 EXPECT_LT(time.tm_mon, 12);
1753 // Years since 1900
1754 EXPECT_GT(time.tm_year, 110);
1755 EXPECT_LT(time.tm_year, 200);
1756 }
1757 }
1758 }
1759
1760 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1761 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1762 // indicates correct encoding. No need to check if it's in both lists, since the
1763 // AuthorizationSet compare below will handle mismatches of tags.
1764 if (security_level == SecurityLevel::SOFTWARE) {
1765 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1766 } else {
1767 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1768 }
1769
Shawn Willden7c130392020-12-21 09:58:22 -07001770 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1771 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1772 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1773 att_hw_enforced.Contains(TAG_KEY_SIZE));
1774 }
1775
1776 // Test root of trust elements
1777 vector<uint8_t> verified_boot_key;
1778 VerifiedBoot verified_boot_state;
1779 bool device_locked;
1780 vector<uint8_t> verified_boot_hash;
1781 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1782 &verified_boot_state, &device_locked, &verified_boot_hash);
1783 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001784 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001785
1786 att_sw_enforced.Sort();
1787 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001788 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001789
1790 att_hw_enforced.Sort();
1791 expected_hw_enforced.Sort();
1792 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1793
David Drysdale565ccc72021-10-11 12:49:50 +01001794 if (unique_id != nullptr) {
1795 *unique_id = att_unique_id;
1796 }
1797
Shawn Willden7c130392020-12-21 09:58:22 -07001798 return true;
1799}
1800
1801string bin2hex(const vector<uint8_t>& data) {
1802 string retval;
1803 retval.reserve(data.size() * 2 + 1);
1804 for (uint8_t byte : data) {
1805 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1806 retval.push_back(nibble2hex[0x0F & byte]);
1807 }
1808 return retval;
1809}
1810
David Drysdalef0d516d2021-03-22 07:51:43 +00001811AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1812 AuthorizationSet authList;
1813 for (auto& entry : key_characteristics) {
1814 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1815 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1816 authList.push_back(AuthorizationSet(entry.authorizations));
1817 }
1818 }
1819 return authList;
1820}
1821
1822AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1823 AuthorizationSet authList;
1824 for (auto& entry : key_characteristics) {
1825 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1826 entry.securityLevel == SecurityLevel::KEYSTORE) {
1827 authList.push_back(AuthorizationSet(entry.authorizations));
1828 }
1829 }
1830 return authList;
1831}
1832
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001833AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1834 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001835 std::stringstream cert_data;
1836
1837 for (size_t i = 0; i < chain.size(); ++i) {
1838 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1839
1840 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1841 X509_Ptr signing_cert;
1842 if (i < chain.size() - 1) {
1843 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1844 } else {
1845 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1846 }
1847 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1848
1849 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1850 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1851
1852 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1853 return AssertionFailure()
1854 << "Verification of certificate " << i << " failed "
1855 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1856 << cert_data.str();
1857 }
1858
1859 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1860 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001861 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001862 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1863 << " Signer subject is " << signer_subj
1864 << " Issuer subject is " << cert_issuer << endl
1865 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001866 }
Shawn Willden7c130392020-12-21 09:58:22 -07001867 }
1868
1869 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1870 return AssertionSuccess();
1871}
1872
1873X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1874 const uint8_t* p = blob.data();
1875 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1876}
1877
Tri Voec50ee12023-02-14 16:29:53 -08001878// Extract attestation record from cert. Returned object is still part of cert; don't free it
1879// separately.
1880ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
1881 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
1882 EXPECT_TRUE(!!oid.get());
1883 if (!oid.get()) return nullptr;
1884
1885 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
1886 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
1887 if (location == -1) return nullptr;
1888
1889 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
1890 EXPECT_TRUE(!!attest_rec_ext)
1891 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
1892 if (!attest_rec_ext) return nullptr;
1893
1894 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
1895 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
1896 return attest_rec;
1897}
1898
David Drysdalef0d516d2021-03-22 07:51:43 +00001899vector<uint8_t> make_name_from_str(const string& name) {
1900 X509_NAME_Ptr x509_name(X509_NAME_new());
1901 EXPECT_TRUE(x509_name.get() != nullptr);
1902 if (!x509_name) return {};
1903
1904 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1905 "CN", //
1906 MBSTRING_ASC,
1907 reinterpret_cast<const uint8_t*>(name.c_str()),
1908 -1, // len
1909 -1, // loc
1910 0 /* set */));
1911
1912 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1913 EXPECT_GT(len, 0);
1914
1915 vector<uint8_t> retval(len);
1916 uint8_t* p = retval.data();
1917 i2d_X509_NAME(x509_name.get(), &p);
1918
1919 return retval;
1920}
1921
David Drysdale4dc01072021-04-01 12:17:35 +01001922namespace {
1923
1924void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1925 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1926 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1927
1928 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1929 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001930 EXPECT_THAT(
1931 cppbor::prettyPrint(parsedPayload.get()),
1932 MatchesRegex("\\{\n"
1933 " 1 : 2,\n" // kty: EC2
1934 " 3 : -7,\n" // alg: ES256
1935 " -1 : 1,\n" // EC id: P256
1936 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1937 // sequence of 32 hexadecimal bytes, enclosed in braces and
1938 // separated by commas. In this case, some Ed25519 public key.
1939 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1940 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1941 " -70000 : null,\n" // test marker
1942 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001943 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001944 EXPECT_THAT(
1945 cppbor::prettyPrint(parsedPayload.get()),
1946 MatchesRegex("\\{\n"
1947 " 1 : 2,\n" // kty: EC2
1948 " 3 : -7,\n" // alg: ES256
1949 " -1 : 1,\n" // EC id: P256
1950 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1951 // sequence of 32 hexadecimal bytes, enclosed in braces and
1952 // separated by commas. In this case, some Ed25519 public key.
1953 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1954 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1955 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001956 }
1957}
1958
1959} // namespace
1960
1961void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1962 vector<uint8_t>* payload_value) {
1963 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1964 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1965
1966 ASSERT_NE(coseMac0->asArray(), nullptr);
1967 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1968
1969 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1970 ASSERT_NE(protParms, nullptr);
1971
1972 // Header label:value of 'alg': HMAC-256
1973 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1974
1975 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1976 ASSERT_NE(unprotParms, nullptr);
1977 ASSERT_EQ(unprotParms->size(), 0);
1978
1979 // The payload is a bstr holding an encoded COSE_Key
1980 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1981 ASSERT_NE(payload, nullptr);
1982 check_cose_key(payload->value(), testMode);
1983
1984 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1985 ASSERT_TRUE(coseMac0Tag);
1986 auto extractedTag = coseMac0Tag->value();
1987 EXPECT_EQ(extractedTag.size(), 32U);
1988
1989 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001990 auto macFunction = [](const cppcose::bytevec& input) {
1991 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1992 };
1993 auto testTag =
1994 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001995 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1996
1997 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001998 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001999 } else {
Seth Moore026bb742021-04-30 11:41:18 -07002000 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002001 }
2002 if (payload_value != nullptr) {
2003 *payload_value = payload->value();
2004 }
2005}
2006
2007void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2008 // Extract x and y affine coordinates from the encoded Cose_Key.
2009 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2010 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2011 auto coseKey = parsedPayload->asMap();
2012 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2013 ASSERT_NE(xItem->asBstr(), nullptr);
2014 vector<uint8_t> x = xItem->asBstr()->value();
2015 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2016 ASSERT_NE(yItem->asBstr(), nullptr);
2017 vector<uint8_t> y = yItem->asBstr()->value();
2018
2019 // Concatenate: 0x04 (uncompressed form marker) | x | y
2020 vector<uint8_t> pubKeyData{0x04};
2021 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2022 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2023
2024 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2025 ASSERT_NE(ecKey, nullptr);
2026 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2027 ASSERT_NE(group, nullptr);
2028 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2029 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2030 ASSERT_NE(point, nullptr);
2031 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2032 nullptr),
2033 1);
2034 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2035
2036 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2037 ASSERT_NE(pubKey, nullptr);
2038 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2039 *signingKey = std::move(pubKey);
2040}
2041
Max Biresa97ec692022-11-21 23:37:54 -08002042void device_id_attestation_vsr_check(const ErrorCode& result) {
2043 if (get_vsr_api_level() >= 34) {
2044 ASSERT_FALSE(result == ErrorCode::INVALID_TAG)
2045 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2046 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2047 << "be used for a case where updateAad() is called after update(). As of "
2048 << "VSR-14, this is now enforced as an error.";
2049 }
2050}
2051
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002052// Check whether the given named feature is available.
2053bool check_feature(const std::string& name) {
2054 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002055 ::android::sp<::android::IBinder> binder(
2056 sm->waitForService(::android::String16("package_native")));
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002057 if (binder == nullptr) {
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002058 GTEST_LOG_(ERROR) << "waitForService package_native failed";
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002059 return false;
2060 }
2061 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2062 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2063 if (packageMgr == nullptr) {
2064 GTEST_LOG_(ERROR) << "Cannot find package manager";
2065 return false;
2066 }
2067 bool hasFeature = false;
2068 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2069 if (!status.isOk()) {
2070 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2071 return false;
2072 }
2073 return hasFeature;
2074}
2075
Selene Huang31ab4042020-04-29 04:22:39 -07002076} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002077
Janis Danisevskis24c04702020-12-16 18:28:39 -08002078} // namespace aidl::android::hardware::security::keymint