blob: 3a2717b9d9d0a48bf11f9f3191a169f340ff08a8 [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
143string x509NameToStr(X509_NAME* name) {
144 char* s = X509_NAME_oneline(name, nullptr, 0);
145 string retval(s);
146 OPENSSL_free(s);
147 return retval;
148}
149
Shawn Willden7f424372021-01-10 18:06:50 -0700150} // namespace
151
Shawn Willden7c130392020-12-21 09:58:22 -0700152bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
153bool KeyMintAidlTestBase::dump_Attestations = false;
154
Janis Danisevskis24c04702020-12-16 18:28:39 -0800155ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700156 if (result.isOk()) return ErrorCode::OK;
157
Janis Danisevskis24c04702020-12-16 18:28:39 -0800158 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
159 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700160 }
161
162 return ErrorCode::UNKNOWN_ERROR;
163}
164
Janis Danisevskis24c04702020-12-16 18:28:39 -0800165void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700166 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800167 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700168
169 KeyMintHardwareInfo info;
170 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
171
172 securityLevel_ = info.securityLevel;
173 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
174 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100175 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700176
177 os_version_ = getOsVersion();
178 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100179 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700180}
181
182void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800183 if (AServiceManager_isDeclared(GetParam().c_str())) {
184 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
185 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
186 } else {
187 InitializeKeyMint(nullptr);
188 }
Selene Huang31ab4042020-04-29 04:22:39 -0700189}
190
191ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700192 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700193 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700194 vector<KeyCharacteristics>* key_characteristics,
195 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700196 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
197 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700198 << "Previous characteristics not deleted before generating key. Test bug.";
199
Shawn Willden7f424372021-01-10 18:06:50 -0700200 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700201 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700202 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700203 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
204 creationResult.keyCharacteristics);
205 EXPECT_GT(creationResult.keyBlob.size(), 0);
206 *key_blob = std::move(creationResult.keyBlob);
207 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700208 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700209
210 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
211 EXPECT_TRUE(algorithm);
212 if (algorithm &&
213 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700214 EXPECT_GE(cert_chain->size(), 1);
215 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
216 if (attest_key) {
217 EXPECT_EQ(cert_chain->size(), 1);
218 } else {
219 EXPECT_GT(cert_chain->size(), 1);
220 }
221 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700222 } else {
223 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700224 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700225 }
Selene Huang31ab4042020-04-29 04:22:39 -0700226 }
227
228 return GetReturnErrorCode(result);
229}
230
Shawn Willden7c130392020-12-21 09:58:22 -0700231ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
232 const optional<AttestationKey>& attest_key) {
233 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700234}
235
236ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
237 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700238 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700239 Status result;
240
Shawn Willden7f424372021-01-10 18:06:50 -0700241 cert_chain_.clear();
242 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700243 key_blob->clear();
244
Shawn Willden7f424372021-01-10 18:06:50 -0700245 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700246 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700247 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700248 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700249
250 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700251 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
252 creationResult.keyCharacteristics);
253 EXPECT_GT(creationResult.keyBlob.size(), 0);
254
255 *key_blob = std::move(creationResult.keyBlob);
256 *key_characteristics = std::move(creationResult.keyCharacteristics);
257 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700258
259 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
260 EXPECT_TRUE(algorithm);
261 if (algorithm &&
262 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
263 EXPECT_GE(cert_chain_.size(), 1);
264 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
265 } else {
266 // For symmetric keys there should be no certificates.
267 EXPECT_EQ(cert_chain_.size(), 0);
268 }
Selene Huang31ab4042020-04-29 04:22:39 -0700269 }
270
271 return GetReturnErrorCode(result);
272}
273
274ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
275 const string& key_material) {
276 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
277}
278
279ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
280 const AuthorizationSet& wrapping_key_desc,
281 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100282 const AuthorizationSet& unwrapping_params,
283 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700284 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
285
Shawn Willden7f424372021-01-10 18:06:50 -0700286 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700287
Shawn Willden7f424372021-01-10 18:06:50 -0700288 KeyCreationResult creationResult;
289 Status result = keymint_->importWrappedKey(
290 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
291 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100292 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700293
294 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700295 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
296 creationResult.keyCharacteristics);
297 EXPECT_GT(creationResult.keyBlob.size(), 0);
298
299 key_blob_ = std::move(creationResult.keyBlob);
300 key_characteristics_ = std::move(creationResult.keyCharacteristics);
301 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700302
303 AuthorizationSet allAuths;
304 for (auto& entry : key_characteristics_) {
305 allAuths.push_back(AuthorizationSet(entry.authorizations));
306 }
307 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
308 EXPECT_TRUE(algorithm);
309 if (algorithm &&
310 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
311 EXPECT_GE(cert_chain_.size(), 1);
312 } else {
313 // For symmetric keys there should be no certificates.
314 EXPECT_EQ(cert_chain_.size(), 0);
315 }
Selene Huang31ab4042020-04-29 04:22:39 -0700316 }
317
318 return GetReturnErrorCode(result);
319}
320
321ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
322 Status result = keymint_->deleteKey(*key_blob);
323 if (!keep_key_blob) {
324 *key_blob = vector<uint8_t>();
325 }
326
Janis Danisevskis24c04702020-12-16 18:28:39 -0800327 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700328 return GetReturnErrorCode(result);
329}
330
331ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
332 return DeleteKey(&key_blob_, keep_key_blob);
333}
334
335ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
336 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800337 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700338 return GetReturnErrorCode(result);
339}
340
David Drysdaled2cc8c22021-04-15 13:29:45 +0100341ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
342 Status result = keymint_->destroyAttestationIds();
343 return GetReturnErrorCode(result);
344}
345
Selene Huang31ab4042020-04-29 04:22:39 -0700346void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
347 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
348 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
349}
350
351void KeyMintAidlTestBase::CheckedDeleteKey() {
352 CheckedDeleteKey(&key_blob_);
353}
354
355ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
356 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800357 AuthorizationSet* out_params,
358 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700359 SCOPED_TRACE("Begin");
360 Status result;
361 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100362 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700363
364 if (result.isOk()) {
365 *out_params = out.params;
366 challenge_ = out.challenge;
367 op = out.operation;
368 }
369
370 return GetReturnErrorCode(result);
371}
372
373ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
374 const AuthorizationSet& in_params,
375 AuthorizationSet* out_params) {
376 SCOPED_TRACE("Begin");
377 Status result;
378 BeginResult out;
379
David Drysdale56ba9122021-04-19 19:10:47 +0100380 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700381
382 if (result.isOk()) {
383 *out_params = out.params;
384 challenge_ = out.challenge;
385 op_ = out.operation;
386 }
387
388 return GetReturnErrorCode(result);
389}
390
391ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
392 AuthorizationSet* out_params) {
393 SCOPED_TRACE("Begin");
394 EXPECT_EQ(nullptr, op_);
395 return Begin(purpose, key_blob_, in_params, out_params);
396}
397
398ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
399 SCOPED_TRACE("Begin");
400 AuthorizationSet out_params;
401 ErrorCode result = Begin(purpose, in_params, &out_params);
402 EXPECT_TRUE(out_params.empty());
403 return result;
404}
405
Shawn Willden92d79c02021-02-19 07:31:55 -0700406ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
407 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
408 {} /* hardwareAuthToken */,
409 {} /* verificationToken */));
410}
411
412ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700413 SCOPED_TRACE("Update");
414
415 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700416 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700417
Shawn Willden92d79c02021-02-19 07:31:55 -0700418 std::vector<uint8_t> o_put;
419 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700420
Shawn Willden92d79c02021-02-19 07:31:55 -0700421 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700422
423 return GetReturnErrorCode(result);
424}
425
Shawn Willden92d79c02021-02-19 07:31:55 -0700426ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700427 string* output) {
428 SCOPED_TRACE("Finish");
429 Status result;
430
431 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700432 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700433
434 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700435 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
436 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
437 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700438
Shawn Willden92d79c02021-02-19 07:31:55 -0700439 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700440
Shawn Willden92d79c02021-02-19 07:31:55 -0700441 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700442 return GetReturnErrorCode(result);
443}
444
Janis Danisevskis24c04702020-12-16 18:28:39 -0800445ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700446 SCOPED_TRACE("Abort");
447
448 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700449 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700450
451 Status retval = op->abort();
452 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800453 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700454}
455
456ErrorCode KeyMintAidlTestBase::Abort() {
457 SCOPED_TRACE("Abort");
458
459 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700460 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700461
462 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800463 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700464}
465
466void KeyMintAidlTestBase::AbortIfNeeded() {
467 SCOPED_TRACE("AbortIfNeeded");
468 if (op_) {
469 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800470 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700471 }
472}
473
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000474auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
475 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700476 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000477 AuthorizationSet begin_out_params;
478 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700479 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000480
481 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700482 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000483}
484
Selene Huang31ab4042020-04-29 04:22:39 -0700485string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
486 const string& message, const AuthorizationSet& in_params,
487 AuthorizationSet* out_params) {
488 SCOPED_TRACE("ProcessMessage");
489 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700490 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700491 EXPECT_EQ(ErrorCode::OK, result);
492 if (result != ErrorCode::OK) {
493 return "";
494 }
495
496 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700497 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700498 return output;
499}
500
501string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
502 const AuthorizationSet& params) {
503 SCOPED_TRACE("SignMessage");
504 AuthorizationSet out_params;
505 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
506 EXPECT_TRUE(out_params.empty());
507 return signature;
508}
509
510string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
511 SCOPED_TRACE("SignMessage");
512 return SignMessage(key_blob_, message, params);
513}
514
515string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
516 SCOPED_TRACE("MacMessage");
517 return SignMessage(
518 key_blob_, message,
519 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
520}
521
522void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
523 Digest digest, const string& expected_mac) {
524 SCOPED_TRACE("CheckHmacTestVector");
525 ASSERT_EQ(ErrorCode::OK,
526 ImportKey(AuthorizationSetBuilder()
527 .Authorization(TAG_NO_AUTH_REQUIRED)
528 .HmacKey(key.size() * 8)
529 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
530 .Digest(digest),
531 KeyFormat::RAW, key));
532 string signature = MacMessage(message, digest, expected_mac.size() * 8);
533 EXPECT_EQ(expected_mac, signature)
534 << "Test vector didn't match for key of size " << key.size() << " message of size "
535 << message.size() << " and digest " << digest;
536 CheckedDeleteKey();
537}
538
539void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
540 const string& message,
541 const string& expected_ciphertext) {
542 SCOPED_TRACE("CheckAesCtrTestVector");
543 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
544 .Authorization(TAG_NO_AUTH_REQUIRED)
545 .AesEncryptionKey(key.size() * 8)
546 .BlockMode(BlockMode::CTR)
547 .Authorization(TAG_CALLER_NONCE)
548 .Padding(PaddingMode::NONE),
549 KeyFormat::RAW, key));
550
551 auto params = AuthorizationSetBuilder()
552 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
553 .BlockMode(BlockMode::CTR)
554 .Padding(PaddingMode::NONE);
555 AuthorizationSet out_params;
556 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
557 EXPECT_EQ(expected_ciphertext, ciphertext);
558}
559
560void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
561 PaddingMode padding_mode, const string& key,
562 const string& iv, const string& input,
563 const string& expected_output) {
564 auto authset = AuthorizationSetBuilder()
565 .TripleDesEncryptionKey(key.size() * 7)
566 .BlockMode(block_mode)
567 .Authorization(TAG_NO_AUTH_REQUIRED)
568 .Padding(padding_mode);
569 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
570 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
571 ASSERT_GT(key_blob_.size(), 0U);
572
573 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
574 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
575 AuthorizationSet output_params;
576 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
577 EXPECT_EQ(expected_output, output);
578}
579
580void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
581 const string& signature, const AuthorizationSet& params) {
582 SCOPED_TRACE("VerifyMessage");
583 AuthorizationSet begin_out_params;
584 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
585
586 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700587 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700588 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700589 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700590}
591
592void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
593 const AuthorizationSet& params) {
594 SCOPED_TRACE("VerifyMessage");
595 VerifyMessage(key_blob_, message, signature, params);
596}
597
David Drysdaledf8f52e2021-05-06 08:10:58 +0100598void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
599 const AuthorizationSet& params) {
600 SCOPED_TRACE("LocalVerifyMessage");
601
602 // Retrieve the public key from the leaf certificate.
603 ASSERT_GT(cert_chain_.size(), 0);
604 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
605 ASSERT_TRUE(key_cert.get());
606 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
607 ASSERT_TRUE(pub_key.get());
608
609 Digest digest = params.GetTagValue(TAG_DIGEST).value();
610 PaddingMode padding = PaddingMode::NONE;
611 auto tag = params.GetTagValue(TAG_PADDING);
612 if (tag.has_value()) {
613 padding = tag.value();
614 }
615
616 if (digest == Digest::NONE) {
617 switch (EVP_PKEY_id(pub_key.get())) {
618 case EVP_PKEY_EC: {
619 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
620 size_t data_size = std::min(data.size(), message.size());
621 memcpy(data.data(), message.data(), data_size);
622 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
623 ASSERT_TRUE(ecdsa.get());
624 ASSERT_EQ(1,
625 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
626 reinterpret_cast<const uint8_t*>(signature.data()),
627 signature.size(), ecdsa.get()));
628 break;
629 }
630 case EVP_PKEY_RSA: {
631 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
632 size_t data_size = std::min(data.size(), message.size());
633 memcpy(data.data(), message.data(), data_size);
634
635 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
636 ASSERT_TRUE(rsa.get());
637
638 size_t key_len = RSA_size(rsa.get());
639 int openssl_padding = RSA_NO_PADDING;
640 switch (padding) {
641 case PaddingMode::NONE:
642 ASSERT_TRUE(data_size <= key_len);
643 ASSERT_EQ(key_len, signature.size());
644 openssl_padding = RSA_NO_PADDING;
645 break;
646 case PaddingMode::RSA_PKCS1_1_5_SIGN:
647 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
648 key_len);
649 openssl_padding = RSA_PKCS1_PADDING;
650 break;
651 default:
652 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
653 }
654
655 vector<uint8_t> decrypted_data(key_len);
656 int bytes_decrypted = RSA_public_decrypt(
657 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
658 decrypted_data.data(), rsa.get(), openssl_padding);
659 ASSERT_GE(bytes_decrypted, 0);
660
661 const uint8_t* compare_pos = decrypted_data.data();
662 size_t bytes_to_compare = bytes_decrypted;
663 uint8_t zero_check_result = 0;
664 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
665 // If the data is short, for "unpadded" signing we zero-pad to the left. So
666 // during verification we should have zeros on the left of the decrypted data.
667 // Do a constant-time check.
668 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
669 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
670 ASSERT_EQ(0, zero_check_result);
671 bytes_to_compare = data_size;
672 }
673 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
674 break;
675 }
676 default:
677 ADD_FAILURE() << "Unknown public key type";
678 }
679 } else {
680 EVP_MD_CTX digest_ctx;
681 EVP_MD_CTX_init(&digest_ctx);
682 EVP_PKEY_CTX* pkey_ctx;
683 const EVP_MD* md = openssl_digest(digest);
684 ASSERT_NE(md, nullptr);
685 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
686
687 if (padding == PaddingMode::RSA_PSS) {
688 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
689 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
690 }
691
692 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
693 reinterpret_cast<const uint8_t*>(message.data()),
694 message.size()));
695 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
696 reinterpret_cast<const uint8_t*>(signature.data()),
697 signature.size()));
698 EVP_MD_CTX_cleanup(&digest_ctx);
699 }
700}
701
David Drysdale59cae642021-05-12 13:52:03 +0100702string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
703 const AuthorizationSet& params) {
704 SCOPED_TRACE("LocalRsaEncryptMessage");
705
706 // Retrieve the public key from the leaf certificate.
707 if (cert_chain_.empty()) {
708 ADD_FAILURE() << "No public key available";
709 return "Failure";
710 }
711 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
712 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
713 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
714
715 // Retrieve relevant tags.
716 Digest digest = Digest::NONE;
717 Digest mgf_digest = Digest::NONE;
718 PaddingMode padding = PaddingMode::NONE;
719
720 auto digest_tag = params.GetTagValue(TAG_DIGEST);
721 if (digest_tag.has_value()) digest = digest_tag.value();
722 auto pad_tag = params.GetTagValue(TAG_PADDING);
723 if (pad_tag.has_value()) padding = pad_tag.value();
724 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
725 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
726
727 const EVP_MD* md = openssl_digest(digest);
728 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
729
730 // Set up encryption context.
731 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
732 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
733 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
734 return "Failure";
735 }
736
737 int rc = -1;
738 switch (padding) {
739 case PaddingMode::NONE:
740 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
741 break;
742 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
743 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
744 break;
745 case PaddingMode::RSA_OAEP:
746 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
747 break;
748 default:
749 break;
750 }
751 if (rc <= 0) {
752 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
753 return "Failure";
754 }
755 if (padding == PaddingMode::RSA_OAEP) {
756 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
757 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
758 return "Failure";
759 }
760 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
761 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
762 return "Failure";
763 }
764 }
765
766 // Determine output size.
767 size_t outlen;
768 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
769 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
770 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
771 return "Failure";
772 }
773
774 // Left-zero-pad the input if necessary.
775 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
776 size_t to_encrypt_len = message.size();
777
778 std::unique_ptr<string> zero_padded_message;
779 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
780 zero_padded_message.reset(new string(outlen, '\0'));
781 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
782 message.size());
783 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
784 to_encrypt_len = outlen;
785 }
786
787 // Do the encryption.
788 string output(outlen, '\0');
789 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
790 to_encrypt_len) <= 0) {
791 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
792 return "Failure";
793 }
794 return output;
795}
796
Selene Huang31ab4042020-04-29 04:22:39 -0700797string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
798 const AuthorizationSet& in_params,
799 AuthorizationSet* out_params) {
800 SCOPED_TRACE("EncryptMessage");
801 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
802}
803
804string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
805 AuthorizationSet* out_params) {
806 SCOPED_TRACE("EncryptMessage");
807 return EncryptMessage(key_blob_, message, params, out_params);
808}
809
810string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
811 SCOPED_TRACE("EncryptMessage");
812 AuthorizationSet out_params;
813 string ciphertext = EncryptMessage(message, params, &out_params);
814 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
815 return ciphertext;
816}
817
818string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
819 PaddingMode padding) {
820 SCOPED_TRACE("EncryptMessage");
821 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
822 AuthorizationSet out_params;
823 string ciphertext = EncryptMessage(message, params, &out_params);
824 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
825 return ciphertext;
826}
827
828string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
829 PaddingMode padding, vector<uint8_t>* iv_out) {
830 SCOPED_TRACE("EncryptMessage");
831 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
832 AuthorizationSet out_params;
833 string ciphertext = EncryptMessage(message, params, &out_params);
834 EXPECT_EQ(1U, out_params.size());
835 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800836 EXPECT_TRUE(ivVal);
837 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700838 return ciphertext;
839}
840
841string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
842 PaddingMode padding, const vector<uint8_t>& iv_in) {
843 SCOPED_TRACE("EncryptMessage");
844 auto params = AuthorizationSetBuilder()
845 .BlockMode(block_mode)
846 .Padding(padding)
847 .Authorization(TAG_NONCE, iv_in);
848 AuthorizationSet out_params;
849 string ciphertext = EncryptMessage(message, params, &out_params);
850 return ciphertext;
851}
852
853string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
854 PaddingMode padding, uint8_t mac_length_bits,
855 const vector<uint8_t>& iv_in) {
856 SCOPED_TRACE("EncryptMessage");
857 auto params = AuthorizationSetBuilder()
858 .BlockMode(block_mode)
859 .Padding(padding)
860 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
861 .Authorization(TAG_NONCE, iv_in);
862 AuthorizationSet out_params;
863 string ciphertext = EncryptMessage(message, params, &out_params);
864 return ciphertext;
865}
866
David Drysdaled2cc8c22021-04-15 13:29:45 +0100867string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
868 PaddingMode padding, uint8_t mac_length_bits) {
869 SCOPED_TRACE("EncryptMessage");
870 auto params = AuthorizationSetBuilder()
871 .BlockMode(block_mode)
872 .Padding(padding)
873 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
874 AuthorizationSet out_params;
875 string ciphertext = EncryptMessage(message, params, &out_params);
876 return ciphertext;
877}
878
Selene Huang31ab4042020-04-29 04:22:39 -0700879string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
880 const string& ciphertext,
881 const AuthorizationSet& params) {
882 SCOPED_TRACE("DecryptMessage");
883 AuthorizationSet out_params;
884 string plaintext =
885 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
886 EXPECT_TRUE(out_params.empty());
887 return plaintext;
888}
889
890string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
891 const AuthorizationSet& params) {
892 SCOPED_TRACE("DecryptMessage");
893 return DecryptMessage(key_blob_, ciphertext, params);
894}
895
896string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
897 PaddingMode padding_mode, const vector<uint8_t>& iv) {
898 SCOPED_TRACE("DecryptMessage");
899 auto params = AuthorizationSetBuilder()
900 .BlockMode(block_mode)
901 .Padding(padding_mode)
902 .Authorization(TAG_NONCE, iv);
903 return DecryptMessage(key_blob_, ciphertext, params);
904}
905
906std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
907 const vector<uint8_t>& key_blob) {
908 std::pair<ErrorCode, vector<uint8_t>> retval;
909 vector<uint8_t> outKeyBlob;
910 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
911 ErrorCode errorcode = GetReturnErrorCode(result);
912 retval = std::tie(errorcode, outKeyBlob);
913
914 return retval;
915}
916vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
917 switch (algorithm) {
918 case Algorithm::RSA:
919 switch (SecLevel()) {
920 case SecurityLevel::SOFTWARE:
921 case SecurityLevel::TRUSTED_ENVIRONMENT:
922 return {2048, 3072, 4096};
923 case SecurityLevel::STRONGBOX:
924 return {2048};
925 default:
926 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
927 break;
928 }
929 break;
930 case Algorithm::EC:
931 switch (SecLevel()) {
932 case SecurityLevel::SOFTWARE:
933 case SecurityLevel::TRUSTED_ENVIRONMENT:
934 return {224, 256, 384, 521};
935 case SecurityLevel::STRONGBOX:
936 return {256};
937 default:
938 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
939 break;
940 }
941 break;
942 case Algorithm::AES:
943 return {128, 256};
944 case Algorithm::TRIPLE_DES:
945 return {168};
946 case Algorithm::HMAC: {
947 vector<uint32_t> retval((512 - 64) / 8 + 1);
948 uint32_t size = 64 - 8;
949 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
950 return retval;
951 }
952 default:
953 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
954 return {};
955 }
956 ADD_FAILURE() << "Should be impossible to get here";
957 return {};
958}
959
960vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
961 if (SecLevel() == SecurityLevel::STRONGBOX) {
962 switch (algorithm) {
963 case Algorithm::RSA:
964 return {3072, 4096};
965 case Algorithm::EC:
966 return {224, 384, 521};
967 case Algorithm::AES:
968 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +0000969 case Algorithm::TRIPLE_DES:
970 return {56};
971 default:
972 return {};
973 }
974 } else {
975 switch (algorithm) {
976 case Algorithm::TRIPLE_DES:
977 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -0700978 default:
979 return {};
980 }
981 }
982 return {};
983}
984
David Drysdale7de9feb2021-03-05 14:56:19 +0000985vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
986 switch (algorithm) {
987 case Algorithm::AES:
988 return {
989 BlockMode::CBC,
990 BlockMode::CTR,
991 BlockMode::ECB,
992 BlockMode::GCM,
993 };
994 case Algorithm::TRIPLE_DES:
995 return {
996 BlockMode::CBC,
997 BlockMode::ECB,
998 };
999 default:
1000 return {};
1001 }
1002}
1003
1004vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1005 BlockMode blockMode) {
1006 switch (algorithm) {
1007 case Algorithm::AES:
1008 switch (blockMode) {
1009 case BlockMode::CBC:
1010 case BlockMode::ECB:
1011 return {PaddingMode::NONE, PaddingMode::PKCS7};
1012 case BlockMode::CTR:
1013 case BlockMode::GCM:
1014 return {PaddingMode::NONE};
1015 default:
1016 return {};
1017 };
1018 case Algorithm::TRIPLE_DES:
1019 switch (blockMode) {
1020 case BlockMode::CBC:
1021 case BlockMode::ECB:
1022 return {PaddingMode::NONE, PaddingMode::PKCS7};
1023 default:
1024 return {};
1025 };
1026 default:
1027 return {};
1028 }
1029}
1030
1031vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1032 BlockMode blockMode) {
1033 switch (algorithm) {
1034 case Algorithm::AES:
1035 switch (blockMode) {
1036 case BlockMode::CTR:
1037 case BlockMode::GCM:
1038 return {PaddingMode::PKCS7};
1039 default:
1040 return {};
1041 };
1042 default:
1043 return {};
1044 }
1045}
1046
Selene Huang31ab4042020-04-29 04:22:39 -07001047vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1048 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1049 return {EcCurve::P_256};
1050 } else {
1051 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1052 }
1053}
1054
1055vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
1056 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
1057 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
1058 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
1059}
1060
1061vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1062 switch (SecLevel()) {
1063 case SecurityLevel::SOFTWARE:
1064 case SecurityLevel::TRUSTED_ENVIRONMENT:
1065 if (withNone) {
1066 if (withMD5)
1067 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1068 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1069 Digest::SHA_2_512};
1070 else
1071 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1072 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1073 } else {
1074 if (withMD5)
1075 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1076 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1077 else
1078 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1079 Digest::SHA_2_512};
1080 }
1081 break;
1082 case SecurityLevel::STRONGBOX:
1083 if (withNone)
1084 return {Digest::NONE, Digest::SHA_2_256};
1085 else
1086 return {Digest::SHA_2_256};
1087 break;
1088 default:
1089 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1090 break;
1091 }
1092 ADD_FAILURE() << "Should be impossible to get here";
1093 return {};
1094}
1095
Shawn Willden7f424372021-01-10 18:06:50 -07001096static const vector<KeyParameter> kEmptyAuthList{};
1097
1098const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1099 const vector<KeyCharacteristics>& key_characteristics) {
1100 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1101 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1102 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1103}
1104
Qi Wubeefae42021-01-28 23:16:37 +08001105const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1106 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1107 auto found = std::find_if(
1108 key_characteristics.begin(), key_characteristics.end(),
1109 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001110 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1111}
1112
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001113ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001114 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001115 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1116 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1117 return result;
1118}
1119
1120ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001121 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001122 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1123 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1124 return result;
1125}
1126
1127ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1128 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001129 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001130 rsaKeyBlob, KeyPurpose::SIGN, message,
1131 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1132 return result;
1133}
1134
1135ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001136 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1137 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001138 return result;
1139}
1140
Selene Huang6e46f142021-04-20 19:20:11 -07001141void verify_serial(X509* cert, const uint64_t expected_serial) {
1142 BIGNUM_Ptr ser(BN_new());
1143 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1144
1145 uint64_t serial;
1146 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1147 EXPECT_EQ(serial, expected_serial);
1148}
1149
1150// Please set self_signed to true for fake certificates or self signed
1151// certificates
1152void verify_subject(const X509* cert, //
1153 const string& subject, //
1154 bool self_signed) {
1155 char* cert_issuer = //
1156 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1157
1158 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1159
1160 string expected_subject("/CN=");
1161 if (subject.empty()) {
1162 expected_subject.append("Android Keystore Key");
1163 } else {
1164 expected_subject.append(subject);
1165 }
1166
1167 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1168
1169 if (self_signed) {
1170 EXPECT_STREQ(cert_issuer, cert_subj)
1171 << "Cert issuer and subject mismatch for self signed certificate.";
1172 }
1173
1174 OPENSSL_free(cert_subj);
1175 OPENSSL_free(cert_issuer);
1176}
1177
1178vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1179 BIGNUM_Ptr serial(BN_new());
1180 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1181
1182 int len = BN_num_bytes(serial.get());
1183 vector<uint8_t> serial_blob(len);
1184 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1185 return {};
1186 }
1187
1188 return serial_blob;
1189}
1190
1191void verify_subject_and_serial(const Certificate& certificate, //
1192 const uint64_t expected_serial, //
1193 const string& subject, bool self_signed) {
1194 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1195 ASSERT_TRUE(!!cert.get());
1196
1197 verify_serial(cert.get(), expected_serial);
1198 verify_subject(cert.get(), subject, self_signed);
1199}
1200
Shawn Willden7c130392020-12-21 09:58:22 -07001201bool verify_attestation_record(const string& challenge, //
1202 const string& app_id, //
1203 AuthorizationSet expected_sw_enforced, //
1204 AuthorizationSet expected_hw_enforced, //
1205 SecurityLevel security_level,
1206 const vector<uint8_t>& attestation_cert) {
1207 X509_Ptr cert(parse_cert_blob(attestation_cert));
1208 EXPECT_TRUE(!!cert.get());
1209 if (!cert.get()) return false;
1210
1211 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1212 EXPECT_TRUE(!!attest_rec);
1213 if (!attest_rec) return false;
1214
1215 AuthorizationSet att_sw_enforced;
1216 AuthorizationSet att_hw_enforced;
1217 uint32_t att_attestation_version;
1218 uint32_t att_keymaster_version;
1219 SecurityLevel att_attestation_security_level;
1220 SecurityLevel att_keymaster_security_level;
1221 vector<uint8_t> att_challenge;
1222 vector<uint8_t> att_unique_id;
1223 vector<uint8_t> att_app_id;
1224
1225 auto error = parse_attestation_record(attest_rec->data, //
1226 attest_rec->length, //
1227 &att_attestation_version, //
1228 &att_attestation_security_level, //
1229 &att_keymaster_version, //
1230 &att_keymaster_security_level, //
1231 &att_challenge, //
1232 &att_sw_enforced, //
1233 &att_hw_enforced, //
1234 &att_unique_id);
1235 EXPECT_EQ(ErrorCode::OK, error);
1236 if (error != ErrorCode::OK) return false;
1237
Shawn Willden3cb64a62021-04-05 14:39:05 -06001238 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -07001239 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001240
Selene Huang4f64c222021-04-13 19:54:36 -07001241 // check challenge and app id only if we expects a non-fake certificate
1242 if (challenge.length() > 0) {
1243 EXPECT_EQ(challenge.length(), att_challenge.size());
1244 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1245
1246 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1247 }
Shawn Willden7c130392020-12-21 09:58:22 -07001248
Shawn Willden3cb64a62021-04-05 14:39:05 -06001249 EXPECT_EQ(att_keymaster_version, 100U);
Shawn Willden7c130392020-12-21 09:58:22 -07001250 EXPECT_EQ(security_level, att_keymaster_security_level);
1251 EXPECT_EQ(security_level, att_attestation_security_level);
1252
Shawn Willden7c130392020-12-21 09:58:22 -07001253
1254 char property_value[PROPERTY_VALUE_MAX] = {};
1255 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
1256 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
1257 // for the BOOT_PATCH_LEVEL.
1258 if (avb_verification_enabled()) {
1259 for (int i = 0; i < att_hw_enforced.size(); i++) {
1260 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1261 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1262 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001263 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -07001264 // strptime seems to require delimiters, but the tag value will
1265 // be YYYYMMDD
1266 date.insert(6, "-");
1267 date.insert(4, "-");
1268 EXPECT_EQ(date.size(), 10);
1269 struct tm time;
1270 strptime(date.c_str(), "%Y-%m-%d", &time);
1271
1272 // Day of the month (0-31)
1273 EXPECT_GE(time.tm_mday, 0);
1274 EXPECT_LT(time.tm_mday, 32);
1275 // Months since Jan (0-11)
1276 EXPECT_GE(time.tm_mon, 0);
1277 EXPECT_LT(time.tm_mon, 12);
1278 // Years since 1900
1279 EXPECT_GT(time.tm_year, 110);
1280 EXPECT_LT(time.tm_year, 200);
1281 }
1282 }
1283 }
1284
1285 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1286 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1287 // indicates correct encoding. No need to check if it's in both lists, since the
1288 // AuthorizationSet compare below will handle mismatches of tags.
1289 if (security_level == SecurityLevel::SOFTWARE) {
1290 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1291 } else {
1292 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1293 }
1294
1295 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
1296 // the authorization list during key generation) isn't being attested to in the certificate.
1297 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1298 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1299 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1300 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1301
1302 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1303 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1304 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1305 att_hw_enforced.Contains(TAG_KEY_SIZE));
1306 }
1307
1308 // Test root of trust elements
1309 vector<uint8_t> verified_boot_key;
1310 VerifiedBoot verified_boot_state;
1311 bool device_locked;
1312 vector<uint8_t> verified_boot_hash;
1313 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1314 &verified_boot_state, &device_locked, &verified_boot_hash);
1315 EXPECT_EQ(ErrorCode::OK, error);
1316
1317 if (avb_verification_enabled()) {
1318 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1319 string prop_string(property_value);
1320 EXPECT_EQ(prop_string.size(), 64);
1321 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1322
1323 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1324 if (!strcmp(property_value, "unlocked")) {
1325 EXPECT_FALSE(device_locked);
1326 } else {
1327 EXPECT_TRUE(device_locked);
1328 }
1329
1330 // Check that the device is locked if not debuggable, e.g., user build
1331 // images in CTS. For VTS, debuggable images are used to allow adb root
1332 // and the device is unlocked.
1333 if (!property_get_bool("ro.debuggable", false)) {
1334 EXPECT_TRUE(device_locked);
1335 } else {
1336 EXPECT_FALSE(device_locked);
1337 }
1338 }
1339
1340 // Verified boot key should be all 0's if the boot state is not verified or self signed
1341 std::string empty_boot_key(32, '\0');
1342 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1343 verified_boot_key.size());
1344 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1345 if (!strcmp(property_value, "green")) {
1346 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1347 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1348 verified_boot_key.size()));
1349 } else if (!strcmp(property_value, "yellow")) {
1350 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1351 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1352 verified_boot_key.size()));
1353 } else if (!strcmp(property_value, "orange")) {
1354 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1355 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1356 verified_boot_key.size()));
1357 } else if (!strcmp(property_value, "red")) {
1358 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1359 } else {
1360 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1361 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1362 verified_boot_key.size()));
1363 }
1364
1365 att_sw_enforced.Sort();
1366 expected_sw_enforced.Sort();
1367 auto a = filtered_tags(expected_sw_enforced);
1368 auto b = filtered_tags(att_sw_enforced);
1369 EXPECT_EQ(a, b);
1370
1371 att_hw_enforced.Sort();
1372 expected_hw_enforced.Sort();
1373 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1374
1375 return true;
1376}
1377
1378string bin2hex(const vector<uint8_t>& data) {
1379 string retval;
1380 retval.reserve(data.size() * 2 + 1);
1381 for (uint8_t byte : data) {
1382 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1383 retval.push_back(nibble2hex[0x0F & byte]);
1384 }
1385 return retval;
1386}
1387
David Drysdalef0d516d2021-03-22 07:51:43 +00001388AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1389 AuthorizationSet authList;
1390 for (auto& entry : key_characteristics) {
1391 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1392 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1393 authList.push_back(AuthorizationSet(entry.authorizations));
1394 }
1395 }
1396 return authList;
1397}
1398
1399AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1400 AuthorizationSet authList;
1401 for (auto& entry : key_characteristics) {
1402 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1403 entry.securityLevel == SecurityLevel::KEYSTORE) {
1404 authList.push_back(AuthorizationSet(entry.authorizations));
1405 }
1406 }
1407 return authList;
1408}
1409
Shawn Willden7c130392020-12-21 09:58:22 -07001410AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1411 std::stringstream cert_data;
1412
1413 for (size_t i = 0; i < chain.size(); ++i) {
1414 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1415
1416 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1417 X509_Ptr signing_cert;
1418 if (i < chain.size() - 1) {
1419 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1420 } else {
1421 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1422 }
1423 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1424
1425 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1426 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1427
1428 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1429 return AssertionFailure()
1430 << "Verification of certificate " << i << " failed "
1431 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1432 << cert_data.str();
1433 }
1434
1435 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1436 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1437 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001438 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1439 << " Signer subject is " << signer_subj
1440 << " Issuer subject is " << cert_issuer << endl
1441 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001442 }
Shawn Willden7c130392020-12-21 09:58:22 -07001443 }
1444
1445 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1446 return AssertionSuccess();
1447}
1448
1449X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1450 const uint8_t* p = blob.data();
1451 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1452}
1453
David Drysdalef0d516d2021-03-22 07:51:43 +00001454vector<uint8_t> make_name_from_str(const string& name) {
1455 X509_NAME_Ptr x509_name(X509_NAME_new());
1456 EXPECT_TRUE(x509_name.get() != nullptr);
1457 if (!x509_name) return {};
1458
1459 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1460 "CN", //
1461 MBSTRING_ASC,
1462 reinterpret_cast<const uint8_t*>(name.c_str()),
1463 -1, // len
1464 -1, // loc
1465 0 /* set */));
1466
1467 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1468 EXPECT_GT(len, 0);
1469
1470 vector<uint8_t> retval(len);
1471 uint8_t* p = retval.data();
1472 i2d_X509_NAME(x509_name.get(), &p);
1473
1474 return retval;
1475}
1476
David Drysdale4dc01072021-04-01 12:17:35 +01001477namespace {
1478
1479void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1480 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1481 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1482
1483 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1484 if (testMode) {
1485 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1486 MatchesRegex("{\n"
1487 " 1 : 2,\n" // kty: EC2
1488 " 3 : -7,\n" // alg: ES256
1489 " -1 : 1,\n" // EC id: P256
1490 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1491 // sequence of 32 hexadecimal bytes, enclosed in braces and
1492 // separated by commas. In this case, some Ed25519 public key.
1493 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1494 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1495 " -70000 : null,\n" // test marker
1496 "}"));
1497 } else {
1498 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1499 MatchesRegex("{\n"
1500 " 1 : 2,\n" // kty: EC2
1501 " 3 : -7,\n" // alg: ES256
1502 " -1 : 1,\n" // EC id: P256
1503 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1504 // sequence of 32 hexadecimal bytes, enclosed in braces and
1505 // separated by commas. In this case, some Ed25519 public key.
1506 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1507 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1508 "}"));
1509 }
1510}
1511
1512} // namespace
1513
1514void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1515 vector<uint8_t>* payload_value) {
1516 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1517 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1518
1519 ASSERT_NE(coseMac0->asArray(), nullptr);
1520 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1521
1522 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1523 ASSERT_NE(protParms, nullptr);
1524
1525 // Header label:value of 'alg': HMAC-256
1526 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1527
1528 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1529 ASSERT_NE(unprotParms, nullptr);
1530 ASSERT_EQ(unprotParms->size(), 0);
1531
1532 // The payload is a bstr holding an encoded COSE_Key
1533 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1534 ASSERT_NE(payload, nullptr);
1535 check_cose_key(payload->value(), testMode);
1536
1537 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1538 ASSERT_TRUE(coseMac0Tag);
1539 auto extractedTag = coseMac0Tag->value();
1540 EXPECT_EQ(extractedTag.size(), 32U);
1541
1542 // Compare with tag generated with kTestMacKey. Should only match in test mode
1543 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
1544 payload->value());
1545 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1546
1547 if (testMode) {
1548 EXPECT_EQ(*testTag, extractedTag);
1549 } else {
1550 EXPECT_NE(*testTag, extractedTag);
1551 }
1552 if (payload_value != nullptr) {
1553 *payload_value = payload->value();
1554 }
1555}
1556
1557void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1558 // Extract x and y affine coordinates from the encoded Cose_Key.
1559 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1560 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1561 auto coseKey = parsedPayload->asMap();
1562 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1563 ASSERT_NE(xItem->asBstr(), nullptr);
1564 vector<uint8_t> x = xItem->asBstr()->value();
1565 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1566 ASSERT_NE(yItem->asBstr(), nullptr);
1567 vector<uint8_t> y = yItem->asBstr()->value();
1568
1569 // Concatenate: 0x04 (uncompressed form marker) | x | y
1570 vector<uint8_t> pubKeyData{0x04};
1571 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1572 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1573
1574 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1575 ASSERT_NE(ecKey, nullptr);
1576 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1577 ASSERT_NE(group, nullptr);
1578 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1579 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1580 ASSERT_NE(point, nullptr);
1581 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1582 nullptr),
1583 1);
1584 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1585
1586 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1587 ASSERT_NE(pubKey, nullptr);
1588 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1589 *signingKey = std::move(pubKey);
1590}
1591
Selene Huang31ab4042020-04-29 04:22:39 -07001592} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001593
Janis Danisevskis24c04702020-12-16 18:28:39 -08001594} // namespace aidl::android::hardware::security::keymint