blob: 02462fce3a6bdacaa9defed6588de69cc2261ada [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>
Shawn Willden7f424372021-01-10 18:06:50 -070020#include <unordered_set>
Selene Huang31ab4042020-04-29 04:22:39 -070021#include <vector>
22
23#include <android-base/logging.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080024#include <android/binder_manager.h>
David Drysdale4dc01072021-04-01 12:17:35 +010025#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070026#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010027#include <gmock/gmock.h>
Shawn Willden7c130392020-12-21 09:58:22 -070028#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010029#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
Max Bires9704ff62021-04-07 11:12:01 -070031#include <keymaster/cppcose/cppcose.h>
Shawn Willden7c130392020-12-21 09:58:22 -070032#include <keymint_support/attestation_record.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000033#include <keymint_support/key_param_output.h>
34#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070035#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Janis Danisevskis24c04702020-12-16 18:28:39 -080037namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070038
David Drysdale4dc01072021-04-01 12:17:35 +010039using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070040using namespace std::literals::chrono_literals;
41using std::endl;
42using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070043using std::unique_ptr;
44using ::testing::AssertionFailure;
45using ::testing::AssertionResult;
46using ::testing::AssertionSuccess;
Seth Moore026bb742021-04-30 11:41:18 -070047using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010048using ::testing::MatchesRegex;
Seth Moore026bb742021-04-30 11:41:18 -070049using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
52 if (set.size() == 0)
53 os << "(Empty)" << ::std::endl;
54 else {
55 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070056 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070057 }
58 return os;
59}
60
61namespace test {
62
Shawn Willden7f424372021-01-10 18:06:50 -070063namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010064
David Drysdale37af4b32021-05-14 16:46:59 +010065// Invalid value for a patchlevel (which is of form YYYYMMDD).
66const uint32_t kInvalidPatchlevel = 99998877;
67
David Drysdaledf8f52e2021-05-06 08:10:58 +010068// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
69// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
70const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
71
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000072typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070073// Predicate for testing basic characteristics validity in generation or import.
74bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
75 const vector<KeyCharacteristics>& key_characteristics) {
76 if (key_characteristics.empty()) return false;
77
78 std::unordered_set<SecurityLevel> levels_seen;
79 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070080 if (entry.authorizations.empty()) {
81 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
82 return false;
83 }
Shawn Willden7f424372021-01-10 18:06:50 -070084
Qi Wubeefae42021-01-28 23:16:37 +080085 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
86 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
87
Seth Moore2a9a00e2021-08-04 16:31:52 -070088 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
89 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
90 return false;
91 }
Shawn Willden7f424372021-01-10 18:06:50 -070092 levels_seen.insert(entry.securityLevel);
93
94 // Generally, we should only have one entry, at the same security level as the KM
95 // instance. There is an exception: StrongBox KM can have some authorizations that are
96 // enforced by the TEE.
97 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
98 (secLevel == SecurityLevel::STRONGBOX &&
99 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
100
Seth Moore2a9a00e2021-08-04 16:31:52 -0700101 if (!isExpectedSecurityLevel) {
102 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
103 return false;
104 }
Shawn Willden7f424372021-01-10 18:06:50 -0700105 }
106 return true;
107}
108
Shawn Willden7c130392020-12-21 09:58:22 -0700109// Extract attestation record from cert. Returned object is still part of cert; don't free it
110// separately.
111ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
112 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
113 EXPECT_TRUE(!!oid.get());
114 if (!oid.get()) return nullptr;
115
116 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
117 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
118 if (location == -1) return nullptr;
119
120 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
121 EXPECT_TRUE(!!attest_rec_ext)
122 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
123 if (!attest_rec_ext) return nullptr;
124
125 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
126 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
127 return attest_rec;
128}
129
David Drysdale7dff4fc2021-12-10 10:10:52 +0000130void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
131 // Version numbers in attestation extensions should be a multiple of 100.
132 EXPECT_EQ(attestation_version % 100, 0);
133
134 // The multiplier should never be higher than the AIDL version, but can be less
135 // (for example, if the implementation is from an earlier version but the HAL service
136 // uses the default libraries and so reports the current AIDL version).
137 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
138}
139
Shawn Willden7c130392020-12-21 09:58:22 -0700140bool avb_verification_enabled() {
141 char value[PROPERTY_VALUE_MAX];
142 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
143}
144
145char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
146 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
147
148// Attestations don't contain everything in key authorization lists, so we need to filter the key
149// lists to produce the lists that we expect to match the attestations.
150auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100151 Tag::CREATION_DATETIME,
152 Tag::HARDWARE_TYPE,
153 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700154};
155
156AuthorizationSet filtered_tags(const AuthorizationSet& set) {
157 AuthorizationSet filtered;
158 std::remove_copy_if(
159 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
160 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
161 kTagsToFilter.end();
162 });
163 return filtered;
164}
165
David Drysdale300b5552021-05-20 12:05:26 +0100166// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
167void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
168 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
169 [](const auto& entry) {
170 return entry.securityLevel == SecurityLevel::KEYSTORE;
171 }),
172 characteristics->end());
173}
174
Shawn Willden7c130392020-12-21 09:58:22 -0700175string x509NameToStr(X509_NAME* name) {
176 char* s = X509_NAME_oneline(name, nullptr, 0);
177 string retval(s);
178 OPENSSL_free(s);
179 return retval;
180}
181
Shawn Willden7f424372021-01-10 18:06:50 -0700182} // namespace
183
Shawn Willden7c130392020-12-21 09:58:22 -0700184bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
185bool KeyMintAidlTestBase::dump_Attestations = false;
186
David Drysdale37af4b32021-05-14 16:46:59 +0100187uint32_t KeyMintAidlTestBase::boot_patch_level(
188 const vector<KeyCharacteristics>& key_characteristics) {
189 // The boot patchlevel is not available as a property, but should be present
190 // in the key characteristics of any created key.
191 AuthorizationSet allAuths;
192 for (auto& entry : key_characteristics) {
193 allAuths.push_back(AuthorizationSet(entry.authorizations));
194 }
195 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
196 if (patchlevel.has_value()) {
197 return patchlevel.value();
198 } else {
199 // No boot patchlevel is available. Return a value that won't match anything
200 // and so will trigger test failures.
201 return kInvalidPatchlevel;
202 }
203}
204
205uint32_t KeyMintAidlTestBase::boot_patch_level() {
206 return boot_patch_level(key_characteristics_);
207}
208
Janis Danisevskis24c04702020-12-16 18:28:39 -0800209ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700210 if (result.isOk()) return ErrorCode::OK;
211
Janis Danisevskis24c04702020-12-16 18:28:39 -0800212 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
213 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700214 }
215
216 return ErrorCode::UNKNOWN_ERROR;
217}
218
Janis Danisevskis24c04702020-12-16 18:28:39 -0800219void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700220 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800221 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700222
223 KeyMintHardwareInfo info;
224 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
225
226 securityLevel_ = info.securityLevel;
227 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
228 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100229 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700230
231 os_version_ = getOsVersion();
232 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100233 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700234}
235
David Drysdale7dff4fc2021-12-10 10:10:52 +0000236int32_t KeyMintAidlTestBase::AidlVersion() {
237 int32_t version = 0;
238 auto status = keymint_->getInterfaceVersion(&version);
239 if (!status.isOk()) {
240 ADD_FAILURE() << "Failed to determine interface version";
241 }
242 return version;
243}
244
Selene Huang31ab4042020-04-29 04:22:39 -0700245void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800246 if (AServiceManager_isDeclared(GetParam().c_str())) {
247 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
248 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
249 } else {
250 InitializeKeyMint(nullptr);
251 }
Selene Huang31ab4042020-04-29 04:22:39 -0700252}
253
254ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700255 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700256 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700257 vector<KeyCharacteristics>* key_characteristics,
258 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700259 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
260 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700261 << "Previous characteristics not deleted before generating key. Test bug.";
262
Shawn Willden7f424372021-01-10 18:06:50 -0700263 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700264 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700265 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700266 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
267 creationResult.keyCharacteristics);
268 EXPECT_GT(creationResult.keyBlob.size(), 0);
269 *key_blob = std::move(creationResult.keyBlob);
270 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700271 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700272
273 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
274 EXPECT_TRUE(algorithm);
275 if (algorithm &&
276 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700277 EXPECT_GE(cert_chain->size(), 1);
278 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
279 if (attest_key) {
280 EXPECT_EQ(cert_chain->size(), 1);
281 } else {
282 EXPECT_GT(cert_chain->size(), 1);
283 }
284 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700285 } else {
286 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700287 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700288 }
Selene Huang31ab4042020-04-29 04:22:39 -0700289 }
290
291 return GetReturnErrorCode(result);
292}
293
Shawn Willden7c130392020-12-21 09:58:22 -0700294ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
295 const optional<AttestationKey>& attest_key) {
296 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700297}
298
299ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
300 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700301 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700302 Status result;
303
Shawn Willden7f424372021-01-10 18:06:50 -0700304 cert_chain_.clear();
305 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700306 key_blob->clear();
307
Shawn Willden7f424372021-01-10 18:06:50 -0700308 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700309 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700310 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700311 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700312
313 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700314 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
315 creationResult.keyCharacteristics);
316 EXPECT_GT(creationResult.keyBlob.size(), 0);
317
318 *key_blob = std::move(creationResult.keyBlob);
319 *key_characteristics = std::move(creationResult.keyCharacteristics);
320 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700321
322 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
323 EXPECT_TRUE(algorithm);
324 if (algorithm &&
325 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
326 EXPECT_GE(cert_chain_.size(), 1);
327 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
328 } else {
329 // For symmetric keys there should be no certificates.
330 EXPECT_EQ(cert_chain_.size(), 0);
331 }
Selene Huang31ab4042020-04-29 04:22:39 -0700332 }
333
334 return GetReturnErrorCode(result);
335}
336
337ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
338 const string& key_material) {
339 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
340}
341
342ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
343 const AuthorizationSet& wrapping_key_desc,
344 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100345 const AuthorizationSet& unwrapping_params,
346 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700347 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
348
Shawn Willden7f424372021-01-10 18:06:50 -0700349 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700350
Shawn Willden7f424372021-01-10 18:06:50 -0700351 KeyCreationResult creationResult;
352 Status result = keymint_->importWrappedKey(
353 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
354 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100355 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700356
357 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700358 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
359 creationResult.keyCharacteristics);
360 EXPECT_GT(creationResult.keyBlob.size(), 0);
361
362 key_blob_ = std::move(creationResult.keyBlob);
363 key_characteristics_ = std::move(creationResult.keyCharacteristics);
364 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700365
366 AuthorizationSet allAuths;
367 for (auto& entry : key_characteristics_) {
368 allAuths.push_back(AuthorizationSet(entry.authorizations));
369 }
370 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
371 EXPECT_TRUE(algorithm);
372 if (algorithm &&
373 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
374 EXPECT_GE(cert_chain_.size(), 1);
375 } else {
376 // For symmetric keys there should be no certificates.
377 EXPECT_EQ(cert_chain_.size(), 0);
378 }
Selene Huang31ab4042020-04-29 04:22:39 -0700379 }
380
381 return GetReturnErrorCode(result);
382}
383
David Drysdale300b5552021-05-20 12:05:26 +0100384ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
385 const vector<uint8_t>& app_id,
386 const vector<uint8_t>& app_data,
387 vector<KeyCharacteristics>* key_characteristics) {
388 Status result =
389 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
390 return GetReturnErrorCode(result);
391}
392
393ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
394 vector<KeyCharacteristics>* key_characteristics) {
395 vector<uint8_t> empty_app_id, empty_app_data;
396 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
397}
398
399void KeyMintAidlTestBase::CheckCharacteristics(
400 const vector<uint8_t>& key_blob,
401 const vector<KeyCharacteristics>& generate_characteristics) {
402 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
403 // generateKey() should be excluded, as KeyMint will have no record of them.
404 // This applies to CREATION_DATETIME in particular.
405 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
406 strip_keystore_tags(&expected_characteristics);
407
408 vector<KeyCharacteristics> retrieved;
409 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
410 EXPECT_EQ(expected_characteristics, retrieved);
411}
412
413void KeyMintAidlTestBase::CheckAppIdCharacteristics(
414 const vector<uint8_t>& key_blob, std::string_view app_id_string,
415 std::string_view app_data_string,
416 const vector<KeyCharacteristics>& generate_characteristics) {
417 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
418 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
419 strip_keystore_tags(&expected_characteristics);
420
421 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
422 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
423 vector<KeyCharacteristics> retrieved;
424 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
425 EXPECT_EQ(expected_characteristics, retrieved);
426
427 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
428 vector<uint8_t> empty;
429 vector<KeyCharacteristics> not_retrieved;
430 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
431 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
432 EXPECT_EQ(not_retrieved.size(), 0);
433
434 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
435 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
436 EXPECT_EQ(not_retrieved.size(), 0);
437
438 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
439 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
440 EXPECT_EQ(not_retrieved.size(), 0);
441}
442
Selene Huang31ab4042020-04-29 04:22:39 -0700443ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
444 Status result = keymint_->deleteKey(*key_blob);
445 if (!keep_key_blob) {
446 *key_blob = vector<uint8_t>();
447 }
448
Janis Danisevskis24c04702020-12-16 18:28:39 -0800449 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700450 return GetReturnErrorCode(result);
451}
452
453ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
454 return DeleteKey(&key_blob_, keep_key_blob);
455}
456
457ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
458 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800459 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700460 return GetReturnErrorCode(result);
461}
462
David Drysdaled2cc8c22021-04-15 13:29:45 +0100463ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
464 Status result = keymint_->destroyAttestationIds();
465 return GetReturnErrorCode(result);
466}
467
Selene Huang31ab4042020-04-29 04:22:39 -0700468void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
469 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
470 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
471}
472
473void KeyMintAidlTestBase::CheckedDeleteKey() {
474 CheckedDeleteKey(&key_blob_);
475}
476
477ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
478 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800479 AuthorizationSet* out_params,
480 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700481 SCOPED_TRACE("Begin");
482 Status result;
483 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100484 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700485
486 if (result.isOk()) {
487 *out_params = out.params;
488 challenge_ = out.challenge;
489 op = out.operation;
490 }
491
492 return GetReturnErrorCode(result);
493}
494
495ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
496 const AuthorizationSet& in_params,
497 AuthorizationSet* out_params) {
498 SCOPED_TRACE("Begin");
499 Status result;
500 BeginResult out;
501
David Drysdale56ba9122021-04-19 19:10:47 +0100502 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700503
504 if (result.isOk()) {
505 *out_params = out.params;
506 challenge_ = out.challenge;
507 op_ = out.operation;
508 }
509
510 return GetReturnErrorCode(result);
511}
512
513ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
514 AuthorizationSet* out_params) {
515 SCOPED_TRACE("Begin");
516 EXPECT_EQ(nullptr, op_);
517 return Begin(purpose, key_blob_, in_params, out_params);
518}
519
520ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
521 SCOPED_TRACE("Begin");
522 AuthorizationSet out_params;
523 ErrorCode result = Begin(purpose, in_params, &out_params);
524 EXPECT_TRUE(out_params.empty());
525 return result;
526}
527
Shawn Willden92d79c02021-02-19 07:31:55 -0700528ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
529 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
530 {} /* hardwareAuthToken */,
531 {} /* verificationToken */));
532}
533
534ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700535 SCOPED_TRACE("Update");
536
537 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700538 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700539
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800540 EXPECT_NE(op_, nullptr);
541 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
542
Shawn Willden92d79c02021-02-19 07:31:55 -0700543 std::vector<uint8_t> o_put;
544 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700545
Shawn Willden92d79c02021-02-19 07:31:55 -0700546 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700547
548 return GetReturnErrorCode(result);
549}
550
Shawn Willden92d79c02021-02-19 07:31:55 -0700551ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700552 string* output) {
553 SCOPED_TRACE("Finish");
554 Status result;
555
556 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700557 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700558
559 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700560 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
561 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
562 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700563
Shawn Willden92d79c02021-02-19 07:31:55 -0700564 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700565
Shawn Willden92d79c02021-02-19 07:31:55 -0700566 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700567 return GetReturnErrorCode(result);
568}
569
Janis Danisevskis24c04702020-12-16 18:28:39 -0800570ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700571 SCOPED_TRACE("Abort");
572
573 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700574 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700575
576 Status retval = op->abort();
577 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800578 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700579}
580
581ErrorCode KeyMintAidlTestBase::Abort() {
582 SCOPED_TRACE("Abort");
583
584 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700585 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700586
587 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800588 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700589}
590
591void KeyMintAidlTestBase::AbortIfNeeded() {
592 SCOPED_TRACE("AbortIfNeeded");
593 if (op_) {
594 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800595 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700596 }
597}
598
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000599auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
600 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700601 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000602 AuthorizationSet begin_out_params;
603 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700604 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000605
606 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700607 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000608}
609
Selene Huang31ab4042020-04-29 04:22:39 -0700610string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
611 const string& message, const AuthorizationSet& in_params,
612 AuthorizationSet* out_params) {
613 SCOPED_TRACE("ProcessMessage");
614 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700615 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700616 EXPECT_EQ(ErrorCode::OK, result);
617 if (result != ErrorCode::OK) {
618 return "";
619 }
620
621 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700622 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700623 return output;
624}
625
626string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
627 const AuthorizationSet& params) {
628 SCOPED_TRACE("SignMessage");
629 AuthorizationSet out_params;
630 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
631 EXPECT_TRUE(out_params.empty());
632 return signature;
633}
634
635string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
636 SCOPED_TRACE("SignMessage");
637 return SignMessage(key_blob_, message, params);
638}
639
640string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
641 SCOPED_TRACE("MacMessage");
642 return SignMessage(
643 key_blob_, message,
644 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
645}
646
647void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
648 Digest digest, const string& expected_mac) {
649 SCOPED_TRACE("CheckHmacTestVector");
650 ASSERT_EQ(ErrorCode::OK,
651 ImportKey(AuthorizationSetBuilder()
652 .Authorization(TAG_NO_AUTH_REQUIRED)
653 .HmacKey(key.size() * 8)
654 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
655 .Digest(digest),
656 KeyFormat::RAW, key));
657 string signature = MacMessage(message, digest, expected_mac.size() * 8);
658 EXPECT_EQ(expected_mac, signature)
659 << "Test vector didn't match for key of size " << key.size() << " message of size "
660 << message.size() << " and digest " << digest;
661 CheckedDeleteKey();
662}
663
664void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
665 const string& message,
666 const string& expected_ciphertext) {
667 SCOPED_TRACE("CheckAesCtrTestVector");
668 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
669 .Authorization(TAG_NO_AUTH_REQUIRED)
670 .AesEncryptionKey(key.size() * 8)
671 .BlockMode(BlockMode::CTR)
672 .Authorization(TAG_CALLER_NONCE)
673 .Padding(PaddingMode::NONE),
674 KeyFormat::RAW, key));
675
676 auto params = AuthorizationSetBuilder()
677 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
678 .BlockMode(BlockMode::CTR)
679 .Padding(PaddingMode::NONE);
680 AuthorizationSet out_params;
681 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
682 EXPECT_EQ(expected_ciphertext, ciphertext);
683}
684
685void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
686 PaddingMode padding_mode, const string& key,
687 const string& iv, const string& input,
688 const string& expected_output) {
689 auto authset = AuthorizationSetBuilder()
690 .TripleDesEncryptionKey(key.size() * 7)
691 .BlockMode(block_mode)
692 .Authorization(TAG_NO_AUTH_REQUIRED)
693 .Padding(padding_mode);
694 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
695 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
696 ASSERT_GT(key_blob_.size(), 0U);
697
698 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
699 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
700 AuthorizationSet output_params;
701 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
702 EXPECT_EQ(expected_output, output);
703}
704
705void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
706 const string& signature, const AuthorizationSet& params) {
707 SCOPED_TRACE("VerifyMessage");
708 AuthorizationSet begin_out_params;
709 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
710
711 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700712 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700713 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700714 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700715}
716
717void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
718 const AuthorizationSet& params) {
719 SCOPED_TRACE("VerifyMessage");
720 VerifyMessage(key_blob_, message, signature, params);
721}
722
David Drysdaledf8f52e2021-05-06 08:10:58 +0100723void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
724 const AuthorizationSet& params) {
725 SCOPED_TRACE("LocalVerifyMessage");
726
727 // Retrieve the public key from the leaf certificate.
728 ASSERT_GT(cert_chain_.size(), 0);
729 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
730 ASSERT_TRUE(key_cert.get());
731 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
732 ASSERT_TRUE(pub_key.get());
733
734 Digest digest = params.GetTagValue(TAG_DIGEST).value();
735 PaddingMode padding = PaddingMode::NONE;
736 auto tag = params.GetTagValue(TAG_PADDING);
737 if (tag.has_value()) {
738 padding = tag.value();
739 }
740
741 if (digest == Digest::NONE) {
742 switch (EVP_PKEY_id(pub_key.get())) {
743 case EVP_PKEY_EC: {
744 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
745 size_t data_size = std::min(data.size(), message.size());
746 memcpy(data.data(), message.data(), data_size);
747 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
748 ASSERT_TRUE(ecdsa.get());
749 ASSERT_EQ(1,
750 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
751 reinterpret_cast<const uint8_t*>(signature.data()),
752 signature.size(), ecdsa.get()));
753 break;
754 }
755 case EVP_PKEY_RSA: {
756 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
757 size_t data_size = std::min(data.size(), message.size());
758 memcpy(data.data(), message.data(), data_size);
759
760 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
761 ASSERT_TRUE(rsa.get());
762
763 size_t key_len = RSA_size(rsa.get());
764 int openssl_padding = RSA_NO_PADDING;
765 switch (padding) {
766 case PaddingMode::NONE:
767 ASSERT_TRUE(data_size <= key_len);
768 ASSERT_EQ(key_len, signature.size());
769 openssl_padding = RSA_NO_PADDING;
770 break;
771 case PaddingMode::RSA_PKCS1_1_5_SIGN:
772 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
773 key_len);
774 openssl_padding = RSA_PKCS1_PADDING;
775 break;
776 default:
777 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
778 }
779
780 vector<uint8_t> decrypted_data(key_len);
781 int bytes_decrypted = RSA_public_decrypt(
782 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
783 decrypted_data.data(), rsa.get(), openssl_padding);
784 ASSERT_GE(bytes_decrypted, 0);
785
786 const uint8_t* compare_pos = decrypted_data.data();
787 size_t bytes_to_compare = bytes_decrypted;
788 uint8_t zero_check_result = 0;
789 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
790 // If the data is short, for "unpadded" signing we zero-pad to the left. So
791 // during verification we should have zeros on the left of the decrypted data.
792 // Do a constant-time check.
793 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
794 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
795 ASSERT_EQ(0, zero_check_result);
796 bytes_to_compare = data_size;
797 }
798 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
799 break;
800 }
801 default:
802 ADD_FAILURE() << "Unknown public key type";
803 }
804 } else {
805 EVP_MD_CTX digest_ctx;
806 EVP_MD_CTX_init(&digest_ctx);
807 EVP_PKEY_CTX* pkey_ctx;
808 const EVP_MD* md = openssl_digest(digest);
809 ASSERT_NE(md, nullptr);
810 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
811
812 if (padding == PaddingMode::RSA_PSS) {
813 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
814 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
815 }
816
817 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
818 reinterpret_cast<const uint8_t*>(message.data()),
819 message.size()));
820 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
821 reinterpret_cast<const uint8_t*>(signature.data()),
822 signature.size()));
823 EVP_MD_CTX_cleanup(&digest_ctx);
824 }
825}
826
David Drysdale59cae642021-05-12 13:52:03 +0100827string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
828 const AuthorizationSet& params) {
829 SCOPED_TRACE("LocalRsaEncryptMessage");
830
831 // Retrieve the public key from the leaf certificate.
832 if (cert_chain_.empty()) {
833 ADD_FAILURE() << "No public key available";
834 return "Failure";
835 }
836 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
837 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
838 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
839
840 // Retrieve relevant tags.
841 Digest digest = Digest::NONE;
842 Digest mgf_digest = Digest::NONE;
843 PaddingMode padding = PaddingMode::NONE;
844
845 auto digest_tag = params.GetTagValue(TAG_DIGEST);
846 if (digest_tag.has_value()) digest = digest_tag.value();
847 auto pad_tag = params.GetTagValue(TAG_PADDING);
848 if (pad_tag.has_value()) padding = pad_tag.value();
849 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
850 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
851
852 const EVP_MD* md = openssl_digest(digest);
853 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
854
855 // Set up encryption context.
856 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
857 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
858 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
859 return "Failure";
860 }
861
862 int rc = -1;
863 switch (padding) {
864 case PaddingMode::NONE:
865 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
866 break;
867 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
868 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
869 break;
870 case PaddingMode::RSA_OAEP:
871 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
872 break;
873 default:
874 break;
875 }
876 if (rc <= 0) {
877 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
878 return "Failure";
879 }
880 if (padding == PaddingMode::RSA_OAEP) {
881 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
882 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
883 return "Failure";
884 }
885 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
886 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
887 return "Failure";
888 }
889 }
890
891 // Determine output size.
892 size_t outlen;
893 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
894 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
895 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
896 return "Failure";
897 }
898
899 // Left-zero-pad the input if necessary.
900 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
901 size_t to_encrypt_len = message.size();
902
903 std::unique_ptr<string> zero_padded_message;
904 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
905 zero_padded_message.reset(new string(outlen, '\0'));
906 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
907 message.size());
908 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
909 to_encrypt_len = outlen;
910 }
911
912 // Do the encryption.
913 string output(outlen, '\0');
914 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
915 to_encrypt_len) <= 0) {
916 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
917 return "Failure";
918 }
919 return output;
920}
921
Selene Huang31ab4042020-04-29 04:22:39 -0700922string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
923 const AuthorizationSet& in_params,
924 AuthorizationSet* out_params) {
925 SCOPED_TRACE("EncryptMessage");
926 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
927}
928
929string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
930 AuthorizationSet* out_params) {
931 SCOPED_TRACE("EncryptMessage");
932 return EncryptMessage(key_blob_, message, params, out_params);
933}
934
935string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
936 SCOPED_TRACE("EncryptMessage");
937 AuthorizationSet out_params;
938 string ciphertext = EncryptMessage(message, params, &out_params);
939 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
940 return ciphertext;
941}
942
943string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
944 PaddingMode padding) {
945 SCOPED_TRACE("EncryptMessage");
946 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
947 AuthorizationSet out_params;
948 string ciphertext = EncryptMessage(message, params, &out_params);
949 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
950 return ciphertext;
951}
952
953string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
954 PaddingMode padding, vector<uint8_t>* iv_out) {
955 SCOPED_TRACE("EncryptMessage");
956 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
957 AuthorizationSet out_params;
958 string ciphertext = EncryptMessage(message, params, &out_params);
959 EXPECT_EQ(1U, out_params.size());
960 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800961 EXPECT_TRUE(ivVal);
962 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700963 return ciphertext;
964}
965
966string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
967 PaddingMode padding, const vector<uint8_t>& iv_in) {
968 SCOPED_TRACE("EncryptMessage");
969 auto params = AuthorizationSetBuilder()
970 .BlockMode(block_mode)
971 .Padding(padding)
972 .Authorization(TAG_NONCE, iv_in);
973 AuthorizationSet out_params;
974 string ciphertext = EncryptMessage(message, params, &out_params);
975 return ciphertext;
976}
977
978string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
979 PaddingMode padding, uint8_t mac_length_bits,
980 const vector<uint8_t>& iv_in) {
981 SCOPED_TRACE("EncryptMessage");
982 auto params = AuthorizationSetBuilder()
983 .BlockMode(block_mode)
984 .Padding(padding)
985 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
986 .Authorization(TAG_NONCE, iv_in);
987 AuthorizationSet out_params;
988 string ciphertext = EncryptMessage(message, params, &out_params);
989 return ciphertext;
990}
991
David Drysdaled2cc8c22021-04-15 13:29:45 +0100992string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
993 PaddingMode padding, uint8_t mac_length_bits) {
994 SCOPED_TRACE("EncryptMessage");
995 auto params = AuthorizationSetBuilder()
996 .BlockMode(block_mode)
997 .Padding(padding)
998 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
999 AuthorizationSet out_params;
1000 string ciphertext = EncryptMessage(message, params, &out_params);
1001 return ciphertext;
1002}
1003
Selene Huang31ab4042020-04-29 04:22:39 -07001004string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1005 const string& ciphertext,
1006 const AuthorizationSet& params) {
1007 SCOPED_TRACE("DecryptMessage");
1008 AuthorizationSet out_params;
1009 string plaintext =
1010 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1011 EXPECT_TRUE(out_params.empty());
1012 return plaintext;
1013}
1014
1015string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1016 const AuthorizationSet& params) {
1017 SCOPED_TRACE("DecryptMessage");
1018 return DecryptMessage(key_blob_, ciphertext, params);
1019}
1020
1021string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1022 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1023 SCOPED_TRACE("DecryptMessage");
1024 auto params = AuthorizationSetBuilder()
1025 .BlockMode(block_mode)
1026 .Padding(padding_mode)
1027 .Authorization(TAG_NONCE, iv);
1028 return DecryptMessage(key_blob_, ciphertext, params);
1029}
1030
1031std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1032 const vector<uint8_t>& key_blob) {
1033 std::pair<ErrorCode, vector<uint8_t>> retval;
1034 vector<uint8_t> outKeyBlob;
1035 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1036 ErrorCode errorcode = GetReturnErrorCode(result);
1037 retval = std::tie(errorcode, outKeyBlob);
1038
1039 return retval;
1040}
1041vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1042 switch (algorithm) {
1043 case Algorithm::RSA:
1044 switch (SecLevel()) {
1045 case SecurityLevel::SOFTWARE:
1046 case SecurityLevel::TRUSTED_ENVIRONMENT:
1047 return {2048, 3072, 4096};
1048 case SecurityLevel::STRONGBOX:
1049 return {2048};
1050 default:
1051 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1052 break;
1053 }
1054 break;
1055 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001056 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001057 break;
1058 case Algorithm::AES:
1059 return {128, 256};
1060 case Algorithm::TRIPLE_DES:
1061 return {168};
1062 case Algorithm::HMAC: {
1063 vector<uint32_t> retval((512 - 64) / 8 + 1);
1064 uint32_t size = 64 - 8;
1065 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1066 return retval;
1067 }
1068 default:
1069 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1070 return {};
1071 }
1072 ADD_FAILURE() << "Should be impossible to get here";
1073 return {};
1074}
1075
1076vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1077 if (SecLevel() == SecurityLevel::STRONGBOX) {
1078 switch (algorithm) {
1079 case Algorithm::RSA:
1080 return {3072, 4096};
1081 case Algorithm::EC:
1082 return {224, 384, 521};
1083 case Algorithm::AES:
1084 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001085 case Algorithm::TRIPLE_DES:
1086 return {56};
1087 default:
1088 return {};
1089 }
1090 } else {
1091 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001092 case Algorithm::AES:
1093 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001094 case Algorithm::TRIPLE_DES:
1095 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001096 default:
1097 return {};
1098 }
1099 }
1100 return {};
1101}
1102
David Drysdale7de9feb2021-03-05 14:56:19 +00001103vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1104 switch (algorithm) {
1105 case Algorithm::AES:
1106 return {
1107 BlockMode::CBC,
1108 BlockMode::CTR,
1109 BlockMode::ECB,
1110 BlockMode::GCM,
1111 };
1112 case Algorithm::TRIPLE_DES:
1113 return {
1114 BlockMode::CBC,
1115 BlockMode::ECB,
1116 };
1117 default:
1118 return {};
1119 }
1120}
1121
1122vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1123 BlockMode blockMode) {
1124 switch (algorithm) {
1125 case Algorithm::AES:
1126 switch (blockMode) {
1127 case BlockMode::CBC:
1128 case BlockMode::ECB:
1129 return {PaddingMode::NONE, PaddingMode::PKCS7};
1130 case BlockMode::CTR:
1131 case BlockMode::GCM:
1132 return {PaddingMode::NONE};
1133 default:
1134 return {};
1135 };
1136 case Algorithm::TRIPLE_DES:
1137 switch (blockMode) {
1138 case BlockMode::CBC:
1139 case BlockMode::ECB:
1140 return {PaddingMode::NONE, PaddingMode::PKCS7};
1141 default:
1142 return {};
1143 };
1144 default:
1145 return {};
1146 }
1147}
1148
1149vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1150 BlockMode blockMode) {
1151 switch (algorithm) {
1152 case Algorithm::AES:
1153 switch (blockMode) {
1154 case BlockMode::CTR:
1155 case BlockMode::GCM:
1156 return {PaddingMode::PKCS7};
1157 default:
1158 return {};
1159 };
1160 default:
1161 return {};
1162 }
1163}
1164
Selene Huang31ab4042020-04-29 04:22:39 -07001165vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1166 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1167 return {EcCurve::P_256};
1168 } else {
1169 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1170 }
1171}
1172
1173vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001174 if (SecLevel() == SecurityLevel::STRONGBOX) {
1175 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
1176 } else {
1177 return {};
1178 }
Selene Huang31ab4042020-04-29 04:22:39 -07001179}
1180
1181vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1182 switch (SecLevel()) {
1183 case SecurityLevel::SOFTWARE:
1184 case SecurityLevel::TRUSTED_ENVIRONMENT:
1185 if (withNone) {
1186 if (withMD5)
1187 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1188 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1189 Digest::SHA_2_512};
1190 else
1191 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1192 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1193 } else {
1194 if (withMD5)
1195 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1196 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1197 else
1198 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1199 Digest::SHA_2_512};
1200 }
1201 break;
1202 case SecurityLevel::STRONGBOX:
1203 if (withNone)
1204 return {Digest::NONE, Digest::SHA_2_256};
1205 else
1206 return {Digest::SHA_2_256};
1207 break;
1208 default:
1209 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1210 break;
1211 }
1212 ADD_FAILURE() << "Should be impossible to get here";
1213 return {};
1214}
1215
Shawn Willden7f424372021-01-10 18:06:50 -07001216static const vector<KeyParameter> kEmptyAuthList{};
1217
1218const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1219 const vector<KeyCharacteristics>& key_characteristics) {
1220 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1221 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1222 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1223}
1224
Qi Wubeefae42021-01-28 23:16:37 +08001225const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1226 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1227 auto found = std::find_if(
1228 key_characteristics.begin(), key_characteristics.end(),
1229 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001230 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1231}
1232
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001233ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001234 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001235 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1236 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1237 return result;
1238}
1239
1240ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001241 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001242 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1243 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1244 return result;
1245}
1246
1247ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1248 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001249 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001250 rsaKeyBlob, KeyPurpose::SIGN, message,
1251 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1252 return result;
1253}
1254
1255ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001256 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1257 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001258 return result;
1259}
1260
Selene Huang6e46f142021-04-20 19:20:11 -07001261void verify_serial(X509* cert, const uint64_t expected_serial) {
1262 BIGNUM_Ptr ser(BN_new());
1263 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1264
1265 uint64_t serial;
1266 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1267 EXPECT_EQ(serial, expected_serial);
1268}
1269
1270// Please set self_signed to true for fake certificates or self signed
1271// certificates
1272void verify_subject(const X509* cert, //
1273 const string& subject, //
1274 bool self_signed) {
1275 char* cert_issuer = //
1276 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1277
1278 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1279
1280 string expected_subject("/CN=");
1281 if (subject.empty()) {
1282 expected_subject.append("Android Keystore Key");
1283 } else {
1284 expected_subject.append(subject);
1285 }
1286
1287 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1288
1289 if (self_signed) {
1290 EXPECT_STREQ(cert_issuer, cert_subj)
1291 << "Cert issuer and subject mismatch for self signed certificate.";
1292 }
1293
1294 OPENSSL_free(cert_subj);
1295 OPENSSL_free(cert_issuer);
1296}
1297
1298vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1299 BIGNUM_Ptr serial(BN_new());
1300 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1301
1302 int len = BN_num_bytes(serial.get());
1303 vector<uint8_t> serial_blob(len);
1304 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1305 return {};
1306 }
1307
David Drysdaledb0dcf52021-05-18 11:43:31 +01001308 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1309 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1310 // Top bit being set indicates a negative number in two's complement, but our input
1311 // was positive.
1312 // In either case, prepend a zero byte.
1313 serial_blob.insert(serial_blob.begin(), 0x00);
1314 }
1315
Selene Huang6e46f142021-04-20 19:20:11 -07001316 return serial_blob;
1317}
1318
1319void verify_subject_and_serial(const Certificate& certificate, //
1320 const uint64_t expected_serial, //
1321 const string& subject, bool self_signed) {
1322 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1323 ASSERT_TRUE(!!cert.get());
1324
1325 verify_serial(cert.get(), expected_serial);
1326 verify_subject(cert.get(), subject, self_signed);
1327}
1328
David Drysdale7dff4fc2021-12-10 10:10:52 +00001329bool verify_attestation_record(int32_t aidl_version, //
1330 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001331 const string& app_id, //
1332 AuthorizationSet expected_sw_enforced, //
1333 AuthorizationSet expected_hw_enforced, //
1334 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001335 const vector<uint8_t>& attestation_cert,
1336 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001337 X509_Ptr cert(parse_cert_blob(attestation_cert));
1338 EXPECT_TRUE(!!cert.get());
1339 if (!cert.get()) return false;
1340
1341 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1342 EXPECT_TRUE(!!attest_rec);
1343 if (!attest_rec) return false;
1344
1345 AuthorizationSet att_sw_enforced;
1346 AuthorizationSet att_hw_enforced;
1347 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001348 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001349 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001350 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001351 vector<uint8_t> att_challenge;
1352 vector<uint8_t> att_unique_id;
1353 vector<uint8_t> att_app_id;
1354
1355 auto error = parse_attestation_record(attest_rec->data, //
1356 attest_rec->length, //
1357 &att_attestation_version, //
1358 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001359 &att_keymint_version, //
1360 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001361 &att_challenge, //
1362 &att_sw_enforced, //
1363 &att_hw_enforced, //
1364 &att_unique_id);
1365 EXPECT_EQ(ErrorCode::OK, error);
1366 if (error != ErrorCode::OK) return false;
1367
David Drysdale7dff4fc2021-12-10 10:10:52 +00001368 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001369 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001370
Selene Huang4f64c222021-04-13 19:54:36 -07001371 // check challenge and app id only if we expects a non-fake certificate
1372 if (challenge.length() > 0) {
1373 EXPECT_EQ(challenge.length(), att_challenge.size());
1374 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1375
1376 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1377 }
Shawn Willden7c130392020-12-21 09:58:22 -07001378
David Drysdale7dff4fc2021-12-10 10:10:52 +00001379 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001380 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001381 EXPECT_EQ(security_level, att_attestation_security_level);
1382
Shawn Willden7c130392020-12-21 09:58:22 -07001383
1384 char property_value[PROPERTY_VALUE_MAX] = {};
1385 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001386 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001387 // for the BOOT_PATCH_LEVEL.
1388 if (avb_verification_enabled()) {
1389 for (int i = 0; i < att_hw_enforced.size(); i++) {
1390 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1391 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1392 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001393 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001394
Shawn Willden7c130392020-12-21 09:58:22 -07001395 // strptime seems to require delimiters, but the tag value will
1396 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001397 if (date.size() != 8) {
1398 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1399 << " with invalid format (not YYYYMMDD): " << date;
1400 return false;
1401 }
Shawn Willden7c130392020-12-21 09:58:22 -07001402 date.insert(6, "-");
1403 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001404 struct tm time;
1405 strptime(date.c_str(), "%Y-%m-%d", &time);
1406
1407 // Day of the month (0-31)
1408 EXPECT_GE(time.tm_mday, 0);
1409 EXPECT_LT(time.tm_mday, 32);
1410 // Months since Jan (0-11)
1411 EXPECT_GE(time.tm_mon, 0);
1412 EXPECT_LT(time.tm_mon, 12);
1413 // Years since 1900
1414 EXPECT_GT(time.tm_year, 110);
1415 EXPECT_LT(time.tm_year, 200);
1416 }
1417 }
1418 }
1419
1420 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1421 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1422 // indicates correct encoding. No need to check if it's in both lists, since the
1423 // AuthorizationSet compare below will handle mismatches of tags.
1424 if (security_level == SecurityLevel::SOFTWARE) {
1425 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1426 } else {
1427 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1428 }
1429
Shawn Willden7c130392020-12-21 09:58:22 -07001430 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1431 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1432 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1433 att_hw_enforced.Contains(TAG_KEY_SIZE));
1434 }
1435
1436 // Test root of trust elements
1437 vector<uint8_t> verified_boot_key;
1438 VerifiedBoot verified_boot_state;
1439 bool device_locked;
1440 vector<uint8_t> verified_boot_hash;
1441 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1442 &verified_boot_state, &device_locked, &verified_boot_hash);
1443 EXPECT_EQ(ErrorCode::OK, error);
1444
1445 if (avb_verification_enabled()) {
1446 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1447 string prop_string(property_value);
1448 EXPECT_EQ(prop_string.size(), 64);
1449 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1450
1451 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1452 if (!strcmp(property_value, "unlocked")) {
1453 EXPECT_FALSE(device_locked);
1454 } else {
1455 EXPECT_TRUE(device_locked);
1456 }
1457
1458 // Check that the device is locked if not debuggable, e.g., user build
1459 // images in CTS. For VTS, debuggable images are used to allow adb root
1460 // and the device is unlocked.
1461 if (!property_get_bool("ro.debuggable", false)) {
1462 EXPECT_TRUE(device_locked);
1463 } else {
1464 EXPECT_FALSE(device_locked);
1465 }
1466 }
1467
1468 // Verified boot key should be all 0's if the boot state is not verified or self signed
1469 std::string empty_boot_key(32, '\0');
1470 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1471 verified_boot_key.size());
1472 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1473 if (!strcmp(property_value, "green")) {
1474 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1475 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1476 verified_boot_key.size()));
1477 } else if (!strcmp(property_value, "yellow")) {
1478 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1479 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1480 verified_boot_key.size()));
1481 } else if (!strcmp(property_value, "orange")) {
1482 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1483 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1484 verified_boot_key.size()));
1485 } else if (!strcmp(property_value, "red")) {
1486 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1487 } else {
1488 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1489 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1490 verified_boot_key.size()));
1491 }
1492
1493 att_sw_enforced.Sort();
1494 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001495 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001496
1497 att_hw_enforced.Sort();
1498 expected_hw_enforced.Sort();
1499 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1500
David Drysdale565ccc72021-10-11 12:49:50 +01001501 if (unique_id != nullptr) {
1502 *unique_id = att_unique_id;
1503 }
1504
Shawn Willden7c130392020-12-21 09:58:22 -07001505 return true;
1506}
1507
1508string bin2hex(const vector<uint8_t>& data) {
1509 string retval;
1510 retval.reserve(data.size() * 2 + 1);
1511 for (uint8_t byte : data) {
1512 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1513 retval.push_back(nibble2hex[0x0F & byte]);
1514 }
1515 return retval;
1516}
1517
David Drysdalef0d516d2021-03-22 07:51:43 +00001518AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1519 AuthorizationSet authList;
1520 for (auto& entry : key_characteristics) {
1521 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1522 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1523 authList.push_back(AuthorizationSet(entry.authorizations));
1524 }
1525 }
1526 return authList;
1527}
1528
1529AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1530 AuthorizationSet authList;
1531 for (auto& entry : key_characteristics) {
1532 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1533 entry.securityLevel == SecurityLevel::KEYSTORE) {
1534 authList.push_back(AuthorizationSet(entry.authorizations));
1535 }
1536 }
1537 return authList;
1538}
1539
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001540AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1541 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001542 std::stringstream cert_data;
1543
1544 for (size_t i = 0; i < chain.size(); ++i) {
1545 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1546
1547 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1548 X509_Ptr signing_cert;
1549 if (i < chain.size() - 1) {
1550 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1551 } else {
1552 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1553 }
1554 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1555
1556 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1557 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1558
1559 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1560 return AssertionFailure()
1561 << "Verification of certificate " << i << " failed "
1562 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1563 << cert_data.str();
1564 }
1565
1566 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1567 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001568 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001569 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1570 << " Signer subject is " << signer_subj
1571 << " Issuer subject is " << cert_issuer << endl
1572 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001573 }
Shawn Willden7c130392020-12-21 09:58:22 -07001574 }
1575
1576 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1577 return AssertionSuccess();
1578}
1579
1580X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1581 const uint8_t* p = blob.data();
1582 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1583}
1584
David Drysdalef0d516d2021-03-22 07:51:43 +00001585vector<uint8_t> make_name_from_str(const string& name) {
1586 X509_NAME_Ptr x509_name(X509_NAME_new());
1587 EXPECT_TRUE(x509_name.get() != nullptr);
1588 if (!x509_name) return {};
1589
1590 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1591 "CN", //
1592 MBSTRING_ASC,
1593 reinterpret_cast<const uint8_t*>(name.c_str()),
1594 -1, // len
1595 -1, // loc
1596 0 /* set */));
1597
1598 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1599 EXPECT_GT(len, 0);
1600
1601 vector<uint8_t> retval(len);
1602 uint8_t* p = retval.data();
1603 i2d_X509_NAME(x509_name.get(), &p);
1604
1605 return retval;
1606}
1607
David Drysdale4dc01072021-04-01 12:17:35 +01001608namespace {
1609
1610void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1611 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1612 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1613
1614 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1615 if (testMode) {
1616 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1617 MatchesRegex("{\n"
1618 " 1 : 2,\n" // kty: EC2
1619 " 3 : -7,\n" // alg: ES256
1620 " -1 : 1,\n" // EC id: P256
1621 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1622 // sequence of 32 hexadecimal bytes, enclosed in braces and
1623 // separated by commas. In this case, some Ed25519 public key.
1624 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1625 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1626 " -70000 : null,\n" // test marker
1627 "}"));
1628 } else {
1629 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1630 MatchesRegex("{\n"
1631 " 1 : 2,\n" // kty: EC2
1632 " 3 : -7,\n" // alg: ES256
1633 " -1 : 1,\n" // EC id: P256
1634 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1635 // sequence of 32 hexadecimal bytes, enclosed in braces and
1636 // separated by commas. In this case, some Ed25519 public key.
1637 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1638 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1639 "}"));
1640 }
1641}
1642
1643} // namespace
1644
1645void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1646 vector<uint8_t>* payload_value) {
1647 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1648 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1649
1650 ASSERT_NE(coseMac0->asArray(), nullptr);
1651 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1652
1653 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1654 ASSERT_NE(protParms, nullptr);
1655
1656 // Header label:value of 'alg': HMAC-256
1657 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1658
1659 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1660 ASSERT_NE(unprotParms, nullptr);
1661 ASSERT_EQ(unprotParms->size(), 0);
1662
1663 // The payload is a bstr holding an encoded COSE_Key
1664 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1665 ASSERT_NE(payload, nullptr);
1666 check_cose_key(payload->value(), testMode);
1667
1668 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1669 ASSERT_TRUE(coseMac0Tag);
1670 auto extractedTag = coseMac0Tag->value();
1671 EXPECT_EQ(extractedTag.size(), 32U);
1672
1673 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001674 auto macFunction = [](const cppcose::bytevec& input) {
1675 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1676 };
1677 auto testTag =
1678 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001679 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1680
1681 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001682 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001683 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001684 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001685 }
1686 if (payload_value != nullptr) {
1687 *payload_value = payload->value();
1688 }
1689}
1690
1691void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1692 // Extract x and y affine coordinates from the encoded Cose_Key.
1693 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1694 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1695 auto coseKey = parsedPayload->asMap();
1696 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1697 ASSERT_NE(xItem->asBstr(), nullptr);
1698 vector<uint8_t> x = xItem->asBstr()->value();
1699 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1700 ASSERT_NE(yItem->asBstr(), nullptr);
1701 vector<uint8_t> y = yItem->asBstr()->value();
1702
1703 // Concatenate: 0x04 (uncompressed form marker) | x | y
1704 vector<uint8_t> pubKeyData{0x04};
1705 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1706 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1707
1708 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1709 ASSERT_NE(ecKey, nullptr);
1710 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1711 ASSERT_NE(group, nullptr);
1712 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1713 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1714 ASSERT_NE(point, nullptr);
1715 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1716 nullptr),
1717 1);
1718 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1719
1720 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1721 ASSERT_NE(pubKey, nullptr);
1722 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1723 *signingKey = std::move(pubKey);
1724}
1725
Selene Huang31ab4042020-04-29 04:22:39 -07001726} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001727
Janis Danisevskis24c04702020-12-16 18:28:39 -08001728} // namespace aidl::android::hardware::security::keymint