blob: 41d47eee8c943465635ff96ceb5392d534da1020 [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 Drysdale3d2ba0a2023-01-11 13:27:26 +000026#include <android/content/pm/IPackageManagerNative.h>
David Drysdale4dc01072021-04-01 12:17:35 +010027#include <cppbor_parse.h>
Shawn Willden7c130392020-12-21 09:58:22 -070028#include <cutils/properties.h>
David Drysdale4dc01072021-04-01 12:17:35 +010029#include <gmock/gmock.h>
David Drysdale42fe1892021-10-14 14:43:46 +010030#include <openssl/evp.h>
Shawn Willden7c130392020-12-21 09:58:22 -070031#include <openssl/mem.h>
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <remote_prov/remote_prov_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070033
Max Bires9704ff62021-04-07 11:12:01 -070034#include <keymaster/cppcose/cppcose.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000035#include <keymint_support/key_param_output.h>
36#include <keymint_support/keymint_utils.h>
Shawn Willden7c130392020-12-21 09:58:22 -070037#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070038
Janis Danisevskis24c04702020-12-16 18:28:39 -080039namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070040
David Drysdale4dc01072021-04-01 12:17:35 +010041using namespace cppcose;
Selene Huang31ab4042020-04-29 04:22:39 -070042using namespace std::literals::chrono_literals;
43using std::endl;
44using std::optional;
Shawn Willden7c130392020-12-21 09:58:22 -070045using std::unique_ptr;
46using ::testing::AssertionFailure;
47using ::testing::AssertionResult;
48using ::testing::AssertionSuccess;
Seth Moore026bb742021-04-30 11:41:18 -070049using ::testing::ElementsAreArray;
David Drysdale4dc01072021-04-01 12:17:35 +010050using ::testing::MatchesRegex;
Seth Moore026bb742021-04-30 11:41:18 -070051using ::testing::Not;
Selene Huang31ab4042020-04-29 04:22:39 -070052
53::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
54 if (set.size() == 0)
55 os << "(Empty)" << ::std::endl;
56 else {
57 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070058 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070059 }
60 return os;
61}
62
63namespace test {
64
Shawn Willden7f424372021-01-10 18:06:50 -070065namespace {
David Drysdaledf8f52e2021-05-06 08:10:58 +010066
David Drysdale37af4b32021-05-14 16:46:59 +010067// Invalid value for a patchlevel (which is of form YYYYMMDD).
68const uint32_t kInvalidPatchlevel = 99998877;
69
David Drysdaledf8f52e2021-05-06 08:10:58 +010070// Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have
71// additional overhead, for the digest algorithmIdentifier required by PKCS#1.
72const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
73
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000074typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070075// Predicate for testing basic characteristics validity in generation or import.
76bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
77 const vector<KeyCharacteristics>& key_characteristics) {
78 if (key_characteristics.empty()) return false;
79
80 std::unordered_set<SecurityLevel> levels_seen;
81 for (auto& entry : key_characteristics) {
Seth Moore2a9a00e2021-08-04 16:31:52 -070082 if (entry.authorizations.empty()) {
83 GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel;
84 return false;
85 }
Shawn Willden7f424372021-01-10 18:06:50 -070086
Qi Wubeefae42021-01-28 23:16:37 +080087 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
88 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
89
Seth Moore2a9a00e2021-08-04 16:31:52 -070090 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) {
91 GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel;
92 return false;
93 }
Shawn Willden7f424372021-01-10 18:06:50 -070094 levels_seen.insert(entry.securityLevel);
95
96 // Generally, we should only have one entry, at the same security level as the KM
97 // instance. There is an exception: StrongBox KM can have some authorizations that are
98 // enforced by the TEE.
99 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
100 (secLevel == SecurityLevel::STRONGBOX &&
101 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
102
Seth Moore2a9a00e2021-08-04 16:31:52 -0700103 if (!isExpectedSecurityLevel) {
104 GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel;
105 return false;
106 }
Shawn Willden7f424372021-01-10 18:06:50 -0700107 }
108 return true;
109}
110
Shawn Willden7c130392020-12-21 09:58:22 -0700111// Extract attestation record from cert. Returned object is still part of cert; don't free it
112// separately.
113ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
114 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
115 EXPECT_TRUE(!!oid.get());
116 if (!oid.get()) return nullptr;
117
118 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
119 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
120 if (location == -1) return nullptr;
121
122 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
123 EXPECT_TRUE(!!attest_rec_ext)
124 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
125 if (!attest_rec_ext) return nullptr;
126
127 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
128 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
129 return attest_rec;
130}
131
David Drysdale7dff4fc2021-12-10 10:10:52 +0000132void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) {
133 // Version numbers in attestation extensions should be a multiple of 100.
134 EXPECT_EQ(attestation_version % 100, 0);
135
136 // The multiplier should never be higher than the AIDL version, but can be less
137 // (for example, if the implementation is from an earlier version but the HAL service
138 // uses the default libraries and so reports the current AIDL version).
139 EXPECT_TRUE((attestation_version / 100) <= aidl_version);
140}
141
Shawn Willden7c130392020-12-21 09:58:22 -0700142bool avb_verification_enabled() {
143 char value[PROPERTY_VALUE_MAX];
144 return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
145}
146
147char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
148 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
149
150// Attestations don't contain everything in key authorization lists, so we need to filter the key
151// lists to produce the lists that we expect to match the attestations.
152auto kTagsToFilter = {
David Drysdale37af4b32021-05-14 16:46:59 +0100153 Tag::CREATION_DATETIME,
154 Tag::HARDWARE_TYPE,
155 Tag::INCLUDE_UNIQUE_ID,
Shawn Willden7c130392020-12-21 09:58:22 -0700156};
157
158AuthorizationSet filtered_tags(const AuthorizationSet& set) {
159 AuthorizationSet filtered;
160 std::remove_copy_if(
161 set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool {
162 return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) !=
163 kTagsToFilter.end();
164 });
165 return filtered;
166}
167
David Drysdale300b5552021-05-20 12:05:26 +0100168// Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics.
169void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) {
170 characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(),
171 [](const auto& entry) {
172 return entry.securityLevel == SecurityLevel::KEYSTORE;
173 }),
174 characteristics->end());
175}
176
Shawn Willden7c130392020-12-21 09:58:22 -0700177string x509NameToStr(X509_NAME* name) {
178 char* s = X509_NAME_oneline(name, nullptr, 0);
179 string retval(s);
180 OPENSSL_free(s);
181 return retval;
182}
183
Shawn Willden7f424372021-01-10 18:06:50 -0700184} // namespace
185
Shawn Willden7c130392020-12-21 09:58:22 -0700186bool KeyMintAidlTestBase::arm_deleteAllKeys = false;
187bool KeyMintAidlTestBase::dump_Attestations = false;
David Drysdale9f5c0c52022-11-03 15:10:16 +0000188std::string KeyMintAidlTestBase::keyblob_dir;
Shawn Willden7c130392020-12-21 09:58:22 -0700189
David Drysdale37af4b32021-05-14 16:46:59 +0100190uint32_t KeyMintAidlTestBase::boot_patch_level(
191 const vector<KeyCharacteristics>& key_characteristics) {
192 // The boot patchlevel is not available as a property, but should be present
193 // in the key characteristics of any created key.
194 AuthorizationSet allAuths;
195 for (auto& entry : key_characteristics) {
196 allAuths.push_back(AuthorizationSet(entry.authorizations));
197 }
198 auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL);
199 if (patchlevel.has_value()) {
200 return patchlevel.value();
201 } else {
202 // No boot patchlevel is available. Return a value that won't match anything
203 // and so will trigger test failures.
204 return kInvalidPatchlevel;
205 }
206}
207
208uint32_t KeyMintAidlTestBase::boot_patch_level() {
209 return boot_patch_level(key_characteristics_);
210}
211
Prashant Patil88ad1892022-03-15 16:31:02 +0000212/**
213 * An API to determine device IDs attestation is required or not,
214 * which is mandatory for KeyMint version 2 or first_api_level 33 or greater.
215 */
216bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() {
217 return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= 33;
218}
219
Rajesh Nyamagoud5283f812023-01-06 00:27:56 +0000220/**
221 * An API to determine second IMEI ID attestation is required or not,
222 * which is supported for KeyMint version 3 or first_api_level greater than 33.
223 */
224bool KeyMintAidlTestBase::isSecondImeiIdAttestationRequired() {
225 return AidlVersion() >= 3 && property_get_int32("ro.vendor.api_level", 0) > 33;
226}
227
David Drysdale42fe1892021-10-14 14:43:46 +0100228bool KeyMintAidlTestBase::Curve25519Supported() {
229 // Strongbox never supports curve 25519.
230 if (SecLevel() == SecurityLevel::STRONGBOX) {
231 return false;
232 }
233
234 // Curve 25519 was included in version 2 of the KeyMint interface.
235 int32_t version = 0;
236 auto status = keymint_->getInterfaceVersion(&version);
237 if (!status.isOk()) {
238 ADD_FAILURE() << "Failed to determine interface version";
239 }
240 return version >= 2;
241}
242
Janis Danisevskis24c04702020-12-16 18:28:39 -0800243ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -0700244 if (result.isOk()) return ErrorCode::OK;
245
Janis Danisevskis24c04702020-12-16 18:28:39 -0800246 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
247 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700248 }
249
250 return ErrorCode::UNKNOWN_ERROR;
251}
252
Janis Danisevskis24c04702020-12-16 18:28:39 -0800253void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -0700254 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -0800255 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -0700256
257 KeyMintHardwareInfo info;
258 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
259
260 securityLevel_ = info.securityLevel;
261 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
262 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
David Drysdaled2cc8c22021-04-15 13:29:45 +0100263 timestamp_token_required_ = info.timestampTokenRequired;
Selene Huang31ab4042020-04-29 04:22:39 -0700264
265 os_version_ = getOsVersion();
266 os_patch_level_ = getOsPatchlevel();
David Drysdalebb3d85e2021-04-13 11:15:51 +0100267 vendor_patch_level_ = getVendorPatchlevel();
Selene Huang31ab4042020-04-29 04:22:39 -0700268}
269
David Drysdale7dff4fc2021-12-10 10:10:52 +0000270int32_t KeyMintAidlTestBase::AidlVersion() {
271 int32_t version = 0;
272 auto status = keymint_->getInterfaceVersion(&version);
273 if (!status.isOk()) {
274 ADD_FAILURE() << "Failed to determine interface version";
275 }
276 return version;
277}
278
Selene Huang31ab4042020-04-29 04:22:39 -0700279void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800280 if (AServiceManager_isDeclared(GetParam().c_str())) {
281 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
282 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
283 } else {
284 InitializeKeyMint(nullptr);
285 }
Selene Huang31ab4042020-04-29 04:22:39 -0700286}
287
288ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7c130392020-12-21 09:58:22 -0700289 const optional<AttestationKey>& attest_key,
Shawn Willden7f424372021-01-10 18:06:50 -0700290 vector<uint8_t>* key_blob,
Shawn Willden7c130392020-12-21 09:58:22 -0700291 vector<KeyCharacteristics>* key_characteristics,
292 vector<Certificate>* cert_chain) {
Shawn Willden7f424372021-01-10 18:06:50 -0700293 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
294 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700295 << "Previous characteristics not deleted before generating key. Test bug.";
296
Shawn Willden7f424372021-01-10 18:06:50 -0700297 KeyCreationResult creationResult;
Shawn Willden7c130392020-12-21 09:58:22 -0700298 Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700299 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700300 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
301 creationResult.keyCharacteristics);
302 EXPECT_GT(creationResult.keyBlob.size(), 0);
303 *key_blob = std::move(creationResult.keyBlob);
304 *key_characteristics = std::move(creationResult.keyCharacteristics);
Shawn Willden7c130392020-12-21 09:58:22 -0700305 *cert_chain = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700306
307 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
308 EXPECT_TRUE(algorithm);
309 if (algorithm &&
310 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
Shawn Willden7c130392020-12-21 09:58:22 -0700311 EXPECT_GE(cert_chain->size(), 1);
312 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) {
313 if (attest_key) {
314 EXPECT_EQ(cert_chain->size(), 1);
315 } else {
316 EXPECT_GT(cert_chain->size(), 1);
317 }
318 }
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700319 } else {
320 // For symmetric keys there should be no certificates.
Shawn Willden7c130392020-12-21 09:58:22 -0700321 EXPECT_EQ(cert_chain->size(), 0);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700322 }
Selene Huang31ab4042020-04-29 04:22:39 -0700323 }
324
325 return GetReturnErrorCode(result);
326}
327
Shawn Willden7c130392020-12-21 09:58:22 -0700328ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
329 const optional<AttestationKey>& attest_key) {
330 return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_);
Selene Huang31ab4042020-04-29 04:22:39 -0700331}
332
subrahmanyaman7d9bc462022-03-16 01:40:39 +0000333ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey(
334 const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc,
335 vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics,
336 vector<Certificate>* cert_chain) {
337 AttestationKey attest_key;
338 vector<Certificate> attest_cert_chain;
339 vector<KeyCharacteristics> attest_key_characteristics;
340 // Generate a key with self signed attestation.
341 auto error = GenerateKey(attest_key_desc, std::nullopt, &attest_key.keyBlob,
342 &attest_key_characteristics, &attest_cert_chain);
343 if (error != ErrorCode::OK) {
344 return error;
345 }
346
347 attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
348 // Generate a key, by passing the above self signed attestation key as attest key.
349 error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain);
350 if (error == ErrorCode::OK) {
351 // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain.
352 cert_chain->push_back(attest_cert_chain[0]);
353 }
354 return error;
355}
356
Selene Huang31ab4042020-04-29 04:22:39 -0700357ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
358 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700359 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700360 Status result;
361
Shawn Willden7f424372021-01-10 18:06:50 -0700362 cert_chain_.clear();
363 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700364 key_blob->clear();
365
Shawn Willden7f424372021-01-10 18:06:50 -0700366 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700367 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700368 vector<uint8_t>(key_material.begin(), key_material.end()),
Shawn Willden7c130392020-12-21 09:58:22 -0700369 {} /* attestationSigningKeyBlob */, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700370
371 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700372 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
373 creationResult.keyCharacteristics);
374 EXPECT_GT(creationResult.keyBlob.size(), 0);
375
376 *key_blob = std::move(creationResult.keyBlob);
377 *key_characteristics = std::move(creationResult.keyCharacteristics);
378 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700379
380 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
381 EXPECT_TRUE(algorithm);
382 if (algorithm &&
383 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
384 EXPECT_GE(cert_chain_.size(), 1);
385 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
386 } else {
387 // For symmetric keys there should be no certificates.
388 EXPECT_EQ(cert_chain_.size(), 0);
389 }
Selene Huang31ab4042020-04-29 04:22:39 -0700390 }
391
392 return GetReturnErrorCode(result);
393}
394
395ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
396 const string& key_material) {
397 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
398}
399
400ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
401 const AuthorizationSet& wrapping_key_desc,
402 string masking_key,
David Drysdaled2cc8c22021-04-15 13:29:45 +0100403 const AuthorizationSet& unwrapping_params,
404 int64_t password_sid, int64_t biometric_sid) {
Selene Huang31ab4042020-04-29 04:22:39 -0700405 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
406
Shawn Willden7f424372021-01-10 18:06:50 -0700407 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700408
Shawn Willden7f424372021-01-10 18:06:50 -0700409 KeyCreationResult creationResult;
410 Status result = keymint_->importWrappedKey(
411 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
412 vector<uint8_t>(masking_key.begin(), masking_key.end()),
David Drysdaled2cc8c22021-04-15 13:29:45 +0100413 unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700414
415 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700416 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
417 creationResult.keyCharacteristics);
418 EXPECT_GT(creationResult.keyBlob.size(), 0);
419
420 key_blob_ = std::move(creationResult.keyBlob);
421 key_characteristics_ = std::move(creationResult.keyCharacteristics);
422 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700423
424 AuthorizationSet allAuths;
425 for (auto& entry : key_characteristics_) {
426 allAuths.push_back(AuthorizationSet(entry.authorizations));
427 }
428 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
429 EXPECT_TRUE(algorithm);
430 if (algorithm &&
431 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
432 EXPECT_GE(cert_chain_.size(), 1);
433 } else {
434 // For symmetric keys there should be no certificates.
435 EXPECT_EQ(cert_chain_.size(), 0);
436 }
Selene Huang31ab4042020-04-29 04:22:39 -0700437 }
438
439 return GetReturnErrorCode(result);
440}
441
David Drysdale300b5552021-05-20 12:05:26 +0100442ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
443 const vector<uint8_t>& app_id,
444 const vector<uint8_t>& app_data,
445 vector<KeyCharacteristics>* key_characteristics) {
446 Status result =
447 keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics);
448 return GetReturnErrorCode(result);
449}
450
451ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob,
452 vector<KeyCharacteristics>* key_characteristics) {
453 vector<uint8_t> empty_app_id, empty_app_data;
454 return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics);
455}
456
457void KeyMintAidlTestBase::CheckCharacteristics(
458 const vector<uint8_t>& key_blob,
459 const vector<KeyCharacteristics>& generate_characteristics) {
460 // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from
461 // generateKey() should be excluded, as KeyMint will have no record of them.
462 // This applies to CREATION_DATETIME in particular.
463 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
464 strip_keystore_tags(&expected_characteristics);
465
466 vector<KeyCharacteristics> retrieved;
467 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved));
468 EXPECT_EQ(expected_characteristics, retrieved);
469}
470
471void KeyMintAidlTestBase::CheckAppIdCharacteristics(
472 const vector<uint8_t>& key_blob, std::string_view app_id_string,
473 std::string_view app_data_string,
474 const vector<KeyCharacteristics>& generate_characteristics) {
475 // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons.
476 vector<KeyCharacteristics> expected_characteristics(generate_characteristics);
477 strip_keystore_tags(&expected_characteristics);
478
479 vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end());
480 vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end());
481 vector<KeyCharacteristics> retrieved;
482 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved));
483 EXPECT_EQ(expected_characteristics, retrieved);
484
485 // Check that key characteristics can't be retrieved if the app ID or app data is missing.
486 vector<uint8_t> empty;
487 vector<KeyCharacteristics> not_retrieved;
488 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
489 GetCharacteristics(key_blob, empty, app_data, &not_retrieved));
490 EXPECT_EQ(not_retrieved.size(), 0);
491
492 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
493 GetCharacteristics(key_blob, app_id, empty, &not_retrieved));
494 EXPECT_EQ(not_retrieved.size(), 0);
495
496 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
497 GetCharacteristics(key_blob, empty, empty, &not_retrieved));
498 EXPECT_EQ(not_retrieved.size(), 0);
499}
500
Selene Huang31ab4042020-04-29 04:22:39 -0700501ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
502 Status result = keymint_->deleteKey(*key_blob);
503 if (!keep_key_blob) {
504 *key_blob = vector<uint8_t>();
505 }
506
Janis Danisevskis24c04702020-12-16 18:28:39 -0800507 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700508 return GetReturnErrorCode(result);
509}
510
511ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
512 return DeleteKey(&key_blob_, keep_key_blob);
513}
514
515ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
516 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800517 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700518 return GetReturnErrorCode(result);
519}
520
David Drysdaled2cc8c22021-04-15 13:29:45 +0100521ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() {
522 Status result = keymint_->destroyAttestationIds();
523 return GetReturnErrorCode(result);
524}
525
Selene Huang31ab4042020-04-29 04:22:39 -0700526void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
527 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
528 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
529}
530
531void KeyMintAidlTestBase::CheckedDeleteKey() {
532 CheckedDeleteKey(&key_blob_);
533}
534
535ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
536 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800537 AuthorizationSet* out_params,
538 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700539 SCOPED_TRACE("Begin");
540 Status result;
541 BeginResult out;
David Drysdale56ba9122021-04-19 19:10:47 +0100542 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700543
544 if (result.isOk()) {
545 *out_params = out.params;
546 challenge_ = out.challenge;
547 op = out.operation;
548 }
549
550 return GetReturnErrorCode(result);
551}
552
553ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
554 const AuthorizationSet& in_params,
555 AuthorizationSet* out_params) {
556 SCOPED_TRACE("Begin");
557 Status result;
558 BeginResult out;
559
David Drysdale56ba9122021-04-19 19:10:47 +0100560 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out);
Selene Huang31ab4042020-04-29 04:22:39 -0700561
562 if (result.isOk()) {
563 *out_params = out.params;
564 challenge_ = out.challenge;
565 op_ = out.operation;
566 }
567
568 return GetReturnErrorCode(result);
569}
570
571ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
572 AuthorizationSet* out_params) {
573 SCOPED_TRACE("Begin");
574 EXPECT_EQ(nullptr, op_);
575 return Begin(purpose, key_blob_, in_params, out_params);
576}
577
578ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
579 SCOPED_TRACE("Begin");
580 AuthorizationSet out_params;
581 ErrorCode result = Begin(purpose, in_params, &out_params);
582 EXPECT_TRUE(out_params.empty());
583 return result;
584}
585
Shawn Willden92d79c02021-02-19 07:31:55 -0700586ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) {
587 return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()),
588 {} /* hardwareAuthToken */,
589 {} /* verificationToken */));
590}
591
592ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) {
Selene Huang31ab4042020-04-29 04:22:39 -0700593 SCOPED_TRACE("Update");
594
595 Status result;
Shawn Willden92d79c02021-02-19 07:31:55 -0700596 if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700597
Brian J Murrayeabd9d62022-01-06 15:13:51 -0800598 EXPECT_NE(op_, nullptr);
599 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
600
Shawn Willden92d79c02021-02-19 07:31:55 -0700601 std::vector<uint8_t> o_put;
602 result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put);
Selene Huang31ab4042020-04-29 04:22:39 -0700603
David Drysdalefeab5d92022-01-06 15:46:23 +0000604 if (result.isOk()) {
605 output->append(o_put.begin(), o_put.end());
606 } else {
607 // Failure always terminates the operation.
608 op_ = {};
609 }
Selene Huang31ab4042020-04-29 04:22:39 -0700610
611 return GetReturnErrorCode(result);
612}
613
Shawn Willden92d79c02021-02-19 07:31:55 -0700614ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature,
Selene Huang31ab4042020-04-29 04:22:39 -0700615 string* output) {
616 SCOPED_TRACE("Finish");
617 Status result;
618
619 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700620 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700621
622 vector<uint8_t> oPut;
Shawn Willden92d79c02021-02-19 07:31:55 -0700623 result = op_->finish(vector<uint8_t>(input.begin(), input.end()),
624 vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */,
625 {} /* timestampToken */, {} /* confirmationToken */, &oPut);
Selene Huang31ab4042020-04-29 04:22:39 -0700626
Shawn Willden92d79c02021-02-19 07:31:55 -0700627 if (result.isOk()) output->append(oPut.begin(), oPut.end());
Selene Huang31ab4042020-04-29 04:22:39 -0700628
Shawn Willden92d79c02021-02-19 07:31:55 -0700629 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700630 return GetReturnErrorCode(result);
631}
632
Janis Danisevskis24c04702020-12-16 18:28:39 -0800633ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700634 SCOPED_TRACE("Abort");
635
636 EXPECT_NE(op, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700637 if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700638
639 Status retval = op->abort();
640 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800641 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700642}
643
644ErrorCode KeyMintAidlTestBase::Abort() {
645 SCOPED_TRACE("Abort");
646
647 EXPECT_NE(op_, nullptr);
Shawn Willden92d79c02021-02-19 07:31:55 -0700648 if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER;
Selene Huang31ab4042020-04-29 04:22:39 -0700649
650 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800651 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700652}
653
654void KeyMintAidlTestBase::AbortIfNeeded() {
655 SCOPED_TRACE("AbortIfNeeded");
656 if (op_) {
657 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800658 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700659 }
660}
661
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000662auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
663 const string& message, const AuthorizationSet& in_params)
Shawn Willden92d79c02021-02-19 07:31:55 -0700664 -> std::tuple<ErrorCode, string> {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000665 AuthorizationSet begin_out_params;
666 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
Shawn Willden92d79c02021-02-19 07:31:55 -0700667 if (result != ErrorCode::OK) return {result, {}};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000668
669 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700670 return {Finish(message, &output), output};
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000671}
672
Selene Huang31ab4042020-04-29 04:22:39 -0700673string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
674 const string& message, const AuthorizationSet& in_params,
675 AuthorizationSet* out_params) {
676 SCOPED_TRACE("ProcessMessage");
677 AuthorizationSet begin_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -0700678 ErrorCode result = Begin(operation, key_blob, in_params, out_params);
Selene Huang31ab4042020-04-29 04:22:39 -0700679 EXPECT_EQ(ErrorCode::OK, result);
680 if (result != ErrorCode::OK) {
681 return "";
682 }
683
684 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700685 EXPECT_EQ(ErrorCode::OK, Finish(message, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700686 return output;
687}
688
689string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
690 const AuthorizationSet& params) {
691 SCOPED_TRACE("SignMessage");
692 AuthorizationSet out_params;
693 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
694 EXPECT_TRUE(out_params.empty());
695 return signature;
696}
697
698string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
699 SCOPED_TRACE("SignMessage");
700 return SignMessage(key_blob_, message, params);
701}
702
703string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
704 SCOPED_TRACE("MacMessage");
705 return SignMessage(
706 key_blob_, message,
707 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
708}
709
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530710void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
711 int message_size) {
David Drysdale1a637192022-03-14 09:11:29 +0000712 auto builder = AuthorizationSetBuilder()
713 .Authorization(TAG_NO_AUTH_REQUIRED)
714 .AesEncryptionKey(128)
715 .BlockMode(block_mode)
716 .Padding(PaddingMode::NONE);
717 if (block_mode == BlockMode::GCM) {
718 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
719 }
720 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
anil.hiranniah19a4ca12022-03-03 17:39:30 +0530721
722 for (int increment = 1; increment <= message_size; ++increment) {
723 string message(message_size, 'a');
724 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
725 if (block_mode == BlockMode::GCM) {
726 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
727 }
728
729 AuthorizationSet output_params;
730 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
731
732 string ciphertext;
733 string to_send;
734 for (size_t i = 0; i < message.size(); i += increment) {
735 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
736 }
737 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
738 << "Error sending " << to_send << " with block mode " << block_mode;
739
740 switch (block_mode) {
741 case BlockMode::GCM:
742 EXPECT_EQ(message.size() + 16, ciphertext.size());
743 break;
744 case BlockMode::CTR:
745 EXPECT_EQ(message.size(), ciphertext.size());
746 break;
747 case BlockMode::CBC:
748 case BlockMode::ECB:
749 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
750 break;
751 }
752
753 auto iv = output_params.GetTagValue(TAG_NONCE);
754 switch (block_mode) {
755 case BlockMode::CBC:
756 case BlockMode::GCM:
757 case BlockMode::CTR:
758 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
759 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
760 params.push_back(TAG_NONCE, iv->get());
761 break;
762
763 case BlockMode::ECB:
764 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
765 break;
766 }
767
768 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
769 << "Decrypt begin() failed for block mode " << block_mode;
770
771 string plaintext;
772 for (size_t i = 0; i < ciphertext.size(); i += increment) {
773 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
774 }
775 ErrorCode error = Finish(to_send, &plaintext);
776 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
777 << " and increment " << increment;
778 if (error == ErrorCode::OK) {
779 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
780 << " and increment " << increment;
781 }
782 }
783}
784
Prashant Patildd5f7f02022-07-06 18:58:07 +0000785void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode,
786 PaddingMode padding_mode, const string& iv,
787 const string& plaintext,
788 const string& exp_cipher_text) {
789 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
790 auto auth_set = AuthorizationSetBuilder()
791 .Authorization(TAG_NO_AUTH_REQUIRED)
792 .AesEncryptionKey(key.size() * 8)
793 .BlockMode(block_mode)
794 .Padding(padding_mode);
795 if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE);
796 if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128);
797 ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key));
798
799 CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext,
800 exp_cipher_text);
801}
802
803void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size,
804 PaddingMode padding_mode, const string& iv,
805 const string& plaintext,
806 const string& exp_cipher_text) {
807 bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM);
808 bool is_authenticated_cipher = (block_mode == BlockMode::GCM);
809 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
810 if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size());
811 if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128);
812
813 AuthorizationSet output_params;
814 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
815
816 string actual_ciphertext;
817 if (is_stream_cipher) {
818 // Assert that a 1 byte of output is produced for 1 byte of input.
819 // Every input byte produces an output byte.
820 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
821 string ciphertext;
822 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
823 // Some StrongBox implementations cannot support 1:1 input:output lengths, so
824 // we relax this API restriction for them.
825 if (SecLevel() != SecurityLevel::STRONGBOX) {
826 EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index;
827 }
828 actual_ciphertext.append(ciphertext);
829 }
830 string ciphertext;
831 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
832 if (SecLevel() != SecurityLevel::STRONGBOX) {
833 string expected_final_output;
834 if (is_authenticated_cipher) {
835 expected_final_output = exp_cipher_text.substr(plaintext.size());
836 }
837 EXPECT_EQ(expected_final_output, ciphertext);
838 }
839 actual_ciphertext.append(ciphertext);
840 } else {
841 // Assert that a block of output is produced once a full block of input is provided.
842 // Every input block produces an output block.
843 bool compare_output = true;
844 string additional_information;
845 int vendor_api_level = property_get_int32("ro.vendor.api_level", 0);
846 if (SecLevel() == SecurityLevel::STRONGBOX) {
847 // This is known to be broken on older vendor implementations.
848 if (vendor_api_level < 33) {
849 compare_output = false;
850 } else {
851 additional_information = " (b/194134359) ";
852 }
853 }
854 for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) {
855 string ciphertext;
856 EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext));
857 if (compare_output) {
858 if ((plaintext_index % block_size) == block_size - 1) {
859 // Update is expected to have output a new block
860 EXPECT_EQ(block_size, ciphertext.size())
861 << "plaintext index: " << plaintext_index << additional_information;
862 } else {
863 // Update is expected to have produced no output
864 EXPECT_EQ(0, ciphertext.size())
865 << "plaintext index: " << plaintext_index << additional_information;
866 }
867 }
868 actual_ciphertext.append(ciphertext);
869 }
870 string ciphertext;
871 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
872 actual_ciphertext.append(ciphertext);
873 }
874 // Regardless of how the completed ciphertext got accumulated, it should match the expected
875 // ciphertext.
876 EXPECT_EQ(exp_cipher_text, actual_ciphertext);
877}
878
Selene Huang31ab4042020-04-29 04:22:39 -0700879void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
880 Digest digest, const string& expected_mac) {
881 SCOPED_TRACE("CheckHmacTestVector");
882 ASSERT_EQ(ErrorCode::OK,
883 ImportKey(AuthorizationSetBuilder()
884 .Authorization(TAG_NO_AUTH_REQUIRED)
885 .HmacKey(key.size() * 8)
886 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
887 .Digest(digest),
888 KeyFormat::RAW, key));
889 string signature = MacMessage(message, digest, expected_mac.size() * 8);
890 EXPECT_EQ(expected_mac, signature)
891 << "Test vector didn't match for key of size " << key.size() << " message of size "
892 << message.size() << " and digest " << digest;
893 CheckedDeleteKey();
894}
895
896void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
897 const string& message,
898 const string& expected_ciphertext) {
899 SCOPED_TRACE("CheckAesCtrTestVector");
900 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
901 .Authorization(TAG_NO_AUTH_REQUIRED)
902 .AesEncryptionKey(key.size() * 8)
903 .BlockMode(BlockMode::CTR)
904 .Authorization(TAG_CALLER_NONCE)
905 .Padding(PaddingMode::NONE),
906 KeyFormat::RAW, key));
907
908 auto params = AuthorizationSetBuilder()
909 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
910 .BlockMode(BlockMode::CTR)
911 .Padding(PaddingMode::NONE);
912 AuthorizationSet out_params;
913 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
914 EXPECT_EQ(expected_ciphertext, ciphertext);
915}
916
917void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
918 PaddingMode padding_mode, const string& key,
919 const string& iv, const string& input,
920 const string& expected_output) {
921 auto authset = AuthorizationSetBuilder()
922 .TripleDesEncryptionKey(key.size() * 7)
923 .BlockMode(block_mode)
924 .Authorization(TAG_NO_AUTH_REQUIRED)
925 .Padding(padding_mode);
926 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
927 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
928 ASSERT_GT(key_blob_.size(), 0U);
929
930 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
931 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
932 AuthorizationSet output_params;
933 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
934 EXPECT_EQ(expected_output, output);
935}
936
937void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
938 const string& signature, const AuthorizationSet& params) {
939 SCOPED_TRACE("VerifyMessage");
940 AuthorizationSet begin_out_params;
941 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
942
943 string output;
Shawn Willden92d79c02021-02-19 07:31:55 -0700944 EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output));
Selene Huang31ab4042020-04-29 04:22:39 -0700945 EXPECT_TRUE(output.empty());
Shawn Willden92d79c02021-02-19 07:31:55 -0700946 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -0700947}
948
949void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
950 const AuthorizationSet& params) {
951 SCOPED_TRACE("VerifyMessage");
952 VerifyMessage(key_blob_, message, signature, params);
953}
954
David Drysdaledf8f52e2021-05-06 08:10:58 +0100955void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature,
956 const AuthorizationSet& params) {
957 SCOPED_TRACE("LocalVerifyMessage");
958
David Drysdaledf8f52e2021-05-06 08:10:58 +0100959 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale9f5c0c52022-11-03 15:10:16 +0000960 LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params);
961}
962
963void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message,
964 const string& signature,
965 const AuthorizationSet& params) {
966 // Retrieve the public key from the leaf certificate.
967 X509_Ptr key_cert(parse_cert_blob(der_cert));
David Drysdaledf8f52e2021-05-06 08:10:58 +0100968 ASSERT_TRUE(key_cert.get());
969 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
970 ASSERT_TRUE(pub_key.get());
971
972 Digest digest = params.GetTagValue(TAG_DIGEST).value();
973 PaddingMode padding = PaddingMode::NONE;
974 auto tag = params.GetTagValue(TAG_PADDING);
975 if (tag.has_value()) {
976 padding = tag.value();
977 }
978
979 if (digest == Digest::NONE) {
980 switch (EVP_PKEY_id(pub_key.get())) {
David Drysdale42fe1892021-10-14 14:43:46 +0100981 case EVP_PKEY_ED25519: {
982 ASSERT_EQ(64, signature.size());
983 uint8_t pub_keydata[32];
984 size_t pub_len = sizeof(pub_keydata);
985 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len));
986 ASSERT_EQ(sizeof(pub_keydata), pub_len);
987 ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()),
988 message.size(),
989 reinterpret_cast<const uint8_t*>(signature.data()),
990 pub_keydata));
991 break;
992 }
993
David Drysdaledf8f52e2021-05-06 08:10:58 +0100994 case EVP_PKEY_EC: {
995 vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8);
996 size_t data_size = std::min(data.size(), message.size());
997 memcpy(data.data(), message.data(), data_size);
998 EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get()));
999 ASSERT_TRUE(ecdsa.get());
1000 ASSERT_EQ(1,
1001 ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size,
1002 reinterpret_cast<const uint8_t*>(signature.data()),
1003 signature.size(), ecdsa.get()));
1004 break;
1005 }
1006 case EVP_PKEY_RSA: {
1007 vector<uint8_t> data(EVP_PKEY_size(pub_key.get()));
1008 size_t data_size = std::min(data.size(), message.size());
1009 memcpy(data.data(), message.data(), data_size);
1010
1011 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
1012 ASSERT_TRUE(rsa.get());
1013
1014 size_t key_len = RSA_size(rsa.get());
1015 int openssl_padding = RSA_NO_PADDING;
1016 switch (padding) {
1017 case PaddingMode::NONE:
1018 ASSERT_TRUE(data_size <= key_len);
1019 ASSERT_EQ(key_len, signature.size());
1020 openssl_padding = RSA_NO_PADDING;
1021 break;
1022 case PaddingMode::RSA_PKCS1_1_5_SIGN:
1023 ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <=
1024 key_len);
1025 openssl_padding = RSA_PKCS1_PADDING;
1026 break;
1027 default:
1028 ADD_FAILURE() << "Unsupported RSA padding mode " << padding;
1029 }
1030
1031 vector<uint8_t> decrypted_data(key_len);
1032 int bytes_decrypted = RSA_public_decrypt(
1033 signature.size(), reinterpret_cast<const uint8_t*>(signature.data()),
1034 decrypted_data.data(), rsa.get(), openssl_padding);
1035 ASSERT_GE(bytes_decrypted, 0);
1036
1037 const uint8_t* compare_pos = decrypted_data.data();
1038 size_t bytes_to_compare = bytes_decrypted;
1039 uint8_t zero_check_result = 0;
1040 if (padding == PaddingMode::NONE && data_size < bytes_to_compare) {
1041 // If the data is short, for "unpadded" signing we zero-pad to the left. So
1042 // during verification we should have zeros on the left of the decrypted data.
1043 // Do a constant-time check.
1044 const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size;
1045 while (compare_pos < zero_end) zero_check_result |= *compare_pos++;
1046 ASSERT_EQ(0, zero_check_result);
1047 bytes_to_compare = data_size;
1048 }
1049 ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare));
1050 break;
1051 }
1052 default:
1053 ADD_FAILURE() << "Unknown public key type";
1054 }
1055 } else {
1056 EVP_MD_CTX digest_ctx;
1057 EVP_MD_CTX_init(&digest_ctx);
1058 EVP_PKEY_CTX* pkey_ctx;
1059 const EVP_MD* md = openssl_digest(digest);
1060 ASSERT_NE(md, nullptr);
1061 ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get()));
1062
1063 if (padding == PaddingMode::RSA_PSS) {
1064 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1065 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
David Drysdalec6b89072021-12-14 14:32:51 +00001066 EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0);
David Drysdaledf8f52e2021-05-06 08:10:58 +01001067 }
1068
1069 ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx,
1070 reinterpret_cast<const uint8_t*>(message.data()),
1071 message.size()));
1072 ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1073 reinterpret_cast<const uint8_t*>(signature.data()),
1074 signature.size()));
1075 EVP_MD_CTX_cleanup(&digest_ctx);
1076 }
1077}
1078
David Drysdale59cae642021-05-12 13:52:03 +01001079string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message,
1080 const AuthorizationSet& params) {
1081 SCOPED_TRACE("LocalRsaEncryptMessage");
1082
1083 // Retrieve the public key from the leaf certificate.
1084 if (cert_chain_.empty()) {
1085 ADD_FAILURE() << "No public key available";
1086 return "Failure";
1087 }
1088 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
David Drysdaleb97121d2022-08-12 11:54:08 +01001089 if (key_cert.get() == nullptr) {
1090 ADD_FAILURE() << "Failed to parse cert";
1091 return "Failure";
1092 }
David Drysdale59cae642021-05-12 13:52:03 +01001093 EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get()));
David Drysdaleb97121d2022-08-12 11:54:08 +01001094 if (pub_key.get() == nullptr) {
1095 ADD_FAILURE() << "Failed to retrieve public key";
1096 return "Failure";
1097 }
David Drysdale59cae642021-05-12 13:52:03 +01001098 RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get())));
David Drysdaleb97121d2022-08-12 11:54:08 +01001099 if (rsa.get() == nullptr) {
1100 ADD_FAILURE() << "Failed to retrieve RSA public key";
1101 return "Failure";
1102 }
David Drysdale59cae642021-05-12 13:52:03 +01001103
1104 // Retrieve relevant tags.
1105 Digest digest = Digest::NONE;
David Drysdaleae3727b2021-11-11 09:00:14 +00001106 Digest mgf_digest = Digest::SHA1;
David Drysdale59cae642021-05-12 13:52:03 +01001107 PaddingMode padding = PaddingMode::NONE;
1108
1109 auto digest_tag = params.GetTagValue(TAG_DIGEST);
1110 if (digest_tag.has_value()) digest = digest_tag.value();
1111 auto pad_tag = params.GetTagValue(TAG_PADDING);
1112 if (pad_tag.has_value()) padding = pad_tag.value();
1113 auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST);
1114 if (mgf_tag.has_value()) mgf_digest = mgf_tag.value();
1115
1116 const EVP_MD* md = openssl_digest(digest);
1117 const EVP_MD* mgf_md = openssl_digest(mgf_digest);
1118
1119 // Set up encryption context.
1120 EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr));
1121 if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) {
1122 ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error();
1123 return "Failure";
1124 }
1125
1126 int rc = -1;
1127 switch (padding) {
1128 case PaddingMode::NONE:
1129 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
1130 break;
1131 case PaddingMode::RSA_PKCS1_1_5_ENCRYPT:
1132 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING);
1133 break;
1134 case PaddingMode::RSA_OAEP:
1135 rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING);
1136 break;
1137 default:
1138 break;
1139 }
1140 if (rc <= 0) {
1141 ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error();
1142 return "Failure";
1143 }
1144 if (padding == PaddingMode::RSA_OAEP) {
1145 if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) {
1146 ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error();
1147 return "Failure";
1148 }
1149 if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) {
1150 ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error();
1151 return "Failure";
1152 }
1153 }
1154
1155 // Determine output size.
1156 size_t outlen;
1157 if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen,
1158 reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) {
1159 ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error();
1160 return "Failure";
1161 }
1162
1163 // Left-zero-pad the input if necessary.
1164 const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data());
1165 size_t to_encrypt_len = message.size();
1166
1167 std::unique_ptr<string> zero_padded_message;
1168 if (padding == PaddingMode::NONE && to_encrypt_len < outlen) {
1169 zero_padded_message.reset(new string(outlen, '\0'));
1170 memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(),
1171 message.size());
1172 to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data());
1173 to_encrypt_len = outlen;
1174 }
1175
1176 // Do the encryption.
1177 string output(outlen, '\0');
1178 if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt,
1179 to_encrypt_len) <= 0) {
1180 ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error();
1181 return "Failure";
1182 }
1183 return output;
1184}
1185
Selene Huang31ab4042020-04-29 04:22:39 -07001186string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
1187 const AuthorizationSet& in_params,
1188 AuthorizationSet* out_params) {
1189 SCOPED_TRACE("EncryptMessage");
1190 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
1191}
1192
1193string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
1194 AuthorizationSet* out_params) {
1195 SCOPED_TRACE("EncryptMessage");
1196 return EncryptMessage(key_blob_, message, params, out_params);
1197}
1198
1199string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
1200 SCOPED_TRACE("EncryptMessage");
1201 AuthorizationSet out_params;
1202 string ciphertext = EncryptMessage(message, params, &out_params);
1203 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1204 return ciphertext;
1205}
1206
1207string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1208 PaddingMode padding) {
1209 SCOPED_TRACE("EncryptMessage");
1210 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1211 AuthorizationSet out_params;
1212 string ciphertext = EncryptMessage(message, params, &out_params);
1213 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
1214 return ciphertext;
1215}
1216
1217string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1218 PaddingMode padding, vector<uint8_t>* iv_out) {
1219 SCOPED_TRACE("EncryptMessage");
1220 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
1221 AuthorizationSet out_params;
1222 string ciphertext = EncryptMessage(message, params, &out_params);
1223 EXPECT_EQ(1U, out_params.size());
1224 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08001225 EXPECT_TRUE(ivVal);
1226 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -07001227 return ciphertext;
1228}
1229
1230string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1231 PaddingMode padding, const vector<uint8_t>& iv_in) {
1232 SCOPED_TRACE("EncryptMessage");
1233 auto params = AuthorizationSetBuilder()
1234 .BlockMode(block_mode)
1235 .Padding(padding)
1236 .Authorization(TAG_NONCE, iv_in);
1237 AuthorizationSet out_params;
1238 string ciphertext = EncryptMessage(message, params, &out_params);
1239 return ciphertext;
1240}
1241
1242string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1243 PaddingMode padding, uint8_t mac_length_bits,
1244 const vector<uint8_t>& iv_in) {
1245 SCOPED_TRACE("EncryptMessage");
1246 auto params = AuthorizationSetBuilder()
1247 .BlockMode(block_mode)
1248 .Padding(padding)
1249 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
1250 .Authorization(TAG_NONCE, iv_in);
1251 AuthorizationSet out_params;
1252 string ciphertext = EncryptMessage(message, params, &out_params);
1253 return ciphertext;
1254}
1255
David Drysdaled2cc8c22021-04-15 13:29:45 +01001256string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
1257 PaddingMode padding, uint8_t mac_length_bits) {
1258 SCOPED_TRACE("EncryptMessage");
1259 auto params = AuthorizationSetBuilder()
1260 .BlockMode(block_mode)
1261 .Padding(padding)
1262 .Authorization(TAG_MAC_LENGTH, mac_length_bits);
1263 AuthorizationSet out_params;
1264 string ciphertext = EncryptMessage(message, params, &out_params);
1265 return ciphertext;
1266}
1267
Selene Huang31ab4042020-04-29 04:22:39 -07001268string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
1269 const string& ciphertext,
1270 const AuthorizationSet& params) {
1271 SCOPED_TRACE("DecryptMessage");
1272 AuthorizationSet out_params;
1273 string plaintext =
1274 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
1275 EXPECT_TRUE(out_params.empty());
1276 return plaintext;
1277}
1278
1279string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
1280 const AuthorizationSet& params) {
1281 SCOPED_TRACE("DecryptMessage");
1282 return DecryptMessage(key_blob_, ciphertext, params);
1283}
1284
1285string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
1286 PaddingMode padding_mode, const vector<uint8_t>& iv) {
1287 SCOPED_TRACE("DecryptMessage");
1288 auto params = AuthorizationSetBuilder()
1289 .BlockMode(block_mode)
1290 .Padding(padding_mode)
1291 .Authorization(TAG_NONCE, iv);
1292 return DecryptMessage(key_blob_, ciphertext, params);
1293}
1294
1295std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
1296 const vector<uint8_t>& key_blob) {
1297 std::pair<ErrorCode, vector<uint8_t>> retval;
1298 vector<uint8_t> outKeyBlob;
1299 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
1300 ErrorCode errorcode = GetReturnErrorCode(result);
1301 retval = std::tie(errorcode, outKeyBlob);
1302
1303 return retval;
1304}
1305vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
1306 switch (algorithm) {
1307 case Algorithm::RSA:
1308 switch (SecLevel()) {
1309 case SecurityLevel::SOFTWARE:
1310 case SecurityLevel::TRUSTED_ENVIRONMENT:
1311 return {2048, 3072, 4096};
1312 case SecurityLevel::STRONGBOX:
1313 return {2048};
1314 default:
1315 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1316 break;
1317 }
1318 break;
1319 case Algorithm::EC:
David Drysdaledf09e542021-06-08 15:46:11 +01001320 ADD_FAILURE() << "EC keys must be specified by curve not size";
Selene Huang31ab4042020-04-29 04:22:39 -07001321 break;
1322 case Algorithm::AES:
1323 return {128, 256};
1324 case Algorithm::TRIPLE_DES:
1325 return {168};
1326 case Algorithm::HMAC: {
1327 vector<uint32_t> retval((512 - 64) / 8 + 1);
1328 uint32_t size = 64 - 8;
1329 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
1330 return retval;
1331 }
1332 default:
1333 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
1334 return {};
1335 }
1336 ADD_FAILURE() << "Should be impossible to get here";
1337 return {};
1338}
1339
1340vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
1341 if (SecLevel() == SecurityLevel::STRONGBOX) {
1342 switch (algorithm) {
1343 case Algorithm::RSA:
1344 return {3072, 4096};
1345 case Algorithm::EC:
1346 return {224, 384, 521};
1347 case Algorithm::AES:
1348 return {192};
David Drysdale7de9feb2021-03-05 14:56:19 +00001349 case Algorithm::TRIPLE_DES:
1350 return {56};
1351 default:
1352 return {};
1353 }
1354 } else {
1355 switch (algorithm) {
Prashant Patild72b3512021-11-16 08:19:19 +00001356 case Algorithm::AES:
1357 return {64, 96, 131, 512};
David Drysdale7de9feb2021-03-05 14:56:19 +00001358 case Algorithm::TRIPLE_DES:
1359 return {56};
Selene Huang31ab4042020-04-29 04:22:39 -07001360 default:
1361 return {};
1362 }
1363 }
1364 return {};
1365}
1366
David Drysdale7de9feb2021-03-05 14:56:19 +00001367vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) {
1368 switch (algorithm) {
1369 case Algorithm::AES:
1370 return {
1371 BlockMode::CBC,
1372 BlockMode::CTR,
1373 BlockMode::ECB,
1374 BlockMode::GCM,
1375 };
1376 case Algorithm::TRIPLE_DES:
1377 return {
1378 BlockMode::CBC,
1379 BlockMode::ECB,
1380 };
1381 default:
1382 return {};
1383 }
1384}
1385
1386vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm,
1387 BlockMode blockMode) {
1388 switch (algorithm) {
1389 case Algorithm::AES:
1390 switch (blockMode) {
1391 case BlockMode::CBC:
1392 case BlockMode::ECB:
1393 return {PaddingMode::NONE, PaddingMode::PKCS7};
1394 case BlockMode::CTR:
1395 case BlockMode::GCM:
1396 return {PaddingMode::NONE};
1397 default:
1398 return {};
1399 };
1400 case Algorithm::TRIPLE_DES:
1401 switch (blockMode) {
1402 case BlockMode::CBC:
1403 case BlockMode::ECB:
1404 return {PaddingMode::NONE, PaddingMode::PKCS7};
1405 default:
1406 return {};
1407 };
1408 default:
1409 return {};
1410 }
1411}
1412
1413vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm,
1414 BlockMode blockMode) {
1415 switch (algorithm) {
1416 case Algorithm::AES:
1417 switch (blockMode) {
1418 case BlockMode::CTR:
1419 case BlockMode::GCM:
1420 return {PaddingMode::PKCS7};
1421 default:
1422 return {};
1423 };
1424 default:
1425 return {};
1426 }
1427}
1428
Selene Huang31ab4042020-04-29 04:22:39 -07001429vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
1430 if (securityLevel_ == SecurityLevel::STRONGBOX) {
1431 return {EcCurve::P_256};
David Drysdale42fe1892021-10-14 14:43:46 +01001432 } else if (Curve25519Supported()) {
1433 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521,
1434 EcCurve::CURVE_25519};
Selene Huang31ab4042020-04-29 04:22:39 -07001435 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001436 return {
1437 EcCurve::P_224,
1438 EcCurve::P_256,
1439 EcCurve::P_384,
1440 EcCurve::P_521,
1441 };
Selene Huang31ab4042020-04-29 04:22:39 -07001442 }
1443}
1444
1445vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
David Drysdaledf09e542021-06-08 15:46:11 +01001446 if (SecLevel() == SecurityLevel::STRONGBOX) {
David Drysdale42fe1892021-10-14 14:43:46 +01001447 // Curve 25519 is not supported, either because:
1448 // - KeyMint v1: it's an unknown enum value
1449 // - KeyMint v2+: it's not supported by StrongBox.
1450 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519};
David Drysdaledf09e542021-06-08 15:46:11 +01001451 } else {
David Drysdale42fe1892021-10-14 14:43:46 +01001452 if (Curve25519Supported()) {
1453 return {};
1454 } else {
1455 return {EcCurve::CURVE_25519};
1456 }
David Drysdaledf09e542021-06-08 15:46:11 +01001457 }
Selene Huang31ab4042020-04-29 04:22:39 -07001458}
1459
subrahmanyaman05642492022-02-05 07:10:56 +00001460vector<uint64_t> KeyMintAidlTestBase::ValidExponents() {
1461 if (SecLevel() == SecurityLevel::STRONGBOX) {
1462 return {65537};
1463 } else {
1464 return {3, 65537};
1465 }
1466}
1467
Selene Huang31ab4042020-04-29 04:22:39 -07001468vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
1469 switch (SecLevel()) {
1470 case SecurityLevel::SOFTWARE:
1471 case SecurityLevel::TRUSTED_ENVIRONMENT:
1472 if (withNone) {
1473 if (withMD5)
1474 return {Digest::NONE, Digest::MD5, Digest::SHA1,
1475 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1476 Digest::SHA_2_512};
1477 else
1478 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
1479 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1480 } else {
1481 if (withMD5)
1482 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
1483 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
1484 else
1485 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1486 Digest::SHA_2_512};
1487 }
1488 break;
1489 case SecurityLevel::STRONGBOX:
1490 if (withNone)
1491 return {Digest::NONE, Digest::SHA_2_256};
1492 else
1493 return {Digest::SHA_2_256};
1494 break;
1495 default:
1496 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
1497 break;
1498 }
1499 ADD_FAILURE() << "Should be impossible to get here";
1500 return {};
1501}
1502
Shawn Willden7f424372021-01-10 18:06:50 -07001503static const vector<KeyParameter> kEmptyAuthList{};
1504
1505const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1506 const vector<KeyCharacteristics>& key_characteristics) {
1507 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
1508 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
1509 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1510}
1511
Qi Wubeefae42021-01-28 23:16:37 +08001512const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
1513 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
1514 auto found = std::find_if(
1515 key_characteristics.begin(), key_characteristics.end(),
1516 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001517 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
1518}
1519
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001520ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001521 auto [result, ciphertext] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001522 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
1523 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
1524 return result;
1525}
1526
1527ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001528 auto [result, mac] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001529 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
1530 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
1531 return result;
1532}
1533
1534ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
1535 std::string message(2048 / 8, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07001536 auto [result, signature] = ProcessMessage(
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001537 rsaKeyBlob, KeyPurpose::SIGN, message,
1538 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1539 return result;
1540}
1541
1542ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
Shawn Willden92d79c02021-02-19 07:31:55 -07001543 auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
1544 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00001545 return result;
1546}
1547
Selene Huang6e46f142021-04-20 19:20:11 -07001548void verify_serial(X509* cert, const uint64_t expected_serial) {
1549 BIGNUM_Ptr ser(BN_new());
1550 EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get()));
1551
1552 uint64_t serial;
1553 EXPECT_TRUE(BN_get_u64(ser.get(), &serial));
1554 EXPECT_EQ(serial, expected_serial);
1555}
1556
1557// Please set self_signed to true for fake certificates or self signed
1558// certificates
1559void verify_subject(const X509* cert, //
1560 const string& subject, //
1561 bool self_signed) {
1562 char* cert_issuer = //
1563 X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0);
1564
1565 char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0);
1566
1567 string expected_subject("/CN=");
1568 if (subject.empty()) {
1569 expected_subject.append("Android Keystore Key");
1570 } else {
1571 expected_subject.append(subject);
1572 }
1573
1574 EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj;
1575
1576 if (self_signed) {
1577 EXPECT_STREQ(cert_issuer, cert_subj)
1578 << "Cert issuer and subject mismatch for self signed certificate.";
1579 }
1580
1581 OPENSSL_free(cert_subj);
1582 OPENSSL_free(cert_issuer);
1583}
1584
Shawn Willden22fb9c12022-06-02 14:04:33 -06001585int get_vsr_api_level() {
Shawn Willden35db3492022-06-16 12:50:40 -06001586 int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
1587 if (vendor_api_level != -1) {
1588 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001589 }
Shawn Willden35db3492022-06-16 12:50:40 -06001590
1591 // Android S and older devices do not define ro.vendor.api_level
1592 vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
1593 if (vendor_api_level == -1) {
1594 vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1);
Shawn Willden22fb9c12022-06-02 14:04:33 -06001595 }
Shawn Willden35db3492022-06-16 12:50:40 -06001596
1597 int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1);
1598 if (product_api_level == -1) {
1599 product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1);
1600 EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk";
Shawn Willden22fb9c12022-06-02 14:04:33 -06001601 }
Shawn Willden35db3492022-06-16 12:50:40 -06001602
1603 // VSR API level is the minimum of vendor_api_level and product_api_level.
1604 if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
1605 return product_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001606 }
Shawn Willden35db3492022-06-16 12:50:40 -06001607 return vendor_api_level;
Shawn Willden22fb9c12022-06-02 14:04:33 -06001608}
1609
David Drysdale555ba002022-05-03 18:48:57 +01001610bool is_gsi_image() {
1611 std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc");
1612 return ifs.good();
1613}
1614
Selene Huang6e46f142021-04-20 19:20:11 -07001615vector<uint8_t> build_serial_blob(const uint64_t serial_int) {
1616 BIGNUM_Ptr serial(BN_new());
1617 EXPECT_TRUE(BN_set_u64(serial.get(), serial_int));
1618
1619 int len = BN_num_bytes(serial.get());
1620 vector<uint8_t> serial_blob(len);
1621 if (BN_bn2bin(serial.get(), serial_blob.data()) != len) {
1622 return {};
1623 }
1624
David Drysdaledb0dcf52021-05-18 11:43:31 +01001625 if (serial_blob.empty() || serial_blob[0] & 0x80) {
1626 // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte.
1627 // Top bit being set indicates a negative number in two's complement, but our input
1628 // was positive.
1629 // In either case, prepend a zero byte.
1630 serial_blob.insert(serial_blob.begin(), 0x00);
1631 }
1632
Selene Huang6e46f142021-04-20 19:20:11 -07001633 return serial_blob;
1634}
1635
1636void verify_subject_and_serial(const Certificate& certificate, //
1637 const uint64_t expected_serial, //
1638 const string& subject, bool self_signed) {
1639 X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate));
1640 ASSERT_TRUE(!!cert.get());
1641
1642 verify_serial(cert.get(), expected_serial);
1643 verify_subject(cert.get(), subject, self_signed);
1644}
1645
Shawn Willden4315e132022-03-20 12:49:46 -06001646void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked,
1647 VerifiedBoot verified_boot_state,
1648 const vector<uint8_t>& verified_boot_hash) {
1649 char property_value[PROPERTY_VALUE_MAX] = {};
1650
1651 if (avb_verification_enabled()) {
1652 EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
1653 string prop_string(property_value);
1654 EXPECT_EQ(prop_string.size(), 64);
1655 EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
1656
1657 EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
1658 if (!strcmp(property_value, "unlocked")) {
1659 EXPECT_FALSE(device_locked);
1660 } else {
1661 EXPECT_TRUE(device_locked);
1662 }
1663
1664 // Check that the device is locked if not debuggable, e.g., user build
1665 // images in CTS. For VTS, debuggable images are used to allow adb root
1666 // and the device is unlocked.
1667 if (!property_get_bool("ro.debuggable", false)) {
1668 EXPECT_TRUE(device_locked);
1669 } else {
1670 EXPECT_FALSE(device_locked);
1671 }
1672 }
1673
1674 // Verified boot key should be all 0's if the boot state is not verified or self signed
1675 std::string empty_boot_key(32, '\0');
1676 std::string verified_boot_key_str((const char*)verified_boot_key.data(),
1677 verified_boot_key.size());
1678 EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
1679 if (!strcmp(property_value, "green")) {
1680 EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED);
1681 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1682 verified_boot_key.size()));
1683 } else if (!strcmp(property_value, "yellow")) {
1684 EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED);
1685 EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1686 verified_boot_key.size()));
1687 } else if (!strcmp(property_value, "orange")) {
1688 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1689 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1690 verified_boot_key.size()));
1691 } else if (!strcmp(property_value, "red")) {
1692 EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED);
1693 } else {
1694 EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED);
1695 EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
1696 verified_boot_key.size()));
1697 }
1698}
1699
David Drysdale7dff4fc2021-12-10 10:10:52 +00001700bool verify_attestation_record(int32_t aidl_version, //
1701 const string& challenge, //
Shawn Willden7c130392020-12-21 09:58:22 -07001702 const string& app_id, //
1703 AuthorizationSet expected_sw_enforced, //
1704 AuthorizationSet expected_hw_enforced, //
1705 SecurityLevel security_level,
David Drysdale565ccc72021-10-11 12:49:50 +01001706 const vector<uint8_t>& attestation_cert,
1707 vector<uint8_t>* unique_id) {
Shawn Willden7c130392020-12-21 09:58:22 -07001708 X509_Ptr cert(parse_cert_blob(attestation_cert));
1709 EXPECT_TRUE(!!cert.get());
1710 if (!cert.get()) return false;
1711
1712 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
1713 EXPECT_TRUE(!!attest_rec);
1714 if (!attest_rec) return false;
1715
1716 AuthorizationSet att_sw_enforced;
1717 AuthorizationSet att_hw_enforced;
1718 uint32_t att_attestation_version;
David Drysdale37af4b32021-05-14 16:46:59 +01001719 uint32_t att_keymint_version;
Shawn Willden7c130392020-12-21 09:58:22 -07001720 SecurityLevel att_attestation_security_level;
David Drysdale37af4b32021-05-14 16:46:59 +01001721 SecurityLevel att_keymint_security_level;
Shawn Willden7c130392020-12-21 09:58:22 -07001722 vector<uint8_t> att_challenge;
1723 vector<uint8_t> att_unique_id;
1724 vector<uint8_t> att_app_id;
1725
1726 auto error = parse_attestation_record(attest_rec->data, //
1727 attest_rec->length, //
1728 &att_attestation_version, //
1729 &att_attestation_security_level, //
David Drysdale37af4b32021-05-14 16:46:59 +01001730 &att_keymint_version, //
1731 &att_keymint_security_level, //
Shawn Willden7c130392020-12-21 09:58:22 -07001732 &att_challenge, //
1733 &att_sw_enforced, //
1734 &att_hw_enforced, //
1735 &att_unique_id);
1736 EXPECT_EQ(ErrorCode::OK, error);
1737 if (error != ErrorCode::OK) return false;
1738
David Drysdale7dff4fc2021-12-10 10:10:52 +00001739 check_attestation_version(att_attestation_version, aidl_version);
Selene Huang4f64c222021-04-13 19:54:36 -07001740 vector<uint8_t> appId(app_id.begin(), app_id.end());
Shawn Willden7c130392020-12-21 09:58:22 -07001741
Selene Huang4f64c222021-04-13 19:54:36 -07001742 // check challenge and app id only if we expects a non-fake certificate
1743 if (challenge.length() > 0) {
1744 EXPECT_EQ(challenge.length(), att_challenge.size());
1745 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1746
1747 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId);
1748 }
Shawn Willden7c130392020-12-21 09:58:22 -07001749
David Drysdale7dff4fc2021-12-10 10:10:52 +00001750 check_attestation_version(att_keymint_version, aidl_version);
David Drysdale37af4b32021-05-14 16:46:59 +01001751 EXPECT_EQ(security_level, att_keymint_security_level);
Shawn Willden7c130392020-12-21 09:58:22 -07001752 EXPECT_EQ(security_level, att_attestation_security_level);
1753
Tri Vob21e6df2023-02-17 14:55:43 -08001754 for (int i = 0; i < att_hw_enforced.size(); i++) {
1755 if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
1756 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
1757 std::string date =
1758 std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>());
David Drysdale168228a2021-10-05 08:43:52 +01001759
Tri Vob21e6df2023-02-17 14:55:43 -08001760 // strptime seems to require delimiters, but the tag value will
1761 // be YYYYMMDD
1762 if (date.size() != 8) {
1763 ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag
1764 << " with invalid format (not YYYYMMDD): " << date;
1765 return false;
Shawn Willden7c130392020-12-21 09:58:22 -07001766 }
Tri Vob21e6df2023-02-17 14:55:43 -08001767 date.insert(6, "-");
1768 date.insert(4, "-");
1769 struct tm time;
1770 strptime(date.c_str(), "%Y-%m-%d", &time);
1771
1772 // Day of the month (0-31)
1773 EXPECT_GE(time.tm_mday, 0);
1774 EXPECT_LT(time.tm_mday, 32);
1775 // Months since Jan (0-11)
1776 EXPECT_GE(time.tm_mon, 0);
1777 EXPECT_LT(time.tm_mon, 12);
1778 // Years since 1900
1779 EXPECT_GT(time.tm_year, 110);
1780 EXPECT_LT(time.tm_year, 200);
Shawn Willden7c130392020-12-21 09:58:22 -07001781 }
1782 }
1783
1784 // Check to make sure boolean values are properly encoded. Presence of a boolean tag
1785 // indicates true. A provided boolean tag that can be pulled back out of the certificate
1786 // indicates correct encoding. No need to check if it's in both lists, since the
1787 // AuthorizationSet compare below will handle mismatches of tags.
1788 if (security_level == SecurityLevel::SOFTWARE) {
1789 EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1790 } else {
1791 EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
1792 }
1793
Shawn Willden7c130392020-12-21 09:58:22 -07001794 if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
1795 // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
1796 EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
1797 att_hw_enforced.Contains(TAG_KEY_SIZE));
1798 }
1799
1800 // Test root of trust elements
1801 vector<uint8_t> verified_boot_key;
1802 VerifiedBoot verified_boot_state;
1803 bool device_locked;
1804 vector<uint8_t> verified_boot_hash;
1805 error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
1806 &verified_boot_state, &device_locked, &verified_boot_hash);
1807 EXPECT_EQ(ErrorCode::OK, error);
Shawn Willden4315e132022-03-20 12:49:46 -06001808 verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash);
Shawn Willden7c130392020-12-21 09:58:22 -07001809
1810 att_sw_enforced.Sort();
1811 expected_sw_enforced.Sort();
David Drysdale37af4b32021-05-14 16:46:59 +01001812 EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced));
Shawn Willden7c130392020-12-21 09:58:22 -07001813
1814 att_hw_enforced.Sort();
1815 expected_hw_enforced.Sort();
1816 EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced));
1817
David Drysdale565ccc72021-10-11 12:49:50 +01001818 if (unique_id != nullptr) {
1819 *unique_id = att_unique_id;
1820 }
1821
Shawn Willden7c130392020-12-21 09:58:22 -07001822 return true;
1823}
1824
1825string bin2hex(const vector<uint8_t>& data) {
1826 string retval;
1827 retval.reserve(data.size() * 2 + 1);
1828 for (uint8_t byte : data) {
1829 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
1830 retval.push_back(nibble2hex[0x0F & byte]);
1831 }
1832 return retval;
1833}
1834
David Drysdalef0d516d2021-03-22 07:51:43 +00001835AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1836 AuthorizationSet authList;
1837 for (auto& entry : key_characteristics) {
1838 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
1839 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
1840 authList.push_back(AuthorizationSet(entry.authorizations));
1841 }
1842 }
1843 return authList;
1844}
1845
1846AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) {
1847 AuthorizationSet authList;
1848 for (auto& entry : key_characteristics) {
1849 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
1850 entry.securityLevel == SecurityLevel::KEYSTORE) {
1851 authList.push_back(AuthorizationSet(entry.authorizations));
1852 }
1853 }
1854 return authList;
1855}
1856
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001857AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain,
1858 bool strict_issuer_check) {
Shawn Willden7c130392020-12-21 09:58:22 -07001859 std::stringstream cert_data;
1860
1861 for (size_t i = 0; i < chain.size(); ++i) {
1862 cert_data << bin2hex(chain[i].encodedCertificate) << std::endl;
1863
1864 X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate));
1865 X509_Ptr signing_cert;
1866 if (i < chain.size() - 1) {
1867 signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate);
1868 } else {
1869 signing_cert = parse_cert_blob(chain[i].encodedCertificate);
1870 }
1871 if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str();
1872
1873 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
1874 if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str();
1875
1876 if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
1877 return AssertionFailure()
1878 << "Verification of certificate " << i << " failed "
1879 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n'
1880 << cert_data.str();
1881 }
1882
1883 string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
1884 string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
Eran Messeri03d7a1a2021-07-06 12:07:57 +01001885 if (cert_issuer != signer_subj && strict_issuer_check) {
Selene Huang8f9494c2021-04-21 15:10:36 -07001886 return AssertionFailure() << "Cert " << i << " has wrong issuer.\n"
1887 << " Signer subject is " << signer_subj
1888 << " Issuer subject is " << cert_issuer << endl
1889 << cert_data.str();
Shawn Willden7c130392020-12-21 09:58:22 -07001890 }
Shawn Willden7c130392020-12-21 09:58:22 -07001891 }
1892
1893 if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str();
1894 return AssertionSuccess();
1895}
1896
1897X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) {
1898 const uint8_t* p = blob.data();
1899 return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
1900}
1901
David Drysdalef0d516d2021-03-22 07:51:43 +00001902vector<uint8_t> make_name_from_str(const string& name) {
1903 X509_NAME_Ptr x509_name(X509_NAME_new());
1904 EXPECT_TRUE(x509_name.get() != nullptr);
1905 if (!x509_name) return {};
1906
1907 EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), //
1908 "CN", //
1909 MBSTRING_ASC,
1910 reinterpret_cast<const uint8_t*>(name.c_str()),
1911 -1, // len
1912 -1, // loc
1913 0 /* set */));
1914
1915 int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */);
1916 EXPECT_GT(len, 0);
1917
1918 vector<uint8_t> retval(len);
1919 uint8_t* p = retval.data();
1920 i2d_X509_NAME(x509_name.get(), &p);
1921
1922 return retval;
1923}
1924
David Drysdale4dc01072021-04-01 12:17:35 +01001925namespace {
1926
1927void check_cose_key(const vector<uint8_t>& data, bool testMode) {
1928 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
1929 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
1930
1931 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
1932 if (testMode) {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001933 EXPECT_THAT(
1934 cppbor::prettyPrint(parsedPayload.get()),
1935 MatchesRegex("\\{\n"
1936 " 1 : 2,\n" // kty: EC2
1937 " 3 : -7,\n" // alg: ES256
1938 " -1 : 1,\n" // EC id: P256
1939 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1940 // sequence of 32 hexadecimal bytes, enclosed in braces and
1941 // separated by commas. In this case, some Ed25519 public key.
1942 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1943 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1944 " -70000 : null,\n" // test marker
1945 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001946 } else {
Elliott Hughesbe36da42022-11-09 21:35:07 +00001947 EXPECT_THAT(
1948 cppbor::prettyPrint(parsedPayload.get()),
1949 MatchesRegex("\\{\n"
1950 " 1 : 2,\n" // kty: EC2
1951 " 3 : -7,\n" // alg: ES256
1952 " -1 : 1,\n" // EC id: P256
1953 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
1954 // sequence of 32 hexadecimal bytes, enclosed in braces and
1955 // separated by commas. In this case, some Ed25519 public key.
1956 " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data
1957 " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data
1958 "\\}"));
David Drysdale4dc01072021-04-01 12:17:35 +01001959 }
1960}
1961
1962} // namespace
1963
1964void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
1965 vector<uint8_t>* payload_value) {
1966 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
1967 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
1968
1969 ASSERT_NE(coseMac0->asArray(), nullptr);
1970 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
1971
1972 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
1973 ASSERT_NE(protParms, nullptr);
1974
1975 // Header label:value of 'alg': HMAC-256
1976 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
1977
1978 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
1979 ASSERT_NE(unprotParms, nullptr);
1980 ASSERT_EQ(unprotParms->size(), 0);
1981
1982 // The payload is a bstr holding an encoded COSE_Key
1983 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
1984 ASSERT_NE(payload, nullptr);
1985 check_cose_key(payload->value(), testMode);
1986
1987 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
1988 ASSERT_TRUE(coseMac0Tag);
1989 auto extractedTag = coseMac0Tag->value();
1990 EXPECT_EQ(extractedTag.size(), 32U);
1991
1992 // Compare with tag generated with kTestMacKey. Should only match in test mode
Seth Moore026bb742021-04-30 11:41:18 -07001993 auto macFunction = [](const cppcose::bytevec& input) {
1994 return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input);
1995 };
1996 auto testTag =
1997 cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
David Drysdale4dc01072021-04-01 12:17:35 +01001998 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
1999
2000 if (testMode) {
Seth Moore026bb742021-04-30 11:41:18 -07002001 EXPECT_THAT(*testTag, ElementsAreArray(extractedTag));
David Drysdale4dc01072021-04-01 12:17:35 +01002002 } else {
Seth Moore026bb742021-04-30 11:41:18 -07002003 EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag)));
David Drysdale4dc01072021-04-01 12:17:35 +01002004 }
2005 if (payload_value != nullptr) {
2006 *payload_value = payload->value();
2007 }
2008}
2009
2010void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
2011 // Extract x and y affine coordinates from the encoded Cose_Key.
2012 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
2013 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
2014 auto coseKey = parsedPayload->asMap();
2015 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
2016 ASSERT_NE(xItem->asBstr(), nullptr);
2017 vector<uint8_t> x = xItem->asBstr()->value();
2018 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
2019 ASSERT_NE(yItem->asBstr(), nullptr);
2020 vector<uint8_t> y = yItem->asBstr()->value();
2021
2022 // Concatenate: 0x04 (uncompressed form marker) | x | y
2023 vector<uint8_t> pubKeyData{0x04};
2024 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
2025 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
2026
2027 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
2028 ASSERT_NE(ecKey, nullptr);
2029 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
2030 ASSERT_NE(group, nullptr);
2031 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
2032 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
2033 ASSERT_NE(point, nullptr);
2034 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
2035 nullptr),
2036 1);
2037 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
2038
2039 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
2040 ASSERT_NE(pubKey, nullptr);
2041 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
2042 *signingKey = std::move(pubKey);
2043}
2044
Max Biresa97ec692022-11-21 23:37:54 -08002045void device_id_attestation_vsr_check(const ErrorCode& result) {
2046 if (get_vsr_api_level() >= 34) {
2047 ASSERT_FALSE(result == ErrorCode::INVALID_TAG)
2048 << "It is a specification violation for INVALID_TAG to be returned due to ID "
2049 << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
2050 << "be used for a case where updateAad() is called after update(). As of "
2051 << "VSR-14, this is now enforced as an error.";
2052 }
2053}
2054
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002055// Check whether the given named feature is available.
2056bool check_feature(const std::string& name) {
2057 ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager());
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002058 ::android::sp<::android::IBinder> binder(
2059 sm->waitForService(::android::String16("package_native")));
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002060 if (binder == nullptr) {
Tommy Chiu6e5736b2023-02-08 10:16:03 +08002061 GTEST_LOG_(ERROR) << "waitForService package_native failed";
David Drysdale3d2ba0a2023-01-11 13:27:26 +00002062 return false;
2063 }
2064 ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr =
2065 ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder);
2066 if (packageMgr == nullptr) {
2067 GTEST_LOG_(ERROR) << "Cannot find package manager";
2068 return false;
2069 }
2070 bool hasFeature = false;
2071 auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature);
2072 if (!status.isOk()) {
2073 GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status;
2074 return false;
2075 }
2076 return hasFeature;
2077}
2078
Selene Huang31ab4042020-04-29 04:22:39 -07002079} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +00002080
Janis Danisevskis24c04702020-12-16 18:28:39 -08002081} // namespace aidl::android::hardware::security::keymint