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