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