blob: 44b015f4efa81fa990c80efdfcfa6a3f9b20fbd0 [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;
David Drysdale4dc01072021-04-01 12:17:35 +010047using ::testing::MatchesRegex;
Selene Huang31ab4042020-04-29 04:22:39 -070048
49::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
50 if (set.size() == 0)
51 os << "(Empty)" << ::std::endl;
52 else {
53 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070054 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070055 }
56 return os;
57}
58
59namespace test {
60
Shawn Willden7f424372021-01-10 18:06:50 -070061namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010062
63// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
64// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
65const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
66
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000067typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070068// Predicate for testing basic characteristics validity in generation or import.
69bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
70 const vector<KeyCharacteristics>& key_characteristics) {
71 if (key_characteristics.empty()) return false;
72
73 std::unordered_set<SecurityLevel> levels_seen;
74 for (auto& entry : key_characteristics) {
75 if (entry.authorizations.empty()) return false;
76
Qi Wubeefae42021-01-28 23:16:37 +080077 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
78 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
79
Shawn Willden7f424372021-01-10 18:06:50 -070080 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
81 levels_seen.insert(entry.securityLevel);
82
83 // Generally, we should only have one entry, at the same security level as the KM
84 // instance. There is an exception: StrongBox KM can have some authorizations that are
85 // enforced by the TEE.
86 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
87 (secLevel == SecurityLevel::STRONGBOX &&
88 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
89
90 if (!isExpectedSecurityLevel) return false;
91 }
92 return true;
93}
94
Shawn Willden7c130392020-12-21 09:58:22 -070095// Extract attestation record from cert. Returned object is still part of cert; don't free it
96// separately.
97ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
98 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
99 EXPECT_TRUE(!!oid.get());
100 if (!oid.get()) return nullptr;
101
102 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
103 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
104 if (location == -1) return nullptr;
105
106 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
107 EXPECT_TRUE(!!attest_rec_ext)
108 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
109 if (!attest_rec_ext) return nullptr;
110
111 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
112 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
113 return attest_rec;
114}
115
116bool avb_verification_enabled() {
117 char value[PROPERTY_VALUE_MAX];
118 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
119}
120
121char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
122 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
123
124// Attestations don't contain everything in key authorization lists, so we need to filter the key
125// lists to produce the lists that we expect to match the attestations.
126auto kTagsToFilter = {
Tommy Chiuc93c4392021-05-11 18:36:50 +0800127 Tag::CREATION_DATETIME,
128 Tag::EC_CURVE,
129 Tag::HARDWARE_TYPE,
130 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700131};
132
133AuthorizationSet filtered_tags(const AuthorizationSet& set) {
134 AuthorizationSet filtered;
135 std::remove_copy_if(
136 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
137 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
138 kTagsToFilter.end();
139 });
140 return filtered;
141}
142
David Drysdale300b5552021-05-20 12:05:26 +0100143// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
144void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
145 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
146 [](const auto& entry) {
147 return entry.securityLevel == SecurityLevel::KEYSTORE;
148 }),
149 characteristics->end());
150}
151
Shawn Willden7c130392020-12-21 09:58:22 -0700152string x509NameToStr(X509_NAME* name) {
153 char* s = X509_NAME_oneline(name, nullptr, 0);
154 string retval(s);
155 OPENSSL_free(s);
156 return retval;
157}
158
Shawn Willden7f424372021-01-10 18:06:50 -0700159} // namespace
160
Shawn Willden7c130392020-12-21 09:58:22 -0700161bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
162bool KeyMintAidlTestBase::dump_Attestations = false;
163
Janis Danisevskis24c04702020-12-16 18:28:39 -0800164ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700165 if (result.isOk()) return ErrorCode::OK;
166
Janis Danisevskis24c04702020-12-16 18:28:39 -0800167 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
168 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700169 }
170
171 return ErrorCode::UNKNOWN_ERROR;
172}
173
Janis Danisevskis24c04702020-12-16 18:28:39 -0800174void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700175 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800176 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700177
178 KeyMintHardwareInfo info;
179 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
180
181 securityLevel_ = info.securityLevel;
182 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
183 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100184 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700185
186 os_version_ = getOsVersion();
187 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100188 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700189}
190
191void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800192 if (AServiceManager_isDeclared(GetParam().c_str())) {
193 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
194 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
195 } else {
196 InitializeKeyMint(nullptr);
197 }
Selene Huang31ab4042020-04-29 04:22:39 -0700198}
199
200ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700201 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700202 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700203 vector<KeyCharacteristics>* key_characteristics,
204 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700205 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
206 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700207 << "Previous characteristics not deleted before generating key. Test bug.";
208
Shawn Willden7f424372021-01-10 18:06:50 -0700209 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700210 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700211 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700212 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
213 creationResult.keyCharacteristics);
214 EXPECT_GT(creationResult.keyBlob.size(), 0);
215 *key_blob = std::move(creationResult.keyBlob);
216 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700217 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700218
219 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
220 EXPECT_TRUE(algorithm);
221 if (algorithm &&
222 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700223 EXPECT_GE(cert_chain->size(), 1);
224 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
225 if (attest_key) {
226 EXPECT_EQ(cert_chain->size(), 1);
227 } else {
228 EXPECT_GT(cert_chain->size(), 1);
229 }
230 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700231 } else {
232 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700233 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700234 }
Selene Huang31ab4042020-04-29 04:22:39 -0700235 }
236
237 return GetReturnErrorCode(result);
238}
239
Shawn Willden7c130392020-12-21 09:58:22 -0700240ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
241 const optional<AttestationKey>& attest_key) {
242 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700243}
244
245ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
246 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700247 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700248 Status result;
249
Shawn Willden7f424372021-01-10 18:06:50 -0700250 cert_chain_.clear();
251 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700252 key_blob->clear();
253
Shawn Willden7f424372021-01-10 18:06:50 -0700254 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700255 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700256 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700257 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700258
259 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700260 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
261 creationResult.keyCharacteristics);
262 EXPECT_GT(creationResult.keyBlob.size(), 0);
263
264 *key_blob = std::move(creationResult.keyBlob);
265 *key_characteristics = std::move(creationResult.keyCharacteristics);
266 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700267
268 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
269 EXPECT_TRUE(algorithm);
270 if (algorithm &&
271 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
272 EXPECT_GE(cert_chain_.size(), 1);
273 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
274 } else {
275 // For symmetric keys there should be no certificates.
276 EXPECT_EQ(cert_chain_.size(), 0);
277 }
Selene Huang31ab4042020-04-29 04:22:39 -0700278 }
279
280 return GetReturnErrorCode(result);
281}
282
283ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
284 const string& key_material) {
285 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
286}
287
288ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
289 const AuthorizationSet& wrapping_key_desc,
290 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100291 const AuthorizationSet& unwrapping_params,
292 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700293 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
294
Shawn Willden7f424372021-01-10 18:06:50 -0700295 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700296
Shawn Willden7f424372021-01-10 18:06:50 -0700297 KeyCreationResult creationResult;
298 Status result = keymint_->importWrappedKey(
299 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
300 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700302
303 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700304 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
305 creationResult.keyCharacteristics);
306 EXPECT_GT(creationResult.keyBlob.size(), 0);
307
308 key_blob_ = std::move(creationResult.keyBlob);
309 key_characteristics_ = std::move(creationResult.keyCharacteristics);
310 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700311
312 AuthorizationSet allAuths;
313 for (auto& entry : key_characteristics_) {
314 allAuths.push_back(AuthorizationSet(entry.authorizations));
315 }
316 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
317 EXPECT_TRUE(algorithm);
318 if (algorithm &&
319 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
320 EXPECT_GE(cert_chain_.size(), 1);
321 } else {
322 // For symmetric keys there should be no certificates.
323 EXPECT_EQ(cert_chain_.size(), 0);
324 }
Selene Huang31ab4042020-04-29 04:22:39 -0700325 }
326
327 return GetReturnErrorCode(result);
328}
329
David Drysdale300b5552021-05-20 12:05:26 +0100330ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
331 const vector<uint8_t>& app_id,
332 const vector<uint8_t>& app_data,
333 vector<KeyCharacteristics>* key_characteristics) {
334 Status result =
335 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
336 return GetReturnErrorCode(result);
337}
338
339ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
340 vector<KeyCharacteristics>* key_characteristics) {
341 vector<uint8_t> empty_app_id, empty_app_data;
342 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
343}
344
345void KeyMintAidlTestBase::CheckCharacteristics(
346 const vector<uint8_t>& key_blob,
347 const vector<KeyCharacteristics>& generate_characteristics) {
348 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
349 // generateKey() should be excluded, as KeyMint will have no record of them.
350 // This applies to CREATION_DATETIME in particular.
351 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
352 strip_keystore_tags(&expected_characteristics);
353
354 vector<KeyCharacteristics> retrieved;
355 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
356 EXPECT_EQ(expected_characteristics, retrieved);
357}
358
359void KeyMintAidlTestBase::CheckAppIdCharacteristics(
360 const vector<uint8_t>& key_blob, std::string_view app_id_string,
361 std::string_view app_data_string,
362 const vector<KeyCharacteristics>& generate_characteristics) {
363 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
364 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
365 strip_keystore_tags(&expected_characteristics);
366
367 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
368 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
369 vector<KeyCharacteristics> retrieved;
370 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
371 EXPECT_EQ(expected_characteristics, retrieved);
372
373 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
374 vector<uint8_t> empty;
375 vector<KeyCharacteristics> not_retrieved;
376 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
377 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
378 EXPECT_EQ(not_retrieved.size(), 0);
379
380 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
381 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
382 EXPECT_EQ(not_retrieved.size(), 0);
383
384 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
385 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
386 EXPECT_EQ(not_retrieved.size(), 0);
387}
388
Selene Huang31ab4042020-04-29 04:22:39 -0700389ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
390 Status result = keymint_->deleteKey(*key_blob);
391 if (!keep_key_blob) {
392 *key_blob = vector<uint8_t>();
393 }
394
Janis Danisevskis24c04702020-12-16 18:28:39 -0800395 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700396 return GetReturnErrorCode(result);
397}
398
399ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
400 return DeleteKey(&key_blob_, keep_key_blob);
401}
402
403ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
404 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800405 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700406 return GetReturnErrorCode(result);
407}
408
David Drysdaled2cc8c22021-04-15 13:29:45 +0100409ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
410 Status result = keymint_->destroyAttestationIds();
411 return GetReturnErrorCode(result);
412}
413
Selene Huang31ab4042020-04-29 04:22:39 -0700414void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
415 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
416 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
417}
418
419void KeyMintAidlTestBase::CheckedDeleteKey() {
420 CheckedDeleteKey(&key_blob_);
421}
422
423ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
424 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800425 AuthorizationSet* out_params,
426 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700427 SCOPED_TRACE("Begin");
428 Status result;
429 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100430 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700431
432 if (result.isOk()) {
433 *out_params = out.params;
434 challenge_ = out.challenge;
435 op = out.operation;
436 }
437
438 return GetReturnErrorCode(result);
439}
440
441ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
442 const AuthorizationSet& in_params,
443 AuthorizationSet* out_params) {
444 SCOPED_TRACE("Begin");
445 Status result;
446 BeginResult out;
447
David Drysdale56ba9122021-04-19 19:10:47 +0100448 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700449
450 if (result.isOk()) {
451 *out_params = out.params;
452 challenge_ = out.challenge;
453 op_ = out.operation;
454 }
455
456 return GetReturnErrorCode(result);
457}
458
459ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
460 AuthorizationSet* out_params) {
461 SCOPED_TRACE("Begin");
462 EXPECT_EQ(nullptr, op_);
463 return Begin(purpose, key_blob_, in_params, out_params);
464}
465
466ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
467 SCOPED_TRACE("Begin");
468 AuthorizationSet out_params;
469 ErrorCode result = Begin(purpose, in_params, &out_params);
470 EXPECT_TRUE(out_params.empty());
471 return result;
472}
473
Shawn Willden92d79c02021-02-19 07:31:55 -0700474ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
475 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
476 {} /* hardwareAuthToken */,
477 {} /* verificationToken */));
478}
479
480ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700481 SCOPED_TRACE("Update");
482
483 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700484 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700485
Shawn Willden92d79c02021-02-19 07:31:55 -0700486 std::vector<uint8_t> o_put;
487 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700488
Shawn Willden92d79c02021-02-19 07:31:55 -0700489 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700490
491 return GetReturnErrorCode(result);
492}
493
Shawn Willden92d79c02021-02-19 07:31:55 -0700494ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700495 string* output) {
496 SCOPED_TRACE("Finish");
497 Status result;
498
499 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700500 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700501
502 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700503 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
504 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
505 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700506
Shawn Willden92d79c02021-02-19 07:31:55 -0700507 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700508
Shawn Willden92d79c02021-02-19 07:31:55 -0700509 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700510 return GetReturnErrorCode(result);
511}
512
Janis Danisevskis24c04702020-12-16 18:28:39 -0800513ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700514 SCOPED_TRACE("Abort");
515
516 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700517 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700518
519 Status retval = op->abort();
520 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800521 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700522}
523
524ErrorCode KeyMintAidlTestBase::Abort() {
525 SCOPED_TRACE("Abort");
526
527 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700528 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700529
530 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800531 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700532}
533
534void KeyMintAidlTestBase::AbortIfNeeded() {
535 SCOPED_TRACE("AbortIfNeeded");
536 if (op_) {
537 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800538 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700539 }
540}
541
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000542auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
543 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700544 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000545 AuthorizationSet begin_out_params;
546 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700547 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000548
549 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700550 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000551}
552
Selene Huang31ab4042020-04-29 04:22:39 -0700553string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
554 const string& message, const AuthorizationSet& in_params,
555 AuthorizationSet* out_params) {
556 SCOPED_TRACE("ProcessMessage");
557 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700558 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700559 EXPECT_EQ(ErrorCode::OK, result);
560 if (result != ErrorCode::OK) {
561 return "";
562 }
563
564 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700565 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700566 return output;
567}
568
569string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
570 const AuthorizationSet& params) {
571 SCOPED_TRACE("SignMessage");
572 AuthorizationSet out_params;
573 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
574 EXPECT_TRUE(out_params.empty());
575 return signature;
576}
577
578string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
579 SCOPED_TRACE("SignMessage");
580 return SignMessage(key_blob_, message, params);
581}
582
583string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
584 SCOPED_TRACE("MacMessage");
585 return SignMessage(
586 key_blob_, message,
587 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
588}
589
590void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
591 Digest digest, const string& expected_mac) {
592 SCOPED_TRACE("CheckHmacTestVector");
593 ASSERT_EQ(ErrorCode::OK,
594 ImportKey(AuthorizationSetBuilder()
595 .Authorization(TAG_NO_AUTH_REQUIRED)
596 .HmacKey(key.size() * 8)
597 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
598 .Digest(digest),
599 KeyFormat::RAW, key));
600 string signature = MacMessage(message, digest, expected_mac.size() * 8);
601 EXPECT_EQ(expected_mac, signature)
602 << "Test vector didn't match for key of size " << key.size() << " message of size "
603 << message.size() << " and digest " << digest;
604 CheckedDeleteKey();
605}
606
607void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
608 const string& message,
609 const string& expected_ciphertext) {
610 SCOPED_TRACE("CheckAesCtrTestVector");
611 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
612 .Authorization(TAG_NO_AUTH_REQUIRED)
613 .AesEncryptionKey(key.size() * 8)
614 .BlockMode(BlockMode::CTR)
615 .Authorization(TAG_CALLER_NONCE)
616 .Padding(PaddingMode::NONE),
617 KeyFormat::RAW, key));
618
619 auto params = AuthorizationSetBuilder()
620 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
621 .BlockMode(BlockMode::CTR)
622 .Padding(PaddingMode::NONE);
623 AuthorizationSet out_params;
624 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
625 EXPECT_EQ(expected_ciphertext, ciphertext);
626}
627
628void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
629 PaddingMode padding_mode, const string& key,
630 const string& iv, const string& input,
631 const string& expected_output) {
632 auto authset = AuthorizationSetBuilder()
633 .TripleDesEncryptionKey(key.size() * 7)
634 .BlockMode(block_mode)
635 .Authorization(TAG_NO_AUTH_REQUIRED)
636 .Padding(padding_mode);
637 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
638 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
639 ASSERT_GT(key_blob_.size(), 0U);
640
641 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
642 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
643 AuthorizationSet output_params;
644 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
645 EXPECT_EQ(expected_output, output);
646}
647
648void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
649 const string& signature, const AuthorizationSet& params) {
650 SCOPED_TRACE("VerifyMessage");
651 AuthorizationSet begin_out_params;
652 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
653
654 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700655 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700656 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700657 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700658}
659
660void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
661 const AuthorizationSet& params) {
662 SCOPED_TRACE("VerifyMessage");
663 VerifyMessage(key_blob_, message, signature, params);
664}
665
David Drysdaledf8f52e2021-05-06 08:10:58 +0100666void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
667 const AuthorizationSet& params) {
668 SCOPED_TRACE("LocalVerifyMessage");
669
670 // Retrieve the public key from the leaf certificate.
671 ASSERT_GT(cert_chain_.size(), 0);
672 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
673 ASSERT_TRUE(key_cert.get());
674 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
675 ASSERT_TRUE(pub_key.get());
676
677 Digest digest = params.GetTagValue(TAG_DIGEST).value();
678 PaddingMode padding = PaddingMode::NONE;
679 auto tag = params.GetTagValue(TAG_PADDING);
680 if (tag.has_value()) {
681 padding = tag.value();
682 }
683
684 if (digest == Digest::NONE) {
685 switch (EVP_PKEY_id(pub_key.get())) {
686 case EVP_PKEY_EC: {
687 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
688 size_t data_size = std::min(data.size(), message.size());
689 memcpy(data.data(), message.data(), data_size);
690 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
691 ASSERT_TRUE(ecdsa.get());
692 ASSERT_EQ(1,
693 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
694 reinterpret_cast<const uint8_t*>(signature.data()),
695 signature.size(), ecdsa.get()));
696 break;
697 }
698 case EVP_PKEY_RSA: {
699 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
700 size_t data_size = std::min(data.size(), message.size());
701 memcpy(data.data(), message.data(), data_size);
702
703 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
704 ASSERT_TRUE(rsa.get());
705
706 size_t key_len = RSA_size(rsa.get());
707 int openssl_padding = RSA_NO_PADDING;
708 switch (padding) {
709 case PaddingMode::NONE:
710 ASSERT_TRUE(data_size <= key_len);
711 ASSERT_EQ(key_len, signature.size());
712 openssl_padding = RSA_NO_PADDING;
713 break;
714 case PaddingMode::RSA_PKCS1_1_5_SIGN:
715 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
716 key_len);
717 openssl_padding = RSA_PKCS1_PADDING;
718 break;
719 default:
720 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
721 }
722
723 vector<uint8_t> decrypted_data(key_len);
724 int bytes_decrypted = RSA_public_decrypt(
725 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
726 decrypted_data.data(), rsa.get(), openssl_padding);
727 ASSERT_GE(bytes_decrypted, 0);
728
729 const uint8_t* compare_pos = decrypted_data.data();
730 size_t bytes_to_compare = bytes_decrypted;
731 uint8_t zero_check_result = 0;
732 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
733 // If the data is short, for "unpadded" signing we zero-pad to the left. So
734 // during verification we should have zeros on the left of the decrypted data.
735 // Do a constant-time check.
736 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
737 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
738 ASSERT_EQ(0, zero_check_result);
739 bytes_to_compare = data_size;
740 }
741 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
742 break;
743 }
744 default:
745 ADD_FAILURE() << "Unknown public key type";
746 }
747 } else {
748 EVP_MD_CTX digest_ctx;
749 EVP_MD_CTX_init(&digest_ctx);
750 EVP_PKEY_CTX* pkey_ctx;
751 const EVP_MD* md = openssl_digest(digest);
752 ASSERT_NE(md, nullptr);
753 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
754
755 if (padding == PaddingMode::RSA_PSS) {
756 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
757 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
758 }
759
760 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
761 reinterpret_cast<const uint8_t*>(message.data()),
762 message.size()));
763 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
764 reinterpret_cast<const uint8_t*>(signature.data()),
765 signature.size()));
766 EVP_MD_CTX_cleanup(&digest_ctx);
767 }
768}
769
David Drysdale59cae642021-05-12 13:52:03 +0100770string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
771 const AuthorizationSet& params) {
772 SCOPED_TRACE("LocalRsaEncryptMessage");
773
774 // Retrieve the public key from the leaf certificate.
775 if (cert_chain_.empty()) {
776 ADD_FAILURE() << "No public key available";
777 return "Failure";
778 }
779 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
780 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
781 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
782
783 // Retrieve relevant tags.
784 Digest digest = Digest::NONE;
785 Digest mgf_digest = Digest::NONE;
786 PaddingMode padding = PaddingMode::NONE;
787
788 auto digest_tag = params.GetTagValue(TAG_DIGEST);
789 if (digest_tag.has_value()) digest = digest_tag.value();
790 auto pad_tag = params.GetTagValue(TAG_PADDING);
791 if (pad_tag.has_value()) padding = pad_tag.value();
792 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
793 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
794
795 const EVP_MD* md = openssl_digest(digest);
796 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
797
798 // Set up encryption context.
799 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
800 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
801 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
802 return "Failure";
803 }
804
805 int rc = -1;
806 switch (padding) {
807 case PaddingMode::NONE:
808 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
809 break;
810 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
811 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
812 break;
813 case PaddingMode::RSA_OAEP:
814 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
815 break;
816 default:
817 break;
818 }
819 if (rc <= 0) {
820 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
821 return "Failure";
822 }
823 if (padding == PaddingMode::RSA_OAEP) {
824 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
825 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
826 return "Failure";
827 }
828 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
829 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
830 return "Failure";
831 }
832 }
833
834 // Determine output size.
835 size_t outlen;
836 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
837 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
838 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
839 return "Failure";
840 }
841
842 // Left-zero-pad the input if necessary.
843 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
844 size_t to_encrypt_len = message.size();
845
846 std::unique_ptr<string> zero_padded_message;
847 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
848 zero_padded_message.reset(new string(outlen, '\0'));
849 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
850 message.size());
851 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
852 to_encrypt_len = outlen;
853 }
854
855 // Do the encryption.
856 string output(outlen, '\0');
857 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
858 to_encrypt_len) <= 0) {
859 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
860 return "Failure";
861 }
862 return output;
863}
864
Selene Huang31ab4042020-04-29 04:22:39 -0700865string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
866 const AuthorizationSet& in_params,
867 AuthorizationSet* out_params) {
868 SCOPED_TRACE("EncryptMessage");
869 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
870}
871
872string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
873 AuthorizationSet* out_params) {
874 SCOPED_TRACE("EncryptMessage");
875 return EncryptMessage(key_blob_, message, params, out_params);
876}
877
878string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
879 SCOPED_TRACE("EncryptMessage");
880 AuthorizationSet out_params;
881 string ciphertext = EncryptMessage(message, params, &out_params);
882 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
883 return ciphertext;
884}
885
886string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
887 PaddingMode padding) {
888 SCOPED_TRACE("EncryptMessage");
889 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
890 AuthorizationSet out_params;
891 string ciphertext = EncryptMessage(message, params, &out_params);
892 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
893 return ciphertext;
894}
895
896string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
897 PaddingMode padding, vector<uint8_t>* iv_out) {
898 SCOPED_TRACE("EncryptMessage");
899 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
900 AuthorizationSet out_params;
901 string ciphertext = EncryptMessage(message, params, &out_params);
902 EXPECT_EQ(1U, out_params.size());
903 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800904 EXPECT_TRUE(ivVal);
905 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700906 return ciphertext;
907}
908
909string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
910 PaddingMode padding, const vector<uint8_t>& iv_in) {
911 SCOPED_TRACE("EncryptMessage");
912 auto params = AuthorizationSetBuilder()
913 .BlockMode(block_mode)
914 .Padding(padding)
915 .Authorization(TAG_NONCE, iv_in);
916 AuthorizationSet out_params;
917 string ciphertext = EncryptMessage(message, params, &out_params);
918 return ciphertext;
919}
920
921string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
922 PaddingMode padding, uint8_t mac_length_bits,
923 const vector<uint8_t>& iv_in) {
924 SCOPED_TRACE("EncryptMessage");
925 auto params = AuthorizationSetBuilder()
926 .BlockMode(block_mode)
927 .Padding(padding)
928 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
929 .Authorization(TAG_NONCE, iv_in);
930 AuthorizationSet out_params;
931 string ciphertext = EncryptMessage(message, params, &out_params);
932 return ciphertext;
933}
934
David Drysdaled2cc8c22021-04-15 13:29:45 +0100935string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
936 PaddingMode padding, uint8_t mac_length_bits) {
937 SCOPED_TRACE("EncryptMessage");
938 auto params = AuthorizationSetBuilder()
939 .BlockMode(block_mode)
940 .Padding(padding)
941 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
942 AuthorizationSet out_params;
943 string ciphertext = EncryptMessage(message, params, &out_params);
944 return ciphertext;
945}
946
Selene Huang31ab4042020-04-29 04:22:39 -0700947string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
948 const string& ciphertext,
949 const AuthorizationSet& params) {
950 SCOPED_TRACE("DecryptMessage");
951 AuthorizationSet out_params;
952 string plaintext =
953 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
954 EXPECT_TRUE(out_params.empty());
955 return plaintext;
956}
957
958string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
959 const AuthorizationSet& params) {
960 SCOPED_TRACE("DecryptMessage");
961 return DecryptMessage(key_blob_, ciphertext, params);
962}
963
964string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
965 PaddingMode padding_mode, const vector<uint8_t>& iv) {
966 SCOPED_TRACE("DecryptMessage");
967 auto params = AuthorizationSetBuilder()
968 .BlockMode(block_mode)
969 .Padding(padding_mode)
970 .Authorization(TAG_NONCE, iv);
971 return DecryptMessage(key_blob_, ciphertext, params);
972}
973
974std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
975 const vector<uint8_t>& key_blob) {
976 std::pair<ErrorCode, vector<uint8_t>> retval;
977 vector<uint8_t> outKeyBlob;
978 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
979 ErrorCode errorcode = GetReturnErrorCode(result);
980 retval = std::tie(errorcode, outKeyBlob);
981
982 return retval;
983}
984vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
985 switch (algorithm) {
986 case Algorithm::RSA:
987 switch (SecLevel()) {
988 case SecurityLevel::SOFTWARE:
989 case SecurityLevel::TRUSTED_ENVIRONMENT:
990 return {2048, 3072, 4096};
991 case SecurityLevel::STRONGBOX:
992 return {2048};
993 default:
994 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
995 break;
996 }
997 break;
998 case Algorithm::EC:
999 switch (SecLevel()) {
1000 case SecurityLevel::SOFTWARE:
1001 case SecurityLevel::TRUSTED_ENVIRONMENT:
1002 return {224, 256, 384, 521};
1003 case SecurityLevel::STRONGBOX:
1004 return {256};
1005 default:
1006 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1007 break;
1008 }
1009 break;
1010 case Algorithm::AES:
1011 return {128, 256};
1012 case Algorithm::TRIPLE_DES:
1013 return {168};
1014 case Algorithm::HMAC: {
1015 vector<uint32_t> retval((512 - 64) / 8 + 1);
1016 uint32_t size = 64 - 8;
1017 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1018 return retval;
1019 }
1020 default:
1021 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1022 return {};
1023 }
1024 ADD_FAILURE() << "Should be impossible to get here";
1025 return {};
1026}
1027
1028vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1029 if (SecLevel() == SecurityLevel::STRONGBOX) {
1030 switch (algorithm) {
1031 case Algorithm::RSA:
1032 return {3072, 4096};
1033 case Algorithm::EC:
1034 return {224, 384, 521};
1035 case Algorithm::AES:
1036 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001037 case Algorithm::TRIPLE_DES:
1038 return {56};
1039 default:
1040 return {};
1041 }
1042 } else {
1043 switch (algorithm) {
1044 case Algorithm::TRIPLE_DES:
1045 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001046 default:
1047 return {};
1048 }
1049 }
1050 return {};
1051}
1052
David Drysdale7de9feb2021-03-05 14:56:19 +00001053vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1054 switch (algorithm) {
1055 case Algorithm::AES:
1056 return {
1057 BlockMode::CBC,
1058 BlockMode::CTR,
1059 BlockMode::ECB,
1060 BlockMode::GCM,
1061 };
1062 case Algorithm::TRIPLE_DES:
1063 return {
1064 BlockMode::CBC,
1065 BlockMode::ECB,
1066 };
1067 default:
1068 return {};
1069 }
1070}
1071
1072vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1073 BlockMode blockMode) {
1074 switch (algorithm) {
1075 case Algorithm::AES:
1076 switch (blockMode) {
1077 case BlockMode::CBC:
1078 case BlockMode::ECB:
1079 return {PaddingMode::NONE, PaddingMode::PKCS7};
1080 case BlockMode::CTR:
1081 case BlockMode::GCM:
1082 return {PaddingMode::NONE};
1083 default:
1084 return {};
1085 };
1086 case Algorithm::TRIPLE_DES:
1087 switch (blockMode) {
1088 case BlockMode::CBC:
1089 case BlockMode::ECB:
1090 return {PaddingMode::NONE, PaddingMode::PKCS7};
1091 default:
1092 return {};
1093 };
1094 default:
1095 return {};
1096 }
1097}
1098
1099vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1100 BlockMode blockMode) {
1101 switch (algorithm) {
1102 case Algorithm::AES:
1103 switch (blockMode) {
1104 case BlockMode::CTR:
1105 case BlockMode::GCM:
1106 return {PaddingMode::PKCS7};
1107 default:
1108 return {};
1109 };
1110 default:
1111 return {};
1112 }
1113}
1114
Selene Huang31ab4042020-04-29 04:22:39 -07001115vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1116 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1117 return {EcCurve::P_256};
1118 } else {
1119 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1120 }
1121}
1122
1123vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
1124 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
1125 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
1126 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
1127}
1128
1129vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1130 switch (SecLevel()) {
1131 case SecurityLevel::SOFTWARE:
1132 case SecurityLevel::TRUSTED_ENVIRONMENT:
1133 if (withNone) {
1134 if (withMD5)
1135 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1136 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1137 Digest::SHA_2_512};
1138 else
1139 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1140 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1141 } else {
1142 if (withMD5)
1143 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1144 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1145 else
1146 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1147 Digest::SHA_2_512};
1148 }
1149 break;
1150 case SecurityLevel::STRONGBOX:
1151 if (withNone)
1152 return {Digest::NONE, Digest::SHA_2_256};
1153 else
1154 return {Digest::SHA_2_256};
1155 break;
1156 default:
1157 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1158 break;
1159 }
1160 ADD_FAILURE() << "Should be impossible to get here";
1161 return {};
1162}
1163
Shawn Willden7f424372021-01-10 18:06:50 -07001164static const vector<KeyParameter> kEmptyAuthList{};
1165
1166const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1167 const vector<KeyCharacteristics>& key_characteristics) {
1168 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1169 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1170 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1171}
1172
Qi Wubeefae42021-01-28 23:16:37 +08001173const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1174 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1175 auto found = std::find_if(
1176 key_characteristics.begin(), key_characteristics.end(),
1177 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001178 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1179}
1180
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001181ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001182 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001183 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1184 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1185 return result;
1186}
1187
1188ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001189 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001190 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1191 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1192 return result;
1193}
1194
1195ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1196 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001197 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001198 rsaKeyBlob, KeyPurpose::SIGN, message,
1199 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1200 return result;
1201}
1202
1203ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001204 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1205 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001206 return result;
1207}
1208
Selene Huang6e46f142021-04-20 19:20:11 -07001209void verify_serial(X509* cert, const uint64_t expected_serial) {
1210 BIGNUM_Ptr ser(BN_new());
1211 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1212
1213 uint64_t serial;
1214 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1215 EXPECT_EQ(serial, expected_serial);
1216}
1217
1218// Please set self_signed to true for fake certificates or self signed
1219// certificates
1220void verify_subject(const X509* cert, //
1221 const string& subject, //
1222 bool self_signed) {
1223 char* cert_issuer = //
1224 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1225
1226 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1227
1228 string expected_subject("/CN=");
1229 if (subject.empty()) {
1230 expected_subject.append("Android Keystore Key");
1231 } else {
1232 expected_subject.append(subject);
1233 }
1234
1235 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1236
1237 if (self_signed) {
1238 EXPECT_STREQ(cert_issuer, cert_subj)
1239 << "Cert issuer and subject mismatch for self signed certificate.";
1240 }
1241
1242 OPENSSL_free(cert_subj);
1243 OPENSSL_free(cert_issuer);
1244}
1245
1246vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1247 BIGNUM_Ptr serial(BN_new());
1248 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1249
1250 int len = BN_num_bytes(serial.get());
1251 vector<uint8_t> serial_blob(len);
1252 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1253 return {};
1254 }
1255
David Drysdaledb0dcf52021-05-18 11:43:31 +01001256 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1257 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1258 // Top bit being set indicates a negative number in two's complement, but our input
1259 // was positive.
1260 // In either case, prepend a zero byte.
1261 serial_blob.insert(serial_blob.begin(), 0x00);
1262 }
1263
Selene Huang6e46f142021-04-20 19:20:11 -07001264 return serial_blob;
1265}
1266
1267void verify_subject_and_serial(const Certificate& certificate, //
1268 const uint64_t expected_serial, //
1269 const string& subject, bool self_signed) {
1270 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1271 ASSERT_TRUE(!!cert.get());
1272
1273 verify_serial(cert.get(), expected_serial);
1274 verify_subject(cert.get(), subject, self_signed);
1275}
1276
Shawn Willden7c130392020-12-21 09:58:22 -07001277bool verify_attestation_record(const string& challenge, //
1278 const string& app_id, //
1279 AuthorizationSet expected_sw_enforced, //
1280 AuthorizationSet expected_hw_enforced, //
1281 SecurityLevel security_level,
1282 const vector<uint8_t>& attestation_cert) {
1283 X509_Ptr cert(parse_cert_blob(attestation_cert));
1284 EXPECT_TRUE(!!cert.get());
1285 if (!cert.get()) return false;
1286
1287 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1288 EXPECT_TRUE(!!attest_rec);
1289 if (!attest_rec) return false;
1290
1291 AuthorizationSet att_sw_enforced;
1292 AuthorizationSet att_hw_enforced;
1293 uint32_t att_attestation_version;
1294 uint32_t att_keymaster_version;
1295 SecurityLevel att_attestation_security_level;
1296 SecurityLevel att_keymaster_security_level;
1297 vector<uint8_t> att_challenge;
1298 vector<uint8_t> att_unique_id;
1299 vector<uint8_t> att_app_id;
1300
1301 auto error = parse_attestation_record(attest_rec->data, //
1302 attest_rec->length, //
1303 &att_attestation_version, //
1304 &att_attestation_security_level, //
1305 &att_keymaster_version, //
1306 &att_keymaster_security_level, //
1307 &att_challenge, //
1308 &att_sw_enforced, //
1309 &att_hw_enforced, //
1310 &att_unique_id);
1311 EXPECT_EQ(ErrorCode::OK, error);
1312 if (error != ErrorCode::OK) return false;
1313
Shawn Willden3cb64a62021-04-05 14:39:05 -06001314 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -07001315 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001316
Selene Huang4f64c222021-04-13 19:54:36 -07001317 // check challenge and app id only if we expects a non-fake certificate
1318 if (challenge.length() > 0) {
1319 EXPECT_EQ(challenge.length(), att_challenge.size());
1320 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1321
1322 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1323 }
Shawn Willden7c130392020-12-21 09:58:22 -07001324
Shawn Willden3cb64a62021-04-05 14:39:05 -06001325 EXPECT_EQ(att_keymaster_version, 100U);
Shawn Willden7c130392020-12-21 09:58:22 -07001326 EXPECT_EQ(security_level, att_keymaster_security_level);
1327 EXPECT_EQ(security_level, att_attestation_security_level);
1328
Shawn Willden7c130392020-12-21 09:58:22 -07001329
1330 char property_value[PROPERTY_VALUE_MAX] = {};
1331 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
1332 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
1333 // for the BOOT_PATCH_LEVEL.
1334 if (avb_verification_enabled()) {
1335 for (int i = 0; i < att_hw_enforced.size(); i++) {
1336 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1337 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1338 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001339 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -07001340 // strptime seems to require delimiters, but the tag value will
1341 // be YYYYMMDD
1342 date.insert(6, "-");
1343 date.insert(4, "-");
1344 EXPECT_EQ(date.size(), 10);
1345 struct tm time;
1346 strptime(date.c_str(), "%Y-%m-%d", &time);
1347
1348 // Day of the month (0-31)
1349 EXPECT_GE(time.tm_mday, 0);
1350 EXPECT_LT(time.tm_mday, 32);
1351 // Months since Jan (0-11)
1352 EXPECT_GE(time.tm_mon, 0);
1353 EXPECT_LT(time.tm_mon, 12);
1354 // Years since 1900
1355 EXPECT_GT(time.tm_year, 110);
1356 EXPECT_LT(time.tm_year, 200);
1357 }
1358 }
1359 }
1360
1361 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1362 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1363 // indicates correct encoding. No need to check if it's in both lists, since the
1364 // AuthorizationSet compare below will handle mismatches of tags.
1365 if (security_level == SecurityLevel::SOFTWARE) {
1366 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1367 } else {
1368 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1369 }
1370
1371 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
1372 // the authorization list during key generation) isn't being attested to in the certificate.
1373 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1374 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1375 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1376 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1377
1378 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1379 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1380 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1381 att_hw_enforced.Contains(TAG_KEY_SIZE));
1382 }
1383
1384 // Test root of trust elements
1385 vector<uint8_t> verified_boot_key;
1386 VerifiedBoot verified_boot_state;
1387 bool device_locked;
1388 vector<uint8_t> verified_boot_hash;
1389 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1390 &verified_boot_state, &device_locked, &verified_boot_hash);
1391 EXPECT_EQ(ErrorCode::OK, error);
1392
1393 if (avb_verification_enabled()) {
1394 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1395 string prop_string(property_value);
1396 EXPECT_EQ(prop_string.size(), 64);
1397 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1398
1399 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1400 if (!strcmp(property_value, "unlocked")) {
1401 EXPECT_FALSE(device_locked);
1402 } else {
1403 EXPECT_TRUE(device_locked);
1404 }
1405
1406 // Check that the device is locked if not debuggable, e.g., user build
1407 // images in CTS. For VTS, debuggable images are used to allow adb root
1408 // and the device is unlocked.
1409 if (!property_get_bool("ro.debuggable", false)) {
1410 EXPECT_TRUE(device_locked);
1411 } else {
1412 EXPECT_FALSE(device_locked);
1413 }
1414 }
1415
1416 // Verified boot key should be all 0's if the boot state is not verified or self signed
1417 std::string empty_boot_key(32, '\0');
1418 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1419 verified_boot_key.size());
1420 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1421 if (!strcmp(property_value, "green")) {
1422 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1423 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1424 verified_boot_key.size()));
1425 } else if (!strcmp(property_value, "yellow")) {
1426 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1427 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1428 verified_boot_key.size()));
1429 } else if (!strcmp(property_value, "orange")) {
1430 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1431 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1432 verified_boot_key.size()));
1433 } else if (!strcmp(property_value, "red")) {
1434 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1435 } else {
1436 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1437 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1438 verified_boot_key.size()));
1439 }
1440
1441 att_sw_enforced.Sort();
1442 expected_sw_enforced.Sort();
1443 auto a = filtered_tags(expected_sw_enforced);
1444 auto b = filtered_tags(att_sw_enforced);
1445 EXPECT_EQ(a, b);
1446
1447 att_hw_enforced.Sort();
1448 expected_hw_enforced.Sort();
1449 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1450
1451 return true;
1452}
1453
1454string bin2hex(const vector<uint8_t>& data) {
1455 string retval;
1456 retval.reserve(data.size() * 2 + 1);
1457 for (uint8_t byte : data) {
1458 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1459 retval.push_back(nibble2hex[0x0F & byte]);
1460 }
1461 return retval;
1462}
1463
David Drysdalef0d516d2021-03-22 07:51:43 +00001464AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1465 AuthorizationSet authList;
1466 for (auto& entry : key_characteristics) {
1467 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1468 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1469 authList.push_back(AuthorizationSet(entry.authorizations));
1470 }
1471 }
1472 return authList;
1473}
1474
1475AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1476 AuthorizationSet authList;
1477 for (auto& entry : key_characteristics) {
1478 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1479 entry.securityLevel == SecurityLevel::KEYSTORE) {
1480 authList.push_back(AuthorizationSet(entry.authorizations));
1481 }
1482 }
1483 return authList;
1484}
1485
Shawn Willden7c130392020-12-21 09:58:22 -07001486AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1487 std::stringstream cert_data;
1488
1489 for (size_t i = 0; i < chain.size(); ++i) {
1490 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1491
1492 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1493 X509_Ptr signing_cert;
1494 if (i < chain.size() - 1) {
1495 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1496 } else {
1497 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1498 }
1499 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1500
1501 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1502 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1503
1504 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1505 return AssertionFailure()
1506 << "Verification of certificate " << i << " failed "
1507 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1508 << cert_data.str();
1509 }
1510
1511 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1512 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1513 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001514 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1515 << " Signer subject is " << signer_subj
1516 << " Issuer subject is " << cert_issuer << endl
1517 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001518 }
Shawn Willden7c130392020-12-21 09:58:22 -07001519 }
1520
1521 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1522 return AssertionSuccess();
1523}
1524
1525X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1526 const uint8_t* p = blob.data();
1527 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1528}
1529
David Drysdalef0d516d2021-03-22 07:51:43 +00001530vector<uint8_t> make_name_from_str(const string& name) {
1531 X509_NAME_Ptr x509_name(X509_NAME_new());
1532 EXPECT_TRUE(x509_name.get() != nullptr);
1533 if (!x509_name) return {};
1534
1535 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1536 "CN", //
1537 MBSTRING_ASC,
1538 reinterpret_cast<const uint8_t*>(name.c_str()),
1539 -1, // len
1540 -1, // loc
1541 0 /* set */));
1542
1543 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1544 EXPECT_GT(len, 0);
1545
1546 vector<uint8_t> retval(len);
1547 uint8_t* p = retval.data();
1548 i2d_X509_NAME(x509_name.get(), &p);
1549
1550 return retval;
1551}
1552
David Drysdale4dc01072021-04-01 12:17:35 +01001553namespace {
1554
1555void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1556 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1557 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1558
1559 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1560 if (testMode) {
1561 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1562 MatchesRegex("{\n"
1563 " 1 : 2,\n" // kty: EC2
1564 " 3 : -7,\n" // alg: ES256
1565 " -1 : 1,\n" // EC id: P256
1566 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1567 // sequence of 32 hexadecimal bytes, enclosed in braces and
1568 // separated by commas. In this case, some Ed25519 public key.
1569 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1570 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1571 " -70000 : null,\n" // test marker
1572 "}"));
1573 } else {
1574 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1575 MatchesRegex("{\n"
1576 " 1 : 2,\n" // kty: EC2
1577 " 3 : -7,\n" // alg: ES256
1578 " -1 : 1,\n" // EC id: P256
1579 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1580 // sequence of 32 hexadecimal bytes, enclosed in braces and
1581 // separated by commas. In this case, some Ed25519 public key.
1582 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1583 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1584 "}"));
1585 }
1586}
1587
1588} // namespace
1589
1590void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1591 vector<uint8_t>* payload_value) {
1592 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1593 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1594
1595 ASSERT_NE(coseMac0->asArray(), nullptr);
1596 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1597
1598 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1599 ASSERT_NE(protParms, nullptr);
1600
1601 // Header label:value of 'alg': HMAC-256
1602 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1603
1604 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1605 ASSERT_NE(unprotParms, nullptr);
1606 ASSERT_EQ(unprotParms->size(), 0);
1607
1608 // The payload is a bstr holding an encoded COSE_Key
1609 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1610 ASSERT_NE(payload, nullptr);
1611 check_cose_key(payload->value(), testMode);
1612
1613 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1614 ASSERT_TRUE(coseMac0Tag);
1615 auto extractedTag = coseMac0Tag->value();
1616 EXPECT_EQ(extractedTag.size(), 32U);
1617
1618 // Compare with tag generated with kTestMacKey. Should only match in test mode
1619 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
1620 payload->value());
1621 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1622
1623 if (testMode) {
1624 EXPECT_EQ(*testTag, extractedTag);
1625 } else {
1626 EXPECT_NE(*testTag, extractedTag);
1627 }
1628 if (payload_value != nullptr) {
1629 *payload_value = payload->value();
1630 }
1631}
1632
1633void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1634 // Extract x and y affine coordinates from the encoded Cose_Key.
1635 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1636 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1637 auto coseKey = parsedPayload->asMap();
1638 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1639 ASSERT_NE(xItem->asBstr(), nullptr);
1640 vector<uint8_t> x = xItem->asBstr()->value();
1641 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1642 ASSERT_NE(yItem->asBstr(), nullptr);
1643 vector<uint8_t> y = yItem->asBstr()->value();
1644
1645 // Concatenate: 0x04 (uncompressed form marker) | x | y
1646 vector<uint8_t> pubKeyData{0x04};
1647 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1648 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1649
1650 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1651 ASSERT_NE(ecKey, nullptr);
1652 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1653 ASSERT_NE(group, nullptr);
1654 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1655 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1656 ASSERT_NE(point, nullptr);
1657 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1658 nullptr),
1659 1);
1660 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1661
1662 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1663 ASSERT_NE(pubKey, nullptr);
1664 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1665 *signingKey = std::move(pubKey);
1666}
1667
Selene Huang31ab4042020-04-29 04:22:39 -07001668} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001669
Janis Danisevskis24c04702020-12-16 18:28:39 -08001670} // namespace aidl::android::hardware::security::keymint