blob: 8382781368f9678d85022526398ed2b7a8149a96 [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>
David Drysdale42fe1892021-10-14 14:43:46 +010028#include <openssl/evp.h>
Shawn Willden7c130392020-12-21 09:58:22 -070029#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010030#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070031
Max Bires9704ff62021-04-07 11:12:01 -070032#include <keymaster/cppcose/cppcose.h>
Shawn Willden7c130392020-12-21 09:58:22 -070033#include <keymint_support/attestation_record.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000034#include <keymint_support/key_param_output.h>
35#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070036#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Janis Danisevskis24c04702020-12-16 18:28:39 -080038namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070039
David Drysdale4dc01072021-04-01 12:17:35 +010040using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070041using namespace std::literals::chrono_literals;
42using std::endl;
43using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070044using std::unique_ptr;
45using ::testing::AssertionFailure;
46using ::testing::AssertionResult;
47using ::testing::AssertionSuccess;
Seth Moore026bb742021-04-30 11:41:18 -070048using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010049using ::testing::MatchesRegex;
Seth Moore026bb742021-04-30 11:41:18 -070050using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070051
52::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
53 if (set.size() == 0)
54 os << "(Empty)" << ::std::endl;
55 else {
56 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070057 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070058 }
59 return os;
60}
61
62namespace test {
63
Shawn Willden7f424372021-01-10 18:06:50 -070064namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010065
David Drysdale37af4b32021-05-14 16:46:59 +010066// Invalid value for a patchlevel (which is of form YYYYMMDD).
67const uint32_t kInvalidPatchlevel = 99998877;
68
David Drysdaledf8f52e2021-05-06 08:10:58 +010069// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
70// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
71const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
72
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000073typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070074// Predicate for testing basic characteristics validity in generation or import.
75bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
76 const vector<KeyCharacteristics>& key_characteristics) {
77 if (key_characteristics.empty()) return false;
78
79 std::unordered_set<SecurityLevel> levels_seen;
80 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070081 if (entry.authorizations.empty()) {
82 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
83 return false;
84 }
Shawn Willden7f424372021-01-10 18:06:50 -070085
Qi Wubeefae42021-01-28 23:16:37 +080086 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
87 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
88
Seth Moore2a9a00e2021-08-04 16:31:52 -070089 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
90 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
91 return false;
92 }
Shawn Willden7f424372021-01-10 18:06:50 -070093 levels_seen.insert(entry.securityLevel);
94
95 // Generally, we should only have one entry, at the same security level as the KM
96 // instance. There is an exception: StrongBox KM can have some authorizations that are
97 // enforced by the TEE.
98 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
99 (secLevel == SecurityLevel::STRONGBOX &&
100 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
101
Seth Moore2a9a00e2021-08-04 16:31:52 -0700102 if (!isExpectedSecurityLevel) {
103 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
104 return false;
105 }
Shawn Willden7f424372021-01-10 18:06:50 -0700106 }
107 return true;
108}
109
Shawn Willden7c130392020-12-21 09:58:22 -0700110// Extract attestation record from cert. Returned object is still part of cert; don't free it
111// separately.
112ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
113 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
114 EXPECT_TRUE(!!oid.get());
115 if (!oid.get()) return nullptr;
116
117 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
118 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
119 if (location == -1) return nullptr;
120
121 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
122 EXPECT_TRUE(!!attest_rec_ext)
123 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
124 if (!attest_rec_ext) return nullptr;
125
126 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
127 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
128 return attest_rec;
129}
130
David Drysdale7dff4fc2021-12-10 10:10:52 +0000131void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
132 // Version numbers in attestation extensions should be a multiple of 100.
133 EXPECT_EQ(attestation_version % 100, 0);
134
135 // The multiplier should never be higher than the AIDL version, but can be less
136 // (for example, if the implementation is from an earlier version but the HAL service
137 // uses the default libraries and so reports the current AIDL version).
138 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
139}
140
Shawn Willden7c130392020-12-21 09:58:22 -0700141bool avb_verification_enabled() {
142 char value[PROPERTY_VALUE_MAX];
143 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
144}
145
146char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
147 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
148
149// Attestations don't contain everything in key authorization lists, so we need to filter the key
150// lists to produce the lists that we expect to match the attestations.
151auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100152 Tag::CREATION_DATETIME,
153 Tag::HARDWARE_TYPE,
154 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700155};
156
157AuthorizationSet filtered_tags(const AuthorizationSet& set) {
158 AuthorizationSet filtered;
159 std::remove_copy_if(
160 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
161 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
162 kTagsToFilter.end();
163 });
164 return filtered;
165}
166
David Drysdale300b5552021-05-20 12:05:26 +0100167// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
168void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
169 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
170 [](const auto& entry) {
171 return entry.securityLevel == SecurityLevel::KEYSTORE;
172 }),
173 characteristics->end());
174}
175
Shawn Willden7c130392020-12-21 09:58:22 -0700176string x509NameToStr(X509_NAME* name) {
177 char* s = X509_NAME_oneline(name, nullptr, 0);
178 string retval(s);
179 OPENSSL_free(s);
180 return retval;
181}
182
Shawn Willden7f424372021-01-10 18:06:50 -0700183} // namespace
184
Shawn Willden7c130392020-12-21 09:58:22 -0700185bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
186bool KeyMintAidlTestBase::dump_Attestations = false;
187
David Drysdale37af4b32021-05-14 16:46:59 +0100188uint32_t KeyMintAidlTestBase::boot_patch_level(
189 const vector<KeyCharacteristics>& key_characteristics) {
190 // The boot patchlevel is not available as a property, but should be present
191 // in the key characteristics of any created key.
192 AuthorizationSet allAuths;
193 for (auto& entry : key_characteristics) {
194 allAuths.push_back(AuthorizationSet(entry.authorizations));
195 }
196 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
197 if (patchlevel.has_value()) {
198 return patchlevel.value();
199 } else {
200 // No boot patchlevel is available. Return a value that won't match anything
201 // and so will trigger test failures.
202 return kInvalidPatchlevel;
203 }
204}
205
206uint32_t KeyMintAidlTestBase::boot_patch_level() {
207 return boot_patch_level(key_characteristics_);
208}
209
David Drysdale42fe1892021-10-14 14:43:46 +0100210bool KeyMintAidlTestBase::Curve25519Supported() {
211 // Strongbox never supports curve 25519.
212 if (SecLevel() == SecurityLevel::STRONGBOX) {
213 return false;
214 }
215
216 // Curve 25519 was included in version 2 of the KeyMint interface.
217 int32_t version = 0;
218 auto status = keymint_->getInterfaceVersion(&version);
219 if (!status.isOk()) {
220 ADD_FAILURE() << "Failed to determine interface version";
221 }
222 return version >= 2;
223}
224
Janis Danisevskis24c04702020-12-16 18:28:39 -0800225ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700226 if (result.isOk()) return ErrorCode::OK;
227
Janis Danisevskis24c04702020-12-16 18:28:39 -0800228 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
229 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700230 }
231
232 return ErrorCode::UNKNOWN_ERROR;
233}
234
Janis Danisevskis24c04702020-12-16 18:28:39 -0800235void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700236 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800237 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700238
239 KeyMintHardwareInfo info;
240 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
241
242 securityLevel_ = info.securityLevel;
243 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
244 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100245 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700246
247 os_version_ = getOsVersion();
248 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100249 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700250}
251
David Drysdale7dff4fc2021-12-10 10:10:52 +0000252int32_t KeyMintAidlTestBase::AidlVersion() {
253 int32_t version = 0;
254 auto status = keymint_->getInterfaceVersion(&version);
255 if (!status.isOk()) {
256 ADD_FAILURE() << "Failed to determine interface version";
257 }
258 return version;
259}
260
Selene Huang31ab4042020-04-29 04:22:39 -0700261void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800262 if (AServiceManager_isDeclared(GetParam().c_str())) {
263 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
264 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
265 } else {
266 InitializeKeyMint(nullptr);
267 }
Selene Huang31ab4042020-04-29 04:22:39 -0700268}
269
270ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700271 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700272 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700273 vector<KeyCharacteristics>* key_characteristics,
274 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700275 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
276 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700277 << "Previous characteristics not deleted before generating key. Test bug.";
278
Shawn Willden7f424372021-01-10 18:06:50 -0700279 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700280 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700281 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700282 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
283 creationResult.keyCharacteristics);
284 EXPECT_GT(creationResult.keyBlob.size(), 0);
285 *key_blob = std::move(creationResult.keyBlob);
286 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700287 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700288
289 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
290 EXPECT_TRUE(algorithm);
291 if (algorithm &&
292 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700293 EXPECT_GE(cert_chain->size(), 1);
294 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
295 if (attest_key) {
296 EXPECT_EQ(cert_chain->size(), 1);
297 } else {
298 EXPECT_GT(cert_chain->size(), 1);
299 }
300 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700301 } else {
302 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700303 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700304 }
Selene Huang31ab4042020-04-29 04:22:39 -0700305 }
306
307 return GetReturnErrorCode(result);
308}
309
Shawn Willden7c130392020-12-21 09:58:22 -0700310ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
311 const optional<AttestationKey>& attest_key) {
312 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700313}
314
315ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
316 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700317 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700318 Status result;
319
Shawn Willden7f424372021-01-10 18:06:50 -0700320 cert_chain_.clear();
321 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700322 key_blob->clear();
323
Shawn Willden7f424372021-01-10 18:06:50 -0700324 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700325 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700326 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700327 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700328
329 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700330 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
331 creationResult.keyCharacteristics);
332 EXPECT_GT(creationResult.keyBlob.size(), 0);
333
334 *key_blob = std::move(creationResult.keyBlob);
335 *key_characteristics = std::move(creationResult.keyCharacteristics);
336 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700337
338 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
339 EXPECT_TRUE(algorithm);
340 if (algorithm &&
341 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
342 EXPECT_GE(cert_chain_.size(), 1);
343 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
344 } else {
345 // For symmetric keys there should be no certificates.
346 EXPECT_EQ(cert_chain_.size(), 0);
347 }
Selene Huang31ab4042020-04-29 04:22:39 -0700348 }
349
350 return GetReturnErrorCode(result);
351}
352
353ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
354 const string& key_material) {
355 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
356}
357
358ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
359 const AuthorizationSet& wrapping_key_desc,
360 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100361 const AuthorizationSet& unwrapping_params,
362 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700363 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
364
Shawn Willden7f424372021-01-10 18:06:50 -0700365 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700366
Shawn Willden7f424372021-01-10 18:06:50 -0700367 KeyCreationResult creationResult;
368 Status result = keymint_->importWrappedKey(
369 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
370 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100371 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700372
373 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700374 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
375 creationResult.keyCharacteristics);
376 EXPECT_GT(creationResult.keyBlob.size(), 0);
377
378 key_blob_ = std::move(creationResult.keyBlob);
379 key_characteristics_ = std::move(creationResult.keyCharacteristics);
380 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700381
382 AuthorizationSet allAuths;
383 for (auto& entry : key_characteristics_) {
384 allAuths.push_back(AuthorizationSet(entry.authorizations));
385 }
386 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
387 EXPECT_TRUE(algorithm);
388 if (algorithm &&
389 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
390 EXPECT_GE(cert_chain_.size(), 1);
391 } else {
392 // For symmetric keys there should be no certificates.
393 EXPECT_EQ(cert_chain_.size(), 0);
394 }
Selene Huang31ab4042020-04-29 04:22:39 -0700395 }
396
397 return GetReturnErrorCode(result);
398}
399
David Drysdale300b5552021-05-20 12:05:26 +0100400ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
401 const vector<uint8_t>& app_id,
402 const vector<uint8_t>& app_data,
403 vector<KeyCharacteristics>* key_characteristics) {
404 Status result =
405 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
406 return GetReturnErrorCode(result);
407}
408
409ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
410 vector<KeyCharacteristics>* key_characteristics) {
411 vector<uint8_t> empty_app_id, empty_app_data;
412 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
413}
414
415void KeyMintAidlTestBase::CheckCharacteristics(
416 const vector<uint8_t>& key_blob,
417 const vector<KeyCharacteristics>& generate_characteristics) {
418 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
419 // generateKey() should be excluded, as KeyMint will have no record of them.
420 // This applies to CREATION_DATETIME in particular.
421 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
422 strip_keystore_tags(&expected_characteristics);
423
424 vector<KeyCharacteristics> retrieved;
425 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
426 EXPECT_EQ(expected_characteristics, retrieved);
427}
428
429void KeyMintAidlTestBase::CheckAppIdCharacteristics(
430 const vector<uint8_t>& key_blob, std::string_view app_id_string,
431 std::string_view app_data_string,
432 const vector<KeyCharacteristics>& generate_characteristics) {
433 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
434 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
435 strip_keystore_tags(&expected_characteristics);
436
437 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
438 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
439 vector<KeyCharacteristics> retrieved;
440 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
441 EXPECT_EQ(expected_characteristics, retrieved);
442
443 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
444 vector<uint8_t> empty;
445 vector<KeyCharacteristics> not_retrieved;
446 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
447 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
448 EXPECT_EQ(not_retrieved.size(), 0);
449
450 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
451 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
452 EXPECT_EQ(not_retrieved.size(), 0);
453
454 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
455 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
456 EXPECT_EQ(not_retrieved.size(), 0);
457}
458
Selene Huang31ab4042020-04-29 04:22:39 -0700459ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
460 Status result = keymint_->deleteKey(*key_blob);
461 if (!keep_key_blob) {
462 *key_blob = vector<uint8_t>();
463 }
464
Janis Danisevskis24c04702020-12-16 18:28:39 -0800465 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700466 return GetReturnErrorCode(result);
467}
468
469ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
470 return DeleteKey(&key_blob_, keep_key_blob);
471}
472
473ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
474 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800475 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700476 return GetReturnErrorCode(result);
477}
478
David Drysdaled2cc8c22021-04-15 13:29:45 +0100479ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
480 Status result = keymint_->destroyAttestationIds();
481 return GetReturnErrorCode(result);
482}
483
Selene Huang31ab4042020-04-29 04:22:39 -0700484void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
485 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
486 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
487}
488
489void KeyMintAidlTestBase::CheckedDeleteKey() {
490 CheckedDeleteKey(&key_blob_);
491}
492
493ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
494 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800495 AuthorizationSet* out_params,
496 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700497 SCOPED_TRACE("Begin");
498 Status result;
499 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100500 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700501
502 if (result.isOk()) {
503 *out_params = out.params;
504 challenge_ = out.challenge;
505 op = out.operation;
506 }
507
508 return GetReturnErrorCode(result);
509}
510
511ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
512 const AuthorizationSet& in_params,
513 AuthorizationSet* out_params) {
514 SCOPED_TRACE("Begin");
515 Status result;
516 BeginResult out;
517
David Drysdale56ba9122021-04-19 19:10:47 +0100518 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700519
520 if (result.isOk()) {
521 *out_params = out.params;
522 challenge_ = out.challenge;
523 op_ = out.operation;
524 }
525
526 return GetReturnErrorCode(result);
527}
528
529ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
530 AuthorizationSet* out_params) {
531 SCOPED_TRACE("Begin");
532 EXPECT_EQ(nullptr, op_);
533 return Begin(purpose, key_blob_, in_params, out_params);
534}
535
536ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
537 SCOPED_TRACE("Begin");
538 AuthorizationSet out_params;
539 ErrorCode result = Begin(purpose, in_params, &out_params);
540 EXPECT_TRUE(out_params.empty());
541 return result;
542}
543
Shawn Willden92d79c02021-02-19 07:31:55 -0700544ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
545 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
546 {} /* hardwareAuthToken */,
547 {} /* verificationToken */));
548}
549
550ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700551 SCOPED_TRACE("Update");
552
553 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700554 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700555
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800556 EXPECT_NE(op_, nullptr);
557 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
558
Shawn Willden92d79c02021-02-19 07:31:55 -0700559 std::vector<uint8_t> o_put;
560 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700561
Shawn Willden92d79c02021-02-19 07:31:55 -0700562 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700563
564 return GetReturnErrorCode(result);
565}
566
Shawn Willden92d79c02021-02-19 07:31:55 -0700567ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700568 string* output) {
569 SCOPED_TRACE("Finish");
570 Status result;
571
572 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700573 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700574
575 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700576 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
577 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
578 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700579
Shawn Willden92d79c02021-02-19 07:31:55 -0700580 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700581
Shawn Willden92d79c02021-02-19 07:31:55 -0700582 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700583 return GetReturnErrorCode(result);
584}
585
Janis Danisevskis24c04702020-12-16 18:28:39 -0800586ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700587 SCOPED_TRACE("Abort");
588
589 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700590 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700591
592 Status retval = op->abort();
593 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800594 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700595}
596
597ErrorCode KeyMintAidlTestBase::Abort() {
598 SCOPED_TRACE("Abort");
599
600 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700601 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700602
603 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800604 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700605}
606
607void KeyMintAidlTestBase::AbortIfNeeded() {
608 SCOPED_TRACE("AbortIfNeeded");
609 if (op_) {
610 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800611 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700612 }
613}
614
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000615auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
616 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700617 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000618 AuthorizationSet begin_out_params;
619 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700620 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000621
622 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700623 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000624}
625
Selene Huang31ab4042020-04-29 04:22:39 -0700626string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
627 const string& message, const AuthorizationSet& in_params,
628 AuthorizationSet* out_params) {
629 SCOPED_TRACE("ProcessMessage");
630 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700631 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700632 EXPECT_EQ(ErrorCode::OK, result);
633 if (result != ErrorCode::OK) {
634 return "";
635 }
636
637 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700638 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700639 return output;
640}
641
642string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
643 const AuthorizationSet& params) {
644 SCOPED_TRACE("SignMessage");
645 AuthorizationSet out_params;
646 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
647 EXPECT_TRUE(out_params.empty());
648 return signature;
649}
650
651string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
652 SCOPED_TRACE("SignMessage");
653 return SignMessage(key_blob_, message, params);
654}
655
656string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
657 SCOPED_TRACE("MacMessage");
658 return SignMessage(
659 key_blob_, message,
660 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
661}
662
663void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
664 Digest digest, const string& expected_mac) {
665 SCOPED_TRACE("CheckHmacTestVector");
666 ASSERT_EQ(ErrorCode::OK,
667 ImportKey(AuthorizationSetBuilder()
668 .Authorization(TAG_NO_AUTH_REQUIRED)
669 .HmacKey(key.size() * 8)
670 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
671 .Digest(digest),
672 KeyFormat::RAW, key));
673 string signature = MacMessage(message, digest, expected_mac.size() * 8);
674 EXPECT_EQ(expected_mac, signature)
675 << "Test vector didn't match for key of size " << key.size() << " message of size "
676 << message.size() << " and digest " << digest;
677 CheckedDeleteKey();
678}
679
680void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
681 const string& message,
682 const string& expected_ciphertext) {
683 SCOPED_TRACE("CheckAesCtrTestVector");
684 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
685 .Authorization(TAG_NO_AUTH_REQUIRED)
686 .AesEncryptionKey(key.size() * 8)
687 .BlockMode(BlockMode::CTR)
688 .Authorization(TAG_CALLER_NONCE)
689 .Padding(PaddingMode::NONE),
690 KeyFormat::RAW, key));
691
692 auto params = AuthorizationSetBuilder()
693 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
694 .BlockMode(BlockMode::CTR)
695 .Padding(PaddingMode::NONE);
696 AuthorizationSet out_params;
697 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
698 EXPECT_EQ(expected_ciphertext, ciphertext);
699}
700
701void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
702 PaddingMode padding_mode, const string& key,
703 const string& iv, const string& input,
704 const string& expected_output) {
705 auto authset = AuthorizationSetBuilder()
706 .TripleDesEncryptionKey(key.size() * 7)
707 .BlockMode(block_mode)
708 .Authorization(TAG_NO_AUTH_REQUIRED)
709 .Padding(padding_mode);
710 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
711 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
712 ASSERT_GT(key_blob_.size(), 0U);
713
714 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
715 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
716 AuthorizationSet output_params;
717 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
718 EXPECT_EQ(expected_output, output);
719}
720
721void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
722 const string& signature, const AuthorizationSet& params) {
723 SCOPED_TRACE("VerifyMessage");
724 AuthorizationSet begin_out_params;
725 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
726
727 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700728 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700729 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700730 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700731}
732
733void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
734 const AuthorizationSet& params) {
735 SCOPED_TRACE("VerifyMessage");
736 VerifyMessage(key_blob_, message, signature, params);
737}
738
David Drysdaledf8f52e2021-05-06 08:10:58 +0100739void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
740 const AuthorizationSet& params) {
741 SCOPED_TRACE("LocalVerifyMessage");
742
743 // Retrieve the public key from the leaf certificate.
744 ASSERT_GT(cert_chain_.size(), 0);
745 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
746 ASSERT_TRUE(key_cert.get());
747 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
748 ASSERT_TRUE(pub_key.get());
749
750 Digest digest = params.GetTagValue(TAG_DIGEST).value();
751 PaddingMode padding = PaddingMode::NONE;
752 auto tag = params.GetTagValue(TAG_PADDING);
753 if (tag.has_value()) {
754 padding = tag.value();
755 }
756
757 if (digest == Digest::NONE) {
758 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100759 case EVP_PKEY_ED25519: {
760 ASSERT_EQ(64, signature.size());
761 uint8_t pub_keydata[32];
762 size_t pub_len = sizeof(pub_keydata);
763 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
764 ASSERT_EQ(sizeof(pub_keydata), pub_len);
765 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
766 message.size(),
767 reinterpret_cast<const uint8_t*>(signature.data()),
768 pub_keydata));
769 break;
770 }
771
David Drysdaledf8f52e2021-05-06 08:10:58 +0100772 case EVP_PKEY_EC: {
773 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
774 size_t data_size = std::min(data.size(), message.size());
775 memcpy(data.data(), message.data(), data_size);
776 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
777 ASSERT_TRUE(ecdsa.get());
778 ASSERT_EQ(1,
779 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
780 reinterpret_cast<const uint8_t*>(signature.data()),
781 signature.size(), ecdsa.get()));
782 break;
783 }
784 case EVP_PKEY_RSA: {
785 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
786 size_t data_size = std::min(data.size(), message.size());
787 memcpy(data.data(), message.data(), data_size);
788
789 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
790 ASSERT_TRUE(rsa.get());
791
792 size_t key_len = RSA_size(rsa.get());
793 int openssl_padding = RSA_NO_PADDING;
794 switch (padding) {
795 case PaddingMode::NONE:
796 ASSERT_TRUE(data_size <= key_len);
797 ASSERT_EQ(key_len, signature.size());
798 openssl_padding = RSA_NO_PADDING;
799 break;
800 case PaddingMode::RSA_PKCS1_1_5_SIGN:
801 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
802 key_len);
803 openssl_padding = RSA_PKCS1_PADDING;
804 break;
805 default:
806 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
807 }
808
809 vector<uint8_t> decrypted_data(key_len);
810 int bytes_decrypted = RSA_public_decrypt(
811 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
812 decrypted_data.data(), rsa.get(), openssl_padding);
813 ASSERT_GE(bytes_decrypted, 0);
814
815 const uint8_t* compare_pos = decrypted_data.data();
816 size_t bytes_to_compare = bytes_decrypted;
817 uint8_t zero_check_result = 0;
818 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
819 // If the data is short, for "unpadded" signing we zero-pad to the left. So
820 // during verification we should have zeros on the left of the decrypted data.
821 // Do a constant-time check.
822 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
823 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
824 ASSERT_EQ(0, zero_check_result);
825 bytes_to_compare = data_size;
826 }
827 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
828 break;
829 }
830 default:
831 ADD_FAILURE() << "Unknown public key type";
832 }
833 } else {
834 EVP_MD_CTX digest_ctx;
835 EVP_MD_CTX_init(&digest_ctx);
836 EVP_PKEY_CTX* pkey_ctx;
837 const EVP_MD* md = openssl_digest(digest);
838 ASSERT_NE(md, nullptr);
839 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
840
841 if (padding == PaddingMode::RSA_PSS) {
842 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
843 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
844 }
845
846 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
847 reinterpret_cast<const uint8_t*>(message.data()),
848 message.size()));
849 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
850 reinterpret_cast<const uint8_t*>(signature.data()),
851 signature.size()));
852 EVP_MD_CTX_cleanup(&digest_ctx);
853 }
854}
855
David Drysdale59cae642021-05-12 13:52:03 +0100856string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
857 const AuthorizationSet& params) {
858 SCOPED_TRACE("LocalRsaEncryptMessage");
859
860 // Retrieve the public key from the leaf certificate.
861 if (cert_chain_.empty()) {
862 ADD_FAILURE() << "No public key available";
863 return "Failure";
864 }
865 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
866 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
867 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
868
869 // Retrieve relevant tags.
870 Digest digest = Digest::NONE;
871 Digest mgf_digest = Digest::NONE;
872 PaddingMode padding = PaddingMode::NONE;
873
874 auto digest_tag = params.GetTagValue(TAG_DIGEST);
875 if (digest_tag.has_value()) digest = digest_tag.value();
876 auto pad_tag = params.GetTagValue(TAG_PADDING);
877 if (pad_tag.has_value()) padding = pad_tag.value();
878 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
879 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
880
881 const EVP_MD* md = openssl_digest(digest);
882 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
883
884 // Set up encryption context.
885 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
886 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
887 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
888 return "Failure";
889 }
890
891 int rc = -1;
892 switch (padding) {
893 case PaddingMode::NONE:
894 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
895 break;
896 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
897 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
898 break;
899 case PaddingMode::RSA_OAEP:
900 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
901 break;
902 default:
903 break;
904 }
905 if (rc <= 0) {
906 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
907 return "Failure";
908 }
909 if (padding == PaddingMode::RSA_OAEP) {
910 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
911 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
912 return "Failure";
913 }
914 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
915 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
916 return "Failure";
917 }
918 }
919
920 // Determine output size.
921 size_t outlen;
922 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
923 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
924 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
925 return "Failure";
926 }
927
928 // Left-zero-pad the input if necessary.
929 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
930 size_t to_encrypt_len = message.size();
931
932 std::unique_ptr<string> zero_padded_message;
933 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
934 zero_padded_message.reset(new string(outlen, '\0'));
935 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
936 message.size());
937 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
938 to_encrypt_len = outlen;
939 }
940
941 // Do the encryption.
942 string output(outlen, '\0');
943 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
944 to_encrypt_len) <= 0) {
945 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
946 return "Failure";
947 }
948 return output;
949}
950
Selene Huang31ab4042020-04-29 04:22:39 -0700951string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
952 const AuthorizationSet& in_params,
953 AuthorizationSet* out_params) {
954 SCOPED_TRACE("EncryptMessage");
955 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
956}
957
958string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
959 AuthorizationSet* out_params) {
960 SCOPED_TRACE("EncryptMessage");
961 return EncryptMessage(key_blob_, message, params, out_params);
962}
963
964string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
965 SCOPED_TRACE("EncryptMessage");
966 AuthorizationSet out_params;
967 string ciphertext = EncryptMessage(message, params, &out_params);
968 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
969 return ciphertext;
970}
971
972string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
973 PaddingMode padding) {
974 SCOPED_TRACE("EncryptMessage");
975 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
976 AuthorizationSet out_params;
977 string ciphertext = EncryptMessage(message, params, &out_params);
978 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
979 return ciphertext;
980}
981
982string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
983 PaddingMode padding, vector<uint8_t>* iv_out) {
984 SCOPED_TRACE("EncryptMessage");
985 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
986 AuthorizationSet out_params;
987 string ciphertext = EncryptMessage(message, params, &out_params);
988 EXPECT_EQ(1U, out_params.size());
989 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800990 EXPECT_TRUE(ivVal);
991 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700992 return ciphertext;
993}
994
995string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
996 PaddingMode padding, const vector<uint8_t>& iv_in) {
997 SCOPED_TRACE("EncryptMessage");
998 auto params = AuthorizationSetBuilder()
999 .BlockMode(block_mode)
1000 .Padding(padding)
1001 .Authorization(TAG_NONCE, iv_in);
1002 AuthorizationSet out_params;
1003 string ciphertext = EncryptMessage(message, params, &out_params);
1004 return ciphertext;
1005}
1006
1007string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1008 PaddingMode padding, uint8_t mac_length_bits,
1009 const vector<uint8_t>& iv_in) {
1010 SCOPED_TRACE("EncryptMessage");
1011 auto params = AuthorizationSetBuilder()
1012 .BlockMode(block_mode)
1013 .Padding(padding)
1014 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1015 .Authorization(TAG_NONCE, iv_in);
1016 AuthorizationSet out_params;
1017 string ciphertext = EncryptMessage(message, params, &out_params);
1018 return ciphertext;
1019}
1020
David Drysdaled2cc8c22021-04-15 13:29:45 +01001021string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1022 PaddingMode padding, uint8_t mac_length_bits) {
1023 SCOPED_TRACE("EncryptMessage");
1024 auto params = AuthorizationSetBuilder()
1025 .BlockMode(block_mode)
1026 .Padding(padding)
1027 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1028 AuthorizationSet out_params;
1029 string ciphertext = EncryptMessage(message, params, &out_params);
1030 return ciphertext;
1031}
1032
Selene Huang31ab4042020-04-29 04:22:39 -07001033string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1034 const string& ciphertext,
1035 const AuthorizationSet& params) {
1036 SCOPED_TRACE("DecryptMessage");
1037 AuthorizationSet out_params;
1038 string plaintext =
1039 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1040 EXPECT_TRUE(out_params.empty());
1041 return plaintext;
1042}
1043
1044string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1045 const AuthorizationSet& params) {
1046 SCOPED_TRACE("DecryptMessage");
1047 return DecryptMessage(key_blob_, ciphertext, params);
1048}
1049
1050string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1051 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1052 SCOPED_TRACE("DecryptMessage");
1053 auto params = AuthorizationSetBuilder()
1054 .BlockMode(block_mode)
1055 .Padding(padding_mode)
1056 .Authorization(TAG_NONCE, iv);
1057 return DecryptMessage(key_blob_, ciphertext, params);
1058}
1059
1060std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1061 const vector<uint8_t>& key_blob) {
1062 std::pair<ErrorCode, vector<uint8_t>> retval;
1063 vector<uint8_t> outKeyBlob;
1064 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1065 ErrorCode errorcode = GetReturnErrorCode(result);
1066 retval = std::tie(errorcode, outKeyBlob);
1067
1068 return retval;
1069}
1070vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1071 switch (algorithm) {
1072 case Algorithm::RSA:
1073 switch (SecLevel()) {
1074 case SecurityLevel::SOFTWARE:
1075 case SecurityLevel::TRUSTED_ENVIRONMENT:
1076 return {2048, 3072, 4096};
1077 case SecurityLevel::STRONGBOX:
1078 return {2048};
1079 default:
1080 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1081 break;
1082 }
1083 break;
1084 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001085 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001086 break;
1087 case Algorithm::AES:
1088 return {128, 256};
1089 case Algorithm::TRIPLE_DES:
1090 return {168};
1091 case Algorithm::HMAC: {
1092 vector<uint32_t> retval((512 - 64) / 8 + 1);
1093 uint32_t size = 64 - 8;
1094 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1095 return retval;
1096 }
1097 default:
1098 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1099 return {};
1100 }
1101 ADD_FAILURE() << "Should be impossible to get here";
1102 return {};
1103}
1104
1105vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1106 if (SecLevel() == SecurityLevel::STRONGBOX) {
1107 switch (algorithm) {
1108 case Algorithm::RSA:
1109 return {3072, 4096};
1110 case Algorithm::EC:
1111 return {224, 384, 521};
1112 case Algorithm::AES:
1113 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001114 case Algorithm::TRIPLE_DES:
1115 return {56};
1116 default:
1117 return {};
1118 }
1119 } else {
1120 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001121 case Algorithm::AES:
1122 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001123 case Algorithm::TRIPLE_DES:
1124 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001125 default:
1126 return {};
1127 }
1128 }
1129 return {};
1130}
1131
David Drysdale7de9feb2021-03-05 14:56:19 +00001132vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1133 switch (algorithm) {
1134 case Algorithm::AES:
1135 return {
1136 BlockMode::CBC,
1137 BlockMode::CTR,
1138 BlockMode::ECB,
1139 BlockMode::GCM,
1140 };
1141 case Algorithm::TRIPLE_DES:
1142 return {
1143 BlockMode::CBC,
1144 BlockMode::ECB,
1145 };
1146 default:
1147 return {};
1148 }
1149}
1150
1151vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1152 BlockMode blockMode) {
1153 switch (algorithm) {
1154 case Algorithm::AES:
1155 switch (blockMode) {
1156 case BlockMode::CBC:
1157 case BlockMode::ECB:
1158 return {PaddingMode::NONE, PaddingMode::PKCS7};
1159 case BlockMode::CTR:
1160 case BlockMode::GCM:
1161 return {PaddingMode::NONE};
1162 default:
1163 return {};
1164 };
1165 case Algorithm::TRIPLE_DES:
1166 switch (blockMode) {
1167 case BlockMode::CBC:
1168 case BlockMode::ECB:
1169 return {PaddingMode::NONE, PaddingMode::PKCS7};
1170 default:
1171 return {};
1172 };
1173 default:
1174 return {};
1175 }
1176}
1177
1178vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1179 BlockMode blockMode) {
1180 switch (algorithm) {
1181 case Algorithm::AES:
1182 switch (blockMode) {
1183 case BlockMode::CTR:
1184 case BlockMode::GCM:
1185 return {PaddingMode::PKCS7};
1186 default:
1187 return {};
1188 };
1189 default:
1190 return {};
1191 }
1192}
1193
Selene Huang31ab4042020-04-29 04:22:39 -07001194vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1195 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1196 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001197 } else if (Curve25519Supported()) {
1198 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1199 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001200 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001201 return {
1202 EcCurve::P_224,
1203 EcCurve::P_256,
1204 EcCurve::P_384,
1205 EcCurve::P_521,
1206 };
Selene Huang31ab4042020-04-29 04:22:39 -07001207 }
1208}
1209
1210vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001211 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001212 // Curve 25519 is not supported, either because:
1213 // - KeyMint v1: it's an unknown enum value
1214 // - KeyMint v2+: it's not supported by StrongBox.
1215 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001216 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001217 if (Curve25519Supported()) {
1218 return {};
1219 } else {
1220 return {EcCurve::CURVE_25519};
1221 }
David Drysdaledf09e542021-06-08 15:46:11 +01001222 }
Selene Huang31ab4042020-04-29 04:22:39 -07001223}
1224
1225vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1226 switch (SecLevel()) {
1227 case SecurityLevel::SOFTWARE:
1228 case SecurityLevel::TRUSTED_ENVIRONMENT:
1229 if (withNone) {
1230 if (withMD5)
1231 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1232 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1233 Digest::SHA_2_512};
1234 else
1235 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1236 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1237 } else {
1238 if (withMD5)
1239 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1240 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1241 else
1242 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1243 Digest::SHA_2_512};
1244 }
1245 break;
1246 case SecurityLevel::STRONGBOX:
1247 if (withNone)
1248 return {Digest::NONE, Digest::SHA_2_256};
1249 else
1250 return {Digest::SHA_2_256};
1251 break;
1252 default:
1253 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1254 break;
1255 }
1256 ADD_FAILURE() << "Should be impossible to get here";
1257 return {};
1258}
1259
Shawn Willden7f424372021-01-10 18:06:50 -07001260static const vector<KeyParameter> kEmptyAuthList{};
1261
1262const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1263 const vector<KeyCharacteristics>& key_characteristics) {
1264 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1265 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1266 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1267}
1268
Qi Wubeefae42021-01-28 23:16:37 +08001269const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1270 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1271 auto found = std::find_if(
1272 key_characteristics.begin(), key_characteristics.end(),
1273 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001274 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1275}
1276
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001277ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001278 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001279 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1280 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1281 return result;
1282}
1283
1284ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001285 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001286 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1287 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1288 return result;
1289}
1290
1291ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1292 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001293 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001294 rsaKeyBlob, KeyPurpose::SIGN, message,
1295 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1296 return result;
1297}
1298
1299ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001300 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1301 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001302 return result;
1303}
1304
Selene Huang6e46f142021-04-20 19:20:11 -07001305void verify_serial(X509* cert, const uint64_t expected_serial) {
1306 BIGNUM_Ptr ser(BN_new());
1307 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1308
1309 uint64_t serial;
1310 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1311 EXPECT_EQ(serial, expected_serial);
1312}
1313
1314// Please set self_signed to true for fake certificates or self signed
1315// certificates
1316void verify_subject(const X509* cert, //
1317 const string& subject, //
1318 bool self_signed) {
1319 char* cert_issuer = //
1320 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1321
1322 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1323
1324 string expected_subject("/CN=");
1325 if (subject.empty()) {
1326 expected_subject.append("Android Keystore Key");
1327 } else {
1328 expected_subject.append(subject);
1329 }
1330
1331 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1332
1333 if (self_signed) {
1334 EXPECT_STREQ(cert_issuer, cert_subj)
1335 << "Cert issuer and subject mismatch for self signed certificate.";
1336 }
1337
1338 OPENSSL_free(cert_subj);
1339 OPENSSL_free(cert_issuer);
1340}
1341
1342vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1343 BIGNUM_Ptr serial(BN_new());
1344 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1345
1346 int len = BN_num_bytes(serial.get());
1347 vector<uint8_t> serial_blob(len);
1348 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1349 return {};
1350 }
1351
David Drysdaledb0dcf52021-05-18 11:43:31 +01001352 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1353 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1354 // Top bit being set indicates a negative number in two's complement, but our input
1355 // was positive.
1356 // In either case, prepend a zero byte.
1357 serial_blob.insert(serial_blob.begin(), 0x00);
1358 }
1359
Selene Huang6e46f142021-04-20 19:20:11 -07001360 return serial_blob;
1361}
1362
1363void verify_subject_and_serial(const Certificate& certificate, //
1364 const uint64_t expected_serial, //
1365 const string& subject, bool self_signed) {
1366 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1367 ASSERT_TRUE(!!cert.get());
1368
1369 verify_serial(cert.get(), expected_serial);
1370 verify_subject(cert.get(), subject, self_signed);
1371}
1372
David Drysdale7dff4fc2021-12-10 10:10:52 +00001373bool verify_attestation_record(int32_t aidl_version, //
1374 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001375 const string& app_id, //
1376 AuthorizationSet expected_sw_enforced, //
1377 AuthorizationSet expected_hw_enforced, //
1378 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001379 const vector<uint8_t>& attestation_cert,
1380 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001381 X509_Ptr cert(parse_cert_blob(attestation_cert));
1382 EXPECT_TRUE(!!cert.get());
1383 if (!cert.get()) return false;
1384
1385 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1386 EXPECT_TRUE(!!attest_rec);
1387 if (!attest_rec) return false;
1388
1389 AuthorizationSet att_sw_enforced;
1390 AuthorizationSet att_hw_enforced;
1391 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001392 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001393 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001394 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001395 vector<uint8_t> att_challenge;
1396 vector<uint8_t> att_unique_id;
1397 vector<uint8_t> att_app_id;
1398
1399 auto error = parse_attestation_record(attest_rec->data, //
1400 attest_rec->length, //
1401 &att_attestation_version, //
1402 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001403 &att_keymint_version, //
1404 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001405 &att_challenge, //
1406 &att_sw_enforced, //
1407 &att_hw_enforced, //
1408 &att_unique_id);
1409 EXPECT_EQ(ErrorCode::OK, error);
1410 if (error != ErrorCode::OK) return false;
1411
David Drysdale7dff4fc2021-12-10 10:10:52 +00001412 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001413 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001414
Selene Huang4f64c222021-04-13 19:54:36 -07001415 // check challenge and app id only if we expects a non-fake certificate
1416 if (challenge.length() > 0) {
1417 EXPECT_EQ(challenge.length(), att_challenge.size());
1418 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1419
1420 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1421 }
Shawn Willden7c130392020-12-21 09:58:22 -07001422
David Drysdale7dff4fc2021-12-10 10:10:52 +00001423 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001424 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001425 EXPECT_EQ(security_level, att_attestation_security_level);
1426
Shawn Willden7c130392020-12-21 09:58:22 -07001427
1428 char property_value[PROPERTY_VALUE_MAX] = {};
1429 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001430 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001431 // for the BOOT_PATCH_LEVEL.
1432 if (avb_verification_enabled()) {
1433 for (int i = 0; i < att_hw_enforced.size(); i++) {
1434 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1435 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1436 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001437 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001438
Shawn Willden7c130392020-12-21 09:58:22 -07001439 // strptime seems to require delimiters, but the tag value will
1440 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001441 if (date.size() != 8) {
1442 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1443 << " with invalid format (not YYYYMMDD): " << date;
1444 return false;
1445 }
Shawn Willden7c130392020-12-21 09:58:22 -07001446 date.insert(6, "-");
1447 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001448 struct tm time;
1449 strptime(date.c_str(), "%Y-%m-%d", &time);
1450
1451 // Day of the month (0-31)
1452 EXPECT_GE(time.tm_mday, 0);
1453 EXPECT_LT(time.tm_mday, 32);
1454 // Months since Jan (0-11)
1455 EXPECT_GE(time.tm_mon, 0);
1456 EXPECT_LT(time.tm_mon, 12);
1457 // Years since 1900
1458 EXPECT_GT(time.tm_year, 110);
1459 EXPECT_LT(time.tm_year, 200);
1460 }
1461 }
1462 }
1463
1464 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1465 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1466 // indicates correct encoding. No need to check if it's in both lists, since the
1467 // AuthorizationSet compare below will handle mismatches of tags.
1468 if (security_level == SecurityLevel::SOFTWARE) {
1469 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1470 } else {
1471 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1472 }
1473
Shawn Willden7c130392020-12-21 09:58:22 -07001474 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1475 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1476 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1477 att_hw_enforced.Contains(TAG_KEY_SIZE));
1478 }
1479
1480 // Test root of trust elements
1481 vector<uint8_t> verified_boot_key;
1482 VerifiedBoot verified_boot_state;
1483 bool device_locked;
1484 vector<uint8_t> verified_boot_hash;
1485 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1486 &verified_boot_state, &device_locked, &verified_boot_hash);
1487 EXPECT_EQ(ErrorCode::OK, error);
1488
1489 if (avb_verification_enabled()) {
1490 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1491 string prop_string(property_value);
1492 EXPECT_EQ(prop_string.size(), 64);
1493 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1494
1495 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1496 if (!strcmp(property_value, "unlocked")) {
1497 EXPECT_FALSE(device_locked);
1498 } else {
1499 EXPECT_TRUE(device_locked);
1500 }
1501
1502 // Check that the device is locked if not debuggable, e.g., user build
1503 // images in CTS. For VTS, debuggable images are used to allow adb root
1504 // and the device is unlocked.
1505 if (!property_get_bool("ro.debuggable", false)) {
1506 EXPECT_TRUE(device_locked);
1507 } else {
1508 EXPECT_FALSE(device_locked);
1509 }
1510 }
1511
1512 // Verified boot key should be all 0's if the boot state is not verified or self signed
1513 std::string empty_boot_key(32, '\0');
1514 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1515 verified_boot_key.size());
1516 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1517 if (!strcmp(property_value, "green")) {
1518 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1519 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1520 verified_boot_key.size()));
1521 } else if (!strcmp(property_value, "yellow")) {
1522 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1523 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1524 verified_boot_key.size()));
1525 } else if (!strcmp(property_value, "orange")) {
1526 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1527 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1528 verified_boot_key.size()));
1529 } else if (!strcmp(property_value, "red")) {
1530 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1531 } else {
1532 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1533 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1534 verified_boot_key.size()));
1535 }
1536
1537 att_sw_enforced.Sort();
1538 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001539 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001540
1541 att_hw_enforced.Sort();
1542 expected_hw_enforced.Sort();
1543 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1544
David Drysdale565ccc72021-10-11 12:49:50 +01001545 if (unique_id != nullptr) {
1546 *unique_id = att_unique_id;
1547 }
1548
Shawn Willden7c130392020-12-21 09:58:22 -07001549 return true;
1550}
1551
1552string bin2hex(const vector<uint8_t>& data) {
1553 string retval;
1554 retval.reserve(data.size() * 2 + 1);
1555 for (uint8_t byte : data) {
1556 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1557 retval.push_back(nibble2hex[0x0F & byte]);
1558 }
1559 return retval;
1560}
1561
David Drysdalef0d516d2021-03-22 07:51:43 +00001562AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1563 AuthorizationSet authList;
1564 for (auto& entry : key_characteristics) {
1565 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1566 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1567 authList.push_back(AuthorizationSet(entry.authorizations));
1568 }
1569 }
1570 return authList;
1571}
1572
1573AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1574 AuthorizationSet authList;
1575 for (auto& entry : key_characteristics) {
1576 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1577 entry.securityLevel == SecurityLevel::KEYSTORE) {
1578 authList.push_back(AuthorizationSet(entry.authorizations));
1579 }
1580 }
1581 return authList;
1582}
1583
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001584AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1585 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001586 std::stringstream cert_data;
1587
1588 for (size_t i = 0; i < chain.size(); ++i) {
1589 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1590
1591 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1592 X509_Ptr signing_cert;
1593 if (i < chain.size() - 1) {
1594 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1595 } else {
1596 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1597 }
1598 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1599
1600 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1601 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1602
1603 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1604 return AssertionFailure()
1605 << "Verification of certificate " << i << " failed "
1606 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1607 << cert_data.str();
1608 }
1609
1610 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1611 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001612 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001613 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1614 << " Signer subject is " << signer_subj
1615 << " Issuer subject is " << cert_issuer << endl
1616 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001617 }
Shawn Willden7c130392020-12-21 09:58:22 -07001618 }
1619
1620 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1621 return AssertionSuccess();
1622}
1623
1624X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1625 const uint8_t* p = blob.data();
1626 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1627}
1628
David Drysdalef0d516d2021-03-22 07:51:43 +00001629vector<uint8_t> make_name_from_str(const string& name) {
1630 X509_NAME_Ptr x509_name(X509_NAME_new());
1631 EXPECT_TRUE(x509_name.get() != nullptr);
1632 if (!x509_name) return {};
1633
1634 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1635 "CN", //
1636 MBSTRING_ASC,
1637 reinterpret_cast<const uint8_t*>(name.c_str()),
1638 -1, // len
1639 -1, // loc
1640 0 /* set */));
1641
1642 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1643 EXPECT_GT(len, 0);
1644
1645 vector<uint8_t> retval(len);
1646 uint8_t* p = retval.data();
1647 i2d_X509_NAME(x509_name.get(), &p);
1648
1649 return retval;
1650}
1651
David Drysdale4dc01072021-04-01 12:17:35 +01001652namespace {
1653
1654void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1655 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1656 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1657
1658 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1659 if (testMode) {
1660 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1661 MatchesRegex("{\n"
1662 " 1 : 2,\n" // kty: EC2
1663 " 3 : -7,\n" // alg: ES256
1664 " -1 : 1,\n" // EC id: P256
1665 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1666 // sequence of 32 hexadecimal bytes, enclosed in braces and
1667 // separated by commas. In this case, some Ed25519 public key.
1668 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1669 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1670 " -70000 : null,\n" // test marker
1671 "}"));
1672 } else {
1673 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1674 MatchesRegex("{\n"
1675 " 1 : 2,\n" // kty: EC2
1676 " 3 : -7,\n" // alg: ES256
1677 " -1 : 1,\n" // EC id: P256
1678 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1679 // sequence of 32 hexadecimal bytes, enclosed in braces and
1680 // separated by commas. In this case, some Ed25519 public key.
1681 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1682 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1683 "}"));
1684 }
1685}
1686
1687} // namespace
1688
1689void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1690 vector<uint8_t>* payload_value) {
1691 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1692 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1693
1694 ASSERT_NE(coseMac0->asArray(), nullptr);
1695 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1696
1697 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1698 ASSERT_NE(protParms, nullptr);
1699
1700 // Header label:value of 'alg': HMAC-256
1701 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1702
1703 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1704 ASSERT_NE(unprotParms, nullptr);
1705 ASSERT_EQ(unprotParms->size(), 0);
1706
1707 // The payload is a bstr holding an encoded COSE_Key
1708 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1709 ASSERT_NE(payload, nullptr);
1710 check_cose_key(payload->value(), testMode);
1711
1712 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1713 ASSERT_TRUE(coseMac0Tag);
1714 auto extractedTag = coseMac0Tag->value();
1715 EXPECT_EQ(extractedTag.size(), 32U);
1716
1717 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001718 auto macFunction = [](const cppcose::bytevec& input) {
1719 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1720 };
1721 auto testTag =
1722 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001723 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1724
1725 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001726 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001727 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001728 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001729 }
1730 if (payload_value != nullptr) {
1731 *payload_value = payload->value();
1732 }
1733}
1734
1735void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1736 // Extract x and y affine coordinates from the encoded Cose_Key.
1737 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1738 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1739 auto coseKey = parsedPayload->asMap();
1740 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1741 ASSERT_NE(xItem->asBstr(), nullptr);
1742 vector<uint8_t> x = xItem->asBstr()->value();
1743 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1744 ASSERT_NE(yItem->asBstr(), nullptr);
1745 vector<uint8_t> y = yItem->asBstr()->value();
1746
1747 // Concatenate: 0x04 (uncompressed form marker) | x | y
1748 vector<uint8_t> pubKeyData{0x04};
1749 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1750 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1751
1752 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1753 ASSERT_NE(ecKey, nullptr);
1754 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1755 ASSERT_NE(group, nullptr);
1756 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1757 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1758 ASSERT_NE(point, nullptr);
1759 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1760 nullptr),
1761 1);
1762 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1763
1764 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1765 ASSERT_NE(pubKey, nullptr);
1766 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1767 *signingKey = std::move(pubKey);
1768}
1769
Selene Huang31ab4042020-04-29 04:22:39 -07001770} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001771
Janis Danisevskis24c04702020-12-16 18:28:39 -08001772} // namespace aidl::android::hardware::security::keymint