blob: 6140df135040d87c4be4ea8d122e1f59afffb8fa [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
130bool avb_verification_enabled() {
131 char value[PROPERTY_VALUE_MAX];
132 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
133}
134
135char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
136 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
137
138// Attestations don't contain everything in key authorization lists, so we need to filter the key
139// lists to produce the lists that we expect to match the attestations.
140auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100141 Tag::CREATION_DATETIME,
142 Tag::HARDWARE_TYPE,
143 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700144};
145
146AuthorizationSet filtered_tags(const AuthorizationSet& set) {
147 AuthorizationSet filtered;
148 std::remove_copy_if(
149 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
150 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
151 kTagsToFilter.end();
152 });
153 return filtered;
154}
155
David Drysdale300b5552021-05-20 12:05:26 +0100156// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
157void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
158 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
159 [](const auto& entry) {
160 return entry.securityLevel == SecurityLevel::KEYSTORE;
161 }),
162 characteristics->end());
163}
164
Shawn Willden7c130392020-12-21 09:58:22 -0700165string x509NameToStr(X509_NAME* name) {
166 char* s = X509_NAME_oneline(name, nullptr, 0);
167 string retval(s);
168 OPENSSL_free(s);
169 return retval;
170}
171
Shawn Willden7f424372021-01-10 18:06:50 -0700172} // namespace
173
Shawn Willden7c130392020-12-21 09:58:22 -0700174bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
175bool KeyMintAidlTestBase::dump_Attestations = false;
176
David Drysdale37af4b32021-05-14 16:46:59 +0100177uint32_t KeyMintAidlTestBase::boot_patch_level(
178 const vector<KeyCharacteristics>& key_characteristics) {
179 // The boot patchlevel is not available as a property, but should be present
180 // in the key characteristics of any created key.
181 AuthorizationSet allAuths;
182 for (auto& entry : key_characteristics) {
183 allAuths.push_back(AuthorizationSet(entry.authorizations));
184 }
185 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
186 if (patchlevel.has_value()) {
187 return patchlevel.value();
188 } else {
189 // No boot patchlevel is available. Return a value that won't match anything
190 // and so will trigger test failures.
191 return kInvalidPatchlevel;
192 }
193}
194
195uint32_t KeyMintAidlTestBase::boot_patch_level() {
196 return boot_patch_level(key_characteristics_);
197}
198
Janis Danisevskis24c04702020-12-16 18:28:39 -0800199ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700200 if (result.isOk()) return ErrorCode::OK;
201
Janis Danisevskis24c04702020-12-16 18:28:39 -0800202 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
203 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700204 }
205
206 return ErrorCode::UNKNOWN_ERROR;
207}
208
Janis Danisevskis24c04702020-12-16 18:28:39 -0800209void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700210 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800211 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700212
213 KeyMintHardwareInfo info;
214 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
215
216 securityLevel_ = info.securityLevel;
217 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
218 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100219 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700220
221 os_version_ = getOsVersion();
222 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100223 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700224}
225
226void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800227 if (AServiceManager_isDeclared(GetParam().c_str())) {
228 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
229 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
230 } else {
231 InitializeKeyMint(nullptr);
232 }
Selene Huang31ab4042020-04-29 04:22:39 -0700233}
234
235ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700236 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700237 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700238 vector<KeyCharacteristics>* key_characteristics,
239 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700240 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
241 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700242 << "Previous characteristics not deleted before generating key. Test bug.";
243
Shawn Willden7f424372021-01-10 18:06:50 -0700244 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700245 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700246 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700247 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
248 creationResult.keyCharacteristics);
249 EXPECT_GT(creationResult.keyBlob.size(), 0);
250 *key_blob = std::move(creationResult.keyBlob);
251 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700252 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700253
254 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
255 EXPECT_TRUE(algorithm);
256 if (algorithm &&
257 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700258 EXPECT_GE(cert_chain->size(), 1);
259 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
260 if (attest_key) {
261 EXPECT_EQ(cert_chain->size(), 1);
262 } else {
263 EXPECT_GT(cert_chain->size(), 1);
264 }
265 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700266 } else {
267 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700268 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700269 }
Selene Huang31ab4042020-04-29 04:22:39 -0700270 }
271
272 return GetReturnErrorCode(result);
273}
274
Shawn Willden7c130392020-12-21 09:58:22 -0700275ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
276 const optional<AttestationKey>& attest_key) {
277 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700278}
279
280ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
281 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700282 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700283 Status result;
284
Shawn Willden7f424372021-01-10 18:06:50 -0700285 cert_chain_.clear();
286 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700287 key_blob->clear();
288
Shawn Willden7f424372021-01-10 18:06:50 -0700289 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700290 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700291 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700292 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700293
294 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700295 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
296 creationResult.keyCharacteristics);
297 EXPECT_GT(creationResult.keyBlob.size(), 0);
298
299 *key_blob = std::move(creationResult.keyBlob);
300 *key_characteristics = std::move(creationResult.keyCharacteristics);
301 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700302
303 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
304 EXPECT_TRUE(algorithm);
305 if (algorithm &&
306 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
307 EXPECT_GE(cert_chain_.size(), 1);
308 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
309 } else {
310 // For symmetric keys there should be no certificates.
311 EXPECT_EQ(cert_chain_.size(), 0);
312 }
Selene Huang31ab4042020-04-29 04:22:39 -0700313 }
314
315 return GetReturnErrorCode(result);
316}
317
318ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
319 const string& key_material) {
320 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
321}
322
323ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
324 const AuthorizationSet& wrapping_key_desc,
325 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100326 const AuthorizationSet& unwrapping_params,
327 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700328 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
329
Shawn Willden7f424372021-01-10 18:06:50 -0700330 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700331
Shawn Willden7f424372021-01-10 18:06:50 -0700332 KeyCreationResult creationResult;
333 Status result = keymint_->importWrappedKey(
334 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
335 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100336 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700337
338 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700339 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
340 creationResult.keyCharacteristics);
341 EXPECT_GT(creationResult.keyBlob.size(), 0);
342
343 key_blob_ = std::move(creationResult.keyBlob);
344 key_characteristics_ = std::move(creationResult.keyCharacteristics);
345 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700346
347 AuthorizationSet allAuths;
348 for (auto& entry : key_characteristics_) {
349 allAuths.push_back(AuthorizationSet(entry.authorizations));
350 }
351 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
352 EXPECT_TRUE(algorithm);
353 if (algorithm &&
354 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
355 EXPECT_GE(cert_chain_.size(), 1);
356 } else {
357 // For symmetric keys there should be no certificates.
358 EXPECT_EQ(cert_chain_.size(), 0);
359 }
Selene Huang31ab4042020-04-29 04:22:39 -0700360 }
361
362 return GetReturnErrorCode(result);
363}
364
David Drysdale300b5552021-05-20 12:05:26 +0100365ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
366 const vector<uint8_t>& app_id,
367 const vector<uint8_t>& app_data,
368 vector<KeyCharacteristics>* key_characteristics) {
369 Status result =
370 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
371 return GetReturnErrorCode(result);
372}
373
374ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
375 vector<KeyCharacteristics>* key_characteristics) {
376 vector<uint8_t> empty_app_id, empty_app_data;
377 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
378}
379
380void KeyMintAidlTestBase::CheckCharacteristics(
381 const vector<uint8_t>& key_blob,
382 const vector<KeyCharacteristics>& generate_characteristics) {
383 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
384 // generateKey() should be excluded, as KeyMint will have no record of them.
385 // This applies to CREATION_DATETIME in particular.
386 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
387 strip_keystore_tags(&expected_characteristics);
388
389 vector<KeyCharacteristics> retrieved;
390 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
391 EXPECT_EQ(expected_characteristics, retrieved);
392}
393
394void KeyMintAidlTestBase::CheckAppIdCharacteristics(
395 const vector<uint8_t>& key_blob, std::string_view app_id_string,
396 std::string_view app_data_string,
397 const vector<KeyCharacteristics>& generate_characteristics) {
398 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
399 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
400 strip_keystore_tags(&expected_characteristics);
401
402 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
403 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
404 vector<KeyCharacteristics> retrieved;
405 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
406 EXPECT_EQ(expected_characteristics, retrieved);
407
408 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
409 vector<uint8_t> empty;
410 vector<KeyCharacteristics> not_retrieved;
411 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
412 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
413 EXPECT_EQ(not_retrieved.size(), 0);
414
415 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
416 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
417 EXPECT_EQ(not_retrieved.size(), 0);
418
419 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
420 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
421 EXPECT_EQ(not_retrieved.size(), 0);
422}
423
Selene Huang31ab4042020-04-29 04:22:39 -0700424ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
425 Status result = keymint_->deleteKey(*key_blob);
426 if (!keep_key_blob) {
427 *key_blob = vector<uint8_t>();
428 }
429
Janis Danisevskis24c04702020-12-16 18:28:39 -0800430 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700431 return GetReturnErrorCode(result);
432}
433
434ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
435 return DeleteKey(&key_blob_, keep_key_blob);
436}
437
438ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
439 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800440 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700441 return GetReturnErrorCode(result);
442}
443
David Drysdaled2cc8c22021-04-15 13:29:45 +0100444ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
445 Status result = keymint_->destroyAttestationIds();
446 return GetReturnErrorCode(result);
447}
448
Selene Huang31ab4042020-04-29 04:22:39 -0700449void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
450 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
451 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
452}
453
454void KeyMintAidlTestBase::CheckedDeleteKey() {
455 CheckedDeleteKey(&key_blob_);
456}
457
458ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
459 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800460 AuthorizationSet* out_params,
461 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700462 SCOPED_TRACE("Begin");
463 Status result;
464 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100465 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700466
467 if (result.isOk()) {
468 *out_params = out.params;
469 challenge_ = out.challenge;
470 op = out.operation;
471 }
472
473 return GetReturnErrorCode(result);
474}
475
476ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
477 const AuthorizationSet& in_params,
478 AuthorizationSet* out_params) {
479 SCOPED_TRACE("Begin");
480 Status result;
481 BeginResult out;
482
David Drysdale56ba9122021-04-19 19:10:47 +0100483 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700484
485 if (result.isOk()) {
486 *out_params = out.params;
487 challenge_ = out.challenge;
488 op_ = out.operation;
489 }
490
491 return GetReturnErrorCode(result);
492}
493
494ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
495 AuthorizationSet* out_params) {
496 SCOPED_TRACE("Begin");
497 EXPECT_EQ(nullptr, op_);
498 return Begin(purpose, key_blob_, in_params, out_params);
499}
500
501ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
502 SCOPED_TRACE("Begin");
503 AuthorizationSet out_params;
504 ErrorCode result = Begin(purpose, in_params, &out_params);
505 EXPECT_TRUE(out_params.empty());
506 return result;
507}
508
Shawn Willden92d79c02021-02-19 07:31:55 -0700509ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
510 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
511 {} /* hardwareAuthToken */,
512 {} /* verificationToken */));
513}
514
515ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700516 SCOPED_TRACE("Update");
517
518 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700519 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700520
Shawn Willden92d79c02021-02-19 07:31:55 -0700521 std::vector<uint8_t> o_put;
522 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700523
Shawn Willden92d79c02021-02-19 07:31:55 -0700524 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700525
526 return GetReturnErrorCode(result);
527}
528
Shawn Willden92d79c02021-02-19 07:31:55 -0700529ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700530 string* output) {
531 SCOPED_TRACE("Finish");
532 Status result;
533
534 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700535 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700536
537 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700538 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
539 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
540 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700541
Shawn Willden92d79c02021-02-19 07:31:55 -0700542 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700543
Shawn Willden92d79c02021-02-19 07:31:55 -0700544 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700545 return GetReturnErrorCode(result);
546}
547
Janis Danisevskis24c04702020-12-16 18:28:39 -0800548ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700549 SCOPED_TRACE("Abort");
550
551 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700552 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700553
554 Status retval = op->abort();
555 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800556 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700557}
558
559ErrorCode KeyMintAidlTestBase::Abort() {
560 SCOPED_TRACE("Abort");
561
562 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700563 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700564
565 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800566 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700567}
568
569void KeyMintAidlTestBase::AbortIfNeeded() {
570 SCOPED_TRACE("AbortIfNeeded");
571 if (op_) {
572 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800573 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700574 }
575}
576
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000577auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
578 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700579 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000580 AuthorizationSet begin_out_params;
581 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700582 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000583
584 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700585 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000586}
587
Selene Huang31ab4042020-04-29 04:22:39 -0700588string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
589 const string& message, const AuthorizationSet& in_params,
590 AuthorizationSet* out_params) {
591 SCOPED_TRACE("ProcessMessage");
592 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700593 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700594 EXPECT_EQ(ErrorCode::OK, result);
595 if (result != ErrorCode::OK) {
596 return "";
597 }
598
599 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700600 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700601 return output;
602}
603
604string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
605 const AuthorizationSet& params) {
606 SCOPED_TRACE("SignMessage");
607 AuthorizationSet out_params;
608 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
609 EXPECT_TRUE(out_params.empty());
610 return signature;
611}
612
613string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
614 SCOPED_TRACE("SignMessage");
615 return SignMessage(key_blob_, message, params);
616}
617
618string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
619 SCOPED_TRACE("MacMessage");
620 return SignMessage(
621 key_blob_, message,
622 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
623}
624
625void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
626 Digest digest, const string& expected_mac) {
627 SCOPED_TRACE("CheckHmacTestVector");
628 ASSERT_EQ(ErrorCode::OK,
629 ImportKey(AuthorizationSetBuilder()
630 .Authorization(TAG_NO_AUTH_REQUIRED)
631 .HmacKey(key.size() * 8)
632 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
633 .Digest(digest),
634 KeyFormat::RAW, key));
635 string signature = MacMessage(message, digest, expected_mac.size() * 8);
636 EXPECT_EQ(expected_mac, signature)
637 << "Test vector didn't match for key of size " << key.size() << " message of size "
638 << message.size() << " and digest " << digest;
639 CheckedDeleteKey();
640}
641
642void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
643 const string& message,
644 const string& expected_ciphertext) {
645 SCOPED_TRACE("CheckAesCtrTestVector");
646 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
647 .Authorization(TAG_NO_AUTH_REQUIRED)
648 .AesEncryptionKey(key.size() * 8)
649 .BlockMode(BlockMode::CTR)
650 .Authorization(TAG_CALLER_NONCE)
651 .Padding(PaddingMode::NONE),
652 KeyFormat::RAW, key));
653
654 auto params = AuthorizationSetBuilder()
655 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
656 .BlockMode(BlockMode::CTR)
657 .Padding(PaddingMode::NONE);
658 AuthorizationSet out_params;
659 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
660 EXPECT_EQ(expected_ciphertext, ciphertext);
661}
662
663void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
664 PaddingMode padding_mode, const string& key,
665 const string& iv, const string& input,
666 const string& expected_output) {
667 auto authset = AuthorizationSetBuilder()
668 .TripleDesEncryptionKey(key.size() * 7)
669 .BlockMode(block_mode)
670 .Authorization(TAG_NO_AUTH_REQUIRED)
671 .Padding(padding_mode);
672 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
673 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
674 ASSERT_GT(key_blob_.size(), 0U);
675
676 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
677 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
678 AuthorizationSet output_params;
679 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
680 EXPECT_EQ(expected_output, output);
681}
682
683void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
684 const string& signature, const AuthorizationSet& params) {
685 SCOPED_TRACE("VerifyMessage");
686 AuthorizationSet begin_out_params;
687 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
688
689 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700690 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700691 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700692 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700693}
694
695void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
696 const AuthorizationSet& params) {
697 SCOPED_TRACE("VerifyMessage");
698 VerifyMessage(key_blob_, message, signature, params);
699}
700
David Drysdaledf8f52e2021-05-06 08:10:58 +0100701void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
702 const AuthorizationSet& params) {
703 SCOPED_TRACE("LocalVerifyMessage");
704
705 // Retrieve the public key from the leaf certificate.
706 ASSERT_GT(cert_chain_.size(), 0);
707 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
708 ASSERT_TRUE(key_cert.get());
709 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
710 ASSERT_TRUE(pub_key.get());
711
712 Digest digest = params.GetTagValue(TAG_DIGEST).value();
713 PaddingMode padding = PaddingMode::NONE;
714 auto tag = params.GetTagValue(TAG_PADDING);
715 if (tag.has_value()) {
716 padding = tag.value();
717 }
718
719 if (digest == Digest::NONE) {
720 switch (EVP_PKEY_id(pub_key.get())) {
721 case EVP_PKEY_EC: {
722 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
723 size_t data_size = std::min(data.size(), message.size());
724 memcpy(data.data(), message.data(), data_size);
725 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
726 ASSERT_TRUE(ecdsa.get());
727 ASSERT_EQ(1,
728 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
729 reinterpret_cast<const uint8_t*>(signature.data()),
730 signature.size(), ecdsa.get()));
731 break;
732 }
733 case EVP_PKEY_RSA: {
734 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
735 size_t data_size = std::min(data.size(), message.size());
736 memcpy(data.data(), message.data(), data_size);
737
738 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
739 ASSERT_TRUE(rsa.get());
740
741 size_t key_len = RSA_size(rsa.get());
742 int openssl_padding = RSA_NO_PADDING;
743 switch (padding) {
744 case PaddingMode::NONE:
745 ASSERT_TRUE(data_size <= key_len);
746 ASSERT_EQ(key_len, signature.size());
747 openssl_padding = RSA_NO_PADDING;
748 break;
749 case PaddingMode::RSA_PKCS1_1_5_SIGN:
750 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
751 key_len);
752 openssl_padding = RSA_PKCS1_PADDING;
753 break;
754 default:
755 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
756 }
757
758 vector<uint8_t> decrypted_data(key_len);
759 int bytes_decrypted = RSA_public_decrypt(
760 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
761 decrypted_data.data(), rsa.get(), openssl_padding);
762 ASSERT_GE(bytes_decrypted, 0);
763
764 const uint8_t* compare_pos = decrypted_data.data();
765 size_t bytes_to_compare = bytes_decrypted;
766 uint8_t zero_check_result = 0;
767 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
768 // If the data is short, for "unpadded" signing we zero-pad to the left. So
769 // during verification we should have zeros on the left of the decrypted data.
770 // Do a constant-time check.
771 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
772 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
773 ASSERT_EQ(0, zero_check_result);
774 bytes_to_compare = data_size;
775 }
776 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
777 break;
778 }
779 default:
780 ADD_FAILURE() << "Unknown public key type";
781 }
782 } else {
783 EVP_MD_CTX digest_ctx;
784 EVP_MD_CTX_init(&digest_ctx);
785 EVP_PKEY_CTX* pkey_ctx;
786 const EVP_MD* md = openssl_digest(digest);
787 ASSERT_NE(md, nullptr);
788 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
789
790 if (padding == PaddingMode::RSA_PSS) {
791 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
792 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
793 }
794
795 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
796 reinterpret_cast<const uint8_t*>(message.data()),
797 message.size()));
798 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
799 reinterpret_cast<const uint8_t*>(signature.data()),
800 signature.size()));
801 EVP_MD_CTX_cleanup(&digest_ctx);
802 }
803}
804
David Drysdale59cae642021-05-12 13:52:03 +0100805string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
806 const AuthorizationSet& params) {
807 SCOPED_TRACE("LocalRsaEncryptMessage");
808
809 // Retrieve the public key from the leaf certificate.
810 if (cert_chain_.empty()) {
811 ADD_FAILURE() << "No public key available";
812 return "Failure";
813 }
814 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
815 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
816 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
817
818 // Retrieve relevant tags.
819 Digest digest = Digest::NONE;
820 Digest mgf_digest = Digest::NONE;
821 PaddingMode padding = PaddingMode::NONE;
822
823 auto digest_tag = params.GetTagValue(TAG_DIGEST);
824 if (digest_tag.has_value()) digest = digest_tag.value();
825 auto pad_tag = params.GetTagValue(TAG_PADDING);
826 if (pad_tag.has_value()) padding = pad_tag.value();
827 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
828 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
829
830 const EVP_MD* md = openssl_digest(digest);
831 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
832
833 // Set up encryption context.
834 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
835 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
836 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
837 return "Failure";
838 }
839
840 int rc = -1;
841 switch (padding) {
842 case PaddingMode::NONE:
843 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
844 break;
845 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
846 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
847 break;
848 case PaddingMode::RSA_OAEP:
849 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
850 break;
851 default:
852 break;
853 }
854 if (rc <= 0) {
855 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
856 return "Failure";
857 }
858 if (padding == PaddingMode::RSA_OAEP) {
859 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
860 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
861 return "Failure";
862 }
863 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
864 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
865 return "Failure";
866 }
867 }
868
869 // Determine output size.
870 size_t outlen;
871 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
872 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
873 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
874 return "Failure";
875 }
876
877 // Left-zero-pad the input if necessary.
878 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
879 size_t to_encrypt_len = message.size();
880
881 std::unique_ptr<string> zero_padded_message;
882 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
883 zero_padded_message.reset(new string(outlen, '\0'));
884 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
885 message.size());
886 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
887 to_encrypt_len = outlen;
888 }
889
890 // Do the encryption.
891 string output(outlen, '\0');
892 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
893 to_encrypt_len) <= 0) {
894 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
895 return "Failure";
896 }
897 return output;
898}
899
Selene Huang31ab4042020-04-29 04:22:39 -0700900string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
901 const AuthorizationSet& in_params,
902 AuthorizationSet* out_params) {
903 SCOPED_TRACE("EncryptMessage");
904 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
905}
906
907string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
908 AuthorizationSet* out_params) {
909 SCOPED_TRACE("EncryptMessage");
910 return EncryptMessage(key_blob_, message, params, out_params);
911}
912
913string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
914 SCOPED_TRACE("EncryptMessage");
915 AuthorizationSet out_params;
916 string ciphertext = EncryptMessage(message, params, &out_params);
917 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
918 return ciphertext;
919}
920
921string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
922 PaddingMode padding) {
923 SCOPED_TRACE("EncryptMessage");
924 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
925 AuthorizationSet out_params;
926 string ciphertext = EncryptMessage(message, params, &out_params);
927 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
928 return ciphertext;
929}
930
931string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
932 PaddingMode padding, vector<uint8_t>* iv_out) {
933 SCOPED_TRACE("EncryptMessage");
934 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
935 AuthorizationSet out_params;
936 string ciphertext = EncryptMessage(message, params, &out_params);
937 EXPECT_EQ(1U, out_params.size());
938 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800939 EXPECT_TRUE(ivVal);
940 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700941 return ciphertext;
942}
943
944string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
945 PaddingMode padding, const vector<uint8_t>& iv_in) {
946 SCOPED_TRACE("EncryptMessage");
947 auto params = AuthorizationSetBuilder()
948 .BlockMode(block_mode)
949 .Padding(padding)
950 .Authorization(TAG_NONCE, iv_in);
951 AuthorizationSet out_params;
952 string ciphertext = EncryptMessage(message, params, &out_params);
953 return ciphertext;
954}
955
956string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
957 PaddingMode padding, uint8_t mac_length_bits,
958 const vector<uint8_t>& iv_in) {
959 SCOPED_TRACE("EncryptMessage");
960 auto params = AuthorizationSetBuilder()
961 .BlockMode(block_mode)
962 .Padding(padding)
963 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
964 .Authorization(TAG_NONCE, iv_in);
965 AuthorizationSet out_params;
966 string ciphertext = EncryptMessage(message, params, &out_params);
967 return ciphertext;
968}
969
David Drysdaled2cc8c22021-04-15 13:29:45 +0100970string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
971 PaddingMode padding, uint8_t mac_length_bits) {
972 SCOPED_TRACE("EncryptMessage");
973 auto params = AuthorizationSetBuilder()
974 .BlockMode(block_mode)
975 .Padding(padding)
976 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
977 AuthorizationSet out_params;
978 string ciphertext = EncryptMessage(message, params, &out_params);
979 return ciphertext;
980}
981
Selene Huang31ab4042020-04-29 04:22:39 -0700982string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
983 const string& ciphertext,
984 const AuthorizationSet& params) {
985 SCOPED_TRACE("DecryptMessage");
986 AuthorizationSet out_params;
987 string plaintext =
988 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
989 EXPECT_TRUE(out_params.empty());
990 return plaintext;
991}
992
993string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
994 const AuthorizationSet& params) {
995 SCOPED_TRACE("DecryptMessage");
996 return DecryptMessage(key_blob_, ciphertext, params);
997}
998
999string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1000 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1001 SCOPED_TRACE("DecryptMessage");
1002 auto params = AuthorizationSetBuilder()
1003 .BlockMode(block_mode)
1004 .Padding(padding_mode)
1005 .Authorization(TAG_NONCE, iv);
1006 return DecryptMessage(key_blob_, ciphertext, params);
1007}
1008
1009std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1010 const vector<uint8_t>& key_blob) {
1011 std::pair<ErrorCode, vector<uint8_t>> retval;
1012 vector<uint8_t> outKeyBlob;
1013 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1014 ErrorCode errorcode = GetReturnErrorCode(result);
1015 retval = std::tie(errorcode, outKeyBlob);
1016
1017 return retval;
1018}
1019vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1020 switch (algorithm) {
1021 case Algorithm::RSA:
1022 switch (SecLevel()) {
1023 case SecurityLevel::SOFTWARE:
1024 case SecurityLevel::TRUSTED_ENVIRONMENT:
1025 return {2048, 3072, 4096};
1026 case SecurityLevel::STRONGBOX:
1027 return {2048};
1028 default:
1029 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1030 break;
1031 }
1032 break;
1033 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001034 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001035 break;
1036 case Algorithm::AES:
1037 return {128, 256};
1038 case Algorithm::TRIPLE_DES:
1039 return {168};
1040 case Algorithm::HMAC: {
1041 vector<uint32_t> retval((512 - 64) / 8 + 1);
1042 uint32_t size = 64 - 8;
1043 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1044 return retval;
1045 }
1046 default:
1047 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1048 return {};
1049 }
1050 ADD_FAILURE() << "Should be impossible to get here";
1051 return {};
1052}
1053
1054vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1055 if (SecLevel() == SecurityLevel::STRONGBOX) {
1056 switch (algorithm) {
1057 case Algorithm::RSA:
1058 return {3072, 4096};
1059 case Algorithm::EC:
1060 return {224, 384, 521};
1061 case Algorithm::AES:
1062 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001063 case Algorithm::TRIPLE_DES:
1064 return {56};
1065 default:
1066 return {};
1067 }
1068 } else {
1069 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001070 case Algorithm::AES:
1071 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001072 case Algorithm::TRIPLE_DES:
1073 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001074 default:
1075 return {};
1076 }
1077 }
1078 return {};
1079}
1080
David Drysdale7de9feb2021-03-05 14:56:19 +00001081vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1082 switch (algorithm) {
1083 case Algorithm::AES:
1084 return {
1085 BlockMode::CBC,
1086 BlockMode::CTR,
1087 BlockMode::ECB,
1088 BlockMode::GCM,
1089 };
1090 case Algorithm::TRIPLE_DES:
1091 return {
1092 BlockMode::CBC,
1093 BlockMode::ECB,
1094 };
1095 default:
1096 return {};
1097 }
1098}
1099
1100vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1101 BlockMode blockMode) {
1102 switch (algorithm) {
1103 case Algorithm::AES:
1104 switch (blockMode) {
1105 case BlockMode::CBC:
1106 case BlockMode::ECB:
1107 return {PaddingMode::NONE, PaddingMode::PKCS7};
1108 case BlockMode::CTR:
1109 case BlockMode::GCM:
1110 return {PaddingMode::NONE};
1111 default:
1112 return {};
1113 };
1114 case Algorithm::TRIPLE_DES:
1115 switch (blockMode) {
1116 case BlockMode::CBC:
1117 case BlockMode::ECB:
1118 return {PaddingMode::NONE, PaddingMode::PKCS7};
1119 default:
1120 return {};
1121 };
1122 default:
1123 return {};
1124 }
1125}
1126
1127vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1128 BlockMode blockMode) {
1129 switch (algorithm) {
1130 case Algorithm::AES:
1131 switch (blockMode) {
1132 case BlockMode::CTR:
1133 case BlockMode::GCM:
1134 return {PaddingMode::PKCS7};
1135 default:
1136 return {};
1137 };
1138 default:
1139 return {};
1140 }
1141}
1142
Selene Huang31ab4042020-04-29 04:22:39 -07001143vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1144 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1145 return {EcCurve::P_256};
1146 } else {
1147 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1148 }
1149}
1150
1151vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001152 if (SecLevel() == SecurityLevel::STRONGBOX) {
1153 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
1154 } else {
1155 return {};
1156 }
Selene Huang31ab4042020-04-29 04:22:39 -07001157}
1158
1159vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1160 switch (SecLevel()) {
1161 case SecurityLevel::SOFTWARE:
1162 case SecurityLevel::TRUSTED_ENVIRONMENT:
1163 if (withNone) {
1164 if (withMD5)
1165 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1166 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1167 Digest::SHA_2_512};
1168 else
1169 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1170 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1171 } else {
1172 if (withMD5)
1173 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1174 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1175 else
1176 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1177 Digest::SHA_2_512};
1178 }
1179 break;
1180 case SecurityLevel::STRONGBOX:
1181 if (withNone)
1182 return {Digest::NONE, Digest::SHA_2_256};
1183 else
1184 return {Digest::SHA_2_256};
1185 break;
1186 default:
1187 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1188 break;
1189 }
1190 ADD_FAILURE() << "Should be impossible to get here";
1191 return {};
1192}
1193
Shawn Willden7f424372021-01-10 18:06:50 -07001194static const vector<KeyParameter> kEmptyAuthList{};
1195
1196const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1197 const vector<KeyCharacteristics>& key_characteristics) {
1198 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1199 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1200 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1201}
1202
Qi Wubeefae42021-01-28 23:16:37 +08001203const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1204 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1205 auto found = std::find_if(
1206 key_characteristics.begin(), key_characteristics.end(),
1207 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001208 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1209}
1210
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001211ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001212 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001213 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1214 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1215 return result;
1216}
1217
1218ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001219 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001220 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1221 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1222 return result;
1223}
1224
1225ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1226 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001227 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001228 rsaKeyBlob, KeyPurpose::SIGN, message,
1229 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1230 return result;
1231}
1232
1233ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001234 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1235 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001236 return result;
1237}
1238
Selene Huang6e46f142021-04-20 19:20:11 -07001239void verify_serial(X509* cert, const uint64_t expected_serial) {
1240 BIGNUM_Ptr ser(BN_new());
1241 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1242
1243 uint64_t serial;
1244 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1245 EXPECT_EQ(serial, expected_serial);
1246}
1247
1248// Please set self_signed to true for fake certificates or self signed
1249// certificates
1250void verify_subject(const X509* cert, //
1251 const string& subject, //
1252 bool self_signed) {
1253 char* cert_issuer = //
1254 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1255
1256 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1257
1258 string expected_subject("/CN=");
1259 if (subject.empty()) {
1260 expected_subject.append("Android Keystore Key");
1261 } else {
1262 expected_subject.append(subject);
1263 }
1264
1265 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1266
1267 if (self_signed) {
1268 EXPECT_STREQ(cert_issuer, cert_subj)
1269 << "Cert issuer and subject mismatch for self signed certificate.";
1270 }
1271
1272 OPENSSL_free(cert_subj);
1273 OPENSSL_free(cert_issuer);
1274}
1275
1276vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1277 BIGNUM_Ptr serial(BN_new());
1278 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1279
1280 int len = BN_num_bytes(serial.get());
1281 vector<uint8_t> serial_blob(len);
1282 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1283 return {};
1284 }
1285
David Drysdaledb0dcf52021-05-18 11:43:31 +01001286 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1287 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1288 // Top bit being set indicates a negative number in two's complement, but our input
1289 // was positive.
1290 // In either case, prepend a zero byte.
1291 serial_blob.insert(serial_blob.begin(), 0x00);
1292 }
1293
Selene Huang6e46f142021-04-20 19:20:11 -07001294 return serial_blob;
1295}
1296
1297void verify_subject_and_serial(const Certificate& certificate, //
1298 const uint64_t expected_serial, //
1299 const string& subject, bool self_signed) {
1300 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1301 ASSERT_TRUE(!!cert.get());
1302
1303 verify_serial(cert.get(), expected_serial);
1304 verify_subject(cert.get(), subject, self_signed);
1305}
1306
Shawn Willden7c130392020-12-21 09:58:22 -07001307bool verify_attestation_record(const string& challenge, //
1308 const string& app_id, //
1309 AuthorizationSet expected_sw_enforced, //
1310 AuthorizationSet expected_hw_enforced, //
1311 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001312 const vector<uint8_t>& attestation_cert,
1313 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001314 X509_Ptr cert(parse_cert_blob(attestation_cert));
1315 EXPECT_TRUE(!!cert.get());
1316 if (!cert.get()) return false;
1317
1318 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1319 EXPECT_TRUE(!!attest_rec);
1320 if (!attest_rec) return false;
1321
1322 AuthorizationSet att_sw_enforced;
1323 AuthorizationSet att_hw_enforced;
1324 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001325 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001326 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001327 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001328 vector<uint8_t> att_challenge;
1329 vector<uint8_t> att_unique_id;
1330 vector<uint8_t> att_app_id;
1331
1332 auto error = parse_attestation_record(attest_rec->data, //
1333 attest_rec->length, //
1334 &att_attestation_version, //
1335 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001336 &att_keymint_version, //
1337 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001338 &att_challenge, //
1339 &att_sw_enforced, //
1340 &att_hw_enforced, //
1341 &att_unique_id);
1342 EXPECT_EQ(ErrorCode::OK, error);
1343 if (error != ErrorCode::OK) return false;
1344
Shawn Willden3cb64a62021-04-05 14:39:05 -06001345 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -07001346 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001347
Selene Huang4f64c222021-04-13 19:54:36 -07001348 // check challenge and app id only if we expects a non-fake certificate
1349 if (challenge.length() > 0) {
1350 EXPECT_EQ(challenge.length(), att_challenge.size());
1351 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1352
1353 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1354 }
Shawn Willden7c130392020-12-21 09:58:22 -07001355
David Drysdale37af4b32021-05-14 16:46:59 +01001356 EXPECT_EQ(att_keymint_version, 100U);
1357 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001358 EXPECT_EQ(security_level, att_attestation_security_level);
1359
Shawn Willden7c130392020-12-21 09:58:22 -07001360
1361 char property_value[PROPERTY_VALUE_MAX] = {};
1362 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001363 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001364 // for the BOOT_PATCH_LEVEL.
1365 if (avb_verification_enabled()) {
1366 for (int i = 0; i < att_hw_enforced.size(); i++) {
1367 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1368 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1369 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001370 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001371
Shawn Willden7c130392020-12-21 09:58:22 -07001372 // strptime seems to require delimiters, but the tag value will
1373 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001374 if (date.size() != 8) {
1375 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1376 << " with invalid format (not YYYYMMDD): " << date;
1377 return false;
1378 }
Shawn Willden7c130392020-12-21 09:58:22 -07001379 date.insert(6, "-");
1380 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001381 struct tm time;
1382 strptime(date.c_str(), "%Y-%m-%d", &time);
1383
1384 // Day of the month (0-31)
1385 EXPECT_GE(time.tm_mday, 0);
1386 EXPECT_LT(time.tm_mday, 32);
1387 // Months since Jan (0-11)
1388 EXPECT_GE(time.tm_mon, 0);
1389 EXPECT_LT(time.tm_mon, 12);
1390 // Years since 1900
1391 EXPECT_GT(time.tm_year, 110);
1392 EXPECT_LT(time.tm_year, 200);
1393 }
1394 }
1395 }
1396
1397 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1398 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1399 // indicates correct encoding. No need to check if it's in both lists, since the
1400 // AuthorizationSet compare below will handle mismatches of tags.
1401 if (security_level == SecurityLevel::SOFTWARE) {
1402 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1403 } else {
1404 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1405 }
1406
Shawn Willden7c130392020-12-21 09:58:22 -07001407 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1408 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1409 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1410 att_hw_enforced.Contains(TAG_KEY_SIZE));
1411 }
1412
1413 // Test root of trust elements
1414 vector<uint8_t> verified_boot_key;
1415 VerifiedBoot verified_boot_state;
1416 bool device_locked;
1417 vector<uint8_t> verified_boot_hash;
1418 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1419 &verified_boot_state, &device_locked, &verified_boot_hash);
1420 EXPECT_EQ(ErrorCode::OK, error);
1421
1422 if (avb_verification_enabled()) {
1423 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1424 string prop_string(property_value);
1425 EXPECT_EQ(prop_string.size(), 64);
1426 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1427
1428 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1429 if (!strcmp(property_value, "unlocked")) {
1430 EXPECT_FALSE(device_locked);
1431 } else {
1432 EXPECT_TRUE(device_locked);
1433 }
1434
1435 // Check that the device is locked if not debuggable, e.g., user build
1436 // images in CTS. For VTS, debuggable images are used to allow adb root
1437 // and the device is unlocked.
1438 if (!property_get_bool("ro.debuggable", false)) {
1439 EXPECT_TRUE(device_locked);
1440 } else {
1441 EXPECT_FALSE(device_locked);
1442 }
1443 }
1444
1445 // Verified boot key should be all 0's if the boot state is not verified or self signed
1446 std::string empty_boot_key(32, '\0');
1447 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1448 verified_boot_key.size());
1449 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1450 if (!strcmp(property_value, "green")) {
1451 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1452 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1453 verified_boot_key.size()));
1454 } else if (!strcmp(property_value, "yellow")) {
1455 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1456 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1457 verified_boot_key.size()));
1458 } else if (!strcmp(property_value, "orange")) {
1459 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1460 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1461 verified_boot_key.size()));
1462 } else if (!strcmp(property_value, "red")) {
1463 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1464 } else {
1465 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1466 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1467 verified_boot_key.size()));
1468 }
1469
1470 att_sw_enforced.Sort();
1471 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001472 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001473
1474 att_hw_enforced.Sort();
1475 expected_hw_enforced.Sort();
1476 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1477
David Drysdale565ccc72021-10-11 12:49:50 +01001478 if (unique_id != nullptr) {
1479 *unique_id = att_unique_id;
1480 }
1481
Shawn Willden7c130392020-12-21 09:58:22 -07001482 return true;
1483}
1484
1485string bin2hex(const vector<uint8_t>& data) {
1486 string retval;
1487 retval.reserve(data.size() * 2 + 1);
1488 for (uint8_t byte : data) {
1489 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1490 retval.push_back(nibble2hex[0x0F & byte]);
1491 }
1492 return retval;
1493}
1494
David Drysdalef0d516d2021-03-22 07:51:43 +00001495AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1496 AuthorizationSet authList;
1497 for (auto& entry : key_characteristics) {
1498 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1499 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1500 authList.push_back(AuthorizationSet(entry.authorizations));
1501 }
1502 }
1503 return authList;
1504}
1505
1506AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1507 AuthorizationSet authList;
1508 for (auto& entry : key_characteristics) {
1509 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1510 entry.securityLevel == SecurityLevel::KEYSTORE) {
1511 authList.push_back(AuthorizationSet(entry.authorizations));
1512 }
1513 }
1514 return authList;
1515}
1516
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001517AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1518 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001519 std::stringstream cert_data;
1520
1521 for (size_t i = 0; i < chain.size(); ++i) {
1522 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1523
1524 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1525 X509_Ptr signing_cert;
1526 if (i < chain.size() - 1) {
1527 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1528 } else {
1529 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1530 }
1531 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1532
1533 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1534 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1535
1536 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1537 return AssertionFailure()
1538 << "Verification of certificate " << i << " failed "
1539 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1540 << cert_data.str();
1541 }
1542
1543 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1544 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001545 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001546 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1547 << " Signer subject is " << signer_subj
1548 << " Issuer subject is " << cert_issuer << endl
1549 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001550 }
Shawn Willden7c130392020-12-21 09:58:22 -07001551 }
1552
1553 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1554 return AssertionSuccess();
1555}
1556
1557X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1558 const uint8_t* p = blob.data();
1559 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1560}
1561
David Drysdalef0d516d2021-03-22 07:51:43 +00001562vector<uint8_t> make_name_from_str(const string& name) {
1563 X509_NAME_Ptr x509_name(X509_NAME_new());
1564 EXPECT_TRUE(x509_name.get() != nullptr);
1565 if (!x509_name) return {};
1566
1567 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1568 "CN", //
1569 MBSTRING_ASC,
1570 reinterpret_cast<const uint8_t*>(name.c_str()),
1571 -1, // len
1572 -1, // loc
1573 0 /* set */));
1574
1575 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1576 EXPECT_GT(len, 0);
1577
1578 vector<uint8_t> retval(len);
1579 uint8_t* p = retval.data();
1580 i2d_X509_NAME(x509_name.get(), &p);
1581
1582 return retval;
1583}
1584
David Drysdale4dc01072021-04-01 12:17:35 +01001585namespace {
1586
1587void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1588 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1589 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1590
1591 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1592 if (testMode) {
1593 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1594 MatchesRegex("{\n"
1595 " 1 : 2,\n" // kty: EC2
1596 " 3 : -7,\n" // alg: ES256
1597 " -1 : 1,\n" // EC id: P256
1598 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1599 // sequence of 32 hexadecimal bytes, enclosed in braces and
1600 // separated by commas. In this case, some Ed25519 public key.
1601 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1602 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1603 " -70000 : null,\n" // test marker
1604 "}"));
1605 } else {
1606 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1607 MatchesRegex("{\n"
1608 " 1 : 2,\n" // kty: EC2
1609 " 3 : -7,\n" // alg: ES256
1610 " -1 : 1,\n" // EC id: P256
1611 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1612 // sequence of 32 hexadecimal bytes, enclosed in braces and
1613 // separated by commas. In this case, some Ed25519 public key.
1614 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1615 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1616 "}"));
1617 }
1618}
1619
1620} // namespace
1621
1622void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1623 vector<uint8_t>* payload_value) {
1624 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1625 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1626
1627 ASSERT_NE(coseMac0->asArray(), nullptr);
1628 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1629
1630 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1631 ASSERT_NE(protParms, nullptr);
1632
1633 // Header label:value of 'alg': HMAC-256
1634 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1635
1636 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1637 ASSERT_NE(unprotParms, nullptr);
1638 ASSERT_EQ(unprotParms->size(), 0);
1639
1640 // The payload is a bstr holding an encoded COSE_Key
1641 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1642 ASSERT_NE(payload, nullptr);
1643 check_cose_key(payload->value(), testMode);
1644
1645 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1646 ASSERT_TRUE(coseMac0Tag);
1647 auto extractedTag = coseMac0Tag->value();
1648 EXPECT_EQ(extractedTag.size(), 32U);
1649
1650 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001651 auto macFunction = [](const cppcose::bytevec& input) {
1652 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1653 };
1654 auto testTag =
1655 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001656 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1657
1658 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001659 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001660 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001661 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001662 }
1663 if (payload_value != nullptr) {
1664 *payload_value = payload->value();
1665 }
1666}
1667
1668void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1669 // Extract x and y affine coordinates from the encoded Cose_Key.
1670 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1671 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1672 auto coseKey = parsedPayload->asMap();
1673 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1674 ASSERT_NE(xItem->asBstr(), nullptr);
1675 vector<uint8_t> x = xItem->asBstr()->value();
1676 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1677 ASSERT_NE(yItem->asBstr(), nullptr);
1678 vector<uint8_t> y = yItem->asBstr()->value();
1679
1680 // Concatenate: 0x04 (uncompressed form marker) | x | y
1681 vector<uint8_t> pubKeyData{0x04};
1682 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1683 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1684
1685 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1686 ASSERT_NE(ecKey, nullptr);
1687 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1688 ASSERT_NE(group, nullptr);
1689 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1690 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1691 ASSERT_NE(point, nullptr);
1692 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1693 nullptr),
1694 1);
1695 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1696
1697 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1698 ASSERT_NE(pubKey, nullptr);
1699 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1700 *signingKey = std::move(pubKey);
1701}
1702
Selene Huang31ab4042020-04-29 04:22:39 -07001703} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001704
Janis Danisevskis24c04702020-12-16 18:28:39 -08001705} // namespace aidl::android::hardware::security::keymint