blob: a9a67bcc505d482e2bdd0996d0ad526082e7189c [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "KeyMintAidlTestBase.h"
18
19#include <chrono>
Shawn Willden7f424372021-01-10 18:06:50 -070020#include <unordered_set>
Selene Huang31ab4042020-04-29 04:22:39 -070021#include <vector>
22
23#include <android-base/logging.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080024#include <android/binder_manager.h>
David Drysdale4dc01072021-04-01 12:17:35 +010025#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070026#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010027#include <gmock/gmock.h>
Shawn Willden7c130392020-12-21 09:58:22 -070028#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010029#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
Max Bires9704ff62021-04-07 11:12:01 -070031#include <keymaster/cppcose/cppcose.h>
Shawn Willden7c130392020-12-21 09:58:22 -070032#include <keymint_support/attestation_record.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000033#include <keymint_support/key_param_output.h>
34#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070035#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Janis Danisevskis24c04702020-12-16 18:28:39 -080037namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070038
David Drysdale4dc01072021-04-01 12:17:35 +010039using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070040using namespace std::literals::chrono_literals;
41using std::endl;
42using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070043using std::unique_ptr;
44using ::testing::AssertionFailure;
45using ::testing::AssertionResult;
46using ::testing::AssertionSuccess;
Seth Moore7735ba52021-04-30 11:41:18 -070047using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010048using ::testing::MatchesRegex;
Seth Moore7735ba52021-04-30 11:41:18 -070049using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
52 if (set.size() == 0)
53 os << "(Empty)" << ::std::endl;
54 else {
55 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070056 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070057 }
58 return os;
59}
60
61namespace test {
62
Shawn Willden7f424372021-01-10 18:06:50 -070063namespace {
David Drysdalefe42aa32021-05-06 08:10:58 +010064
65// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
66// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
67const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
68
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000069typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070070// Predicate for testing basic characteristics validity in generation or import.
71bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
72 const vector<KeyCharacteristics>& key_characteristics) {
73 if (key_characteristics.empty()) return false;
74
75 std::unordered_set<SecurityLevel> levels_seen;
76 for (auto& entry : key_characteristics) {
77 if (entry.authorizations.empty()) return false;
78
Qi Wubeefae42021-01-28 23:16:37 +080079 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
80 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
81
Shawn Willden7f424372021-01-10 18:06:50 -070082 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
83 levels_seen.insert(entry.securityLevel);
84
85 // Generally, we should only have one entry, at the same security level as the KM
86 // instance. There is an exception: StrongBox KM can have some authorizations that are
87 // enforced by the TEE.
88 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
89 (secLevel == SecurityLevel::STRONGBOX &&
90 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
91
92 if (!isExpectedSecurityLevel) return false;
93 }
94 return true;
95}
96
Shawn Willden7c130392020-12-21 09:58:22 -070097// Extract attestation record from cert. Returned object is still part of cert; don't free it
98// separately.
99ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
100 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
101 EXPECT_TRUE(!!oid.get());
102 if (!oid.get()) return nullptr;
103
104 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
105 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
106 if (location == -1) return nullptr;
107
108 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
109 EXPECT_TRUE(!!attest_rec_ext)
110 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
111 if (!attest_rec_ext) return nullptr;
112
113 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
114 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
115 return attest_rec;
116}
117
118bool avb_verification_enabled() {
119 char value[PROPERTY_VALUE_MAX];
120 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
121}
122
123char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
124 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
125
126// Attestations don't contain everything in key authorization lists, so we need to filter the key
127// lists to produce the lists that we expect to match the attestations.
128auto kTagsToFilter = {
Tommy Chiu3b56cbc2021-05-11 18:36:50 +0800129 Tag::CREATION_DATETIME,
130 Tag::EC_CURVE,
131 Tag::HARDWARE_TYPE,
132 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700133};
134
135AuthorizationSet filtered_tags(const AuthorizationSet& set) {
136 AuthorizationSet filtered;
137 std::remove_copy_if(
138 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
139 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
140 kTagsToFilter.end();
141 });
142 return filtered;
143}
144
145string x509NameToStr(X509_NAME* name) {
146 char* s = X509_NAME_oneline(name, nullptr, 0);
147 string retval(s);
148 OPENSSL_free(s);
149 return retval;
150}
151
Shawn Willden7f424372021-01-10 18:06:50 -0700152} // namespace
153
Shawn Willden7c130392020-12-21 09:58:22 -0700154bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
155bool KeyMintAidlTestBase::dump_Attestations = false;
156
Janis Danisevskis24c04702020-12-16 18:28:39 -0800157ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700158 if (result.isOk()) return ErrorCode::OK;
159
Janis Danisevskis24c04702020-12-16 18:28:39 -0800160 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
161 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700162 }
163
164 return ErrorCode::UNKNOWN_ERROR;
165}
166
Janis Danisevskis24c04702020-12-16 18:28:39 -0800167void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700168 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800169 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700170
171 KeyMintHardwareInfo info;
172 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
173
174 securityLevel_ = info.securityLevel;
175 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
176 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100177 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700178
179 os_version_ = getOsVersion();
180 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100181 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700182}
183
184void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800185 if (AServiceManager_isDeclared(GetParam().c_str())) {
186 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
187 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
188 } else {
189 InitializeKeyMint(nullptr);
190 }
Selene Huang31ab4042020-04-29 04:22:39 -0700191}
192
193ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700194 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700195 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700196 vector<KeyCharacteristics>* key_characteristics,
197 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700198 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
199 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700200 << "Previous characteristics not deleted before generating key. Test bug.";
201
Shawn Willden7f424372021-01-10 18:06:50 -0700202 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700203 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700204 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700205 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
206 creationResult.keyCharacteristics);
207 EXPECT_GT(creationResult.keyBlob.size(), 0);
208 *key_blob = std::move(creationResult.keyBlob);
209 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700210 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700211
212 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
213 EXPECT_TRUE(algorithm);
214 if (algorithm &&
215 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700216 EXPECT_GE(cert_chain->size(), 1);
217 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
218 if (attest_key) {
219 EXPECT_EQ(cert_chain->size(), 1);
220 } else {
221 EXPECT_GT(cert_chain->size(), 1);
222 }
223 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700224 } else {
225 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700226 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700227 }
Selene Huang31ab4042020-04-29 04:22:39 -0700228 }
229
230 return GetReturnErrorCode(result);
231}
232
Shawn Willden7c130392020-12-21 09:58:22 -0700233ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
234 const optional<AttestationKey>& attest_key) {
235 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700236}
237
238ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
239 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700240 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700241 Status result;
242
Shawn Willden7f424372021-01-10 18:06:50 -0700243 cert_chain_.clear();
244 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700245 key_blob->clear();
246
Shawn Willden7f424372021-01-10 18:06:50 -0700247 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700248 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700249 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700250 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700251
252 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700253 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
254 creationResult.keyCharacteristics);
255 EXPECT_GT(creationResult.keyBlob.size(), 0);
256
257 *key_blob = std::move(creationResult.keyBlob);
258 *key_characteristics = std::move(creationResult.keyCharacteristics);
259 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700260
261 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
262 EXPECT_TRUE(algorithm);
263 if (algorithm &&
264 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
265 EXPECT_GE(cert_chain_.size(), 1);
266 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
267 } else {
268 // For symmetric keys there should be no certificates.
269 EXPECT_EQ(cert_chain_.size(), 0);
270 }
Selene Huang31ab4042020-04-29 04:22:39 -0700271 }
272
273 return GetReturnErrorCode(result);
274}
275
276ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
277 const string& key_material) {
278 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
279}
280
281ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
282 const AuthorizationSet& wrapping_key_desc,
283 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100284 const AuthorizationSet& unwrapping_params,
285 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700286 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
287
Shawn Willden7f424372021-01-10 18:06:50 -0700288 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700289
Shawn Willden7f424372021-01-10 18:06:50 -0700290 KeyCreationResult creationResult;
291 Status result = keymint_->importWrappedKey(
292 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
293 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100294 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700295
296 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700297 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
298 creationResult.keyCharacteristics);
299 EXPECT_GT(creationResult.keyBlob.size(), 0);
300
301 key_blob_ = std::move(creationResult.keyBlob);
302 key_characteristics_ = std::move(creationResult.keyCharacteristics);
303 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700304
305 AuthorizationSet allAuths;
306 for (auto& entry : key_characteristics_) {
307 allAuths.push_back(AuthorizationSet(entry.authorizations));
308 }
309 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
310 EXPECT_TRUE(algorithm);
311 if (algorithm &&
312 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
313 EXPECT_GE(cert_chain_.size(), 1);
314 } else {
315 // For symmetric keys there should be no certificates.
316 EXPECT_EQ(cert_chain_.size(), 0);
317 }
Selene Huang31ab4042020-04-29 04:22:39 -0700318 }
319
320 return GetReturnErrorCode(result);
321}
322
323ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
324 Status result = keymint_->deleteKey(*key_blob);
325 if (!keep_key_blob) {
326 *key_blob = vector<uint8_t>();
327 }
328
Janis Danisevskis24c04702020-12-16 18:28:39 -0800329 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700330 return GetReturnErrorCode(result);
331}
332
333ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
334 return DeleteKey(&key_blob_, keep_key_blob);
335}
336
337ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
338 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800339 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700340 return GetReturnErrorCode(result);
341}
342
David Drysdaled2cc8c22021-04-15 13:29:45 +0100343ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
344 Status result = keymint_->destroyAttestationIds();
345 return GetReturnErrorCode(result);
346}
347
Selene Huang31ab4042020-04-29 04:22:39 -0700348void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
349 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
350 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
351}
352
353void KeyMintAidlTestBase::CheckedDeleteKey() {
354 CheckedDeleteKey(&key_blob_);
355}
356
357ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
358 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800359 AuthorizationSet* out_params,
360 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700361 SCOPED_TRACE("Begin");
362 Status result;
363 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100364 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700365
366 if (result.isOk()) {
367 *out_params = out.params;
368 challenge_ = out.challenge;
369 op = out.operation;
370 }
371
372 return GetReturnErrorCode(result);
373}
374
375ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
376 const AuthorizationSet& in_params,
377 AuthorizationSet* out_params) {
378 SCOPED_TRACE("Begin");
379 Status result;
380 BeginResult out;
381
David Drysdale56ba9122021-04-19 19:10:47 +0100382 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700383
384 if (result.isOk()) {
385 *out_params = out.params;
386 challenge_ = out.challenge;
387 op_ = out.operation;
388 }
389
390 return GetReturnErrorCode(result);
391}
392
393ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
394 AuthorizationSet* out_params) {
395 SCOPED_TRACE("Begin");
396 EXPECT_EQ(nullptr, op_);
397 return Begin(purpose, key_blob_, in_params, out_params);
398}
399
400ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
401 SCOPED_TRACE("Begin");
402 AuthorizationSet out_params;
403 ErrorCode result = Begin(purpose, in_params, &out_params);
404 EXPECT_TRUE(out_params.empty());
405 return result;
406}
407
Shawn Willden92d79c02021-02-19 07:31:55 -0700408ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
409 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
410 {} /* hardwareAuthToken */,
411 {} /* verificationToken */));
412}
413
414ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700415 SCOPED_TRACE("Update");
416
417 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700418 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700419
Shawn Willden92d79c02021-02-19 07:31:55 -0700420 std::vector<uint8_t> o_put;
421 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700422
Shawn Willden92d79c02021-02-19 07:31:55 -0700423 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700424
425 return GetReturnErrorCode(result);
426}
427
Shawn Willden92d79c02021-02-19 07:31:55 -0700428ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700429 string* output) {
430 SCOPED_TRACE("Finish");
431 Status result;
432
433 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700434 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700435
436 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700437 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
438 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
439 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700440
Shawn Willden92d79c02021-02-19 07:31:55 -0700441 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700442
Shawn Willden92d79c02021-02-19 07:31:55 -0700443 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700444 return GetReturnErrorCode(result);
445}
446
Janis Danisevskis24c04702020-12-16 18:28:39 -0800447ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700448 SCOPED_TRACE("Abort");
449
450 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700451 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700452
453 Status retval = op->abort();
454 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800455 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700456}
457
458ErrorCode KeyMintAidlTestBase::Abort() {
459 SCOPED_TRACE("Abort");
460
461 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700462 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700463
464 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800465 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700466}
467
468void KeyMintAidlTestBase::AbortIfNeeded() {
469 SCOPED_TRACE("AbortIfNeeded");
470 if (op_) {
471 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800472 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700473 }
474}
475
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000476auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
477 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700478 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000479 AuthorizationSet begin_out_params;
480 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700481 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000482
483 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700484 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000485}
486
Selene Huang31ab4042020-04-29 04:22:39 -0700487string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
488 const string& message, const AuthorizationSet& in_params,
489 AuthorizationSet* out_params) {
490 SCOPED_TRACE("ProcessMessage");
491 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700492 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700493 EXPECT_EQ(ErrorCode::OK, result);
494 if (result != ErrorCode::OK) {
495 return "";
496 }
497
498 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700499 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700500 return output;
501}
502
503string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
504 const AuthorizationSet& params) {
505 SCOPED_TRACE("SignMessage");
506 AuthorizationSet out_params;
507 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
508 EXPECT_TRUE(out_params.empty());
509 return signature;
510}
511
512string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
513 SCOPED_TRACE("SignMessage");
514 return SignMessage(key_blob_, message, params);
515}
516
517string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
518 SCOPED_TRACE("MacMessage");
519 return SignMessage(
520 key_blob_, message,
521 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
522}
523
524void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
525 Digest digest, const string& expected_mac) {
526 SCOPED_TRACE("CheckHmacTestVector");
527 ASSERT_EQ(ErrorCode::OK,
528 ImportKey(AuthorizationSetBuilder()
529 .Authorization(TAG_NO_AUTH_REQUIRED)
530 .HmacKey(key.size() * 8)
531 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
532 .Digest(digest),
533 KeyFormat::RAW, key));
534 string signature = MacMessage(message, digest, expected_mac.size() * 8);
535 EXPECT_EQ(expected_mac, signature)
536 << "Test vector didn't match for key of size " << key.size() << " message of size "
537 << message.size() << " and digest " << digest;
538 CheckedDeleteKey();
539}
540
541void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
542 const string& message,
543 const string& expected_ciphertext) {
544 SCOPED_TRACE("CheckAesCtrTestVector");
545 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
546 .Authorization(TAG_NO_AUTH_REQUIRED)
547 .AesEncryptionKey(key.size() * 8)
548 .BlockMode(BlockMode::CTR)
549 .Authorization(TAG_CALLER_NONCE)
550 .Padding(PaddingMode::NONE),
551 KeyFormat::RAW, key));
552
553 auto params = AuthorizationSetBuilder()
554 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
555 .BlockMode(BlockMode::CTR)
556 .Padding(PaddingMode::NONE);
557 AuthorizationSet out_params;
558 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
559 EXPECT_EQ(expected_ciphertext, ciphertext);
560}
561
562void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
563 PaddingMode padding_mode, const string& key,
564 const string& iv, const string& input,
565 const string& expected_output) {
566 auto authset = AuthorizationSetBuilder()
567 .TripleDesEncryptionKey(key.size() * 7)
568 .BlockMode(block_mode)
569 .Authorization(TAG_NO_AUTH_REQUIRED)
570 .Padding(padding_mode);
571 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
572 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
573 ASSERT_GT(key_blob_.size(), 0U);
574
575 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
576 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
577 AuthorizationSet output_params;
578 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
579 EXPECT_EQ(expected_output, output);
580}
581
582void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
583 const string& signature, const AuthorizationSet& params) {
584 SCOPED_TRACE("VerifyMessage");
585 AuthorizationSet begin_out_params;
586 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
587
588 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700589 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700590 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700591 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700592}
593
594void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
595 const AuthorizationSet& params) {
596 SCOPED_TRACE("VerifyMessage");
597 VerifyMessage(key_blob_, message, signature, params);
598}
599
David Drysdalefe42aa32021-05-06 08:10:58 +0100600void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
601 const AuthorizationSet& params) {
602 SCOPED_TRACE("LocalVerifyMessage");
603
604 // Retrieve the public key from the leaf certificate.
605 ASSERT_GT(cert_chain_.size(), 0);
606 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
607 ASSERT_TRUE(key_cert.get());
608 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
609 ASSERT_TRUE(pub_key.get());
610
611 Digest digest = params.GetTagValue(TAG_DIGEST).value();
612 PaddingMode padding = PaddingMode::NONE;
613 auto tag = params.GetTagValue(TAG_PADDING);
614 if (tag.has_value()) {
615 padding = tag.value();
616 }
617
618 if (digest == Digest::NONE) {
619 switch (EVP_PKEY_id(pub_key.get())) {
620 case EVP_PKEY_EC: {
621 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
622 size_t data_size = std::min(data.size(), message.size());
623 memcpy(data.data(), message.data(), data_size);
624 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
625 ASSERT_TRUE(ecdsa.get());
626 ASSERT_EQ(1,
627 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
628 reinterpret_cast<const uint8_t*>(signature.data()),
629 signature.size(), ecdsa.get()));
630 break;
631 }
632 case EVP_PKEY_RSA: {
633 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
634 size_t data_size = std::min(data.size(), message.size());
635 memcpy(data.data(), message.data(), data_size);
636
637 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
638 ASSERT_TRUE(rsa.get());
639
640 size_t key_len = RSA_size(rsa.get());
641 int openssl_padding = RSA_NO_PADDING;
642 switch (padding) {
643 case PaddingMode::NONE:
644 ASSERT_TRUE(data_size <= key_len);
645 ASSERT_EQ(key_len, signature.size());
646 openssl_padding = RSA_NO_PADDING;
647 break;
648 case PaddingMode::RSA_PKCS1_1_5_SIGN:
649 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
650 key_len);
651 openssl_padding = RSA_PKCS1_PADDING;
652 break;
653 default:
654 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
655 }
656
657 vector<uint8_t> decrypted_data(key_len);
658 int bytes_decrypted = RSA_public_decrypt(
659 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
660 decrypted_data.data(), rsa.get(), openssl_padding);
661 ASSERT_GE(bytes_decrypted, 0);
662
663 const uint8_t* compare_pos = decrypted_data.data();
664 size_t bytes_to_compare = bytes_decrypted;
665 uint8_t zero_check_result = 0;
666 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
667 // If the data is short, for "unpadded" signing we zero-pad to the left. So
668 // during verification we should have zeros on the left of the decrypted data.
669 // Do a constant-time check.
670 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
671 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
672 ASSERT_EQ(0, zero_check_result);
673 bytes_to_compare = data_size;
674 }
675 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
676 break;
677 }
678 default:
679 ADD_FAILURE() << "Unknown public key type";
680 }
681 } else {
682 EVP_MD_CTX digest_ctx;
683 EVP_MD_CTX_init(&digest_ctx);
684 EVP_PKEY_CTX* pkey_ctx;
685 const EVP_MD* md = openssl_digest(digest);
686 ASSERT_NE(md, nullptr);
687 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
688
689 if (padding == PaddingMode::RSA_PSS) {
690 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
691 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
692 }
693
694 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
695 reinterpret_cast<const uint8_t*>(message.data()),
696 message.size()));
697 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
698 reinterpret_cast<const uint8_t*>(signature.data()),
699 signature.size()));
700 EVP_MD_CTX_cleanup(&digest_ctx);
701 }
702}
703
David Drysdale2b6c3512021-05-12 13:52:03 +0100704string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
705 const AuthorizationSet& params) {
706 SCOPED_TRACE("LocalRsaEncryptMessage");
707
708 // Retrieve the public key from the leaf certificate.
709 if (cert_chain_.empty()) {
710 ADD_FAILURE() << "No public key available";
711 return "Failure";
712 }
713 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
714 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
715 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
716
717 // Retrieve relevant tags.
718 Digest digest = Digest::NONE;
719 Digest mgf_digest = Digest::NONE;
720 PaddingMode padding = PaddingMode::NONE;
721
722 auto digest_tag = params.GetTagValue(TAG_DIGEST);
723 if (digest_tag.has_value()) digest = digest_tag.value();
724 auto pad_tag = params.GetTagValue(TAG_PADDING);
725 if (pad_tag.has_value()) padding = pad_tag.value();
726 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
727 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
728
729 const EVP_MD* md = openssl_digest(digest);
730 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
731
732 // Set up encryption context.
733 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
734 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
735 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
736 return "Failure";
737 }
738
739 int rc = -1;
740 switch (padding) {
741 case PaddingMode::NONE:
742 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
743 break;
744 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
745 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
746 break;
747 case PaddingMode::RSA_OAEP:
748 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
749 break;
750 default:
751 break;
752 }
753 if (rc <= 0) {
754 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
755 return "Failure";
756 }
757 if (padding == PaddingMode::RSA_OAEP) {
758 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
759 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
760 return "Failure";
761 }
762 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
763 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
764 return "Failure";
765 }
766 }
767
768 // Determine output size.
769 size_t outlen;
770 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
771 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
772 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
773 return "Failure";
774 }
775
776 // Left-zero-pad the input if necessary.
777 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
778 size_t to_encrypt_len = message.size();
779
780 std::unique_ptr<string> zero_padded_message;
781 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
782 zero_padded_message.reset(new string(outlen, '\0'));
783 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
784 message.size());
785 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
786 to_encrypt_len = outlen;
787 }
788
789 // Do the encryption.
790 string output(outlen, '\0');
791 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
792 to_encrypt_len) <= 0) {
793 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
794 return "Failure";
795 }
796 return output;
797}
798
Selene Huang31ab4042020-04-29 04:22:39 -0700799string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
800 const AuthorizationSet& in_params,
801 AuthorizationSet* out_params) {
802 SCOPED_TRACE("EncryptMessage");
803 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
804}
805
806string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
807 AuthorizationSet* out_params) {
808 SCOPED_TRACE("EncryptMessage");
809 return EncryptMessage(key_blob_, message, params, out_params);
810}
811
812string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
813 SCOPED_TRACE("EncryptMessage");
814 AuthorizationSet out_params;
815 string ciphertext = EncryptMessage(message, params, &out_params);
816 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
817 return ciphertext;
818}
819
820string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
821 PaddingMode padding) {
822 SCOPED_TRACE("EncryptMessage");
823 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
824 AuthorizationSet out_params;
825 string ciphertext = EncryptMessage(message, params, &out_params);
826 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
827 return ciphertext;
828}
829
830string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
831 PaddingMode padding, vector<uint8_t>* iv_out) {
832 SCOPED_TRACE("EncryptMessage");
833 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
834 AuthorizationSet out_params;
835 string ciphertext = EncryptMessage(message, params, &out_params);
836 EXPECT_EQ(1U, out_params.size());
837 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800838 EXPECT_TRUE(ivVal);
839 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700840 return ciphertext;
841}
842
843string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
844 PaddingMode padding, const vector<uint8_t>& iv_in) {
845 SCOPED_TRACE("EncryptMessage");
846 auto params = AuthorizationSetBuilder()
847 .BlockMode(block_mode)
848 .Padding(padding)
849 .Authorization(TAG_NONCE, iv_in);
850 AuthorizationSet out_params;
851 string ciphertext = EncryptMessage(message, params, &out_params);
852 return ciphertext;
853}
854
855string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
856 PaddingMode padding, uint8_t mac_length_bits,
857 const vector<uint8_t>& iv_in) {
858 SCOPED_TRACE("EncryptMessage");
859 auto params = AuthorizationSetBuilder()
860 .BlockMode(block_mode)
861 .Padding(padding)
862 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
863 .Authorization(TAG_NONCE, iv_in);
864 AuthorizationSet out_params;
865 string ciphertext = EncryptMessage(message, params, &out_params);
866 return ciphertext;
867}
868
David Drysdaled2cc8c22021-04-15 13:29:45 +0100869string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
870 PaddingMode padding, uint8_t mac_length_bits) {
871 SCOPED_TRACE("EncryptMessage");
872 auto params = AuthorizationSetBuilder()
873 .BlockMode(block_mode)
874 .Padding(padding)
875 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
876 AuthorizationSet out_params;
877 string ciphertext = EncryptMessage(message, params, &out_params);
878 return ciphertext;
879}
880
Selene Huang31ab4042020-04-29 04:22:39 -0700881string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
882 const string& ciphertext,
883 const AuthorizationSet& params) {
884 SCOPED_TRACE("DecryptMessage");
885 AuthorizationSet out_params;
886 string plaintext =
887 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
888 EXPECT_TRUE(out_params.empty());
889 return plaintext;
890}
891
892string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
893 const AuthorizationSet& params) {
894 SCOPED_TRACE("DecryptMessage");
895 return DecryptMessage(key_blob_, ciphertext, params);
896}
897
898string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
899 PaddingMode padding_mode, const vector<uint8_t>& iv) {
900 SCOPED_TRACE("DecryptMessage");
901 auto params = AuthorizationSetBuilder()
902 .BlockMode(block_mode)
903 .Padding(padding_mode)
904 .Authorization(TAG_NONCE, iv);
905 return DecryptMessage(key_blob_, ciphertext, params);
906}
907
908std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
909 const vector<uint8_t>& key_blob) {
910 std::pair<ErrorCode, vector<uint8_t>> retval;
911 vector<uint8_t> outKeyBlob;
912 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
913 ErrorCode errorcode = GetReturnErrorCode(result);
914 retval = std::tie(errorcode, outKeyBlob);
915
916 return retval;
917}
918vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
919 switch (algorithm) {
920 case Algorithm::RSA:
921 switch (SecLevel()) {
922 case SecurityLevel::SOFTWARE:
923 case SecurityLevel::TRUSTED_ENVIRONMENT:
924 return {2048, 3072, 4096};
925 case SecurityLevel::STRONGBOX:
926 return {2048};
927 default:
928 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
929 break;
930 }
931 break;
932 case Algorithm::EC:
933 switch (SecLevel()) {
934 case SecurityLevel::SOFTWARE:
935 case SecurityLevel::TRUSTED_ENVIRONMENT:
936 return {224, 256, 384, 521};
937 case SecurityLevel::STRONGBOX:
938 return {256};
939 default:
940 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
941 break;
942 }
943 break;
944 case Algorithm::AES:
945 return {128, 256};
946 case Algorithm::TRIPLE_DES:
947 return {168};
948 case Algorithm::HMAC: {
949 vector<uint32_t> retval((512 - 64) / 8 + 1);
950 uint32_t size = 64 - 8;
951 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
952 return retval;
953 }
954 default:
955 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
956 return {};
957 }
958 ADD_FAILURE() << "Should be impossible to get here";
959 return {};
960}
961
962vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
963 if (SecLevel() == SecurityLevel::STRONGBOX) {
964 switch (algorithm) {
965 case Algorithm::RSA:
966 return {3072, 4096};
967 case Algorithm::EC:
968 return {224, 384, 521};
969 case Algorithm::AES:
970 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +0000971 case Algorithm::TRIPLE_DES:
972 return {56};
973 default:
974 return {};
975 }
976 } else {
977 switch (algorithm) {
978 case Algorithm::TRIPLE_DES:
979 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -0700980 default:
981 return {};
982 }
983 }
984 return {};
985}
986
David Drysdale7de9feb2021-03-05 14:56:19 +0000987vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
988 switch (algorithm) {
989 case Algorithm::AES:
990 return {
991 BlockMode::CBC,
992 BlockMode::CTR,
993 BlockMode::ECB,
994 BlockMode::GCM,
995 };
996 case Algorithm::TRIPLE_DES:
997 return {
998 BlockMode::CBC,
999 BlockMode::ECB,
1000 };
1001 default:
1002 return {};
1003 }
1004}
1005
1006vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1007 BlockMode blockMode) {
1008 switch (algorithm) {
1009 case Algorithm::AES:
1010 switch (blockMode) {
1011 case BlockMode::CBC:
1012 case BlockMode::ECB:
1013 return {PaddingMode::NONE, PaddingMode::PKCS7};
1014 case BlockMode::CTR:
1015 case BlockMode::GCM:
1016 return {PaddingMode::NONE};
1017 default:
1018 return {};
1019 };
1020 case Algorithm::TRIPLE_DES:
1021 switch (blockMode) {
1022 case BlockMode::CBC:
1023 case BlockMode::ECB:
1024 return {PaddingMode::NONE, PaddingMode::PKCS7};
1025 default:
1026 return {};
1027 };
1028 default:
1029 return {};
1030 }
1031}
1032
1033vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1034 BlockMode blockMode) {
1035 switch (algorithm) {
1036 case Algorithm::AES:
1037 switch (blockMode) {
1038 case BlockMode::CTR:
1039 case BlockMode::GCM:
1040 return {PaddingMode::PKCS7};
1041 default:
1042 return {};
1043 };
1044 default:
1045 return {};
1046 }
1047}
1048
Selene Huang31ab4042020-04-29 04:22:39 -07001049vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1050 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1051 return {EcCurve::P_256};
1052 } else {
1053 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1054 }
1055}
1056
1057vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
1058 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
1059 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
1060 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
1061}
1062
1063vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1064 switch (SecLevel()) {
1065 case SecurityLevel::SOFTWARE:
1066 case SecurityLevel::TRUSTED_ENVIRONMENT:
1067 if (withNone) {
1068 if (withMD5)
1069 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1070 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1071 Digest::SHA_2_512};
1072 else
1073 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1074 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1075 } else {
1076 if (withMD5)
1077 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1078 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1079 else
1080 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1081 Digest::SHA_2_512};
1082 }
1083 break;
1084 case SecurityLevel::STRONGBOX:
1085 if (withNone)
1086 return {Digest::NONE, Digest::SHA_2_256};
1087 else
1088 return {Digest::SHA_2_256};
1089 break;
1090 default:
1091 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1092 break;
1093 }
1094 ADD_FAILURE() << "Should be impossible to get here";
1095 return {};
1096}
1097
Shawn Willden7f424372021-01-10 18:06:50 -07001098static const vector<KeyParameter> kEmptyAuthList{};
1099
1100const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1101 const vector<KeyCharacteristics>& key_characteristics) {
1102 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1103 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1104 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1105}
1106
Qi Wubeefae42021-01-28 23:16:37 +08001107const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1108 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1109 auto found = std::find_if(
1110 key_characteristics.begin(), key_characteristics.end(),
1111 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001112 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1113}
1114
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001115ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001116 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001117 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1118 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1119 return result;
1120}
1121
1122ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001123 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001124 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1125 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1126 return result;
1127}
1128
1129ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1130 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001131 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001132 rsaKeyBlob, KeyPurpose::SIGN, message,
1133 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1134 return result;
1135}
1136
1137ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001138 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1139 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001140 return result;
1141}
1142
Selene Huang6e46f142021-04-20 19:20:11 -07001143void verify_serial(X509* cert, const uint64_t expected_serial) {
1144 BIGNUM_Ptr ser(BN_new());
1145 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1146
1147 uint64_t serial;
1148 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1149 EXPECT_EQ(serial, expected_serial);
1150}
1151
1152// Please set self_signed to true for fake certificates or self signed
1153// certificates
1154void verify_subject(const X509* cert, //
1155 const string& subject, //
1156 bool self_signed) {
1157 char* cert_issuer = //
1158 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1159
1160 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1161
1162 string expected_subject("/CN=");
1163 if (subject.empty()) {
1164 expected_subject.append("Android Keystore Key");
1165 } else {
1166 expected_subject.append(subject);
1167 }
1168
1169 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1170
1171 if (self_signed) {
1172 EXPECT_STREQ(cert_issuer, cert_subj)
1173 << "Cert issuer and subject mismatch for self signed certificate.";
1174 }
1175
1176 OPENSSL_free(cert_subj);
1177 OPENSSL_free(cert_issuer);
1178}
1179
1180vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1181 BIGNUM_Ptr serial(BN_new());
1182 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1183
1184 int len = BN_num_bytes(serial.get());
1185 vector<uint8_t> serial_blob(len);
1186 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1187 return {};
1188 }
1189
David Drysdale216d9922021-05-18 11:43:31 +01001190 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1191 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1192 // Top bit being set indicates a negative number in two's complement, but our input
1193 // was positive.
1194 // In either case, prepend a zero byte.
1195 serial_blob.insert(serial_blob.begin(), 0x00);
1196 }
1197
Selene Huang6e46f142021-04-20 19:20:11 -07001198 return serial_blob;
1199}
1200
1201void verify_subject_and_serial(const Certificate& certificate, //
1202 const uint64_t expected_serial, //
1203 const string& subject, bool self_signed) {
1204 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1205 ASSERT_TRUE(!!cert.get());
1206
1207 verify_serial(cert.get(), expected_serial);
1208 verify_subject(cert.get(), subject, self_signed);
1209}
1210
Shawn Willden7c130392020-12-21 09:58:22 -07001211bool verify_attestation_record(const string& challenge, //
1212 const string& app_id, //
1213 AuthorizationSet expected_sw_enforced, //
1214 AuthorizationSet expected_hw_enforced, //
1215 SecurityLevel security_level,
1216 const vector<uint8_t>& attestation_cert) {
1217 X509_Ptr cert(parse_cert_blob(attestation_cert));
1218 EXPECT_TRUE(!!cert.get());
1219 if (!cert.get()) return false;
1220
1221 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1222 EXPECT_TRUE(!!attest_rec);
1223 if (!attest_rec) return false;
1224
1225 AuthorizationSet att_sw_enforced;
1226 AuthorizationSet att_hw_enforced;
1227 uint32_t att_attestation_version;
1228 uint32_t att_keymaster_version;
1229 SecurityLevel att_attestation_security_level;
1230 SecurityLevel att_keymaster_security_level;
1231 vector<uint8_t> att_challenge;
1232 vector<uint8_t> att_unique_id;
1233 vector<uint8_t> att_app_id;
1234
1235 auto error = parse_attestation_record(attest_rec->data, //
1236 attest_rec->length, //
1237 &att_attestation_version, //
1238 &att_attestation_security_level, //
1239 &att_keymaster_version, //
1240 &att_keymaster_security_level, //
1241 &att_challenge, //
1242 &att_sw_enforced, //
1243 &att_hw_enforced, //
1244 &att_unique_id);
1245 EXPECT_EQ(ErrorCode::OK, error);
1246 if (error != ErrorCode::OK) return false;
1247
Shawn Willden3cb64a62021-04-05 14:39:05 -06001248 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -07001249 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001250
Selene Huang4f64c222021-04-13 19:54:36 -07001251 // check challenge and app id only if we expects a non-fake certificate
1252 if (challenge.length() > 0) {
1253 EXPECT_EQ(challenge.length(), att_challenge.size());
1254 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1255
1256 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1257 }
Shawn Willden7c130392020-12-21 09:58:22 -07001258
Shawn Willden3cb64a62021-04-05 14:39:05 -06001259 EXPECT_EQ(att_keymaster_version, 100U);
Shawn Willden7c130392020-12-21 09:58:22 -07001260 EXPECT_EQ(security_level, att_keymaster_security_level);
1261 EXPECT_EQ(security_level, att_attestation_security_level);
1262
Shawn Willden7c130392020-12-21 09:58:22 -07001263
1264 char property_value[PROPERTY_VALUE_MAX] = {};
1265 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
1266 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
1267 // for the BOOT_PATCH_LEVEL.
1268 if (avb_verification_enabled()) {
1269 for (int i = 0; i < att_hw_enforced.size(); i++) {
1270 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1271 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1272 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001273 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -07001274 // strptime seems to require delimiters, but the tag value will
1275 // be YYYYMMDD
1276 date.insert(6, "-");
1277 date.insert(4, "-");
1278 EXPECT_EQ(date.size(), 10);
1279 struct tm time;
1280 strptime(date.c_str(), "%Y-%m-%d", &time);
1281
1282 // Day of the month (0-31)
1283 EXPECT_GE(time.tm_mday, 0);
1284 EXPECT_LT(time.tm_mday, 32);
1285 // Months since Jan (0-11)
1286 EXPECT_GE(time.tm_mon, 0);
1287 EXPECT_LT(time.tm_mon, 12);
1288 // Years since 1900
1289 EXPECT_GT(time.tm_year, 110);
1290 EXPECT_LT(time.tm_year, 200);
1291 }
1292 }
1293 }
1294
1295 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1296 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1297 // indicates correct encoding. No need to check if it's in both lists, since the
1298 // AuthorizationSet compare below will handle mismatches of tags.
1299 if (security_level == SecurityLevel::SOFTWARE) {
1300 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1301 } else {
1302 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1303 }
1304
1305 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
1306 // the authorization list during key generation) isn't being attested to in the certificate.
1307 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1308 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1309 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1310 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1311
1312 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1313 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1314 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1315 att_hw_enforced.Contains(TAG_KEY_SIZE));
1316 }
1317
1318 // Test root of trust elements
1319 vector<uint8_t> verified_boot_key;
1320 VerifiedBoot verified_boot_state;
1321 bool device_locked;
1322 vector<uint8_t> verified_boot_hash;
1323 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1324 &verified_boot_state, &device_locked, &verified_boot_hash);
1325 EXPECT_EQ(ErrorCode::OK, error);
1326
1327 if (avb_verification_enabled()) {
1328 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1329 string prop_string(property_value);
1330 EXPECT_EQ(prop_string.size(), 64);
1331 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1332
1333 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1334 if (!strcmp(property_value, "unlocked")) {
1335 EXPECT_FALSE(device_locked);
1336 } else {
1337 EXPECT_TRUE(device_locked);
1338 }
1339
1340 // Check that the device is locked if not debuggable, e.g., user build
1341 // images in CTS. For VTS, debuggable images are used to allow adb root
1342 // and the device is unlocked.
1343 if (!property_get_bool("ro.debuggable", false)) {
1344 EXPECT_TRUE(device_locked);
1345 } else {
1346 EXPECT_FALSE(device_locked);
1347 }
1348 }
1349
1350 // Verified boot key should be all 0's if the boot state is not verified or self signed
1351 std::string empty_boot_key(32, '\0');
1352 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1353 verified_boot_key.size());
1354 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1355 if (!strcmp(property_value, "green")) {
1356 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1357 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1358 verified_boot_key.size()));
1359 } else if (!strcmp(property_value, "yellow")) {
1360 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1361 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1362 verified_boot_key.size()));
1363 } else if (!strcmp(property_value, "orange")) {
1364 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1365 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1366 verified_boot_key.size()));
1367 } else if (!strcmp(property_value, "red")) {
1368 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1369 } else {
1370 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1371 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1372 verified_boot_key.size()));
1373 }
1374
1375 att_sw_enforced.Sort();
1376 expected_sw_enforced.Sort();
1377 auto a = filtered_tags(expected_sw_enforced);
1378 auto b = filtered_tags(att_sw_enforced);
1379 EXPECT_EQ(a, b);
1380
1381 att_hw_enforced.Sort();
1382 expected_hw_enforced.Sort();
1383 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1384
1385 return true;
1386}
1387
1388string bin2hex(const vector<uint8_t>& data) {
1389 string retval;
1390 retval.reserve(data.size() * 2 + 1);
1391 for (uint8_t byte : data) {
1392 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1393 retval.push_back(nibble2hex[0x0F & byte]);
1394 }
1395 return retval;
1396}
1397
David Drysdalef0d516d2021-03-22 07:51:43 +00001398AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1399 AuthorizationSet authList;
1400 for (auto& entry : key_characteristics) {
1401 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1402 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1403 authList.push_back(AuthorizationSet(entry.authorizations));
1404 }
1405 }
1406 return authList;
1407}
1408
1409AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1410 AuthorizationSet authList;
1411 for (auto& entry : key_characteristics) {
1412 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1413 entry.securityLevel == SecurityLevel::KEYSTORE) {
1414 authList.push_back(AuthorizationSet(entry.authorizations));
1415 }
1416 }
1417 return authList;
1418}
1419
Shawn Willden7c130392020-12-21 09:58:22 -07001420AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1421 std::stringstream cert_data;
1422
1423 for (size_t i = 0; i < chain.size(); ++i) {
1424 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1425
1426 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1427 X509_Ptr signing_cert;
1428 if (i < chain.size() - 1) {
1429 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1430 } else {
1431 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1432 }
1433 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1434
1435 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1436 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1437
1438 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1439 return AssertionFailure()
1440 << "Verification of certificate " << i << " failed "
1441 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1442 << cert_data.str();
1443 }
1444
1445 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1446 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1447 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001448 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1449 << " Signer subject is " << signer_subj
1450 << " Issuer subject is " << cert_issuer << endl
1451 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001452 }
Shawn Willden7c130392020-12-21 09:58:22 -07001453 }
1454
1455 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1456 return AssertionSuccess();
1457}
1458
1459X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1460 const uint8_t* p = blob.data();
1461 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1462}
1463
David Drysdalef0d516d2021-03-22 07:51:43 +00001464vector<uint8_t> make_name_from_str(const string& name) {
1465 X509_NAME_Ptr x509_name(X509_NAME_new());
1466 EXPECT_TRUE(x509_name.get() != nullptr);
1467 if (!x509_name) return {};
1468
1469 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1470 "CN", //
1471 MBSTRING_ASC,
1472 reinterpret_cast<const uint8_t*>(name.c_str()),
1473 -1, // len
1474 -1, // loc
1475 0 /* set */));
1476
1477 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1478 EXPECT_GT(len, 0);
1479
1480 vector<uint8_t> retval(len);
1481 uint8_t* p = retval.data();
1482 i2d_X509_NAME(x509_name.get(), &p);
1483
1484 return retval;
1485}
1486
David Drysdale4dc01072021-04-01 12:17:35 +01001487namespace {
1488
1489void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1490 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1491 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1492
1493 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1494 if (testMode) {
1495 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1496 MatchesRegex("{\n"
1497 " 1 : 2,\n" // kty: EC2
1498 " 3 : -7,\n" // alg: ES256
1499 " -1 : 1,\n" // EC id: P256
1500 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1501 // sequence of 32 hexadecimal bytes, enclosed in braces and
1502 // separated by commas. In this case, some Ed25519 public key.
1503 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1504 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1505 " -70000 : null,\n" // test marker
1506 "}"));
1507 } else {
1508 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1509 MatchesRegex("{\n"
1510 " 1 : 2,\n" // kty: EC2
1511 " 3 : -7,\n" // alg: ES256
1512 " -1 : 1,\n" // EC id: P256
1513 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1514 // sequence of 32 hexadecimal bytes, enclosed in braces and
1515 // separated by commas. In this case, some Ed25519 public key.
1516 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1517 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1518 "}"));
1519 }
1520}
1521
1522} // namespace
1523
1524void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1525 vector<uint8_t>* payload_value) {
1526 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1527 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1528
1529 ASSERT_NE(coseMac0->asArray(), nullptr);
1530 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1531
1532 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1533 ASSERT_NE(protParms, nullptr);
1534
1535 // Header label:value of 'alg': HMAC-256
1536 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1537
1538 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1539 ASSERT_NE(unprotParms, nullptr);
1540 ASSERT_EQ(unprotParms->size(), 0);
1541
1542 // The payload is a bstr holding an encoded COSE_Key
1543 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1544 ASSERT_NE(payload, nullptr);
1545 check_cose_key(payload->value(), testMode);
1546
1547 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1548 ASSERT_TRUE(coseMac0Tag);
1549 auto extractedTag = coseMac0Tag->value();
1550 EXPECT_EQ(extractedTag.size(), 32U);
1551
1552 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore7735ba52021-04-30 11:41:18 -07001553 auto macFunction = [](const cppcose::bytevec& input) {
1554 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1555 };
1556 auto testTag =
1557 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001558 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1559
1560 if (testMode) {
Seth Moore7735ba52021-04-30 11:41:18 -07001561 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001562 } else {
Seth Moore7735ba52021-04-30 11:41:18 -07001563 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01001564 }
1565 if (payload_value != nullptr) {
1566 *payload_value = payload->value();
1567 }
1568}
1569
1570void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1571 // Extract x and y affine coordinates from the encoded Cose_Key.
1572 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1573 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1574 auto coseKey = parsedPayload->asMap();
1575 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1576 ASSERT_NE(xItem->asBstr(), nullptr);
1577 vector<uint8_t> x = xItem->asBstr()->value();
1578 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1579 ASSERT_NE(yItem->asBstr(), nullptr);
1580 vector<uint8_t> y = yItem->asBstr()->value();
1581
1582 // Concatenate: 0x04 (uncompressed form marker) | x | y
1583 vector<uint8_t> pubKeyData{0x04};
1584 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1585 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1586
1587 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1588 ASSERT_NE(ecKey, nullptr);
1589 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1590 ASSERT_NE(group, nullptr);
1591 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1592 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1593 ASSERT_NE(point, nullptr);
1594 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1595 nullptr),
1596 1);
1597 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1598
1599 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1600 ASSERT_NE(pubKey, nullptr);
1601 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1602 *signingKey = std::move(pubKey);
1603}
1604
Selene Huang31ab4042020-04-29 04:22:39 -07001605} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001606
Janis Danisevskis24c04702020-12-16 18:28:39 -08001607} // namespace aidl::android::hardware::security::keymint