blob: 80bd057dfaa0a48b2dddd53d2a09b02df9f67993 [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};
David Drysdale7de9feb2021-03-05 14:56:19 +0000746 case Algorithm::TRIPLE_DES:
747 return {56};
748 default:
749 return {};
750 }
751 } else {
752 switch (algorithm) {
753 case Algorithm::TRIPLE_DES:
754 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -0700755 default:
756 return {};
757 }
758 }
759 return {};
760}
761
David Drysdale7de9feb2021-03-05 14:56:19 +0000762vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
763 switch (algorithm) {
764 case Algorithm::AES:
765 return {
766 BlockMode::CBC,
767 BlockMode::CTR,
768 BlockMode::ECB,
769 BlockMode::GCM,
770 };
771 case Algorithm::TRIPLE_DES:
772 return {
773 BlockMode::CBC,
774 BlockMode::ECB,
775 };
776 default:
777 return {};
778 }
779}
780
781vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
782 BlockMode blockMode) {
783 switch (algorithm) {
784 case Algorithm::AES:
785 switch (blockMode) {
786 case BlockMode::CBC:
787 case BlockMode::ECB:
788 return {PaddingMode::NONE, PaddingMode::PKCS7};
789 case BlockMode::CTR:
790 case BlockMode::GCM:
791 return {PaddingMode::NONE};
792 default:
793 return {};
794 };
795 case Algorithm::TRIPLE_DES:
796 switch (blockMode) {
797 case BlockMode::CBC:
798 case BlockMode::ECB:
799 return {PaddingMode::NONE, PaddingMode::PKCS7};
800 default:
801 return {};
802 };
803 default:
804 return {};
805 }
806}
807
808vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
809 BlockMode blockMode) {
810 switch (algorithm) {
811 case Algorithm::AES:
812 switch (blockMode) {
813 case BlockMode::CTR:
814 case BlockMode::GCM:
815 return {PaddingMode::PKCS7};
816 default:
817 return {};
818 };
819 default:
820 return {};
821 }
822}
823
Selene Huang31ab4042020-04-29 04:22:39 -0700824vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
825 if (securityLevel_ == SecurityLevel::STRONGBOX) {
826 return {EcCurve::P_256};
827 } else {
828 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
829 }
830}
831
832vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
833 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
834 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
835 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
836}
837
838vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
839 switch (SecLevel()) {
840 case SecurityLevel::SOFTWARE:
841 case SecurityLevel::TRUSTED_ENVIRONMENT:
842 if (withNone) {
843 if (withMD5)
844 return {Digest::NONE, Digest::MD5, Digest::SHA1,
845 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
846 Digest::SHA_2_512};
847 else
848 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
849 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
850 } else {
851 if (withMD5)
852 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
853 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
854 else
855 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
856 Digest::SHA_2_512};
857 }
858 break;
859 case SecurityLevel::STRONGBOX:
860 if (withNone)
861 return {Digest::NONE, Digest::SHA_2_256};
862 else
863 return {Digest::SHA_2_256};
864 break;
865 default:
866 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
867 break;
868 }
869 ADD_FAILURE() << "Should be impossible to get here";
870 return {};
871}
872
Shawn Willden7f424372021-01-10 18:06:50 -0700873static const vector<KeyParameter> kEmptyAuthList{};
874
875const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
876 const vector<KeyCharacteristics>& key_characteristics) {
877 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
878 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
879 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
880}
881
Qi Wubeefae42021-01-28 23:16:37 +0800882const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
883 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
884 auto found = std::find_if(
885 key_characteristics.begin(), key_characteristics.end(),
886 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700887 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
888}
889
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000890ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700891 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000892 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
893 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
894 return result;
895}
896
897ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700898 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000899 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
900 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
901 return result;
902}
903
904ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
905 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -0700906 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000907 rsaKeyBlob, KeyPurpose::SIGN, message,
908 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
909 return result;
910}
911
912ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700913 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
914 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000915 return result;
916}
917
Selene Huang6e46f142021-04-20 19:20:11 -0700918void verify_serial(X509* cert, const uint64_t expected_serial) {
919 BIGNUM_Ptr ser(BN_new());
920 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
921
922 uint64_t serial;
923 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
924 EXPECT_EQ(serial, expected_serial);
925}
926
927// Please set self_signed to true for fake certificates or self signed
928// certificates
929void verify_subject(const X509* cert, //
930 const string& subject, //
931 bool self_signed) {
932 char* cert_issuer = //
933 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
934
935 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
936
937 string expected_subject("/CN=");
938 if (subject.empty()) {
939 expected_subject.append("Android Keystore Key");
940 } else {
941 expected_subject.append(subject);
942 }
943
944 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
945
946 if (self_signed) {
947 EXPECT_STREQ(cert_issuer, cert_subj)
948 << "Cert issuer and subject mismatch for self signed certificate.";
949 }
950
951 OPENSSL_free(cert_subj);
952 OPENSSL_free(cert_issuer);
953}
954
955vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
956 BIGNUM_Ptr serial(BN_new());
957 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
958
959 int len = BN_num_bytes(serial.get());
960 vector<uint8_t> serial_blob(len);
961 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
962 return {};
963 }
964
965 return serial_blob;
966}
967
968void verify_subject_and_serial(const Certificate& certificate, //
969 const uint64_t expected_serial, //
970 const string& subject, bool self_signed) {
971 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
972 ASSERT_TRUE(!!cert.get());
973
974 verify_serial(cert.get(), expected_serial);
975 verify_subject(cert.get(), subject, self_signed);
976}
977
Shawn Willden7c130392020-12-21 09:58:22 -0700978bool verify_attestation_record(const string& challenge, //
979 const string& app_id, //
980 AuthorizationSet expected_sw_enforced, //
981 AuthorizationSet expected_hw_enforced, //
982 SecurityLevel security_level,
983 const vector<uint8_t>& attestation_cert) {
984 X509_Ptr cert(parse_cert_blob(attestation_cert));
985 EXPECT_TRUE(!!cert.get());
986 if (!cert.get()) return false;
987
988 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
989 EXPECT_TRUE(!!attest_rec);
990 if (!attest_rec) return false;
991
992 AuthorizationSet att_sw_enforced;
993 AuthorizationSet att_hw_enforced;
994 uint32_t att_attestation_version;
995 uint32_t att_keymaster_version;
996 SecurityLevel att_attestation_security_level;
997 SecurityLevel att_keymaster_security_level;
998 vector<uint8_t> att_challenge;
999 vector<uint8_t> att_unique_id;
1000 vector<uint8_t> att_app_id;
1001
1002 auto error = parse_attestation_record(attest_rec->data, //
1003 attest_rec->length, //
1004 &att_attestation_version, //
1005 &att_attestation_security_level, //
1006 &att_keymaster_version, //
1007 &att_keymaster_security_level, //
1008 &att_challenge, //
1009 &att_sw_enforced, //
1010 &att_hw_enforced, //
1011 &att_unique_id);
1012 EXPECT_EQ(ErrorCode::OK, error);
1013 if (error != ErrorCode::OK) return false;
1014
Shawn Willden3cb64a62021-04-05 14:39:05 -06001015 EXPECT_EQ(att_attestation_version, 100U);
Selene Huang4f64c222021-04-13 19:54:36 -07001016 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001017
Selene Huang4f64c222021-04-13 19:54:36 -07001018 // check challenge and app id only if we expects a non-fake certificate
1019 if (challenge.length() > 0) {
1020 EXPECT_EQ(challenge.length(), att_challenge.size());
1021 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1022
1023 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1024 }
Shawn Willden7c130392020-12-21 09:58:22 -07001025
Shawn Willden3cb64a62021-04-05 14:39:05 -06001026 EXPECT_EQ(att_keymaster_version, 100U);
Shawn Willden7c130392020-12-21 09:58:22 -07001027 EXPECT_EQ(security_level, att_keymaster_security_level);
1028 EXPECT_EQ(security_level, att_attestation_security_level);
1029
Shawn Willden7c130392020-12-21 09:58:22 -07001030
1031 char property_value[PROPERTY_VALUE_MAX] = {};
1032 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
1033 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
1034 // for the BOOT_PATCH_LEVEL.
1035 if (avb_verification_enabled()) {
1036 for (int i = 0; i < att_hw_enforced.size(); i++) {
1037 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1038 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1039 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001040 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -07001041 // strptime seems to require delimiters, but the tag value will
1042 // be YYYYMMDD
1043 date.insert(6, "-");
1044 date.insert(4, "-");
1045 EXPECT_EQ(date.size(), 10);
1046 struct tm time;
1047 strptime(date.c_str(), "%Y-%m-%d", &time);
1048
1049 // Day of the month (0-31)
1050 EXPECT_GE(time.tm_mday, 0);
1051 EXPECT_LT(time.tm_mday, 32);
1052 // Months since Jan (0-11)
1053 EXPECT_GE(time.tm_mon, 0);
1054 EXPECT_LT(time.tm_mon, 12);
1055 // Years since 1900
1056 EXPECT_GT(time.tm_year, 110);
1057 EXPECT_LT(time.tm_year, 200);
1058 }
1059 }
1060 }
1061
1062 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1063 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1064 // indicates correct encoding. No need to check if it's in both lists, since the
1065 // AuthorizationSet compare below will handle mismatches of tags.
1066 if (security_level == SecurityLevel::SOFTWARE) {
1067 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1068 } else {
1069 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1070 }
1071
1072 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
1073 // the authorization list during key generation) isn't being attested to in the certificate.
1074 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1075 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1076 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1077 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
1078
1079 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1080 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1081 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1082 att_hw_enforced.Contains(TAG_KEY_SIZE));
1083 }
1084
1085 // Test root of trust elements
1086 vector<uint8_t> verified_boot_key;
1087 VerifiedBoot verified_boot_state;
1088 bool device_locked;
1089 vector<uint8_t> verified_boot_hash;
1090 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1091 &verified_boot_state, &device_locked, &verified_boot_hash);
1092 EXPECT_EQ(ErrorCode::OK, error);
1093
1094 if (avb_verification_enabled()) {
1095 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1096 string prop_string(property_value);
1097 EXPECT_EQ(prop_string.size(), 64);
1098 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1099
1100 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1101 if (!strcmp(property_value, "unlocked")) {
1102 EXPECT_FALSE(device_locked);
1103 } else {
1104 EXPECT_TRUE(device_locked);
1105 }
1106
1107 // Check that the device is locked if not debuggable, e.g., user build
1108 // images in CTS. For VTS, debuggable images are used to allow adb root
1109 // and the device is unlocked.
1110 if (!property_get_bool("ro.debuggable", false)) {
1111 EXPECT_TRUE(device_locked);
1112 } else {
1113 EXPECT_FALSE(device_locked);
1114 }
1115 }
1116
1117 // Verified boot key should be all 0's if the boot state is not verified or self signed
1118 std::string empty_boot_key(32, '\0');
1119 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1120 verified_boot_key.size());
1121 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1122 if (!strcmp(property_value, "green")) {
1123 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1124 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1125 verified_boot_key.size()));
1126 } else if (!strcmp(property_value, "yellow")) {
1127 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1128 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1129 verified_boot_key.size()));
1130 } else if (!strcmp(property_value, "orange")) {
1131 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1132 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1133 verified_boot_key.size()));
1134 } else if (!strcmp(property_value, "red")) {
1135 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1136 } else {
1137 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1138 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1139 verified_boot_key.size()));
1140 }
1141
1142 att_sw_enforced.Sort();
1143 expected_sw_enforced.Sort();
1144 auto a = filtered_tags(expected_sw_enforced);
1145 auto b = filtered_tags(att_sw_enforced);
1146 EXPECT_EQ(a, b);
1147
1148 att_hw_enforced.Sort();
1149 expected_hw_enforced.Sort();
1150 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1151
1152 return true;
1153}
1154
1155string bin2hex(const vector<uint8_t>& data) {
1156 string retval;
1157 retval.reserve(data.size() * 2 + 1);
1158 for (uint8_t byte : data) {
1159 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1160 retval.push_back(nibble2hex[0x0F & byte]);
1161 }
1162 return retval;
1163}
1164
David Drysdalef0d516d2021-03-22 07:51:43 +00001165AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1166 AuthorizationSet authList;
1167 for (auto& entry : key_characteristics) {
1168 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1169 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1170 authList.push_back(AuthorizationSet(entry.authorizations));
1171 }
1172 }
1173 return authList;
1174}
1175
1176AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1177 AuthorizationSet authList;
1178 for (auto& entry : key_characteristics) {
1179 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1180 entry.securityLevel == SecurityLevel::KEYSTORE) {
1181 authList.push_back(AuthorizationSet(entry.authorizations));
1182 }
1183 }
1184 return authList;
1185}
1186
Shawn Willden7c130392020-12-21 09:58:22 -07001187AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1188 std::stringstream cert_data;
1189
1190 for (size_t i = 0; i < chain.size(); ++i) {
1191 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1192
1193 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1194 X509_Ptr signing_cert;
1195 if (i < chain.size() - 1) {
1196 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1197 } else {
1198 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1199 }
1200 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1201
1202 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1203 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1204
1205 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1206 return AssertionFailure()
1207 << "Verification of certificate " << i << " failed "
1208 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1209 << cert_data.str();
1210 }
1211
1212 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1213 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1214 if (cert_issuer != signer_subj) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001215 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1216 << " Signer subject is " << signer_subj
1217 << " Issuer subject is " << cert_issuer << endl
1218 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001219 }
Shawn Willden7c130392020-12-21 09:58:22 -07001220 }
1221
1222 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1223 return AssertionSuccess();
1224}
1225
1226X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1227 const uint8_t* p = blob.data();
1228 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1229}
1230
David Drysdalef0d516d2021-03-22 07:51:43 +00001231vector<uint8_t> make_name_from_str(const string& name) {
1232 X509_NAME_Ptr x509_name(X509_NAME_new());
1233 EXPECT_TRUE(x509_name.get() != nullptr);
1234 if (!x509_name) return {};
1235
1236 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1237 "CN", //
1238 MBSTRING_ASC,
1239 reinterpret_cast<const uint8_t*>(name.c_str()),
1240 -1, // len
1241 -1, // loc
1242 0 /* set */));
1243
1244 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1245 EXPECT_GT(len, 0);
1246
1247 vector<uint8_t> retval(len);
1248 uint8_t* p = retval.data();
1249 i2d_X509_NAME(x509_name.get(), &p);
1250
1251 return retval;
1252}
1253
David Drysdale4dc01072021-04-01 12:17:35 +01001254namespace {
1255
1256void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1257 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1258 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1259
1260 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1261 if (testMode) {
1262 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1263 MatchesRegex("{\n"
1264 " 1 : 2,\n" // kty: EC2
1265 " 3 : -7,\n" // alg: ES256
1266 " -1 : 1,\n" // EC id: P256
1267 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1268 // sequence of 32 hexadecimal bytes, enclosed in braces and
1269 // separated by commas. In this case, some Ed25519 public key.
1270 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1271 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1272 " -70000 : null,\n" // test marker
1273 "}"));
1274 } else {
1275 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1276 MatchesRegex("{\n"
1277 " 1 : 2,\n" // kty: EC2
1278 " 3 : -7,\n" // alg: ES256
1279 " -1 : 1,\n" // EC id: P256
1280 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1281 // sequence of 32 hexadecimal bytes, enclosed in braces and
1282 // separated by commas. In this case, some Ed25519 public key.
1283 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1284 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1285 "}"));
1286 }
1287}
1288
1289} // namespace
1290
1291void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1292 vector<uint8_t>* payload_value) {
1293 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1294 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1295
1296 ASSERT_NE(coseMac0->asArray(), nullptr);
1297 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1298
1299 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1300 ASSERT_NE(protParms, nullptr);
1301
1302 // Header label:value of 'alg': HMAC-256
1303 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1304
1305 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1306 ASSERT_NE(unprotParms, nullptr);
1307 ASSERT_EQ(unprotParms->size(), 0);
1308
1309 // The payload is a bstr holding an encoded COSE_Key
1310 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1311 ASSERT_NE(payload, nullptr);
1312 check_cose_key(payload->value(), testMode);
1313
1314 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1315 ASSERT_TRUE(coseMac0Tag);
1316 auto extractedTag = coseMac0Tag->value();
1317 EXPECT_EQ(extractedTag.size(), 32U);
1318
1319 // Compare with tag generated with kTestMacKey. Should only match in test mode
1320 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
1321 payload->value());
1322 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1323
1324 if (testMode) {
1325 EXPECT_EQ(*testTag, extractedTag);
1326 } else {
1327 EXPECT_NE(*testTag, extractedTag);
1328 }
1329 if (payload_value != nullptr) {
1330 *payload_value = payload->value();
1331 }
1332}
1333
1334void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1335 // Extract x and y affine coordinates from the encoded Cose_Key.
1336 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1337 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1338 auto coseKey = parsedPayload->asMap();
1339 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1340 ASSERT_NE(xItem->asBstr(), nullptr);
1341 vector<uint8_t> x = xItem->asBstr()->value();
1342 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1343 ASSERT_NE(yItem->asBstr(), nullptr);
1344 vector<uint8_t> y = yItem->asBstr()->value();
1345
1346 // Concatenate: 0x04 (uncompressed form marker) | x | y
1347 vector<uint8_t> pubKeyData{0x04};
1348 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1349 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1350
1351 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1352 ASSERT_NE(ecKey, nullptr);
1353 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1354 ASSERT_NE(group, nullptr);
1355 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1356 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1357 ASSERT_NE(point, nullptr);
1358 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1359 nullptr),
1360 1);
1361 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1362
1363 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1364 ASSERT_NE(pubKey, nullptr);
1365 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1366 *signingKey = std::move(pubKey);
1367}
1368
Selene Huang31ab4042020-04-29 04:22:39 -07001369} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001370
Janis Danisevskis24c04702020-12-16 18:28:39 -08001371} // namespace aidl::android::hardware::security::keymint