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