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> |
David Drysdale | 555ba00 | 2022-05-03 18:48:57 +0100 | [diff] [blame] | 20 | #include <fstream> |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 21 | #include <unordered_set> |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 22 | #include <vector> |
| 23 | |
| 24 | #include <android-base/logging.h> |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 25 | #include <android/binder_manager.h> |
David Drysdale | 3d2ba0a | 2023-01-11 13:27:26 +0000 | [diff] [blame] | 26 | #include <android/content/pm/IPackageManagerNative.h> |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 27 | #include <cppbor_parse.h> |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 28 | #include <cutils/properties.h> |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 29 | #include <gmock/gmock.h> |
David Drysdale | 42fe189 | 2021-10-14 14:43:46 +0100 | [diff] [blame] | 30 | #include <openssl/evp.h> |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 31 | #include <openssl/mem.h> |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 32 | #include <remote_prov/remote_prov_utils.h> |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 33 | |
Max Bires | 9704ff6 | 2021-04-07 11:12:01 -0700 | [diff] [blame] | 34 | #include <keymaster/cppcose/cppcose.h> |
Shawn Willden | 08a7e43 | 2020-12-11 13:05:27 +0000 | [diff] [blame] | 35 | #include <keymint_support/key_param_output.h> |
| 36 | #include <keymint_support/keymint_utils.h> |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 37 | #include <keymint_support/openssl_utils.h> |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 38 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 39 | namespace aidl::android::hardware::security::keymint { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 40 | |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 41 | using namespace cppcose; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 42 | using namespace std::literals::chrono_literals; |
| 43 | using std::endl; |
| 44 | using std::optional; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 45 | using std::unique_ptr; |
| 46 | using ::testing::AssertionFailure; |
| 47 | using ::testing::AssertionResult; |
| 48 | using ::testing::AssertionSuccess; |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 49 | using ::testing::ElementsAreArray; |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 50 | using ::testing::MatchesRegex; |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 51 | using ::testing::Not; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 52 | |
| 53 | ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) { |
| 54 | if (set.size() == 0) |
| 55 | os << "(Empty)" << ::std::endl; |
| 56 | else { |
| 57 | os << "\n"; |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 58 | for (auto& entry : set) os << entry << ::std::endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 59 | } |
| 60 | return os; |
| 61 | } |
| 62 | |
| 63 | namespace test { |
| 64 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 65 | namespace { |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 66 | |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 67 | // Invalid value for a patchlevel (which is of form YYYYMMDD). |
| 68 | const uint32_t kInvalidPatchlevel = 99998877; |
| 69 | |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 70 | // Overhead for PKCS#1 v1.5 signature padding of undigested messages. Digested messages have |
| 71 | // additional overhead, for the digest algorithmIdentifier required by PKCS#1. |
| 72 | const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11; |
| 73 | |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 74 | typedef KeyMintAidlTestBase::KeyData KeyData; |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 75 | // Predicate for testing basic characteristics validity in generation or import. |
| 76 | bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel, |
| 77 | const vector<KeyCharacteristics>& key_characteristics) { |
| 78 | if (key_characteristics.empty()) return false; |
| 79 | |
| 80 | std::unordered_set<SecurityLevel> levels_seen; |
| 81 | for (auto& entry : key_characteristics) { |
Seth Moore | 2a9a00e | 2021-08-04 16:31:52 -0700 | [diff] [blame] | 82 | if (entry.authorizations.empty()) { |
| 83 | GTEST_LOG_(ERROR) << "empty authorizations for " << entry.securityLevel; |
| 84 | return false; |
| 85 | } |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 86 | |
Qi Wu | beefae4 | 2021-01-28 23:16:37 +0800 | [diff] [blame] | 87 | // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this. |
| 88 | if (entry.securityLevel == SecurityLevel::KEYSTORE) continue; |
| 89 | |
Seth Moore | 2a9a00e | 2021-08-04 16:31:52 -0700 | [diff] [blame] | 90 | if (levels_seen.find(entry.securityLevel) != levels_seen.end()) { |
| 91 | GTEST_LOG_(ERROR) << "duplicate authorizations for " << entry.securityLevel; |
| 92 | return false; |
| 93 | } |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 94 | levels_seen.insert(entry.securityLevel); |
| 95 | |
| 96 | // Generally, we should only have one entry, at the same security level as the KM |
| 97 | // instance. There is an exception: StrongBox KM can have some authorizations that are |
| 98 | // enforced by the TEE. |
| 99 | bool isExpectedSecurityLevel = secLevel == entry.securityLevel || |
| 100 | (secLevel == SecurityLevel::STRONGBOX && |
| 101 | entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT); |
| 102 | |
Seth Moore | 2a9a00e | 2021-08-04 16:31:52 -0700 | [diff] [blame] | 103 | if (!isExpectedSecurityLevel) { |
| 104 | GTEST_LOG_(ERROR) << "Unexpected security level " << entry.securityLevel; |
| 105 | return false; |
| 106 | } |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 107 | } |
| 108 | return true; |
| 109 | } |
| 110 | |
Rajesh Nyamagoud | e98263e | 2023-02-09 20:36:33 +0000 | [diff] [blame] | 111 | void check_crl_distribution_points_extension_not_present(X509* certificate) { |
| 112 | ASN1_OBJECT_Ptr crl_dp_oid(OBJ_txt2obj(kCrlDPOid, 1 /* dotted string format */)); |
| 113 | ASSERT_TRUE(crl_dp_oid.get()); |
| 114 | |
| 115 | int location = |
| 116 | X509_get_ext_by_OBJ(certificate, crl_dp_oid.get(), -1 /* search from beginning */); |
| 117 | ASSERT_EQ(location, -1); |
| 118 | } |
| 119 | |
David Drysdale | 7dff4fc | 2021-12-10 10:10:52 +0000 | [diff] [blame] | 120 | void check_attestation_version(uint32_t attestation_version, int32_t aidl_version) { |
| 121 | // Version numbers in attestation extensions should be a multiple of 100. |
| 122 | EXPECT_EQ(attestation_version % 100, 0); |
| 123 | |
| 124 | // The multiplier should never be higher than the AIDL version, but can be less |
| 125 | // (for example, if the implementation is from an earlier version but the HAL service |
| 126 | // uses the default libraries and so reports the current AIDL version). |
| 127 | EXPECT_TRUE((attestation_version / 100) <= aidl_version); |
| 128 | } |
| 129 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 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; |
David Drysdale | 9f5c0c5 | 2022-11-03 15:10:16 +0000 | [diff] [blame] | 176 | std::string KeyMintAidlTestBase::keyblob_dir; |
Tommy Chiu | 025f3c5 | 2023-05-15 06:23:44 +0000 | [diff] [blame] | 177 | std::optional<bool> KeyMintAidlTestBase::expect_upgrade = std::nullopt; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 178 | |
David Drysdale | 1b9febc | 2023-06-07 13:43:24 +0100 | [diff] [blame] | 179 | KeyBlobDeleter::~KeyBlobDeleter() { |
| 180 | if (key_blob_.empty()) { |
| 181 | return; |
| 182 | } |
| 183 | Status result = keymint_->deleteKey(key_blob_); |
| 184 | key_blob_.clear(); |
| 185 | EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << "\n"; |
| 186 | ErrorCode rc = GetReturnErrorCode(result); |
| 187 | EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED) << result << "\n"; |
| 188 | } |
| 189 | |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 190 | uint32_t KeyMintAidlTestBase::boot_patch_level( |
| 191 | const vector<KeyCharacteristics>& key_characteristics) { |
| 192 | // The boot patchlevel is not available as a property, but should be present |
| 193 | // in the key characteristics of any created key. |
| 194 | AuthorizationSet allAuths; |
| 195 | for (auto& entry : key_characteristics) { |
| 196 | allAuths.push_back(AuthorizationSet(entry.authorizations)); |
| 197 | } |
| 198 | auto patchlevel = allAuths.GetTagValue(TAG_BOOT_PATCHLEVEL); |
| 199 | if (patchlevel.has_value()) { |
| 200 | return patchlevel.value(); |
| 201 | } else { |
| 202 | // No boot patchlevel is available. Return a value that won't match anything |
| 203 | // and so will trigger test failures. |
| 204 | return kInvalidPatchlevel; |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | uint32_t KeyMintAidlTestBase::boot_patch_level() { |
| 209 | return boot_patch_level(key_characteristics_); |
| 210 | } |
| 211 | |
Prashant Patil | 88ad189 | 2022-03-15 16:31:02 +0000 | [diff] [blame] | 212 | /** |
| 213 | * An API to determine device IDs attestation is required or not, |
| 214 | * which is mandatory for KeyMint version 2 or first_api_level 33 or greater. |
| 215 | */ |
| 216 | bool KeyMintAidlTestBase::isDeviceIdAttestationRequired() { |
Shawn Willden | 1a545db | 2023-02-22 14:32:33 -0700 | [diff] [blame] | 217 | return AidlVersion() >= 2 || property_get_int32("ro.vendor.api_level", 0) >= __ANDROID_API_T__; |
Prashant Patil | 88ad189 | 2022-03-15 16:31:02 +0000 | [diff] [blame] | 218 | } |
| 219 | |
Rajesh Nyamagoud | 5283f81 | 2023-01-06 00:27:56 +0000 | [diff] [blame] | 220 | /** |
| 221 | * An API to determine second IMEI ID attestation is required or not, |
| 222 | * which is supported for KeyMint version 3 or first_api_level greater than 33. |
| 223 | */ |
| 224 | bool KeyMintAidlTestBase::isSecondImeiIdAttestationRequired() { |
Shawn Willden | 1a545db | 2023-02-22 14:32:33 -0700 | [diff] [blame] | 225 | return AidlVersion() >= 3 && property_get_int32("ro.vendor.api_level", 0) > __ANDROID_API_T__; |
Rajesh Nyamagoud | 5283f81 | 2023-01-06 00:27:56 +0000 | [diff] [blame] | 226 | } |
| 227 | |
David Drysdale | 42fe189 | 2021-10-14 14:43:46 +0100 | [diff] [blame] | 228 | bool KeyMintAidlTestBase::Curve25519Supported() { |
| 229 | // Strongbox never supports curve 25519. |
| 230 | if (SecLevel() == SecurityLevel::STRONGBOX) { |
| 231 | return false; |
| 232 | } |
| 233 | |
| 234 | // Curve 25519 was included in version 2 of the KeyMint interface. |
| 235 | int32_t version = 0; |
| 236 | auto status = keymint_->getInterfaceVersion(&version); |
| 237 | if (!status.isOk()) { |
| 238 | ADD_FAILURE() << "Failed to determine interface version"; |
| 239 | } |
| 240 | return version >= 2; |
| 241 | } |
| 242 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 243 | void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 244 | ASSERT_NE(keyMint, nullptr); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 245 | keymint_ = std::move(keyMint); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 246 | |
| 247 | KeyMintHardwareInfo info; |
| 248 | ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk()); |
| 249 | |
| 250 | securityLevel_ = info.securityLevel; |
| 251 | name_.assign(info.keyMintName.begin(), info.keyMintName.end()); |
| 252 | author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end()); |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 253 | timestamp_token_required_ = info.timestampTokenRequired; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 254 | |
| 255 | os_version_ = getOsVersion(); |
| 256 | os_patch_level_ = getOsPatchlevel(); |
David Drysdale | bb3d85e | 2021-04-13 11:15:51 +0100 | [diff] [blame] | 257 | vendor_patch_level_ = getVendorPatchlevel(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 258 | } |
| 259 | |
David Drysdale | 7dff4fc | 2021-12-10 10:10:52 +0000 | [diff] [blame] | 260 | int32_t KeyMintAidlTestBase::AidlVersion() { |
| 261 | int32_t version = 0; |
| 262 | auto status = keymint_->getInterfaceVersion(&version); |
| 263 | if (!status.isOk()) { |
| 264 | ADD_FAILURE() << "Failed to determine interface version"; |
| 265 | } |
| 266 | return version; |
| 267 | } |
| 268 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 269 | void KeyMintAidlTestBase::SetUp() { |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 270 | if (AServiceManager_isDeclared(GetParam().c_str())) { |
| 271 | ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str())); |
| 272 | InitializeKeyMint(IKeyMintDevice::fromBinder(binder)); |
| 273 | } else { |
| 274 | InitializeKeyMint(nullptr); |
| 275 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 276 | } |
| 277 | |
| 278 | ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc, |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 279 | const optional<AttestationKey>& attest_key, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 280 | vector<uint8_t>* key_blob, |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 281 | vector<KeyCharacteristics>* key_characteristics, |
| 282 | vector<Certificate>* cert_chain) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 283 | EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug"; |
| 284 | EXPECT_NE(key_characteristics, nullptr) |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 285 | << "Previous characteristics not deleted before generating key. Test bug."; |
| 286 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 287 | KeyCreationResult creationResult; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 288 | Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 289 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 290 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 291 | creationResult.keyCharacteristics); |
| 292 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 293 | *key_blob = std::move(creationResult.keyBlob); |
| 294 | *key_characteristics = std::move(creationResult.keyCharacteristics); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 295 | *cert_chain = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 296 | |
| 297 | auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM); |
| 298 | EXPECT_TRUE(algorithm); |
| 299 | if (algorithm && |
| 300 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 301 | EXPECT_GE(cert_chain->size(), 1); |
| 302 | if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) { |
| 303 | if (attest_key) { |
| 304 | EXPECT_EQ(cert_chain->size(), 1); |
| 305 | } else { |
| 306 | EXPECT_GT(cert_chain->size(), 1); |
| 307 | } |
| 308 | } |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 309 | } else { |
| 310 | // For symmetric keys there should be no certificates. |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 311 | EXPECT_EQ(cert_chain->size(), 0); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 312 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 313 | } |
| 314 | |
| 315 | return GetReturnErrorCode(result); |
| 316 | } |
| 317 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 318 | ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc, |
| 319 | const optional<AttestationKey>& attest_key) { |
| 320 | return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 321 | } |
| 322 | |
subrahmanyaman | 7d9bc46 | 2022-03-16 01:40:39 +0000 | [diff] [blame] | 323 | ErrorCode KeyMintAidlTestBase::GenerateKeyWithSelfSignedAttestKey( |
| 324 | const AuthorizationSet& attest_key_desc, const AuthorizationSet& key_desc, |
| 325 | vector<uint8_t>* key_blob, vector<KeyCharacteristics>* key_characteristics, |
| 326 | vector<Certificate>* cert_chain) { |
Subrahmanyaman | 50fcf7d | 2023-04-20 22:48:39 +0000 | [diff] [blame] | 327 | skipAttestKeyTest(); |
subrahmanyaman | 7d9bc46 | 2022-03-16 01:40:39 +0000 | [diff] [blame] | 328 | AttestationKey attest_key; |
| 329 | vector<Certificate> attest_cert_chain; |
| 330 | vector<KeyCharacteristics> attest_key_characteristics; |
| 331 | // Generate a key with self signed attestation. |
Subrahmanyaman | 50fcf7d | 2023-04-20 22:48:39 +0000 | [diff] [blame] | 332 | auto error = GenerateAttestKey(attest_key_desc, std::nullopt, &attest_key.keyBlob, |
| 333 | &attest_key_characteristics, &attest_cert_chain); |
subrahmanyaman | 7d9bc46 | 2022-03-16 01:40:39 +0000 | [diff] [blame] | 334 | if (error != ErrorCode::OK) { |
| 335 | return error; |
| 336 | } |
| 337 | |
| 338 | attest_key.issuerSubjectName = make_name_from_str("Android Keystore Key"); |
| 339 | // Generate a key, by passing the above self signed attestation key as attest key. |
| 340 | error = GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain); |
| 341 | if (error == ErrorCode::OK) { |
| 342 | // Append the attest_cert_chain to the attested cert_chain to yield a valid cert chain. |
| 343 | cert_chain->push_back(attest_cert_chain[0]); |
| 344 | } |
| 345 | return error; |
| 346 | } |
| 347 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 348 | ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format, |
| 349 | const string& key_material, vector<uint8_t>* key_blob, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 350 | vector<KeyCharacteristics>* key_characteristics) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 351 | Status result; |
| 352 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 353 | cert_chain_.clear(); |
| 354 | key_characteristics->clear(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 355 | key_blob->clear(); |
| 356 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 357 | KeyCreationResult creationResult; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 358 | result = keymint_->importKey(key_desc.vector_data(), format, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 359 | vector<uint8_t>(key_material.begin(), key_material.end()), |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 360 | {} /* attestationSigningKeyBlob */, &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 361 | |
| 362 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 363 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 364 | creationResult.keyCharacteristics); |
| 365 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 366 | |
| 367 | *key_blob = std::move(creationResult.keyBlob); |
| 368 | *key_characteristics = std::move(creationResult.keyCharacteristics); |
| 369 | cert_chain_ = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 370 | |
| 371 | auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM); |
| 372 | EXPECT_TRUE(algorithm); |
| 373 | if (algorithm && |
| 374 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
| 375 | EXPECT_GE(cert_chain_.size(), 1); |
| 376 | if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1); |
| 377 | } else { |
| 378 | // For symmetric keys there should be no certificates. |
| 379 | EXPECT_EQ(cert_chain_.size(), 0); |
| 380 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 381 | } |
| 382 | |
| 383 | return GetReturnErrorCode(result); |
| 384 | } |
| 385 | |
| 386 | ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format, |
| 387 | const string& key_material) { |
| 388 | return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_); |
| 389 | } |
| 390 | |
| 391 | ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key, |
| 392 | const AuthorizationSet& wrapping_key_desc, |
| 393 | string masking_key, |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 394 | const AuthorizationSet& unwrapping_params, |
| 395 | int64_t password_sid, int64_t biometric_sid) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 396 | EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key)); |
| 397 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 398 | key_characteristics_.clear(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 399 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 400 | KeyCreationResult creationResult; |
| 401 | Status result = keymint_->importWrappedKey( |
| 402 | vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_, |
| 403 | vector<uint8_t>(masking_key.begin(), masking_key.end()), |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 404 | unwrapping_params.vector_data(), password_sid, biometric_sid, &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 405 | |
| 406 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 407 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 408 | creationResult.keyCharacteristics); |
| 409 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 410 | |
| 411 | key_blob_ = std::move(creationResult.keyBlob); |
| 412 | key_characteristics_ = std::move(creationResult.keyCharacteristics); |
| 413 | cert_chain_ = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 414 | |
| 415 | AuthorizationSet allAuths; |
| 416 | for (auto& entry : key_characteristics_) { |
| 417 | allAuths.push_back(AuthorizationSet(entry.authorizations)); |
| 418 | } |
| 419 | auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM); |
| 420 | EXPECT_TRUE(algorithm); |
| 421 | if (algorithm && |
| 422 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
| 423 | EXPECT_GE(cert_chain_.size(), 1); |
| 424 | } else { |
| 425 | // For symmetric keys there should be no certificates. |
| 426 | EXPECT_EQ(cert_chain_.size(), 0); |
| 427 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 428 | } |
| 429 | |
| 430 | return GetReturnErrorCode(result); |
| 431 | } |
| 432 | |
David Drysdale | 300b555 | 2021-05-20 12:05:26 +0100 | [diff] [blame] | 433 | ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob, |
| 434 | const vector<uint8_t>& app_id, |
| 435 | const vector<uint8_t>& app_data, |
| 436 | vector<KeyCharacteristics>* key_characteristics) { |
| 437 | Status result = |
| 438 | keymint_->getKeyCharacteristics(key_blob, app_id, app_data, key_characteristics); |
| 439 | return GetReturnErrorCode(result); |
| 440 | } |
| 441 | |
| 442 | ErrorCode KeyMintAidlTestBase::GetCharacteristics(const vector<uint8_t>& key_blob, |
| 443 | vector<KeyCharacteristics>* key_characteristics) { |
| 444 | vector<uint8_t> empty_app_id, empty_app_data; |
| 445 | return GetCharacteristics(key_blob, empty_app_id, empty_app_data, key_characteristics); |
| 446 | } |
| 447 | |
| 448 | void KeyMintAidlTestBase::CheckCharacteristics( |
| 449 | const vector<uint8_t>& key_blob, |
| 450 | const vector<KeyCharacteristics>& generate_characteristics) { |
| 451 | // Any key characteristics that were in SecurityLevel::KEYSTORE when returned from |
| 452 | // generateKey() should be excluded, as KeyMint will have no record of them. |
| 453 | // This applies to CREATION_DATETIME in particular. |
| 454 | vector<KeyCharacteristics> expected_characteristics(generate_characteristics); |
| 455 | strip_keystore_tags(&expected_characteristics); |
| 456 | |
| 457 | vector<KeyCharacteristics> retrieved; |
| 458 | ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved)); |
| 459 | EXPECT_EQ(expected_characteristics, retrieved); |
| 460 | } |
| 461 | |
| 462 | void KeyMintAidlTestBase::CheckAppIdCharacteristics( |
| 463 | const vector<uint8_t>& key_blob, std::string_view app_id_string, |
| 464 | std::string_view app_data_string, |
| 465 | const vector<KeyCharacteristics>& generate_characteristics) { |
| 466 | // Exclude any SecurityLevel::KEYSTORE characteristics for comparisons. |
| 467 | vector<KeyCharacteristics> expected_characteristics(generate_characteristics); |
| 468 | strip_keystore_tags(&expected_characteristics); |
| 469 | |
| 470 | vector<uint8_t> app_id(app_id_string.begin(), app_id_string.end()); |
| 471 | vector<uint8_t> app_data(app_data_string.begin(), app_data_string.end()); |
| 472 | vector<KeyCharacteristics> retrieved; |
| 473 | ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, app_id, app_data, &retrieved)); |
| 474 | EXPECT_EQ(expected_characteristics, retrieved); |
| 475 | |
| 476 | // Check that key characteristics can't be retrieved if the app ID or app data is missing. |
| 477 | vector<uint8_t> empty; |
| 478 | vector<KeyCharacteristics> not_retrieved; |
| 479 | EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, |
| 480 | GetCharacteristics(key_blob, empty, app_data, ¬_retrieved)); |
| 481 | EXPECT_EQ(not_retrieved.size(), 0); |
| 482 | |
| 483 | EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, |
| 484 | GetCharacteristics(key_blob, app_id, empty, ¬_retrieved)); |
| 485 | EXPECT_EQ(not_retrieved.size(), 0); |
| 486 | |
| 487 | EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, |
| 488 | GetCharacteristics(key_blob, empty, empty, ¬_retrieved)); |
| 489 | EXPECT_EQ(not_retrieved.size(), 0); |
| 490 | } |
| 491 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 492 | ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) { |
| 493 | Status result = keymint_->deleteKey(*key_blob); |
| 494 | if (!keep_key_blob) { |
| 495 | *key_blob = vector<uint8_t>(); |
| 496 | } |
| 497 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 498 | EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 499 | return GetReturnErrorCode(result); |
| 500 | } |
| 501 | |
| 502 | ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) { |
| 503 | return DeleteKey(&key_blob_, keep_key_blob); |
| 504 | } |
| 505 | |
| 506 | ErrorCode KeyMintAidlTestBase::DeleteAllKeys() { |
| 507 | Status result = keymint_->deleteAllKeys(); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 508 | EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 509 | return GetReturnErrorCode(result); |
| 510 | } |
| 511 | |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 512 | ErrorCode KeyMintAidlTestBase::DestroyAttestationIds() { |
| 513 | Status result = keymint_->destroyAttestationIds(); |
| 514 | return GetReturnErrorCode(result); |
| 515 | } |
| 516 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 517 | void KeyMintAidlTestBase::CheckedDeleteKey() { |
David Drysdale | 1b9febc | 2023-06-07 13:43:24 +0100 | [diff] [blame] | 518 | ErrorCode result = DeleteKey(&key_blob_, /* keep_key_blob = */ false); |
| 519 | EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 520 | } |
| 521 | |
| 522 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob, |
| 523 | const AuthorizationSet& in_params, |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 524 | AuthorizationSet* out_params, |
| 525 | std::shared_ptr<IKeyMintOperation>& op) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 526 | SCOPED_TRACE("Begin"); |
| 527 | Status result; |
| 528 | BeginResult out; |
David Drysdale | 56ba912 | 2021-04-19 19:10:47 +0100 | [diff] [blame] | 529 | 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] | 530 | |
| 531 | if (result.isOk()) { |
| 532 | *out_params = out.params; |
| 533 | challenge_ = out.challenge; |
| 534 | op = out.operation; |
| 535 | } |
| 536 | |
| 537 | return GetReturnErrorCode(result); |
| 538 | } |
| 539 | |
| 540 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob, |
| 541 | const AuthorizationSet& in_params, |
David Drysdale | 28fa931 | 2023-02-01 14:53:01 +0000 | [diff] [blame] | 542 | AuthorizationSet* out_params, |
| 543 | std::optional<HardwareAuthToken> hat) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 544 | SCOPED_TRACE("Begin"); |
| 545 | Status result; |
| 546 | BeginResult out; |
| 547 | |
David Drysdale | 28fa931 | 2023-02-01 14:53:01 +0000 | [diff] [blame] | 548 | result = keymint_->begin(purpose, key_blob, in_params.vector_data(), hat, &out); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 549 | |
| 550 | if (result.isOk()) { |
| 551 | *out_params = out.params; |
| 552 | challenge_ = out.challenge; |
| 553 | op_ = out.operation; |
| 554 | } |
| 555 | |
| 556 | return GetReturnErrorCode(result); |
| 557 | } |
| 558 | |
| 559 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params, |
| 560 | AuthorizationSet* out_params) { |
| 561 | SCOPED_TRACE("Begin"); |
| 562 | EXPECT_EQ(nullptr, op_); |
| 563 | return Begin(purpose, key_blob_, in_params, out_params); |
| 564 | } |
| 565 | |
| 566 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) { |
| 567 | SCOPED_TRACE("Begin"); |
| 568 | AuthorizationSet out_params; |
| 569 | ErrorCode result = Begin(purpose, in_params, &out_params); |
| 570 | EXPECT_TRUE(out_params.empty()); |
| 571 | return result; |
| 572 | } |
| 573 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 574 | ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) { |
| 575 | return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()), |
| 576 | {} /* hardwareAuthToken */, |
| 577 | {} /* verificationToken */)); |
| 578 | } |
| 579 | |
| 580 | ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 581 | SCOPED_TRACE("Update"); |
| 582 | |
| 583 | Status result; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 584 | if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 585 | |
Brian J Murray | eabd9d6 | 2022-01-06 15:13:51 -0800 | [diff] [blame] | 586 | EXPECT_NE(op_, nullptr); |
| 587 | if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER; |
| 588 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 589 | std::vector<uint8_t> o_put; |
| 590 | result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 591 | |
David Drysdale | feab5d9 | 2022-01-06 15:46:23 +0000 | [diff] [blame] | 592 | if (result.isOk()) { |
| 593 | output->append(o_put.begin(), o_put.end()); |
| 594 | } else { |
| 595 | // Failure always terminates the operation. |
| 596 | op_ = {}; |
| 597 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 598 | |
| 599 | return GetReturnErrorCode(result); |
| 600 | } |
| 601 | |
David Drysdale | 28fa931 | 2023-02-01 14:53:01 +0000 | [diff] [blame] | 602 | ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, string* output, |
| 603 | std::optional<HardwareAuthToken> hat, |
| 604 | std::optional<secureclock::TimeStampToken> time_token) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 605 | SCOPED_TRACE("Finish"); |
| 606 | Status result; |
| 607 | |
| 608 | EXPECT_NE(op_, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 609 | if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 610 | |
| 611 | vector<uint8_t> oPut; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 612 | result = op_->finish(vector<uint8_t>(input.begin(), input.end()), |
David Drysdale | 28fa931 | 2023-02-01 14:53:01 +0000 | [diff] [blame] | 613 | vector<uint8_t>(signature.begin(), signature.end()), hat, time_token, |
| 614 | {} /* confirmationToken */, &oPut); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 615 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 616 | if (result.isOk()) output->append(oPut.begin(), oPut.end()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 617 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 618 | op_ = {}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 619 | return GetReturnErrorCode(result); |
| 620 | } |
| 621 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 622 | ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 623 | SCOPED_TRACE("Abort"); |
| 624 | |
| 625 | EXPECT_NE(op, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 626 | if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 627 | |
| 628 | Status retval = op->abort(); |
| 629 | EXPECT_TRUE(retval.isOk()); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 630 | return static_cast<ErrorCode>(retval.getServiceSpecificError()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 631 | } |
| 632 | |
| 633 | ErrorCode KeyMintAidlTestBase::Abort() { |
| 634 | SCOPED_TRACE("Abort"); |
| 635 | |
| 636 | EXPECT_NE(op_, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 637 | if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 638 | |
| 639 | Status retval = op_->abort(); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 640 | return static_cast<ErrorCode>(retval.getServiceSpecificError()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 641 | } |
| 642 | |
| 643 | void KeyMintAidlTestBase::AbortIfNeeded() { |
| 644 | SCOPED_TRACE("AbortIfNeeded"); |
| 645 | if (op_) { |
| 646 | EXPECT_EQ(ErrorCode::OK, Abort()); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 647 | op_.reset(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 648 | } |
| 649 | } |
| 650 | |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 651 | auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation, |
| 652 | const string& message, const AuthorizationSet& in_params) |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 653 | -> std::tuple<ErrorCode, string> { |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 654 | AuthorizationSet begin_out_params; |
| 655 | ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 656 | if (result != ErrorCode::OK) return {result, {}}; |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 657 | |
| 658 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 659 | return {Finish(message, &output), output}; |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 660 | } |
| 661 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 662 | string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation, |
| 663 | const string& message, const AuthorizationSet& in_params, |
| 664 | AuthorizationSet* out_params) { |
| 665 | SCOPED_TRACE("ProcessMessage"); |
| 666 | AuthorizationSet begin_out_params; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 667 | ErrorCode result = Begin(operation, key_blob, in_params, out_params); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 668 | EXPECT_EQ(ErrorCode::OK, result); |
| 669 | if (result != ErrorCode::OK) { |
| 670 | return ""; |
| 671 | } |
| 672 | |
| 673 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 674 | EXPECT_EQ(ErrorCode::OK, Finish(message, &output)); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 675 | return output; |
| 676 | } |
| 677 | |
| 678 | string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message, |
| 679 | const AuthorizationSet& params) { |
| 680 | SCOPED_TRACE("SignMessage"); |
| 681 | AuthorizationSet out_params; |
| 682 | string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params); |
| 683 | EXPECT_TRUE(out_params.empty()); |
| 684 | return signature; |
| 685 | } |
| 686 | |
| 687 | string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) { |
| 688 | SCOPED_TRACE("SignMessage"); |
| 689 | return SignMessage(key_blob_, message, params); |
| 690 | } |
| 691 | |
| 692 | string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) { |
| 693 | SCOPED_TRACE("MacMessage"); |
| 694 | return SignMessage( |
| 695 | key_blob_, message, |
| 696 | AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length)); |
| 697 | } |
| 698 | |
anil.hiranniah | 19a4ca1 | 2022-03-03 17:39:30 +0530 | [diff] [blame] | 699 | void KeyMintAidlTestBase::CheckAesIncrementalEncryptOperation(BlockMode block_mode, |
| 700 | int message_size) { |
David Drysdale | 1a63719 | 2022-03-14 09:11:29 +0000 | [diff] [blame] | 701 | auto builder = AuthorizationSetBuilder() |
| 702 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 703 | .AesEncryptionKey(128) |
| 704 | .BlockMode(block_mode) |
| 705 | .Padding(PaddingMode::NONE); |
| 706 | if (block_mode == BlockMode::GCM) { |
| 707 | builder.Authorization(TAG_MIN_MAC_LENGTH, 128); |
| 708 | } |
| 709 | ASSERT_EQ(ErrorCode::OK, GenerateKey(builder)); |
anil.hiranniah | 19a4ca1 | 2022-03-03 17:39:30 +0530 | [diff] [blame] | 710 | |
| 711 | for (int increment = 1; increment <= message_size; ++increment) { |
| 712 | string message(message_size, 'a'); |
| 713 | auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE); |
| 714 | if (block_mode == BlockMode::GCM) { |
| 715 | params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */; |
| 716 | } |
| 717 | |
| 718 | AuthorizationSet output_params; |
| 719 | EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params)); |
| 720 | |
| 721 | string ciphertext; |
| 722 | string to_send; |
| 723 | for (size_t i = 0; i < message.size(); i += increment) { |
| 724 | EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext)); |
| 725 | } |
| 726 | EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) |
| 727 | << "Error sending " << to_send << " with block mode " << block_mode; |
| 728 | |
| 729 | switch (block_mode) { |
| 730 | case BlockMode::GCM: |
| 731 | EXPECT_EQ(message.size() + 16, ciphertext.size()); |
| 732 | break; |
| 733 | case BlockMode::CTR: |
| 734 | EXPECT_EQ(message.size(), ciphertext.size()); |
| 735 | break; |
| 736 | case BlockMode::CBC: |
| 737 | case BlockMode::ECB: |
| 738 | EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size()); |
| 739 | break; |
| 740 | } |
| 741 | |
| 742 | auto iv = output_params.GetTagValue(TAG_NONCE); |
| 743 | switch (block_mode) { |
| 744 | case BlockMode::CBC: |
| 745 | case BlockMode::GCM: |
| 746 | case BlockMode::CTR: |
| 747 | ASSERT_TRUE(iv) << "No IV for block mode " << block_mode; |
| 748 | EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size()); |
| 749 | params.push_back(TAG_NONCE, iv->get()); |
| 750 | break; |
| 751 | |
| 752 | case BlockMode::ECB: |
| 753 | EXPECT_FALSE(iv) << "ECB mode should not generate IV"; |
| 754 | break; |
| 755 | } |
| 756 | |
| 757 | EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params)) |
| 758 | << "Decrypt begin() failed for block mode " << block_mode; |
| 759 | |
| 760 | string plaintext; |
| 761 | for (size_t i = 0; i < ciphertext.size(); i += increment) { |
| 762 | EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext)); |
| 763 | } |
| 764 | ErrorCode error = Finish(to_send, &plaintext); |
| 765 | ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode |
| 766 | << " and increment " << increment; |
| 767 | if (error == ErrorCode::OK) { |
| 768 | ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode |
| 769 | << " and increment " << increment; |
| 770 | } |
| 771 | } |
| 772 | } |
| 773 | |
Prashant Patil | dd5f7f0 | 2022-07-06 18:58:07 +0000 | [diff] [blame] | 774 | void KeyMintAidlTestBase::AesCheckEncryptOneByteAtATime(const string& key, BlockMode block_mode, |
| 775 | PaddingMode padding_mode, const string& iv, |
| 776 | const string& plaintext, |
| 777 | const string& exp_cipher_text) { |
| 778 | bool is_authenticated_cipher = (block_mode == BlockMode::GCM); |
| 779 | auto auth_set = AuthorizationSetBuilder() |
| 780 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 781 | .AesEncryptionKey(key.size() * 8) |
| 782 | .BlockMode(block_mode) |
| 783 | .Padding(padding_mode); |
| 784 | if (iv.size() > 0) auth_set.Authorization(TAG_CALLER_NONCE); |
| 785 | if (is_authenticated_cipher) auth_set.Authorization(TAG_MIN_MAC_LENGTH, 128); |
| 786 | ASSERT_EQ(ErrorCode::OK, ImportKey(auth_set, KeyFormat::RAW, key)); |
| 787 | |
| 788 | CheckEncryptOneByteAtATime(block_mode, 16 /*block_size*/, padding_mode, iv, plaintext, |
| 789 | exp_cipher_text); |
| 790 | } |
| 791 | |
| 792 | void KeyMintAidlTestBase::CheckEncryptOneByteAtATime(BlockMode block_mode, const int block_size, |
| 793 | PaddingMode padding_mode, const string& iv, |
| 794 | const string& plaintext, |
| 795 | const string& exp_cipher_text) { |
| 796 | bool is_stream_cipher = (block_mode == BlockMode::CTR || block_mode == BlockMode::GCM); |
| 797 | bool is_authenticated_cipher = (block_mode == BlockMode::GCM); |
| 798 | auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode); |
| 799 | if (iv.size() > 0) params.Authorization(TAG_NONCE, iv.data(), iv.size()); |
| 800 | if (is_authenticated_cipher) params.Authorization(TAG_MAC_LENGTH, 128); |
| 801 | |
| 802 | AuthorizationSet output_params; |
| 803 | EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params)); |
| 804 | |
| 805 | string actual_ciphertext; |
| 806 | if (is_stream_cipher) { |
| 807 | // Assert that a 1 byte of output is produced for 1 byte of input. |
| 808 | // Every input byte produces an output byte. |
| 809 | for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) { |
| 810 | string ciphertext; |
| 811 | EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext)); |
| 812 | // Some StrongBox implementations cannot support 1:1 input:output lengths, so |
| 813 | // we relax this API restriction for them. |
| 814 | if (SecLevel() != SecurityLevel::STRONGBOX) { |
| 815 | EXPECT_EQ(1, ciphertext.size()) << "plaintext index: " << plaintext_index; |
| 816 | } |
| 817 | actual_ciphertext.append(ciphertext); |
| 818 | } |
| 819 | string ciphertext; |
| 820 | EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext)); |
| 821 | if (SecLevel() != SecurityLevel::STRONGBOX) { |
| 822 | string expected_final_output; |
| 823 | if (is_authenticated_cipher) { |
| 824 | expected_final_output = exp_cipher_text.substr(plaintext.size()); |
| 825 | } |
| 826 | EXPECT_EQ(expected_final_output, ciphertext); |
| 827 | } |
| 828 | actual_ciphertext.append(ciphertext); |
| 829 | } else { |
| 830 | // Assert that a block of output is produced once a full block of input is provided. |
| 831 | // Every input block produces an output block. |
| 832 | bool compare_output = true; |
| 833 | string additional_information; |
| 834 | int vendor_api_level = property_get_int32("ro.vendor.api_level", 0); |
| 835 | if (SecLevel() == SecurityLevel::STRONGBOX) { |
| 836 | // This is known to be broken on older vendor implementations. |
Shawn Willden | 1a545db | 2023-02-22 14:32:33 -0700 | [diff] [blame] | 837 | if (vendor_api_level < __ANDROID_API_T__) { |
Prashant Patil | dd5f7f0 | 2022-07-06 18:58:07 +0000 | [diff] [blame] | 838 | compare_output = false; |
| 839 | } else { |
| 840 | additional_information = " (b/194134359) "; |
| 841 | } |
| 842 | } |
| 843 | for (int plaintext_index = 0; plaintext_index < plaintext.size(); plaintext_index++) { |
| 844 | string ciphertext; |
| 845 | EXPECT_EQ(ErrorCode::OK, Update(plaintext.substr(plaintext_index, 1), &ciphertext)); |
| 846 | if (compare_output) { |
| 847 | if ((plaintext_index % block_size) == block_size - 1) { |
| 848 | // Update is expected to have output a new block |
| 849 | EXPECT_EQ(block_size, ciphertext.size()) |
| 850 | << "plaintext index: " << plaintext_index << additional_information; |
| 851 | } else { |
| 852 | // Update is expected to have produced no output |
| 853 | EXPECT_EQ(0, ciphertext.size()) |
| 854 | << "plaintext index: " << plaintext_index << additional_information; |
| 855 | } |
| 856 | } |
| 857 | actual_ciphertext.append(ciphertext); |
| 858 | } |
| 859 | string ciphertext; |
| 860 | EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext)); |
| 861 | actual_ciphertext.append(ciphertext); |
| 862 | } |
| 863 | // Regardless of how the completed ciphertext got accumulated, it should match the expected |
| 864 | // ciphertext. |
| 865 | EXPECT_EQ(exp_cipher_text, actual_ciphertext); |
| 866 | } |
| 867 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 868 | void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message, |
| 869 | Digest digest, const string& expected_mac) { |
| 870 | SCOPED_TRACE("CheckHmacTestVector"); |
| 871 | ASSERT_EQ(ErrorCode::OK, |
| 872 | ImportKey(AuthorizationSetBuilder() |
| 873 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 874 | .HmacKey(key.size() * 8) |
| 875 | .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8) |
| 876 | .Digest(digest), |
| 877 | KeyFormat::RAW, key)); |
| 878 | string signature = MacMessage(message, digest, expected_mac.size() * 8); |
| 879 | EXPECT_EQ(expected_mac, signature) |
| 880 | << "Test vector didn't match for key of size " << key.size() << " message of size " |
| 881 | << message.size() << " and digest " << digest; |
| 882 | CheckedDeleteKey(); |
| 883 | } |
| 884 | |
| 885 | void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce, |
| 886 | const string& message, |
| 887 | const string& expected_ciphertext) { |
| 888 | SCOPED_TRACE("CheckAesCtrTestVector"); |
| 889 | ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() |
| 890 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 891 | .AesEncryptionKey(key.size() * 8) |
| 892 | .BlockMode(BlockMode::CTR) |
| 893 | .Authorization(TAG_CALLER_NONCE) |
| 894 | .Padding(PaddingMode::NONE), |
| 895 | KeyFormat::RAW, key)); |
| 896 | |
| 897 | auto params = AuthorizationSetBuilder() |
| 898 | .Authorization(TAG_NONCE, nonce.data(), nonce.size()) |
| 899 | .BlockMode(BlockMode::CTR) |
| 900 | .Padding(PaddingMode::NONE); |
| 901 | AuthorizationSet out_params; |
| 902 | string ciphertext = EncryptMessage(key_blob_, message, params, &out_params); |
| 903 | EXPECT_EQ(expected_ciphertext, ciphertext); |
| 904 | } |
| 905 | |
| 906 | void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode, |
| 907 | PaddingMode padding_mode, const string& key, |
| 908 | const string& iv, const string& input, |
| 909 | const string& expected_output) { |
| 910 | auto authset = AuthorizationSetBuilder() |
| 911 | .TripleDesEncryptionKey(key.size() * 7) |
| 912 | .BlockMode(block_mode) |
| 913 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 914 | .Padding(padding_mode); |
| 915 | if (iv.size()) authset.Authorization(TAG_CALLER_NONCE); |
| 916 | ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key)); |
| 917 | ASSERT_GT(key_blob_.size(), 0U); |
| 918 | |
| 919 | auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode); |
| 920 | if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size()); |
| 921 | AuthorizationSet output_params; |
| 922 | string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params); |
| 923 | EXPECT_EQ(expected_output, output); |
| 924 | } |
| 925 | |
| 926 | void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message, |
| 927 | const string& signature, const AuthorizationSet& params) { |
| 928 | SCOPED_TRACE("VerifyMessage"); |
| 929 | AuthorizationSet begin_out_params; |
| 930 | ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params)); |
| 931 | |
| 932 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 933 | EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output)); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 934 | EXPECT_TRUE(output.empty()); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 935 | op_ = {}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 936 | } |
| 937 | |
| 938 | void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature, |
| 939 | const AuthorizationSet& params) { |
| 940 | SCOPED_TRACE("VerifyMessage"); |
| 941 | VerifyMessage(key_blob_, message, signature, params); |
| 942 | } |
| 943 | |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 944 | void KeyMintAidlTestBase::LocalVerifyMessage(const string& message, const string& signature, |
| 945 | const AuthorizationSet& params) { |
| 946 | SCOPED_TRACE("LocalVerifyMessage"); |
| 947 | |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 948 | ASSERT_GT(cert_chain_.size(), 0); |
David Drysdale | 9f5c0c5 | 2022-11-03 15:10:16 +0000 | [diff] [blame] | 949 | LocalVerifyMessage(cert_chain_[0].encodedCertificate, message, signature, params); |
| 950 | } |
| 951 | |
| 952 | void KeyMintAidlTestBase::LocalVerifyMessage(const vector<uint8_t>& der_cert, const string& message, |
| 953 | const string& signature, |
| 954 | const AuthorizationSet& params) { |
| 955 | // Retrieve the public key from the leaf certificate. |
| 956 | X509_Ptr key_cert(parse_cert_blob(der_cert)); |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 957 | ASSERT_TRUE(key_cert.get()); |
| 958 | EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get())); |
| 959 | ASSERT_TRUE(pub_key.get()); |
| 960 | |
| 961 | Digest digest = params.GetTagValue(TAG_DIGEST).value(); |
| 962 | PaddingMode padding = PaddingMode::NONE; |
| 963 | auto tag = params.GetTagValue(TAG_PADDING); |
| 964 | if (tag.has_value()) { |
| 965 | padding = tag.value(); |
| 966 | } |
| 967 | |
| 968 | if (digest == Digest::NONE) { |
| 969 | switch (EVP_PKEY_id(pub_key.get())) { |
David Drysdale | 42fe189 | 2021-10-14 14:43:46 +0100 | [diff] [blame] | 970 | case EVP_PKEY_ED25519: { |
| 971 | ASSERT_EQ(64, signature.size()); |
| 972 | uint8_t pub_keydata[32]; |
| 973 | size_t pub_len = sizeof(pub_keydata); |
| 974 | ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(pub_key.get(), pub_keydata, &pub_len)); |
| 975 | ASSERT_EQ(sizeof(pub_keydata), pub_len); |
| 976 | ASSERT_EQ(1, ED25519_verify(reinterpret_cast<const uint8_t*>(message.data()), |
| 977 | message.size(), |
| 978 | reinterpret_cast<const uint8_t*>(signature.data()), |
| 979 | pub_keydata)); |
| 980 | break; |
| 981 | } |
| 982 | |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 983 | case EVP_PKEY_EC: { |
| 984 | vector<uint8_t> data((EVP_PKEY_bits(pub_key.get()) + 7) / 8); |
| 985 | size_t data_size = std::min(data.size(), message.size()); |
| 986 | memcpy(data.data(), message.data(), data_size); |
| 987 | EC_KEY_Ptr ecdsa(EVP_PKEY_get1_EC_KEY(pub_key.get())); |
| 988 | ASSERT_TRUE(ecdsa.get()); |
| 989 | ASSERT_EQ(1, |
| 990 | ECDSA_verify(0, reinterpret_cast<const uint8_t*>(data.data()), data_size, |
| 991 | reinterpret_cast<const uint8_t*>(signature.data()), |
| 992 | signature.size(), ecdsa.get())); |
| 993 | break; |
| 994 | } |
| 995 | case EVP_PKEY_RSA: { |
| 996 | vector<uint8_t> data(EVP_PKEY_size(pub_key.get())); |
| 997 | size_t data_size = std::min(data.size(), message.size()); |
| 998 | memcpy(data.data(), message.data(), data_size); |
| 999 | |
| 1000 | RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get()))); |
| 1001 | ASSERT_TRUE(rsa.get()); |
| 1002 | |
| 1003 | size_t key_len = RSA_size(rsa.get()); |
| 1004 | int openssl_padding = RSA_NO_PADDING; |
| 1005 | switch (padding) { |
| 1006 | case PaddingMode::NONE: |
| 1007 | ASSERT_TRUE(data_size <= key_len); |
| 1008 | ASSERT_EQ(key_len, signature.size()); |
| 1009 | openssl_padding = RSA_NO_PADDING; |
| 1010 | break; |
| 1011 | case PaddingMode::RSA_PKCS1_1_5_SIGN: |
| 1012 | ASSERT_TRUE(data_size + kPkcs1UndigestedSignaturePaddingOverhead <= |
| 1013 | key_len); |
| 1014 | openssl_padding = RSA_PKCS1_PADDING; |
| 1015 | break; |
| 1016 | default: |
| 1017 | ADD_FAILURE() << "Unsupported RSA padding mode " << padding; |
| 1018 | } |
| 1019 | |
| 1020 | vector<uint8_t> decrypted_data(key_len); |
| 1021 | int bytes_decrypted = RSA_public_decrypt( |
| 1022 | signature.size(), reinterpret_cast<const uint8_t*>(signature.data()), |
| 1023 | decrypted_data.data(), rsa.get(), openssl_padding); |
| 1024 | ASSERT_GE(bytes_decrypted, 0); |
| 1025 | |
| 1026 | const uint8_t* compare_pos = decrypted_data.data(); |
| 1027 | size_t bytes_to_compare = bytes_decrypted; |
| 1028 | uint8_t zero_check_result = 0; |
| 1029 | if (padding == PaddingMode::NONE && data_size < bytes_to_compare) { |
| 1030 | // If the data is short, for "unpadded" signing we zero-pad to the left. So |
| 1031 | // during verification we should have zeros on the left of the decrypted data. |
| 1032 | // Do a constant-time check. |
| 1033 | const uint8_t* zero_end = compare_pos + bytes_to_compare - data_size; |
| 1034 | while (compare_pos < zero_end) zero_check_result |= *compare_pos++; |
| 1035 | ASSERT_EQ(0, zero_check_result); |
| 1036 | bytes_to_compare = data_size; |
| 1037 | } |
| 1038 | ASSERT_EQ(0, memcmp(compare_pos, data.data(), bytes_to_compare)); |
| 1039 | break; |
| 1040 | } |
| 1041 | default: |
| 1042 | ADD_FAILURE() << "Unknown public key type"; |
| 1043 | } |
| 1044 | } else { |
| 1045 | EVP_MD_CTX digest_ctx; |
| 1046 | EVP_MD_CTX_init(&digest_ctx); |
| 1047 | EVP_PKEY_CTX* pkey_ctx; |
| 1048 | const EVP_MD* md = openssl_digest(digest); |
| 1049 | ASSERT_NE(md, nullptr); |
| 1050 | ASSERT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr, pub_key.get())); |
| 1051 | |
| 1052 | if (padding == PaddingMode::RSA_PSS) { |
| 1053 | EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0); |
| 1054 | EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0); |
David Drysdale | c6b8907 | 2021-12-14 14:32:51 +0000 | [diff] [blame] | 1055 | EXPECT_GT(EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, md), 0); |
David Drysdale | df8f52e | 2021-05-06 08:10:58 +0100 | [diff] [blame] | 1056 | } |
| 1057 | |
| 1058 | ASSERT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, |
| 1059 | reinterpret_cast<const uint8_t*>(message.data()), |
| 1060 | message.size())); |
| 1061 | ASSERT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx, |
| 1062 | reinterpret_cast<const uint8_t*>(signature.data()), |
| 1063 | signature.size())); |
| 1064 | EVP_MD_CTX_cleanup(&digest_ctx); |
| 1065 | } |
| 1066 | } |
| 1067 | |
David Drysdale | 59cae64 | 2021-05-12 13:52:03 +0100 | [diff] [blame] | 1068 | string KeyMintAidlTestBase::LocalRsaEncryptMessage(const string& message, |
| 1069 | const AuthorizationSet& params) { |
| 1070 | SCOPED_TRACE("LocalRsaEncryptMessage"); |
| 1071 | |
| 1072 | // Retrieve the public key from the leaf certificate. |
| 1073 | if (cert_chain_.empty()) { |
| 1074 | ADD_FAILURE() << "No public key available"; |
| 1075 | return "Failure"; |
| 1076 | } |
| 1077 | X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate)); |
David Drysdale | b97121d | 2022-08-12 11:54:08 +0100 | [diff] [blame] | 1078 | if (key_cert.get() == nullptr) { |
| 1079 | ADD_FAILURE() << "Failed to parse cert"; |
| 1080 | return "Failure"; |
| 1081 | } |
David Drysdale | 59cae64 | 2021-05-12 13:52:03 +0100 | [diff] [blame] | 1082 | EVP_PKEY_Ptr pub_key(X509_get_pubkey(key_cert.get())); |
David Drysdale | b97121d | 2022-08-12 11:54:08 +0100 | [diff] [blame] | 1083 | if (pub_key.get() == nullptr) { |
| 1084 | ADD_FAILURE() << "Failed to retrieve public key"; |
| 1085 | return "Failure"; |
| 1086 | } |
David Drysdale | 59cae64 | 2021-05-12 13:52:03 +0100 | [diff] [blame] | 1087 | RSA_Ptr rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pub_key.get()))); |
David Drysdale | b97121d | 2022-08-12 11:54:08 +0100 | [diff] [blame] | 1088 | if (rsa.get() == nullptr) { |
| 1089 | ADD_FAILURE() << "Failed to retrieve RSA public key"; |
| 1090 | return "Failure"; |
| 1091 | } |
David Drysdale | 59cae64 | 2021-05-12 13:52:03 +0100 | [diff] [blame] | 1092 | |
| 1093 | // Retrieve relevant tags. |
| 1094 | Digest digest = Digest::NONE; |
David Drysdale | ae3727b | 2021-11-11 09:00:14 +0000 | [diff] [blame] | 1095 | Digest mgf_digest = Digest::SHA1; |
David Drysdale | 59cae64 | 2021-05-12 13:52:03 +0100 | [diff] [blame] | 1096 | PaddingMode padding = PaddingMode::NONE; |
| 1097 | |
| 1098 | auto digest_tag = params.GetTagValue(TAG_DIGEST); |
| 1099 | if (digest_tag.has_value()) digest = digest_tag.value(); |
| 1100 | auto pad_tag = params.GetTagValue(TAG_PADDING); |
| 1101 | if (pad_tag.has_value()) padding = pad_tag.value(); |
| 1102 | auto mgf_tag = params.GetTagValue(TAG_RSA_OAEP_MGF_DIGEST); |
| 1103 | if (mgf_tag.has_value()) mgf_digest = mgf_tag.value(); |
| 1104 | |
| 1105 | const EVP_MD* md = openssl_digest(digest); |
| 1106 | const EVP_MD* mgf_md = openssl_digest(mgf_digest); |
| 1107 | |
| 1108 | // Set up encryption context. |
| 1109 | EVP_PKEY_CTX_Ptr ctx(EVP_PKEY_CTX_new(pub_key.get(), /* engine= */ nullptr)); |
| 1110 | if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) { |
| 1111 | ADD_FAILURE() << "Encryption init failed: " << ERR_peek_last_error(); |
| 1112 | return "Failure"; |
| 1113 | } |
| 1114 | |
| 1115 | int rc = -1; |
| 1116 | switch (padding) { |
| 1117 | case PaddingMode::NONE: |
| 1118 | rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING); |
| 1119 | break; |
| 1120 | case PaddingMode::RSA_PKCS1_1_5_ENCRYPT: |
| 1121 | rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING); |
| 1122 | break; |
| 1123 | case PaddingMode::RSA_OAEP: |
| 1124 | rc = EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING); |
| 1125 | break; |
| 1126 | default: |
| 1127 | break; |
| 1128 | } |
| 1129 | if (rc <= 0) { |
| 1130 | ADD_FAILURE() << "Set padding failed: " << ERR_peek_last_error(); |
| 1131 | return "Failure"; |
| 1132 | } |
| 1133 | if (padding == PaddingMode::RSA_OAEP) { |
| 1134 | if (!EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md)) { |
| 1135 | ADD_FAILURE() << "Set digest failed: " << ERR_peek_last_error(); |
| 1136 | return "Failure"; |
| 1137 | } |
| 1138 | if (!EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), mgf_md)) { |
| 1139 | ADD_FAILURE() << "Set MGF digest failed: " << ERR_peek_last_error(); |
| 1140 | return "Failure"; |
| 1141 | } |
| 1142 | } |
| 1143 | |
| 1144 | // Determine output size. |
| 1145 | size_t outlen; |
| 1146 | if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen, |
| 1147 | reinterpret_cast<const uint8_t*>(message.data()), message.size()) <= 0) { |
| 1148 | ADD_FAILURE() << "Determine output size failed: " << ERR_peek_last_error(); |
| 1149 | return "Failure"; |
| 1150 | } |
| 1151 | |
| 1152 | // Left-zero-pad the input if necessary. |
| 1153 | const uint8_t* to_encrypt = reinterpret_cast<const uint8_t*>(message.data()); |
| 1154 | size_t to_encrypt_len = message.size(); |
| 1155 | |
| 1156 | std::unique_ptr<string> zero_padded_message; |
| 1157 | if (padding == PaddingMode::NONE && to_encrypt_len < outlen) { |
| 1158 | zero_padded_message.reset(new string(outlen, '\0')); |
| 1159 | memcpy(zero_padded_message->data() + (outlen - to_encrypt_len), message.data(), |
| 1160 | message.size()); |
| 1161 | to_encrypt = reinterpret_cast<const uint8_t*>(zero_padded_message->data()); |
| 1162 | to_encrypt_len = outlen; |
| 1163 | } |
| 1164 | |
| 1165 | // Do the encryption. |
| 1166 | string output(outlen, '\0'); |
| 1167 | if (EVP_PKEY_encrypt(ctx.get(), reinterpret_cast<uint8_t*>(output.data()), &outlen, to_encrypt, |
| 1168 | to_encrypt_len) <= 0) { |
| 1169 | ADD_FAILURE() << "Encryption failed: " << ERR_peek_last_error(); |
| 1170 | return "Failure"; |
| 1171 | } |
| 1172 | return output; |
| 1173 | } |
| 1174 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1175 | string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message, |
| 1176 | const AuthorizationSet& in_params, |
| 1177 | AuthorizationSet* out_params) { |
| 1178 | SCOPED_TRACE("EncryptMessage"); |
| 1179 | return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params); |
| 1180 | } |
| 1181 | |
| 1182 | string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params, |
| 1183 | AuthorizationSet* out_params) { |
| 1184 | SCOPED_TRACE("EncryptMessage"); |
| 1185 | return EncryptMessage(key_blob_, message, params, out_params); |
| 1186 | } |
| 1187 | |
| 1188 | string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) { |
| 1189 | SCOPED_TRACE("EncryptMessage"); |
| 1190 | AuthorizationSet out_params; |
| 1191 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 1192 | EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params; |
| 1193 | return ciphertext; |
| 1194 | } |
| 1195 | |
| 1196 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 1197 | PaddingMode padding) { |
| 1198 | SCOPED_TRACE("EncryptMessage"); |
| 1199 | auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding); |
| 1200 | AuthorizationSet out_params; |
| 1201 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 1202 | EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params; |
| 1203 | return ciphertext; |
| 1204 | } |
| 1205 | |
| 1206 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 1207 | PaddingMode padding, vector<uint8_t>* iv_out) { |
| 1208 | SCOPED_TRACE("EncryptMessage"); |
| 1209 | auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding); |
| 1210 | AuthorizationSet out_params; |
| 1211 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 1212 | EXPECT_EQ(1U, out_params.size()); |
| 1213 | auto ivVal = out_params.GetTagValue(TAG_NONCE); |
Janis Danisevskis | 5ba0933 | 2020-12-17 10:05:15 -0800 | [diff] [blame] | 1214 | EXPECT_TRUE(ivVal); |
| 1215 | if (ivVal) *iv_out = *ivVal; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1216 | return ciphertext; |
| 1217 | } |
| 1218 | |
| 1219 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 1220 | PaddingMode padding, const vector<uint8_t>& iv_in) { |
| 1221 | SCOPED_TRACE("EncryptMessage"); |
| 1222 | auto params = AuthorizationSetBuilder() |
| 1223 | .BlockMode(block_mode) |
| 1224 | .Padding(padding) |
| 1225 | .Authorization(TAG_NONCE, iv_in); |
| 1226 | AuthorizationSet out_params; |
| 1227 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 1228 | return ciphertext; |
| 1229 | } |
| 1230 | |
| 1231 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 1232 | PaddingMode padding, uint8_t mac_length_bits, |
| 1233 | const vector<uint8_t>& iv_in) { |
| 1234 | SCOPED_TRACE("EncryptMessage"); |
| 1235 | auto params = AuthorizationSetBuilder() |
| 1236 | .BlockMode(block_mode) |
| 1237 | .Padding(padding) |
| 1238 | .Authorization(TAG_MAC_LENGTH, mac_length_bits) |
| 1239 | .Authorization(TAG_NONCE, iv_in); |
| 1240 | AuthorizationSet out_params; |
| 1241 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 1242 | return ciphertext; |
| 1243 | } |
| 1244 | |
David Drysdale | d2cc8c2 | 2021-04-15 13:29:45 +0100 | [diff] [blame] | 1245 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 1246 | PaddingMode padding, uint8_t mac_length_bits) { |
| 1247 | SCOPED_TRACE("EncryptMessage"); |
| 1248 | auto params = AuthorizationSetBuilder() |
| 1249 | .BlockMode(block_mode) |
| 1250 | .Padding(padding) |
| 1251 | .Authorization(TAG_MAC_LENGTH, mac_length_bits); |
| 1252 | AuthorizationSet out_params; |
| 1253 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 1254 | return ciphertext; |
| 1255 | } |
| 1256 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1257 | string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob, |
| 1258 | const string& ciphertext, |
| 1259 | const AuthorizationSet& params) { |
| 1260 | SCOPED_TRACE("DecryptMessage"); |
| 1261 | AuthorizationSet out_params; |
| 1262 | string plaintext = |
| 1263 | ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params); |
| 1264 | EXPECT_TRUE(out_params.empty()); |
| 1265 | return plaintext; |
| 1266 | } |
| 1267 | |
| 1268 | string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, |
| 1269 | const AuthorizationSet& params) { |
| 1270 | SCOPED_TRACE("DecryptMessage"); |
| 1271 | return DecryptMessage(key_blob_, ciphertext, params); |
| 1272 | } |
| 1273 | |
| 1274 | string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode, |
| 1275 | PaddingMode padding_mode, const vector<uint8_t>& iv) { |
| 1276 | SCOPED_TRACE("DecryptMessage"); |
| 1277 | auto params = AuthorizationSetBuilder() |
| 1278 | .BlockMode(block_mode) |
| 1279 | .Padding(padding_mode) |
| 1280 | .Authorization(TAG_NONCE, iv); |
| 1281 | return DecryptMessage(key_blob_, ciphertext, params); |
| 1282 | } |
| 1283 | |
| 1284 | std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey( |
| 1285 | const vector<uint8_t>& key_blob) { |
| 1286 | std::pair<ErrorCode, vector<uint8_t>> retval; |
| 1287 | vector<uint8_t> outKeyBlob; |
| 1288 | Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob); |
| 1289 | ErrorCode errorcode = GetReturnErrorCode(result); |
| 1290 | retval = std::tie(errorcode, outKeyBlob); |
| 1291 | |
| 1292 | return retval; |
| 1293 | } |
Seth Moore | a12ac74 | 2023-03-03 13:40:30 -0800 | [diff] [blame] | 1294 | |
| 1295 | bool KeyMintAidlTestBase::IsRkpSupportRequired() const { |
| 1296 | if (get_vsr_api_level() >= __ANDROID_API_T__) { |
| 1297 | return true; |
| 1298 | } |
| 1299 | |
| 1300 | if (get_vsr_api_level() >= __ANDROID_API_S__) { |
| 1301 | return SecLevel() != SecurityLevel::STRONGBOX; |
| 1302 | } |
| 1303 | |
| 1304 | return false; |
| 1305 | } |
| 1306 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1307 | vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) { |
| 1308 | switch (algorithm) { |
| 1309 | case Algorithm::RSA: |
| 1310 | switch (SecLevel()) { |
| 1311 | case SecurityLevel::SOFTWARE: |
| 1312 | case SecurityLevel::TRUSTED_ENVIRONMENT: |
| 1313 | return {2048, 3072, 4096}; |
| 1314 | case SecurityLevel::STRONGBOX: |
| 1315 | return {2048}; |
| 1316 | default: |
| 1317 | ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel()); |
| 1318 | break; |
| 1319 | } |
| 1320 | break; |
| 1321 | case Algorithm::EC: |
David Drysdale | df09e54 | 2021-06-08 15:46:11 +0100 | [diff] [blame] | 1322 | ADD_FAILURE() << "EC keys must be specified by curve not size"; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1323 | break; |
| 1324 | case Algorithm::AES: |
| 1325 | return {128, 256}; |
| 1326 | case Algorithm::TRIPLE_DES: |
| 1327 | return {168}; |
| 1328 | case Algorithm::HMAC: { |
| 1329 | vector<uint32_t> retval((512 - 64) / 8 + 1); |
| 1330 | uint32_t size = 64 - 8; |
| 1331 | std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); }); |
| 1332 | return retval; |
| 1333 | } |
| 1334 | default: |
| 1335 | ADD_FAILURE() << "Invalid Algorithm: " << algorithm; |
| 1336 | return {}; |
| 1337 | } |
| 1338 | ADD_FAILURE() << "Should be impossible to get here"; |
| 1339 | return {}; |
| 1340 | } |
| 1341 | |
| 1342 | vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) { |
| 1343 | if (SecLevel() == SecurityLevel::STRONGBOX) { |
| 1344 | switch (algorithm) { |
| 1345 | case Algorithm::RSA: |
| 1346 | return {3072, 4096}; |
| 1347 | case Algorithm::EC: |
| 1348 | return {224, 384, 521}; |
| 1349 | case Algorithm::AES: |
| 1350 | return {192}; |
David Drysdale | 7de9feb | 2021-03-05 14:56:19 +0000 | [diff] [blame] | 1351 | case Algorithm::TRIPLE_DES: |
| 1352 | return {56}; |
| 1353 | default: |
| 1354 | return {}; |
| 1355 | } |
| 1356 | } else { |
| 1357 | switch (algorithm) { |
Prashant Patil | d72b351 | 2021-11-16 08:19:19 +0000 | [diff] [blame] | 1358 | case Algorithm::AES: |
| 1359 | return {64, 96, 131, 512}; |
David Drysdale | 7de9feb | 2021-03-05 14:56:19 +0000 | [diff] [blame] | 1360 | case Algorithm::TRIPLE_DES: |
| 1361 | return {56}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1362 | default: |
| 1363 | return {}; |
| 1364 | } |
| 1365 | } |
| 1366 | return {}; |
| 1367 | } |
| 1368 | |
David Drysdale | 7de9feb | 2021-03-05 14:56:19 +0000 | [diff] [blame] | 1369 | vector<BlockMode> KeyMintAidlTestBase::ValidBlockModes(Algorithm algorithm) { |
| 1370 | switch (algorithm) { |
| 1371 | case Algorithm::AES: |
| 1372 | return { |
| 1373 | BlockMode::CBC, |
| 1374 | BlockMode::CTR, |
| 1375 | BlockMode::ECB, |
| 1376 | BlockMode::GCM, |
| 1377 | }; |
| 1378 | case Algorithm::TRIPLE_DES: |
| 1379 | return { |
| 1380 | BlockMode::CBC, |
| 1381 | BlockMode::ECB, |
| 1382 | }; |
| 1383 | default: |
| 1384 | return {}; |
| 1385 | } |
| 1386 | } |
| 1387 | |
| 1388 | vector<PaddingMode> KeyMintAidlTestBase::ValidPaddingModes(Algorithm algorithm, |
| 1389 | BlockMode blockMode) { |
| 1390 | switch (algorithm) { |
| 1391 | case Algorithm::AES: |
| 1392 | switch (blockMode) { |
| 1393 | case BlockMode::CBC: |
| 1394 | case BlockMode::ECB: |
| 1395 | return {PaddingMode::NONE, PaddingMode::PKCS7}; |
| 1396 | case BlockMode::CTR: |
| 1397 | case BlockMode::GCM: |
| 1398 | return {PaddingMode::NONE}; |
| 1399 | default: |
| 1400 | return {}; |
| 1401 | }; |
| 1402 | case Algorithm::TRIPLE_DES: |
| 1403 | switch (blockMode) { |
| 1404 | case BlockMode::CBC: |
| 1405 | case BlockMode::ECB: |
| 1406 | return {PaddingMode::NONE, PaddingMode::PKCS7}; |
| 1407 | default: |
| 1408 | return {}; |
| 1409 | }; |
| 1410 | default: |
| 1411 | return {}; |
| 1412 | } |
| 1413 | } |
| 1414 | |
| 1415 | vector<PaddingMode> KeyMintAidlTestBase::InvalidPaddingModes(Algorithm algorithm, |
| 1416 | BlockMode blockMode) { |
| 1417 | switch (algorithm) { |
| 1418 | case Algorithm::AES: |
| 1419 | switch (blockMode) { |
| 1420 | case BlockMode::CTR: |
| 1421 | case BlockMode::GCM: |
| 1422 | return {PaddingMode::PKCS7}; |
| 1423 | default: |
| 1424 | return {}; |
| 1425 | }; |
| 1426 | default: |
| 1427 | return {}; |
| 1428 | } |
| 1429 | } |
| 1430 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1431 | vector<EcCurve> KeyMintAidlTestBase::ValidCurves() { |
| 1432 | if (securityLevel_ == SecurityLevel::STRONGBOX) { |
| 1433 | return {EcCurve::P_256}; |
David Drysdale | 42fe189 | 2021-10-14 14:43:46 +0100 | [diff] [blame] | 1434 | } else if (Curve25519Supported()) { |
| 1435 | return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521, |
| 1436 | EcCurve::CURVE_25519}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1437 | } else { |
David Drysdale | 42fe189 | 2021-10-14 14:43:46 +0100 | [diff] [blame] | 1438 | return { |
| 1439 | EcCurve::P_224, |
| 1440 | EcCurve::P_256, |
| 1441 | EcCurve::P_384, |
| 1442 | EcCurve::P_521, |
| 1443 | }; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1444 | } |
| 1445 | } |
| 1446 | |
| 1447 | vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() { |
David Drysdale | df09e54 | 2021-06-08 15:46:11 +0100 | [diff] [blame] | 1448 | if (SecLevel() == SecurityLevel::STRONGBOX) { |
David Drysdale | 42fe189 | 2021-10-14 14:43:46 +0100 | [diff] [blame] | 1449 | // Curve 25519 is not supported, either because: |
| 1450 | // - KeyMint v1: it's an unknown enum value |
| 1451 | // - KeyMint v2+: it's not supported by StrongBox. |
| 1452 | return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521, EcCurve::CURVE_25519}; |
David Drysdale | df09e54 | 2021-06-08 15:46:11 +0100 | [diff] [blame] | 1453 | } else { |
David Drysdale | 42fe189 | 2021-10-14 14:43:46 +0100 | [diff] [blame] | 1454 | if (Curve25519Supported()) { |
| 1455 | return {}; |
| 1456 | } else { |
| 1457 | return {EcCurve::CURVE_25519}; |
| 1458 | } |
David Drysdale | df09e54 | 2021-06-08 15:46:11 +0100 | [diff] [blame] | 1459 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1460 | } |
| 1461 | |
subrahmanyaman | 0564249 | 2022-02-05 07:10:56 +0000 | [diff] [blame] | 1462 | vector<uint64_t> KeyMintAidlTestBase::ValidExponents() { |
| 1463 | if (SecLevel() == SecurityLevel::STRONGBOX) { |
| 1464 | return {65537}; |
| 1465 | } else { |
| 1466 | return {3, 65537}; |
| 1467 | } |
| 1468 | } |
| 1469 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1470 | vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) { |
| 1471 | switch (SecLevel()) { |
| 1472 | case SecurityLevel::SOFTWARE: |
| 1473 | case SecurityLevel::TRUSTED_ENVIRONMENT: |
| 1474 | if (withNone) { |
| 1475 | if (withMD5) |
| 1476 | return {Digest::NONE, Digest::MD5, Digest::SHA1, |
| 1477 | Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384, |
| 1478 | Digest::SHA_2_512}; |
| 1479 | else |
| 1480 | return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224, |
| 1481 | Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}; |
| 1482 | } else { |
| 1483 | if (withMD5) |
| 1484 | return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224, |
| 1485 | Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}; |
| 1486 | else |
| 1487 | return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384, |
| 1488 | Digest::SHA_2_512}; |
| 1489 | } |
| 1490 | break; |
| 1491 | case SecurityLevel::STRONGBOX: |
| 1492 | if (withNone) |
| 1493 | return {Digest::NONE, Digest::SHA_2_256}; |
| 1494 | else |
| 1495 | return {Digest::SHA_2_256}; |
| 1496 | break; |
| 1497 | default: |
| 1498 | ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel()); |
| 1499 | break; |
| 1500 | } |
| 1501 | ADD_FAILURE() << "Should be impossible to get here"; |
| 1502 | return {}; |
| 1503 | } |
| 1504 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 1505 | static const vector<KeyParameter> kEmptyAuthList{}; |
| 1506 | |
| 1507 | const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations( |
| 1508 | const vector<KeyCharacteristics>& key_characteristics) { |
| 1509 | auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(), |
| 1510 | [this](auto& entry) { return entry.securityLevel == SecLevel(); }); |
| 1511 | return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations; |
| 1512 | } |
| 1513 | |
Qi Wu | beefae4 | 2021-01-28 23:16:37 +0800 | [diff] [blame] | 1514 | const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations( |
| 1515 | const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) { |
| 1516 | auto found = std::find_if( |
| 1517 | key_characteristics.begin(), key_characteristics.end(), |
| 1518 | [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; }); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 1519 | return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations; |
| 1520 | } |
| 1521 | |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1522 | ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 1523 | auto [result, ciphertext] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1524 | aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456", |
| 1525 | AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)); |
| 1526 | return result; |
| 1527 | } |
| 1528 | |
| 1529 | ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 1530 | auto [result, mac] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1531 | hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456", |
| 1532 | AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256)); |
| 1533 | return result; |
| 1534 | } |
| 1535 | |
| 1536 | ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) { |
| 1537 | std::string message(2048 / 8, 'a'); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 1538 | auto [result, signature] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1539 | rsaKeyBlob, KeyPurpose::SIGN, message, |
| 1540 | AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)); |
| 1541 | return result; |
| 1542 | } |
| 1543 | |
| 1544 | ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 1545 | auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a", |
| 1546 | AuthorizationSetBuilder().Digest(Digest::SHA_2_256)); |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 1547 | return result; |
| 1548 | } |
| 1549 | |
Subrahmanyaman | 50fcf7d | 2023-04-20 22:48:39 +0000 | [diff] [blame] | 1550 | ErrorCode KeyMintAidlTestBase::GenerateAttestKey(const AuthorizationSet& key_desc, |
| 1551 | const optional<AttestationKey>& attest_key, |
| 1552 | vector<uint8_t>* key_blob, |
| 1553 | vector<KeyCharacteristics>* key_characteristics, |
| 1554 | vector<Certificate>* cert_chain) { |
| 1555 | // The original specification for KeyMint v1 required ATTEST_KEY not be combined |
| 1556 | // with any other key purpose, but the original VTS tests incorrectly did exactly that. |
| 1557 | // This means that a device that launched prior to Android T (API level 33) may |
| 1558 | // accept or even require KeyPurpose::SIGN too. |
| 1559 | if (property_get_int32("ro.board.first_api_level", 0) < __ANDROID_API_T__) { |
| 1560 | AuthorizationSet key_desc_plus_sign = key_desc; |
| 1561 | key_desc_plus_sign.push_back(TAG_PURPOSE, KeyPurpose::SIGN); |
| 1562 | |
| 1563 | auto result = GenerateKey(key_desc_plus_sign, attest_key, key_blob, key_characteristics, |
| 1564 | cert_chain); |
| 1565 | if (result == ErrorCode::OK) { |
| 1566 | return result; |
| 1567 | } |
| 1568 | // If the key generation failed, it may be because the device is (correctly) |
| 1569 | // rejecting the combination of ATTEST_KEY+SIGN. Fall through to try again with |
| 1570 | // just ATTEST_KEY. |
| 1571 | } |
| 1572 | return GenerateKey(key_desc, attest_key, key_blob, key_characteristics, cert_chain); |
| 1573 | } |
| 1574 | |
| 1575 | // Check if ATTEST_KEY feature is disabled |
| 1576 | bool KeyMintAidlTestBase::is_attest_key_feature_disabled(void) const { |
| 1577 | if (!check_feature(FEATURE_KEYSTORE_APP_ATTEST_KEY)) { |
| 1578 | GTEST_LOG_(INFO) << "Feature " + FEATURE_KEYSTORE_APP_ATTEST_KEY + " is disabled"; |
| 1579 | return true; |
| 1580 | } |
| 1581 | |
| 1582 | return false; |
| 1583 | } |
| 1584 | |
| 1585 | // Check if StrongBox KeyStore is enabled |
| 1586 | bool KeyMintAidlTestBase::is_strongbox_enabled(void) const { |
| 1587 | if (check_feature(FEATURE_STRONGBOX_KEYSTORE)) { |
| 1588 | GTEST_LOG_(INFO) << "Feature " + FEATURE_STRONGBOX_KEYSTORE + " is enabled"; |
| 1589 | return true; |
| 1590 | } |
| 1591 | |
| 1592 | return false; |
| 1593 | } |
| 1594 | |
| 1595 | // Check if chipset has received a waiver allowing it to be launched with Android S or T with |
| 1596 | // Keymaster 4.0 in StrongBox. |
| 1597 | bool KeyMintAidlTestBase::is_chipset_allowed_km4_strongbox(void) const { |
| 1598 | std::array<char, PROPERTY_VALUE_MAX> buffer; |
| 1599 | |
| 1600 | const int32_t first_api_level = property_get_int32("ro.board.first_api_level", 0); |
| 1601 | if (first_api_level <= 0 || first_api_level > __ANDROID_API_T__) return false; |
| 1602 | |
| 1603 | auto res = property_get("ro.vendor.qti.soc_model", buffer.data(), nullptr); |
| 1604 | if (res <= 0) return false; |
| 1605 | |
Shawn Willden | 0f1b257 | 2023-05-30 14:52:53 -0600 | [diff] [blame] | 1606 | const string allowed_soc_models[] = {"SM8450", "SM8475", "SM8550", "SXR2230P", |
| 1607 | "SM4450", "SM7450", "SM6450"}; |
Subrahmanyaman | 50fcf7d | 2023-04-20 22:48:39 +0000 | [diff] [blame] | 1608 | |
| 1609 | for (const string model : allowed_soc_models) { |
| 1610 | if (model.compare(buffer.data()) == 0) { |
| 1611 | GTEST_LOG_(INFO) << "QTI SOC Model " + model + " is allowed SB KM 4.0"; |
| 1612 | return true; |
| 1613 | } |
| 1614 | } |
| 1615 | |
| 1616 | return false; |
| 1617 | } |
| 1618 | |
| 1619 | // Skip the test if all the following conditions hold: |
| 1620 | // 1. ATTEST_KEY feature is disabled |
| 1621 | // 2. STRONGBOX is enabled |
| 1622 | // 3. The device is running one of the chipsets that have received a waiver |
| 1623 | // allowing it to be launched with Android S (or later) with Keymaster 4.0 |
| 1624 | // in StrongBox |
| 1625 | void KeyMintAidlTestBase::skipAttestKeyTest(void) const { |
| 1626 | // Check the chipset first as that doesn't require a round-trip to Package Manager. |
| 1627 | if (is_chipset_allowed_km4_strongbox() && is_strongbox_enabled() && |
| 1628 | is_attest_key_feature_disabled()) { |
| 1629 | GTEST_SKIP() << "Test is not applicable"; |
| 1630 | } |
| 1631 | } |
| 1632 | |
Selene Huang | 6e46f14 | 2021-04-20 19:20:11 -0700 | [diff] [blame] | 1633 | void verify_serial(X509* cert, const uint64_t expected_serial) { |
| 1634 | BIGNUM_Ptr ser(BN_new()); |
| 1635 | EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get())); |
| 1636 | |
| 1637 | uint64_t serial; |
| 1638 | EXPECT_TRUE(BN_get_u64(ser.get(), &serial)); |
| 1639 | EXPECT_EQ(serial, expected_serial); |
| 1640 | } |
| 1641 | |
| 1642 | // Please set self_signed to true for fake certificates or self signed |
| 1643 | // certificates |
| 1644 | void verify_subject(const X509* cert, // |
| 1645 | const string& subject, // |
| 1646 | bool self_signed) { |
| 1647 | char* cert_issuer = // |
| 1648 | X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0); |
| 1649 | |
| 1650 | char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0); |
| 1651 | |
| 1652 | string expected_subject("/CN="); |
| 1653 | if (subject.empty()) { |
| 1654 | expected_subject.append("Android Keystore Key"); |
| 1655 | } else { |
| 1656 | expected_subject.append(subject); |
| 1657 | } |
| 1658 | |
| 1659 | EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj; |
| 1660 | |
| 1661 | if (self_signed) { |
| 1662 | EXPECT_STREQ(cert_issuer, cert_subj) |
| 1663 | << "Cert issuer and subject mismatch for self signed certificate."; |
| 1664 | } |
| 1665 | |
| 1666 | OPENSSL_free(cert_subj); |
| 1667 | OPENSSL_free(cert_issuer); |
| 1668 | } |
| 1669 | |
Shawn Willden | 22fb9c1 | 2022-06-02 14:04:33 -0600 | [diff] [blame] | 1670 | int get_vsr_api_level() { |
Shawn Willden | 35db349 | 2022-06-16 12:50:40 -0600 | [diff] [blame] | 1671 | int vendor_api_level = ::android::base::GetIntProperty("ro.vendor.api_level", -1); |
| 1672 | if (vendor_api_level != -1) { |
| 1673 | return vendor_api_level; |
Shawn Willden | 22fb9c1 | 2022-06-02 14:04:33 -0600 | [diff] [blame] | 1674 | } |
Shawn Willden | 35db349 | 2022-06-16 12:50:40 -0600 | [diff] [blame] | 1675 | |
| 1676 | // Android S and older devices do not define ro.vendor.api_level |
| 1677 | vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1); |
| 1678 | if (vendor_api_level == -1) { |
| 1679 | vendor_api_level = ::android::base::GetIntProperty("ro.board.first_api_level", -1); |
Shawn Willden | 22fb9c1 | 2022-06-02 14:04:33 -0600 | [diff] [blame] | 1680 | } |
Shawn Willden | 35db349 | 2022-06-16 12:50:40 -0600 | [diff] [blame] | 1681 | |
| 1682 | int product_api_level = ::android::base::GetIntProperty("ro.product.first_api_level", -1); |
| 1683 | if (product_api_level == -1) { |
| 1684 | product_api_level = ::android::base::GetIntProperty("ro.build.version.sdk", -1); |
| 1685 | EXPECT_NE(product_api_level, -1) << "Could not find ro.build.version.sdk"; |
Shawn Willden | 22fb9c1 | 2022-06-02 14:04:33 -0600 | [diff] [blame] | 1686 | } |
Shawn Willden | 35db349 | 2022-06-16 12:50:40 -0600 | [diff] [blame] | 1687 | |
| 1688 | // VSR API level is the minimum of vendor_api_level and product_api_level. |
| 1689 | if (vendor_api_level == -1 || vendor_api_level > product_api_level) { |
| 1690 | return product_api_level; |
Shawn Willden | 22fb9c1 | 2022-06-02 14:04:33 -0600 | [diff] [blame] | 1691 | } |
Shawn Willden | 35db349 | 2022-06-16 12:50:40 -0600 | [diff] [blame] | 1692 | return vendor_api_level; |
Shawn Willden | 22fb9c1 | 2022-06-02 14:04:33 -0600 | [diff] [blame] | 1693 | } |
| 1694 | |
David Drysdale | 555ba00 | 2022-05-03 18:48:57 +0100 | [diff] [blame] | 1695 | bool is_gsi_image() { |
| 1696 | std::ifstream ifs("/system/system_ext/etc/init/init.gsi.rc"); |
| 1697 | return ifs.good(); |
| 1698 | } |
| 1699 | |
Selene Huang | 6e46f14 | 2021-04-20 19:20:11 -0700 | [diff] [blame] | 1700 | vector<uint8_t> build_serial_blob(const uint64_t serial_int) { |
| 1701 | BIGNUM_Ptr serial(BN_new()); |
| 1702 | EXPECT_TRUE(BN_set_u64(serial.get(), serial_int)); |
| 1703 | |
| 1704 | int len = BN_num_bytes(serial.get()); |
| 1705 | vector<uint8_t> serial_blob(len); |
| 1706 | if (BN_bn2bin(serial.get(), serial_blob.data()) != len) { |
| 1707 | return {}; |
| 1708 | } |
| 1709 | |
David Drysdale | db0dcf5 | 2021-05-18 11:43:31 +0100 | [diff] [blame] | 1710 | if (serial_blob.empty() || serial_blob[0] & 0x80) { |
| 1711 | // An empty blob is OpenSSL's encoding of the zero value; we need single zero byte. |
| 1712 | // Top bit being set indicates a negative number in two's complement, but our input |
| 1713 | // was positive. |
| 1714 | // In either case, prepend a zero byte. |
| 1715 | serial_blob.insert(serial_blob.begin(), 0x00); |
| 1716 | } |
| 1717 | |
Selene Huang | 6e46f14 | 2021-04-20 19:20:11 -0700 | [diff] [blame] | 1718 | return serial_blob; |
| 1719 | } |
| 1720 | |
| 1721 | void verify_subject_and_serial(const Certificate& certificate, // |
| 1722 | const uint64_t expected_serial, // |
| 1723 | const string& subject, bool self_signed) { |
| 1724 | X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate)); |
| 1725 | ASSERT_TRUE(!!cert.get()); |
| 1726 | |
| 1727 | verify_serial(cert.get(), expected_serial); |
| 1728 | verify_subject(cert.get(), subject, self_signed); |
| 1729 | } |
| 1730 | |
Shawn Willden | 4315e13 | 2022-03-20 12:49:46 -0600 | [diff] [blame] | 1731 | void verify_root_of_trust(const vector<uint8_t>& verified_boot_key, bool device_locked, |
| 1732 | VerifiedBoot verified_boot_state, |
| 1733 | const vector<uint8_t>& verified_boot_hash) { |
| 1734 | char property_value[PROPERTY_VALUE_MAX] = {}; |
| 1735 | |
| 1736 | if (avb_verification_enabled()) { |
| 1737 | EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0); |
| 1738 | string prop_string(property_value); |
| 1739 | EXPECT_EQ(prop_string.size(), 64); |
| 1740 | EXPECT_EQ(prop_string, bin2hex(verified_boot_hash)); |
| 1741 | |
| 1742 | EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0); |
| 1743 | if (!strcmp(property_value, "unlocked")) { |
| 1744 | EXPECT_FALSE(device_locked); |
| 1745 | } else { |
| 1746 | EXPECT_TRUE(device_locked); |
| 1747 | } |
| 1748 | |
| 1749 | // Check that the device is locked if not debuggable, e.g., user build |
| 1750 | // images in CTS. For VTS, debuggable images are used to allow adb root |
| 1751 | // and the device is unlocked. |
| 1752 | if (!property_get_bool("ro.debuggable", false)) { |
| 1753 | EXPECT_TRUE(device_locked); |
| 1754 | } else { |
| 1755 | EXPECT_FALSE(device_locked); |
| 1756 | } |
| 1757 | } |
| 1758 | |
| 1759 | // Verified boot key should be all 0's if the boot state is not verified or self signed |
| 1760 | std::string empty_boot_key(32, '\0'); |
| 1761 | std::string verified_boot_key_str((const char*)verified_boot_key.data(), |
| 1762 | verified_boot_key.size()); |
| 1763 | EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0); |
| 1764 | if (!strcmp(property_value, "green")) { |
| 1765 | EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED); |
| 1766 | EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1767 | verified_boot_key.size())); |
| 1768 | } else if (!strcmp(property_value, "yellow")) { |
| 1769 | EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED); |
| 1770 | EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1771 | verified_boot_key.size())); |
| 1772 | } else if (!strcmp(property_value, "orange")) { |
| 1773 | EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED); |
| 1774 | EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1775 | verified_boot_key.size())); |
| 1776 | } else if (!strcmp(property_value, "red")) { |
| 1777 | EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED); |
| 1778 | } else { |
| 1779 | EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED); |
| 1780 | EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1781 | verified_boot_key.size())); |
| 1782 | } |
| 1783 | } |
| 1784 | |
David Drysdale | 7dff4fc | 2021-12-10 10:10:52 +0000 | [diff] [blame] | 1785 | bool verify_attestation_record(int32_t aidl_version, // |
| 1786 | const string& challenge, // |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1787 | const string& app_id, // |
| 1788 | AuthorizationSet expected_sw_enforced, // |
| 1789 | AuthorizationSet expected_hw_enforced, // |
| 1790 | SecurityLevel security_level, |
David Drysdale | 565ccc7 | 2021-10-11 12:49:50 +0100 | [diff] [blame] | 1791 | const vector<uint8_t>& attestation_cert, |
| 1792 | vector<uint8_t>* unique_id) { |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1793 | X509_Ptr cert(parse_cert_blob(attestation_cert)); |
| 1794 | EXPECT_TRUE(!!cert.get()); |
| 1795 | if (!cert.get()) return false; |
| 1796 | |
Rajesh Nyamagoud | e98263e | 2023-02-09 20:36:33 +0000 | [diff] [blame] | 1797 | // Make sure CRL Distribution Points extension is not present in a certificate |
| 1798 | // containing attestation record. |
| 1799 | check_crl_distribution_points_extension_not_present(cert.get()); |
| 1800 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1801 | ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get()); |
| 1802 | EXPECT_TRUE(!!attest_rec); |
| 1803 | if (!attest_rec) return false; |
| 1804 | |
| 1805 | AuthorizationSet att_sw_enforced; |
| 1806 | AuthorizationSet att_hw_enforced; |
| 1807 | uint32_t att_attestation_version; |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1808 | uint32_t att_keymint_version; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1809 | SecurityLevel att_attestation_security_level; |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1810 | SecurityLevel att_keymint_security_level; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1811 | vector<uint8_t> att_challenge; |
| 1812 | vector<uint8_t> att_unique_id; |
| 1813 | vector<uint8_t> att_app_id; |
| 1814 | |
| 1815 | auto error = parse_attestation_record(attest_rec->data, // |
| 1816 | attest_rec->length, // |
| 1817 | &att_attestation_version, // |
| 1818 | &att_attestation_security_level, // |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1819 | &att_keymint_version, // |
| 1820 | &att_keymint_security_level, // |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1821 | &att_challenge, // |
| 1822 | &att_sw_enforced, // |
| 1823 | &att_hw_enforced, // |
| 1824 | &att_unique_id); |
| 1825 | EXPECT_EQ(ErrorCode::OK, error); |
| 1826 | if (error != ErrorCode::OK) return false; |
| 1827 | |
David Drysdale | 7dff4fc | 2021-12-10 10:10:52 +0000 | [diff] [blame] | 1828 | check_attestation_version(att_attestation_version, aidl_version); |
Selene Huang | 4f64c22 | 2021-04-13 19:54:36 -0700 | [diff] [blame] | 1829 | vector<uint8_t> appId(app_id.begin(), app_id.end()); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1830 | |
Selene Huang | 4f64c22 | 2021-04-13 19:54:36 -0700 | [diff] [blame] | 1831 | // check challenge and app id only if we expects a non-fake certificate |
| 1832 | if (challenge.length() > 0) { |
| 1833 | EXPECT_EQ(challenge.length(), att_challenge.size()); |
| 1834 | EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length())); |
| 1835 | |
| 1836 | expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId); |
| 1837 | } |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1838 | |
David Drysdale | 7dff4fc | 2021-12-10 10:10:52 +0000 | [diff] [blame] | 1839 | check_attestation_version(att_keymint_version, aidl_version); |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1840 | EXPECT_EQ(security_level, att_keymint_security_level); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1841 | EXPECT_EQ(security_level, att_attestation_security_level); |
| 1842 | |
Tri Vo | b21e6df | 2023-02-17 14:55:43 -0800 | [diff] [blame] | 1843 | for (int i = 0; i < att_hw_enforced.size(); i++) { |
| 1844 | if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL || |
| 1845 | att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) { |
| 1846 | std::string date = |
| 1847 | std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>()); |
David Drysdale | 168228a | 2021-10-05 08:43:52 +0100 | [diff] [blame] | 1848 | |
Tri Vo | b21e6df | 2023-02-17 14:55:43 -0800 | [diff] [blame] | 1849 | // strptime seems to require delimiters, but the tag value will |
| 1850 | // be YYYYMMDD |
| 1851 | if (date.size() != 8) { |
| 1852 | ADD_FAILURE() << "Tag " << att_hw_enforced[i].tag |
| 1853 | << " with invalid format (not YYYYMMDD): " << date; |
| 1854 | return false; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1855 | } |
Tri Vo | b21e6df | 2023-02-17 14:55:43 -0800 | [diff] [blame] | 1856 | date.insert(6, "-"); |
| 1857 | date.insert(4, "-"); |
| 1858 | struct tm time; |
| 1859 | strptime(date.c_str(), "%Y-%m-%d", &time); |
| 1860 | |
| 1861 | // Day of the month (0-31) |
| 1862 | EXPECT_GE(time.tm_mday, 0); |
| 1863 | EXPECT_LT(time.tm_mday, 32); |
| 1864 | // Months since Jan (0-11) |
| 1865 | EXPECT_GE(time.tm_mon, 0); |
| 1866 | EXPECT_LT(time.tm_mon, 12); |
| 1867 | // Years since 1900 |
| 1868 | EXPECT_GT(time.tm_year, 110); |
| 1869 | EXPECT_LT(time.tm_year, 200); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1870 | } |
| 1871 | } |
| 1872 | |
| 1873 | // Check to make sure boolean values are properly encoded. Presence of a boolean tag |
| 1874 | // indicates true. A provided boolean tag that can be pulled back out of the certificate |
| 1875 | // indicates correct encoding. No need to check if it's in both lists, since the |
| 1876 | // AuthorizationSet compare below will handle mismatches of tags. |
| 1877 | if (security_level == SecurityLevel::SOFTWARE) { |
| 1878 | EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED)); |
| 1879 | } else { |
| 1880 | EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED)); |
| 1881 | } |
| 1882 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1883 | if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) { |
| 1884 | // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be. |
| 1885 | EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) || |
| 1886 | att_hw_enforced.Contains(TAG_KEY_SIZE)); |
| 1887 | } |
| 1888 | |
| 1889 | // Test root of trust elements |
| 1890 | vector<uint8_t> verified_boot_key; |
| 1891 | VerifiedBoot verified_boot_state; |
| 1892 | bool device_locked; |
| 1893 | vector<uint8_t> verified_boot_hash; |
| 1894 | error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key, |
| 1895 | &verified_boot_state, &device_locked, &verified_boot_hash); |
| 1896 | EXPECT_EQ(ErrorCode::OK, error); |
Shawn Willden | 4315e13 | 2022-03-20 12:49:46 -0600 | [diff] [blame] | 1897 | verify_root_of_trust(verified_boot_key, device_locked, verified_boot_state, verified_boot_hash); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1898 | |
| 1899 | att_sw_enforced.Sort(); |
| 1900 | expected_sw_enforced.Sort(); |
David Drysdale | 37af4b3 | 2021-05-14 16:46:59 +0100 | [diff] [blame] | 1901 | EXPECT_EQ(filtered_tags(expected_sw_enforced), filtered_tags(att_sw_enforced)); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1902 | |
| 1903 | att_hw_enforced.Sort(); |
| 1904 | expected_hw_enforced.Sort(); |
| 1905 | EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced)); |
| 1906 | |
David Drysdale | 565ccc7 | 2021-10-11 12:49:50 +0100 | [diff] [blame] | 1907 | if (unique_id != nullptr) { |
| 1908 | *unique_id = att_unique_id; |
| 1909 | } |
| 1910 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1911 | return true; |
| 1912 | } |
| 1913 | |
| 1914 | string bin2hex(const vector<uint8_t>& data) { |
| 1915 | string retval; |
| 1916 | retval.reserve(data.size() * 2 + 1); |
| 1917 | for (uint8_t byte : data) { |
| 1918 | retval.push_back(nibble2hex[0x0F & (byte >> 4)]); |
| 1919 | retval.push_back(nibble2hex[0x0F & byte]); |
| 1920 | } |
| 1921 | return retval; |
| 1922 | } |
| 1923 | |
David Drysdale | f0d516d | 2021-03-22 07:51:43 +0000 | [diff] [blame] | 1924 | AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) { |
| 1925 | AuthorizationSet authList; |
| 1926 | for (auto& entry : key_characteristics) { |
| 1927 | if (entry.securityLevel == SecurityLevel::STRONGBOX || |
| 1928 | entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) { |
| 1929 | authList.push_back(AuthorizationSet(entry.authorizations)); |
| 1930 | } |
| 1931 | } |
| 1932 | return authList; |
| 1933 | } |
| 1934 | |
| 1935 | AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) { |
| 1936 | AuthorizationSet authList; |
| 1937 | for (auto& entry : key_characteristics) { |
| 1938 | if (entry.securityLevel == SecurityLevel::SOFTWARE || |
| 1939 | entry.securityLevel == SecurityLevel::KEYSTORE) { |
| 1940 | authList.push_back(AuthorizationSet(entry.authorizations)); |
| 1941 | } |
| 1942 | } |
| 1943 | return authList; |
| 1944 | } |
| 1945 | |
Eran Messeri | 03d7a1a | 2021-07-06 12:07:57 +0100 | [diff] [blame] | 1946 | AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain, |
| 1947 | bool strict_issuer_check) { |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1948 | std::stringstream cert_data; |
| 1949 | |
| 1950 | for (size_t i = 0; i < chain.size(); ++i) { |
| 1951 | cert_data << bin2hex(chain[i].encodedCertificate) << std::endl; |
| 1952 | |
| 1953 | X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate)); |
| 1954 | X509_Ptr signing_cert; |
| 1955 | if (i < chain.size() - 1) { |
| 1956 | signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate); |
| 1957 | } else { |
| 1958 | signing_cert = parse_cert_blob(chain[i].encodedCertificate); |
| 1959 | } |
| 1960 | if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str(); |
| 1961 | |
| 1962 | EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get())); |
| 1963 | if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str(); |
| 1964 | |
| 1965 | if (!X509_verify(key_cert.get(), signing_pubkey.get())) { |
| 1966 | return AssertionFailure() |
| 1967 | << "Verification of certificate " << i << " failed " |
| 1968 | << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n' |
| 1969 | << cert_data.str(); |
| 1970 | } |
| 1971 | |
| 1972 | string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get())); |
| 1973 | string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get())); |
Eran Messeri | 03d7a1a | 2021-07-06 12:07:57 +0100 | [diff] [blame] | 1974 | if (cert_issuer != signer_subj && strict_issuer_check) { |
Selene Huang | 8f9494c | 2021-04-21 15:10:36 -0700 | [diff] [blame] | 1975 | return AssertionFailure() << "Cert " << i << " has wrong issuer.\n" |
| 1976 | << " Signer subject is " << signer_subj |
| 1977 | << " Issuer subject is " << cert_issuer << endl |
| 1978 | << cert_data.str(); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1979 | } |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1980 | } |
| 1981 | |
| 1982 | if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str(); |
| 1983 | return AssertionSuccess(); |
| 1984 | } |
| 1985 | |
David Drysdale | 1b9febc | 2023-06-07 13:43:24 +0100 | [diff] [blame] | 1986 | ErrorCode GetReturnErrorCode(const Status& result) { |
| 1987 | if (result.isOk()) return ErrorCode::OK; |
| 1988 | |
| 1989 | if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) { |
| 1990 | return static_cast<ErrorCode>(result.getServiceSpecificError()); |
| 1991 | } |
| 1992 | |
| 1993 | return ErrorCode::UNKNOWN_ERROR; |
| 1994 | } |
| 1995 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1996 | X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) { |
| 1997 | const uint8_t* p = blob.data(); |
| 1998 | return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size())); |
| 1999 | } |
| 2000 | |
Tri Vo | ec50ee1 | 2023-02-14 16:29:53 -0800 | [diff] [blame] | 2001 | // Extract attestation record from cert. Returned object is still part of cert; don't free it |
| 2002 | // separately. |
| 2003 | ASN1_OCTET_STRING* get_attestation_record(X509* certificate) { |
| 2004 | ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */)); |
| 2005 | EXPECT_TRUE(!!oid.get()); |
| 2006 | if (!oid.get()) return nullptr; |
| 2007 | |
| 2008 | int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */); |
| 2009 | EXPECT_NE(-1, location) << "Attestation extension not found in certificate"; |
| 2010 | if (location == -1) return nullptr; |
| 2011 | |
| 2012 | X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location); |
| 2013 | EXPECT_TRUE(!!attest_rec_ext) |
| 2014 | << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug."; |
| 2015 | if (!attest_rec_ext) return nullptr; |
| 2016 | |
| 2017 | ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext); |
| 2018 | EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data"; |
| 2019 | return attest_rec; |
| 2020 | } |
| 2021 | |
David Drysdale | f0d516d | 2021-03-22 07:51:43 +0000 | [diff] [blame] | 2022 | vector<uint8_t> make_name_from_str(const string& name) { |
| 2023 | X509_NAME_Ptr x509_name(X509_NAME_new()); |
| 2024 | EXPECT_TRUE(x509_name.get() != nullptr); |
| 2025 | if (!x509_name) return {}; |
| 2026 | |
| 2027 | EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), // |
| 2028 | "CN", // |
| 2029 | MBSTRING_ASC, |
| 2030 | reinterpret_cast<const uint8_t*>(name.c_str()), |
| 2031 | -1, // len |
| 2032 | -1, // loc |
| 2033 | 0 /* set */)); |
| 2034 | |
| 2035 | int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */); |
| 2036 | EXPECT_GT(len, 0); |
| 2037 | |
| 2038 | vector<uint8_t> retval(len); |
| 2039 | uint8_t* p = retval.data(); |
| 2040 | i2d_X509_NAME(x509_name.get(), &p); |
| 2041 | |
| 2042 | return retval; |
| 2043 | } |
| 2044 | |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 2045 | namespace { |
| 2046 | |
| 2047 | void check_cose_key(const vector<uint8_t>& data, bool testMode) { |
| 2048 | auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data); |
| 2049 | ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr; |
| 2050 | |
| 2051 | // The following check assumes that canonical CBOR encoding is used for the COSE_Key. |
| 2052 | if (testMode) { |
Elliott Hughes | be36da4 | 2022-11-09 21:35:07 +0000 | [diff] [blame] | 2053 | EXPECT_THAT( |
| 2054 | cppbor::prettyPrint(parsedPayload.get()), |
| 2055 | MatchesRegex("\\{\n" |
| 2056 | " 1 : 2,\n" // kty: EC2 |
| 2057 | " 3 : -7,\n" // alg: ES256 |
| 2058 | " -1 : 1,\n" // EC id: P256 |
| 2059 | // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a |
| 2060 | // sequence of 32 hexadecimal bytes, enclosed in braces and |
| 2061 | // separated by commas. In this case, some Ed25519 public key. |
| 2062 | " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data |
| 2063 | " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data |
| 2064 | " -70000 : null,\n" // test marker |
| 2065 | "\\}")); |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 2066 | } else { |
Elliott Hughes | be36da4 | 2022-11-09 21:35:07 +0000 | [diff] [blame] | 2067 | EXPECT_THAT( |
| 2068 | cppbor::prettyPrint(parsedPayload.get()), |
| 2069 | MatchesRegex("\\{\n" |
| 2070 | " 1 : 2,\n" // kty: EC2 |
| 2071 | " 3 : -7,\n" // alg: ES256 |
| 2072 | " -1 : 1,\n" // EC id: P256 |
| 2073 | // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a |
| 2074 | // sequence of 32 hexadecimal bytes, enclosed in braces and |
| 2075 | // separated by commas. In this case, some Ed25519 public key. |
| 2076 | " -2 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_x: data |
| 2077 | " -3 : \\{(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}\\},\n" // pub_y: data |
| 2078 | "\\}")); |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 2079 | } |
| 2080 | } |
| 2081 | |
| 2082 | } // namespace |
| 2083 | |
| 2084 | void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode, |
| 2085 | vector<uint8_t>* payload_value) { |
| 2086 | auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey); |
| 2087 | ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr; |
| 2088 | |
| 2089 | ASSERT_NE(coseMac0->asArray(), nullptr); |
| 2090 | ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount); |
| 2091 | |
| 2092 | auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr(); |
| 2093 | ASSERT_NE(protParms, nullptr); |
| 2094 | |
| 2095 | // Header label:value of 'alg': HMAC-256 |
| 2096 | ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}"); |
| 2097 | |
| 2098 | auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap(); |
| 2099 | ASSERT_NE(unprotParms, nullptr); |
| 2100 | ASSERT_EQ(unprotParms->size(), 0); |
| 2101 | |
| 2102 | // The payload is a bstr holding an encoded COSE_Key |
| 2103 | auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr(); |
| 2104 | ASSERT_NE(payload, nullptr); |
| 2105 | check_cose_key(payload->value(), testMode); |
| 2106 | |
| 2107 | auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr(); |
| 2108 | ASSERT_TRUE(coseMac0Tag); |
| 2109 | auto extractedTag = coseMac0Tag->value(); |
| 2110 | EXPECT_EQ(extractedTag.size(), 32U); |
| 2111 | |
| 2112 | // Compare with tag generated with kTestMacKey. Should only match in test mode |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 2113 | auto macFunction = [](const cppcose::bytevec& input) { |
| 2114 | return cppcose::generateHmacSha256(remote_prov::kTestMacKey, input); |
| 2115 | }; |
| 2116 | auto testTag = |
| 2117 | cppcose::generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value()); |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 2118 | ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message(); |
| 2119 | |
| 2120 | if (testMode) { |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 2121 | EXPECT_THAT(*testTag, ElementsAreArray(extractedTag)); |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 2122 | } else { |
Seth Moore | 026bb74 | 2021-04-30 11:41:18 -0700 | [diff] [blame] | 2123 | EXPECT_THAT(*testTag, Not(ElementsAreArray(extractedTag))); |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 2124 | } |
| 2125 | if (payload_value != nullptr) { |
| 2126 | *payload_value = payload->value(); |
| 2127 | } |
| 2128 | } |
| 2129 | |
| 2130 | void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) { |
| 2131 | // Extract x and y affine coordinates from the encoded Cose_Key. |
| 2132 | auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData); |
| 2133 | ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr; |
| 2134 | auto coseKey = parsedPayload->asMap(); |
| 2135 | const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X); |
| 2136 | ASSERT_NE(xItem->asBstr(), nullptr); |
| 2137 | vector<uint8_t> x = xItem->asBstr()->value(); |
| 2138 | const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y); |
| 2139 | ASSERT_NE(yItem->asBstr(), nullptr); |
| 2140 | vector<uint8_t> y = yItem->asBstr()->value(); |
| 2141 | |
| 2142 | // Concatenate: 0x04 (uncompressed form marker) | x | y |
| 2143 | vector<uint8_t> pubKeyData{0x04}; |
| 2144 | pubKeyData.insert(pubKeyData.end(), x.begin(), x.end()); |
| 2145 | pubKeyData.insert(pubKeyData.end(), y.begin(), y.end()); |
| 2146 | |
| 2147 | EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new()); |
| 2148 | ASSERT_NE(ecKey, nullptr); |
| 2149 | EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); |
| 2150 | ASSERT_NE(group, nullptr); |
| 2151 | ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1); |
| 2152 | EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get())); |
| 2153 | ASSERT_NE(point, nullptr); |
| 2154 | ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(), |
| 2155 | nullptr), |
| 2156 | 1); |
| 2157 | ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1); |
| 2158 | |
| 2159 | EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new()); |
| 2160 | ASSERT_NE(pubKey, nullptr); |
| 2161 | EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release()); |
| 2162 | *signingKey = std::move(pubKey); |
| 2163 | } |
| 2164 | |
David Drysdale | f42238c | 2023-06-15 09:41:05 +0100 | [diff] [blame] | 2165 | // Check the error code from an attempt to perform device ID attestation with an invalid value. |
| 2166 | void device_id_attestation_check_acceptable_error(Tag tag, const ErrorCode& result) { |
| 2167 | // Standard/default error code for ID mismatch. |
| 2168 | if (result == ErrorCode::CANNOT_ATTEST_IDS) { |
| 2169 | return; |
| 2170 | } |
| 2171 | |
| 2172 | // Depending on the situation, other error codes may be acceptable. First, allow older |
| 2173 | // implementations to use INVALID_TAG. |
| 2174 | if (result == ErrorCode::INVALID_TAG) { |
| 2175 | ASSERT_FALSE(get_vsr_api_level() > __ANDROID_API_T__) |
Max Bires | a97ec69 | 2022-11-21 23:37:54 -0800 | [diff] [blame] | 2176 | << "It is a specification violation for INVALID_TAG to be returned due to ID " |
| 2177 | << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to " |
| 2178 | << "be used for a case where updateAad() is called after update(). As of " |
| 2179 | << "VSR-14, this is now enforced as an error."; |
| 2180 | } |
David Drysdale | f42238c | 2023-06-15 09:41:05 +0100 | [diff] [blame] | 2181 | |
| 2182 | // If the device is not a phone, it will not have IMEI/MEID values available. Allow |
| 2183 | // ATTESTATION_IDS_NOT_PROVISIONED in this case. |
| 2184 | if (result == ErrorCode::ATTESTATION_IDS_NOT_PROVISIONED) { |
| 2185 | ASSERT_TRUE((tag == TAG_ATTESTATION_ID_IMEI || tag == TAG_ATTESTATION_ID_MEID || |
| 2186 | tag == TAG_ATTESTATION_ID_SECOND_IMEI)) |
| 2187 | << "incorrect error code on attestation ID mismatch"; |
| 2188 | } |
| 2189 | ADD_FAILURE() << "Error code " << result |
| 2190 | << " returned on attestation ID mismatch, should be CANNOT_ATTEST_IDS"; |
Max Bires | a97ec69 | 2022-11-21 23:37:54 -0800 | [diff] [blame] | 2191 | } |
| 2192 | |
David Drysdale | 3d2ba0a | 2023-01-11 13:27:26 +0000 | [diff] [blame] | 2193 | // Check whether the given named feature is available. |
| 2194 | bool check_feature(const std::string& name) { |
| 2195 | ::android::sp<::android::IServiceManager> sm(::android::defaultServiceManager()); |
Tommy Chiu | 6e5736b | 2023-02-08 10:16:03 +0800 | [diff] [blame] | 2196 | ::android::sp<::android::IBinder> binder( |
| 2197 | sm->waitForService(::android::String16("package_native"))); |
David Drysdale | 3d2ba0a | 2023-01-11 13:27:26 +0000 | [diff] [blame] | 2198 | if (binder == nullptr) { |
Tommy Chiu | 6e5736b | 2023-02-08 10:16:03 +0800 | [diff] [blame] | 2199 | GTEST_LOG_(ERROR) << "waitForService package_native failed"; |
David Drysdale | 3d2ba0a | 2023-01-11 13:27:26 +0000 | [diff] [blame] | 2200 | return false; |
| 2201 | } |
| 2202 | ::android::sp<::android::content::pm::IPackageManagerNative> packageMgr = |
| 2203 | ::android::interface_cast<::android::content::pm::IPackageManagerNative>(binder); |
| 2204 | if (packageMgr == nullptr) { |
| 2205 | GTEST_LOG_(ERROR) << "Cannot find package manager"; |
| 2206 | return false; |
| 2207 | } |
| 2208 | bool hasFeature = false; |
| 2209 | auto status = packageMgr->hasSystemFeature(::android::String16(name.c_str()), 0, &hasFeature); |
| 2210 | if (!status.isOk()) { |
| 2211 | GTEST_LOG_(ERROR) << "hasSystemFeature('" << name << "') failed: " << status; |
| 2212 | return false; |
| 2213 | } |
| 2214 | return hasFeature; |
| 2215 | } |
| 2216 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 2217 | } // namespace test |
Shawn Willden | 08a7e43 | 2020-12-11 13:05:27 +0000 | [diff] [blame] | 2218 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 2219 | } // namespace aidl::android::hardware::security::keymint |