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