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