blob: 3695f1e094a5e874110492b89bf4aaf59679a520 [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
Shawn Willden92d79c02021-02-19 07:31:55 -0700540 std::vector<uint8_t> o_put;
541 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700542
Shawn Willden92d79c02021-02-19 07:31:55 -0700543 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700544
545 return GetReturnErrorCode(result);
546}
547
Shawn Willden92d79c02021-02-19 07:31:55 -0700548ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700549 string* output) {
550 SCOPED_TRACE("Finish");
551 Status result;
552
553 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700554 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700555
556 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700557 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
558 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
559 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700560
Shawn Willden92d79c02021-02-19 07:31:55 -0700561 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700562
Shawn Willden92d79c02021-02-19 07:31:55 -0700563 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700564 return GetReturnErrorCode(result);
565}
566
Janis Danisevskis24c04702020-12-16 18:28:39 -0800567ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700568 SCOPED_TRACE("Abort");
569
570 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700571 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700572
573 Status retval = op->abort();
574 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800575 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700576}
577
578ErrorCode KeyMintAidlTestBase::Abort() {
579 SCOPED_TRACE("Abort");
580
581 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700582 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700583
584 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800585 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700586}
587
588void KeyMintAidlTestBase::AbortIfNeeded() {
589 SCOPED_TRACE("AbortIfNeeded");
590 if (op_) {
591 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800592 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700593 }
594}
595
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000596auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
597 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700598 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000599 AuthorizationSet begin_out_params;
600 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700601 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000602
603 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700604 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000605}
606
Selene Huang31ab4042020-04-29 04:22:39 -0700607string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
608 const string& message, const AuthorizationSet& in_params,
609 AuthorizationSet* out_params) {
610 SCOPED_TRACE("ProcessMessage");
611 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700612 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700613 EXPECT_EQ(ErrorCode::OK, result);
614 if (result != ErrorCode::OK) {
615 return "";
616 }
617
618 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700619 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700620 return output;
621}
622
623string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
624 const AuthorizationSet& params) {
625 SCOPED_TRACE("SignMessage");
626 AuthorizationSet out_params;
627 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
628 EXPECT_TRUE(out_params.empty());
629 return signature;
630}
631
632string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
633 SCOPED_TRACE("SignMessage");
634 return SignMessage(key_blob_, message, params);
635}
636
637string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
638 SCOPED_TRACE("MacMessage");
639 return SignMessage(
640 key_blob_, message,
641 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
642}
643
644void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
645 Digest digest, const string& expected_mac) {
646 SCOPED_TRACE("CheckHmacTestVector");
647 ASSERT_EQ(ErrorCode::OK,
648 ImportKey(AuthorizationSetBuilder()
649 .Authorization(TAG_NO_AUTH_REQUIRED)
650 .HmacKey(key.size() * 8)
651 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
652 .Digest(digest),
653 KeyFormat::RAW, key));
654 string signature = MacMessage(message, digest, expected_mac.size() * 8);
655 EXPECT_EQ(expected_mac, signature)
656 << "Test vector didn't match for key of size " << key.size() << " message of size "
657 << message.size() << " and digest " << digest;
658 CheckedDeleteKey();
659}
660
661void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
662 const string& message,
663 const string& expected_ciphertext) {
664 SCOPED_TRACE("CheckAesCtrTestVector");
665 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
666 .Authorization(TAG_NO_AUTH_REQUIRED)
667 .AesEncryptionKey(key.size() * 8)
668 .BlockMode(BlockMode::CTR)
669 .Authorization(TAG_CALLER_NONCE)
670 .Padding(PaddingMode::NONE),
671 KeyFormat::RAW, key));
672
673 auto params = AuthorizationSetBuilder()
674 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
675 .BlockMode(BlockMode::CTR)
676 .Padding(PaddingMode::NONE);
677 AuthorizationSet out_params;
678 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
679 EXPECT_EQ(expected_ciphertext, ciphertext);
680}
681
682void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
683 PaddingMode padding_mode, const string& key,
684 const string& iv, const string& input,
685 const string& expected_output) {
686 auto authset = AuthorizationSetBuilder()
687 .TripleDesEncryptionKey(key.size() * 7)
688 .BlockMode(block_mode)
689 .Authorization(TAG_NO_AUTH_REQUIRED)
690 .Padding(padding_mode);
691 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
692 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
693 ASSERT_GT(key_blob_.size(), 0U);
694
695 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
696 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
697 AuthorizationSet output_params;
698 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
699 EXPECT_EQ(expected_output, output);
700}
701
702void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
703 const string& signature, const AuthorizationSet& params) {
704 SCOPED_TRACE("VerifyMessage");
705 AuthorizationSet begin_out_params;
706 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
707
708 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700709 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700710 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700711 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700712}
713
714void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
715 const AuthorizationSet& params) {
716 SCOPED_TRACE("VerifyMessage");
717 VerifyMessage(key_blob_, message, signature, params);
718}
719
David Drysdaledf8f52e2021-05-06 08:10:58 +0100720void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
721 const AuthorizationSet& params) {
722 SCOPED_TRACE("LocalVerifyMessage");
723
724 // Retrieve the public key from the leaf certificate.
725 ASSERT_GT(cert_chain_.size(), 0);
726 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
727 ASSERT_TRUE(key_cert.get());
728 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
729 ASSERT_TRUE(pub_key.get());
730
731 Digest digest = params.GetTagValue(TAG_DIGEST).value();
732 PaddingMode padding = PaddingMode::NONE;
733 auto tag = params.GetTagValue(TAG_PADDING);
734 if (tag.has_value()) {
735 padding = tag.value();
736 }
737
738 if (digest == Digest::NONE) {
739 switch (EVP_PKEY_id(pub_key.get())) {
740 case EVP_PKEY_EC: {
741 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
742 size_t data_size = std::min(data.size(), message.size());
743 memcpy(data.data(), message.data(), data_size);
744 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
745 ASSERT_TRUE(ecdsa.get());
746 ASSERT_EQ(1,
747 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
748 reinterpret_cast<const uint8_t*>(signature.data()),
749 signature.size(), ecdsa.get()));
750 break;
751 }
752 case EVP_PKEY_RSA: {
753 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
754 size_t data_size = std::min(data.size(), message.size());
755 memcpy(data.data(), message.data(), data_size);
756
757 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
758 ASSERT_TRUE(rsa.get());
759
760 size_t key_len = RSA_size(rsa.get());
761 int openssl_padding = RSA_NO_PADDING;
762 switch (padding) {
763 case PaddingMode::NONE:
764 ASSERT_TRUE(data_size <= key_len);
765 ASSERT_EQ(key_len, signature.size());
766 openssl_padding = RSA_NO_PADDING;
767 break;
768 case PaddingMode::RSA_PKCS1_1_5_SIGN:
769 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
770 key_len);
771 openssl_padding = RSA_PKCS1_PADDING;
772 break;
773 default:
774 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
775 }
776
777 vector<uint8_t> decrypted_data(key_len);
778 int bytes_decrypted = RSA_public_decrypt(
779 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
780 decrypted_data.data(), rsa.get(), openssl_padding);
781 ASSERT_GE(bytes_decrypted, 0);
782
783 const uint8_t* compare_pos = decrypted_data.data();
784 size_t bytes_to_compare = bytes_decrypted;
785 uint8_t zero_check_result = 0;
786 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
787 // If the data is short, for "unpadded" signing we zero-pad to the left. So
788 // during verification we should have zeros on the left of the decrypted data.
789 // Do a constant-time check.
790 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
791 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
792 ASSERT_EQ(0, zero_check_result);
793 bytes_to_compare = data_size;
794 }
795 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
796 break;
797 }
798 default:
799 ADD_FAILURE() << "Unknown public key type";
800 }
801 } else {
802 EVP_MD_CTX digest_ctx;
803 EVP_MD_CTX_init(&digest_ctx);
804 EVP_PKEY_CTX* pkey_ctx;
805 const EVP_MD* md = openssl_digest(digest);
806 ASSERT_NE(md, nullptr);
807 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
808
809 if (padding == PaddingMode::RSA_PSS) {
810 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
811 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
812 }
813
814 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
815 reinterpret_cast<const uint8_t*>(message.data()),
816 message.size()));
817 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
818 reinterpret_cast<const uint8_t*>(signature.data()),
819 signature.size()));
820 EVP_MD_CTX_cleanup(&digest_ctx);
821 }
822}
823
David Drysdale59cae642021-05-12 13:52:03 +0100824string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
825 const AuthorizationSet& params) {
826 SCOPED_TRACE("LocalRsaEncryptMessage");
827
828 // Retrieve the public key from the leaf certificate.
829 if (cert_chain_.empty()) {
830 ADD_FAILURE() << "No public key available";
831 return "Failure";
832 }
833 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
834 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
835 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
836
837 // Retrieve relevant tags.
838 Digest digest = Digest::NONE;
839 Digest mgf_digest = Digest::NONE;
840 PaddingMode padding = PaddingMode::NONE;
841
842 auto digest_tag = params.GetTagValue(TAG_DIGEST);
843 if (digest_tag.has_value()) digest = digest_tag.value();
844 auto pad_tag = params.GetTagValue(TAG_PADDING);
845 if (pad_tag.has_value()) padding = pad_tag.value();
846 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
847 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
848
849 const EVP_MD* md = openssl_digest(digest);
850 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
851
852 // Set up encryption context.
853 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
854 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
855 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
856 return "Failure";
857 }
858
859 int rc = -1;
860 switch (padding) {
861 case PaddingMode::NONE:
862 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
863 break;
864 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
865 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
866 break;
867 case PaddingMode::RSA_OAEP:
868 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
869 break;
870 default:
871 break;
872 }
873 if (rc <= 0) {
874 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
875 return "Failure";
876 }
877 if (padding == PaddingMode::RSA_OAEP) {
878 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
879 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
880 return "Failure";
881 }
882 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
883 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
884 return "Failure";
885 }
886 }
887
888 // Determine output size.
889 size_t outlen;
890 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
891 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
892 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
893 return "Failure";
894 }
895
896 // Left-zero-pad the input if necessary.
897 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
898 size_t to_encrypt_len = message.size();
899
900 std::unique_ptr<string> zero_padded_message;
901 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
902 zero_padded_message.reset(new string(outlen, '\0'));
903 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
904 message.size());
905 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
906 to_encrypt_len = outlen;
907 }
908
909 // Do the encryption.
910 string output(outlen, '\0');
911 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
912 to_encrypt_len) <= 0) {
913 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
914 return "Failure";
915 }
916 return output;
917}
918
Selene Huang31ab4042020-04-29 04:22:39 -0700919string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
920 const AuthorizationSet& in_params,
921 AuthorizationSet* out_params) {
922 SCOPED_TRACE("EncryptMessage");
923 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
924}
925
926string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
927 AuthorizationSet* out_params) {
928 SCOPED_TRACE("EncryptMessage");
929 return EncryptMessage(key_blob_, message, params, out_params);
930}
931
932string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
933 SCOPED_TRACE("EncryptMessage");
934 AuthorizationSet out_params;
935 string ciphertext = EncryptMessage(message, params, &out_params);
936 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
937 return ciphertext;
938}
939
940string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
941 PaddingMode padding) {
942 SCOPED_TRACE("EncryptMessage");
943 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
944 AuthorizationSet out_params;
945 string ciphertext = EncryptMessage(message, params, &out_params);
946 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
947 return ciphertext;
948}
949
950string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
951 PaddingMode padding, vector<uint8_t>* iv_out) {
952 SCOPED_TRACE("EncryptMessage");
953 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
954 AuthorizationSet out_params;
955 string ciphertext = EncryptMessage(message, params, &out_params);
956 EXPECT_EQ(1U, out_params.size());
957 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800958 EXPECT_TRUE(ivVal);
959 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700960 return ciphertext;
961}
962
963string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
964 PaddingMode padding, const vector<uint8_t>& iv_in) {
965 SCOPED_TRACE("EncryptMessage");
966 auto params = AuthorizationSetBuilder()
967 .BlockMode(block_mode)
968 .Padding(padding)
969 .Authorization(TAG_NONCE, iv_in);
970 AuthorizationSet out_params;
971 string ciphertext = EncryptMessage(message, params, &out_params);
972 return ciphertext;
973}
974
975string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
976 PaddingMode padding, uint8_t mac_length_bits,
977 const vector<uint8_t>& iv_in) {
978 SCOPED_TRACE("EncryptMessage");
979 auto params = AuthorizationSetBuilder()
980 .BlockMode(block_mode)
981 .Padding(padding)
982 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
983 .Authorization(TAG_NONCE, iv_in);
984 AuthorizationSet out_params;
985 string ciphertext = EncryptMessage(message, params, &out_params);
986 return ciphertext;
987}
988
David Drysdaled2cc8c22021-04-15 13:29:45 +0100989string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
990 PaddingMode padding, uint8_t mac_length_bits) {
991 SCOPED_TRACE("EncryptMessage");
992 auto params = AuthorizationSetBuilder()
993 .BlockMode(block_mode)
994 .Padding(padding)
995 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
996 AuthorizationSet out_params;
997 string ciphertext = EncryptMessage(message, params, &out_params);
998 return ciphertext;
999}
1000
Selene Huang31ab4042020-04-29 04:22:39 -07001001string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1002 const string& ciphertext,
1003 const AuthorizationSet& params) {
1004 SCOPED_TRACE("DecryptMessage");
1005 AuthorizationSet out_params;
1006 string plaintext =
1007 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1008 EXPECT_TRUE(out_params.empty());
1009 return plaintext;
1010}
1011
1012string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1013 const AuthorizationSet& params) {
1014 SCOPED_TRACE("DecryptMessage");
1015 return DecryptMessage(key_blob_, ciphertext, params);
1016}
1017
1018string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1019 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1020 SCOPED_TRACE("DecryptMessage");
1021 auto params = AuthorizationSetBuilder()
1022 .BlockMode(block_mode)
1023 .Padding(padding_mode)
1024 .Authorization(TAG_NONCE, iv);
1025 return DecryptMessage(key_blob_, ciphertext, params);
1026}
1027
1028std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1029 const vector<uint8_t>& key_blob) {
1030 std::pair<ErrorCode, vector<uint8_t>> retval;
1031 vector<uint8_t> outKeyBlob;
1032 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1033 ErrorCode errorcode = GetReturnErrorCode(result);
1034 retval = std::tie(errorcode, outKeyBlob);
1035
1036 return retval;
1037}
1038vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1039 switch (algorithm) {
1040 case Algorithm::RSA:
1041 switch (SecLevel()) {
1042 case SecurityLevel::SOFTWARE:
1043 case SecurityLevel::TRUSTED_ENVIRONMENT:
1044 return {2048, 3072, 4096};
1045 case SecurityLevel::STRONGBOX:
1046 return {2048};
1047 default:
1048 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1049 break;
1050 }
1051 break;
1052 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001053 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001054 break;
1055 case Algorithm::AES:
1056 return {128, 256};
1057 case Algorithm::TRIPLE_DES:
1058 return {168};
1059 case Algorithm::HMAC: {
1060 vector<uint32_t> retval((512 - 64) / 8 + 1);
1061 uint32_t size = 64 - 8;
1062 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1063 return retval;
1064 }
1065 default:
1066 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1067 return {};
1068 }
1069 ADD_FAILURE() << "Should be impossible to get here";
1070 return {};
1071}
1072
1073vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1074 if (SecLevel() == SecurityLevel::STRONGBOX) {
1075 switch (algorithm) {
1076 case Algorithm::RSA:
1077 return {3072, 4096};
1078 case Algorithm::EC:
1079 return {224, 384, 521};
1080 case Algorithm::AES:
1081 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001082 case Algorithm::TRIPLE_DES:
1083 return {56};
1084 default:
1085 return {};
1086 }
1087 } else {
1088 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001089 case Algorithm::AES:
1090 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001091 case Algorithm::TRIPLE_DES:
1092 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001093 default:
1094 return {};
1095 }
1096 }
1097 return {};
1098}
1099
David Drysdale7de9feb2021-03-05 14:56:19 +00001100vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1101 switch (algorithm) {
1102 case Algorithm::AES:
1103 return {
1104 BlockMode::CBC,
1105 BlockMode::CTR,
1106 BlockMode::ECB,
1107 BlockMode::GCM,
1108 };
1109 case Algorithm::TRIPLE_DES:
1110 return {
1111 BlockMode::CBC,
1112 BlockMode::ECB,
1113 };
1114 default:
1115 return {};
1116 }
1117}
1118
1119vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1120 BlockMode blockMode) {
1121 switch (algorithm) {
1122 case Algorithm::AES:
1123 switch (blockMode) {
1124 case BlockMode::CBC:
1125 case BlockMode::ECB:
1126 return {PaddingMode::NONE, PaddingMode::PKCS7};
1127 case BlockMode::CTR:
1128 case BlockMode::GCM:
1129 return {PaddingMode::NONE};
1130 default:
1131 return {};
1132 };
1133 case Algorithm::TRIPLE_DES:
1134 switch (blockMode) {
1135 case BlockMode::CBC:
1136 case BlockMode::ECB:
1137 return {PaddingMode::NONE, PaddingMode::PKCS7};
1138 default:
1139 return {};
1140 };
1141 default:
1142 return {};
1143 }
1144}
1145
1146vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1147 BlockMode blockMode) {
1148 switch (algorithm) {
1149 case Algorithm::AES:
1150 switch (blockMode) {
1151 case BlockMode::CTR:
1152 case BlockMode::GCM:
1153 return {PaddingMode::PKCS7};
1154 default:
1155 return {};
1156 };
1157 default:
1158 return {};
1159 }
1160}
1161
Selene Huang31ab4042020-04-29 04:22:39 -07001162vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1163 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1164 return {EcCurve::P_256};
1165 } else {
1166 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1167 }
1168}
1169
1170vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001171 if (SecLevel() == SecurityLevel::STRONGBOX) {
1172 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
1173 } else {
1174 return {};
1175 }
Selene Huang31ab4042020-04-29 04:22:39 -07001176}
1177
1178vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1179 switch (SecLevel()) {
1180 case SecurityLevel::SOFTWARE:
1181 case SecurityLevel::TRUSTED_ENVIRONMENT:
1182 if (withNone) {
1183 if (withMD5)
1184 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1185 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1186 Digest::SHA_2_512};
1187 else
1188 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1189 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1190 } else {
1191 if (withMD5)
1192 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1193 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1194 else
1195 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1196 Digest::SHA_2_512};
1197 }
1198 break;
1199 case SecurityLevel::STRONGBOX:
1200 if (withNone)
1201 return {Digest::NONE, Digest::SHA_2_256};
1202 else
1203 return {Digest::SHA_2_256};
1204 break;
1205 default:
1206 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1207 break;
1208 }
1209 ADD_FAILURE() << "Should be impossible to get here";
1210 return {};
1211}
1212
Shawn Willden7f424372021-01-10 18:06:50 -07001213static const vector<KeyParameter> kEmptyAuthList{};
1214
1215const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1216 const vector<KeyCharacteristics>& key_characteristics) {
1217 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1218 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1219 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1220}
1221
Qi Wubeefae42021-01-28 23:16:37 +08001222const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1223 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1224 auto found = std::find_if(
1225 key_characteristics.begin(), key_characteristics.end(),
1226 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001227 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1228}
1229
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001230ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001231 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001232 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1233 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1234 return result;
1235}
1236
1237ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001238 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001239 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1240 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1241 return result;
1242}
1243
1244ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1245 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001246 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001247 rsaKeyBlob, KeyPurpose::SIGN, message,
1248 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1249 return result;
1250}
1251
1252ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001253 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1254 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001255 return result;
1256}
1257
Selene Huang6e46f142021-04-20 19:20:11 -07001258void verify_serial(X509* cert, const uint64_t expected_serial) {
1259 BIGNUM_Ptr ser(BN_new());
1260 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1261
1262 uint64_t serial;
1263 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1264 EXPECT_EQ(serial, expected_serial);
1265}
1266
1267// Please set self_signed to true for fake certificates or self signed
1268// certificates
1269void verify_subject(const X509* cert, //
1270 const string& subject, //
1271 bool self_signed) {
1272 char* cert_issuer = //
1273 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1274
1275 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1276
1277 string expected_subject("/CN=");
1278 if (subject.empty()) {
1279 expected_subject.append("Android Keystore Key");
1280 } else {
1281 expected_subject.append(subject);
1282 }
1283
1284 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1285
1286 if (self_signed) {
1287 EXPECT_STREQ(cert_issuer, cert_subj)
1288 << "Cert issuer and subject mismatch for self signed certificate.";
1289 }
1290
1291 OPENSSL_free(cert_subj);
1292 OPENSSL_free(cert_issuer);
1293}
1294
1295vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1296 BIGNUM_Ptr serial(BN_new());
1297 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1298
1299 int len = BN_num_bytes(serial.get());
1300 vector<uint8_t> serial_blob(len);
1301 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1302 return {};
1303 }
1304
David Drysdaledb0dcf52021-05-18 11:43:31 +01001305 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1306 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1307 // Top bit being set indicates a negative number in two's complement, but our input
1308 // was positive.
1309 // In either case, prepend a zero byte.
1310 serial_blob.insert(serial_blob.begin(), 0x00);
1311 }
1312
Selene Huang6e46f142021-04-20 19:20:11 -07001313 return serial_blob;
1314}
1315
1316void verify_subject_and_serial(const Certificate& certificate, //
1317 const uint64_t expected_serial, //
1318 const string& subject, bool self_signed) {
1319 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1320 ASSERT_TRUE(!!cert.get());
1321
1322 verify_serial(cert.get(), expected_serial);
1323 verify_subject(cert.get(), subject, self_signed);
1324}
1325
David Drysdale7dff4fc2021-12-10 10:10:52 +00001326bool verify_attestation_record(int32_t aidl_version, //
1327 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001328 const string& app_id, //
1329 AuthorizationSet expected_sw_enforced, //
1330 AuthorizationSet expected_hw_enforced, //
1331 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001332 const vector<uint8_t>& attestation_cert,
1333 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001334 X509_Ptr cert(parse_cert_blob(attestation_cert));
1335 EXPECT_TRUE(!!cert.get());
1336 if (!cert.get()) return false;
1337
1338 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1339 EXPECT_TRUE(!!attest_rec);
1340 if (!attest_rec) return false;
1341
1342 AuthorizationSet att_sw_enforced;
1343 AuthorizationSet att_hw_enforced;
1344 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001345 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001346 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001347 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001348 vector<uint8_t> att_challenge;
1349 vector<uint8_t> att_unique_id;
1350 vector<uint8_t> att_app_id;
1351
1352 auto error = parse_attestation_record(attest_rec->data, //
1353 attest_rec->length, //
1354 &att_attestation_version, //
1355 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001356 &att_keymint_version, //
1357 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001358 &att_challenge, //
1359 &att_sw_enforced, //
1360 &att_hw_enforced, //
1361 &att_unique_id);
1362 EXPECT_EQ(ErrorCode::OK, error);
1363 if (error != ErrorCode::OK) return false;
1364
David Drysdale7dff4fc2021-12-10 10:10:52 +00001365 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001366 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001367
Selene Huang4f64c222021-04-13 19:54:36 -07001368 // check challenge and app id only if we expects a non-fake certificate
1369 if (challenge.length() > 0) {
1370 EXPECT_EQ(challenge.length(), att_challenge.size());
1371 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1372
1373 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1374 }
Shawn Willden7c130392020-12-21 09:58:22 -07001375
David Drysdale7dff4fc2021-12-10 10:10:52 +00001376 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001377 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001378 EXPECT_EQ(security_level, att_attestation_security_level);
1379
Shawn Willden7c130392020-12-21 09:58:22 -07001380
1381 char property_value[PROPERTY_VALUE_MAX] = {};
1382 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001383 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001384 // for the BOOT_PATCH_LEVEL.
1385 if (avb_verification_enabled()) {
1386 for (int i = 0; i < att_hw_enforced.size(); i++) {
1387 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1388 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1389 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001390 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001391
Shawn Willden7c130392020-12-21 09:58:22 -07001392 // strptime seems to require delimiters, but the tag value will
1393 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001394 if (date.size() != 8) {
1395 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1396 << " with invalid format (not YYYYMMDD): " << date;
1397 return false;
1398 }
Shawn Willden7c130392020-12-21 09:58:22 -07001399 date.insert(6, "-");
1400 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001401 struct tm time;
1402 strptime(date.c_str(), "%Y-%m-%d", &time);
1403
1404 // Day of the month (0-31)
1405 EXPECT_GE(time.tm_mday, 0);
1406 EXPECT_LT(time.tm_mday, 32);
1407 // Months since Jan (0-11)
1408 EXPECT_GE(time.tm_mon, 0);
1409 EXPECT_LT(time.tm_mon, 12);
1410 // Years since 1900
1411 EXPECT_GT(time.tm_year, 110);
1412 EXPECT_LT(time.tm_year, 200);
1413 }
1414 }
1415 }
1416
1417 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1418 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1419 // indicates correct encoding. No need to check if it's in both lists, since the
1420 // AuthorizationSet compare below will handle mismatches of tags.
1421 if (security_level == SecurityLevel::SOFTWARE) {
1422 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1423 } else {
1424 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1425 }
1426
Shawn Willden7c130392020-12-21 09:58:22 -07001427 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1428 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1429 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1430 att_hw_enforced.Contains(TAG_KEY_SIZE));
1431 }
1432
1433 // Test root of trust elements
1434 vector<uint8_t> verified_boot_key;
1435 VerifiedBoot verified_boot_state;
1436 bool device_locked;
1437 vector<uint8_t> verified_boot_hash;
1438 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1439 &verified_boot_state, &device_locked, &verified_boot_hash);
1440 EXPECT_EQ(ErrorCode::OK, error);
1441
1442 if (avb_verification_enabled()) {
1443 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1444 string prop_string(property_value);
1445 EXPECT_EQ(prop_string.size(), 64);
1446 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1447
1448 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1449 if (!strcmp(property_value, "unlocked")) {
1450 EXPECT_FALSE(device_locked);
1451 } else {
1452 EXPECT_TRUE(device_locked);
1453 }
1454
1455 // Check that the device is locked if not debuggable, e.g., user build
1456 // images in CTS. For VTS, debuggable images are used to allow adb root
1457 // and the device is unlocked.
1458 if (!property_get_bool("ro.debuggable", false)) {
1459 EXPECT_TRUE(device_locked);
1460 } else {
1461 EXPECT_FALSE(device_locked);
1462 }
1463 }
1464
1465 // Verified boot key should be all 0's if the boot state is not verified or self signed
1466 std::string empty_boot_key(32, '\0');
1467 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1468 verified_boot_key.size());
1469 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1470 if (!strcmp(property_value, "green")) {
1471 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1472 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1473 verified_boot_key.size()));
1474 } else if (!strcmp(property_value, "yellow")) {
1475 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1476 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1477 verified_boot_key.size()));
1478 } else if (!strcmp(property_value, "orange")) {
1479 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1480 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1481 verified_boot_key.size()));
1482 } else if (!strcmp(property_value, "red")) {
1483 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1484 } else {
1485 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1486 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1487 verified_boot_key.size()));
1488 }
1489
1490 att_sw_enforced.Sort();
1491 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001492 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001493
1494 att_hw_enforced.Sort();
1495 expected_hw_enforced.Sort();
1496 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1497
David Drysdale565ccc72021-10-11 12:49:50 +01001498 if (unique_id != nullptr) {
1499 *unique_id = att_unique_id;
1500 }
1501
Shawn Willden7c130392020-12-21 09:58:22 -07001502 return true;
1503}
1504
1505string bin2hex(const vector<uint8_t>& data) {
1506 string retval;
1507 retval.reserve(data.size() * 2 + 1);
1508 for (uint8_t byte : data) {
1509 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1510 retval.push_back(nibble2hex[0x0F & byte]);
1511 }
1512 return retval;
1513}
1514
David Drysdalef0d516d2021-03-22 07:51:43 +00001515AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1516 AuthorizationSet authList;
1517 for (auto& entry : key_characteristics) {
1518 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1519 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1520 authList.push_back(AuthorizationSet(entry.authorizations));
1521 }
1522 }
1523 return authList;
1524}
1525
1526AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1527 AuthorizationSet authList;
1528 for (auto& entry : key_characteristics) {
1529 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1530 entry.securityLevel == SecurityLevel::KEYSTORE) {
1531 authList.push_back(AuthorizationSet(entry.authorizations));
1532 }
1533 }
1534 return authList;
1535}
1536
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001537AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1538 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001539 std::stringstream cert_data;
1540
1541 for (size_t i = 0; i < chain.size(); ++i) {
1542 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1543
1544 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1545 X509_Ptr signing_cert;
1546 if (i < chain.size() - 1) {
1547 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1548 } else {
1549 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1550 }
1551 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1552
1553 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1554 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1555
1556 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1557 return AssertionFailure()
1558 << "Verification of certificate " << i << " failed "
1559 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1560 << cert_data.str();
1561 }
1562
1563 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1564 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001565 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001566 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1567 << " Signer subject is " << signer_subj
1568 << " Issuer subject is " << cert_issuer << endl
1569 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001570 }
Shawn Willden7c130392020-12-21 09:58:22 -07001571 }
1572
1573 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1574 return AssertionSuccess();
1575}
1576
1577X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1578 const uint8_t* p = blob.data();
1579 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1580}
1581
David Drysdalef0d516d2021-03-22 07:51:43 +00001582vector<uint8_t> make_name_from_str(const string& name) {
1583 X509_NAME_Ptr x509_name(X509_NAME_new());
1584 EXPECT_TRUE(x509_name.get() != nullptr);
1585 if (!x509_name) return {};
1586
1587 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1588 "CN", //
1589 MBSTRING_ASC,
1590 reinterpret_cast<const uint8_t*>(name.c_str()),
1591 -1, // len
1592 -1, // loc
1593 0 /* set */));
1594
1595 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1596 EXPECT_GT(len, 0);
1597
1598 vector<uint8_t> retval(len);
1599 uint8_t* p = retval.data();
1600 i2d_X509_NAME(x509_name.get(), &p);
1601
1602 return retval;
1603}
1604
David Drysdale4dc01072021-04-01 12:17:35 +01001605namespace {
1606
1607void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1608 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1609 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1610
1611 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1612 if (testMode) {
1613 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1614 MatchesRegex("{\n"
1615 " 1 : 2,\n" // kty: EC2
1616 " 3 : -7,\n" // alg: ES256
1617 " -1 : 1,\n" // EC id: P256
1618 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1619 // sequence of 32 hexadecimal bytes, enclosed in braces and
1620 // separated by commas. In this case, some Ed25519 public key.
1621 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1622 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1623 " -70000 : null,\n" // test marker
1624 "}"));
1625 } else {
1626 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1627 MatchesRegex("{\n"
1628 " 1 : 2,\n" // kty: EC2
1629 " 3 : -7,\n" // alg: ES256
1630 " -1 : 1,\n" // EC id: P256
1631 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1632 // sequence of 32 hexadecimal bytes, enclosed in braces and
1633 // separated by commas. In this case, some Ed25519 public key.
1634 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1635 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1636 "}"));
1637 }
1638}
1639
1640} // namespace
1641
1642void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1643 vector<uint8_t>* payload_value) {
1644 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1645 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1646
1647 ASSERT_NE(coseMac0->asArray(), nullptr);
1648 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1649
1650 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1651 ASSERT_NE(protParms, nullptr);
1652
1653 // Header label:value of 'alg': HMAC-256
1654 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1655
1656 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1657 ASSERT_NE(unprotParms, nullptr);
1658 ASSERT_EQ(unprotParms->size(), 0);
1659
1660 // The payload is a bstr holding an encoded COSE_Key
1661 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1662 ASSERT_NE(payload, nullptr);
1663 check_cose_key(payload->value(), testMode);
1664
1665 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1666 ASSERT_TRUE(coseMac0Tag);
1667 auto extractedTag = coseMac0Tag->value();
1668 EXPECT_EQ(extractedTag.size(), 32U);
1669
1670 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001671 auto macFunction = [](const cppcose::bytevec& input) {
1672 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1673 };
1674 auto testTag =
1675 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001676 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1677
1678 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001679 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001680 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001681 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001682 }
1683 if (payload_value != nullptr) {
1684 *payload_value = payload->value();
1685 }
1686}
1687
1688void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1689 // Extract x and y affine coordinates from the encoded Cose_Key.
1690 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1691 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1692 auto coseKey = parsedPayload->asMap();
1693 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1694 ASSERT_NE(xItem->asBstr(), nullptr);
1695 vector<uint8_t> x = xItem->asBstr()->value();
1696 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1697 ASSERT_NE(yItem->asBstr(), nullptr);
1698 vector<uint8_t> y = yItem->asBstr()->value();
1699
1700 // Concatenate: 0x04 (uncompressed form marker) | x | y
1701 vector<uint8_t> pubKeyData{0x04};
1702 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1703 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1704
1705 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1706 ASSERT_NE(ecKey, nullptr);
1707 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1708 ASSERT_NE(group, nullptr);
1709 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1710 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1711 ASSERT_NE(point, nullptr);
1712 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1713 nullptr),
1714 1);
1715 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1716
1717 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1718 ASSERT_NE(pubKey, nullptr);
1719 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1720 *signingKey = std::move(pubKey);
1721}
1722
Selene Huang31ab4042020-04-29 04:22:39 -07001723} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001724
Janis Danisevskis24c04702020-12-16 18:28:39 -08001725} // namespace aidl::android::hardware::security::keymint