blob: 5a511752b53589d08c53ce8a3b38c84f0a4a6a2b [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 Moore7735ba52021-04-30 11:41:18 -070047using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010048using ::testing::MatchesRegex;
Seth Moore7735ba52021-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 Drysdalefe42aa32021-05-06 08:10:58 +010064
David Drysdale92464372021-05-14 16:46:59 +010065// Invalid value for a patchlevel (which is of form YYYYMMDD).
66const uint32_t kInvalidPatchlevel = 99998877;
67
David Drysdalefe42aa32021-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) {
80 if (entry.authorizations.empty()) return false;
81
Qi Wubeefae42021-01-28 23:16:37 +080082 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
83 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
84
Shawn Willden7f424372021-01-10 18:06:50 -070085 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
86 levels_seen.insert(entry.securityLevel);
87
88 // Generally, we should only have one entry, at the same security level as the KM
89 // instance. There is an exception: StrongBox KM can have some authorizations that are
90 // enforced by the TEE.
91 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
92 (secLevel == SecurityLevel::STRONGBOX &&
93 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
94
95 if (!isExpectedSecurityLevel) return false;
96 }
97 return true;
98}
99
Shawn Willden7c130392020-12-21 09:58:22 -0700100// Extract attestation record from cert. Returned object is still part of cert; don't free it
101// separately.
102ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
103 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
104 EXPECT_TRUE(!!oid.get());
105 if (!oid.get()) return nullptr;
106
107 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
108 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
109 if (location == -1) return nullptr;
110
111 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
112 EXPECT_TRUE(!!attest_rec_ext)
113 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
114 if (!attest_rec_ext) return nullptr;
115
116 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
117 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
118 return attest_rec;
119}
120
121bool avb_verification_enabled() {
122 char value[PROPERTY_VALUE_MAX];
123 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
124}
125
126char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
127 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
128
129// Attestations don't contain everything in key authorization lists, so we need to filter the key
130// lists to produce the lists that we expect to match the attestations.
131auto kTagsToFilter = {
David Drysdale92464372021-05-14 16:46:59 +0100132 Tag::CREATION_DATETIME,
133 Tag::HARDWARE_TYPE,
134 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700135};
136
137AuthorizationSet filtered_tags(const AuthorizationSet& set) {
138 AuthorizationSet filtered;
139 std::remove_copy_if(
140 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
141 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
142 kTagsToFilter.end();
143 });
144 return filtered;
145}
146
David Drysdale96ad2032021-05-20 12:05:26 +0100147// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
148void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
149 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
150 [](const auto& entry) {
151 return entry.securityLevel == SecurityLevel::KEYSTORE;
152 }),
153 characteristics->end());
154}
155
Shawn Willden7c130392020-12-21 09:58:22 -0700156string x509NameToStr(X509_NAME* name) {
157 char* s = X509_NAME_oneline(name, nullptr, 0);
158 string retval(s);
159 OPENSSL_free(s);
160 return retval;
161}
162
Shawn Willden7f424372021-01-10 18:06:50 -0700163} // namespace
164
Shawn Willden7c130392020-12-21 09:58:22 -0700165bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
166bool KeyMintAidlTestBase::dump_Attestations = false;
167
David Drysdale92464372021-05-14 16:46:59 +0100168uint32_t KeyMintAidlTestBase::boot_patch_level(
169 const vector<KeyCharacteristics>& key_characteristics) {
170 // The boot patchlevel is not available as a property, but should be present
171 // in the key characteristics of any created key.
172 AuthorizationSet allAuths;
173 for (auto& entry : key_characteristics) {
174 allAuths.push_back(AuthorizationSet(entry.authorizations));
175 }
176 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
177 if (patchlevel.has_value()) {
178 return patchlevel.value();
179 } else {
180 // No boot patchlevel is available. Return a value that won't match anything
181 // and so will trigger test failures.
182 return kInvalidPatchlevel;
183 }
184}
185
186uint32_t KeyMintAidlTestBase::boot_patch_level() {
187 return boot_patch_level(key_characteristics_);
188}
189
Janis Danisevskis24c04702020-12-16 18:28:39 -0800190ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700191 if (result.isOk()) return ErrorCode::OK;
192
Janis Danisevskis24c04702020-12-16 18:28:39 -0800193 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
194 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700195 }
196
197 return ErrorCode::UNKNOWN_ERROR;
198}
199
Janis Danisevskis24c04702020-12-16 18:28:39 -0800200void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700201 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800202 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700203
204 KeyMintHardwareInfo info;
205 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
206
207 securityLevel_ = info.securityLevel;
208 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
209 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100210 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700211
212 os_version_ = getOsVersion();
213 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100214 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700215}
216
217void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800218 if (AServiceManager_isDeclared(GetParam().c_str())) {
219 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
220 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
221 } else {
222 InitializeKeyMint(nullptr);
223 }
Selene Huang31ab4042020-04-29 04:22:39 -0700224}
225
226ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700227 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700228 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700229 vector<KeyCharacteristics>* key_characteristics,
230 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700231 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
232 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700233 << "Previous characteristics not deleted before generating key. Test bug.";
234
Shawn Willden7f424372021-01-10 18:06:50 -0700235 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700236 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700237 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700238 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
239 creationResult.keyCharacteristics);
240 EXPECT_GT(creationResult.keyBlob.size(), 0);
241 *key_blob = std::move(creationResult.keyBlob);
242 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700243 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700244
245 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
246 EXPECT_TRUE(algorithm);
247 if (algorithm &&
248 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700249 EXPECT_GE(cert_chain->size(), 1);
250 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
251 if (attest_key) {
252 EXPECT_EQ(cert_chain->size(), 1);
253 } else {
254 EXPECT_GT(cert_chain->size(), 1);
255 }
256 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700257 } else {
258 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700259 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700260 }
Selene Huang31ab4042020-04-29 04:22:39 -0700261 }
262
263 return GetReturnErrorCode(result);
264}
265
Shawn Willden7c130392020-12-21 09:58:22 -0700266ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
267 const optional<AttestationKey>& attest_key) {
268 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700269}
270
271ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
272 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700273 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700274 Status result;
275
Shawn Willden7f424372021-01-10 18:06:50 -0700276 cert_chain_.clear();
277 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700278 key_blob->clear();
279
Shawn Willden7f424372021-01-10 18:06:50 -0700280 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700281 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700282 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700283 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700284
285 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700286 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
287 creationResult.keyCharacteristics);
288 EXPECT_GT(creationResult.keyBlob.size(), 0);
289
290 *key_blob = std::move(creationResult.keyBlob);
291 *key_characteristics = std::move(creationResult.keyCharacteristics);
292 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700293
294 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
295 EXPECT_TRUE(algorithm);
296 if (algorithm &&
297 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
298 EXPECT_GE(cert_chain_.size(), 1);
299 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
300 } else {
301 // For symmetric keys there should be no certificates.
302 EXPECT_EQ(cert_chain_.size(), 0);
303 }
Selene Huang31ab4042020-04-29 04:22:39 -0700304 }
305
306 return GetReturnErrorCode(result);
307}
308
309ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
310 const string& key_material) {
311 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
312}
313
314ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
315 const AuthorizationSet& wrapping_key_desc,
316 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100317 const AuthorizationSet& unwrapping_params,
318 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700319 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
320
Shawn Willden7f424372021-01-10 18:06:50 -0700321 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700322
Shawn Willden7f424372021-01-10 18:06:50 -0700323 KeyCreationResult creationResult;
324 Status result = keymint_->importWrappedKey(
325 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
326 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327 unwrapping_params.vector_data(), password_sid, biometric_sid, &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 AuthorizationSet allAuths;
339 for (auto& entry : key_characteristics_) {
340 allAuths.push_back(AuthorizationSet(entry.authorizations));
341 }
342 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
343 EXPECT_TRUE(algorithm);
344 if (algorithm &&
345 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
346 EXPECT_GE(cert_chain_.size(), 1);
347 } else {
348 // For symmetric keys there should be no certificates.
349 EXPECT_EQ(cert_chain_.size(), 0);
350 }
Selene Huang31ab4042020-04-29 04:22:39 -0700351 }
352
353 return GetReturnErrorCode(result);
354}
355
David Drysdale96ad2032021-05-20 12:05:26 +0100356ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
357 const vector<uint8_t>& app_id,
358 const vector<uint8_t>& app_data,
359 vector<KeyCharacteristics>* key_characteristics) {
360 Status result =
361 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
362 return GetReturnErrorCode(result);
363}
364
365ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
366 vector<KeyCharacteristics>* key_characteristics) {
367 vector<uint8_t> empty_app_id, empty_app_data;
368 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
369}
370
371void KeyMintAidlTestBase::CheckCharacteristics(
372 const vector<uint8_t>& key_blob,
373 const vector<KeyCharacteristics>& generate_characteristics) {
374 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
375 // generateKey() should be excluded, as KeyMint will have no record of them.
376 // This applies to CREATION_DATETIME in particular.
377 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
378 strip_keystore_tags(&expected_characteristics);
379
380 vector<KeyCharacteristics> retrieved;
381 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
382 EXPECT_EQ(expected_characteristics, retrieved);
383}
384
385void KeyMintAidlTestBase::CheckAppIdCharacteristics(
386 const vector<uint8_t>& key_blob, std::string_view app_id_string,
387 std::string_view app_data_string,
388 const vector<KeyCharacteristics>& generate_characteristics) {
389 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
390 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
391 strip_keystore_tags(&expected_characteristics);
392
393 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
394 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
395 vector<KeyCharacteristics> retrieved;
396 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
397 EXPECT_EQ(expected_characteristics, retrieved);
398
399 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
400 vector<uint8_t> empty;
401 vector<KeyCharacteristics> not_retrieved;
402 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
403 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
404 EXPECT_EQ(not_retrieved.size(), 0);
405
406 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
407 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
408 EXPECT_EQ(not_retrieved.size(), 0);
409
410 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
411 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
412 EXPECT_EQ(not_retrieved.size(), 0);
413}
414
Selene Huang31ab4042020-04-29 04:22:39 -0700415ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
416 Status result = keymint_->deleteKey(*key_blob);
417 if (!keep_key_blob) {
418 *key_blob = vector<uint8_t>();
419 }
420
Janis Danisevskis24c04702020-12-16 18:28:39 -0800421 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700422 return GetReturnErrorCode(result);
423}
424
425ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
426 return DeleteKey(&key_blob_, keep_key_blob);
427}
428
429ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
430 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800431 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700432 return GetReturnErrorCode(result);
433}
434
David Drysdaled2cc8c22021-04-15 13:29:45 +0100435ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
436 Status result = keymint_->destroyAttestationIds();
437 return GetReturnErrorCode(result);
438}
439
Selene Huang31ab4042020-04-29 04:22:39 -0700440void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
441 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
442 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
443}
444
445void KeyMintAidlTestBase::CheckedDeleteKey() {
446 CheckedDeleteKey(&key_blob_);
447}
448
449ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
450 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800451 AuthorizationSet* out_params,
452 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700453 SCOPED_TRACE("Begin");
454 Status result;
455 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100456 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700457
458 if (result.isOk()) {
459 *out_params = out.params;
460 challenge_ = out.challenge;
461 op = out.operation;
462 }
463
464 return GetReturnErrorCode(result);
465}
466
467ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
468 const AuthorizationSet& in_params,
469 AuthorizationSet* out_params) {
470 SCOPED_TRACE("Begin");
471 Status result;
472 BeginResult out;
473
David Drysdale56ba9122021-04-19 19:10:47 +0100474 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700475
476 if (result.isOk()) {
477 *out_params = out.params;
478 challenge_ = out.challenge;
479 op_ = out.operation;
480 }
481
482 return GetReturnErrorCode(result);
483}
484
485ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
486 AuthorizationSet* out_params) {
487 SCOPED_TRACE("Begin");
488 EXPECT_EQ(nullptr, op_);
489 return Begin(purpose, key_blob_, in_params, out_params);
490}
491
492ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
493 SCOPED_TRACE("Begin");
494 AuthorizationSet out_params;
495 ErrorCode result = Begin(purpose, in_params, &out_params);
496 EXPECT_TRUE(out_params.empty());
497 return result;
498}
499
Shawn Willden92d79c02021-02-19 07:31:55 -0700500ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
501 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
502 {} /* hardwareAuthToken */,
503 {} /* verificationToken */));
504}
505
506ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700507 SCOPED_TRACE("Update");
508
509 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700510 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700511
Shawn Willden92d79c02021-02-19 07:31:55 -0700512 std::vector<uint8_t> o_put;
513 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700514
Shawn Willden92d79c02021-02-19 07:31:55 -0700515 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700516
517 return GetReturnErrorCode(result);
518}
519
Shawn Willden92d79c02021-02-19 07:31:55 -0700520ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700521 string* output) {
522 SCOPED_TRACE("Finish");
523 Status result;
524
525 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700526 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700527
528 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700529 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
530 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
531 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700532
Shawn Willden92d79c02021-02-19 07:31:55 -0700533 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700534
Shawn Willden92d79c02021-02-19 07:31:55 -0700535 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700536 return GetReturnErrorCode(result);
537}
538
Janis Danisevskis24c04702020-12-16 18:28:39 -0800539ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700540 SCOPED_TRACE("Abort");
541
542 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700543 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700544
545 Status retval = op->abort();
546 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800547 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700548}
549
550ErrorCode KeyMintAidlTestBase::Abort() {
551 SCOPED_TRACE("Abort");
552
553 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700554 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700555
556 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800557 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700558}
559
560void KeyMintAidlTestBase::AbortIfNeeded() {
561 SCOPED_TRACE("AbortIfNeeded");
562 if (op_) {
563 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800564 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700565 }
566}
567
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000568auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
569 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700570 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000571 AuthorizationSet begin_out_params;
572 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700573 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000574
575 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700576 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000577}
578
Selene Huang31ab4042020-04-29 04:22:39 -0700579string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
580 const string& message, const AuthorizationSet& in_params,
581 AuthorizationSet* out_params) {
582 SCOPED_TRACE("ProcessMessage");
583 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700584 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700585 EXPECT_EQ(ErrorCode::OK, result);
586 if (result != ErrorCode::OK) {
587 return "";
588 }
589
590 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700591 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700592 return output;
593}
594
595string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
596 const AuthorizationSet& params) {
597 SCOPED_TRACE("SignMessage");
598 AuthorizationSet out_params;
599 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
600 EXPECT_TRUE(out_params.empty());
601 return signature;
602}
603
604string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
605 SCOPED_TRACE("SignMessage");
606 return SignMessage(key_blob_, message, params);
607}
608
609string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
610 SCOPED_TRACE("MacMessage");
611 return SignMessage(
612 key_blob_, message,
613 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
614}
615
616void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
617 Digest digest, const string& expected_mac) {
618 SCOPED_TRACE("CheckHmacTestVector");
619 ASSERT_EQ(ErrorCode::OK,
620 ImportKey(AuthorizationSetBuilder()
621 .Authorization(TAG_NO_AUTH_REQUIRED)
622 .HmacKey(key.size() * 8)
623 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
624 .Digest(digest),
625 KeyFormat::RAW, key));
626 string signature = MacMessage(message, digest, expected_mac.size() * 8);
627 EXPECT_EQ(expected_mac, signature)
628 << "Test vector didn't match for key of size " << key.size() << " message of size "
629 << message.size() << " and digest " << digest;
630 CheckedDeleteKey();
631}
632
633void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
634 const string& message,
635 const string& expected_ciphertext) {
636 SCOPED_TRACE("CheckAesCtrTestVector");
637 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
638 .Authorization(TAG_NO_AUTH_REQUIRED)
639 .AesEncryptionKey(key.size() * 8)
640 .BlockMode(BlockMode::CTR)
641 .Authorization(TAG_CALLER_NONCE)
642 .Padding(PaddingMode::NONE),
643 KeyFormat::RAW, key));
644
645 auto params = AuthorizationSetBuilder()
646 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
647 .BlockMode(BlockMode::CTR)
648 .Padding(PaddingMode::NONE);
649 AuthorizationSet out_params;
650 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
651 EXPECT_EQ(expected_ciphertext, ciphertext);
652}
653
654void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
655 PaddingMode padding_mode, const string& key,
656 const string& iv, const string& input,
657 const string& expected_output) {
658 auto authset = AuthorizationSetBuilder()
659 .TripleDesEncryptionKey(key.size() * 7)
660 .BlockMode(block_mode)
661 .Authorization(TAG_NO_AUTH_REQUIRED)
662 .Padding(padding_mode);
663 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
664 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
665 ASSERT_GT(key_blob_.size(), 0U);
666
667 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
668 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
669 AuthorizationSet output_params;
670 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
671 EXPECT_EQ(expected_output, output);
672}
673
674void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
675 const string& signature, const AuthorizationSet& params) {
676 SCOPED_TRACE("VerifyMessage");
677 AuthorizationSet begin_out_params;
678 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
679
680 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700681 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700682 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700683 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700684}
685
686void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
687 const AuthorizationSet& params) {
688 SCOPED_TRACE("VerifyMessage");
689 VerifyMessage(key_blob_, message, signature, params);
690}
691
David Drysdalefe42aa32021-05-06 08:10:58 +0100692void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
693 const AuthorizationSet& params) {
694 SCOPED_TRACE("LocalVerifyMessage");
695
696 // Retrieve the public key from the leaf certificate.
697 ASSERT_GT(cert_chain_.size(), 0);
698 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
699 ASSERT_TRUE(key_cert.get());
700 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
701 ASSERT_TRUE(pub_key.get());
702
703 Digest digest = params.GetTagValue(TAG_DIGEST).value();
704 PaddingMode padding = PaddingMode::NONE;
705 auto tag = params.GetTagValue(TAG_PADDING);
706 if (tag.has_value()) {
707 padding = tag.value();
708 }
709
710 if (digest == Digest::NONE) {
711 switch (EVP_PKEY_id(pub_key.get())) {
712 case EVP_PKEY_EC: {
713 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
714 size_t data_size = std::min(data.size(), message.size());
715 memcpy(data.data(), message.data(), data_size);
716 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
717 ASSERT_TRUE(ecdsa.get());
718 ASSERT_EQ(1,
719 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
720 reinterpret_cast<const uint8_t*>(signature.data()),
721 signature.size(), ecdsa.get()));
722 break;
723 }
724 case EVP_PKEY_RSA: {
725 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
726 size_t data_size = std::min(data.size(), message.size());
727 memcpy(data.data(), message.data(), data_size);
728
729 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
730 ASSERT_TRUE(rsa.get());
731
732 size_t key_len = RSA_size(rsa.get());
733 int openssl_padding = RSA_NO_PADDING;
734 switch (padding) {
735 case PaddingMode::NONE:
736 ASSERT_TRUE(data_size <= key_len);
737 ASSERT_EQ(key_len, signature.size());
738 openssl_padding = RSA_NO_PADDING;
739 break;
740 case PaddingMode::RSA_PKCS1_1_5_SIGN:
741 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
742 key_len);
743 openssl_padding = RSA_PKCS1_PADDING;
744 break;
745 default:
746 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
747 }
748
749 vector<uint8_t> decrypted_data(key_len);
750 int bytes_decrypted = RSA_public_decrypt(
751 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
752 decrypted_data.data(), rsa.get(), openssl_padding);
753 ASSERT_GE(bytes_decrypted, 0);
754
755 const uint8_t* compare_pos = decrypted_data.data();
756 size_t bytes_to_compare = bytes_decrypted;
757 uint8_t zero_check_result = 0;
758 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
759 // If the data is short, for "unpadded" signing we zero-pad to the left. So
760 // during verification we should have zeros on the left of the decrypted data.
761 // Do a constant-time check.
762 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
763 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
764 ASSERT_EQ(0, zero_check_result);
765 bytes_to_compare = data_size;
766 }
767 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
768 break;
769 }
770 default:
771 ADD_FAILURE() << "Unknown public key type";
772 }
773 } else {
774 EVP_MD_CTX digest_ctx;
775 EVP_MD_CTX_init(&digest_ctx);
776 EVP_PKEY_CTX* pkey_ctx;
777 const EVP_MD* md = openssl_digest(digest);
778 ASSERT_NE(md, nullptr);
779 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
780
781 if (padding == PaddingMode::RSA_PSS) {
782 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
783 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
784 }
785
786 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
787 reinterpret_cast<const uint8_t*>(message.data()),
788 message.size()));
789 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
790 reinterpret_cast<const uint8_t*>(signature.data()),
791 signature.size()));
792 EVP_MD_CTX_cleanup(&digest_ctx);
793 }
794}
795
David Drysdale2b6c3512021-05-12 13:52:03 +0100796string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
797 const AuthorizationSet& params) {
798 SCOPED_TRACE("LocalRsaEncryptMessage");
799
800 // Retrieve the public key from the leaf certificate.
801 if (cert_chain_.empty()) {
802 ADD_FAILURE() << "No public key available";
803 return "Failure";
804 }
805 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
806 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
807 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
808
809 // Retrieve relevant tags.
810 Digest digest = Digest::NONE;
811 Digest mgf_digest = Digest::NONE;
812 PaddingMode padding = PaddingMode::NONE;
813
814 auto digest_tag = params.GetTagValue(TAG_DIGEST);
815 if (digest_tag.has_value()) digest = digest_tag.value();
816 auto pad_tag = params.GetTagValue(TAG_PADDING);
817 if (pad_tag.has_value()) padding = pad_tag.value();
818 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
819 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
820
821 const EVP_MD* md = openssl_digest(digest);
822 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
823
824 // Set up encryption context.
825 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
826 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
827 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
828 return "Failure";
829 }
830
831 int rc = -1;
832 switch (padding) {
833 case PaddingMode::NONE:
834 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
835 break;
836 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
837 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
838 break;
839 case PaddingMode::RSA_OAEP:
840 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
841 break;
842 default:
843 break;
844 }
845 if (rc <= 0) {
846 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
847 return "Failure";
848 }
849 if (padding == PaddingMode::RSA_OAEP) {
850 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
851 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
852 return "Failure";
853 }
854 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
855 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
856 return "Failure";
857 }
858 }
859
860 // Determine output size.
861 size_t outlen;
862 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
863 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
864 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
865 return "Failure";
866 }
867
868 // Left-zero-pad the input if necessary.
869 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
870 size_t to_encrypt_len = message.size();
871
872 std::unique_ptr<string> zero_padded_message;
873 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
874 zero_padded_message.reset(new string(outlen, '\0'));
875 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
876 message.size());
877 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
878 to_encrypt_len = outlen;
879 }
880
881 // Do the encryption.
882 string output(outlen, '\0');
883 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
884 to_encrypt_len) <= 0) {
885 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
886 return "Failure";
887 }
888 return output;
889}
890
Selene Huang31ab4042020-04-29 04:22:39 -0700891string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
892 const AuthorizationSet& in_params,
893 AuthorizationSet* out_params) {
894 SCOPED_TRACE("EncryptMessage");
895 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
896}
897
898string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
899 AuthorizationSet* out_params) {
900 SCOPED_TRACE("EncryptMessage");
901 return EncryptMessage(key_blob_, message, params, out_params);
902}
903
904string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
905 SCOPED_TRACE("EncryptMessage");
906 AuthorizationSet out_params;
907 string ciphertext = EncryptMessage(message, params, &out_params);
908 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
909 return ciphertext;
910}
911
912string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
913 PaddingMode padding) {
914 SCOPED_TRACE("EncryptMessage");
915 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
916 AuthorizationSet out_params;
917 string ciphertext = EncryptMessage(message, params, &out_params);
918 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
919 return ciphertext;
920}
921
922string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
923 PaddingMode padding, vector<uint8_t>* iv_out) {
924 SCOPED_TRACE("EncryptMessage");
925 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
926 AuthorizationSet out_params;
927 string ciphertext = EncryptMessage(message, params, &out_params);
928 EXPECT_EQ(1U, out_params.size());
929 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800930 EXPECT_TRUE(ivVal);
931 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700932 return ciphertext;
933}
934
935string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
936 PaddingMode padding, const vector<uint8_t>& iv_in) {
937 SCOPED_TRACE("EncryptMessage");
938 auto params = AuthorizationSetBuilder()
939 .BlockMode(block_mode)
940 .Padding(padding)
941 .Authorization(TAG_NONCE, iv_in);
942 AuthorizationSet out_params;
943 string ciphertext = EncryptMessage(message, params, &out_params);
944 return ciphertext;
945}
946
947string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
948 PaddingMode padding, uint8_t mac_length_bits,
949 const vector<uint8_t>& iv_in) {
950 SCOPED_TRACE("EncryptMessage");
951 auto params = AuthorizationSetBuilder()
952 .BlockMode(block_mode)
953 .Padding(padding)
954 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
955 .Authorization(TAG_NONCE, iv_in);
956 AuthorizationSet out_params;
957 string ciphertext = EncryptMessage(message, params, &out_params);
958 return ciphertext;
959}
960
David Drysdaled2cc8c22021-04-15 13:29:45 +0100961string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
962 PaddingMode padding, uint8_t mac_length_bits) {
963 SCOPED_TRACE("EncryptMessage");
964 auto params = AuthorizationSetBuilder()
965 .BlockMode(block_mode)
966 .Padding(padding)
967 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
968 AuthorizationSet out_params;
969 string ciphertext = EncryptMessage(message, params, &out_params);
970 return ciphertext;
971}
972
Selene Huang31ab4042020-04-29 04:22:39 -0700973string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
974 const string& ciphertext,
975 const AuthorizationSet& params) {
976 SCOPED_TRACE("DecryptMessage");
977 AuthorizationSet out_params;
978 string plaintext =
979 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
980 EXPECT_TRUE(out_params.empty());
981 return plaintext;
982}
983
984string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
985 const AuthorizationSet& params) {
986 SCOPED_TRACE("DecryptMessage");
987 return DecryptMessage(key_blob_, ciphertext, params);
988}
989
990string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
991 PaddingMode padding_mode, const vector<uint8_t>& iv) {
992 SCOPED_TRACE("DecryptMessage");
993 auto params = AuthorizationSetBuilder()
994 .BlockMode(block_mode)
995 .Padding(padding_mode)
996 .Authorization(TAG_NONCE, iv);
997 return DecryptMessage(key_blob_, ciphertext, params);
998}
999
1000std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1001 const vector<uint8_t>& key_blob) {
1002 std::pair<ErrorCode, vector<uint8_t>> retval;
1003 vector<uint8_t> outKeyBlob;
1004 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1005 ErrorCode errorcode = GetReturnErrorCode(result);
1006 retval = std::tie(errorcode, outKeyBlob);
1007
1008 return retval;
1009}
1010vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1011 switch (algorithm) {
1012 case Algorithm::RSA:
1013 switch (SecLevel()) {
1014 case SecurityLevel::SOFTWARE:
1015 case SecurityLevel::TRUSTED_ENVIRONMENT:
1016 return {2048, 3072, 4096};
1017 case SecurityLevel::STRONGBOX:
1018 return {2048};
1019 default:
1020 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1021 break;
1022 }
1023 break;
1024 case Algorithm::EC:
1025 switch (SecLevel()) {
1026 case SecurityLevel::SOFTWARE:
1027 case SecurityLevel::TRUSTED_ENVIRONMENT:
1028 return {224, 256, 384, 521};
1029 case SecurityLevel::STRONGBOX:
1030 return {256};
1031 default:
1032 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1033 break;
1034 }
1035 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) {
1070 case Algorithm::TRIPLE_DES:
1071 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001072 default:
1073 return {};
1074 }
1075 }
1076 return {};
1077}
1078
David Drysdale7de9feb2021-03-05 14:56:19 +00001079vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1080 switch (algorithm) {
1081 case Algorithm::AES:
1082 return {
1083 BlockMode::CBC,
1084 BlockMode::CTR,
1085 BlockMode::ECB,
1086 BlockMode::GCM,
1087 };
1088 case Algorithm::TRIPLE_DES:
1089 return {
1090 BlockMode::CBC,
1091 BlockMode::ECB,
1092 };
1093 default:
1094 return {};
1095 }
1096}
1097
1098vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1099 BlockMode blockMode) {
1100 switch (algorithm) {
1101 case Algorithm::AES:
1102 switch (blockMode) {
1103 case BlockMode::CBC:
1104 case BlockMode::ECB:
1105 return {PaddingMode::NONE, PaddingMode::PKCS7};
1106 case BlockMode::CTR:
1107 case BlockMode::GCM:
1108 return {PaddingMode::NONE};
1109 default:
1110 return {};
1111 };
1112 case Algorithm::TRIPLE_DES:
1113 switch (blockMode) {
1114 case BlockMode::CBC:
1115 case BlockMode::ECB:
1116 return {PaddingMode::NONE, PaddingMode::PKCS7};
1117 default:
1118 return {};
1119 };
1120 default:
1121 return {};
1122 }
1123}
1124
1125vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1126 BlockMode blockMode) {
1127 switch (algorithm) {
1128 case Algorithm::AES:
1129 switch (blockMode) {
1130 case BlockMode::CTR:
1131 case BlockMode::GCM:
1132 return {PaddingMode::PKCS7};
1133 default:
1134 return {};
1135 };
1136 default:
1137 return {};
1138 }
1139}
1140
Selene Huang31ab4042020-04-29 04:22:39 -07001141vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1142 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1143 return {EcCurve::P_256};
1144 } else {
1145 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1146 }
1147}
1148
1149vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
1150 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
1151 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
1152 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
1153}
1154
1155vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1156 switch (SecLevel()) {
1157 case SecurityLevel::SOFTWARE:
1158 case SecurityLevel::TRUSTED_ENVIRONMENT:
1159 if (withNone) {
1160 if (withMD5)
1161 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1162 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1163 Digest::SHA_2_512};
1164 else
1165 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1166 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1167 } else {
1168 if (withMD5)
1169 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1170 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1171 else
1172 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1173 Digest::SHA_2_512};
1174 }
1175 break;
1176 case SecurityLevel::STRONGBOX:
1177 if (withNone)
1178 return {Digest::NONE, Digest::SHA_2_256};
1179 else
1180 return {Digest::SHA_2_256};
1181 break;
1182 default:
1183 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1184 break;
1185 }
1186 ADD_FAILURE() << "Should be impossible to get here";
1187 return {};
1188}
1189
Shawn Willden7f424372021-01-10 18:06:50 -07001190static const vector<KeyParameter> kEmptyAuthList{};
1191
1192const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1193 const vector<KeyCharacteristics>& key_characteristics) {
1194 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1195 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1196 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1197}
1198
Qi Wubeefae42021-01-28 23:16:37 +08001199const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1200 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1201 auto found = std::find_if(
1202 key_characteristics.begin(), key_characteristics.end(),
1203 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001204 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1205}
1206
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001207ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001208 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001209 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1210 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1211 return result;
1212}
1213
1214ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001215 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001216 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1217 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1218 return result;
1219}
1220
1221ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1222 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001223 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001224 rsaKeyBlob, KeyPurpose::SIGN, message,
1225 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1226 return result;
1227}
1228
1229ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001230 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1231 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001232 return result;
1233}
1234
Selene Huang6e46f142021-04-20 19:20:11 -07001235void verify_serial(X509* cert, const uint64_t expected_serial) {
1236 BIGNUM_Ptr ser(BN_new());
1237 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1238
1239 uint64_t serial;
1240 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1241 EXPECT_EQ(serial, expected_serial);
1242}
1243
1244// Please set self_signed to true for fake certificates or self signed
1245// certificates
1246void verify_subject(const X509* cert, //
1247 const string& subject, //
1248 bool self_signed) {
1249 char* cert_issuer = //
1250 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1251
1252 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1253
1254 string expected_subject("/CN=");
1255 if (subject.empty()) {
1256 expected_subject.append("Android Keystore Key");
1257 } else {
1258 expected_subject.append(subject);
1259 }
1260
1261 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1262
1263 if (self_signed) {
1264 EXPECT_STREQ(cert_issuer, cert_subj)
1265 << "Cert issuer and subject mismatch for self signed certificate.";
1266 }
1267
1268 OPENSSL_free(cert_subj);
1269 OPENSSL_free(cert_issuer);
1270}
1271
1272vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1273 BIGNUM_Ptr serial(BN_new());
1274 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1275
1276 int len = BN_num_bytes(serial.get());
1277 vector<uint8_t> serial_blob(len);
1278 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1279 return {};
1280 }
1281
David Drysdale216d9922021-05-18 11:43:31 +01001282 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1283 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1284 // Top bit being set indicates a negative number in two's complement, but our input
1285 // was positive.
1286 // In either case, prepend a zero byte.
1287 serial_blob.insert(serial_blob.begin(), 0x00);
1288 }
1289
Selene Huang6e46f142021-04-20 19:20:11 -07001290 return serial_blob;
1291}
1292
1293void verify_subject_and_serial(const Certificate& certificate, //
1294 const uint64_t expected_serial, //
1295 const string& subject, bool self_signed) {
1296 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1297 ASSERT_TRUE(!!cert.get());
1298
1299 verify_serial(cert.get(), expected_serial);
1300 verify_subject(cert.get(), subject, self_signed);
1301}
1302
Shawn Willden7c130392020-12-21 09:58:22 -07001303bool verify_attestation_record(const string& challenge, //
1304 const string& app_id, //
1305 AuthorizationSet expected_sw_enforced, //
1306 AuthorizationSet expected_hw_enforced, //
1307 SecurityLevel security_level,
1308 const vector<uint8_t>& attestation_cert) {
1309 X509_Ptr cert(parse_cert_blob(attestation_cert));
1310 EXPECT_TRUE(!!cert.get());
1311 if (!cert.get()) return false;
1312
1313 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1314 EXPECT_TRUE(!!attest_rec);
1315 if (!attest_rec) return false;
1316
1317 AuthorizationSet att_sw_enforced;
1318 AuthorizationSet att_hw_enforced;
1319 uint32_t att_attestation_version;
David Drysdale92464372021-05-14 16:46:59 +01001320 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001321 SecurityLevel att_attestation_security_level;
David Drysdale92464372021-05-14 16:46:59 +01001322 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001323 vector<uint8_t> att_challenge;
1324 vector<uint8_t> att_unique_id;
1325 vector<uint8_t> att_app_id;
1326
1327 auto error = parse_attestation_record(attest_rec->data, //
1328 attest_rec->length, //
1329 &att_attestation_version, //
1330 &att_attestation_security_level, //
David Drysdale92464372021-05-14 16:46:59 +01001331 &att_keymint_version, //
1332 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001333 &att_challenge, //
1334 &att_sw_enforced, //
1335 &att_hw_enforced, //
1336 &att_unique_id);
1337 EXPECT_EQ(ErrorCode::OK, error);
1338 if (error != ErrorCode::OK) return false;
1339
Shawn Willden3cb64a62021-04-05 14:39:05 -06001340 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -07001341 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001342
Selene Huang4f64c222021-04-13 19:54:36 -07001343 // check challenge and app id only if we expects a non-fake certificate
1344 if (challenge.length() > 0) {
1345 EXPECT_EQ(challenge.length(), att_challenge.size());
1346 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1347
1348 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1349 }
Shawn Willden7c130392020-12-21 09:58:22 -07001350
David Drysdale92464372021-05-14 16:46:59 +01001351 EXPECT_EQ(att_keymint_version, 100U);
1352 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001353 EXPECT_EQ(security_level, att_attestation_security_level);
1354
Shawn Willden7c130392020-12-21 09:58:22 -07001355
1356 char property_value[PROPERTY_VALUE_MAX] = {};
1357 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale92464372021-05-14 16:46:59 +01001358 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001359 // for the BOOT_PATCH_LEVEL.
1360 if (avb_verification_enabled()) {
1361 for (int i = 0; i < att_hw_enforced.size(); i++) {
1362 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1363 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1364 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001365 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -07001366 // strptime seems to require delimiters, but the tag value will
1367 // be YYYYMMDD
1368 date.insert(6, "-");
1369 date.insert(4, "-");
1370 EXPECT_EQ(date.size(), 10);
1371 struct tm time;
1372 strptime(date.c_str(), "%Y-%m-%d", &time);
1373
1374 // Day of the month (0-31)
1375 EXPECT_GE(time.tm_mday, 0);
1376 EXPECT_LT(time.tm_mday, 32);
1377 // Months since Jan (0-11)
1378 EXPECT_GE(time.tm_mon, 0);
1379 EXPECT_LT(time.tm_mon, 12);
1380 // Years since 1900
1381 EXPECT_GT(time.tm_year, 110);
1382 EXPECT_LT(time.tm_year, 200);
1383 }
1384 }
1385 }
1386
1387 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1388 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1389 // indicates correct encoding. No need to check if it's in both lists, since the
1390 // AuthorizationSet compare below will handle mismatches of tags.
1391 if (security_level == SecurityLevel::SOFTWARE) {
1392 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1393 } else {
1394 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1395 }
1396
Shawn Willden7c130392020-12-21 09:58:22 -07001397 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1398 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1399 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1400 att_hw_enforced.Contains(TAG_KEY_SIZE));
1401 }
1402
1403 // Test root of trust elements
1404 vector<uint8_t> verified_boot_key;
1405 VerifiedBoot verified_boot_state;
1406 bool device_locked;
1407 vector<uint8_t> verified_boot_hash;
1408 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1409 &verified_boot_state, &device_locked, &verified_boot_hash);
1410 EXPECT_EQ(ErrorCode::OK, error);
1411
1412 if (avb_verification_enabled()) {
1413 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1414 string prop_string(property_value);
1415 EXPECT_EQ(prop_string.size(), 64);
1416 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1417
1418 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1419 if (!strcmp(property_value, "unlocked")) {
1420 EXPECT_FALSE(device_locked);
1421 } else {
1422 EXPECT_TRUE(device_locked);
1423 }
1424
1425 // Check that the device is locked if not debuggable, e.g., user build
1426 // images in CTS. For VTS, debuggable images are used to allow adb root
1427 // and the device is unlocked.
1428 if (!property_get_bool("ro.debuggable", false)) {
1429 EXPECT_TRUE(device_locked);
1430 } else {
1431 EXPECT_FALSE(device_locked);
1432 }
1433 }
1434
1435 // Verified boot key should be all 0's if the boot state is not verified or self signed
1436 std::string empty_boot_key(32, '\0');
1437 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1438 verified_boot_key.size());
1439 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1440 if (!strcmp(property_value, "green")) {
1441 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1442 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1443 verified_boot_key.size()));
1444 } else if (!strcmp(property_value, "yellow")) {
1445 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1446 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1447 verified_boot_key.size()));
1448 } else if (!strcmp(property_value, "orange")) {
1449 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1450 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1451 verified_boot_key.size()));
1452 } else if (!strcmp(property_value, "red")) {
1453 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1454 } else {
1455 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1456 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1457 verified_boot_key.size()));
1458 }
1459
1460 att_sw_enforced.Sort();
1461 expected_sw_enforced.Sort();
David Drysdale92464372021-05-14 16:46:59 +01001462 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001463
1464 att_hw_enforced.Sort();
1465 expected_hw_enforced.Sort();
1466 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1467
1468 return true;
1469}
1470
1471string bin2hex(const vector<uint8_t>& data) {
1472 string retval;
1473 retval.reserve(data.size() * 2 + 1);
1474 for (uint8_t byte : data) {
1475 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1476 retval.push_back(nibble2hex[0x0F & byte]);
1477 }
1478 return retval;
1479}
1480
David Drysdalef0d516d2021-03-22 07:51:43 +00001481AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1482 AuthorizationSet authList;
1483 for (auto& entry : key_characteristics) {
1484 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1485 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1486 authList.push_back(AuthorizationSet(entry.authorizations));
1487 }
1488 }
1489 return authList;
1490}
1491
1492AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1493 AuthorizationSet authList;
1494 for (auto& entry : key_characteristics) {
1495 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1496 entry.securityLevel == SecurityLevel::KEYSTORE) {
1497 authList.push_back(AuthorizationSet(entry.authorizations));
1498 }
1499 }
1500 return authList;
1501}
1502
Shawn Willden7c130392020-12-21 09:58:22 -07001503AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1504 std::stringstream cert_data;
1505
1506 for (size_t i = 0; i < chain.size(); ++i) {
1507 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1508
1509 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1510 X509_Ptr signing_cert;
1511 if (i < chain.size() - 1) {
1512 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1513 } else {
1514 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1515 }
1516 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1517
1518 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1519 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1520
1521 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1522 return AssertionFailure()
1523 << "Verification of certificate " << i << " failed "
1524 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1525 << cert_data.str();
1526 }
1527
1528 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1529 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1530 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001531 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1532 << " Signer subject is " << signer_subj
1533 << " Issuer subject is " << cert_issuer << endl
1534 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001535 }
Shawn Willden7c130392020-12-21 09:58:22 -07001536 }
1537
1538 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1539 return AssertionSuccess();
1540}
1541
1542X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1543 const uint8_t* p = blob.data();
1544 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1545}
1546
David Drysdalef0d516d2021-03-22 07:51:43 +00001547vector<uint8_t> make_name_from_str(const string& name) {
1548 X509_NAME_Ptr x509_name(X509_NAME_new());
1549 EXPECT_TRUE(x509_name.get() != nullptr);
1550 if (!x509_name) return {};
1551
1552 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1553 "CN", //
1554 MBSTRING_ASC,
1555 reinterpret_cast<const uint8_t*>(name.c_str()),
1556 -1, // len
1557 -1, // loc
1558 0 /* set */));
1559
1560 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1561 EXPECT_GT(len, 0);
1562
1563 vector<uint8_t> retval(len);
1564 uint8_t* p = retval.data();
1565 i2d_X509_NAME(x509_name.get(), &p);
1566
1567 return retval;
1568}
1569
David Drysdale4dc01072021-04-01 12:17:35 +01001570namespace {
1571
1572void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1573 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1574 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1575
1576 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1577 if (testMode) {
1578 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1579 MatchesRegex("{\n"
1580 " 1 : 2,\n" // kty: EC2
1581 " 3 : -7,\n" // alg: ES256
1582 " -1 : 1,\n" // EC id: P256
1583 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1584 // sequence of 32 hexadecimal bytes, enclosed in braces and
1585 // separated by commas. In this case, some Ed25519 public key.
1586 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1587 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1588 " -70000 : null,\n" // test marker
1589 "}"));
1590 } else {
1591 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1592 MatchesRegex("{\n"
1593 " 1 : 2,\n" // kty: EC2
1594 " 3 : -7,\n" // alg: ES256
1595 " -1 : 1,\n" // EC id: P256
1596 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1597 // sequence of 32 hexadecimal bytes, enclosed in braces and
1598 // separated by commas. In this case, some Ed25519 public key.
1599 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1600 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1601 "}"));
1602 }
1603}
1604
1605} // namespace
1606
1607void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1608 vector<uint8_t>* payload_value) {
1609 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1610 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1611
1612 ASSERT_NE(coseMac0->asArray(), nullptr);
1613 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1614
1615 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1616 ASSERT_NE(protParms, nullptr);
1617
1618 // Header label:value of 'alg': HMAC-256
1619 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1620
1621 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1622 ASSERT_NE(unprotParms, nullptr);
1623 ASSERT_EQ(unprotParms->size(), 0);
1624
1625 // The payload is a bstr holding an encoded COSE_Key
1626 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1627 ASSERT_NE(payload, nullptr);
1628 check_cose_key(payload->value(), testMode);
1629
1630 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1631 ASSERT_TRUE(coseMac0Tag);
1632 auto extractedTag = coseMac0Tag->value();
1633 EXPECT_EQ(extractedTag.size(), 32U);
1634
1635 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore7735ba52021-04-30 11:41:18 -07001636 auto macFunction = [](const cppcose::bytevec& input) {
1637 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1638 };
1639 auto testTag =
1640 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001641 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1642
1643 if (testMode) {
Seth Moore7735ba52021-04-30 11:41:18 -07001644 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001645 } else {
Seth Moore7735ba52021-04-30 11:41:18 -07001646 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001647 }
1648 if (payload_value != nullptr) {
1649 *payload_value = payload->value();
1650 }
1651}
1652
1653void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1654 // Extract x and y affine coordinates from the encoded Cose_Key.
1655 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1656 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1657 auto coseKey = parsedPayload->asMap();
1658 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1659 ASSERT_NE(xItem->asBstr(), nullptr);
1660 vector<uint8_t> x = xItem->asBstr()->value();
1661 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1662 ASSERT_NE(yItem->asBstr(), nullptr);
1663 vector<uint8_t> y = yItem->asBstr()->value();
1664
1665 // Concatenate: 0x04 (uncompressed form marker) | x | y
1666 vector<uint8_t> pubKeyData{0x04};
1667 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1668 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1669
1670 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1671 ASSERT_NE(ecKey, nullptr);
1672 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1673 ASSERT_NE(group, nullptr);
1674 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1675 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1676 ASSERT_NE(point, nullptr);
1677 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1678 nullptr),
1679 1);
1680 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1681
1682 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1683 ASSERT_NE(pubKey, nullptr);
1684 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1685 *signingKey = std::move(pubKey);
1686}
1687
Selene Huang31ab4042020-04-29 04:22:39 -07001688} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001689
Janis Danisevskis24c04702020-12-16 18:28:39 -08001690} // namespace aidl::android::hardware::security::keymint