blob: 6c012faec0633212ac91907eb093cb042361aebd [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>
David Drysdale555ba002022-05-03 18:48:57 +010020#include <fstream>
Shawn Willden7f424372021-01-10 18:06:50 -070021#include <unordered_set>
Selene Huang31ab4042020-04-29 04:22:39 -070022#include <vector>
23
24#include <android-base/logging.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080025#include <android/binder_manager.h>
David Drysdale4dc01072021-04-01 12:17:35 +010026#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070027#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010028#include <gmock/gmock.h>
David Drysdale42fe1892021-10-14 14:43:46 +010029#include <openssl/evp.h>
Shawn Willden7c130392020-12-21 09:58:22 -070030#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010031#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070032
Max Bires9704ff62021-04-07 11:12:01 -070033#include <keymaster/cppcose/cppcose.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000034#include <keymint_support/key_param_output.h>
35#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070036#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Janis Danisevskis24c04702020-12-16 18:28:39 -080038namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070039
David Drysdale4dc01072021-04-01 12:17:35 +010040using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070041using namespace std::literals::chrono_literals;
42using std::endl;
43using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070044using std::unique_ptr;
45using ::testing::AssertionFailure;
46using ::testing::AssertionResult;
47using ::testing::AssertionSuccess;
Seth Moore026bb742021-04-30 11:41:18 -070048using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010049using ::testing::MatchesRegex;
Seth Moore026bb742021-04-30 11:41:18 -070050using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070051
52::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
53 if (set.size() == 0)
54 os << "(Empty)" << ::std::endl;
55 else {
56 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070057 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070058 }
59 return os;
60}
61
62namespace test {
63
Shawn Willden7f424372021-01-10 18:06:50 -070064namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010065
David Drysdale37af4b32021-05-14 16:46:59 +010066// Invalid value for a patchlevel (which is of form YYYYMMDD).
67const uint32_t kInvalidPatchlevel = 99998877;
68
David Drysdaledf8f52e2021-05-06 08:10:58 +010069// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
70// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
71const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
72
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000073typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070074// Predicate for testing basic characteristics validity in generation or import.
75bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
76 const vector<KeyCharacteristics>& key_characteristics) {
77 if (key_characteristics.empty()) return false;
78
79 std::unordered_set<SecurityLevel> levels_seen;
80 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070081 if (entry.authorizations.empty()) {
82 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
83 return false;
84 }
Shawn Willden7f424372021-01-10 18:06:50 -070085
Qi Wubeefae42021-01-28 23:16:37 +080086 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
87 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
88
Seth Moore2a9a00e2021-08-04 16:31:52 -070089 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
90 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
91 return false;
92 }
Shawn Willden7f424372021-01-10 18:06:50 -070093 levels_seen.insert(entry.securityLevel);
94
95 // Generally, we should only have one entry, at the same security level as the KM
96 // instance. There is an exception: StrongBox KM can have some authorizations that are
97 // enforced by the TEE.
98 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
99 (secLevel == SecurityLevel::STRONGBOX &&
100 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
101
Seth Moore2a9a00e2021-08-04 16:31:52 -0700102 if (!isExpectedSecurityLevel) {
103 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
104 return false;
105 }
Shawn Willden7f424372021-01-10 18:06:50 -0700106 }
107 return true;
108}
109
Shawn Willden7c130392020-12-21 09:58:22 -0700110// Extract attestation record from cert. Returned object is still part of cert; don't free it
111// separately.
112ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
113 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
114 EXPECT_TRUE(!!oid.get());
115 if (!oid.get()) return nullptr;
116
117 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
118 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
119 if (location == -1) return nullptr;
120
121 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
122 EXPECT_TRUE(!!attest_rec_ext)
123 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
124 if (!attest_rec_ext) return nullptr;
125
126 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
127 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
128 return attest_rec;
129}
130
David Drysdale7dff4fc2021-12-10 10:10:52 +0000131void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
132 // Version numbers in attestation extensions should be a multiple of 100.
133 EXPECT_EQ(attestation_version % 100, 0);
134
135 // The multiplier should never be higher than the AIDL version, but can be less
136 // (for example, if the implementation is from an earlier version but the HAL service
137 // uses the default libraries and so reports the current AIDL version).
138 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
139}
140
Shawn Willden7c130392020-12-21 09:58:22 -0700141bool avb_verification_enabled() {
142 char value[PROPERTY_VALUE_MAX];
143 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
144}
145
146char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
147 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
148
149// Attestations don't contain everything in key authorization lists, so we need to filter the key
150// lists to produce the lists that we expect to match the attestations.
151auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100152 Tag::CREATION_DATETIME,
153 Tag::HARDWARE_TYPE,
154 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700155};
156
157AuthorizationSet filtered_tags(const AuthorizationSet& set) {
158 AuthorizationSet filtered;
159 std::remove_copy_if(
160 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
161 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
162 kTagsToFilter.end();
163 });
164 return filtered;
165}
166
David Drysdale300b5552021-05-20 12:05:26 +0100167// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
168void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
169 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
170 [](const auto& entry) {
171 return entry.securityLevel == SecurityLevel::KEYSTORE;
172 }),
173 characteristics->end());
174}
175
Shawn Willden7c130392020-12-21 09:58:22 -0700176string x509NameToStr(X509_NAME* name) {
177 char* s = X509_NAME_oneline(name, nullptr, 0);
178 string retval(s);
179 OPENSSL_free(s);
180 return retval;
181}
182
Shawn Willden7f424372021-01-10 18:06:50 -0700183} // namespace
184
Shawn Willden7c130392020-12-21 09:58:22 -0700185bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
186bool KeyMintAidlTestBase::dump_Attestations = false;
David Drysdale9f5c0c52022-11-03 15:10:16 +0000187std::string KeyMintAidlTestBase::keyblob_dir;
Shawn Willden7c130392020-12-21 09:58:22 -0700188
David Drysdale37af4b32021-05-14 16:46:59 +0100189uint32_t KeyMintAidlTestBase::boot_patch_level(
190 const vector<KeyCharacteristics>& key_characteristics) {
191 // The boot patchlevel is not available as a property, but should be present
192 // in the key characteristics of any created key.
193 AuthorizationSet allAuths;
194 for (auto& entry : key_characteristics) {
195 allAuths.push_back(AuthorizationSet(entry.authorizations));
196 }
197 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
198 if (patchlevel.has_value()) {
199 return patchlevel.value();
200 } else {
201 // No boot patchlevel is available. Return a value that won't match anything
202 // and so will trigger test failures.
203 return kInvalidPatchlevel;
204 }
205}
206
207uint32_t KeyMintAidlTestBase::boot_patch_level() {
208 return boot_patch_level(key_characteristics_);
209}
210
Prashant Patil88ad1892022-03-15 16:31:02 +0000211/**
212 * An API to determine device IDs attestation is required or not,
213 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
214 */
215bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
216 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= 33;
217}
218
David Drysdale42fe1892021-10-14 14:43:46 +0100219bool KeyMintAidlTestBase::Curve25519Supported() {
220 // Strongbox never supports curve 25519.
221 if (SecLevel() == SecurityLevel::STRONGBOX) {
222 return false;
223 }
224
225 // Curve 25519 was included in version 2 of the KeyMint interface.
226 int32_t version = 0;
227 auto status = keymint_->getInterfaceVersion(&version);
228 if (!status.isOk()) {
229 ADD_FAILURE() << "Failed to determine interface version";
230 }
231 return version >= 2;
232}
233
Janis Danisevskis24c04702020-12-16 18:28:39 -0800234ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700235 if (result.isOk()) return ErrorCode::OK;
236
Janis Danisevskis24c04702020-12-16 18:28:39 -0800237 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
238 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700239 }
240
241 return ErrorCode::UNKNOWN_ERROR;
242}
243
Janis Danisevskis24c04702020-12-16 18:28:39 -0800244void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700245 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800246 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700247
248 KeyMintHardwareInfo info;
249 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
250
251 securityLevel_ = info.securityLevel;
252 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
253 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100254 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700255
256 os_version_ = getOsVersion();
257 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100258 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700259}
260
David Drysdale7dff4fc2021-12-10 10:10:52 +0000261int32_t KeyMintAidlTestBase::AidlVersion() {
262 int32_t version = 0;
263 auto status = keymint_->getInterfaceVersion(&version);
264 if (!status.isOk()) {
265 ADD_FAILURE() << "Failed to determine interface version";
266 }
267 return version;
268}
269
Selene Huang31ab4042020-04-29 04:22:39 -0700270void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800271 if (AServiceManager_isDeclared(GetParam().c_str())) {
272 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
273 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
274 } else {
275 InitializeKeyMint(nullptr);
276 }
Selene Huang31ab4042020-04-29 04:22:39 -0700277}
278
279ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700280 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700281 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700282 vector<KeyCharacteristics>* key_characteristics,
283 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700284 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
285 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700286 << "Previous characteristics not deleted before generating key. Test bug.";
287
Shawn Willden7f424372021-01-10 18:06:50 -0700288 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700289 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700290 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700291 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
292 creationResult.keyCharacteristics);
293 EXPECT_GT(creationResult.keyBlob.size(), 0);
294 *key_blob = std::move(creationResult.keyBlob);
295 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700296 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700297
298 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
299 EXPECT_TRUE(algorithm);
300 if (algorithm &&
301 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700302 EXPECT_GE(cert_chain->size(), 1);
303 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
304 if (attest_key) {
305 EXPECT_EQ(cert_chain->size(), 1);
306 } else {
307 EXPECT_GT(cert_chain->size(), 1);
308 }
309 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700310 } else {
311 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700312 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700313 }
Selene Huang31ab4042020-04-29 04:22:39 -0700314 }
315
316 return GetReturnErrorCode(result);
317}
318
Shawn Willden7c130392020-12-21 09:58:22 -0700319ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
320 const optional<AttestationKey>& attest_key) {
321 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700322}
323
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000324ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
325 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
326 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
327 vector<Certificate>* cert_chain) {
328 AttestationKey attest_key;
329 vector<Certificate> attest_cert_chain;
330 vector<KeyCharacteristics> attest_key_characteristics;
331 // Generate a key with self signed attestation.
332 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
333 &attest_key_characteristics, &attest_cert_chain);
334 if (error != ErrorCode::OK) {
335 return error;
336 }
337
338 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
339 // Generate a key, by passing the above self signed attestation key as attest key.
340 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
341 if (error == ErrorCode::OK) {
342 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
343 cert_chain->push_back(attest_cert_chain[0]);
344 }
345 return error;
346}
347
Selene Huang31ab4042020-04-29 04:22:39 -0700348ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
349 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700350 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700351 Status result;
352
Shawn Willden7f424372021-01-10 18:06:50 -0700353 cert_chain_.clear();
354 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700355 key_blob->clear();
356
Shawn Willden7f424372021-01-10 18:06:50 -0700357 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700358 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700359 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700360 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700361
362 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700363 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
364 creationResult.keyCharacteristics);
365 EXPECT_GT(creationResult.keyBlob.size(), 0);
366
367 *key_blob = std::move(creationResult.keyBlob);
368 *key_characteristics = std::move(creationResult.keyCharacteristics);
369 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700370
371 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
372 EXPECT_TRUE(algorithm);
373 if (algorithm &&
374 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
375 EXPECT_GE(cert_chain_.size(), 1);
376 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
377 } else {
378 // For symmetric keys there should be no certificates.
379 EXPECT_EQ(cert_chain_.size(), 0);
380 }
Selene Huang31ab4042020-04-29 04:22:39 -0700381 }
382
383 return GetReturnErrorCode(result);
384}
385
386ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
387 const string& key_material) {
388 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
389}
390
391ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
392 const AuthorizationSet& wrapping_key_desc,
393 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100394 const AuthorizationSet& unwrapping_params,
395 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700396 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
397
Shawn Willden7f424372021-01-10 18:06:50 -0700398 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700399
Shawn Willden7f424372021-01-10 18:06:50 -0700400 KeyCreationResult creationResult;
401 Status result = keymint_->importWrappedKey(
402 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
403 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100404 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700405
406 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700407 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
408 creationResult.keyCharacteristics);
409 EXPECT_GT(creationResult.keyBlob.size(), 0);
410
411 key_blob_ = std::move(creationResult.keyBlob);
412 key_characteristics_ = std::move(creationResult.keyCharacteristics);
413 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700414
415 AuthorizationSet allAuths;
416 for (auto& entry : key_characteristics_) {
417 allAuths.push_back(AuthorizationSet(entry.authorizations));
418 }
419 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
420 EXPECT_TRUE(algorithm);
421 if (algorithm &&
422 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
423 EXPECT_GE(cert_chain_.size(), 1);
424 } else {
425 // For symmetric keys there should be no certificates.
426 EXPECT_EQ(cert_chain_.size(), 0);
427 }
Selene Huang31ab4042020-04-29 04:22:39 -0700428 }
429
430 return GetReturnErrorCode(result);
431}
432
David Drysdale300b5552021-05-20 12:05:26 +0100433ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
434 const vector<uint8_t>& app_id,
435 const vector<uint8_t>& app_data,
436 vector<KeyCharacteristics>* key_characteristics) {
437 Status result =
438 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
439 return GetReturnErrorCode(result);
440}
441
442ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
443 vector<KeyCharacteristics>* key_characteristics) {
444 vector<uint8_t> empty_app_id, empty_app_data;
445 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
446}
447
448void KeyMintAidlTestBase::CheckCharacteristics(
449 const vector<uint8_t>& key_blob,
450 const vector<KeyCharacteristics>& generate_characteristics) {
451 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
452 // generateKey() should be excluded, as KeyMint will have no record of them.
453 // This applies to CREATION_DATETIME in particular.
454 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
455 strip_keystore_tags(&expected_characteristics);
456
457 vector<KeyCharacteristics> retrieved;
458 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
459 EXPECT_EQ(expected_characteristics, retrieved);
460}
461
462void KeyMintAidlTestBase::CheckAppIdCharacteristics(
463 const vector<uint8_t>& key_blob, std::string_view app_id_string,
464 std::string_view app_data_string,
465 const vector<KeyCharacteristics>& generate_characteristics) {
466 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
467 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
468 strip_keystore_tags(&expected_characteristics);
469
470 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
471 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
472 vector<KeyCharacteristics> retrieved;
473 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
474 EXPECT_EQ(expected_characteristics, retrieved);
475
476 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
477 vector<uint8_t> empty;
478 vector<KeyCharacteristics> not_retrieved;
479 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
480 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
481 EXPECT_EQ(not_retrieved.size(), 0);
482
483 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
484 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
485 EXPECT_EQ(not_retrieved.size(), 0);
486
487 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
488 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
489 EXPECT_EQ(not_retrieved.size(), 0);
490}
491
Selene Huang31ab4042020-04-29 04:22:39 -0700492ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
493 Status result = keymint_->deleteKey(*key_blob);
494 if (!keep_key_blob) {
495 *key_blob = vector<uint8_t>();
496 }
497
Janis Danisevskis24c04702020-12-16 18:28:39 -0800498 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700499 return GetReturnErrorCode(result);
500}
501
502ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
503 return DeleteKey(&key_blob_, keep_key_blob);
504}
505
506ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
507 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800508 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700509 return GetReturnErrorCode(result);
510}
511
David Drysdaled2cc8c22021-04-15 13:29:45 +0100512ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
513 Status result = keymint_->destroyAttestationIds();
514 return GetReturnErrorCode(result);
515}
516
Selene Huang31ab4042020-04-29 04:22:39 -0700517void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
518 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
519 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
520}
521
522void KeyMintAidlTestBase::CheckedDeleteKey() {
523 CheckedDeleteKey(&key_blob_);
524}
525
526ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
527 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800528 AuthorizationSet* out_params,
529 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700530 SCOPED_TRACE("Begin");
531 Status result;
532 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100533 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700534
535 if (result.isOk()) {
536 *out_params = out.params;
537 challenge_ = out.challenge;
538 op = out.operation;
539 }
540
541 return GetReturnErrorCode(result);
542}
543
544ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
545 const AuthorizationSet& in_params,
546 AuthorizationSet* out_params) {
547 SCOPED_TRACE("Begin");
548 Status result;
549 BeginResult out;
550
David Drysdale56ba9122021-04-19 19:10:47 +0100551 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700552
553 if (result.isOk()) {
554 *out_params = out.params;
555 challenge_ = out.challenge;
556 op_ = out.operation;
557 }
558
559 return GetReturnErrorCode(result);
560}
561
562ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
563 AuthorizationSet* out_params) {
564 SCOPED_TRACE("Begin");
565 EXPECT_EQ(nullptr, op_);
566 return Begin(purpose, key_blob_, in_params, out_params);
567}
568
569ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
570 SCOPED_TRACE("Begin");
571 AuthorizationSet out_params;
572 ErrorCode result = Begin(purpose, in_params, &out_params);
573 EXPECT_TRUE(out_params.empty());
574 return result;
575}
576
Shawn Willden92d79c02021-02-19 07:31:55 -0700577ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
578 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
579 {} /* hardwareAuthToken */,
580 {} /* verificationToken */));
581}
582
583ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700584 SCOPED_TRACE("Update");
585
586 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700587 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700588
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800589 EXPECT_NE(op_, nullptr);
590 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
591
Shawn Willden92d79c02021-02-19 07:31:55 -0700592 std::vector<uint8_t> o_put;
593 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700594
David Drysdalefeab5d92022-01-06 15:46:23 +0000595 if (result.isOk()) {
596 output->append(o_put.begin(), o_put.end());
597 } else {
598 // Failure always terminates the operation.
599 op_ = {};
600 }
Selene Huang31ab4042020-04-29 04:22:39 -0700601
602 return GetReturnErrorCode(result);
603}
604
Shawn Willden92d79c02021-02-19 07:31:55 -0700605ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700606 string* output) {
607 SCOPED_TRACE("Finish");
608 Status result;
609
610 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700611 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700612
613 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700614 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
615 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
616 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700617
Shawn Willden92d79c02021-02-19 07:31:55 -0700618 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700619
Shawn Willden92d79c02021-02-19 07:31:55 -0700620 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700621 return GetReturnErrorCode(result);
622}
623
Janis Danisevskis24c04702020-12-16 18:28:39 -0800624ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700625 SCOPED_TRACE("Abort");
626
627 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700628 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700629
630 Status retval = op->abort();
631 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800632 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700633}
634
635ErrorCode KeyMintAidlTestBase::Abort() {
636 SCOPED_TRACE("Abort");
637
638 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700639 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700640
641 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800642 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700643}
644
645void KeyMintAidlTestBase::AbortIfNeeded() {
646 SCOPED_TRACE("AbortIfNeeded");
647 if (op_) {
648 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800649 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700650 }
651}
652
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000653auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
654 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700655 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000656 AuthorizationSet begin_out_params;
657 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700658 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000659
660 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700661 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000662}
663
Selene Huang31ab4042020-04-29 04:22:39 -0700664string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
665 const string& message, const AuthorizationSet& in_params,
666 AuthorizationSet* out_params) {
667 SCOPED_TRACE("ProcessMessage");
668 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700669 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700670 EXPECT_EQ(ErrorCode::OK, result);
671 if (result != ErrorCode::OK) {
672 return "";
673 }
674
675 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700676 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700677 return output;
678}
679
680string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
681 const AuthorizationSet& params) {
682 SCOPED_TRACE("SignMessage");
683 AuthorizationSet out_params;
684 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
685 EXPECT_TRUE(out_params.empty());
686 return signature;
687}
688
689string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
690 SCOPED_TRACE("SignMessage");
691 return SignMessage(key_blob_, message, params);
692}
693
694string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
695 SCOPED_TRACE("MacMessage");
696 return SignMessage(
697 key_blob_, message,
698 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
699}
700
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530701void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
702 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000703 auto builder = AuthorizationSetBuilder()
704 .Authorization(TAG_NO_AUTH_REQUIRED)
705 .AesEncryptionKey(128)
706 .BlockMode(block_mode)
707 .Padding(PaddingMode::NONE);
708 if (block_mode == BlockMode::GCM) {
709 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
710 }
711 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530712
713 for (int increment = 1; increment <= message_size; ++increment) {
714 string message(message_size, 'a');
715 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
716 if (block_mode == BlockMode::GCM) {
717 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
718 }
719
720 AuthorizationSet output_params;
721 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
722
723 string ciphertext;
724 string to_send;
725 for (size_t i = 0; i < message.size(); i += increment) {
726 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
727 }
728 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
729 << "Error sending " << to_send << " with block mode " << block_mode;
730
731 switch (block_mode) {
732 case BlockMode::GCM:
733 EXPECT_EQ(message.size() + 16, ciphertext.size());
734 break;
735 case BlockMode::CTR:
736 EXPECT_EQ(message.size(), ciphertext.size());
737 break;
738 case BlockMode::CBC:
739 case BlockMode::ECB:
740 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
741 break;
742 }
743
744 auto iv = output_params.GetTagValue(TAG_NONCE);
745 switch (block_mode) {
746 case BlockMode::CBC:
747 case BlockMode::GCM:
748 case BlockMode::CTR:
749 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
750 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
751 params.push_back(TAG_NONCE, iv->get());
752 break;
753
754 case BlockMode::ECB:
755 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
756 break;
757 }
758
759 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
760 << "Decrypt begin() failed for block mode " << block_mode;
761
762 string plaintext;
763 for (size_t i = 0; i < ciphertext.size(); i += increment) {
764 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
765 }
766 ErrorCode error = Finish(to_send, &plaintext);
767 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
768 << " and increment " << increment;
769 if (error == ErrorCode::OK) {
770 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
771 << " and increment " << increment;
772 }
773 }
774}
775
Prashant Patildd5f7f02022-07-06 18:58:07 +0000776void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
777 PaddingMode padding_mode, const string& iv,
778 const string& plaintext,
779 const string& exp_cipher_text) {
780 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
781 auto auth_set = AuthorizationSetBuilder()
782 .Authorization(TAG_NO_AUTH_REQUIRED)
783 .AesEncryptionKey(key.size() * 8)
784 .BlockMode(block_mode)
785 .Padding(padding_mode);
786 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
787 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
788 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
789
790 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
791 exp_cipher_text);
792}
793
794void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
795 PaddingMode padding_mode, const string& iv,
796 const string& plaintext,
797 const string& exp_cipher_text) {
798 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
799 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
800 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
801 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
802 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
803
804 AuthorizationSet output_params;
805 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
806
807 string actual_ciphertext;
808 if (is_stream_cipher) {
809 // Assert that a 1 byte of output is produced for 1 byte of input.
810 // Every input byte produces an output byte.
811 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
812 string ciphertext;
813 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
814 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
815 // we relax this API restriction for them.
816 if (SecLevel() != SecurityLevel::STRONGBOX) {
817 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
818 }
819 actual_ciphertext.append(ciphertext);
820 }
821 string ciphertext;
822 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
823 if (SecLevel() != SecurityLevel::STRONGBOX) {
824 string expected_final_output;
825 if (is_authenticated_cipher) {
826 expected_final_output = exp_cipher_text.substr(plaintext.size());
827 }
828 EXPECT_EQ(expected_final_output, ciphertext);
829 }
830 actual_ciphertext.append(ciphertext);
831 } else {
832 // Assert that a block of output is produced once a full block of input is provided.
833 // Every input block produces an output block.
834 bool compare_output = true;
835 string additional_information;
836 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
837 if (SecLevel() == SecurityLevel::STRONGBOX) {
838 // This is known to be broken on older vendor implementations.
839 if (vendor_api_level < 33) {
840 compare_output = false;
841 } else {
842 additional_information = " (b/194134359) ";
843 }
844 }
845 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
846 string ciphertext;
847 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
848 if (compare_output) {
849 if ((plaintext_index % block_size) == block_size - 1) {
850 // Update is expected to have output a new block
851 EXPECT_EQ(block_size, ciphertext.size())
852 << "plaintext index: " << plaintext_index << additional_information;
853 } else {
854 // Update is expected to have produced no output
855 EXPECT_EQ(0, ciphertext.size())
856 << "plaintext index: " << plaintext_index << additional_information;
857 }
858 }
859 actual_ciphertext.append(ciphertext);
860 }
861 string ciphertext;
862 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
863 actual_ciphertext.append(ciphertext);
864 }
865 // Regardless of how the completed ciphertext got accumulated, it should match the expected
866 // ciphertext.
867 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
868}
869
Selene Huang31ab4042020-04-29 04:22:39 -0700870void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
871 Digest digest, const string& expected_mac) {
872 SCOPED_TRACE("CheckHmacTestVector");
873 ASSERT_EQ(ErrorCode::OK,
874 ImportKey(AuthorizationSetBuilder()
875 .Authorization(TAG_NO_AUTH_REQUIRED)
876 .HmacKey(key.size() * 8)
877 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
878 .Digest(digest),
879 KeyFormat::RAW, key));
880 string signature = MacMessage(message, digest, expected_mac.size() * 8);
881 EXPECT_EQ(expected_mac, signature)
882 << "Test vector didn't match for key of size " << key.size() << " message of size "
883 << message.size() << " and digest " << digest;
884 CheckedDeleteKey();
885}
886
887void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
888 const string& message,
889 const string& expected_ciphertext) {
890 SCOPED_TRACE("CheckAesCtrTestVector");
891 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
892 .Authorization(TAG_NO_AUTH_REQUIRED)
893 .AesEncryptionKey(key.size() * 8)
894 .BlockMode(BlockMode::CTR)
895 .Authorization(TAG_CALLER_NONCE)
896 .Padding(PaddingMode::NONE),
897 KeyFormat::RAW, key));
898
899 auto params = AuthorizationSetBuilder()
900 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
901 .BlockMode(BlockMode::CTR)
902 .Padding(PaddingMode::NONE);
903 AuthorizationSet out_params;
904 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
905 EXPECT_EQ(expected_ciphertext, ciphertext);
906}
907
908void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
909 PaddingMode padding_mode, const string& key,
910 const string& iv, const string& input,
911 const string& expected_output) {
912 auto authset = AuthorizationSetBuilder()
913 .TripleDesEncryptionKey(key.size() * 7)
914 .BlockMode(block_mode)
915 .Authorization(TAG_NO_AUTH_REQUIRED)
916 .Padding(padding_mode);
917 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
918 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
919 ASSERT_GT(key_blob_.size(), 0U);
920
921 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
922 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
923 AuthorizationSet output_params;
924 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
925 EXPECT_EQ(expected_output, output);
926}
927
928void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
929 const string& signature, const AuthorizationSet& params) {
930 SCOPED_TRACE("VerifyMessage");
931 AuthorizationSet begin_out_params;
932 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
933
934 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700935 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700936 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700937 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700938}
939
940void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
941 const AuthorizationSet& params) {
942 SCOPED_TRACE("VerifyMessage");
943 VerifyMessage(key_blob_, message, signature, params);
944}
945
David Drysdaledf8f52e2021-05-06 08:10:58 +0100946void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
947 const AuthorizationSet& params) {
948 SCOPED_TRACE("LocalVerifyMessage");
949
David Drysdaledf8f52e2021-05-06 08:10:58 +0100950 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000951 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
952}
953
954void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
955 const string& signature,
956 const AuthorizationSet& params) {
957 // Retrieve the public key from the leaf certificate.
958 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100959 ASSERT_TRUE(key_cert.get());
960 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
961 ASSERT_TRUE(pub_key.get());
962
963 Digest digest = params.GetTagValue(TAG_DIGEST).value();
964 PaddingMode padding = PaddingMode::NONE;
965 auto tag = params.GetTagValue(TAG_PADDING);
966 if (tag.has_value()) {
967 padding = tag.value();
968 }
969
970 if (digest == Digest::NONE) {
971 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100972 case EVP_PKEY_ED25519: {
973 ASSERT_EQ(64, signature.size());
974 uint8_t pub_keydata[32];
975 size_t pub_len = sizeof(pub_keydata);
976 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
977 ASSERT_EQ(sizeof(pub_keydata), pub_len);
978 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
979 message.size(),
980 reinterpret_cast<const uint8_t*>(signature.data()),
981 pub_keydata));
982 break;
983 }
984
David Drysdaledf8f52e2021-05-06 08:10:58 +0100985 case EVP_PKEY_EC: {
986 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
987 size_t data_size = std::min(data.size(), message.size());
988 memcpy(data.data(), message.data(), data_size);
989 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
990 ASSERT_TRUE(ecdsa.get());
991 ASSERT_EQ(1,
992 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
993 reinterpret_cast<const uint8_t*>(signature.data()),
994 signature.size(), ecdsa.get()));
995 break;
996 }
997 case EVP_PKEY_RSA: {
998 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
999 size_t data_size = std::min(data.size(), message.size());
1000 memcpy(data.data(), message.data(), data_size);
1001
1002 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1003 ASSERT_TRUE(rsa.get());
1004
1005 size_t key_len = RSA_size(rsa.get());
1006 int openssl_padding = RSA_NO_PADDING;
1007 switch (padding) {
1008 case PaddingMode::NONE:
1009 ASSERT_TRUE(data_size <= key_len);
1010 ASSERT_EQ(key_len, signature.size());
1011 openssl_padding = RSA_NO_PADDING;
1012 break;
1013 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1014 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1015 key_len);
1016 openssl_padding = RSA_PKCS1_PADDING;
1017 break;
1018 default:
1019 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1020 }
1021
1022 vector<uint8_t> decrypted_data(key_len);
1023 int bytes_decrypted = RSA_public_decrypt(
1024 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1025 decrypted_data.data(), rsa.get(), openssl_padding);
1026 ASSERT_GE(bytes_decrypted, 0);
1027
1028 const uint8_t* compare_pos = decrypted_data.data();
1029 size_t bytes_to_compare = bytes_decrypted;
1030 uint8_t zero_check_result = 0;
1031 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1032 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1033 // during verification we should have zeros on the left of the decrypted data.
1034 // Do a constant-time check.
1035 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1036 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1037 ASSERT_EQ(0, zero_check_result);
1038 bytes_to_compare = data_size;
1039 }
1040 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1041 break;
1042 }
1043 default:
1044 ADD_FAILURE() << "Unknown public key type";
1045 }
1046 } else {
1047 EVP_MD_CTX digest_ctx;
1048 EVP_MD_CTX_init(&digest_ctx);
1049 EVP_PKEY_CTX* pkey_ctx;
1050 const EVP_MD* md = openssl_digest(digest);
1051 ASSERT_NE(md, nullptr);
1052 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1053
1054 if (padding == PaddingMode::RSA_PSS) {
1055 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1056 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001057 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001058 }
1059
1060 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1061 reinterpret_cast<const uint8_t*>(message.data()),
1062 message.size()));
1063 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1064 reinterpret_cast<const uint8_t*>(signature.data()),
1065 signature.size()));
1066 EVP_MD_CTX_cleanup(&digest_ctx);
1067 }
1068}
1069
David Drysdale59cae642021-05-12 13:52:03 +01001070string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1071 const AuthorizationSet& params) {
1072 SCOPED_TRACE("LocalRsaEncryptMessage");
1073
1074 // Retrieve the public key from the leaf certificate.
1075 if (cert_chain_.empty()) {
1076 ADD_FAILURE() << "No public key available";
1077 return "Failure";
1078 }
1079 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001080 if (key_cert.get() == nullptr) {
1081 ADD_FAILURE() << "Failed to parse cert";
1082 return "Failure";
1083 }
David Drysdale59cae642021-05-12 13:52:03 +01001084 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001085 if (pub_key.get() == nullptr) {
1086 ADD_FAILURE() << "Failed to retrieve public key";
1087 return "Failure";
1088 }
David Drysdale59cae642021-05-12 13:52:03 +01001089 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001090 if (rsa.get() == nullptr) {
1091 ADD_FAILURE() << "Failed to retrieve RSA public key";
1092 return "Failure";
1093 }
David Drysdale59cae642021-05-12 13:52:03 +01001094
1095 // Retrieve relevant tags.
1096 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001097 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001098 PaddingMode padding = PaddingMode::NONE;
1099
1100 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1101 if (digest_tag.has_value()) digest = digest_tag.value();
1102 auto pad_tag = params.GetTagValue(TAG_PADDING);
1103 if (pad_tag.has_value()) padding = pad_tag.value();
1104 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1105 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1106
1107 const EVP_MD* md = openssl_digest(digest);
1108 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1109
1110 // Set up encryption context.
1111 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1112 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1113 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1114 return "Failure";
1115 }
1116
1117 int rc = -1;
1118 switch (padding) {
1119 case PaddingMode::NONE:
1120 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1121 break;
1122 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1123 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1124 break;
1125 case PaddingMode::RSA_OAEP:
1126 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1127 break;
1128 default:
1129 break;
1130 }
1131 if (rc <= 0) {
1132 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1133 return "Failure";
1134 }
1135 if (padding == PaddingMode::RSA_OAEP) {
1136 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1137 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1138 return "Failure";
1139 }
1140 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1141 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1142 return "Failure";
1143 }
1144 }
1145
1146 // Determine output size.
1147 size_t outlen;
1148 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1149 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1150 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1151 return "Failure";
1152 }
1153
1154 // Left-zero-pad the input if necessary.
1155 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1156 size_t to_encrypt_len = message.size();
1157
1158 std::unique_ptr<string> zero_padded_message;
1159 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1160 zero_padded_message.reset(new string(outlen, '\0'));
1161 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1162 message.size());
1163 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1164 to_encrypt_len = outlen;
1165 }
1166
1167 // Do the encryption.
1168 string output(outlen, '\0');
1169 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1170 to_encrypt_len) <= 0) {
1171 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1172 return "Failure";
1173 }
1174 return output;
1175}
1176
Selene Huang31ab4042020-04-29 04:22:39 -07001177string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1178 const AuthorizationSet& in_params,
1179 AuthorizationSet* out_params) {
1180 SCOPED_TRACE("EncryptMessage");
1181 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1182}
1183
1184string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1185 AuthorizationSet* out_params) {
1186 SCOPED_TRACE("EncryptMessage");
1187 return EncryptMessage(key_blob_, message, params, out_params);
1188}
1189
1190string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1191 SCOPED_TRACE("EncryptMessage");
1192 AuthorizationSet out_params;
1193 string ciphertext = EncryptMessage(message, params, &out_params);
1194 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1195 return ciphertext;
1196}
1197
1198string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1199 PaddingMode padding) {
1200 SCOPED_TRACE("EncryptMessage");
1201 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1202 AuthorizationSet out_params;
1203 string ciphertext = EncryptMessage(message, params, &out_params);
1204 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1205 return ciphertext;
1206}
1207
1208string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1209 PaddingMode padding, vector<uint8_t>* iv_out) {
1210 SCOPED_TRACE("EncryptMessage");
1211 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1212 AuthorizationSet out_params;
1213 string ciphertext = EncryptMessage(message, params, &out_params);
1214 EXPECT_EQ(1U, out_params.size());
1215 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001216 EXPECT_TRUE(ivVal);
1217 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001218 return ciphertext;
1219}
1220
1221string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1222 PaddingMode padding, const vector<uint8_t>& iv_in) {
1223 SCOPED_TRACE("EncryptMessage");
1224 auto params = AuthorizationSetBuilder()
1225 .BlockMode(block_mode)
1226 .Padding(padding)
1227 .Authorization(TAG_NONCE, iv_in);
1228 AuthorizationSet out_params;
1229 string ciphertext = EncryptMessage(message, params, &out_params);
1230 return ciphertext;
1231}
1232
1233string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1234 PaddingMode padding, uint8_t mac_length_bits,
1235 const vector<uint8_t>& iv_in) {
1236 SCOPED_TRACE("EncryptMessage");
1237 auto params = AuthorizationSetBuilder()
1238 .BlockMode(block_mode)
1239 .Padding(padding)
1240 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1241 .Authorization(TAG_NONCE, iv_in);
1242 AuthorizationSet out_params;
1243 string ciphertext = EncryptMessage(message, params, &out_params);
1244 return ciphertext;
1245}
1246
David Drysdaled2cc8c22021-04-15 13:29:45 +01001247string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1248 PaddingMode padding, uint8_t mac_length_bits) {
1249 SCOPED_TRACE("EncryptMessage");
1250 auto params = AuthorizationSetBuilder()
1251 .BlockMode(block_mode)
1252 .Padding(padding)
1253 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1254 AuthorizationSet out_params;
1255 string ciphertext = EncryptMessage(message, params, &out_params);
1256 return ciphertext;
1257}
1258
Selene Huang31ab4042020-04-29 04:22:39 -07001259string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1260 const string& ciphertext,
1261 const AuthorizationSet& params) {
1262 SCOPED_TRACE("DecryptMessage");
1263 AuthorizationSet out_params;
1264 string plaintext =
1265 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1266 EXPECT_TRUE(out_params.empty());
1267 return plaintext;
1268}
1269
1270string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1271 const AuthorizationSet& params) {
1272 SCOPED_TRACE("DecryptMessage");
1273 return DecryptMessage(key_blob_, ciphertext, params);
1274}
1275
1276string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1277 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1278 SCOPED_TRACE("DecryptMessage");
1279 auto params = AuthorizationSetBuilder()
1280 .BlockMode(block_mode)
1281 .Padding(padding_mode)
1282 .Authorization(TAG_NONCE, iv);
1283 return DecryptMessage(key_blob_, ciphertext, params);
1284}
1285
1286std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1287 const vector<uint8_t>& key_blob) {
1288 std::pair<ErrorCode, vector<uint8_t>> retval;
1289 vector<uint8_t> outKeyBlob;
1290 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1291 ErrorCode errorcode = GetReturnErrorCode(result);
1292 retval = std::tie(errorcode, outKeyBlob);
1293
1294 return retval;
1295}
1296vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1297 switch (algorithm) {
1298 case Algorithm::RSA:
1299 switch (SecLevel()) {
1300 case SecurityLevel::SOFTWARE:
1301 case SecurityLevel::TRUSTED_ENVIRONMENT:
1302 return {2048, 3072, 4096};
1303 case SecurityLevel::STRONGBOX:
1304 return {2048};
1305 default:
1306 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1307 break;
1308 }
1309 break;
1310 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001311 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001312 break;
1313 case Algorithm::AES:
1314 return {128, 256};
1315 case Algorithm::TRIPLE_DES:
1316 return {168};
1317 case Algorithm::HMAC: {
1318 vector<uint32_t> retval((512 - 64) / 8 + 1);
1319 uint32_t size = 64 - 8;
1320 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1321 return retval;
1322 }
1323 default:
1324 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1325 return {};
1326 }
1327 ADD_FAILURE() << "Should be impossible to get here";
1328 return {};
1329}
1330
1331vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1332 if (SecLevel() == SecurityLevel::STRONGBOX) {
1333 switch (algorithm) {
1334 case Algorithm::RSA:
1335 return {3072, 4096};
1336 case Algorithm::EC:
1337 return {224, 384, 521};
1338 case Algorithm::AES:
1339 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001340 case Algorithm::TRIPLE_DES:
1341 return {56};
1342 default:
1343 return {};
1344 }
1345 } else {
1346 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001347 case Algorithm::AES:
1348 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001349 case Algorithm::TRIPLE_DES:
1350 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001351 default:
1352 return {};
1353 }
1354 }
1355 return {};
1356}
1357
David Drysdale7de9feb2021-03-05 14:56:19 +00001358vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1359 switch (algorithm) {
1360 case Algorithm::AES:
1361 return {
1362 BlockMode::CBC,
1363 BlockMode::CTR,
1364 BlockMode::ECB,
1365 BlockMode::GCM,
1366 };
1367 case Algorithm::TRIPLE_DES:
1368 return {
1369 BlockMode::CBC,
1370 BlockMode::ECB,
1371 };
1372 default:
1373 return {};
1374 }
1375}
1376
1377vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1378 BlockMode blockMode) {
1379 switch (algorithm) {
1380 case Algorithm::AES:
1381 switch (blockMode) {
1382 case BlockMode::CBC:
1383 case BlockMode::ECB:
1384 return {PaddingMode::NONE, PaddingMode::PKCS7};
1385 case BlockMode::CTR:
1386 case BlockMode::GCM:
1387 return {PaddingMode::NONE};
1388 default:
1389 return {};
1390 };
1391 case Algorithm::TRIPLE_DES:
1392 switch (blockMode) {
1393 case BlockMode::CBC:
1394 case BlockMode::ECB:
1395 return {PaddingMode::NONE, PaddingMode::PKCS7};
1396 default:
1397 return {};
1398 };
1399 default:
1400 return {};
1401 }
1402}
1403
1404vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1405 BlockMode blockMode) {
1406 switch (algorithm) {
1407 case Algorithm::AES:
1408 switch (blockMode) {
1409 case BlockMode::CTR:
1410 case BlockMode::GCM:
1411 return {PaddingMode::PKCS7};
1412 default:
1413 return {};
1414 };
1415 default:
1416 return {};
1417 }
1418}
1419
Selene Huang31ab4042020-04-29 04:22:39 -07001420vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1421 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1422 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001423 } else if (Curve25519Supported()) {
1424 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1425 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001426 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001427 return {
1428 EcCurve::P_224,
1429 EcCurve::P_256,
1430 EcCurve::P_384,
1431 EcCurve::P_521,
1432 };
Selene Huang31ab4042020-04-29 04:22:39 -07001433 }
1434}
1435
1436vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001437 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001438 // Curve 25519 is not supported, either because:
1439 // - KeyMint v1: it's an unknown enum value
1440 // - KeyMint v2+: it's not supported by StrongBox.
1441 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001442 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001443 if (Curve25519Supported()) {
1444 return {};
1445 } else {
1446 return {EcCurve::CURVE_25519};
1447 }
David Drysdaledf09e542021-06-08 15:46:11 +01001448 }
Selene Huang31ab4042020-04-29 04:22:39 -07001449}
1450
subrahmanyaman05642492022-02-05 07:10:56 +00001451vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1452 if (SecLevel() == SecurityLevel::STRONGBOX) {
1453 return {65537};
1454 } else {
1455 return {3, 65537};
1456 }
1457}
1458
Selene Huang31ab4042020-04-29 04:22:39 -07001459vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1460 switch (SecLevel()) {
1461 case SecurityLevel::SOFTWARE:
1462 case SecurityLevel::TRUSTED_ENVIRONMENT:
1463 if (withNone) {
1464 if (withMD5)
1465 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1466 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1467 Digest::SHA_2_512};
1468 else
1469 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1470 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1471 } else {
1472 if (withMD5)
1473 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1474 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1475 else
1476 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1477 Digest::SHA_2_512};
1478 }
1479 break;
1480 case SecurityLevel::STRONGBOX:
1481 if (withNone)
1482 return {Digest::NONE, Digest::SHA_2_256};
1483 else
1484 return {Digest::SHA_2_256};
1485 break;
1486 default:
1487 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1488 break;
1489 }
1490 ADD_FAILURE() << "Should be impossible to get here";
1491 return {};
1492}
1493
Shawn Willden7f424372021-01-10 18:06:50 -07001494static const vector<KeyParameter> kEmptyAuthList{};
1495
1496const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1497 const vector<KeyCharacteristics>& key_characteristics) {
1498 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1499 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1500 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1501}
1502
Qi Wubeefae42021-01-28 23:16:37 +08001503const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1504 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1505 auto found = std::find_if(
1506 key_characteristics.begin(), key_characteristics.end(),
1507 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001508 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1509}
1510
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001511ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001512 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001513 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1514 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1515 return result;
1516}
1517
1518ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001519 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001520 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1521 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1522 return result;
1523}
1524
1525ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1526 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001527 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001528 rsaKeyBlob, KeyPurpose::SIGN, message,
1529 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1530 return result;
1531}
1532
1533ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001534 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1535 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001536 return result;
1537}
1538
Selene Huang6e46f142021-04-20 19:20:11 -07001539void verify_serial(X509* cert, const uint64_t expected_serial) {
1540 BIGNUM_Ptr ser(BN_new());
1541 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1542
1543 uint64_t serial;
1544 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1545 EXPECT_EQ(serial, expected_serial);
1546}
1547
1548// Please set self_signed to true for fake certificates or self signed
1549// certificates
1550void verify_subject(const X509* cert, //
1551 const string& subject, //
1552 bool self_signed) {
1553 char* cert_issuer = //
1554 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1555
1556 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1557
1558 string expected_subject("/CN=");
1559 if (subject.empty()) {
1560 expected_subject.append("Android Keystore Key");
1561 } else {
1562 expected_subject.append(subject);
1563 }
1564
1565 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1566
1567 if (self_signed) {
1568 EXPECT_STREQ(cert_issuer, cert_subj)
1569 << "Cert issuer and subject mismatch for self signed certificate.";
1570 }
1571
1572 OPENSSL_free(cert_subj);
1573 OPENSSL_free(cert_issuer);
1574}
1575
Shawn Willden22fb9c12022-06-02 14:04:33 -06001576int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001577 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1578 if (vendor_api_level != -1) {
1579 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001580 }
Shawn Willden35db3492022-06-16 12:50:40 -06001581
1582 // Android S and older devices do not define ro.vendor.api_level
1583 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1584 if (vendor_api_level == -1) {
1585 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001586 }
Shawn Willden35db3492022-06-16 12:50:40 -06001587
1588 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1589 if (product_api_level == -1) {
1590 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1591 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001592 }
Shawn Willden35db3492022-06-16 12:50:40 -06001593
1594 // VSR API level is the minimum of vendor_api_level and product_api_level.
1595 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1596 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001597 }
Shawn Willden35db3492022-06-16 12:50:40 -06001598 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001599}
1600
David Drysdale555ba002022-05-03 18:48:57 +01001601bool is_gsi_image() {
1602 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1603 return ifs.good();
1604}
1605
Selene Huang6e46f142021-04-20 19:20:11 -07001606vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1607 BIGNUM_Ptr serial(BN_new());
1608 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1609
1610 int len = BN_num_bytes(serial.get());
1611 vector<uint8_t> serial_blob(len);
1612 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1613 return {};
1614 }
1615
David Drysdaledb0dcf52021-05-18 11:43:31 +01001616 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1617 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1618 // Top bit being set indicates a negative number in two's complement, but our input
1619 // was positive.
1620 // In either case, prepend a zero byte.
1621 serial_blob.insert(serial_blob.begin(), 0x00);
1622 }
1623
Selene Huang6e46f142021-04-20 19:20:11 -07001624 return serial_blob;
1625}
1626
1627void verify_subject_and_serial(const Certificate& certificate, //
1628 const uint64_t expected_serial, //
1629 const string& subject, bool self_signed) {
1630 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1631 ASSERT_TRUE(!!cert.get());
1632
1633 verify_serial(cert.get(), expected_serial);
1634 verify_subject(cert.get(), subject, self_signed);
1635}
1636
Shawn Willden4315e132022-03-20 12:49:46 -06001637void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1638 VerifiedBoot verified_boot_state,
1639 const vector<uint8_t>& verified_boot_hash) {
1640 char property_value[PROPERTY_VALUE_MAX] = {};
1641
1642 if (avb_verification_enabled()) {
1643 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1644 string prop_string(property_value);
1645 EXPECT_EQ(prop_string.size(), 64);
1646 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1647
1648 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1649 if (!strcmp(property_value, "unlocked")) {
1650 EXPECT_FALSE(device_locked);
1651 } else {
1652 EXPECT_TRUE(device_locked);
1653 }
1654
1655 // Check that the device is locked if not debuggable, e.g., user build
1656 // images in CTS. For VTS, debuggable images are used to allow adb root
1657 // and the device is unlocked.
1658 if (!property_get_bool("ro.debuggable", false)) {
1659 EXPECT_TRUE(device_locked);
1660 } else {
1661 EXPECT_FALSE(device_locked);
1662 }
1663 }
1664
1665 // Verified boot key should be all 0's if the boot state is not verified or self signed
1666 std::string empty_boot_key(32, '\0');
1667 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1668 verified_boot_key.size());
1669 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1670 if (!strcmp(property_value, "green")) {
1671 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1672 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1673 verified_boot_key.size()));
1674 } else if (!strcmp(property_value, "yellow")) {
1675 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1676 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1677 verified_boot_key.size()));
1678 } else if (!strcmp(property_value, "orange")) {
1679 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1680 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1681 verified_boot_key.size()));
1682 } else if (!strcmp(property_value, "red")) {
1683 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1684 } else {
1685 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1686 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1687 verified_boot_key.size()));
1688 }
1689}
1690
David Drysdale7dff4fc2021-12-10 10:10:52 +00001691bool verify_attestation_record(int32_t aidl_version, //
1692 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001693 const string& app_id, //
1694 AuthorizationSet expected_sw_enforced, //
1695 AuthorizationSet expected_hw_enforced, //
1696 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001697 const vector<uint8_t>& attestation_cert,
1698 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001699 X509_Ptr cert(parse_cert_blob(attestation_cert));
1700 EXPECT_TRUE(!!cert.get());
1701 if (!cert.get()) return false;
1702
1703 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1704 EXPECT_TRUE(!!attest_rec);
1705 if (!attest_rec) return false;
1706
1707 AuthorizationSet att_sw_enforced;
1708 AuthorizationSet att_hw_enforced;
1709 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001710 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001711 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001712 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001713 vector<uint8_t> att_challenge;
1714 vector<uint8_t> att_unique_id;
1715 vector<uint8_t> att_app_id;
1716
1717 auto error = parse_attestation_record(attest_rec->data, //
1718 attest_rec->length, //
1719 &att_attestation_version, //
1720 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001721 &att_keymint_version, //
1722 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001723 &att_challenge, //
1724 &att_sw_enforced, //
1725 &att_hw_enforced, //
1726 &att_unique_id);
1727 EXPECT_EQ(ErrorCode::OK, error);
1728 if (error != ErrorCode::OK) return false;
1729
David Drysdale7dff4fc2021-12-10 10:10:52 +00001730 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001731 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001732
Selene Huang4f64c222021-04-13 19:54:36 -07001733 // check challenge and app id only if we expects a non-fake certificate
1734 if (challenge.length() > 0) {
1735 EXPECT_EQ(challenge.length(), att_challenge.size());
1736 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1737
1738 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1739 }
Shawn Willden7c130392020-12-21 09:58:22 -07001740
David Drysdale7dff4fc2021-12-10 10:10:52 +00001741 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001742 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001743 EXPECT_EQ(security_level, att_attestation_security_level);
1744
Shawn Willden7c130392020-12-21 09:58:22 -07001745 // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
David Drysdale37af4b32021-05-14 16:46:59 +01001746 // keymint implementation will report YYYYMM dates instead of YYYYMMDD
Shawn Willden7c130392020-12-21 09:58:22 -07001747 // for the BOOT_PATCH_LEVEL.
1748 if (avb_verification_enabled()) {
1749 for (int i = 0; i < att_hw_enforced.size(); i++) {
1750 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1751 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1752 std::string date =
Tommy Chiuf00d8f12021-04-08 11:07:48 +08001753 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001754
Shawn Willden7c130392020-12-21 09:58:22 -07001755 // strptime seems to require delimiters, but the tag value will
1756 // be YYYYMMDD
David Drysdale168228a2021-10-05 08:43:52 +01001757 if (date.size() != 8) {
1758 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1759 << " with invalid format (not YYYYMMDD): " << date;
1760 return false;
1761 }
Shawn Willden7c130392020-12-21 09:58:22 -07001762 date.insert(6, "-");
1763 date.insert(4, "-");
Shawn Willden7c130392020-12-21 09:58:22 -07001764 struct tm time;
1765 strptime(date.c_str(), "%Y-%m-%d", &time);
1766
1767 // Day of the month (0-31)
1768 EXPECT_GE(time.tm_mday, 0);
1769 EXPECT_LT(time.tm_mday, 32);
1770 // Months since Jan (0-11)
1771 EXPECT_GE(time.tm_mon, 0);
1772 EXPECT_LT(time.tm_mon, 12);
1773 // Years since 1900
1774 EXPECT_GT(time.tm_year, 110);
1775 EXPECT_LT(time.tm_year, 200);
1776 }
1777 }
1778 }
1779
1780 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1781 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1782 // indicates correct encoding. No need to check if it's in both lists, since the
1783 // AuthorizationSet compare below will handle mismatches of tags.
1784 if (security_level == SecurityLevel::SOFTWARE) {
1785 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1786 } else {
1787 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1788 }
1789
Shawn Willden7c130392020-12-21 09:58:22 -07001790 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1791 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1792 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1793 att_hw_enforced.Contains(TAG_KEY_SIZE));
1794 }
1795
1796 // Test root of trust elements
1797 vector<uint8_t> verified_boot_key;
1798 VerifiedBoot verified_boot_state;
1799 bool device_locked;
1800 vector<uint8_t> verified_boot_hash;
1801 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1802 &verified_boot_state, &device_locked, &verified_boot_hash);
1803 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001804 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001805
1806 att_sw_enforced.Sort();
1807 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001808 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001809
1810 att_hw_enforced.Sort();
1811 expected_hw_enforced.Sort();
1812 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1813
David Drysdale565ccc72021-10-11 12:49:50 +01001814 if (unique_id != nullptr) {
1815 *unique_id = att_unique_id;
1816 }
1817
Shawn Willden7c130392020-12-21 09:58:22 -07001818 return true;
1819}
1820
1821string bin2hex(const vector<uint8_t>& data) {
1822 string retval;
1823 retval.reserve(data.size() * 2 + 1);
1824 for (uint8_t byte : data) {
1825 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1826 retval.push_back(nibble2hex[0x0F & byte]);
1827 }
1828 return retval;
1829}
1830
David Drysdalef0d516d2021-03-22 07:51:43 +00001831AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1832 AuthorizationSet authList;
1833 for (auto& entry : key_characteristics) {
1834 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1835 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1836 authList.push_back(AuthorizationSet(entry.authorizations));
1837 }
1838 }
1839 return authList;
1840}
1841
1842AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1843 AuthorizationSet authList;
1844 for (auto& entry : key_characteristics) {
1845 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1846 entry.securityLevel == SecurityLevel::KEYSTORE) {
1847 authList.push_back(AuthorizationSet(entry.authorizations));
1848 }
1849 }
1850 return authList;
1851}
1852
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001853AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1854 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001855 std::stringstream cert_data;
1856
1857 for (size_t i = 0; i < chain.size(); ++i) {
1858 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1859
1860 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1861 X509_Ptr signing_cert;
1862 if (i < chain.size() - 1) {
1863 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1864 } else {
1865 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1866 }
1867 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1868
1869 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1870 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1871
1872 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1873 return AssertionFailure()
1874 << "Verification of certificate " << i << " failed "
1875 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1876 << cert_data.str();
1877 }
1878
1879 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1880 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001881 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001882 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1883 << " Signer subject is " << signer_subj
1884 << " Issuer subject is " << cert_issuer << endl
1885 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001886 }
Shawn Willden7c130392020-12-21 09:58:22 -07001887 }
1888
1889 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1890 return AssertionSuccess();
1891}
1892
1893X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1894 const uint8_t* p = blob.data();
1895 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1896}
1897
David Drysdalef0d516d2021-03-22 07:51:43 +00001898vector<uint8_t> make_name_from_str(const string& name) {
1899 X509_NAME_Ptr x509_name(X509_NAME_new());
1900 EXPECT_TRUE(x509_name.get() != nullptr);
1901 if (!x509_name) return {};
1902
1903 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1904 "CN", //
1905 MBSTRING_ASC,
1906 reinterpret_cast<const uint8_t*>(name.c_str()),
1907 -1, // len
1908 -1, // loc
1909 0 /* set */));
1910
1911 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1912 EXPECT_GT(len, 0);
1913
1914 vector<uint8_t> retval(len);
1915 uint8_t* p = retval.data();
1916 i2d_X509_NAME(x509_name.get(), &p);
1917
1918 return retval;
1919}
1920
David Drysdale4dc01072021-04-01 12:17:35 +01001921namespace {
1922
1923void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1924 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1925 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1926
1927 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1928 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001929 EXPECT_THAT(
1930 cppbor::prettyPrint(parsedPayload.get()),
1931 MatchesRegex("\\{\n"
1932 " 1 : 2,\n" // kty: EC2
1933 " 3 : -7,\n" // alg: ES256
1934 " -1 : 1,\n" // EC id: P256
1935 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1936 // sequence of 32 hexadecimal bytes, enclosed in braces and
1937 // separated by commas. In this case, some Ed25519 public key.
1938 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1939 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1940 " -70000 : null,\n" // test marker
1941 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001942 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001943 EXPECT_THAT(
1944 cppbor::prettyPrint(parsedPayload.get()),
1945 MatchesRegex("\\{\n"
1946 " 1 : 2,\n" // kty: EC2
1947 " 3 : -7,\n" // alg: ES256
1948 " -1 : 1,\n" // EC id: P256
1949 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1950 // sequence of 32 hexadecimal bytes, enclosed in braces and
1951 // separated by commas. In this case, some Ed25519 public key.
1952 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1953 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1954 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001955 }
1956}
1957
1958} // namespace
1959
1960void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1961 vector<uint8_t>* payload_value) {
1962 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1963 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1964
1965 ASSERT_NE(coseMac0->asArray(), nullptr);
1966 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1967
1968 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1969 ASSERT_NE(protParms, nullptr);
1970
1971 // Header label:value of 'alg': HMAC-256
1972 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1973
1974 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1975 ASSERT_NE(unprotParms, nullptr);
1976 ASSERT_EQ(unprotParms->size(), 0);
1977
1978 // The payload is a bstr holding an encoded COSE_Key
1979 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1980 ASSERT_NE(payload, nullptr);
1981 check_cose_key(payload->value(), testMode);
1982
1983 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1984 ASSERT_TRUE(coseMac0Tag);
1985 auto extractedTag = coseMac0Tag->value();
1986 EXPECT_EQ(extractedTag.size(), 32U);
1987
1988 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001989 auto macFunction = [](const cppcose::bytevec& input) {
1990 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1991 };
1992 auto testTag =
1993 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001994 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1995
1996 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07001997 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01001998 } else {
Seth Moore026bb742021-04-30 11:41:18 -07001999 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002000 }
2001 if (payload_value != nullptr) {
2002 *payload_value = payload->value();
2003 }
2004}
2005
2006void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2007 // Extract x and y affine coordinates from the encoded Cose_Key.
2008 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2009 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2010 auto coseKey = parsedPayload->asMap();
2011 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2012 ASSERT_NE(xItem->asBstr(), nullptr);
2013 vector<uint8_t> x = xItem->asBstr()->value();
2014 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2015 ASSERT_NE(yItem->asBstr(), nullptr);
2016 vector<uint8_t> y = yItem->asBstr()->value();
2017
2018 // Concatenate: 0x04 (uncompressed form marker) | x | y
2019 vector<uint8_t> pubKeyData{0x04};
2020 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2021 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2022
2023 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2024 ASSERT_NE(ecKey, nullptr);
2025 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2026 ASSERT_NE(group, nullptr);
2027 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2028 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2029 ASSERT_NE(point, nullptr);
2030 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2031 nullptr),
2032 1);
2033 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2034
2035 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2036 ASSERT_NE(pubKey, nullptr);
2037 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2038 *signingKey = std::move(pubKey);
2039}
2040
Max Biresa97ec692022-11-21 23:37:54 -08002041void device_id_attestation_vsr_check(const ErrorCode& result) {
2042 if (get_vsr_api_level() >= 34) {
2043 ASSERT_FALSE(result == ErrorCode::INVALID_TAG)
2044 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2045 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2046 << "be used for a case where updateAad() is called after update(). As of "
2047 << "VSR-14, this is now enforced as an error.";
2048 }
2049}
2050
Selene Huang31ab4042020-04-29 04:22:39 -07002051} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002052
Janis Danisevskis24c04702020-12-16 18:28:39 -08002053} // namespace aidl::android::hardware::security::keymint