blob: 59cb57b75b021820151da3b265ba4541e06807d9 [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 = {
122 Tag::BLOB_USAGE_REQUIREMENTS, //
123 Tag::CREATION_DATETIME, //
124 Tag::EC_CURVE,
125 Tag::HARDWARE_TYPE,
126 Tag::INCLUDE_UNIQUE_ID,
127};
128
129AuthorizationSet filtered_tags(const AuthorizationSet& set) {
130 AuthorizationSet filtered;
131 std::remove_copy_if(
132 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
133 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
134 kTagsToFilter.end();
135 });
136 return filtered;
137}
138
139string x509NameToStr(X509_NAME* name) {
140 char* s = X509_NAME_oneline(name, nullptr, 0);
141 string retval(s);
142 OPENSSL_free(s);
143 return retval;
144}
145
Shawn Willden7f424372021-01-10 18:06:50 -0700146} // namespace
147
Shawn Willden7c130392020-12-21 09:58:22 -0700148bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
149bool KeyMintAidlTestBase::dump_Attestations = false;
150
Janis Danisevskis24c04702020-12-16 18:28:39 -0800151ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700152 if (result.isOk()) return ErrorCode::OK;
153
Janis Danisevskis24c04702020-12-16 18:28:39 -0800154 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
155 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700156 }
157
158 return ErrorCode::UNKNOWN_ERROR;
159}
160
Janis Danisevskis24c04702020-12-16 18:28:39 -0800161void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700162 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800163 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700164
165 KeyMintHardwareInfo info;
166 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
167
168 securityLevel_ = info.securityLevel;
169 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
170 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
171
172 os_version_ = getOsVersion();
173 os_patch_level_ = getOsPatchlevel();
174}
175
176void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800177 if (AServiceManager_isDeclared(GetParam().c_str())) {
178 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
179 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
180 } else {
181 InitializeKeyMint(nullptr);
182 }
Selene Huang31ab4042020-04-29 04:22:39 -0700183}
184
185ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700186 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700187 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700188 vector<KeyCharacteristics>* key_characteristics,
189 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700190 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
191 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700192 << "Previous characteristics not deleted before generating key. Test bug.";
193
Shawn Willden7f424372021-01-10 18:06:50 -0700194 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700195 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700196 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700197 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
198 creationResult.keyCharacteristics);
199 EXPECT_GT(creationResult.keyBlob.size(), 0);
200 *key_blob = std::move(creationResult.keyBlob);
201 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700202 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700203
204 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
205 EXPECT_TRUE(algorithm);
206 if (algorithm &&
207 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700208 EXPECT_GE(cert_chain->size(), 1);
209 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
210 if (attest_key) {
211 EXPECT_EQ(cert_chain->size(), 1);
212 } else {
213 EXPECT_GT(cert_chain->size(), 1);
214 }
215 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700216 } else {
217 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700218 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700219 }
Selene Huang31ab4042020-04-29 04:22:39 -0700220 }
221
222 return GetReturnErrorCode(result);
223}
224
Shawn Willden7c130392020-12-21 09:58:22 -0700225ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
226 const optional<AttestationKey>& attest_key) {
227 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700228}
229
230ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
231 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700232 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700233 Status result;
234
Shawn Willden7f424372021-01-10 18:06:50 -0700235 cert_chain_.clear();
236 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700237 key_blob->clear();
238
Shawn Willden7f424372021-01-10 18:06:50 -0700239 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700240 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700241 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700242 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700243
244 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700245 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
246 creationResult.keyCharacteristics);
247 EXPECT_GT(creationResult.keyBlob.size(), 0);
248
249 *key_blob = std::move(creationResult.keyBlob);
250 *key_characteristics = std::move(creationResult.keyCharacteristics);
251 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700252
253 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
254 EXPECT_TRUE(algorithm);
255 if (algorithm &&
256 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
257 EXPECT_GE(cert_chain_.size(), 1);
258 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
259 } else {
260 // For symmetric keys there should be no certificates.
261 EXPECT_EQ(cert_chain_.size(), 0);
262 }
Selene Huang31ab4042020-04-29 04:22:39 -0700263 }
264
265 return GetReturnErrorCode(result);
266}
267
268ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
269 const string& key_material) {
270 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
271}
272
273ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
274 const AuthorizationSet& wrapping_key_desc,
275 string masking_key,
276 const AuthorizationSet& unwrapping_params) {
Selene Huang31ab4042020-04-29 04:22:39 -0700277 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
278
Shawn Willden7f424372021-01-10 18:06:50 -0700279 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700280
Shawn Willden7f424372021-01-10 18:06:50 -0700281 KeyCreationResult creationResult;
282 Status result = keymint_->importWrappedKey(
283 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
284 vector<uint8_t>(masking_key.begin(), masking_key.end()),
285 unwrapping_params.vector_data(), 0 /* passwordSid */, 0 /* biometricSid */,
286 &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700287
288 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700289 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
290 creationResult.keyCharacteristics);
291 EXPECT_GT(creationResult.keyBlob.size(), 0);
292
293 key_blob_ = std::move(creationResult.keyBlob);
294 key_characteristics_ = std::move(creationResult.keyCharacteristics);
295 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700296
297 AuthorizationSet allAuths;
298 for (auto& entry : key_characteristics_) {
299 allAuths.push_back(AuthorizationSet(entry.authorizations));
300 }
301 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
302 EXPECT_TRUE(algorithm);
303 if (algorithm &&
304 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
305 EXPECT_GE(cert_chain_.size(), 1);
306 } else {
307 // For symmetric keys there should be no certificates.
308 EXPECT_EQ(cert_chain_.size(), 0);
309 }
Selene Huang31ab4042020-04-29 04:22:39 -0700310 }
311
312 return GetReturnErrorCode(result);
313}
314
315ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
316 Status result = keymint_->deleteKey(*key_blob);
317 if (!keep_key_blob) {
318 *key_blob = vector<uint8_t>();
319 }
320
Janis Danisevskis24c04702020-12-16 18:28:39 -0800321 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700322 return GetReturnErrorCode(result);
323}
324
325ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
326 return DeleteKey(&key_blob_, keep_key_blob);
327}
328
329ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
330 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800331 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700332 return GetReturnErrorCode(result);
333}
334
335void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
336 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
337 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
338}
339
340void KeyMintAidlTestBase::CheckedDeleteKey() {
341 CheckedDeleteKey(&key_blob_);
342}
343
344ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
345 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800346 AuthorizationSet* out_params,
347 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700348 SCOPED_TRACE("Begin");
349 Status result;
350 BeginResult out;
351 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
352
353 if (result.isOk()) {
354 *out_params = out.params;
355 challenge_ = out.challenge;
356 op = out.operation;
357 }
358
359 return GetReturnErrorCode(result);
360}
361
362ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
363 const AuthorizationSet& in_params,
364 AuthorizationSet* out_params) {
365 SCOPED_TRACE("Begin");
366 Status result;
367 BeginResult out;
368
369 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
370
371 if (result.isOk()) {
372 *out_params = out.params;
373 challenge_ = out.challenge;
374 op_ = out.operation;
375 }
376
377 return GetReturnErrorCode(result);
378}
379
380ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
381 AuthorizationSet* out_params) {
382 SCOPED_TRACE("Begin");
383 EXPECT_EQ(nullptr, op_);
384 return Begin(purpose, key_blob_, in_params, out_params);
385}
386
387ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
388 SCOPED_TRACE("Begin");
389 AuthorizationSet out_params;
390 ErrorCode result = Begin(purpose, in_params, &out_params);
391 EXPECT_TRUE(out_params.empty());
392 return result;
393}
394
Shawn Willden92d79c02021-02-19 07:31:55 -0700395ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
396 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
397 {} /* hardwareAuthToken */,
398 {} /* verificationToken */));
399}
400
401ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700402 SCOPED_TRACE("Update");
403
404 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700405 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700406
Shawn Willden92d79c02021-02-19 07:31:55 -0700407 std::vector<uint8_t> o_put;
408 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700409
Shawn Willden92d79c02021-02-19 07:31:55 -0700410 if (result.isOk()) output->append(o_put.begin(), o_put.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700411
412 return GetReturnErrorCode(result);
413}
414
Shawn Willden92d79c02021-02-19 07:31:55 -0700415ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700416 string* output) {
417 SCOPED_TRACE("Finish");
418 Status result;
419
420 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700421 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700422
423 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700424 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
425 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
426 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700427
Shawn Willden92d79c02021-02-19 07:31:55 -0700428 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700429
Shawn Willden92d79c02021-02-19 07:31:55 -0700430 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700431 return GetReturnErrorCode(result);
432}
433
Janis Danisevskis24c04702020-12-16 18:28:39 -0800434ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700435 SCOPED_TRACE("Abort");
436
437 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700438 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700439
440 Status retval = op->abort();
441 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800442 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700443}
444
445ErrorCode KeyMintAidlTestBase::Abort() {
446 SCOPED_TRACE("Abort");
447
448 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700449 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700450
451 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800452 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700453}
454
455void KeyMintAidlTestBase::AbortIfNeeded() {
456 SCOPED_TRACE("AbortIfNeeded");
457 if (op_) {
458 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800459 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700460 }
461}
462
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000463auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
464 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700465 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000466 AuthorizationSet begin_out_params;
467 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700468 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000469
470 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700471 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000472}
473
Selene Huang31ab4042020-04-29 04:22:39 -0700474string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
475 const string& message, const AuthorizationSet& in_params,
476 AuthorizationSet* out_params) {
477 SCOPED_TRACE("ProcessMessage");
478 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700479 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700480 EXPECT_EQ(ErrorCode::OK, result);
481 if (result != ErrorCode::OK) {
482 return "";
483 }
484
485 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700486 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700487 return output;
488}
489
490string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
491 const AuthorizationSet& params) {
492 SCOPED_TRACE("SignMessage");
493 AuthorizationSet out_params;
494 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
495 EXPECT_TRUE(out_params.empty());
496 return signature;
497}
498
499string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
500 SCOPED_TRACE("SignMessage");
501 return SignMessage(key_blob_, message, params);
502}
503
504string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
505 SCOPED_TRACE("MacMessage");
506 return SignMessage(
507 key_blob_, message,
508 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
509}
510
511void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
512 Digest digest, const string& expected_mac) {
513 SCOPED_TRACE("CheckHmacTestVector");
514 ASSERT_EQ(ErrorCode::OK,
515 ImportKey(AuthorizationSetBuilder()
516 .Authorization(TAG_NO_AUTH_REQUIRED)
517 .HmacKey(key.size() * 8)
518 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
519 .Digest(digest),
520 KeyFormat::RAW, key));
521 string signature = MacMessage(message, digest, expected_mac.size() * 8);
522 EXPECT_EQ(expected_mac, signature)
523 << "Test vector didn't match for key of size " << key.size() << " message of size "
524 << message.size() << " and digest " << digest;
525 CheckedDeleteKey();
526}
527
528void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
529 const string& message,
530 const string& expected_ciphertext) {
531 SCOPED_TRACE("CheckAesCtrTestVector");
532 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
533 .Authorization(TAG_NO_AUTH_REQUIRED)
534 .AesEncryptionKey(key.size() * 8)
535 .BlockMode(BlockMode::CTR)
536 .Authorization(TAG_CALLER_NONCE)
537 .Padding(PaddingMode::NONE),
538 KeyFormat::RAW, key));
539
540 auto params = AuthorizationSetBuilder()
541 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
542 .BlockMode(BlockMode::CTR)
543 .Padding(PaddingMode::NONE);
544 AuthorizationSet out_params;
545 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
546 EXPECT_EQ(expected_ciphertext, ciphertext);
547}
548
549void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
550 PaddingMode padding_mode, const string& key,
551 const string& iv, const string& input,
552 const string& expected_output) {
553 auto authset = AuthorizationSetBuilder()
554 .TripleDesEncryptionKey(key.size() * 7)
555 .BlockMode(block_mode)
556 .Authorization(TAG_NO_AUTH_REQUIRED)
557 .Padding(padding_mode);
558 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
559 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
560 ASSERT_GT(key_blob_.size(), 0U);
561
562 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
563 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
564 AuthorizationSet output_params;
565 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
566 EXPECT_EQ(expected_output, output);
567}
568
569void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
570 const string& signature, const AuthorizationSet& params) {
571 SCOPED_TRACE("VerifyMessage");
572 AuthorizationSet begin_out_params;
573 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
574
575 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700576 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700577 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700578 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700579}
580
581void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
582 const AuthorizationSet& params) {
583 SCOPED_TRACE("VerifyMessage");
584 VerifyMessage(key_blob_, message, signature, params);
585}
586
587string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
588 const AuthorizationSet& in_params,
589 AuthorizationSet* out_params) {
590 SCOPED_TRACE("EncryptMessage");
591 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
592}
593
594string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
595 AuthorizationSet* out_params) {
596 SCOPED_TRACE("EncryptMessage");
597 return EncryptMessage(key_blob_, message, params, out_params);
598}
599
600string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
601 SCOPED_TRACE("EncryptMessage");
602 AuthorizationSet out_params;
603 string ciphertext = EncryptMessage(message, params, &out_params);
604 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
605 return ciphertext;
606}
607
608string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
609 PaddingMode padding) {
610 SCOPED_TRACE("EncryptMessage");
611 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
612 AuthorizationSet out_params;
613 string ciphertext = EncryptMessage(message, params, &out_params);
614 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
615 return ciphertext;
616}
617
618string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
619 PaddingMode padding, vector<uint8_t>* iv_out) {
620 SCOPED_TRACE("EncryptMessage");
621 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
622 AuthorizationSet out_params;
623 string ciphertext = EncryptMessage(message, params, &out_params);
624 EXPECT_EQ(1U, out_params.size());
625 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800626 EXPECT_TRUE(ivVal);
627 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700628 return ciphertext;
629}
630
631string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
632 PaddingMode padding, const vector<uint8_t>& iv_in) {
633 SCOPED_TRACE("EncryptMessage");
634 auto params = AuthorizationSetBuilder()
635 .BlockMode(block_mode)
636 .Padding(padding)
637 .Authorization(TAG_NONCE, iv_in);
638 AuthorizationSet out_params;
639 string ciphertext = EncryptMessage(message, params, &out_params);
640 return ciphertext;
641}
642
643string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
644 PaddingMode padding, uint8_t mac_length_bits,
645 const vector<uint8_t>& iv_in) {
646 SCOPED_TRACE("EncryptMessage");
647 auto params = AuthorizationSetBuilder()
648 .BlockMode(block_mode)
649 .Padding(padding)
650 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
651 .Authorization(TAG_NONCE, iv_in);
652 AuthorizationSet out_params;
653 string ciphertext = EncryptMessage(message, params, &out_params);
654 return ciphertext;
655}
656
657string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
658 const string& ciphertext,
659 const AuthorizationSet& params) {
660 SCOPED_TRACE("DecryptMessage");
661 AuthorizationSet out_params;
662 string plaintext =
663 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
664 EXPECT_TRUE(out_params.empty());
665 return plaintext;
666}
667
668string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
669 const AuthorizationSet& params) {
670 SCOPED_TRACE("DecryptMessage");
671 return DecryptMessage(key_blob_, ciphertext, params);
672}
673
674string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
675 PaddingMode padding_mode, const vector<uint8_t>& iv) {
676 SCOPED_TRACE("DecryptMessage");
677 auto params = AuthorizationSetBuilder()
678 .BlockMode(block_mode)
679 .Padding(padding_mode)
680 .Authorization(TAG_NONCE, iv);
681 return DecryptMessage(key_blob_, ciphertext, params);
682}
683
684std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
685 const vector<uint8_t>& key_blob) {
686 std::pair<ErrorCode, vector<uint8_t>> retval;
687 vector<uint8_t> outKeyBlob;
688 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
689 ErrorCode errorcode = GetReturnErrorCode(result);
690 retval = std::tie(errorcode, outKeyBlob);
691
692 return retval;
693}
694vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
695 switch (algorithm) {
696 case Algorithm::RSA:
697 switch (SecLevel()) {
698 case SecurityLevel::SOFTWARE:
699 case SecurityLevel::TRUSTED_ENVIRONMENT:
700 return {2048, 3072, 4096};
701 case SecurityLevel::STRONGBOX:
702 return {2048};
703 default:
704 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
705 break;
706 }
707 break;
708 case Algorithm::EC:
709 switch (SecLevel()) {
710 case SecurityLevel::SOFTWARE:
711 case SecurityLevel::TRUSTED_ENVIRONMENT:
712 return {224, 256, 384, 521};
713 case SecurityLevel::STRONGBOX:
714 return {256};
715 default:
716 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
717 break;
718 }
719 break;
720 case Algorithm::AES:
721 return {128, 256};
722 case Algorithm::TRIPLE_DES:
723 return {168};
724 case Algorithm::HMAC: {
725 vector<uint32_t> retval((512 - 64) / 8 + 1);
726 uint32_t size = 64 - 8;
727 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
728 return retval;
729 }
730 default:
731 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
732 return {};
733 }
734 ADD_FAILURE() << "Should be impossible to get here";
735 return {};
736}
737
738vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
739 if (SecLevel() == SecurityLevel::STRONGBOX) {
740 switch (algorithm) {
741 case Algorithm::RSA:
742 return {3072, 4096};
743 case Algorithm::EC:
744 return {224, 384, 521};
745 case Algorithm::AES:
746 return {192};
747 default:
748 return {};
749 }
750 }
751 return {};
752}
753
754vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
755 if (securityLevel_ == SecurityLevel::STRONGBOX) {
756 return {EcCurve::P_256};
757 } else {
758 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
759 }
760}
761
762vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
763 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
764 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
765 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
766}
767
768vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
769 switch (SecLevel()) {
770 case SecurityLevel::SOFTWARE:
771 case SecurityLevel::TRUSTED_ENVIRONMENT:
772 if (withNone) {
773 if (withMD5)
774 return {Digest::NONE, Digest::MD5, Digest::SHA1,
775 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
776 Digest::SHA_2_512};
777 else
778 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
779 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
780 } else {
781 if (withMD5)
782 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
783 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
784 else
785 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
786 Digest::SHA_2_512};
787 }
788 break;
789 case SecurityLevel::STRONGBOX:
790 if (withNone)
791 return {Digest::NONE, Digest::SHA_2_256};
792 else
793 return {Digest::SHA_2_256};
794 break;
795 default:
796 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
797 break;
798 }
799 ADD_FAILURE() << "Should be impossible to get here";
800 return {};
801}
802
Shawn Willden7f424372021-01-10 18:06:50 -0700803static const vector<KeyParameter> kEmptyAuthList{};
804
805const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
806 const vector<KeyCharacteristics>& key_characteristics) {
807 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
808 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
809 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
810}
811
Qi Wubeefae42021-01-28 23:16:37 +0800812const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
813 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
814 auto found = std::find_if(
815 key_characteristics.begin(), key_characteristics.end(),
816 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700817 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
818}
819
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000820ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700821 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000822 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
823 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
824 return result;
825}
826
827ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700828 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000829 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
830 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
831 return result;
832}
833
834ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
835 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -0700836 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000837 rsaKeyBlob, KeyPurpose::SIGN, message,
838 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
839 return result;
840}
841
842ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -0700843 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
844 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000845 return result;
846}
847
Shawn Willden7c130392020-12-21 09:58:22 -0700848bool verify_attestation_record(const string& challenge, //
849 const string& app_id, //
850 AuthorizationSet expected_sw_enforced, //
851 AuthorizationSet expected_hw_enforced, //
852 SecurityLevel security_level,
853 const vector<uint8_t>& attestation_cert) {
854 X509_Ptr cert(parse_cert_blob(attestation_cert));
855 EXPECT_TRUE(!!cert.get());
856 if (!cert.get()) return false;
857
858 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
859 EXPECT_TRUE(!!attest_rec);
860 if (!attest_rec) return false;
861
862 AuthorizationSet att_sw_enforced;
863 AuthorizationSet att_hw_enforced;
864 uint32_t att_attestation_version;
865 uint32_t att_keymaster_version;
866 SecurityLevel att_attestation_security_level;
867 SecurityLevel att_keymaster_security_level;
868 vector<uint8_t> att_challenge;
869 vector<uint8_t> att_unique_id;
870 vector<uint8_t> att_app_id;
871
872 auto error = parse_attestation_record(attest_rec->data, //
873 attest_rec->length, //
874 &att_attestation_version, //
875 &att_attestation_security_level, //
876 &att_keymaster_version, //
877 &att_keymaster_security_level, //
878 &att_challenge, //
879 &att_sw_enforced, //
880 &att_hw_enforced, //
881 &att_unique_id);
882 EXPECT_EQ(ErrorCode::OK, error);
883 if (error != ErrorCode::OK) return false;
884
885 EXPECT_GE(att_attestation_version, 3U);
Selene Huang4f64c222021-04-13 19:54:36 -0700886 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -0700887
Selene Huang4f64c222021-04-13 19:54:36 -0700888 // check challenge and app id only if we expects a non-fake certificate
889 if (challenge.length() > 0) {
890 EXPECT_EQ(challenge.length(), att_challenge.size());
891 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
892
893 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
894 }
Shawn Willden7c130392020-12-21 09:58:22 -0700895
896 EXPECT_GE(att_keymaster_version, 4U);
897 EXPECT_EQ(security_level, att_keymaster_security_level);
898 EXPECT_EQ(security_level, att_attestation_security_level);
899
Shawn Willden7c130392020-12-21 09:58:22 -0700900
901 char property_value[PROPERTY_VALUE_MAX] = {};
902 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
903 // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
904 // for the BOOT_PATCH_LEVEL.
905 if (avb_verification_enabled()) {
906 for (int i = 0; i < att_hw_enforced.size(); i++) {
907 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
908 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
909 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +0800910 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
Shawn Willden7c130392020-12-21 09:58:22 -0700911 // strptime seems to require delimiters, but the tag value will
912 // be YYYYMMDD
913 date.insert(6, "-");
914 date.insert(4, "-");
915 EXPECT_EQ(date.size(), 10);
916 struct tm time;
917 strptime(date.c_str(), "%Y-%m-%d", &time);
918
919 // Day of the month (0-31)
920 EXPECT_GE(time.tm_mday, 0);
921 EXPECT_LT(time.tm_mday, 32);
922 // Months since Jan (0-11)
923 EXPECT_GE(time.tm_mon, 0);
924 EXPECT_LT(time.tm_mon, 12);
925 // Years since 1900
926 EXPECT_GT(time.tm_year, 110);
927 EXPECT_LT(time.tm_year, 200);
928 }
929 }
930 }
931
932 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
933 // indicates true. A provided boolean tag that can be pulled back out of the certificate
934 // indicates correct encoding. No need to check if it's in both lists, since the
935 // AuthorizationSet compare below will handle mismatches of tags.
936 if (security_level == SecurityLevel::SOFTWARE) {
937 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
938 } else {
939 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
940 }
941
942 // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
943 // the authorization list during key generation) isn't being attested to in the certificate.
944 EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
945 EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
946 EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
947 EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
948
949 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
950 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
951 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
952 att_hw_enforced.Contains(TAG_KEY_SIZE));
953 }
954
955 // Test root of trust elements
956 vector<uint8_t> verified_boot_key;
957 VerifiedBoot verified_boot_state;
958 bool device_locked;
959 vector<uint8_t> verified_boot_hash;
960 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
961 &verified_boot_state, &device_locked, &verified_boot_hash);
962 EXPECT_EQ(ErrorCode::OK, error);
963
964 if (avb_verification_enabled()) {
965 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
966 string prop_string(property_value);
967 EXPECT_EQ(prop_string.size(), 64);
968 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
969
970 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
971 if (!strcmp(property_value, "unlocked")) {
972 EXPECT_FALSE(device_locked);
973 } else {
974 EXPECT_TRUE(device_locked);
975 }
976
977 // Check that the device is locked if not debuggable, e.g., user build
978 // images in CTS. For VTS, debuggable images are used to allow adb root
979 // and the device is unlocked.
980 if (!property_get_bool("ro.debuggable", false)) {
981 EXPECT_TRUE(device_locked);
982 } else {
983 EXPECT_FALSE(device_locked);
984 }
985 }
986
987 // Verified boot key should be all 0's if the boot state is not verified or self signed
988 std::string empty_boot_key(32, '\0');
989 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
990 verified_boot_key.size());
991 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
992 if (!strcmp(property_value, "green")) {
993 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
994 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
995 verified_boot_key.size()));
996 } else if (!strcmp(property_value, "yellow")) {
997 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
998 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
999 verified_boot_key.size()));
1000 } else if (!strcmp(property_value, "orange")) {
1001 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1002 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1003 verified_boot_key.size()));
1004 } else if (!strcmp(property_value, "red")) {
1005 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1006 } else {
1007 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1008 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1009 verified_boot_key.size()));
1010 }
1011
1012 att_sw_enforced.Sort();
1013 expected_sw_enforced.Sort();
1014 auto a = filtered_tags(expected_sw_enforced);
1015 auto b = filtered_tags(att_sw_enforced);
1016 EXPECT_EQ(a, b);
1017
1018 att_hw_enforced.Sort();
1019 expected_hw_enforced.Sort();
1020 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1021
1022 return true;
1023}
1024
1025string bin2hex(const vector<uint8_t>& data) {
1026 string retval;
1027 retval.reserve(data.size() * 2 + 1);
1028 for (uint8_t byte : data) {
1029 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1030 retval.push_back(nibble2hex[0x0F & byte]);
1031 }
1032 return retval;
1033}
1034
David Drysdalef0d516d2021-03-22 07:51:43 +00001035AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1036 AuthorizationSet authList;
1037 for (auto& entry : key_characteristics) {
1038 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1039 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1040 authList.push_back(AuthorizationSet(entry.authorizations));
1041 }
1042 }
1043 return authList;
1044}
1045
1046AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1047 AuthorizationSet authList;
1048 for (auto& entry : key_characteristics) {
1049 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1050 entry.securityLevel == SecurityLevel::KEYSTORE) {
1051 authList.push_back(AuthorizationSet(entry.authorizations));
1052 }
1053 }
1054 return authList;
1055}
1056
Shawn Willden7c130392020-12-21 09:58:22 -07001057AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) {
1058 std::stringstream cert_data;
1059
1060 for (size_t i = 0; i < chain.size(); ++i) {
1061 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1062
1063 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1064 X509_Ptr signing_cert;
1065 if (i < chain.size() - 1) {
1066 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1067 } else {
1068 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1069 }
1070 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1071
1072 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1073 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1074
1075 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1076 return AssertionFailure()
1077 << "Verification of certificate " << i << " failed "
1078 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1079 << cert_data.str();
1080 }
1081
1082 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1083 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
1084 if (cert_issuer != signer_subj) {
1085 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n" << cert_data.str();
1086 }
1087
1088 if (i == 0) {
1089 string cert_sub = x509NameToStr(X509_get_subject_name(key_cert.get()));
1090 if ("/CN=Android Keystore Key" != cert_sub) {
1091 return AssertionFailure()
1092 << "Leaf cert has wrong subject, should be CN=Android Keystore Key, was "
1093 << cert_sub << '\n'
1094 << cert_data.str();
1095 }
1096 }
1097 }
1098
1099 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1100 return AssertionSuccess();
1101}
1102
1103X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1104 const uint8_t* p = blob.data();
1105 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1106}
1107
David Drysdalef0d516d2021-03-22 07:51:43 +00001108vector<uint8_t> make_name_from_str(const string& name) {
1109 X509_NAME_Ptr x509_name(X509_NAME_new());
1110 EXPECT_TRUE(x509_name.get() != nullptr);
1111 if (!x509_name) return {};
1112
1113 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1114 "CN", //
1115 MBSTRING_ASC,
1116 reinterpret_cast<const uint8_t*>(name.c_str()),
1117 -1, // len
1118 -1, // loc
1119 0 /* set */));
1120
1121 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1122 EXPECT_GT(len, 0);
1123
1124 vector<uint8_t> retval(len);
1125 uint8_t* p = retval.data();
1126 i2d_X509_NAME(x509_name.get(), &p);
1127
1128 return retval;
1129}
1130
David Drysdale4dc01072021-04-01 12:17:35 +01001131namespace {
1132
1133void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1134 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1135 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1136
1137 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1138 if (testMode) {
1139 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1140 MatchesRegex("{\n"
1141 " 1 : 2,\n" // kty: EC2
1142 " 3 : -7,\n" // alg: ES256
1143 " -1 : 1,\n" // EC id: P256
1144 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1145 // sequence of 32 hexadecimal bytes, enclosed in braces and
1146 // separated by commas. In this case, some Ed25519 public key.
1147 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1148 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1149 " -70000 : null,\n" // test marker
1150 "}"));
1151 } else {
1152 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
1153 MatchesRegex("{\n"
1154 " 1 : 2,\n" // kty: EC2
1155 " 3 : -7,\n" // alg: ES256
1156 " -1 : 1,\n" // EC id: P256
1157 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1158 // sequence of 32 hexadecimal bytes, enclosed in braces and
1159 // separated by commas. In this case, some Ed25519 public key.
1160 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
1161 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
1162 "}"));
1163 }
1164}
1165
1166} // namespace
1167
1168void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1169 vector<uint8_t>* payload_value) {
1170 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1171 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1172
1173 ASSERT_NE(coseMac0->asArray(), nullptr);
1174 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1175
1176 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1177 ASSERT_NE(protParms, nullptr);
1178
1179 // Header label:value of 'alg': HMAC-256
1180 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1181
1182 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1183 ASSERT_NE(unprotParms, nullptr);
1184 ASSERT_EQ(unprotParms->size(), 0);
1185
1186 // The payload is a bstr holding an encoded COSE_Key
1187 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1188 ASSERT_NE(payload, nullptr);
1189 check_cose_key(payload->value(), testMode);
1190
1191 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1192 ASSERT_TRUE(coseMac0Tag);
1193 auto extractedTag = coseMac0Tag->value();
1194 EXPECT_EQ(extractedTag.size(), 32U);
1195
1196 // Compare with tag generated with kTestMacKey. Should only match in test mode
1197 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
1198 payload->value());
1199 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1200
1201 if (testMode) {
1202 EXPECT_EQ(*testTag, extractedTag);
1203 } else {
1204 EXPECT_NE(*testTag, extractedTag);
1205 }
1206 if (payload_value != nullptr) {
1207 *payload_value = payload->value();
1208 }
1209}
1210
1211void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
1212 // Extract x and y affine coordinates from the encoded Cose_Key.
1213 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
1214 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1215 auto coseKey = parsedPayload->asMap();
1216 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
1217 ASSERT_NE(xItem->asBstr(), nullptr);
1218 vector<uint8_t> x = xItem->asBstr()->value();
1219 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
1220 ASSERT_NE(yItem->asBstr(), nullptr);
1221 vector<uint8_t> y = yItem->asBstr()->value();
1222
1223 // Concatenate: 0x04 (uncompressed form marker) | x | y
1224 vector<uint8_t> pubKeyData{0x04};
1225 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
1226 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
1227
1228 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
1229 ASSERT_NE(ecKey, nullptr);
1230 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
1231 ASSERT_NE(group, nullptr);
1232 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
1233 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
1234 ASSERT_NE(point, nullptr);
1235 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
1236 nullptr),
1237 1);
1238 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
1239
1240 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
1241 ASSERT_NE(pubKey, nullptr);
1242 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
1243 *signingKey = std::move(pubKey);
1244}
1245
Selene Huang31ab4042020-04-29 04:22:39 -07001246} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00001247
Janis Danisevskis24c04702020-12-16 18:28:39 -08001248} // namespace aidl::android::hardware::security::keymint