blob: 374f2da7a898b153164c617e4444a1587ec6449f [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);
David Drysdalec6b89072021-12-14 14:32:51 +0000815 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +0100816 }
817
818 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
819 reinterpret_cast<const uint8_t*>(message.data()),
820 message.size()));
821 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
822 reinterpret_cast<const uint8_t*>(signature.data()),
823 signature.size()));
824 EVP_MD_CTX_cleanup(&digest_ctx);
825 }
826}
827
David Drysdale59cae642021-05-12 13:52:03 +0100828string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
829 const AuthorizationSet& params) {
830 SCOPED_TRACE("LocalRsaEncryptMessage");
831
832 // Retrieve the public key from the leaf certificate.
833 if (cert_chain_.empty()) {
834 ADD_FAILURE() << "No public key available";
835 return "Failure";
836 }
837 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
838 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
839 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
840
841 // Retrieve relevant tags.
842 Digest digest = Digest::NONE;
843 Digest mgf_digest = Digest::NONE;
844 PaddingMode padding = PaddingMode::NONE;
845
846 auto digest_tag = params.GetTagValue(TAG_DIGEST);
847 if (digest_tag.has_value()) digest = digest_tag.value();
848 auto pad_tag = params.GetTagValue(TAG_PADDING);
849 if (pad_tag.has_value()) padding = pad_tag.value();
850 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
851 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
852
853 const EVP_MD* md = openssl_digest(digest);
854 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
855
856 // Set up encryption context.
857 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
858 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
859 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
860 return "Failure";
861 }
862
863 int rc = -1;
864 switch (padding) {
865 case PaddingMode::NONE:
866 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
867 break;
868 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
869 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
870 break;
871 case PaddingMode::RSA_OAEP:
872 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
873 break;
874 default:
875 break;
876 }
877 if (rc <= 0) {
878 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
879 return "Failure";
880 }
881 if (padding == PaddingMode::RSA_OAEP) {
882 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
883 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
884 return "Failure";
885 }
886 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
887 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
888 return "Failure";
889 }
890 }
891
892 // Determine output size.
893 size_t outlen;
894 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
895 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
896 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
897 return "Failure";
898 }
899
900 // Left-zero-pad the input if necessary.
901 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
902 size_t to_encrypt_len = message.size();
903
904 std::unique_ptr<string> zero_padded_message;
905 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
906 zero_padded_message.reset(new string(outlen, '\0'));
907 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
908 message.size());
909 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
910 to_encrypt_len = outlen;
911 }
912
913 // Do the encryption.
914 string output(outlen, '\0');
915 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
916 to_encrypt_len) <= 0) {
917 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
918 return "Failure";
919 }
920 return output;
921}
922
Selene Huang31ab4042020-04-29 04:22:39 -0700923string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
924 const AuthorizationSet& in_params,
925 AuthorizationSet* out_params) {
926 SCOPED_TRACE("EncryptMessage");
927 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
928}
929
930string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
931 AuthorizationSet* out_params) {
932 SCOPED_TRACE("EncryptMessage");
933 return EncryptMessage(key_blob_, message, params, out_params);
934}
935
936string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
937 SCOPED_TRACE("EncryptMessage");
938 AuthorizationSet out_params;
939 string ciphertext = EncryptMessage(message, params, &out_params);
940 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
941 return ciphertext;
942}
943
944string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
945 PaddingMode padding) {
946 SCOPED_TRACE("EncryptMessage");
947 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
948 AuthorizationSet out_params;
949 string ciphertext = EncryptMessage(message, params, &out_params);
950 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
951 return ciphertext;
952}
953
954string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
955 PaddingMode padding, vector<uint8_t>* iv_out) {
956 SCOPED_TRACE("EncryptMessage");
957 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
958 AuthorizationSet out_params;
959 string ciphertext = EncryptMessage(message, params, &out_params);
960 EXPECT_EQ(1U, out_params.size());
961 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800962 EXPECT_TRUE(ivVal);
963 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700964 return ciphertext;
965}
966
967string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
968 PaddingMode padding, const vector<uint8_t>& iv_in) {
969 SCOPED_TRACE("EncryptMessage");
970 auto params = AuthorizationSetBuilder()
971 .BlockMode(block_mode)
972 .Padding(padding)
973 .Authorization(TAG_NONCE, iv_in);
974 AuthorizationSet out_params;
975 string ciphertext = EncryptMessage(message, params, &out_params);
976 return ciphertext;
977}
978
979string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
980 PaddingMode padding, uint8_t mac_length_bits,
981 const vector<uint8_t>& iv_in) {
982 SCOPED_TRACE("EncryptMessage");
983 auto params = AuthorizationSetBuilder()
984 .BlockMode(block_mode)
985 .Padding(padding)
986 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
987 .Authorization(TAG_NONCE, iv_in);
988 AuthorizationSet out_params;
989 string ciphertext = EncryptMessage(message, params, &out_params);
990 return ciphertext;
991}
992
David Drysdaled2cc8c22021-04-15 13:29:45 +0100993string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
994 PaddingMode padding, uint8_t mac_length_bits) {
995 SCOPED_TRACE("EncryptMessage");
996 auto params = AuthorizationSetBuilder()
997 .BlockMode(block_mode)
998 .Padding(padding)
999 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1000 AuthorizationSet out_params;
1001 string ciphertext = EncryptMessage(message, params, &out_params);
1002 return ciphertext;
1003}
1004
Selene Huang31ab4042020-04-29 04:22:39 -07001005string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1006 const string& ciphertext,
1007 const AuthorizationSet& params) {
1008 SCOPED_TRACE("DecryptMessage");
1009 AuthorizationSet out_params;
1010 string plaintext =
1011 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1012 EXPECT_TRUE(out_params.empty());
1013 return plaintext;
1014}
1015
1016string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1017 const AuthorizationSet& params) {
1018 SCOPED_TRACE("DecryptMessage");
1019 return DecryptMessage(key_blob_, ciphertext, params);
1020}
1021
1022string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1023 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1024 SCOPED_TRACE("DecryptMessage");
1025 auto params = AuthorizationSetBuilder()
1026 .BlockMode(block_mode)
1027 .Padding(padding_mode)
1028 .Authorization(TAG_NONCE, iv);
1029 return DecryptMessage(key_blob_, ciphertext, params);
1030}
1031
1032std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1033 const vector<uint8_t>& key_blob) {
1034 std::pair<ErrorCode, vector<uint8_t>> retval;
1035 vector<uint8_t> outKeyBlob;
1036 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1037 ErrorCode errorcode = GetReturnErrorCode(result);
1038 retval = std::tie(errorcode, outKeyBlob);
1039
1040 return retval;
1041}
1042vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1043 switch (algorithm) {
1044 case Algorithm::RSA:
1045 switch (SecLevel()) {
1046 case SecurityLevel::SOFTWARE:
1047 case SecurityLevel::TRUSTED_ENVIRONMENT:
1048 return {2048, 3072, 4096};
1049 case SecurityLevel::STRONGBOX:
1050 return {2048};
1051 default:
1052 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1053 break;
1054 }
1055 break;
1056 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001057 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001058 break;
1059 case Algorithm::AES:
1060 return {128, 256};
1061 case Algorithm::TRIPLE_DES:
1062 return {168};
1063 case Algorithm::HMAC: {
1064 vector<uint32_t> retval((512 - 64) / 8 + 1);
1065 uint32_t size = 64 - 8;
1066 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1067 return retval;
1068 }
1069 default:
1070 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1071 return {};
1072 }
1073 ADD_FAILURE() << "Should be impossible to get here";
1074 return {};
1075}
1076
1077vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1078 if (SecLevel() == SecurityLevel::STRONGBOX) {
1079 switch (algorithm) {
1080 case Algorithm::RSA:
1081 return {3072, 4096};
1082 case Algorithm::EC:
1083 return {224, 384, 521};
1084 case Algorithm::AES:
1085 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001086 case Algorithm::TRIPLE_DES:
1087 return {56};
1088 default:
1089 return {};
1090 }
1091 } else {
1092 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001093 case Algorithm::AES:
1094 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001095 case Algorithm::TRIPLE_DES:
1096 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001097 default:
1098 return {};
1099 }
1100 }
1101 return {};
1102}
1103
David Drysdale7de9feb2021-03-05 14:56:19 +00001104vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1105 switch (algorithm) {
1106 case Algorithm::AES:
1107 return {
1108 BlockMode::CBC,
1109 BlockMode::CTR,
1110 BlockMode::ECB,
1111 BlockMode::GCM,
1112 };
1113 case Algorithm::TRIPLE_DES:
1114 return {
1115 BlockMode::CBC,
1116 BlockMode::ECB,
1117 };
1118 default:
1119 return {};
1120 }
1121}
1122
1123vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1124 BlockMode blockMode) {
1125 switch (algorithm) {
1126 case Algorithm::AES:
1127 switch (blockMode) {
1128 case BlockMode::CBC:
1129 case BlockMode::ECB:
1130 return {PaddingMode::NONE, PaddingMode::PKCS7};
1131 case BlockMode::CTR:
1132 case BlockMode::GCM:
1133 return {PaddingMode::NONE};
1134 default:
1135 return {};
1136 };
1137 case Algorithm::TRIPLE_DES:
1138 switch (blockMode) {
1139 case BlockMode::CBC:
1140 case BlockMode::ECB:
1141 return {PaddingMode::NONE, PaddingMode::PKCS7};
1142 default:
1143 return {};
1144 };
1145 default:
1146 return {};
1147 }
1148}
1149
1150vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1151 BlockMode blockMode) {
1152 switch (algorithm) {
1153 case Algorithm::AES:
1154 switch (blockMode) {
1155 case BlockMode::CTR:
1156 case BlockMode::GCM:
1157 return {PaddingMode::PKCS7};
1158 default:
1159 return {};
1160 };
1161 default:
1162 return {};
1163 }
1164}
1165
Selene Huang31ab4042020-04-29 04:22:39 -07001166vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1167 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1168 return {EcCurve::P_256};
1169 } else {
1170 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1171 }
1172}
1173
1174vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001175 if (SecLevel() == SecurityLevel::STRONGBOX) {
1176 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
1177 } else {
1178 return {};
1179 }
Selene Huang31ab4042020-04-29 04:22:39 -07001180}
1181
1182vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1183 switch (SecLevel()) {
1184 case SecurityLevel::SOFTWARE:
1185 case SecurityLevel::TRUSTED_ENVIRONMENT:
1186 if (withNone) {
1187 if (withMD5)
1188 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1189 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1190 Digest::SHA_2_512};
1191 else
1192 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1193 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1194 } else {
1195 if (withMD5)
1196 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1197 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1198 else
1199 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1200 Digest::SHA_2_512};
1201 }
1202 break;
1203 case SecurityLevel::STRONGBOX:
1204 if (withNone)
1205 return {Digest::NONE, Digest::SHA_2_256};
1206 else
1207 return {Digest::SHA_2_256};
1208 break;
1209 default:
1210 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1211 break;
1212 }
1213 ADD_FAILURE() << "Should be impossible to get here";
1214 return {};
1215}
1216
Shawn Willden7f424372021-01-10 18:06:50 -07001217static const vector<KeyParameter> kEmptyAuthList{};
1218
1219const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1220 const vector<KeyCharacteristics>& key_characteristics) {
1221 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1222 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1223 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1224}
1225
Qi Wubeefae42021-01-28 23:16:37 +08001226const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1227 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1228 auto found = std::find_if(
1229 key_characteristics.begin(), key_characteristics.end(),
1230 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001231 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1232}
1233
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001234ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001235 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001236 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1237 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1238 return result;
1239}
1240
1241ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001242 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001243 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1244 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1245 return result;
1246}
1247
1248ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1249 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001250 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001251 rsaKeyBlob, KeyPurpose::SIGN, message,
1252 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1253 return result;
1254}
1255
1256ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001257 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1258 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001259 return result;
1260}
1261
Selene Huang6e46f142021-04-20 19:20:11 -07001262void verify_serial(X509* cert, const uint64_t expected_serial) {
1263 BIGNUM_Ptr ser(BN_new());
1264 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1265
1266 uint64_t serial;
1267 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1268 EXPECT_EQ(serial, expected_serial);
1269}
1270
1271// Please set self_signed to true for fake certificates or self signed
1272// certificates
1273void verify_subject(const X509* cert, //
1274 const string& subject, //
1275 bool self_signed) {
1276 char* cert_issuer = //
1277 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1278
1279 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1280
1281 string expected_subject("/CN=");
1282 if (subject.empty()) {
1283 expected_subject.append("Android Keystore Key");
1284 } else {
1285 expected_subject.append(subject);
1286 }
1287
1288 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1289
1290 if (self_signed) {
1291 EXPECT_STREQ(cert_issuer, cert_subj)
1292 << "Cert issuer and subject mismatch for self signed certificate.";
1293 }
1294
1295 OPENSSL_free(cert_subj);
1296 OPENSSL_free(cert_issuer);
1297}
1298
1299vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1300 BIGNUM_Ptr serial(BN_new());
1301 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1302
1303 int len = BN_num_bytes(serial.get());
1304 vector<uint8_t> serial_blob(len);
1305 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1306 return {};
1307 }
1308
David Drysdaledb0dcf52021-05-18 11:43:31 +01001309 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1310 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1311 // Top bit being set indicates a negative number in two's complement, but our input
1312 // was positive.
1313 // In either case, prepend a zero byte.
1314 serial_blob.insert(serial_blob.begin(), 0x00);
1315 }
1316
Selene Huang6e46f142021-04-20 19:20:11 -07001317 return serial_blob;
1318}
1319
1320void verify_subject_and_serial(const Certificate& certificate, //
1321 const uint64_t expected_serial, //
1322 const string& subject, bool self_signed) {
1323 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1324 ASSERT_TRUE(!!cert.get());
1325
1326 verify_serial(cert.get(), expected_serial);
1327 verify_subject(cert.get(), subject, self_signed);
1328}
1329
David Drysdale7dff4fc2021-12-10 10:10:52 +00001330bool verify_attestation_record(int32_t aidl_version, //
1331 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001332 const string& app_id, //
1333 AuthorizationSet expected_sw_enforced, //
1334 AuthorizationSet expected_hw_enforced, //
1335 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001336 const vector<uint8_t>& attestation_cert,
1337 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001338 X509_Ptr cert(parse_cert_blob(attestation_cert));
1339 EXPECT_TRUE(!!cert.get());
1340 if (!cert.get()) return false;
1341
1342 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1343 EXPECT_TRUE(!!attest_rec);
1344 if (!attest_rec) return false;
1345
1346 AuthorizationSet att_sw_enforced;
1347 AuthorizationSet att_hw_enforced;
1348 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001349 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001350 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001351 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001352 vector<uint8_t> att_challenge;
1353 vector<uint8_t> att_unique_id;
1354 vector<uint8_t> att_app_id;
1355
1356 auto error = parse_attestation_record(attest_rec->data, //
1357 attest_rec->length, //
1358 &att_attestation_version, //
1359 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001360 &att_keymint_version, //
1361 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001362 &att_challenge, //
1363 &att_sw_enforced, //
1364 &att_hw_enforced, //
1365 &att_unique_id);
1366 EXPECT_EQ(ErrorCode::OK, error);
1367 if (error != ErrorCode::OK) return false;
1368
David Drysdale7dff4fc2021-12-10 10:10:52 +00001369 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001370 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001371
Selene Huang4f64c222021-04-13 19:54:36 -07001372 // check challenge and app id only if we expects a non-fake certificate
1373 if (challenge.length() > 0) {
1374 EXPECT_EQ(challenge.length(), att_challenge.size());
1375 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1376
1377 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1378 }
Shawn Willden7c130392020-12-21 09:58:22 -07001379
David Drysdale7dff4fc2021-12-10 10:10:52 +00001380 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001381 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001382 EXPECT_EQ(security_level, att_attestation_security_level);
1383
Shawn Willden7c130392020-12-21 09:58:22 -07001384
1385 char property_value[PROPERTY_VALUE_MAX] = {};
1386 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001387 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001388 // for the BOOT_PATCH_LEVEL.
1389 if (avb_verification_enabled()) {
1390 for (int i = 0; i < att_hw_enforced.size(); i++) {
1391 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1392 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1393 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001394 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001395
Shawn Willden7c130392020-12-21 09:58:22 -07001396 // strptime seems to require delimiters, but the tag value will
1397 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001398 if (date.size() != 8) {
1399 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1400 << " with invalid format (not YYYYMMDD): " << date;
1401 return false;
1402 }
Shawn Willden7c130392020-12-21 09:58:22 -07001403 date.insert(6, "-");
1404 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001405 struct tm time;
1406 strptime(date.c_str(), "%Y-%m-%d", &time);
1407
1408 // Day of the month (0-31)
1409 EXPECT_GE(time.tm_mday, 0);
1410 EXPECT_LT(time.tm_mday, 32);
1411 // Months since Jan (0-11)
1412 EXPECT_GE(time.tm_mon, 0);
1413 EXPECT_LT(time.tm_mon, 12);
1414 // Years since 1900
1415 EXPECT_GT(time.tm_year, 110);
1416 EXPECT_LT(time.tm_year, 200);
1417 }
1418 }
1419 }
1420
1421 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1422 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1423 // indicates correct encoding. No need to check if it's in both lists, since the
1424 // AuthorizationSet compare below will handle mismatches of tags.
1425 if (security_level == SecurityLevel::SOFTWARE) {
1426 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1427 } else {
1428 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1429 }
1430
Shawn Willden7c130392020-12-21 09:58:22 -07001431 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1432 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1433 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1434 att_hw_enforced.Contains(TAG_KEY_SIZE));
1435 }
1436
1437 // Test root of trust elements
1438 vector<uint8_t> verified_boot_key;
1439 VerifiedBoot verified_boot_state;
1440 bool device_locked;
1441 vector<uint8_t> verified_boot_hash;
1442 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1443 &verified_boot_state, &device_locked, &verified_boot_hash);
1444 EXPECT_EQ(ErrorCode::OK, error);
1445
1446 if (avb_verification_enabled()) {
1447 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1448 string prop_string(property_value);
1449 EXPECT_EQ(prop_string.size(), 64);
1450 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1451
1452 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1453 if (!strcmp(property_value, "unlocked")) {
1454 EXPECT_FALSE(device_locked);
1455 } else {
1456 EXPECT_TRUE(device_locked);
1457 }
1458
1459 // Check that the device is locked if not debuggable, e.g., user build
1460 // images in CTS. For VTS, debuggable images are used to allow adb root
1461 // and the device is unlocked.
1462 if (!property_get_bool("ro.debuggable", false)) {
1463 EXPECT_TRUE(device_locked);
1464 } else {
1465 EXPECT_FALSE(device_locked);
1466 }
1467 }
1468
1469 // Verified boot key should be all 0's if the boot state is not verified or self signed
1470 std::string empty_boot_key(32, '\0');
1471 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1472 verified_boot_key.size());
1473 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1474 if (!strcmp(property_value, "green")) {
1475 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1476 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1477 verified_boot_key.size()));
1478 } else if (!strcmp(property_value, "yellow")) {
1479 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1480 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1481 verified_boot_key.size()));
1482 } else if (!strcmp(property_value, "orange")) {
1483 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1484 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1485 verified_boot_key.size()));
1486 } else if (!strcmp(property_value, "red")) {
1487 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1488 } else {
1489 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1490 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1491 verified_boot_key.size()));
1492 }
1493
1494 att_sw_enforced.Sort();
1495 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001496 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001497
1498 att_hw_enforced.Sort();
1499 expected_hw_enforced.Sort();
1500 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1501
David Drysdale565ccc72021-10-11 12:49:50 +01001502 if (unique_id != nullptr) {
1503 *unique_id = att_unique_id;
1504 }
1505
Shawn Willden7c130392020-12-21 09:58:22 -07001506 return true;
1507}
1508
1509string bin2hex(const vector<uint8_t>& data) {
1510 string retval;
1511 retval.reserve(data.size() * 2 + 1);
1512 for (uint8_t byte : data) {
1513 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1514 retval.push_back(nibble2hex[0x0F & byte]);
1515 }
1516 return retval;
1517}
1518
David Drysdalef0d516d2021-03-22 07:51:43 +00001519AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1520 AuthorizationSet authList;
1521 for (auto& entry : key_characteristics) {
1522 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1523 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1524 authList.push_back(AuthorizationSet(entry.authorizations));
1525 }
1526 }
1527 return authList;
1528}
1529
1530AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1531 AuthorizationSet authList;
1532 for (auto& entry : key_characteristics) {
1533 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1534 entry.securityLevel == SecurityLevel::KEYSTORE) {
1535 authList.push_back(AuthorizationSet(entry.authorizations));
1536 }
1537 }
1538 return authList;
1539}
1540
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001541AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1542 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001543 std::stringstream cert_data;
1544
1545 for (size_t i = 0; i < chain.size(); ++i) {
1546 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1547
1548 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1549 X509_Ptr signing_cert;
1550 if (i < chain.size() - 1) {
1551 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1552 } else {
1553 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1554 }
1555 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1556
1557 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1558 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1559
1560 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1561 return AssertionFailure()
1562 << "Verification of certificate " << i << " failed "
1563 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1564 << cert_data.str();
1565 }
1566
1567 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1568 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001569 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001570 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1571 << " Signer subject is " << signer_subj
1572 << " Issuer subject is " << cert_issuer << endl
1573 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001574 }
Shawn Willden7c130392020-12-21 09:58:22 -07001575 }
1576
1577 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1578 return AssertionSuccess();
1579}
1580
1581X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1582 const uint8_t* p = blob.data();
1583 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1584}
1585
David Drysdalef0d516d2021-03-22 07:51:43 +00001586vector<uint8_t> make_name_from_str(const string& name) {
1587 X509_NAME_Ptr x509_name(X509_NAME_new());
1588 EXPECT_TRUE(x509_name.get() != nullptr);
1589 if (!x509_name) return {};
1590
1591 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1592 "CN", //
1593 MBSTRING_ASC,
1594 reinterpret_cast<const uint8_t*>(name.c_str()),
1595 -1, // len
1596 -1, // loc
1597 0 /* set */));
1598
1599 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1600 EXPECT_GT(len, 0);
1601
1602 vector<uint8_t> retval(len);
1603 uint8_t* p = retval.data();
1604 i2d_X509_NAME(x509_name.get(), &p);
1605
1606 return retval;
1607}
1608
David Drysdale4dc01072021-04-01 12:17:35 +01001609namespace {
1610
1611void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1612 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1613 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1614
1615 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1616 if (testMode) {
1617 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1618 MatchesRegex("{\n"
1619 " 1 : 2,\n" // kty: EC2
1620 " 3 : -7,\n" // alg: ES256
1621 " -1 : 1,\n" // EC id: P256
1622 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1623 // sequence of 32 hexadecimal bytes, enclosed in braces and
1624 // separated by commas. In this case, some Ed25519 public key.
1625 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1626 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1627 " -70000 : null,\n" // test marker
1628 "}"));
1629 } else {
1630 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1631 MatchesRegex("{\n"
1632 " 1 : 2,\n" // kty: EC2
1633 " 3 : -7,\n" // alg: ES256
1634 " -1 : 1,\n" // EC id: P256
1635 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1636 // sequence of 32 hexadecimal bytes, enclosed in braces and
1637 // separated by commas. In this case, some Ed25519 public key.
1638 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1639 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1640 "}"));
1641 }
1642}
1643
1644} // namespace
1645
1646void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1647 vector<uint8_t>* payload_value) {
1648 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1649 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1650
1651 ASSERT_NE(coseMac0->asArray(), nullptr);
1652 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1653
1654 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1655 ASSERT_NE(protParms, nullptr);
1656
1657 // Header label:value of 'alg': HMAC-256
1658 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1659
1660 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1661 ASSERT_NE(unprotParms, nullptr);
1662 ASSERT_EQ(unprotParms->size(), 0);
1663
1664 // The payload is a bstr holding an encoded COSE_Key
1665 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1666 ASSERT_NE(payload, nullptr);
1667 check_cose_key(payload->value(), testMode);
1668
1669 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1670 ASSERT_TRUE(coseMac0Tag);
1671 auto extractedTag = coseMac0Tag->value();
1672 EXPECT_EQ(extractedTag.size(), 32U);
1673
1674 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001675 auto macFunction = [](const cppcose::bytevec& input) {
1676 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1677 };
1678 auto testTag =
1679 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001680 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1681
1682 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001683 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001684 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001685 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001686 }
1687 if (payload_value != nullptr) {
1688 *payload_value = payload->value();
1689 }
1690}
1691
1692void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1693 // Extract x and y affine coordinates from the encoded Cose_Key.
1694 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1695 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1696 auto coseKey = parsedPayload->asMap();
1697 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1698 ASSERT_NE(xItem->asBstr(), nullptr);
1699 vector<uint8_t> x = xItem->asBstr()->value();
1700 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1701 ASSERT_NE(yItem->asBstr(), nullptr);
1702 vector<uint8_t> y = yItem->asBstr()->value();
1703
1704 // Concatenate: 0x04 (uncompressed form marker) | x | y
1705 vector<uint8_t> pubKeyData{0x04};
1706 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1707 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1708
1709 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1710 ASSERT_NE(ecKey, nullptr);
1711 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1712 ASSERT_NE(group, nullptr);
1713 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1714 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1715 ASSERT_NE(point, nullptr);
1716 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1717 nullptr),
1718 1);
1719 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1720
1721 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1722 ASSERT_NE(pubKey, nullptr);
1723 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1724 *signingKey = std::move(pubKey);
1725}
1726
Selene Huang31ab4042020-04-29 04:22:39 -07001727} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001728
Janis Danisevskis24c04702020-12-16 18:28:39 -08001729} // namespace aidl::android::hardware::security::keymint