blob: 61f2f771ab23d51b4839ce9274eba5e80f2b7506 [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 {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000062typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070063// Predicate for testing basic characteristics validity in generation or import.
64bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
65 const vector<KeyCharacteristics>& key_characteristics) {
66 if (key_characteristics.empty()) return false;
67
68 std::unordered_set<SecurityLevel> levels_seen;
69 for (auto& entry : key_characteristics) {
70 if (entry.authorizations.empty()) return false;
71
Qi Wubeefae42021-01-28 23:16:37 +080072 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
73 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
74
Shawn Willden7f424372021-01-10 18:06:50 -070075 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
76 levels_seen.insert(entry.securityLevel);
77
78 // Generally, we should only have one entry, at the same security level as the KM
79 // instance. There is an exception: StrongBox KM can have some authorizations that are
80 // enforced by the TEE.
81 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
82 (secLevel == SecurityLevel::STRONGBOX &&
83 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
84
85 if (!isExpectedSecurityLevel) return false;
86 }
87 return true;
88}
89
Shawn Willden7c130392020-12-21 09:58:22 -070090// Extract attestation record from cert. Returned object is still part of cert; don't free it
91// separately.
92ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
93 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
94 EXPECT_TRUE(!!oid.get());
95 if (!oid.get()) return nullptr;
96
97 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
98 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
99 if (location == -1) return nullptr;
100
101 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
102 EXPECT_TRUE(!!attest_rec_ext)
103 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
104 if (!attest_rec_ext) return nullptr;
105
106 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
107 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
108 return attest_rec;
109}
110
111bool avb_verification_enabled() {
112 char value[PROPERTY_VALUE_MAX];
113 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
114}
115
116char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
117 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
118
119// Attestations don't contain everything in key authorization lists, so we need to filter the key
120// lists to produce the lists that we expect to match the attestations.
121auto kTagsToFilter = {
Shawn Willden7c130392020-12-21 09:58:22 -0700122 Tag::CREATION_DATETIME, //
123 Tag::EC_CURVE,
124 Tag::HARDWARE_TYPE,
125 Tag::INCLUDE_UNIQUE_ID,
126};
127
128AuthorizationSet filtered_tags(const AuthorizationSet& set) {
129 AuthorizationSet filtered;
130 std::remove_copy_if(
131 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
132 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
133 kTagsToFilter.end();
134 });
135 return filtered;
136}
137
138string x509NameToStr(X509_NAME* name) {
139 char* s = X509_NAME_oneline(name, nullptr, 0);
140 string retval(s);
141 OPENSSL_free(s);
142 return retval;
143}
144
Shawn Willden7f424372021-01-10 18:06:50 -0700145} // namespace
146
Shawn Willden7c130392020-12-21 09:58:22 -0700147bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
148bool KeyMintAidlTestBase::dump_Attestations = false;
149
Janis Danisevskis24c04702020-12-16 18:28:39 -0800150ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700151 if (result.isOk()) return ErrorCode::OK;
152
Janis Danisevskis24c04702020-12-16 18:28:39 -0800153 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
154 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700155 }
156
157 return ErrorCode::UNKNOWN_ERROR;
158}
159
Janis Danisevskis24c04702020-12-16 18:28:39 -0800160void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700161 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800162 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700163
164 KeyMintHardwareInfo info;
165 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
166
167 securityLevel_ = info.securityLevel;
168 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
169 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
170
171 os_version_ = getOsVersion();
172 os_patch_level_ = getOsPatchlevel();
173}
174
175void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800176 if (AServiceManager_isDeclared(GetParam().c_str())) {
177 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
178 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
179 } else {
180 InitializeKeyMint(nullptr);
181 }
Selene Huang31ab4042020-04-29 04:22:39 -0700182}
183
184ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700185 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700186 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700187 vector<KeyCharacteristics>* key_characteristics,
188 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700189 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
190 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700191 << "Previous characteristics not deleted before generating key. Test bug.";
192
Shawn Willden7f424372021-01-10 18:06:50 -0700193 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700194 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700195 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700196 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
197 creationResult.keyCharacteristics);
198 EXPECT_GT(creationResult.keyBlob.size(), 0);
199 *key_blob = std::move(creationResult.keyBlob);
200 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700201 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700202
203 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
204 EXPECT_TRUE(algorithm);
205 if (algorithm &&
206 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700207 EXPECT_GE(cert_chain->size(), 1);
208 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
209 if (attest_key) {
210 EXPECT_EQ(cert_chain->size(), 1);
211 } else {
212 EXPECT_GT(cert_chain->size(), 1);
213 }
214 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700215 } else {
216 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700217 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700218 }
Selene Huang31ab4042020-04-29 04:22:39 -0700219 }
220
221 return GetReturnErrorCode(result);
222}
223
Shawn Willden7c130392020-12-21 09:58:22 -0700224ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
225 const optional<AttestationKey>& attest_key) {
226 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700227}
228
229ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
230 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700231 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700232 Status result;
233
Shawn Willden7f424372021-01-10 18:06:50 -0700234 cert_chain_.clear();
235 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700236 key_blob->clear();
237
Shawn Willden7f424372021-01-10 18:06:50 -0700238 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700239 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700240 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700241 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700242
243 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700244 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
245 creationResult.keyCharacteristics);
246 EXPECT_GT(creationResult.keyBlob.size(), 0);
247
248 *key_blob = std::move(creationResult.keyBlob);
249 *key_characteristics = std::move(creationResult.keyCharacteristics);
250 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700251
252 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
253 EXPECT_TRUE(algorithm);
254 if (algorithm &&
255 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
256 EXPECT_GE(cert_chain_.size(), 1);
257 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
258 } else {
259 // For symmetric keys there should be no certificates.
260 EXPECT_EQ(cert_chain_.size(), 0);
261 }
Selene Huang31ab4042020-04-29 04:22:39 -0700262 }
263
264 return GetReturnErrorCode(result);
265}
266
267ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
268 const string& key_material) {
269 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
270}
271
272ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
273 const AuthorizationSet& wrapping_key_desc,
274 string masking_key,
275 const AuthorizationSet& unwrapping_params) {
Selene Huang31ab4042020-04-29 04:22:39 -0700276 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
277
Shawn Willden7f424372021-01-10 18:06:50 -0700278 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700279
Shawn Willden7f424372021-01-10 18:06:50 -0700280 KeyCreationResult creationResult;
281 Status result = keymint_->importWrappedKey(
282 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
283 vector<uint8_t>(masking_key.begin(), masking_key.end()),
284 unwrapping_params.vector_data(), 0 /* passwordSid */, 0 /* biometricSid */,
285 &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700286
287 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700288 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
289 creationResult.keyCharacteristics);
290 EXPECT_GT(creationResult.keyBlob.size(), 0);
291
292 key_blob_ = std::move(creationResult.keyBlob);
293 key_characteristics_ = std::move(creationResult.keyCharacteristics);
294 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700295
296 AuthorizationSet allAuths;
297 for (auto& entry : key_characteristics_) {
298 allAuths.push_back(AuthorizationSet(entry.authorizations));
299 }
300 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
301 EXPECT_TRUE(algorithm);
302 if (algorithm &&
303 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
304 EXPECT_GE(cert_chain_.size(), 1);
305 } else {
306 // For symmetric keys there should be no certificates.
307 EXPECT_EQ(cert_chain_.size(), 0);
308 }
Selene Huang31ab4042020-04-29 04:22:39 -0700309 }
310
311 return GetReturnErrorCode(result);
312}
313
314ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
315 Status result = keymint_->deleteKey(*key_blob);
316 if (!keep_key_blob) {
317 *key_blob = vector<uint8_t>();
318 }
319
Janis Danisevskis24c04702020-12-16 18:28:39 -0800320 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700321 return GetReturnErrorCode(result);
322}
323
324ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
325 return DeleteKey(&key_blob_, keep_key_blob);
326}
327
328ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
329 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800330 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700331 return GetReturnErrorCode(result);
332}
333
334void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
335 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
336 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
337}
338
339void KeyMintAidlTestBase::CheckedDeleteKey() {
340 CheckedDeleteKey(&key_blob_);
341}
342
343ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
344 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800345 AuthorizationSet* out_params,
346 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700347 SCOPED_TRACE("Begin");
348 Status result;
349 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100350 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700351
352 if (result.isOk()) {
353 *out_params = out.params;
354 challenge_ = out.challenge;
355 op = out.operation;
356 }
357
358 return GetReturnErrorCode(result);
359}
360
361ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
362 const AuthorizationSet& in_params,
363 AuthorizationSet* out_params) {
364 SCOPED_TRACE("Begin");
365 Status result;
366 BeginResult out;
367
David Drysdale56ba9122021-04-19 19:10:47 +0100368 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700369
370 if (result.isOk()) {
371 *out_params = out.params;
372 challenge_ = out.challenge;
373 op_ = out.operation;
374 }
375
376 return GetReturnErrorCode(result);
377}
378
379ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
380 AuthorizationSet* out_params) {
381 SCOPED_TRACE("Begin");
382 EXPECT_EQ(nullptr, op_);
383 return Begin(purpose, key_blob_, in_params, out_params);
384}
385
386ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
387 SCOPED_TRACE("Begin");
388 AuthorizationSet out_params;
389 ErrorCode result = Begin(purpose, in_params, &out_params);
390 EXPECT_TRUE(out_params.empty());
391 return result;
392}
393
Shawn Willden92d79c02021-02-19 07:31:55 -0700394ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
395 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
396 {} /* hardwareAuthToken */,
397 {} /* verificationToken */));
398}
399
400ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700401 SCOPED_TRACE("Update");
402
403 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700404 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700405
Shawn Willden92d79c02021-02-19 07:31:55 -0700406 std::vector<uint8_t> o_put;
407 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700408
Shawn Willden92d79c02021-02-19 07:31:55 -0700409 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700410
411 return GetReturnErrorCode(result);
412}
413
Shawn Willden92d79c02021-02-19 07:31:55 -0700414ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700415 string* output) {
416 SCOPED_TRACE("Finish");
417 Status result;
418
419 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700420 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700421
422 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700423 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
424 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
425 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700426
Shawn Willden92d79c02021-02-19 07:31:55 -0700427 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700428
Shawn Willden92d79c02021-02-19 07:31:55 -0700429 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700430 return GetReturnErrorCode(result);
431}
432
Janis Danisevskis24c04702020-12-16 18:28:39 -0800433ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700434 SCOPED_TRACE("Abort");
435
436 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700437 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700438
439 Status retval = op->abort();
440 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800441 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700442}
443
444ErrorCode KeyMintAidlTestBase::Abort() {
445 SCOPED_TRACE("Abort");
446
447 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700448 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700449
450 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800451 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700452}
453
454void KeyMintAidlTestBase::AbortIfNeeded() {
455 SCOPED_TRACE("AbortIfNeeded");
456 if (op_) {
457 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800458 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700459 }
460}
461
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000462auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
463 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700464 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000465 AuthorizationSet begin_out_params;
466 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700467 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000468
469 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700470 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000471}
472
Selene Huang31ab4042020-04-29 04:22:39 -0700473string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
474 const string& message, const AuthorizationSet& in_params,
475 AuthorizationSet* out_params) {
476 SCOPED_TRACE("ProcessMessage");
477 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700478 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700479 EXPECT_EQ(ErrorCode::OK, result);
480 if (result != ErrorCode::OK) {
481 return "";
482 }
483
484 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700485 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700486 return output;
487}
488
489string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
490 const AuthorizationSet& params) {
491 SCOPED_TRACE("SignMessage");
492 AuthorizationSet out_params;
493 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
494 EXPECT_TRUE(out_params.empty());
495 return signature;
496}
497
498string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
499 SCOPED_TRACE("SignMessage");
500 return SignMessage(key_blob_, message, params);
501}
502
503string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
504 SCOPED_TRACE("MacMessage");
505 return SignMessage(
506 key_blob_, message,
507 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
508}
509
510void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
511 Digest digest, const string& expected_mac) {
512 SCOPED_TRACE("CheckHmacTestVector");
513 ASSERT_EQ(ErrorCode::OK,
514 ImportKey(AuthorizationSetBuilder()
515 .Authorization(TAG_NO_AUTH_REQUIRED)
516 .HmacKey(key.size() * 8)
517 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
518 .Digest(digest),
519 KeyFormat::RAW, key));
520 string signature = MacMessage(message, digest, expected_mac.size() * 8);
521 EXPECT_EQ(expected_mac, signature)
522 << "Test vector didn't match for key of size " << key.size() << " message of size "
523 << message.size() << " and digest " << digest;
524 CheckedDeleteKey();
525}
526
527void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
528 const string& message,
529 const string& expected_ciphertext) {
530 SCOPED_TRACE("CheckAesCtrTestVector");
531 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
532 .Authorization(TAG_NO_AUTH_REQUIRED)
533 .AesEncryptionKey(key.size() * 8)
534 .BlockMode(BlockMode::CTR)
535 .Authorization(TAG_CALLER_NONCE)
536 .Padding(PaddingMode::NONE),
537 KeyFormat::RAW, key));
538
539 auto params = AuthorizationSetBuilder()
540 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
541 .BlockMode(BlockMode::CTR)
542 .Padding(PaddingMode::NONE);
543 AuthorizationSet out_params;
544 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
545 EXPECT_EQ(expected_ciphertext, ciphertext);
546}
547
548void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
549 PaddingMode padding_mode, const string& key,
550 const string& iv, const string& input,
551 const string& expected_output) {
552 auto authset = AuthorizationSetBuilder()
553 .TripleDesEncryptionKey(key.size() * 7)
554 .BlockMode(block_mode)
555 .Authorization(TAG_NO_AUTH_REQUIRED)
556 .Padding(padding_mode);
557 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
558 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
559 ASSERT_GT(key_blob_.size(), 0U);
560
561 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
562 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
563 AuthorizationSet output_params;
564 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
565 EXPECT_EQ(expected_output, output);
566}
567
568void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
569 const string& signature, const AuthorizationSet& params) {
570 SCOPED_TRACE("VerifyMessage");
571 AuthorizationSet begin_out_params;
572 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
573
574 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700575 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700576 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700577 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700578}
579
580void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
581 const AuthorizationSet& params) {
582 SCOPED_TRACE("VerifyMessage");
583 VerifyMessage(key_blob_, message, signature, params);
584}
585
586string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
587 const AuthorizationSet& in_params,
588 AuthorizationSet* out_params) {
589 SCOPED_TRACE("EncryptMessage");
590 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
591}
592
593string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
594 AuthorizationSet* out_params) {
595 SCOPED_TRACE("EncryptMessage");
596 return EncryptMessage(key_blob_, message, params, out_params);
597}
598
599string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
600 SCOPED_TRACE("EncryptMessage");
601 AuthorizationSet out_params;
602 string ciphertext = EncryptMessage(message, params, &out_params);
603 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
604 return ciphertext;
605}
606
607string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
608 PaddingMode padding) {
609 SCOPED_TRACE("EncryptMessage");
610 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
611 AuthorizationSet out_params;
612 string ciphertext = EncryptMessage(message, params, &out_params);
613 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
614 return ciphertext;
615}
616
617string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
618 PaddingMode padding, vector<uint8_t>* iv_out) {
619 SCOPED_TRACE("EncryptMessage");
620 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
621 AuthorizationSet out_params;
622 string ciphertext = EncryptMessage(message, params, &out_params);
623 EXPECT_EQ(1U, out_params.size());
624 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800625 EXPECT_TRUE(ivVal);
626 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700627 return ciphertext;
628}
629
630string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
631 PaddingMode padding, const vector<uint8_t>& iv_in) {
632 SCOPED_TRACE("EncryptMessage");
633 auto params = AuthorizationSetBuilder()
634 .BlockMode(block_mode)
635 .Padding(padding)
636 .Authorization(TAG_NONCE, iv_in);
637 AuthorizationSet out_params;
638 string ciphertext = EncryptMessage(message, params, &out_params);
639 return ciphertext;
640}
641
642string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
643 PaddingMode padding, uint8_t mac_length_bits,
644 const vector<uint8_t>& iv_in) {
645 SCOPED_TRACE("EncryptMessage");
646 auto params = AuthorizationSetBuilder()
647 .BlockMode(block_mode)
648 .Padding(padding)
649 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
650 .Authorization(TAG_NONCE, iv_in);
651 AuthorizationSet out_params;
652 string ciphertext = EncryptMessage(message, params, &out_params);
653 return ciphertext;
654}
655
656string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
657 const string& ciphertext,
658 const AuthorizationSet& params) {
659 SCOPED_TRACE("DecryptMessage");
660 AuthorizationSet out_params;
661 string plaintext =
662 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
663 EXPECT_TRUE(out_params.empty());
664 return plaintext;
665}
666
667string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
668 const AuthorizationSet& params) {
669 SCOPED_TRACE("DecryptMessage");
670 return DecryptMessage(key_blob_, ciphertext, params);
671}
672
673string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
674 PaddingMode padding_mode, const vector<uint8_t>& iv) {
675 SCOPED_TRACE("DecryptMessage");
676 auto params = AuthorizationSetBuilder()
677 .BlockMode(block_mode)
678 .Padding(padding_mode)
679 .Authorization(TAG_NONCE, iv);
680 return DecryptMessage(key_blob_, ciphertext, params);
681}
682
683std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
684 const vector<uint8_t>& key_blob) {
685 std::pair<ErrorCode, vector<uint8_t>> retval;
686 vector<uint8_t> outKeyBlob;
687 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
688 ErrorCode errorcode = GetReturnErrorCode(result);
689 retval = std::tie(errorcode, outKeyBlob);
690
691 return retval;
692}
693vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
694 switch (algorithm) {
695 case Algorithm::RSA:
696 switch (SecLevel()) {
697 case SecurityLevel::SOFTWARE:
698 case SecurityLevel::TRUSTED_ENVIRONMENT:
699 return {2048, 3072, 4096};
700 case SecurityLevel::STRONGBOX:
701 return {2048};
702 default:
703 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
704 break;
705 }
706 break;
707 case Algorithm::EC:
708 switch (SecLevel()) {
709 case SecurityLevel::SOFTWARE:
710 case SecurityLevel::TRUSTED_ENVIRONMENT:
711 return {224, 256, 384, 521};
712 case SecurityLevel::STRONGBOX:
713 return {256};
714 default:
715 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
716 break;
717 }
718 break;
719 case Algorithm::AES:
720 return {128, 256};
721 case Algorithm::TRIPLE_DES:
722 return {168};
723 case Algorithm::HMAC: {
724 vector<uint32_t> retval((512 - 64) / 8 + 1);
725 uint32_t size = 64 - 8;
726 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
727 return retval;
728 }
729 default:
730 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
731 return {};
732 }
733 ADD_FAILURE() << "Should be impossible to get here";
734 return {};
735}
736
737vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
738 if (SecLevel() == SecurityLevel::STRONGBOX) {
739 switch (algorithm) {
740 case Algorithm::RSA:
741 return {3072, 4096};
742 case Algorithm::EC:
743 return {224, 384, 521};
744 case Algorithm::AES:
745 return {192};
746 default:
747 return {};
748 }
749 }
750 return {};
751}
752
753vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
754 if (securityLevel_ == SecurityLevel::STRONGBOX) {
755 return {EcCurve::P_256};
756 } else {
757 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
758 }
759}
760
761vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
762 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
763 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
764 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
765}
766
767vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
768 switch (SecLevel()) {
769 case SecurityLevel::SOFTWARE:
770 case SecurityLevel::TRUSTED_ENVIRONMENT:
771 if (withNone) {
772 if (withMD5)
773 return {Digest::NONE, Digest::MD5, Digest::SHA1,
774 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
775 Digest::SHA_2_512};
776 else
777 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
778 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
779 } else {
780 if (withMD5)
781 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
782 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
783 else
784 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
785 Digest::SHA_2_512};
786 }
787 break;
788 case SecurityLevel::STRONGBOX:
789 if (withNone)
790 return {Digest::NONE, Digest::SHA_2_256};
791 else
792 return {Digest::SHA_2_256};
793 break;
794 default:
795 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
796 break;
797 }
798 ADD_FAILURE() << "Should be impossible to get here";
799 return {};
800}
801
Shawn Willden7f424372021-01-10 18:06:50 -0700802static const vector<KeyParameter> kEmptyAuthList{};
803
804const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
805 const vector<KeyCharacteristics>& key_characteristics) {
806 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
807 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
808 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
809}
810
Qi Wubeefae42021-01-28 23:16:37 +0800811const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
812 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
813 auto found = std::find_if(
814 key_characteristics.begin(), key_characteristics.end(),
815 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700816 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
817}
818
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000819ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700820 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000821 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
822 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
823 return result;
824}
825
826ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700827 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000828 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
829 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
830 return result;
831}
832
833ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
834 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -0700835 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000836 rsaKeyBlob, KeyPurpose::SIGN, message,
837 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
838 return result;
839}
840
841ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700842 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
843 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000844 return result;
845}
846
Selene Huang6e46f142021-04-20 19:20:11 -0700847void verify_serial(X509* cert, const uint64_t expected_serial) {
848 BIGNUM_Ptr ser(BN_new());
849 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
850
851 uint64_t serial;
852 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
853 EXPECT_EQ(serial, expected_serial);
854}
855
856// Please set self_signed to true for fake certificates or self signed
857// certificates
858void verify_subject(const X509* cert, //
859 const string& subject, //
860 bool self_signed) {
861 char* cert_issuer = //
862 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
863
864 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
865
866 string expected_subject("/CN=");
867 if (subject.empty()) {
868 expected_subject.append("Android Keystore Key");
869 } else {
870 expected_subject.append(subject);
871 }
872
873 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
874
875 if (self_signed) {
876 EXPECT_STREQ(cert_issuer, cert_subj)
877 << "Cert issuer and subject mismatch for self signed certificate.";
878 }
879
880 OPENSSL_free(cert_subj);
881 OPENSSL_free(cert_issuer);
882}
883
884vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
885 BIGNUM_Ptr serial(BN_new());
886 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
887
888 int len = BN_num_bytes(serial.get());
889 vector<uint8_t> serial_blob(len);
890 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
891 return {};
892 }
893
894 return serial_blob;
895}
896
897void verify_subject_and_serial(const Certificate& certificate, //
898 const uint64_t expected_serial, //
899 const string& subject, bool self_signed) {
900 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
901 ASSERT_TRUE(!!cert.get());
902
903 verify_serial(cert.get(), expected_serial);
904 verify_subject(cert.get(), subject, self_signed);
905}
906
Shawn Willden7c130392020-12-21 09:58:22 -0700907bool verify_attestation_record(const string& challenge, //
908 const string& app_id, //
909 AuthorizationSet expected_sw_enforced, //
910 AuthorizationSet expected_hw_enforced, //
911 SecurityLevel security_level,
912 const vector<uint8_t>& attestation_cert) {
913 X509_Ptr cert(parse_cert_blob(attestation_cert));
914 EXPECT_TRUE(!!cert.get());
915 if (!cert.get()) return false;
916
917 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
918 EXPECT_TRUE(!!attest_rec);
919 if (!attest_rec) return false;
920
921 AuthorizationSet att_sw_enforced;
922 AuthorizationSet att_hw_enforced;
923 uint32_t att_attestation_version;
924 uint32_t att_keymaster_version;
925 SecurityLevel att_attestation_security_level;
926 SecurityLevel att_keymaster_security_level;
927 vector<uint8_t> att_challenge;
928 vector<uint8_t> att_unique_id;
929 vector<uint8_t> att_app_id;
930
931 auto error = parse_attestation_record(attest_rec->data, //
932 attest_rec->length, //
933 &att_attestation_version, //
934 &att_attestation_security_level, //
935 &att_keymaster_version, //
936 &att_keymaster_security_level, //
937 &att_challenge, //
938 &att_sw_enforced, //
939 &att_hw_enforced, //
940 &att_unique_id);
941 EXPECT_EQ(ErrorCode::OK, error);
942 if (error != ErrorCode::OK) return false;
943
Shawn Willden3cb64a62021-04-05 14:39:05 -0600944 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -0700945 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -0700946
Selene Huang4f64c222021-04-13 19:54:36 -0700947 // check challenge and app id only if we expects a non-fake certificate
948 if (challenge.length() > 0) {
949 EXPECT_EQ(challenge.length(), att_challenge.size());
950 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
951
952 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
953 }
Shawn Willden7c130392020-12-21 09:58:22 -0700954
Shawn Willden3cb64a62021-04-05 14:39:05 -0600955 EXPECT_EQ(att_keymaster_version, 100U);
Shawn Willden7c130392020-12-21 09:58:22 -0700956 EXPECT_EQ(security_level, att_keymaster_security_level);
957 EXPECT_EQ(security_level, att_attestation_security_level);
958
Shawn Willden7c130392020-12-21 09:58:22 -0700959
960 char property_value[PROPERTY_VALUE_MAX] = {};
961 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
962 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
963 // for the BOOT_PATCH_LEVEL.
964 if (avb_verification_enabled()) {
965 for (int i = 0; i < att_hw_enforced.size(); i++) {
966 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
967 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
968 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +0800969 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -0700970 // strptime seems to require delimiters, but the tag value will
971 // be YYYYMMDD
972 date.insert(6, "-");
973 date.insert(4, "-");
974 EXPECT_EQ(date.size(), 10);
975 struct tm time;
976 strptime(date.c_str(), "%Y-%m-%d", &time);
977
978 // Day of the month (0-31)
979 EXPECT_GE(time.tm_mday, 0);
980 EXPECT_LT(time.tm_mday, 32);
981 // Months since Jan (0-11)
982 EXPECT_GE(time.tm_mon, 0);
983 EXPECT_LT(time.tm_mon, 12);
984 // Years since 1900
985 EXPECT_GT(time.tm_year, 110);
986 EXPECT_LT(time.tm_year, 200);
987 }
988 }
989 }
990
991 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
992 // indicates true. A provided boolean tag that can be pulled back out of the certificate
993 // indicates correct encoding. No need to check if it's in both lists, since the
994 // AuthorizationSet compare below will handle mismatches of tags.
995 if (security_level == SecurityLevel::SOFTWARE) {
996 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
997 } else {
998 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
999 }
1000
1001 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
1002 // the authorization list during key generation) isn't being attested to in the certificate.
1003 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1004 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1005 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1006 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1007
1008 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1009 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1010 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1011 att_hw_enforced.Contains(TAG_KEY_SIZE));
1012 }
1013
1014 // Test root of trust elements
1015 vector<uint8_t> verified_boot_key;
1016 VerifiedBoot verified_boot_state;
1017 bool device_locked;
1018 vector<uint8_t> verified_boot_hash;
1019 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1020 &verified_boot_state, &device_locked, &verified_boot_hash);
1021 EXPECT_EQ(ErrorCode::OK, error);
1022
1023 if (avb_verification_enabled()) {
1024 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1025 string prop_string(property_value);
1026 EXPECT_EQ(prop_string.size(), 64);
1027 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1028
1029 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1030 if (!strcmp(property_value, "unlocked")) {
1031 EXPECT_FALSE(device_locked);
1032 } else {
1033 EXPECT_TRUE(device_locked);
1034 }
1035
1036 // Check that the device is locked if not debuggable, e.g., user build
1037 // images in CTS. For VTS, debuggable images are used to allow adb root
1038 // and the device is unlocked.
1039 if (!property_get_bool("ro.debuggable", false)) {
1040 EXPECT_TRUE(device_locked);
1041 } else {
1042 EXPECT_FALSE(device_locked);
1043 }
1044 }
1045
1046 // Verified boot key should be all 0's if the boot state is not verified or self signed
1047 std::string empty_boot_key(32, '\0');
1048 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1049 verified_boot_key.size());
1050 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1051 if (!strcmp(property_value, "green")) {
1052 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1053 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1054 verified_boot_key.size()));
1055 } else if (!strcmp(property_value, "yellow")) {
1056 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1057 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1058 verified_boot_key.size()));
1059 } else if (!strcmp(property_value, "orange")) {
1060 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1061 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1062 verified_boot_key.size()));
1063 } else if (!strcmp(property_value, "red")) {
1064 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1065 } else {
1066 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1067 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1068 verified_boot_key.size()));
1069 }
1070
1071 att_sw_enforced.Sort();
1072 expected_sw_enforced.Sort();
1073 auto a = filtered_tags(expected_sw_enforced);
1074 auto b = filtered_tags(att_sw_enforced);
1075 EXPECT_EQ(a, b);
1076
1077 att_hw_enforced.Sort();
1078 expected_hw_enforced.Sort();
1079 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1080
1081 return true;
1082}
1083
1084string bin2hex(const vector<uint8_t>& data) {
1085 string retval;
1086 retval.reserve(data.size() * 2 + 1);
1087 for (uint8_t byte : data) {
1088 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1089 retval.push_back(nibble2hex[0x0F & byte]);
1090 }
1091 return retval;
1092}
1093
David Drysdalef0d516d2021-03-22 07:51:43 +00001094AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1095 AuthorizationSet authList;
1096 for (auto& entry : key_characteristics) {
1097 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1098 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1099 authList.push_back(AuthorizationSet(entry.authorizations));
1100 }
1101 }
1102 return authList;
1103}
1104
1105AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1106 AuthorizationSet authList;
1107 for (auto& entry : key_characteristics) {
1108 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1109 entry.securityLevel == SecurityLevel::KEYSTORE) {
1110 authList.push_back(AuthorizationSet(entry.authorizations));
1111 }
1112 }
1113 return authList;
1114}
1115
Shawn Willden7c130392020-12-21 09:58:22 -07001116AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1117 std::stringstream cert_data;
1118
1119 for (size_t i = 0; i < chain.size(); ++i) {
1120 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1121
1122 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1123 X509_Ptr signing_cert;
1124 if (i < chain.size() - 1) {
1125 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1126 } else {
1127 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1128 }
1129 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1130
1131 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1132 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1133
1134 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1135 return AssertionFailure()
1136 << "Verification of certificate " << i << " failed "
1137 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1138 << cert_data.str();
1139 }
1140
1141 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1142 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1143 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001144 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1145 << " Signer subject is " << signer_subj
1146 << " Issuer subject is " << cert_issuer << endl
1147 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001148 }
Shawn Willden7c130392020-12-21 09:58:22 -07001149 }
1150
1151 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1152 return AssertionSuccess();
1153}
1154
1155X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1156 const uint8_t* p = blob.data();
1157 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1158}
1159
David Drysdalef0d516d2021-03-22 07:51:43 +00001160vector<uint8_t> make_name_from_str(const string& name) {
1161 X509_NAME_Ptr x509_name(X509_NAME_new());
1162 EXPECT_TRUE(x509_name.get() != nullptr);
1163 if (!x509_name) return {};
1164
1165 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1166 "CN", //
1167 MBSTRING_ASC,
1168 reinterpret_cast<const uint8_t*>(name.c_str()),
1169 -1, // len
1170 -1, // loc
1171 0 /* set */));
1172
1173 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1174 EXPECT_GT(len, 0);
1175
1176 vector<uint8_t> retval(len);
1177 uint8_t* p = retval.data();
1178 i2d_X509_NAME(x509_name.get(), &p);
1179
1180 return retval;
1181}
1182
David Drysdale4dc01072021-04-01 12:17:35 +01001183namespace {
1184
1185void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1186 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1187 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1188
1189 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1190 if (testMode) {
1191 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1192 MatchesRegex("{\n"
1193 " 1 : 2,\n" // kty: EC2
1194 " 3 : -7,\n" // alg: ES256
1195 " -1 : 1,\n" // EC id: P256
1196 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1197 // sequence of 32 hexadecimal bytes, enclosed in braces and
1198 // separated by commas. In this case, some Ed25519 public key.
1199 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1200 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1201 " -70000 : null,\n" // test marker
1202 "}"));
1203 } else {
1204 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1205 MatchesRegex("{\n"
1206 " 1 : 2,\n" // kty: EC2
1207 " 3 : -7,\n" // alg: ES256
1208 " -1 : 1,\n" // EC id: P256
1209 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1210 // sequence of 32 hexadecimal bytes, enclosed in braces and
1211 // separated by commas. In this case, some Ed25519 public key.
1212 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1213 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1214 "}"));
1215 }
1216}
1217
1218} // namespace
1219
1220void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1221 vector<uint8_t>* payload_value) {
1222 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1223 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1224
1225 ASSERT_NE(coseMac0->asArray(), nullptr);
1226 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1227
1228 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1229 ASSERT_NE(protParms, nullptr);
1230
1231 // Header label:value of 'alg': HMAC-256
1232 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1233
1234 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1235 ASSERT_NE(unprotParms, nullptr);
1236 ASSERT_EQ(unprotParms->size(), 0);
1237
1238 // The payload is a bstr holding an encoded COSE_Key
1239 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1240 ASSERT_NE(payload, nullptr);
1241 check_cose_key(payload->value(), testMode);
1242
1243 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1244 ASSERT_TRUE(coseMac0Tag);
1245 auto extractedTag = coseMac0Tag->value();
1246 EXPECT_EQ(extractedTag.size(), 32U);
1247
1248 // Compare with tag generated with kTestMacKey. Should only match in test mode
1249 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
1250 payload->value());
1251 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1252
1253 if (testMode) {
1254 EXPECT_EQ(*testTag, extractedTag);
1255 } else {
1256 EXPECT_NE(*testTag, extractedTag);
1257 }
1258 if (payload_value != nullptr) {
1259 *payload_value = payload->value();
1260 }
1261}
1262
1263void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1264 // Extract x and y affine coordinates from the encoded Cose_Key.
1265 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1266 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1267 auto coseKey = parsedPayload->asMap();
1268 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1269 ASSERT_NE(xItem->asBstr(), nullptr);
1270 vector<uint8_t> x = xItem->asBstr()->value();
1271 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1272 ASSERT_NE(yItem->asBstr(), nullptr);
1273 vector<uint8_t> y = yItem->asBstr()->value();
1274
1275 // Concatenate: 0x04 (uncompressed form marker) | x | y
1276 vector<uint8_t> pubKeyData{0x04};
1277 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1278 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1279
1280 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1281 ASSERT_NE(ecKey, nullptr);
1282 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1283 ASSERT_NE(group, nullptr);
1284 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1285 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1286 ASSERT_NE(point, nullptr);
1287 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1288 nullptr),
1289 1);
1290 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1291
1292 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1293 ASSERT_NE(pubKey, nullptr);
1294 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1295 *signingKey = std::move(pubKey);
1296}
1297
Selene Huang31ab4042020-04-29 04:22:39 -07001298} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001299
Janis Danisevskis24c04702020-12-16 18:28:39 -08001300} // namespace aidl::android::hardware::security::keymint