Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2020 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include "KeyMintAidlTestBase.h" |
| 18 | |
| 19 | #include <chrono> |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 20 | #include <unordered_set> |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 21 | #include <vector> |
| 22 | |
| 23 | #include <android-base/logging.h> |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 24 | #include <android/binder_manager.h> |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 25 | #include <cppbor_parse.h> |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 26 | #include <cutils/properties.h> |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 27 | #include <gmock/gmock.h> |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 28 | #include <openssl/mem.h> |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 29 | #include <remote_prov/remote_prov_utils.h> |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 30 | |
Max Bires | 9704ff6 | 2021-04-07 11:12:01 -0700 | [diff] [blame] | 31 | #include <keymaster/cppcose/cppcose.h> |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 32 | #include <keymint_support/attestation_record.h> |
Shawn Willden | 08a7e43 | 2020-12-11 13:05:27 +0000 | [diff] [blame] | 33 | #include <keymint_support/key_param_output.h> |
| 34 | #include <keymint_support/keymint_utils.h> |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 35 | #include <keymint_support/openssl_utils.h> |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 36 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 37 | namespace aidl::android::hardware::security::keymint { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 38 | |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 39 | using namespace cppcose; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 40 | using namespace std::literals::chrono_literals; |
| 41 | using std::endl; |
| 42 | using std::optional; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 43 | using std::unique_ptr; |
| 44 | using ::testing::AssertionFailure; |
| 45 | using ::testing::AssertionResult; |
| 46 | using ::testing::AssertionSuccess; |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 47 | using ::testing::ElementsAreArray; |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 48 | using ::testing::MatchesRegex; |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 49 | using ::testing::Not; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 50 | |
| 51 | ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) { |
| 52 | if (set.size() == 0) |
| 53 | os << "(Empty)" << ::std::endl; |
| 54 | else { |
| 55 | os << "\n"; |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 56 | for (auto& entry : set) os << entry << ::std::endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 57 | } |
| 58 | return os; |
| 59 | } |
| 60 | |
| 61 | namespace test { |
| 62 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 63 | namespace { |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 64 | |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 65 | // Invalid value for a patchlevel (which is of form YYYYMMDD). |
| 66 | const uint32_t kInvalidPatchlevel = 99998877; |
| 67 | |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 68 | // Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have |
| 69 | // additional overhead, for the digest algorithmIdentifier required by PKCS#1. |
| 70 | const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11; |
| 71 | |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 72 | typedef KeyMintAidlTestBase::KeyData KeyData; |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 73 | // Predicate for testing basic characteristics validity in generation or import. |
| 74 | bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel, |
| 75 | const vector<KeyCharacteristics>& key_characteristics) { |
| 76 | if (key_characteristics.empty()) return false; |
| 77 | |
| 78 | std::unordered_set<SecurityLevel> levels_seen; |
| 79 | for (auto& entry : key_characteristics) { |
Seth Moore | 2a9a00e | 2021-08-04 16:31:52 -0700 | [diff] [blame] | 80 | if (entry.authorizations.empty()) { |
| 81 | GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel; |
| 82 | return false; |
| 83 | } |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 84 | |
Qi Wu | beefae4 | 2021-01-28 23:16:37 +0800 | [diff] [blame] | 85 | // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this. |
| 86 | if (entry.securityLevel == SecurityLevel::KEYSTORE) continue; |
| 87 | |
Seth Moore | 2a9a00e | 2021-08-04 16:31:52 -0700 | [diff] [blame] | 88 | if (levels_seen.find(entry.securityLevel) != levels_seen.end()) { |
| 89 | GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel; |
| 90 | return false; |
| 91 | } |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 92 | levels_seen.insert(entry.securityLevel); |
| 93 | |
| 94 | // Generally, we should only have one entry, at the same security level as the KM |
| 95 | // instance. There is an exception: StrongBox KM can have some authorizations that are |
| 96 | // enforced by the TEE. |
| 97 | bool isExpectedSecurityLevel = secLevel == entry.securityLevel || |
| 98 | (secLevel == SecurityLevel::STRONGBOX && |
| 99 | entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT); |
| 100 | |
Seth Moore | 2a9a00e | 2021-08-04 16:31:52 -0700 | [diff] [blame] | 101 | if (!isExpectedSecurityLevel) { |
| 102 | GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel; |
| 103 | return false; |
| 104 | } |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 105 | } |
| 106 | return true; |
| 107 | } |
| 108 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 109 | // Extract attestation record from cert. Returned object is still part of cert; don't free it |
| 110 | // separately. |
| 111 | ASN1_OCTET_STRING* get_attestation_record(X509* certificate) { |
| 112 | ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */)); |
| 113 | EXPECT_TRUE(!!oid.get()); |
| 114 | if (!oid.get()) return nullptr; |
| 115 | |
| 116 | int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */); |
| 117 | EXPECT_NE(-1, location) << "Attestation extension not found in certificate"; |
| 118 | if (location == -1) return nullptr; |
| 119 | |
| 120 | X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location); |
| 121 | EXPECT_TRUE(!!attest_rec_ext) |
| 122 | << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug."; |
| 123 | if (!attest_rec_ext) return nullptr; |
| 124 | |
| 125 | ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext); |
| 126 | EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data"; |
| 127 | return attest_rec; |
| 128 | } |
| 129 | |
| 130 | bool avb_verification_enabled() { |
| 131 | char value[PROPERTY_VALUE_MAX]; |
| 132 | return property_get("ro.boot.vbmeta.device_state", value, "") != 0; |
| 133 | } |
| 134 | |
| 135 | char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', |
| 136 | '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; |
| 137 | |
| 138 | // Attestations don't contain everything in key authorization lists, so we need to filter the key |
| 139 | // lists to produce the lists that we expect to match the attestations. |
| 140 | auto kTagsToFilter = { |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 141 | Tag::CREATION_DATETIME, |
| 142 | Tag::HARDWARE_TYPE, |
| 143 | Tag::INCLUDE_UNIQUE_ID, |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 144 | }; |
| 145 | |
| 146 | AuthorizationSet filtered_tags(const AuthorizationSet& set) { |
| 147 | AuthorizationSet filtered; |
| 148 | std::remove_copy_if( |
| 149 | set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool { |
| 150 | return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) != |
| 151 | kTagsToFilter.end(); |
| 152 | }); |
| 153 | return filtered; |
| 154 | } |
| 155 | |
David Drysdale | 300b555 | 2021-05-20 12:05:26 +0100 | [diff] [blame] | 156 | // Remove any SecurityLevel::KEYSTORE entries from a list of key characteristics. |
| 157 | void strip_keystore_tags(vector<KeyCharacteristics>* characteristics) { |
| 158 | characteristics->erase(std::remove_if(characteristics->begin(), characteristics->end(), |
| 159 | [](const auto& entry) { |
| 160 | return entry.securityLevel == SecurityLevel::KEYSTORE; |
| 161 | }), |
| 162 | characteristics->end()); |
| 163 | } |
| 164 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 165 | string x509NameToStr(X509_NAME* name) { |
| 166 | char* s = X509_NAME_oneline(name, nullptr, 0); |
| 167 | string retval(s); |
| 168 | OPENSSL_free(s); |
| 169 | return retval; |
| 170 | } |
| 171 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 172 | } // namespace |
| 173 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 174 | bool KeyMintAidlTestBase::arm_deleteAllKeys = false; |
| 175 | bool KeyMintAidlTestBase::dump_Attestations = false; |
| 176 | |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 177 | uint32_t KeyMintAidlTestBase::boot_patch_level( |
| 178 | const vector<KeyCharacteristics>& key_characteristics) { |
| 179 | // The boot patchlevel is not available as a property, but should be present |
| 180 | // in the key characteristics of any created key. |
| 181 | AuthorizationSet allAuths; |
| 182 | for (auto& entry : key_characteristics) { |
| 183 | allAuths.push_back(AuthorizationSet(entry.authorizations)); |
| 184 | } |
| 185 | auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL); |
| 186 | if (patchlevel.has_value()) { |
| 187 | return patchlevel.value(); |
| 188 | } else { |
| 189 | // No boot patchlevel is available. Return a value that won't match anything |
| 190 | // and so will trigger test failures. |
| 191 | return kInvalidPatchlevel; |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | uint32_t KeyMintAidlTestBase::boot_patch_level() { |
| 196 | return boot_patch_level(key_characteristics_); |
| 197 | } |
| 198 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 199 | ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 200 | if (result.isOk()) return ErrorCode::OK; |
| 201 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 202 | if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) { |
| 203 | return static_cast<ErrorCode>(result.getServiceSpecificError()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 204 | } |
| 205 | |
| 206 | return ErrorCode::UNKNOWN_ERROR; |
| 207 | } |
| 208 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 209 | void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 210 | ASSERT_NE(keyMint, nullptr); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 211 | keymint_ = std::move(keyMint); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 212 | |
| 213 | KeyMintHardwareInfo info; |
| 214 | ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk()); |
| 215 | |
| 216 | securityLevel_ = info.securityLevel; |
| 217 | name_.assign(info.keyMintName.begin(), info.keyMintName.end()); |
| 218 | author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end()); |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 219 | timestamp_token_required_ = info.timestampTokenRequired; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 220 | |
| 221 | os_version_ = getOsVersion(); |
| 222 | os_patch_level_ = getOsPatchlevel(); |
David Drysdale | bb3d85e | 2021-04-13 11:15:51 +0100 | [diff] [blame] | 223 | vendor_patch_level_ = getVendorPatchlevel(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 224 | } |
| 225 | |
| 226 | void KeyMintAidlTestBase::SetUp() { |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 227 | if (AServiceManager_isDeclared(GetParam().c_str())) { |
| 228 | ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str())); |
| 229 | InitializeKeyMint(IKeyMintDevice::fromBinder(binder)); |
| 230 | } else { |
| 231 | InitializeKeyMint(nullptr); |
| 232 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 233 | } |
| 234 | |
| 235 | ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc, |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 236 | const optional<AttestationKey>& attest_key, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 237 | vector<uint8_t>* key_blob, |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 238 | vector<KeyCharacteristics>* key_characteristics, |
| 239 | vector<Certificate>* cert_chain) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 240 | EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug"; |
| 241 | EXPECT_NE(key_characteristics, nullptr) |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 242 | << "Previous characteristics not deleted before generating key. Test bug."; |
| 243 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 244 | KeyCreationResult creationResult; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 245 | Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 246 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 247 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 248 | creationResult.keyCharacteristics); |
| 249 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 250 | *key_blob = std::move(creationResult.keyBlob); |
| 251 | *key_characteristics = std::move(creationResult.keyCharacteristics); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 252 | *cert_chain = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 253 | |
| 254 | auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM); |
| 255 | EXPECT_TRUE(algorithm); |
| 256 | if (algorithm && |
| 257 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 258 | EXPECT_GE(cert_chain->size(), 1); |
| 259 | if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) { |
| 260 | if (attest_key) { |
| 261 | EXPECT_EQ(cert_chain->size(), 1); |
| 262 | } else { |
| 263 | EXPECT_GT(cert_chain->size(), 1); |
| 264 | } |
| 265 | } |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 266 | } else { |
| 267 | // For symmetric keys there should be no certificates. |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 268 | EXPECT_EQ(cert_chain->size(), 0); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 269 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 270 | } |
| 271 | |
| 272 | return GetReturnErrorCode(result); |
| 273 | } |
| 274 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 275 | ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc, |
| 276 | const optional<AttestationKey>& attest_key) { |
| 277 | return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 278 | } |
| 279 | |
| 280 | ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format, |
| 281 | const string& key_material, vector<uint8_t>* key_blob, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 282 | vector<KeyCharacteristics>* key_characteristics) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 283 | Status result; |
| 284 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 285 | cert_chain_.clear(); |
| 286 | key_characteristics->clear(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 287 | key_blob->clear(); |
| 288 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 289 | KeyCreationResult creationResult; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 290 | result = keymint_->importKey(key_desc.vector_data(), format, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 291 | vector<uint8_t>(key_material.begin(), key_material.end()), |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 292 | {} /* attestationSigningKeyBlob */, &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 293 | |
| 294 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 295 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 296 | creationResult.keyCharacteristics); |
| 297 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 298 | |
| 299 | *key_blob = std::move(creationResult.keyBlob); |
| 300 | *key_characteristics = std::move(creationResult.keyCharacteristics); |
| 301 | cert_chain_ = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 302 | |
| 303 | auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM); |
| 304 | EXPECT_TRUE(algorithm); |
| 305 | if (algorithm && |
| 306 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
| 307 | EXPECT_GE(cert_chain_.size(), 1); |
| 308 | if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1); |
| 309 | } else { |
| 310 | // For symmetric keys there should be no certificates. |
| 311 | EXPECT_EQ(cert_chain_.size(), 0); |
| 312 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 313 | } |
| 314 | |
| 315 | return GetReturnErrorCode(result); |
| 316 | } |
| 317 | |
| 318 | ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format, |
| 319 | const string& key_material) { |
| 320 | return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_); |
| 321 | } |
| 322 | |
| 323 | ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key, |
| 324 | const AuthorizationSet& wrapping_key_desc, |
| 325 | string masking_key, |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 326 | const AuthorizationSet& unwrapping_params, |
| 327 | int64_t password_sid, int64_t biometric_sid) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 328 | EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key)); |
| 329 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 330 | key_characteristics_.clear(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 331 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 332 | KeyCreationResult creationResult; |
| 333 | Status result = keymint_->importWrappedKey( |
| 334 | vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_, |
| 335 | vector<uint8_t>(masking_key.begin(), masking_key.end()), |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 336 | unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 337 | |
| 338 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 339 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 340 | creationResult.keyCharacteristics); |
| 341 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 342 | |
| 343 | key_blob_ = std::move(creationResult.keyBlob); |
| 344 | key_characteristics_ = std::move(creationResult.keyCharacteristics); |
| 345 | cert_chain_ = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 346 | |
| 347 | AuthorizationSet allAuths; |
| 348 | for (auto& entry : key_characteristics_) { |
| 349 | allAuths.push_back(AuthorizationSet(entry.authorizations)); |
| 350 | } |
| 351 | auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM); |
| 352 | EXPECT_TRUE(algorithm); |
| 353 | if (algorithm && |
| 354 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
| 355 | EXPECT_GE(cert_chain_.size(), 1); |
| 356 | } else { |
| 357 | // For symmetric keys there should be no certificates. |
| 358 | EXPECT_EQ(cert_chain_.size(), 0); |
| 359 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 360 | } |
| 361 | |
| 362 | return GetReturnErrorCode(result); |
| 363 | } |
| 364 | |
David Drysdale | 300b555 | 2021-05-20 12:05:26 +0100 | [diff] [blame] | 365 | ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob, |
| 366 | const vector<uint8_t>& app_id, |
| 367 | const vector<uint8_t>& app_data, |
| 368 | vector<KeyCharacteristics>* key_characteristics) { |
| 369 | Status result = |
| 370 | keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics); |
| 371 | return GetReturnErrorCode(result); |
| 372 | } |
| 373 | |
| 374 | ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob, |
| 375 | vector<KeyCharacteristics>* key_characteristics) { |
| 376 | vector<uint8_t> empty_app_id, empty_app_data; |
| 377 | return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics); |
| 378 | } |
| 379 | |
| 380 | void KeyMintAidlTestBase::CheckCharacteristics( |
| 381 | const vector<uint8_t>& key_blob, |
| 382 | const vector<KeyCharacteristics>& generate_characteristics) { |
| 383 | // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from |
| 384 | // generateKey() should be excluded, as KeyMint will have no record of them. |
| 385 | // This applies to CREATION_DATETIME in particular. |
| 386 | vector<KeyCharacteristics> expected_characteristics(generate_characteristics); |
| 387 | strip_keystore_tags(&expected_characteristics); |
| 388 | |
| 389 | vector<KeyCharacteristics> retrieved; |
| 390 | ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved)); |
| 391 | EXPECT_EQ(expected_characteristics, retrieved); |
| 392 | } |
| 393 | |
| 394 | void KeyMintAidlTestBase::CheckAppIdCharacteristics( |
| 395 | const vector<uint8_t>& key_blob, std::string_view app_id_string, |
| 396 | std::string_view app_data_string, |
| 397 | const vector<KeyCharacteristics>& generate_characteristics) { |
| 398 | // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons. |
| 399 | vector<KeyCharacteristics> expected_characteristics(generate_characteristics); |
| 400 | strip_keystore_tags(&expected_characteristics); |
| 401 | |
| 402 | vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end()); |
| 403 | vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end()); |
| 404 | vector<KeyCharacteristics> retrieved; |
| 405 | ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved)); |
| 406 | EXPECT_EQ(expected_characteristics, retrieved); |
| 407 | |
| 408 | // Check that key characteristics can't be retrieved if the app ID or app data is missing. |
| 409 | vector<uint8_t> empty; |
| 410 | vector<KeyCharacteristics> not_retrieved; |
| 411 | EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, |
| 412 | GetCharacteristics(key_blob, empty, app_data, ¬_retrieved)); |
| 413 | EXPECT_EQ(not_retrieved.size(), 0); |
| 414 | |
| 415 | EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, |
| 416 | GetCharacteristics(key_blob, app_id, empty, ¬_retrieved)); |
| 417 | EXPECT_EQ(not_retrieved.size(), 0); |
| 418 | |
| 419 | EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, |
| 420 | GetCharacteristics(key_blob, empty, empty, ¬_retrieved)); |
| 421 | EXPECT_EQ(not_retrieved.size(), 0); |
| 422 | } |
| 423 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 424 | ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) { |
| 425 | Status result = keymint_->deleteKey(*key_blob); |
| 426 | if (!keep_key_blob) { |
| 427 | *key_blob = vector<uint8_t>(); |
| 428 | } |
| 429 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 430 | EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 431 | return GetReturnErrorCode(result); |
| 432 | } |
| 433 | |
| 434 | ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) { |
| 435 | return DeleteKey(&key_blob_, keep_key_blob); |
| 436 | } |
| 437 | |
| 438 | ErrorCode KeyMintAidlTestBase::DeleteAllKeys() { |
| 439 | Status result = keymint_->deleteAllKeys(); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 440 | EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 441 | return GetReturnErrorCode(result); |
| 442 | } |
| 443 | |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 444 | ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() { |
| 445 | Status result = keymint_->destroyAttestationIds(); |
| 446 | return GetReturnErrorCode(result); |
| 447 | } |
| 448 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 449 | void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) { |
| 450 | ErrorCode result = DeleteKey(key_blob, keep_key_blob); |
| 451 | EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl; |
| 452 | } |
| 453 | |
| 454 | void KeyMintAidlTestBase::CheckedDeleteKey() { |
| 455 | CheckedDeleteKey(&key_blob_); |
| 456 | } |
| 457 | |
| 458 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob, |
| 459 | const AuthorizationSet& in_params, |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 460 | AuthorizationSet* out_params, |
| 461 | std::shared_ptr<IKeyMintOperation>& op) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 462 | SCOPED_TRACE("Begin"); |
| 463 | Status result; |
| 464 | BeginResult out; |
David Drysdale | 56ba912 | 2021-04-19 19:10:47 +0100 | [diff] [blame] | 465 | result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 466 | |
| 467 | if (result.isOk()) { |
| 468 | *out_params = out.params; |
| 469 | challenge_ = out.challenge; |
| 470 | op = out.operation; |
| 471 | } |
| 472 | |
| 473 | return GetReturnErrorCode(result); |
| 474 | } |
| 475 | |
| 476 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob, |
| 477 | const AuthorizationSet& in_params, |
| 478 | AuthorizationSet* out_params) { |
| 479 | SCOPED_TRACE("Begin"); |
| 480 | Status result; |
| 481 | BeginResult out; |
| 482 | |
David Drysdale | 56ba912 | 2021-04-19 19:10:47 +0100 | [diff] [blame] | 483 | result = keymint_->begin(purpose, key_blob, in_params.vector_data(), std::nullopt, &out); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 484 | |
| 485 | if (result.isOk()) { |
| 486 | *out_params = out.params; |
| 487 | challenge_ = out.challenge; |
| 488 | op_ = out.operation; |
| 489 | } |
| 490 | |
| 491 | return GetReturnErrorCode(result); |
| 492 | } |
| 493 | |
| 494 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params, |
| 495 | AuthorizationSet* out_params) { |
| 496 | SCOPED_TRACE("Begin"); |
| 497 | EXPECT_EQ(nullptr, op_); |
| 498 | return Begin(purpose, key_blob_, in_params, out_params); |
| 499 | } |
| 500 | |
| 501 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) { |
| 502 | SCOPED_TRACE("Begin"); |
| 503 | AuthorizationSet out_params; |
| 504 | ErrorCode result = Begin(purpose, in_params, &out_params); |
| 505 | EXPECT_TRUE(out_params.empty()); |
| 506 | return result; |
| 507 | } |
| 508 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 509 | ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) { |
| 510 | return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()), |
| 511 | {} /* hardwareAuthToken */, |
| 512 | {} /* verificationToken */)); |
| 513 | } |
| 514 | |
| 515 | ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 516 | SCOPED_TRACE("Update"); |
| 517 | |
| 518 | Status result; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 519 | if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 520 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 521 | std::vector<uint8_t> o_put; |
| 522 | result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 523 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 524 | if (result.isOk()) output->append(o_put.begin(), o_put.end()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 525 | |
| 526 | return GetReturnErrorCode(result); |
| 527 | } |
| 528 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 529 | ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 530 | string* output) { |
| 531 | SCOPED_TRACE("Finish"); |
| 532 | Status result; |
| 533 | |
| 534 | EXPECT_NE(op_, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 535 | if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 536 | |
| 537 | vector<uint8_t> oPut; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 538 | result = op_->finish(vector<uint8_t>(input.begin(), input.end()), |
| 539 | vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */, |
| 540 | {} /* timestampToken */, {} /* confirmationToken */, &oPut); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 541 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 542 | if (result.isOk()) output->append(oPut.begin(), oPut.end()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 543 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 544 | op_ = {}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 545 | return GetReturnErrorCode(result); |
| 546 | } |
| 547 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 548 | ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 549 | SCOPED_TRACE("Abort"); |
| 550 | |
| 551 | EXPECT_NE(op, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 552 | if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 553 | |
| 554 | Status retval = op->abort(); |
| 555 | EXPECT_TRUE(retval.isOk()); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 556 | return static_cast<ErrorCode>(retval.getServiceSpecificError()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 557 | } |
| 558 | |
| 559 | ErrorCode KeyMintAidlTestBase::Abort() { |
| 560 | SCOPED_TRACE("Abort"); |
| 561 | |
| 562 | EXPECT_NE(op_, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 563 | if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 564 | |
| 565 | Status retval = op_->abort(); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 566 | return static_cast<ErrorCode>(retval.getServiceSpecificError()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 567 | } |
| 568 | |
| 569 | void KeyMintAidlTestBase::AbortIfNeeded() { |
| 570 | SCOPED_TRACE("AbortIfNeeded"); |
| 571 | if (op_) { |
| 572 | EXPECT_EQ(ErrorCode::OK, Abort()); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 573 | op_.reset(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 574 | } |
| 575 | } |
| 576 | |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 577 | auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation, |
| 578 | const string& message, const AuthorizationSet& in_params) |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 579 | -> std::tuple<ErrorCode, string> { |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 580 | AuthorizationSet begin_out_params; |
| 581 | ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 582 | if (result != ErrorCode::OK) return {result, {}}; |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 583 | |
| 584 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 585 | return {Finish(message, &output), output}; |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 586 | } |
| 587 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 588 | string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation, |
| 589 | const string& message, const AuthorizationSet& in_params, |
| 590 | AuthorizationSet* out_params) { |
| 591 | SCOPED_TRACE("ProcessMessage"); |
| 592 | AuthorizationSet begin_out_params; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 593 | ErrorCode result = Begin(operation, key_blob, in_params, out_params); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 594 | EXPECT_EQ(ErrorCode::OK, result); |
| 595 | if (result != ErrorCode::OK) { |
| 596 | return ""; |
| 597 | } |
| 598 | |
| 599 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 600 | EXPECT_EQ(ErrorCode::OK, Finish(message, &output)); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 601 | return output; |
| 602 | } |
| 603 | |
| 604 | string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message, |
| 605 | const AuthorizationSet& params) { |
| 606 | SCOPED_TRACE("SignMessage"); |
| 607 | AuthorizationSet out_params; |
| 608 | string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params); |
| 609 | EXPECT_TRUE(out_params.empty()); |
| 610 | return signature; |
| 611 | } |
| 612 | |
| 613 | string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) { |
| 614 | SCOPED_TRACE("SignMessage"); |
| 615 | return SignMessage(key_blob_, message, params); |
| 616 | } |
| 617 | |
| 618 | string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) { |
| 619 | SCOPED_TRACE("MacMessage"); |
| 620 | return SignMessage( |
| 621 | key_blob_, message, |
| 622 | AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length)); |
| 623 | } |
| 624 | |
| 625 | void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message, |
| 626 | Digest digest, const string& expected_mac) { |
| 627 | SCOPED_TRACE("CheckHmacTestVector"); |
| 628 | ASSERT_EQ(ErrorCode::OK, |
| 629 | ImportKey(AuthorizationSetBuilder() |
| 630 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 631 | .HmacKey(key.size() * 8) |
| 632 | .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8) |
| 633 | .Digest(digest), |
| 634 | KeyFormat::RAW, key)); |
| 635 | string signature = MacMessage(message, digest, expected_mac.size() * 8); |
| 636 | EXPECT_EQ(expected_mac, signature) |
| 637 | << "Test vector didn't match for key of size " << key.size() << " message of size " |
| 638 | << message.size() << " and digest " << digest; |
| 639 | CheckedDeleteKey(); |
| 640 | } |
| 641 | |
| 642 | void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce, |
| 643 | const string& message, |
| 644 | const string& expected_ciphertext) { |
| 645 | SCOPED_TRACE("CheckAesCtrTestVector"); |
| 646 | ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() |
| 647 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 648 | .AesEncryptionKey(key.size() * 8) |
| 649 | .BlockMode(BlockMode::CTR) |
| 650 | .Authorization(TAG_CALLER_NONCE) |
| 651 | .Padding(PaddingMode::NONE), |
| 652 | KeyFormat::RAW, key)); |
| 653 | |
| 654 | auto params = AuthorizationSetBuilder() |
| 655 | .Authorization(TAG_NONCE, nonce.data(), nonce.size()) |
| 656 | .BlockMode(BlockMode::CTR) |
| 657 | .Padding(PaddingMode::NONE); |
| 658 | AuthorizationSet out_params; |
| 659 | string ciphertext = EncryptMessage(key_blob_, message, params, &out_params); |
| 660 | EXPECT_EQ(expected_ciphertext, ciphertext); |
| 661 | } |
| 662 | |
| 663 | void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode, |
| 664 | PaddingMode padding_mode, const string& key, |
| 665 | const string& iv, const string& input, |
| 666 | const string& expected_output) { |
| 667 | auto authset = AuthorizationSetBuilder() |
| 668 | .TripleDesEncryptionKey(key.size() * 7) |
| 669 | .BlockMode(block_mode) |
| 670 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 671 | .Padding(padding_mode); |
| 672 | if (iv.size()) authset.Authorization(TAG_CALLER_NONCE); |
| 673 | ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key)); |
| 674 | ASSERT_GT(key_blob_.size(), 0U); |
| 675 | |
| 676 | auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode); |
| 677 | if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size()); |
| 678 | AuthorizationSet output_params; |
| 679 | string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params); |
| 680 | EXPECT_EQ(expected_output, output); |
| 681 | } |
| 682 | |
| 683 | void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message, |
| 684 | const string& signature, const AuthorizationSet& params) { |
| 685 | SCOPED_TRACE("VerifyMessage"); |
| 686 | AuthorizationSet begin_out_params; |
| 687 | ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params)); |
| 688 | |
| 689 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 690 | EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output)); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 691 | EXPECT_TRUE(output.empty()); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 692 | op_ = {}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 693 | } |
| 694 | |
| 695 | void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature, |
| 696 | const AuthorizationSet& params) { |
| 697 | SCOPED_TRACE("VerifyMessage"); |
| 698 | VerifyMessage(key_blob_, message, signature, params); |
| 699 | } |
| 700 | |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 701 | void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature, |
| 702 | const AuthorizationSet& params) { |
| 703 | SCOPED_TRACE("LocalVerifyMessage"); |
| 704 | |
| 705 | // Retrieve the public key from the leaf certificate. |
| 706 | ASSERT_GT(cert_chain_.size(), 0); |
| 707 | X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate)); |
| 708 | ASSERT_TRUE(key_cert.get()); |
| 709 | EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get())); |
| 710 | ASSERT_TRUE(pub_key.get()); |
| 711 | |
| 712 | Digest digest = params.GetTagValue(TAG_DIGEST).value(); |
| 713 | PaddingMode padding = PaddingMode::NONE; |
| 714 | auto tag = params.GetTagValue(TAG_PADDING); |
| 715 | if (tag.has_value()) { |
| 716 | padding = tag.value(); |
| 717 | } |
| 718 | |
| 719 | if (digest == Digest::NONE) { |
| 720 | switch (EVP_PKEY_id(pub_key.get())) { |
| 721 | case EVP_PKEY_EC: { |
| 722 | vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8); |
| 723 | size_t data_size = std::min(data.size(), message.size()); |
| 724 | memcpy(data.data(), message.data(), data_size); |
| 725 | EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get())); |
| 726 | ASSERT_TRUE(ecdsa.get()); |
| 727 | ASSERT_EQ(1, |
| 728 | ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size, |
| 729 | reinterpret_cast<const uint8_t*>(signature.data()), |
| 730 | signature.size(), ecdsa.get())); |
| 731 | break; |
| 732 | } |
| 733 | case EVP_PKEY_RSA: { |
| 734 | vector<uint8_t> data(EVP_PKEY_size(pub_key.get())); |
| 735 | size_t data_size = std::min(data.size(), message.size()); |
| 736 | memcpy(data.data(), message.data(), data_size); |
| 737 | |
| 738 | RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get()))); |
| 739 | ASSERT_TRUE(rsa.get()); |
| 740 | |
| 741 | size_t key_len = RSA_size(rsa.get()); |
| 742 | int openssl_padding = RSA_NO_PADDING; |
| 743 | switch (padding) { |
| 744 | case PaddingMode::NONE: |
| 745 | ASSERT_TRUE(data_size <= key_len); |
| 746 | ASSERT_EQ(key_len, signature.size()); |
| 747 | openssl_padding = RSA_NO_PADDING; |
| 748 | break; |
| 749 | case PaddingMode::RSA_PKCS1_1_5_SIGN: |
| 750 | ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <= |
| 751 | key_len); |
| 752 | openssl_padding = RSA_PKCS1_PADDING; |
| 753 | break; |
| 754 | default: |
| 755 | ADD_FAILURE() << "Unsupported RSA padding mode " << padding; |
| 756 | } |
| 757 | |
| 758 | vector<uint8_t> decrypted_data(key_len); |
| 759 | int bytes_decrypted = RSA_public_decrypt( |
| 760 | signature.size(), reinterpret_cast<const uint8_t*>(signature.data()), |
| 761 | decrypted_data.data(), rsa.get(), openssl_padding); |
| 762 | ASSERT_GE(bytes_decrypted, 0); |
| 763 | |
| 764 | const uint8_t* compare_pos = decrypted_data.data(); |
| 765 | size_t bytes_to_compare = bytes_decrypted; |
| 766 | uint8_t zero_check_result = 0; |
| 767 | if (padding == PaddingMode::NONE && data_size < bytes_to_compare) { |
| 768 | // If the data is short, for "unpadded" signing we zero-pad to the left. So |
| 769 | // during verification we should have zeros on the left of the decrypted data. |
| 770 | // Do a constant-time check. |
| 771 | const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size; |
| 772 | while (compare_pos < zero_end) zero_check_result |= *compare_pos++; |
| 773 | ASSERT_EQ(0, zero_check_result); |
| 774 | bytes_to_compare = data_size; |
| 775 | } |
| 776 | ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare)); |
| 777 | break; |
| 778 | } |
| 779 | default: |
| 780 | ADD_FAILURE() << "Unknown public key type"; |
| 781 | } |
| 782 | } else { |
| 783 | EVP_MD_CTX digest_ctx; |
| 784 | EVP_MD_CTX_init(&digest_ctx); |
| 785 | EVP_PKEY_CTX* pkey_ctx; |
| 786 | const EVP_MD* md = openssl_digest(digest); |
| 787 | ASSERT_NE(md, nullptr); |
| 788 | ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get())); |
| 789 | |
| 790 | if (padding == PaddingMode::RSA_PSS) { |
| 791 | EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0); |
| 792 | EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0); |
| 793 | } |
| 794 | |
| 795 | ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, |
| 796 | reinterpret_cast<const uint8_t*>(message.data()), |
| 797 | message.size())); |
| 798 | ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx, |
| 799 | reinterpret_cast<const uint8_t*>(signature.data()), |
| 800 | signature.size())); |
| 801 | EVP_MD_CTX_cleanup(&digest_ctx); |
| 802 | } |
| 803 | } |
| 804 | |
David Drysdale | 59cae64 | 2021-05-12 13:52:03 +0100 | [diff] [blame] | 805 | string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message, |
| 806 | const AuthorizationSet& params) { |
| 807 | SCOPED_TRACE("LocalRsaEncryptMessage"); |
| 808 | |
| 809 | // Retrieve the public key from the leaf certificate. |
| 810 | if (cert_chain_.empty()) { |
| 811 | ADD_FAILURE() << "No public key available"; |
| 812 | return "Failure"; |
| 813 | } |
| 814 | X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate)); |
| 815 | EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get())); |
| 816 | RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get()))); |
| 817 | |
| 818 | // Retrieve relevant tags. |
| 819 | Digest digest = Digest::NONE; |
| 820 | Digest mgf_digest = Digest::NONE; |
| 821 | PaddingMode padding = PaddingMode::NONE; |
| 822 | |
| 823 | auto digest_tag = params.GetTagValue(TAG_DIGEST); |
| 824 | if (digest_tag.has_value()) digest = digest_tag.value(); |
| 825 | auto pad_tag = params.GetTagValue(TAG_PADDING); |
| 826 | if (pad_tag.has_value()) padding = pad_tag.value(); |
| 827 | auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST); |
| 828 | if (mgf_tag.has_value()) mgf_digest = mgf_tag.value(); |
| 829 | |
| 830 | const EVP_MD* md = openssl_digest(digest); |
| 831 | const EVP_MD* mgf_md = openssl_digest(mgf_digest); |
| 832 | |
| 833 | // Set up encryption context. |
| 834 | EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr)); |
| 835 | if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) { |
| 836 | ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error(); |
| 837 | return "Failure"; |
| 838 | } |
| 839 | |
| 840 | int rc = -1; |
| 841 | switch (padding) { |
| 842 | case PaddingMode::NONE: |
| 843 | rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING); |
| 844 | break; |
| 845 | case PaddingMode::RSA_PKCS1_1_5_ENCRYPT: |
| 846 | rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING); |
| 847 | break; |
| 848 | case PaddingMode::RSA_OAEP: |
| 849 | rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING); |
| 850 | break; |
| 851 | default: |
| 852 | break; |
| 853 | } |
| 854 | if (rc <= 0) { |
| 855 | ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error(); |
| 856 | return "Failure"; |
| 857 | } |
| 858 | if (padding == PaddingMode::RSA_OAEP) { |
| 859 | if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) { |
| 860 | ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error(); |
| 861 | return "Failure"; |
| 862 | } |
| 863 | if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) { |
| 864 | ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error(); |
| 865 | return "Failure"; |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | // Determine output size. |
| 870 | size_t outlen; |
| 871 | if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen, |
| 872 | reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) { |
| 873 | ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error(); |
| 874 | return "Failure"; |
| 875 | } |
| 876 | |
| 877 | // Left-zero-pad the input if necessary. |
| 878 | const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data()); |
| 879 | size_t to_encrypt_len = message.size(); |
| 880 | |
| 881 | std::unique_ptr<string> zero_padded_message; |
| 882 | if (padding == PaddingMode::NONE && to_encrypt_len < outlen) { |
| 883 | zero_padded_message.reset(new string(outlen, '\0')); |
| 884 | memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(), |
| 885 | message.size()); |
| 886 | to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data()); |
| 887 | to_encrypt_len = outlen; |
| 888 | } |
| 889 | |
| 890 | // Do the encryption. |
| 891 | string output(outlen, '\0'); |
| 892 | if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt, |
| 893 | to_encrypt_len) <= 0) { |
| 894 | ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error(); |
| 895 | return "Failure"; |
| 896 | } |
| 897 | return output; |
| 898 | } |
| 899 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 900 | string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message, |
| 901 | const AuthorizationSet& in_params, |
| 902 | AuthorizationSet* out_params) { |
| 903 | SCOPED_TRACE("EncryptMessage"); |
| 904 | return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params); |
| 905 | } |
| 906 | |
| 907 | string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params, |
| 908 | AuthorizationSet* out_params) { |
| 909 | SCOPED_TRACE("EncryptMessage"); |
| 910 | return EncryptMessage(key_blob_, message, params, out_params); |
| 911 | } |
| 912 | |
| 913 | string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) { |
| 914 | SCOPED_TRACE("EncryptMessage"); |
| 915 | AuthorizationSet out_params; |
| 916 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 917 | EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params; |
| 918 | return ciphertext; |
| 919 | } |
| 920 | |
| 921 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 922 | PaddingMode padding) { |
| 923 | SCOPED_TRACE("EncryptMessage"); |
| 924 | auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding); |
| 925 | AuthorizationSet out_params; |
| 926 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 927 | EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params; |
| 928 | return ciphertext; |
| 929 | } |
| 930 | |
| 931 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 932 | PaddingMode padding, vector<uint8_t>* iv_out) { |
| 933 | SCOPED_TRACE("EncryptMessage"); |
| 934 | auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding); |
| 935 | AuthorizationSet out_params; |
| 936 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 937 | EXPECT_EQ(1U, out_params.size()); |
| 938 | auto ivVal = out_params.GetTagValue(TAG_NONCE); |
Janis Danisevskis | 5ba0933 | 2020-12-17 10:05:15 -0800 | [diff] [blame] | 939 | EXPECT_TRUE(ivVal); |
| 940 | if (ivVal) *iv_out = *ivVal; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 941 | return ciphertext; |
| 942 | } |
| 943 | |
| 944 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 945 | PaddingMode padding, const vector<uint8_t>& iv_in) { |
| 946 | SCOPED_TRACE("EncryptMessage"); |
| 947 | auto params = AuthorizationSetBuilder() |
| 948 | .BlockMode(block_mode) |
| 949 | .Padding(padding) |
| 950 | .Authorization(TAG_NONCE, iv_in); |
| 951 | AuthorizationSet out_params; |
| 952 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 953 | return ciphertext; |
| 954 | } |
| 955 | |
| 956 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 957 | PaddingMode padding, uint8_t mac_length_bits, |
| 958 | const vector<uint8_t>& iv_in) { |
| 959 | SCOPED_TRACE("EncryptMessage"); |
| 960 | auto params = AuthorizationSetBuilder() |
| 961 | .BlockMode(block_mode) |
| 962 | .Padding(padding) |
| 963 | .Authorization(TAG_MAC_LENGTH, mac_length_bits) |
| 964 | .Authorization(TAG_NONCE, iv_in); |
| 965 | AuthorizationSet out_params; |
| 966 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 967 | return ciphertext; |
| 968 | } |
| 969 | |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 970 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 971 | PaddingMode padding, uint8_t mac_length_bits) { |
| 972 | SCOPED_TRACE("EncryptMessage"); |
| 973 | auto params = AuthorizationSetBuilder() |
| 974 | .BlockMode(block_mode) |
| 975 | .Padding(padding) |
| 976 | .Authorization(TAG_MAC_LENGTH, mac_length_bits); |
| 977 | AuthorizationSet out_params; |
| 978 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 979 | return ciphertext; |
| 980 | } |
| 981 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 982 | string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob, |
| 983 | const string& ciphertext, |
| 984 | const AuthorizationSet& params) { |
| 985 | SCOPED_TRACE("DecryptMessage"); |
| 986 | AuthorizationSet out_params; |
| 987 | string plaintext = |
| 988 | ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params); |
| 989 | EXPECT_TRUE(out_params.empty()); |
| 990 | return plaintext; |
| 991 | } |
| 992 | |
| 993 | string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, |
| 994 | const AuthorizationSet& params) { |
| 995 | SCOPED_TRACE("DecryptMessage"); |
| 996 | return DecryptMessage(key_blob_, ciphertext, params); |
| 997 | } |
| 998 | |
| 999 | string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode, |
| 1000 | PaddingMode padding_mode, const vector<uint8_t>& iv) { |
| 1001 | SCOPED_TRACE("DecryptMessage"); |
| 1002 | auto params = AuthorizationSetBuilder() |
| 1003 | .BlockMode(block_mode) |
| 1004 | .Padding(padding_mode) |
| 1005 | .Authorization(TAG_NONCE, iv); |
| 1006 | return DecryptMessage(key_blob_, ciphertext, params); |
| 1007 | } |
| 1008 | |
| 1009 | std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey( |
| 1010 | const vector<uint8_t>& key_blob) { |
| 1011 | std::pair<ErrorCode, vector<uint8_t>> retval; |
| 1012 | vector<uint8_t> outKeyBlob; |
| 1013 | Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob); |
| 1014 | ErrorCode errorcode = GetReturnErrorCode(result); |
| 1015 | retval = std::tie(errorcode, outKeyBlob); |
| 1016 | |
| 1017 | return retval; |
| 1018 | } |
| 1019 | vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) { |
| 1020 | switch (algorithm) { |
| 1021 | case Algorithm::RSA: |
| 1022 | switch (SecLevel()) { |
| 1023 | case SecurityLevel::SOFTWARE: |
| 1024 | case SecurityLevel::TRUSTED_ENVIRONMENT: |
| 1025 | return {2048, 3072, 4096}; |
| 1026 | case SecurityLevel::STRONGBOX: |
| 1027 | return {2048}; |
| 1028 | default: |
| 1029 | ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel()); |
| 1030 | break; |
| 1031 | } |
| 1032 | break; |
| 1033 | case Algorithm::EC: |
David Drysdale | df09e54 | 2021-06-08 15:46:11 +0100 | [diff] [blame] | 1034 | ADD_FAILURE() << "EC keys must be specified by curve not size"; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1035 | break; |
| 1036 | case Algorithm::AES: |
| 1037 | return {128, 256}; |
| 1038 | case Algorithm::TRIPLE_DES: |
| 1039 | return {168}; |
| 1040 | case Algorithm::HMAC: { |
| 1041 | vector<uint32_t> retval((512 - 64) / 8 + 1); |
| 1042 | uint32_t size = 64 - 8; |
| 1043 | std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); }); |
| 1044 | return retval; |
| 1045 | } |
| 1046 | default: |
| 1047 | ADD_FAILURE() << "Invalid Algorithm: " << algorithm; |
| 1048 | return {}; |
| 1049 | } |
| 1050 | ADD_FAILURE() << "Should be impossible to get here"; |
| 1051 | return {}; |
| 1052 | } |
| 1053 | |
| 1054 | vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) { |
| 1055 | if (SecLevel() == SecurityLevel::STRONGBOX) { |
| 1056 | switch (algorithm) { |
| 1057 | case Algorithm::RSA: |
| 1058 | return {3072, 4096}; |
| 1059 | case Algorithm::EC: |
| 1060 | return {224, 384, 521}; |
| 1061 | case Algorithm::AES: |
| 1062 | return {192}; |
David Drysdale | 7de9feb | 2021-03-05 14:56:19 +0000 | [diff] [blame] | 1063 | case Algorithm::TRIPLE_DES: |
| 1064 | return {56}; |
| 1065 | default: |
| 1066 | return {}; |
| 1067 | } |
| 1068 | } else { |
| 1069 | switch (algorithm) { |
Prashant Patil | d72b351 | 2021-11-16 08:19:19 +0000 | [diff] [blame^] | 1070 | case Algorithm::AES: |
| 1071 | return {64, 96, 131, 512}; |
David Drysdale | 7de9feb | 2021-03-05 14:56:19 +0000 | [diff] [blame] | 1072 | case Algorithm::TRIPLE_DES: |
| 1073 | return {56}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1074 | default: |
| 1075 | return {}; |
| 1076 | } |
| 1077 | } |
| 1078 | return {}; |
| 1079 | } |
| 1080 | |
David Drysdale | 7de9feb | 2021-03-05 14:56:19 +0000 | [diff] [blame] | 1081 | vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) { |
| 1082 | switch (algorithm) { |
| 1083 | case Algorithm::AES: |
| 1084 | return { |
| 1085 | BlockMode::CBC, |
| 1086 | BlockMode::CTR, |
| 1087 | BlockMode::ECB, |
| 1088 | BlockMode::GCM, |
| 1089 | }; |
| 1090 | case Algorithm::TRIPLE_DES: |
| 1091 | return { |
| 1092 | BlockMode::CBC, |
| 1093 | BlockMode::ECB, |
| 1094 | }; |
| 1095 | default: |
| 1096 | return {}; |
| 1097 | } |
| 1098 | } |
| 1099 | |
| 1100 | vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm, |
| 1101 | BlockMode blockMode) { |
| 1102 | switch (algorithm) { |
| 1103 | case Algorithm::AES: |
| 1104 | switch (blockMode) { |
| 1105 | case BlockMode::CBC: |
| 1106 | case BlockMode::ECB: |
| 1107 | return {PaddingMode::NONE, PaddingMode::PKCS7}; |
| 1108 | case BlockMode::CTR: |
| 1109 | case BlockMode::GCM: |
| 1110 | return {PaddingMode::NONE}; |
| 1111 | default: |
| 1112 | return {}; |
| 1113 | }; |
| 1114 | case Algorithm::TRIPLE_DES: |
| 1115 | switch (blockMode) { |
| 1116 | case BlockMode::CBC: |
| 1117 | case BlockMode::ECB: |
| 1118 | return {PaddingMode::NONE, PaddingMode::PKCS7}; |
| 1119 | default: |
| 1120 | return {}; |
| 1121 | }; |
| 1122 | default: |
| 1123 | return {}; |
| 1124 | } |
| 1125 | } |
| 1126 | |
| 1127 | vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm, |
| 1128 | BlockMode blockMode) { |
| 1129 | switch (algorithm) { |
| 1130 | case Algorithm::AES: |
| 1131 | switch (blockMode) { |
| 1132 | case BlockMode::CTR: |
| 1133 | case BlockMode::GCM: |
| 1134 | return {PaddingMode::PKCS7}; |
| 1135 | default: |
| 1136 | return {}; |
| 1137 | }; |
| 1138 | default: |
| 1139 | return {}; |
| 1140 | } |
| 1141 | } |
| 1142 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1143 | vector<EcCurve> KeyMintAidlTestBase::ValidCurves() { |
| 1144 | if (securityLevel_ == SecurityLevel::STRONGBOX) { |
| 1145 | return {EcCurve::P_256}; |
| 1146 | } else { |
| 1147 | return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}; |
| 1148 | } |
| 1149 | } |
| 1150 | |
| 1151 | vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() { |
David Drysdale | df09e54 | 2021-06-08 15:46:11 +0100 | [diff] [blame] | 1152 | if (SecLevel() == SecurityLevel::STRONGBOX) { |
| 1153 | return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521}; |
| 1154 | } else { |
| 1155 | return {}; |
| 1156 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1157 | } |
| 1158 | |
| 1159 | vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) { |
| 1160 | switch (SecLevel()) { |
| 1161 | case SecurityLevel::SOFTWARE: |
| 1162 | case SecurityLevel::TRUSTED_ENVIRONMENT: |
| 1163 | if (withNone) { |
| 1164 | if (withMD5) |
| 1165 | return {Digest::NONE, Digest::MD5, Digest::SHA1, |
| 1166 | Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384, |
| 1167 | Digest::SHA_2_512}; |
| 1168 | else |
| 1169 | return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224, |
| 1170 | Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}; |
| 1171 | } else { |
| 1172 | if (withMD5) |
| 1173 | return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224, |
| 1174 | Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}; |
| 1175 | else |
| 1176 | return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384, |
| 1177 | Digest::SHA_2_512}; |
| 1178 | } |
| 1179 | break; |
| 1180 | case SecurityLevel::STRONGBOX: |
| 1181 | if (withNone) |
| 1182 | return {Digest::NONE, Digest::SHA_2_256}; |
| 1183 | else |
| 1184 | return {Digest::SHA_2_256}; |
| 1185 | break; |
| 1186 | default: |
| 1187 | ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel()); |
| 1188 | break; |
| 1189 | } |
| 1190 | ADD_FAILURE() << "Should be impossible to get here"; |
| 1191 | return {}; |
| 1192 | } |
| 1193 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 1194 | static const vector<KeyParameter> kEmptyAuthList{}; |
| 1195 | |
| 1196 | const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations( |
| 1197 | const vector<KeyCharacteristics>& key_characteristics) { |
| 1198 | auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(), |
| 1199 | [this](auto& entry) { return entry.securityLevel == SecLevel(); }); |
| 1200 | return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations; |
| 1201 | } |
| 1202 | |
Qi Wu | beefae4 | 2021-01-28 23:16:37 +0800 | [diff] [blame] | 1203 | const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations( |
| 1204 | const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) { |
| 1205 | auto found = std::find_if( |
| 1206 | key_characteristics.begin(), key_characteristics.end(), |
| 1207 | [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; }); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 1208 | return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations; |
| 1209 | } |
| 1210 | |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1211 | ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 1212 | auto [result, ciphertext] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1213 | aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456", |
| 1214 | AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)); |
| 1215 | return result; |
| 1216 | } |
| 1217 | |
| 1218 | ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 1219 | auto [result, mac] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1220 | hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456", |
| 1221 | AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256)); |
| 1222 | return result; |
| 1223 | } |
| 1224 | |
| 1225 | ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) { |
| 1226 | std::string message(2048 / 8, 'a'); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 1227 | auto [result, signature] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1228 | rsaKeyBlob, KeyPurpose::SIGN, message, |
| 1229 | AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)); |
| 1230 | return result; |
| 1231 | } |
| 1232 | |
| 1233 | ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 1234 | auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a", |
| 1235 | AuthorizationSetBuilder().Digest(Digest::SHA_2_256)); |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1236 | return result; |
| 1237 | } |
| 1238 | |
Selene Huang | 6e46f14 | 2021-04-20 19:20:11 -0700 | [diff] [blame] | 1239 | void verify_serial(X509* cert, const uint64_t expected_serial) { |
| 1240 | BIGNUM_Ptr ser(BN_new()); |
| 1241 | EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get())); |
| 1242 | |
| 1243 | uint64_t serial; |
| 1244 | EXPECT_TRUE(BN_get_u64(ser.get(), &serial)); |
| 1245 | EXPECT_EQ(serial, expected_serial); |
| 1246 | } |
| 1247 | |
| 1248 | // Please set self_signed to true for fake certificates or self signed |
| 1249 | // certificates |
| 1250 | void verify_subject(const X509* cert, // |
| 1251 | const string& subject, // |
| 1252 | bool self_signed) { |
| 1253 | char* cert_issuer = // |
| 1254 | X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0); |
| 1255 | |
| 1256 | char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0); |
| 1257 | |
| 1258 | string expected_subject("/CN="); |
| 1259 | if (subject.empty()) { |
| 1260 | expected_subject.append("Android Keystore Key"); |
| 1261 | } else { |
| 1262 | expected_subject.append(subject); |
| 1263 | } |
| 1264 | |
| 1265 | EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj; |
| 1266 | |
| 1267 | if (self_signed) { |
| 1268 | EXPECT_STREQ(cert_issuer, cert_subj) |
| 1269 | << "Cert issuer and subject mismatch for self signed certificate."; |
| 1270 | } |
| 1271 | |
| 1272 | OPENSSL_free(cert_subj); |
| 1273 | OPENSSL_free(cert_issuer); |
| 1274 | } |
| 1275 | |
| 1276 | vector<uint8_t> build_serial_blob(const uint64_t serial_int) { |
| 1277 | BIGNUM_Ptr serial(BN_new()); |
| 1278 | EXPECT_TRUE(BN_set_u64(serial.get(), serial_int)); |
| 1279 | |
| 1280 | int len = BN_num_bytes(serial.get()); |
| 1281 | vector<uint8_t> serial_blob(len); |
| 1282 | if (BN_bn2bin(serial.get(), serial_blob.data()) != len) { |
| 1283 | return {}; |
| 1284 | } |
| 1285 | |
David Drysdale | db0dcf5 | 2021-05-18 11:43:31 +0100 | [diff] [blame] | 1286 | if (serial_blob.empty() || serial_blob[0] & 0x80) { |
| 1287 | // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte. |
| 1288 | // Top bit being set indicates a negative number in two's complement, but our input |
| 1289 | // was positive. |
| 1290 | // In either case, prepend a zero byte. |
| 1291 | serial_blob.insert(serial_blob.begin(), 0x00); |
| 1292 | } |
| 1293 | |
Selene Huang | 6e46f14 | 2021-04-20 19:20:11 -0700 | [diff] [blame] | 1294 | return serial_blob; |
| 1295 | } |
| 1296 | |
| 1297 | void verify_subject_and_serial(const Certificate& certificate, // |
| 1298 | const uint64_t expected_serial, // |
| 1299 | const string& subject, bool self_signed) { |
| 1300 | X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate)); |
| 1301 | ASSERT_TRUE(!!cert.get()); |
| 1302 | |
| 1303 | verify_serial(cert.get(), expected_serial); |
| 1304 | verify_subject(cert.get(), subject, self_signed); |
| 1305 | } |
| 1306 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1307 | bool verify_attestation_record(const string& challenge, // |
| 1308 | const string& app_id, // |
| 1309 | AuthorizationSet expected_sw_enforced, // |
| 1310 | AuthorizationSet expected_hw_enforced, // |
| 1311 | SecurityLevel security_level, |
David Drysdale | 565ccc7 | 2021-10-11 12:49:50 +0100 | [diff] [blame] | 1312 | const vector<uint8_t>& attestation_cert, |
| 1313 | vector<uint8_t>* unique_id) { |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1314 | X509_Ptr cert(parse_cert_blob(attestation_cert)); |
| 1315 | EXPECT_TRUE(!!cert.get()); |
| 1316 | if (!cert.get()) return false; |
| 1317 | |
| 1318 | ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get()); |
| 1319 | EXPECT_TRUE(!!attest_rec); |
| 1320 | if (!attest_rec) return false; |
| 1321 | |
| 1322 | AuthorizationSet att_sw_enforced; |
| 1323 | AuthorizationSet att_hw_enforced; |
| 1324 | uint32_t att_attestation_version; |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1325 | uint32_t att_keymint_version; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1326 | SecurityLevel att_attestation_security_level; |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1327 | SecurityLevel att_keymint_security_level; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1328 | vector<uint8_t> att_challenge; |
| 1329 | vector<uint8_t> att_unique_id; |
| 1330 | vector<uint8_t> att_app_id; |
| 1331 | |
| 1332 | auto error = parse_attestation_record(attest_rec->data, // |
| 1333 | attest_rec->length, // |
| 1334 | &att_attestation_version, // |
| 1335 | &att_attestation_security_level, // |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1336 | &att_keymint_version, // |
| 1337 | &att_keymint_security_level, // |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1338 | &att_challenge, // |
| 1339 | &att_sw_enforced, // |
| 1340 | &att_hw_enforced, // |
| 1341 | &att_unique_id); |
| 1342 | EXPECT_EQ(ErrorCode::OK, error); |
| 1343 | if (error != ErrorCode::OK) return false; |
| 1344 | |
Shawn Willden | 3cb64a6 | 2021-04-05 14:39:05 -0600 | [diff] [blame] | 1345 | EXPECT_EQ(att_attestation_version, 100U); |
Selene Huang | 4f64c22 | 2021-04-13 19:54:36 -0700 | [diff] [blame] | 1346 | vector<uint8_t> appId(app_id.begin(), app_id.end()); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1347 | |
Selene Huang | 4f64c22 | 2021-04-13 19:54:36 -0700 | [diff] [blame] | 1348 | // check challenge and app id only if we expects a non-fake certificate |
| 1349 | if (challenge.length() > 0) { |
| 1350 | EXPECT_EQ(challenge.length(), att_challenge.size()); |
| 1351 | EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length())); |
| 1352 | |
| 1353 | expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId); |
| 1354 | } |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1355 | |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1356 | EXPECT_EQ(att_keymint_version, 100U); |
| 1357 | EXPECT_EQ(security_level, att_keymint_security_level); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1358 | EXPECT_EQ(security_level, att_attestation_security_level); |
| 1359 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1360 | |
| 1361 | char property_value[PROPERTY_VALUE_MAX] = {}; |
| 1362 | // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1363 | // keymint implementation will report YYYYMM dates instead of YYYYMMDD |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1364 | // for the BOOT_PATCH_LEVEL. |
| 1365 | if (avb_verification_enabled()) { |
| 1366 | for (int i = 0; i < att_hw_enforced.size(); i++) { |
| 1367 | if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL || |
| 1368 | att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) { |
| 1369 | std::string date = |
Tommy Chiu | f00d8f1 | 2021-04-08 11:07:48 +0800 | [diff] [blame] | 1370 | std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>()); |
David Drysdale | 168228a | 2021-10-05 08:43:52 +0100 | [diff] [blame] | 1371 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1372 | // strptime seems to require delimiters, but the tag value will |
| 1373 | // be YYYYMMDD |
David Drysdale | 168228a | 2021-10-05 08:43:52 +0100 | [diff] [blame] | 1374 | if (date.size() != 8) { |
| 1375 | ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag |
| 1376 | << " with invalid format (not YYYYMMDD): " << date; |
| 1377 | return false; |
| 1378 | } |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1379 | date.insert(6, "-"); |
| 1380 | date.insert(4, "-"); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1381 | struct tm time; |
| 1382 | strptime(date.c_str(), "%Y-%m-%d", &time); |
| 1383 | |
| 1384 | // Day of the month (0-31) |
| 1385 | EXPECT_GE(time.tm_mday, 0); |
| 1386 | EXPECT_LT(time.tm_mday, 32); |
| 1387 | // Months since Jan (0-11) |
| 1388 | EXPECT_GE(time.tm_mon, 0); |
| 1389 | EXPECT_LT(time.tm_mon, 12); |
| 1390 | // Years since 1900 |
| 1391 | EXPECT_GT(time.tm_year, 110); |
| 1392 | EXPECT_LT(time.tm_year, 200); |
| 1393 | } |
| 1394 | } |
| 1395 | } |
| 1396 | |
| 1397 | // Check to make sure boolean values are properly encoded. Presence of a boolean tag |
| 1398 | // indicates true. A provided boolean tag that can be pulled back out of the certificate |
| 1399 | // indicates correct encoding. No need to check if it's in both lists, since the |
| 1400 | // AuthorizationSet compare below will handle mismatches of tags. |
| 1401 | if (security_level == SecurityLevel::SOFTWARE) { |
| 1402 | EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED)); |
| 1403 | } else { |
| 1404 | EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED)); |
| 1405 | } |
| 1406 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1407 | if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) { |
| 1408 | // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be. |
| 1409 | EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) || |
| 1410 | att_hw_enforced.Contains(TAG_KEY_SIZE)); |
| 1411 | } |
| 1412 | |
| 1413 | // Test root of trust elements |
| 1414 | vector<uint8_t> verified_boot_key; |
| 1415 | VerifiedBoot verified_boot_state; |
| 1416 | bool device_locked; |
| 1417 | vector<uint8_t> verified_boot_hash; |
| 1418 | error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key, |
| 1419 | &verified_boot_state, &device_locked, &verified_boot_hash); |
| 1420 | EXPECT_EQ(ErrorCode::OK, error); |
| 1421 | |
| 1422 | if (avb_verification_enabled()) { |
| 1423 | EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0); |
| 1424 | string prop_string(property_value); |
| 1425 | EXPECT_EQ(prop_string.size(), 64); |
| 1426 | EXPECT_EQ(prop_string, bin2hex(verified_boot_hash)); |
| 1427 | |
| 1428 | EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0); |
| 1429 | if (!strcmp(property_value, "unlocked")) { |
| 1430 | EXPECT_FALSE(device_locked); |
| 1431 | } else { |
| 1432 | EXPECT_TRUE(device_locked); |
| 1433 | } |
| 1434 | |
| 1435 | // Check that the device is locked if not debuggable, e.g., user build |
| 1436 | // images in CTS. For VTS, debuggable images are used to allow adb root |
| 1437 | // and the device is unlocked. |
| 1438 | if (!property_get_bool("ro.debuggable", false)) { |
| 1439 | EXPECT_TRUE(device_locked); |
| 1440 | } else { |
| 1441 | EXPECT_FALSE(device_locked); |
| 1442 | } |
| 1443 | } |
| 1444 | |
| 1445 | // Verified boot key should be all 0's if the boot state is not verified or self signed |
| 1446 | std::string empty_boot_key(32, '\0'); |
| 1447 | std::string verified_boot_key_str((const char*)verified_boot_key.data(), |
| 1448 | verified_boot_key.size()); |
| 1449 | EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0); |
| 1450 | if (!strcmp(property_value, "green")) { |
| 1451 | EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED); |
| 1452 | EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1453 | verified_boot_key.size())); |
| 1454 | } else if (!strcmp(property_value, "yellow")) { |
| 1455 | EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED); |
| 1456 | EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1457 | verified_boot_key.size())); |
| 1458 | } else if (!strcmp(property_value, "orange")) { |
| 1459 | EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED); |
| 1460 | EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1461 | verified_boot_key.size())); |
| 1462 | } else if (!strcmp(property_value, "red")) { |
| 1463 | EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED); |
| 1464 | } else { |
| 1465 | EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED); |
| 1466 | EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1467 | verified_boot_key.size())); |
| 1468 | } |
| 1469 | |
| 1470 | att_sw_enforced.Sort(); |
| 1471 | expected_sw_enforced.Sort(); |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1472 | EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced)); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1473 | |
| 1474 | att_hw_enforced.Sort(); |
| 1475 | expected_hw_enforced.Sort(); |
| 1476 | EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced)); |
| 1477 | |
David Drysdale | 565ccc7 | 2021-10-11 12:49:50 +0100 | [diff] [blame] | 1478 | if (unique_id != nullptr) { |
| 1479 | *unique_id = att_unique_id; |
| 1480 | } |
| 1481 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1482 | return true; |
| 1483 | } |
| 1484 | |
| 1485 | string bin2hex(const vector<uint8_t>& data) { |
| 1486 | string retval; |
| 1487 | retval.reserve(data.size() * 2 + 1); |
| 1488 | for (uint8_t byte : data) { |
| 1489 | retval.push_back(nibble2hex[0x0F & (byte >> 4)]); |
| 1490 | retval.push_back(nibble2hex[0x0F & byte]); |
| 1491 | } |
| 1492 | return retval; |
| 1493 | } |
| 1494 | |
David Drysdale | f0d516d | 2021-03-22 07:51:43 +0000 | [diff] [blame] | 1495 | AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) { |
| 1496 | AuthorizationSet authList; |
| 1497 | for (auto& entry : key_characteristics) { |
| 1498 | if (entry.securityLevel == SecurityLevel::STRONGBOX || |
| 1499 | entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) { |
| 1500 | authList.push_back(AuthorizationSet(entry.authorizations)); |
| 1501 | } |
| 1502 | } |
| 1503 | return authList; |
| 1504 | } |
| 1505 | |
| 1506 | AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) { |
| 1507 | AuthorizationSet authList; |
| 1508 | for (auto& entry : key_characteristics) { |
| 1509 | if (entry.securityLevel == SecurityLevel::SOFTWARE || |
| 1510 | entry.securityLevel == SecurityLevel::KEYSTORE) { |
| 1511 | authList.push_back(AuthorizationSet(entry.authorizations)); |
| 1512 | } |
| 1513 | } |
| 1514 | return authList; |
| 1515 | } |
| 1516 | |
Eran Messeri | 03d7a1a | 2021-07-06 12:07:57 +0100 | [diff] [blame] | 1517 | AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain, |
| 1518 | bool strict_issuer_check) { |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1519 | std::stringstream cert_data; |
| 1520 | |
| 1521 | for (size_t i = 0; i < chain.size(); ++i) { |
| 1522 | cert_data << bin2hex(chain[i].encodedCertificate) << std::endl; |
| 1523 | |
| 1524 | X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate)); |
| 1525 | X509_Ptr signing_cert; |
| 1526 | if (i < chain.size() - 1) { |
| 1527 | signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate); |
| 1528 | } else { |
| 1529 | signing_cert = parse_cert_blob(chain[i].encodedCertificate); |
| 1530 | } |
| 1531 | if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str(); |
| 1532 | |
| 1533 | EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get())); |
| 1534 | if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str(); |
| 1535 | |
| 1536 | if (!X509_verify(key_cert.get(), signing_pubkey.get())) { |
| 1537 | return AssertionFailure() |
| 1538 | << "Verification of certificate " << i << " failed " |
| 1539 | << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n' |
| 1540 | << cert_data.str(); |
| 1541 | } |
| 1542 | |
| 1543 | string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get())); |
| 1544 | string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get())); |
Eran Messeri | 03d7a1a | 2021-07-06 12:07:57 +0100 | [diff] [blame] | 1545 | if (cert_issuer != signer_subj && strict_issuer_check) { |
Selene Huang | 8f9494c | 2021-04-21 15:10:36 -0700 | [diff] [blame] | 1546 | return AssertionFailure() << "Cert " << i << " has wrong issuer.\n" |
| 1547 | << " Signer subject is " << signer_subj |
| 1548 | << " Issuer subject is " << cert_issuer << endl |
| 1549 | << cert_data.str(); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1550 | } |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1551 | } |
| 1552 | |
| 1553 | if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str(); |
| 1554 | return AssertionSuccess(); |
| 1555 | } |
| 1556 | |
| 1557 | X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) { |
| 1558 | const uint8_t* p = blob.data(); |
| 1559 | return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size())); |
| 1560 | } |
| 1561 | |
David Drysdale | f0d516d | 2021-03-22 07:51:43 +0000 | [diff] [blame] | 1562 | vector<uint8_t> make_name_from_str(const string& name) { |
| 1563 | X509_NAME_Ptr x509_name(X509_NAME_new()); |
| 1564 | EXPECT_TRUE(x509_name.get() != nullptr); |
| 1565 | if (!x509_name) return {}; |
| 1566 | |
| 1567 | EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), // |
| 1568 | "CN", // |
| 1569 | MBSTRING_ASC, |
| 1570 | reinterpret_cast<const uint8_t*>(name.c_str()), |
| 1571 | -1, // len |
| 1572 | -1, // loc |
| 1573 | 0 /* set */)); |
| 1574 | |
| 1575 | int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */); |
| 1576 | EXPECT_GT(len, 0); |
| 1577 | |
| 1578 | vector<uint8_t> retval(len); |
| 1579 | uint8_t* p = retval.data(); |
| 1580 | i2d_X509_NAME(x509_name.get(), &p); |
| 1581 | |
| 1582 | return retval; |
| 1583 | } |
| 1584 | |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 1585 | namespace { |
| 1586 | |
| 1587 | void check_cose_key(const vector<uint8_t>& data, bool testMode) { |
| 1588 | auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data); |
| 1589 | ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr; |
| 1590 | |
| 1591 | // The following check assumes that canonical CBOR encoding is used for the COSE_Key. |
| 1592 | if (testMode) { |
| 1593 | EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()), |
| 1594 | MatchesRegex("{\n" |
| 1595 | " 1 : 2,\n" // kty: EC2 |
| 1596 | " 3 : -7,\n" // alg: ES256 |
| 1597 | " -1 : 1,\n" // EC id: P256 |
| 1598 | // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a |
| 1599 | // sequence of 32 hexadecimal bytes, enclosed in braces and |
| 1600 | // separated by commas. In this case, some Ed25519 public key. |
| 1601 | " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data |
| 1602 | " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data |
| 1603 | " -70000 : null,\n" // test marker |
| 1604 | "}")); |
| 1605 | } else { |
| 1606 | EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()), |
| 1607 | MatchesRegex("{\n" |
| 1608 | " 1 : 2,\n" // kty: EC2 |
| 1609 | " 3 : -7,\n" // alg: ES256 |
| 1610 | " -1 : 1,\n" // EC id: P256 |
| 1611 | // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a |
| 1612 | // sequence of 32 hexadecimal bytes, enclosed in braces and |
| 1613 | // separated by commas. In this case, some Ed25519 public key. |
| 1614 | " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data |
| 1615 | " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data |
| 1616 | "}")); |
| 1617 | } |
| 1618 | } |
| 1619 | |
| 1620 | } // namespace |
| 1621 | |
| 1622 | void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode, |
| 1623 | vector<uint8_t>* payload_value) { |
| 1624 | auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey); |
| 1625 | ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr; |
| 1626 | |
| 1627 | ASSERT_NE(coseMac0->asArray(), nullptr); |
| 1628 | ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount); |
| 1629 | |
| 1630 | auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr(); |
| 1631 | ASSERT_NE(protParms, nullptr); |
| 1632 | |
| 1633 | // Header label:value of 'alg': HMAC-256 |
| 1634 | ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}"); |
| 1635 | |
| 1636 | auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap(); |
| 1637 | ASSERT_NE(unprotParms, nullptr); |
| 1638 | ASSERT_EQ(unprotParms->size(), 0); |
| 1639 | |
| 1640 | // The payload is a bstr holding an encoded COSE_Key |
| 1641 | auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr(); |
| 1642 | ASSERT_NE(payload, nullptr); |
| 1643 | check_cose_key(payload->value(), testMode); |
| 1644 | |
| 1645 | auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr(); |
| 1646 | ASSERT_TRUE(coseMac0Tag); |
| 1647 | auto extractedTag = coseMac0Tag->value(); |
| 1648 | EXPECT_EQ(extractedTag.size(), 32U); |
| 1649 | |
| 1650 | // Compare with tag generated with kTestMacKey. Should only match in test mode |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 1651 | auto macFunction = [](const cppcose::bytevec& input) { |
| 1652 | return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input); |
| 1653 | }; |
| 1654 | auto testTag = |
| 1655 | cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value()); |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 1656 | ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message(); |
| 1657 | |
| 1658 | if (testMode) { |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 1659 | EXPECT_THAT(*testTag, ElementsAreArray(extractedTag)); |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 1660 | } else { |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 1661 | EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag))); |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 1662 | } |
| 1663 | if (payload_value != nullptr) { |
| 1664 | *payload_value = payload->value(); |
| 1665 | } |
| 1666 | } |
| 1667 | |
| 1668 | void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) { |
| 1669 | // Extract x and y affine coordinates from the encoded Cose_Key. |
| 1670 | auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData); |
| 1671 | ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr; |
| 1672 | auto coseKey = parsedPayload->asMap(); |
| 1673 | const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X); |
| 1674 | ASSERT_NE(xItem->asBstr(), nullptr); |
| 1675 | vector<uint8_t> x = xItem->asBstr()->value(); |
| 1676 | const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y); |
| 1677 | ASSERT_NE(yItem->asBstr(), nullptr); |
| 1678 | vector<uint8_t> y = yItem->asBstr()->value(); |
| 1679 | |
| 1680 | // Concatenate: 0x04 (uncompressed form marker) | x | y |
| 1681 | vector<uint8_t> pubKeyData{0x04}; |
| 1682 | pubKeyData.insert(pubKeyData.end(), x.begin(), x.end()); |
| 1683 | pubKeyData.insert(pubKeyData.end(), y.begin(), y.end()); |
| 1684 | |
| 1685 | EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new()); |
| 1686 | ASSERT_NE(ecKey, nullptr); |
| 1687 | EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); |
| 1688 | ASSERT_NE(group, nullptr); |
| 1689 | ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1); |
| 1690 | EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get())); |
| 1691 | ASSERT_NE(point, nullptr); |
| 1692 | ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(), |
| 1693 | nullptr), |
| 1694 | 1); |
| 1695 | ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1); |
| 1696 | |
| 1697 | EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new()); |
| 1698 | ASSERT_NE(pubKey, nullptr); |
| 1699 | EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release()); |
| 1700 | *signingKey = std::move(pubKey); |
| 1701 | } |
| 1702 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1703 | } // namespace test |
Shawn Willden | 08a7e43 | 2020-12-11 13:05:27 +0000 | [diff] [blame] | 1704 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 1705 | } // namespace aidl::android::hardware::security::keymint |