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; |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 47 | using ::testing::MatchesRegex; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 48 | |
| 49 | ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) { |
| 50 | if (set.size() == 0) |
| 51 | os << "(Empty)" << ::std::endl; |
| 52 | else { |
| 53 | os << "\n"; |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 54 | for (auto& entry : set) os << entry << ::std::endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 55 | } |
| 56 | return os; |
| 57 | } |
| 58 | |
| 59 | namespace test { |
| 60 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 61 | namespace { |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 62 | typedef KeyMintAidlTestBase::KeyData KeyData; |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 63 | // Predicate for testing basic characteristics validity in generation or import. |
| 64 | bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel, |
| 65 | const vector<KeyCharacteristics>& key_characteristics) { |
| 66 | if (key_characteristics.empty()) return false; |
| 67 | |
| 68 | std::unordered_set<SecurityLevel> levels_seen; |
| 69 | for (auto& entry : key_characteristics) { |
| 70 | if (entry.authorizations.empty()) return false; |
| 71 | |
Qi Wu | beefae4 | 2021-01-28 23:16:37 +0800 | [diff] [blame] | 72 | // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this. |
| 73 | if (entry.securityLevel == SecurityLevel::KEYSTORE) continue; |
| 74 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 75 | if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false; |
| 76 | levels_seen.insert(entry.securityLevel); |
| 77 | |
| 78 | // Generally, we should only have one entry, at the same security level as the KM |
| 79 | // instance. There is an exception: StrongBox KM can have some authorizations that are |
| 80 | // enforced by the TEE. |
| 81 | bool isExpectedSecurityLevel = secLevel == entry.securityLevel || |
| 82 | (secLevel == SecurityLevel::STRONGBOX && |
| 83 | entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT); |
| 84 | |
| 85 | if (!isExpectedSecurityLevel) return false; |
| 86 | } |
| 87 | return true; |
| 88 | } |
| 89 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 90 | // Extract attestation record from cert. Returned object is still part of cert; don't free it |
| 91 | // separately. |
| 92 | ASN1_OCTET_STRING* get_attestation_record(X509* certificate) { |
| 93 | ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */)); |
| 94 | EXPECT_TRUE(!!oid.get()); |
| 95 | if (!oid.get()) return nullptr; |
| 96 | |
| 97 | int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */); |
| 98 | EXPECT_NE(-1, location) << "Attestation extension not found in certificate"; |
| 99 | if (location == -1) return nullptr; |
| 100 | |
| 101 | X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location); |
| 102 | EXPECT_TRUE(!!attest_rec_ext) |
| 103 | << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug."; |
| 104 | if (!attest_rec_ext) return nullptr; |
| 105 | |
| 106 | ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext); |
| 107 | EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data"; |
| 108 | return attest_rec; |
| 109 | } |
| 110 | |
| 111 | bool avb_verification_enabled() { |
| 112 | char value[PROPERTY_VALUE_MAX]; |
| 113 | return property_get("ro.boot.vbmeta.device_state", value, "") != 0; |
| 114 | } |
| 115 | |
| 116 | char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', |
| 117 | '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; |
| 118 | |
| 119 | // Attestations don't contain everything in key authorization lists, so we need to filter the key |
| 120 | // lists to produce the lists that we expect to match the attestations. |
| 121 | auto kTagsToFilter = { |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 122 | Tag::CREATION_DATETIME, // |
| 123 | Tag::EC_CURVE, |
| 124 | Tag::HARDWARE_TYPE, |
| 125 | Tag::INCLUDE_UNIQUE_ID, |
| 126 | }; |
| 127 | |
| 128 | AuthorizationSet filtered_tags(const AuthorizationSet& set) { |
| 129 | AuthorizationSet filtered; |
| 130 | std::remove_copy_if( |
| 131 | set.begin(), set.end(), std::back_inserter(filtered), [](const auto& entry) -> bool { |
| 132 | return std::find(kTagsToFilter.begin(), kTagsToFilter.end(), entry.tag) != |
| 133 | kTagsToFilter.end(); |
| 134 | }); |
| 135 | return filtered; |
| 136 | } |
| 137 | |
| 138 | string x509NameToStr(X509_NAME* name) { |
| 139 | char* s = X509_NAME_oneline(name, nullptr, 0); |
| 140 | string retval(s); |
| 141 | OPENSSL_free(s); |
| 142 | return retval; |
| 143 | } |
| 144 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 145 | } // namespace |
| 146 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 147 | bool KeyMintAidlTestBase::arm_deleteAllKeys = false; |
| 148 | bool KeyMintAidlTestBase::dump_Attestations = false; |
| 149 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 150 | ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 151 | if (result.isOk()) return ErrorCode::OK; |
| 152 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 153 | if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) { |
| 154 | return static_cast<ErrorCode>(result.getServiceSpecificError()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 155 | } |
| 156 | |
| 157 | return ErrorCode::UNKNOWN_ERROR; |
| 158 | } |
| 159 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 160 | void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 161 | ASSERT_NE(keyMint, nullptr); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 162 | keymint_ = std::move(keyMint); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 163 | |
| 164 | KeyMintHardwareInfo info; |
| 165 | ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk()); |
| 166 | |
| 167 | securityLevel_ = info.securityLevel; |
| 168 | name_.assign(info.keyMintName.begin(), info.keyMintName.end()); |
| 169 | author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end()); |
| 170 | |
| 171 | os_version_ = getOsVersion(); |
| 172 | os_patch_level_ = getOsPatchlevel(); |
| 173 | } |
| 174 | |
| 175 | void KeyMintAidlTestBase::SetUp() { |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 176 | if (AServiceManager_isDeclared(GetParam().c_str())) { |
| 177 | ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str())); |
| 178 | InitializeKeyMint(IKeyMintDevice::fromBinder(binder)); |
| 179 | } else { |
| 180 | InitializeKeyMint(nullptr); |
| 181 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 182 | } |
| 183 | |
| 184 | ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc, |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 185 | const optional<AttestationKey>& attest_key, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 186 | vector<uint8_t>* key_blob, |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 187 | vector<KeyCharacteristics>* key_characteristics, |
| 188 | vector<Certificate>* cert_chain) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 189 | EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug"; |
| 190 | EXPECT_NE(key_characteristics, nullptr) |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 191 | << "Previous characteristics not deleted before generating key. Test bug."; |
| 192 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 193 | KeyCreationResult creationResult; |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 194 | Status result = keymint_->generateKey(key_desc.vector_data(), attest_key, &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 195 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 196 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 197 | creationResult.keyCharacteristics); |
| 198 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 199 | *key_blob = std::move(creationResult.keyBlob); |
| 200 | *key_characteristics = std::move(creationResult.keyCharacteristics); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 201 | *cert_chain = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 202 | |
| 203 | auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM); |
| 204 | EXPECT_TRUE(algorithm); |
| 205 | if (algorithm && |
| 206 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 207 | EXPECT_GE(cert_chain->size(), 1); |
| 208 | if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) { |
| 209 | if (attest_key) { |
| 210 | EXPECT_EQ(cert_chain->size(), 1); |
| 211 | } else { |
| 212 | EXPECT_GT(cert_chain->size(), 1); |
| 213 | } |
| 214 | } |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 215 | } else { |
| 216 | // For symmetric keys there should be no certificates. |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 217 | EXPECT_EQ(cert_chain->size(), 0); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 218 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 219 | } |
| 220 | |
| 221 | return GetReturnErrorCode(result); |
| 222 | } |
| 223 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 224 | ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc, |
| 225 | const optional<AttestationKey>& attest_key) { |
| 226 | return GenerateKey(key_desc, attest_key, &key_blob_, &key_characteristics_, &cert_chain_); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 227 | } |
| 228 | |
| 229 | ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format, |
| 230 | const string& key_material, vector<uint8_t>* key_blob, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 231 | vector<KeyCharacteristics>* key_characteristics) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 232 | Status result; |
| 233 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 234 | cert_chain_.clear(); |
| 235 | key_characteristics->clear(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 236 | key_blob->clear(); |
| 237 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 238 | KeyCreationResult creationResult; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 239 | result = keymint_->importKey(key_desc.vector_data(), format, |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 240 | vector<uint8_t>(key_material.begin(), key_material.end()), |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 241 | {} /* attestationSigningKeyBlob */, &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 242 | |
| 243 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 244 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 245 | creationResult.keyCharacteristics); |
| 246 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 247 | |
| 248 | *key_blob = std::move(creationResult.keyBlob); |
| 249 | *key_characteristics = std::move(creationResult.keyCharacteristics); |
| 250 | cert_chain_ = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 251 | |
| 252 | auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM); |
| 253 | EXPECT_TRUE(algorithm); |
| 254 | if (algorithm && |
| 255 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
| 256 | EXPECT_GE(cert_chain_.size(), 1); |
| 257 | if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1); |
| 258 | } else { |
| 259 | // For symmetric keys there should be no certificates. |
| 260 | EXPECT_EQ(cert_chain_.size(), 0); |
| 261 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 262 | } |
| 263 | |
| 264 | return GetReturnErrorCode(result); |
| 265 | } |
| 266 | |
| 267 | ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format, |
| 268 | const string& key_material) { |
| 269 | return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_); |
| 270 | } |
| 271 | |
| 272 | ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key, |
| 273 | const AuthorizationSet& wrapping_key_desc, |
| 274 | string masking_key, |
| 275 | const AuthorizationSet& unwrapping_params) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 276 | EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key)); |
| 277 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 278 | key_characteristics_.clear(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 279 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 280 | KeyCreationResult creationResult; |
| 281 | Status result = keymint_->importWrappedKey( |
| 282 | vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_, |
| 283 | vector<uint8_t>(masking_key.begin(), masking_key.end()), |
| 284 | unwrapping_params.vector_data(), 0 /* passwordSid */, 0 /* biometricSid */, |
| 285 | &creationResult); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 286 | |
| 287 | if (result.isOk()) { |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 288 | EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(), |
| 289 | creationResult.keyCharacteristics); |
| 290 | EXPECT_GT(creationResult.keyBlob.size(), 0); |
| 291 | |
| 292 | key_blob_ = std::move(creationResult.keyBlob); |
| 293 | key_characteristics_ = std::move(creationResult.keyCharacteristics); |
| 294 | cert_chain_ = std::move(creationResult.certificateChain); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 295 | |
| 296 | AuthorizationSet allAuths; |
| 297 | for (auto& entry : key_characteristics_) { |
| 298 | allAuths.push_back(AuthorizationSet(entry.authorizations)); |
| 299 | } |
| 300 | auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM); |
| 301 | EXPECT_TRUE(algorithm); |
| 302 | if (algorithm && |
| 303 | (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) { |
| 304 | EXPECT_GE(cert_chain_.size(), 1); |
| 305 | } else { |
| 306 | // For symmetric keys there should be no certificates. |
| 307 | EXPECT_EQ(cert_chain_.size(), 0); |
| 308 | } |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 309 | } |
| 310 | |
| 311 | return GetReturnErrorCode(result); |
| 312 | } |
| 313 | |
| 314 | ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) { |
| 315 | Status result = keymint_->deleteKey(*key_blob); |
| 316 | if (!keep_key_blob) { |
| 317 | *key_blob = vector<uint8_t>(); |
| 318 | } |
| 319 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 320 | EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 321 | return GetReturnErrorCode(result); |
| 322 | } |
| 323 | |
| 324 | ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) { |
| 325 | return DeleteKey(&key_blob_, keep_key_blob); |
| 326 | } |
| 327 | |
| 328 | ErrorCode KeyMintAidlTestBase::DeleteAllKeys() { |
| 329 | Status result = keymint_->deleteAllKeys(); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 330 | EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 331 | return GetReturnErrorCode(result); |
| 332 | } |
| 333 | |
| 334 | void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) { |
| 335 | ErrorCode result = DeleteKey(key_blob, keep_key_blob); |
| 336 | EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl; |
| 337 | } |
| 338 | |
| 339 | void KeyMintAidlTestBase::CheckedDeleteKey() { |
| 340 | CheckedDeleteKey(&key_blob_); |
| 341 | } |
| 342 | |
| 343 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob, |
| 344 | const AuthorizationSet& in_params, |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 345 | AuthorizationSet* out_params, |
| 346 | std::shared_ptr<IKeyMintOperation>& op) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 347 | SCOPED_TRACE("Begin"); |
| 348 | Status result; |
| 349 | BeginResult out; |
David Drysdale | 56ba912 | 2021-04-19 19:10:47 +0100 | [diff] [blame] | 350 | 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] | 351 | |
| 352 | if (result.isOk()) { |
| 353 | *out_params = out.params; |
| 354 | challenge_ = out.challenge; |
| 355 | op = out.operation; |
| 356 | } |
| 357 | |
| 358 | return GetReturnErrorCode(result); |
| 359 | } |
| 360 | |
| 361 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob, |
| 362 | const AuthorizationSet& in_params, |
| 363 | AuthorizationSet* out_params) { |
| 364 | SCOPED_TRACE("Begin"); |
| 365 | Status result; |
| 366 | BeginResult out; |
| 367 | |
David Drysdale | 56ba912 | 2021-04-19 19:10:47 +0100 | [diff] [blame] | 368 | 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] | 369 | |
| 370 | if (result.isOk()) { |
| 371 | *out_params = out.params; |
| 372 | challenge_ = out.challenge; |
| 373 | op_ = out.operation; |
| 374 | } |
| 375 | |
| 376 | return GetReturnErrorCode(result); |
| 377 | } |
| 378 | |
| 379 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params, |
| 380 | AuthorizationSet* out_params) { |
| 381 | SCOPED_TRACE("Begin"); |
| 382 | EXPECT_EQ(nullptr, op_); |
| 383 | return Begin(purpose, key_blob_, in_params, out_params); |
| 384 | } |
| 385 | |
| 386 | ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) { |
| 387 | SCOPED_TRACE("Begin"); |
| 388 | AuthorizationSet out_params; |
| 389 | ErrorCode result = Begin(purpose, in_params, &out_params); |
| 390 | EXPECT_TRUE(out_params.empty()); |
| 391 | return result; |
| 392 | } |
| 393 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 394 | ErrorCode KeyMintAidlTestBase::UpdateAad(const string& input) { |
| 395 | return GetReturnErrorCode(op_->updateAad(vector<uint8_t>(input.begin(), input.end()), |
| 396 | {} /* hardwareAuthToken */, |
| 397 | {} /* verificationToken */)); |
| 398 | } |
| 399 | |
| 400 | ErrorCode KeyMintAidlTestBase::Update(const string& input, string* output) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 401 | SCOPED_TRACE("Update"); |
| 402 | |
| 403 | Status result; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 404 | if (!output) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 405 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 406 | std::vector<uint8_t> o_put; |
| 407 | result = op_->update(vector<uint8_t>(input.begin(), input.end()), {}, {}, &o_put); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 408 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 409 | if (result.isOk()) output->append(o_put.begin(), o_put.end()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 410 | |
| 411 | return GetReturnErrorCode(result); |
| 412 | } |
| 413 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 414 | ErrorCode KeyMintAidlTestBase::Finish(const string& input, const string& signature, |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 415 | string* output) { |
| 416 | SCOPED_TRACE("Finish"); |
| 417 | Status result; |
| 418 | |
| 419 | EXPECT_NE(op_, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 420 | if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 421 | |
| 422 | vector<uint8_t> oPut; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 423 | result = op_->finish(vector<uint8_t>(input.begin(), input.end()), |
| 424 | vector<uint8_t>(signature.begin(), signature.end()), {} /* authToken */, |
| 425 | {} /* timestampToken */, {} /* confirmationToken */, &oPut); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 426 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 427 | if (result.isOk()) output->append(oPut.begin(), oPut.end()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 428 | |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 429 | op_ = {}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 430 | return GetReturnErrorCode(result); |
| 431 | } |
| 432 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 433 | ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) { |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 434 | SCOPED_TRACE("Abort"); |
| 435 | |
| 436 | EXPECT_NE(op, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 437 | if (!op) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 438 | |
| 439 | Status retval = op->abort(); |
| 440 | EXPECT_TRUE(retval.isOk()); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 441 | return static_cast<ErrorCode>(retval.getServiceSpecificError()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 442 | } |
| 443 | |
| 444 | ErrorCode KeyMintAidlTestBase::Abort() { |
| 445 | SCOPED_TRACE("Abort"); |
| 446 | |
| 447 | EXPECT_NE(op_, nullptr); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 448 | if (!op_) return ErrorCode::UNEXPECTED_NULL_POINTER; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 449 | |
| 450 | Status retval = op_->abort(); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 451 | return static_cast<ErrorCode>(retval.getServiceSpecificError()); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 452 | } |
| 453 | |
| 454 | void KeyMintAidlTestBase::AbortIfNeeded() { |
| 455 | SCOPED_TRACE("AbortIfNeeded"); |
| 456 | if (op_) { |
| 457 | EXPECT_EQ(ErrorCode::OK, Abort()); |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 458 | op_.reset(); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 459 | } |
| 460 | } |
| 461 | |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 462 | auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation, |
| 463 | const string& message, const AuthorizationSet& in_params) |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 464 | -> std::tuple<ErrorCode, string> { |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 465 | AuthorizationSet begin_out_params; |
| 466 | ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 467 | if (result != ErrorCode::OK) return {result, {}}; |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 468 | |
| 469 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 470 | return {Finish(message, &output), output}; |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 471 | } |
| 472 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 473 | string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation, |
| 474 | const string& message, const AuthorizationSet& in_params, |
| 475 | AuthorizationSet* out_params) { |
| 476 | SCOPED_TRACE("ProcessMessage"); |
| 477 | AuthorizationSet begin_out_params; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 478 | ErrorCode result = Begin(operation, key_blob, in_params, out_params); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 479 | EXPECT_EQ(ErrorCode::OK, result); |
| 480 | if (result != ErrorCode::OK) { |
| 481 | return ""; |
| 482 | } |
| 483 | |
| 484 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 485 | EXPECT_EQ(ErrorCode::OK, Finish(message, &output)); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 486 | return output; |
| 487 | } |
| 488 | |
| 489 | string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message, |
| 490 | const AuthorizationSet& params) { |
| 491 | SCOPED_TRACE("SignMessage"); |
| 492 | AuthorizationSet out_params; |
| 493 | string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params); |
| 494 | EXPECT_TRUE(out_params.empty()); |
| 495 | return signature; |
| 496 | } |
| 497 | |
| 498 | string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) { |
| 499 | SCOPED_TRACE("SignMessage"); |
| 500 | return SignMessage(key_blob_, message, params); |
| 501 | } |
| 502 | |
| 503 | string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) { |
| 504 | SCOPED_TRACE("MacMessage"); |
| 505 | return SignMessage( |
| 506 | key_blob_, message, |
| 507 | AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length)); |
| 508 | } |
| 509 | |
| 510 | void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message, |
| 511 | Digest digest, const string& expected_mac) { |
| 512 | SCOPED_TRACE("CheckHmacTestVector"); |
| 513 | ASSERT_EQ(ErrorCode::OK, |
| 514 | ImportKey(AuthorizationSetBuilder() |
| 515 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 516 | .HmacKey(key.size() * 8) |
| 517 | .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8) |
| 518 | .Digest(digest), |
| 519 | KeyFormat::RAW, key)); |
| 520 | string signature = MacMessage(message, digest, expected_mac.size() * 8); |
| 521 | EXPECT_EQ(expected_mac, signature) |
| 522 | << "Test vector didn't match for key of size " << key.size() << " message of size " |
| 523 | << message.size() << " and digest " << digest; |
| 524 | CheckedDeleteKey(); |
| 525 | } |
| 526 | |
| 527 | void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce, |
| 528 | const string& message, |
| 529 | const string& expected_ciphertext) { |
| 530 | SCOPED_TRACE("CheckAesCtrTestVector"); |
| 531 | ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() |
| 532 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 533 | .AesEncryptionKey(key.size() * 8) |
| 534 | .BlockMode(BlockMode::CTR) |
| 535 | .Authorization(TAG_CALLER_NONCE) |
| 536 | .Padding(PaddingMode::NONE), |
| 537 | KeyFormat::RAW, key)); |
| 538 | |
| 539 | auto params = AuthorizationSetBuilder() |
| 540 | .Authorization(TAG_NONCE, nonce.data(), nonce.size()) |
| 541 | .BlockMode(BlockMode::CTR) |
| 542 | .Padding(PaddingMode::NONE); |
| 543 | AuthorizationSet out_params; |
| 544 | string ciphertext = EncryptMessage(key_blob_, message, params, &out_params); |
| 545 | EXPECT_EQ(expected_ciphertext, ciphertext); |
| 546 | } |
| 547 | |
| 548 | void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode, |
| 549 | PaddingMode padding_mode, const string& key, |
| 550 | const string& iv, const string& input, |
| 551 | const string& expected_output) { |
| 552 | auto authset = AuthorizationSetBuilder() |
| 553 | .TripleDesEncryptionKey(key.size() * 7) |
| 554 | .BlockMode(block_mode) |
| 555 | .Authorization(TAG_NO_AUTH_REQUIRED) |
| 556 | .Padding(padding_mode); |
| 557 | if (iv.size()) authset.Authorization(TAG_CALLER_NONCE); |
| 558 | ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key)); |
| 559 | ASSERT_GT(key_blob_.size(), 0U); |
| 560 | |
| 561 | auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode); |
| 562 | if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size()); |
| 563 | AuthorizationSet output_params; |
| 564 | string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params); |
| 565 | EXPECT_EQ(expected_output, output); |
| 566 | } |
| 567 | |
| 568 | void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message, |
| 569 | const string& signature, const AuthorizationSet& params) { |
| 570 | SCOPED_TRACE("VerifyMessage"); |
| 571 | AuthorizationSet begin_out_params; |
| 572 | ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params)); |
| 573 | |
| 574 | string output; |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 575 | EXPECT_EQ(ErrorCode::OK, Finish(message, signature, &output)); |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 576 | EXPECT_TRUE(output.empty()); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 577 | op_ = {}; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 578 | } |
| 579 | |
| 580 | void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature, |
| 581 | const AuthorizationSet& params) { |
| 582 | SCOPED_TRACE("VerifyMessage"); |
| 583 | VerifyMessage(key_blob_, message, signature, params); |
| 584 | } |
| 585 | |
| 586 | string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message, |
| 587 | const AuthorizationSet& in_params, |
| 588 | AuthorizationSet* out_params) { |
| 589 | SCOPED_TRACE("EncryptMessage"); |
| 590 | return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params); |
| 591 | } |
| 592 | |
| 593 | string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params, |
| 594 | AuthorizationSet* out_params) { |
| 595 | SCOPED_TRACE("EncryptMessage"); |
| 596 | return EncryptMessage(key_blob_, message, params, out_params); |
| 597 | } |
| 598 | |
| 599 | string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) { |
| 600 | SCOPED_TRACE("EncryptMessage"); |
| 601 | AuthorizationSet out_params; |
| 602 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 603 | EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params; |
| 604 | return ciphertext; |
| 605 | } |
| 606 | |
| 607 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 608 | PaddingMode padding) { |
| 609 | SCOPED_TRACE("EncryptMessage"); |
| 610 | auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding); |
| 611 | AuthorizationSet out_params; |
| 612 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 613 | EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params; |
| 614 | return ciphertext; |
| 615 | } |
| 616 | |
| 617 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 618 | PaddingMode padding, vector<uint8_t>* iv_out) { |
| 619 | SCOPED_TRACE("EncryptMessage"); |
| 620 | auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding); |
| 621 | AuthorizationSet out_params; |
| 622 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 623 | EXPECT_EQ(1U, out_params.size()); |
| 624 | auto ivVal = out_params.GetTagValue(TAG_NONCE); |
Janis Danisevskis | 5ba0933 | 2020-12-17 10:05:15 -0800 | [diff] [blame] | 625 | EXPECT_TRUE(ivVal); |
| 626 | if (ivVal) *iv_out = *ivVal; |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 627 | return ciphertext; |
| 628 | } |
| 629 | |
| 630 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 631 | PaddingMode padding, const vector<uint8_t>& iv_in) { |
| 632 | SCOPED_TRACE("EncryptMessage"); |
| 633 | auto params = AuthorizationSetBuilder() |
| 634 | .BlockMode(block_mode) |
| 635 | .Padding(padding) |
| 636 | .Authorization(TAG_NONCE, iv_in); |
| 637 | AuthorizationSet out_params; |
| 638 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 639 | return ciphertext; |
| 640 | } |
| 641 | |
| 642 | string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode, |
| 643 | PaddingMode padding, uint8_t mac_length_bits, |
| 644 | const vector<uint8_t>& iv_in) { |
| 645 | SCOPED_TRACE("EncryptMessage"); |
| 646 | auto params = AuthorizationSetBuilder() |
| 647 | .BlockMode(block_mode) |
| 648 | .Padding(padding) |
| 649 | .Authorization(TAG_MAC_LENGTH, mac_length_bits) |
| 650 | .Authorization(TAG_NONCE, iv_in); |
| 651 | AuthorizationSet out_params; |
| 652 | string ciphertext = EncryptMessage(message, params, &out_params); |
| 653 | return ciphertext; |
| 654 | } |
| 655 | |
| 656 | string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob, |
| 657 | const string& ciphertext, |
| 658 | const AuthorizationSet& params) { |
| 659 | SCOPED_TRACE("DecryptMessage"); |
| 660 | AuthorizationSet out_params; |
| 661 | string plaintext = |
| 662 | ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params); |
| 663 | EXPECT_TRUE(out_params.empty()); |
| 664 | return plaintext; |
| 665 | } |
| 666 | |
| 667 | string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, |
| 668 | const AuthorizationSet& params) { |
| 669 | SCOPED_TRACE("DecryptMessage"); |
| 670 | return DecryptMessage(key_blob_, ciphertext, params); |
| 671 | } |
| 672 | |
| 673 | string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode, |
| 674 | PaddingMode padding_mode, const vector<uint8_t>& iv) { |
| 675 | SCOPED_TRACE("DecryptMessage"); |
| 676 | auto params = AuthorizationSetBuilder() |
| 677 | .BlockMode(block_mode) |
| 678 | .Padding(padding_mode) |
| 679 | .Authorization(TAG_NONCE, iv); |
| 680 | return DecryptMessage(key_blob_, ciphertext, params); |
| 681 | } |
| 682 | |
| 683 | std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey( |
| 684 | const vector<uint8_t>& key_blob) { |
| 685 | std::pair<ErrorCode, vector<uint8_t>> retval; |
| 686 | vector<uint8_t> outKeyBlob; |
| 687 | Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob); |
| 688 | ErrorCode errorcode = GetReturnErrorCode(result); |
| 689 | retval = std::tie(errorcode, outKeyBlob); |
| 690 | |
| 691 | return retval; |
| 692 | } |
| 693 | vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) { |
| 694 | switch (algorithm) { |
| 695 | case Algorithm::RSA: |
| 696 | switch (SecLevel()) { |
| 697 | case SecurityLevel::SOFTWARE: |
| 698 | case SecurityLevel::TRUSTED_ENVIRONMENT: |
| 699 | return {2048, 3072, 4096}; |
| 700 | case SecurityLevel::STRONGBOX: |
| 701 | return {2048}; |
| 702 | default: |
| 703 | ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel()); |
| 704 | break; |
| 705 | } |
| 706 | break; |
| 707 | case Algorithm::EC: |
| 708 | switch (SecLevel()) { |
| 709 | case SecurityLevel::SOFTWARE: |
| 710 | case SecurityLevel::TRUSTED_ENVIRONMENT: |
| 711 | return {224, 256, 384, 521}; |
| 712 | case SecurityLevel::STRONGBOX: |
| 713 | return {256}; |
| 714 | default: |
| 715 | ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel()); |
| 716 | break; |
| 717 | } |
| 718 | break; |
| 719 | case Algorithm::AES: |
| 720 | return {128, 256}; |
| 721 | case Algorithm::TRIPLE_DES: |
| 722 | return {168}; |
| 723 | case Algorithm::HMAC: { |
| 724 | vector<uint32_t> retval((512 - 64) / 8 + 1); |
| 725 | uint32_t size = 64 - 8; |
| 726 | std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); }); |
| 727 | return retval; |
| 728 | } |
| 729 | default: |
| 730 | ADD_FAILURE() << "Invalid Algorithm: " << algorithm; |
| 731 | return {}; |
| 732 | } |
| 733 | ADD_FAILURE() << "Should be impossible to get here"; |
| 734 | return {}; |
| 735 | } |
| 736 | |
| 737 | vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) { |
| 738 | if (SecLevel() == SecurityLevel::STRONGBOX) { |
| 739 | switch (algorithm) { |
| 740 | case Algorithm::RSA: |
| 741 | return {3072, 4096}; |
| 742 | case Algorithm::EC: |
| 743 | return {224, 384, 521}; |
| 744 | case Algorithm::AES: |
| 745 | return {192}; |
| 746 | default: |
| 747 | return {}; |
| 748 | } |
| 749 | } |
| 750 | return {}; |
| 751 | } |
| 752 | |
| 753 | vector<EcCurve> KeyMintAidlTestBase::ValidCurves() { |
| 754 | if (securityLevel_ == SecurityLevel::STRONGBOX) { |
| 755 | return {EcCurve::P_256}; |
| 756 | } else { |
| 757 | return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}; |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() { |
| 762 | if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {}; |
| 763 | CHECK(SecLevel() == SecurityLevel::STRONGBOX); |
| 764 | return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521}; |
| 765 | } |
| 766 | |
| 767 | vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) { |
| 768 | switch (SecLevel()) { |
| 769 | case SecurityLevel::SOFTWARE: |
| 770 | case SecurityLevel::TRUSTED_ENVIRONMENT: |
| 771 | if (withNone) { |
| 772 | if (withMD5) |
| 773 | return {Digest::NONE, Digest::MD5, Digest::SHA1, |
| 774 | Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384, |
| 775 | Digest::SHA_2_512}; |
| 776 | else |
| 777 | return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224, |
| 778 | Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}; |
| 779 | } else { |
| 780 | if (withMD5) |
| 781 | return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224, |
| 782 | Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}; |
| 783 | else |
| 784 | return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384, |
| 785 | Digest::SHA_2_512}; |
| 786 | } |
| 787 | break; |
| 788 | case SecurityLevel::STRONGBOX: |
| 789 | if (withNone) |
| 790 | return {Digest::NONE, Digest::SHA_2_256}; |
| 791 | else |
| 792 | return {Digest::SHA_2_256}; |
| 793 | break; |
| 794 | default: |
| 795 | ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel()); |
| 796 | break; |
| 797 | } |
| 798 | ADD_FAILURE() << "Should be impossible to get here"; |
| 799 | return {}; |
| 800 | } |
| 801 | |
Shawn Willden | 7f42437 | 2021-01-10 18:06:50 -0700 | [diff] [blame] | 802 | static const vector<KeyParameter> kEmptyAuthList{}; |
| 803 | |
| 804 | const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations( |
| 805 | const vector<KeyCharacteristics>& key_characteristics) { |
| 806 | auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(), |
| 807 | [this](auto& entry) { return entry.securityLevel == SecLevel(); }); |
| 808 | return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations; |
| 809 | } |
| 810 | |
Qi Wu | beefae4 | 2021-01-28 23:16:37 +0800 | [diff] [blame] | 811 | const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations( |
| 812 | const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) { |
| 813 | auto found = std::find_if( |
| 814 | key_characteristics.begin(), key_characteristics.end(), |
| 815 | [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; }); |
Shawn Willden | 0e80b5d | 2020-12-17 09:07:27 -0700 | [diff] [blame] | 816 | return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations; |
| 817 | } |
| 818 | |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 819 | ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 820 | auto [result, ciphertext] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 821 | aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456", |
| 822 | AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)); |
| 823 | return result; |
| 824 | } |
| 825 | |
| 826 | ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 827 | auto [result, mac] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 828 | hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456", |
| 829 | AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256)); |
| 830 | return result; |
| 831 | } |
| 832 | |
| 833 | ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) { |
| 834 | std::string message(2048 / 8, 'a'); |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 835 | auto [result, signature] = ProcessMessage( |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 836 | rsaKeyBlob, KeyPurpose::SIGN, message, |
| 837 | AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)); |
| 838 | return result; |
| 839 | } |
| 840 | |
| 841 | ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) { |
Shawn Willden | 92d79c0 | 2021-02-19 07:31:55 -0700 | [diff] [blame] | 842 | auto [result, signature] = ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a", |
| 843 | AuthorizationSetBuilder().Digest(Digest::SHA_2_256)); |
Chirag Pathak | 9ea6a0a | 2021-02-01 23:54:27 +0000 | [diff] [blame] | 844 | return result; |
| 845 | } |
| 846 | |
Selene Huang | 6e46f14 | 2021-04-20 19:20:11 -0700 | [diff] [blame] | 847 | void verify_serial(X509* cert, const uint64_t expected_serial) { |
| 848 | BIGNUM_Ptr ser(BN_new()); |
| 849 | EXPECT_TRUE(ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), ser.get())); |
| 850 | |
| 851 | uint64_t serial; |
| 852 | EXPECT_TRUE(BN_get_u64(ser.get(), &serial)); |
| 853 | EXPECT_EQ(serial, expected_serial); |
| 854 | } |
| 855 | |
| 856 | // Please set self_signed to true for fake certificates or self signed |
| 857 | // certificates |
| 858 | void verify_subject(const X509* cert, // |
| 859 | const string& subject, // |
| 860 | bool self_signed) { |
| 861 | char* cert_issuer = // |
| 862 | X509_NAME_oneline(X509_get_issuer_name(cert), nullptr, 0); |
| 863 | |
| 864 | char* cert_subj = X509_NAME_oneline(X509_get_subject_name(cert), nullptr, 0); |
| 865 | |
| 866 | string expected_subject("/CN="); |
| 867 | if (subject.empty()) { |
| 868 | expected_subject.append("Android Keystore Key"); |
| 869 | } else { |
| 870 | expected_subject.append(subject); |
| 871 | } |
| 872 | |
| 873 | EXPECT_STREQ(expected_subject.c_str(), cert_subj) << "Cert has wrong subject." << cert_subj; |
| 874 | |
| 875 | if (self_signed) { |
| 876 | EXPECT_STREQ(cert_issuer, cert_subj) |
| 877 | << "Cert issuer and subject mismatch for self signed certificate."; |
| 878 | } |
| 879 | |
| 880 | OPENSSL_free(cert_subj); |
| 881 | OPENSSL_free(cert_issuer); |
| 882 | } |
| 883 | |
| 884 | vector<uint8_t> build_serial_blob(const uint64_t serial_int) { |
| 885 | BIGNUM_Ptr serial(BN_new()); |
| 886 | EXPECT_TRUE(BN_set_u64(serial.get(), serial_int)); |
| 887 | |
| 888 | int len = BN_num_bytes(serial.get()); |
| 889 | vector<uint8_t> serial_blob(len); |
| 890 | if (BN_bn2bin(serial.get(), serial_blob.data()) != len) { |
| 891 | return {}; |
| 892 | } |
| 893 | |
| 894 | return serial_blob; |
| 895 | } |
| 896 | |
| 897 | void verify_subject_and_serial(const Certificate& certificate, // |
| 898 | const uint64_t expected_serial, // |
| 899 | const string& subject, bool self_signed) { |
| 900 | X509_Ptr cert(parse_cert_blob(certificate.encodedCertificate)); |
| 901 | ASSERT_TRUE(!!cert.get()); |
| 902 | |
| 903 | verify_serial(cert.get(), expected_serial); |
| 904 | verify_subject(cert.get(), subject, self_signed); |
| 905 | } |
| 906 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 907 | bool verify_attestation_record(const string& challenge, // |
| 908 | const string& app_id, // |
| 909 | AuthorizationSet expected_sw_enforced, // |
| 910 | AuthorizationSet expected_hw_enforced, // |
| 911 | SecurityLevel security_level, |
| 912 | const vector<uint8_t>& attestation_cert) { |
| 913 | X509_Ptr cert(parse_cert_blob(attestation_cert)); |
| 914 | EXPECT_TRUE(!!cert.get()); |
| 915 | if (!cert.get()) return false; |
| 916 | |
| 917 | ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get()); |
| 918 | EXPECT_TRUE(!!attest_rec); |
| 919 | if (!attest_rec) return false; |
| 920 | |
| 921 | AuthorizationSet att_sw_enforced; |
| 922 | AuthorizationSet att_hw_enforced; |
| 923 | uint32_t att_attestation_version; |
| 924 | uint32_t att_keymaster_version; |
| 925 | SecurityLevel att_attestation_security_level; |
| 926 | SecurityLevel att_keymaster_security_level; |
| 927 | vector<uint8_t> att_challenge; |
| 928 | vector<uint8_t> att_unique_id; |
| 929 | vector<uint8_t> att_app_id; |
| 930 | |
| 931 | auto error = parse_attestation_record(attest_rec->data, // |
| 932 | attest_rec->length, // |
| 933 | &att_attestation_version, // |
| 934 | &att_attestation_security_level, // |
| 935 | &att_keymaster_version, // |
| 936 | &att_keymaster_security_level, // |
| 937 | &att_challenge, // |
| 938 | &att_sw_enforced, // |
| 939 | &att_hw_enforced, // |
| 940 | &att_unique_id); |
| 941 | EXPECT_EQ(ErrorCode::OK, error); |
| 942 | if (error != ErrorCode::OK) return false; |
| 943 | |
Shawn Willden | 3cb64a6 | 2021-04-05 14:39:05 -0600 | [diff] [blame] | 944 | EXPECT_EQ(att_attestation_version, 100U); |
Selene Huang | 4f64c22 | 2021-04-13 19:54:36 -0700 | [diff] [blame] | 945 | vector<uint8_t> appId(app_id.begin(), app_id.end()); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 946 | |
Selene Huang | 4f64c22 | 2021-04-13 19:54:36 -0700 | [diff] [blame] | 947 | // check challenge and app id only if we expects a non-fake certificate |
| 948 | if (challenge.length() > 0) { |
| 949 | EXPECT_EQ(challenge.length(), att_challenge.size()); |
| 950 | EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length())); |
| 951 | |
| 952 | expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, appId); |
| 953 | } |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 954 | |
Shawn Willden | 3cb64a6 | 2021-04-05 14:39:05 -0600 | [diff] [blame] | 955 | EXPECT_EQ(att_keymaster_version, 100U); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 956 | EXPECT_EQ(security_level, att_keymaster_security_level); |
| 957 | EXPECT_EQ(security_level, att_attestation_security_level); |
| 958 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 959 | |
| 960 | char property_value[PROPERTY_VALUE_MAX] = {}; |
| 961 | // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed |
| 962 | // keymaster implementation will report YYYYMM dates instead of YYYYMMDD |
| 963 | // for the BOOT_PATCH_LEVEL. |
| 964 | if (avb_verification_enabled()) { |
| 965 | for (int i = 0; i < att_hw_enforced.size(); i++) { |
| 966 | if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL || |
| 967 | att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) { |
| 968 | std::string date = |
Tommy Chiu | f00d8f1 | 2021-04-08 11:07:48 +0800 | [diff] [blame] | 969 | std::to_string(att_hw_enforced[i].value.get<KeyParameterValue::integer>()); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 970 | // strptime seems to require delimiters, but the tag value will |
| 971 | // be YYYYMMDD |
| 972 | date.insert(6, "-"); |
| 973 | date.insert(4, "-"); |
| 974 | EXPECT_EQ(date.size(), 10); |
| 975 | struct tm time; |
| 976 | strptime(date.c_str(), "%Y-%m-%d", &time); |
| 977 | |
| 978 | // Day of the month (0-31) |
| 979 | EXPECT_GE(time.tm_mday, 0); |
| 980 | EXPECT_LT(time.tm_mday, 32); |
| 981 | // Months since Jan (0-11) |
| 982 | EXPECT_GE(time.tm_mon, 0); |
| 983 | EXPECT_LT(time.tm_mon, 12); |
| 984 | // Years since 1900 |
| 985 | EXPECT_GT(time.tm_year, 110); |
| 986 | EXPECT_LT(time.tm_year, 200); |
| 987 | } |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | // Check to make sure boolean values are properly encoded. Presence of a boolean tag |
| 992 | // indicates true. A provided boolean tag that can be pulled back out of the certificate |
| 993 | // indicates correct encoding. No need to check if it's in both lists, since the |
| 994 | // AuthorizationSet compare below will handle mismatches of tags. |
| 995 | if (security_level == SecurityLevel::SOFTWARE) { |
| 996 | EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED)); |
| 997 | } else { |
| 998 | EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED)); |
| 999 | } |
| 1000 | |
| 1001 | // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in |
| 1002 | // the authorization list during key generation) isn't being attested to in the certificate. |
| 1003 | EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED)); |
| 1004 | EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED)); |
| 1005 | EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED)); |
| 1006 | EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED)); |
| 1007 | |
| 1008 | if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) { |
| 1009 | // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be. |
| 1010 | EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) || |
| 1011 | att_hw_enforced.Contains(TAG_KEY_SIZE)); |
| 1012 | } |
| 1013 | |
| 1014 | // Test root of trust elements |
| 1015 | vector<uint8_t> verified_boot_key; |
| 1016 | VerifiedBoot verified_boot_state; |
| 1017 | bool device_locked; |
| 1018 | vector<uint8_t> verified_boot_hash; |
| 1019 | error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key, |
| 1020 | &verified_boot_state, &device_locked, &verified_boot_hash); |
| 1021 | EXPECT_EQ(ErrorCode::OK, error); |
| 1022 | |
| 1023 | if (avb_verification_enabled()) { |
| 1024 | EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0); |
| 1025 | string prop_string(property_value); |
| 1026 | EXPECT_EQ(prop_string.size(), 64); |
| 1027 | EXPECT_EQ(prop_string, bin2hex(verified_boot_hash)); |
| 1028 | |
| 1029 | EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0); |
| 1030 | if (!strcmp(property_value, "unlocked")) { |
| 1031 | EXPECT_FALSE(device_locked); |
| 1032 | } else { |
| 1033 | EXPECT_TRUE(device_locked); |
| 1034 | } |
| 1035 | |
| 1036 | // Check that the device is locked if not debuggable, e.g., user build |
| 1037 | // images in CTS. For VTS, debuggable images are used to allow adb root |
| 1038 | // and the device is unlocked. |
| 1039 | if (!property_get_bool("ro.debuggable", false)) { |
| 1040 | EXPECT_TRUE(device_locked); |
| 1041 | } else { |
| 1042 | EXPECT_FALSE(device_locked); |
| 1043 | } |
| 1044 | } |
| 1045 | |
| 1046 | // Verified boot key should be all 0's if the boot state is not verified or self signed |
| 1047 | std::string empty_boot_key(32, '\0'); |
| 1048 | std::string verified_boot_key_str((const char*)verified_boot_key.data(), |
| 1049 | verified_boot_key.size()); |
| 1050 | EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0); |
| 1051 | if (!strcmp(property_value, "green")) { |
| 1052 | EXPECT_EQ(verified_boot_state, VerifiedBoot::VERIFIED); |
| 1053 | EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1054 | verified_boot_key.size())); |
| 1055 | } else if (!strcmp(property_value, "yellow")) { |
| 1056 | EXPECT_EQ(verified_boot_state, VerifiedBoot::SELF_SIGNED); |
| 1057 | EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1058 | verified_boot_key.size())); |
| 1059 | } else if (!strcmp(property_value, "orange")) { |
| 1060 | EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED); |
| 1061 | EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1062 | verified_boot_key.size())); |
| 1063 | } else if (!strcmp(property_value, "red")) { |
| 1064 | EXPECT_EQ(verified_boot_state, VerifiedBoot::FAILED); |
| 1065 | } else { |
| 1066 | EXPECT_EQ(verified_boot_state, VerifiedBoot::UNVERIFIED); |
| 1067 | EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(), |
| 1068 | verified_boot_key.size())); |
| 1069 | } |
| 1070 | |
| 1071 | att_sw_enforced.Sort(); |
| 1072 | expected_sw_enforced.Sort(); |
| 1073 | auto a = filtered_tags(expected_sw_enforced); |
| 1074 | auto b = filtered_tags(att_sw_enforced); |
| 1075 | EXPECT_EQ(a, b); |
| 1076 | |
| 1077 | att_hw_enforced.Sort(); |
| 1078 | expected_hw_enforced.Sort(); |
| 1079 | EXPECT_EQ(filtered_tags(expected_hw_enforced), filtered_tags(att_hw_enforced)); |
| 1080 | |
| 1081 | return true; |
| 1082 | } |
| 1083 | |
| 1084 | string bin2hex(const vector<uint8_t>& data) { |
| 1085 | string retval; |
| 1086 | retval.reserve(data.size() * 2 + 1); |
| 1087 | for (uint8_t byte : data) { |
| 1088 | retval.push_back(nibble2hex[0x0F & (byte >> 4)]); |
| 1089 | retval.push_back(nibble2hex[0x0F & byte]); |
| 1090 | } |
| 1091 | return retval; |
| 1092 | } |
| 1093 | |
David Drysdale | f0d516d | 2021-03-22 07:51:43 +0000 | [diff] [blame] | 1094 | AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) { |
| 1095 | AuthorizationSet authList; |
| 1096 | for (auto& entry : key_characteristics) { |
| 1097 | if (entry.securityLevel == SecurityLevel::STRONGBOX || |
| 1098 | entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) { |
| 1099 | authList.push_back(AuthorizationSet(entry.authorizations)); |
| 1100 | } |
| 1101 | } |
| 1102 | return authList; |
| 1103 | } |
| 1104 | |
| 1105 | AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics) { |
| 1106 | AuthorizationSet authList; |
| 1107 | for (auto& entry : key_characteristics) { |
| 1108 | if (entry.securityLevel == SecurityLevel::SOFTWARE || |
| 1109 | entry.securityLevel == SecurityLevel::KEYSTORE) { |
| 1110 | authList.push_back(AuthorizationSet(entry.authorizations)); |
| 1111 | } |
| 1112 | } |
| 1113 | return authList; |
| 1114 | } |
| 1115 | |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1116 | AssertionResult ChainSignaturesAreValid(const vector<Certificate>& chain) { |
| 1117 | std::stringstream cert_data; |
| 1118 | |
| 1119 | for (size_t i = 0; i < chain.size(); ++i) { |
| 1120 | cert_data << bin2hex(chain[i].encodedCertificate) << std::endl; |
| 1121 | |
| 1122 | X509_Ptr key_cert(parse_cert_blob(chain[i].encodedCertificate)); |
| 1123 | X509_Ptr signing_cert; |
| 1124 | if (i < chain.size() - 1) { |
| 1125 | signing_cert = parse_cert_blob(chain[i + 1].encodedCertificate); |
| 1126 | } else { |
| 1127 | signing_cert = parse_cert_blob(chain[i].encodedCertificate); |
| 1128 | } |
| 1129 | if (!key_cert.get() || !signing_cert.get()) return AssertionFailure() << cert_data.str(); |
| 1130 | |
| 1131 | EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get())); |
| 1132 | if (!signing_pubkey.get()) return AssertionFailure() << cert_data.str(); |
| 1133 | |
| 1134 | if (!X509_verify(key_cert.get(), signing_pubkey.get())) { |
| 1135 | return AssertionFailure() |
| 1136 | << "Verification of certificate " << i << " failed " |
| 1137 | << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL) << '\n' |
| 1138 | << cert_data.str(); |
| 1139 | } |
| 1140 | |
| 1141 | string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get())); |
| 1142 | string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get())); |
| 1143 | if (cert_issuer != signer_subj) { |
Selene Huang | 8f9494c | 2021-04-21 15:10:36 -0700 | [diff] [blame] | 1144 | return AssertionFailure() << "Cert " << i << " has wrong issuer.\n" |
| 1145 | << " Signer subject is " << signer_subj |
| 1146 | << " Issuer subject is " << cert_issuer << endl |
| 1147 | << cert_data.str(); |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1148 | } |
Shawn Willden | 7c13039 | 2020-12-21 09:58:22 -0700 | [diff] [blame] | 1149 | } |
| 1150 | |
| 1151 | if (KeyMintAidlTestBase::dump_Attestations) std::cout << cert_data.str(); |
| 1152 | return AssertionSuccess(); |
| 1153 | } |
| 1154 | |
| 1155 | X509_Ptr parse_cert_blob(const vector<uint8_t>& blob) { |
| 1156 | const uint8_t* p = blob.data(); |
| 1157 | return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size())); |
| 1158 | } |
| 1159 | |
David Drysdale | f0d516d | 2021-03-22 07:51:43 +0000 | [diff] [blame] | 1160 | vector<uint8_t> make_name_from_str(const string& name) { |
| 1161 | X509_NAME_Ptr x509_name(X509_NAME_new()); |
| 1162 | EXPECT_TRUE(x509_name.get() != nullptr); |
| 1163 | if (!x509_name) return {}; |
| 1164 | |
| 1165 | EXPECT_EQ(1, X509_NAME_add_entry_by_txt(x509_name.get(), // |
| 1166 | "CN", // |
| 1167 | MBSTRING_ASC, |
| 1168 | reinterpret_cast<const uint8_t*>(name.c_str()), |
| 1169 | -1, // len |
| 1170 | -1, // loc |
| 1171 | 0 /* set */)); |
| 1172 | |
| 1173 | int len = i2d_X509_NAME(x509_name.get(), nullptr /* only return length */); |
| 1174 | EXPECT_GT(len, 0); |
| 1175 | |
| 1176 | vector<uint8_t> retval(len); |
| 1177 | uint8_t* p = retval.data(); |
| 1178 | i2d_X509_NAME(x509_name.get(), &p); |
| 1179 | |
| 1180 | return retval; |
| 1181 | } |
| 1182 | |
David Drysdale | 4dc0107 | 2021-04-01 12:17:35 +0100 | [diff] [blame] | 1183 | namespace { |
| 1184 | |
| 1185 | void check_cose_key(const vector<uint8_t>& data, bool testMode) { |
| 1186 | auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data); |
| 1187 | ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr; |
| 1188 | |
| 1189 | // The following check assumes that canonical CBOR encoding is used for the COSE_Key. |
| 1190 | if (testMode) { |
| 1191 | EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()), |
| 1192 | MatchesRegex("{\n" |
| 1193 | " 1 : 2,\n" // kty: EC2 |
| 1194 | " 3 : -7,\n" // alg: ES256 |
| 1195 | " -1 : 1,\n" // EC id: P256 |
| 1196 | // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a |
| 1197 | // sequence of 32 hexadecimal bytes, enclosed in braces and |
| 1198 | // separated by commas. In this case, some Ed25519 public key. |
| 1199 | " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data |
| 1200 | " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data |
| 1201 | " -70000 : null,\n" // test marker |
| 1202 | "}")); |
| 1203 | } else { |
| 1204 | EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()), |
| 1205 | MatchesRegex("{\n" |
| 1206 | " 1 : 2,\n" // kty: EC2 |
| 1207 | " 3 : -7,\n" // alg: ES256 |
| 1208 | " -1 : 1,\n" // EC id: P256 |
| 1209 | // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a |
| 1210 | // sequence of 32 hexadecimal bytes, enclosed in braces and |
| 1211 | // separated by commas. In this case, some Ed25519 public key. |
| 1212 | " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data |
| 1213 | " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data |
| 1214 | "}")); |
| 1215 | } |
| 1216 | } |
| 1217 | |
| 1218 | } // namespace |
| 1219 | |
| 1220 | void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode, |
| 1221 | vector<uint8_t>* payload_value) { |
| 1222 | auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey); |
| 1223 | ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr; |
| 1224 | |
| 1225 | ASSERT_NE(coseMac0->asArray(), nullptr); |
| 1226 | ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount); |
| 1227 | |
| 1228 | auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr(); |
| 1229 | ASSERT_NE(protParms, nullptr); |
| 1230 | |
| 1231 | // Header label:value of 'alg': HMAC-256 |
| 1232 | ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}"); |
| 1233 | |
| 1234 | auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap(); |
| 1235 | ASSERT_NE(unprotParms, nullptr); |
| 1236 | ASSERT_EQ(unprotParms->size(), 0); |
| 1237 | |
| 1238 | // The payload is a bstr holding an encoded COSE_Key |
| 1239 | auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr(); |
| 1240 | ASSERT_NE(payload, nullptr); |
| 1241 | check_cose_key(payload->value(), testMode); |
| 1242 | |
| 1243 | auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr(); |
| 1244 | ASSERT_TRUE(coseMac0Tag); |
| 1245 | auto extractedTag = coseMac0Tag->value(); |
| 1246 | EXPECT_EQ(extractedTag.size(), 32U); |
| 1247 | |
| 1248 | // Compare with tag generated with kTestMacKey. Should only match in test mode |
| 1249 | auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */, |
| 1250 | payload->value()); |
| 1251 | ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message(); |
| 1252 | |
| 1253 | if (testMode) { |
| 1254 | EXPECT_EQ(*testTag, extractedTag); |
| 1255 | } else { |
| 1256 | EXPECT_NE(*testTag, extractedTag); |
| 1257 | } |
| 1258 | if (payload_value != nullptr) { |
| 1259 | *payload_value = payload->value(); |
| 1260 | } |
| 1261 | } |
| 1262 | |
| 1263 | void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) { |
| 1264 | // Extract x and y affine coordinates from the encoded Cose_Key. |
| 1265 | auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData); |
| 1266 | ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr; |
| 1267 | auto coseKey = parsedPayload->asMap(); |
| 1268 | const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X); |
| 1269 | ASSERT_NE(xItem->asBstr(), nullptr); |
| 1270 | vector<uint8_t> x = xItem->asBstr()->value(); |
| 1271 | const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y); |
| 1272 | ASSERT_NE(yItem->asBstr(), nullptr); |
| 1273 | vector<uint8_t> y = yItem->asBstr()->value(); |
| 1274 | |
| 1275 | // Concatenate: 0x04 (uncompressed form marker) | x | y |
| 1276 | vector<uint8_t> pubKeyData{0x04}; |
| 1277 | pubKeyData.insert(pubKeyData.end(), x.begin(), x.end()); |
| 1278 | pubKeyData.insert(pubKeyData.end(), y.begin(), y.end()); |
| 1279 | |
| 1280 | EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new()); |
| 1281 | ASSERT_NE(ecKey, nullptr); |
| 1282 | EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); |
| 1283 | ASSERT_NE(group, nullptr); |
| 1284 | ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1); |
| 1285 | EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get())); |
| 1286 | ASSERT_NE(point, nullptr); |
| 1287 | ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(), |
| 1288 | nullptr), |
| 1289 | 1); |
| 1290 | ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1); |
| 1291 | |
| 1292 | EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new()); |
| 1293 | ASSERT_NE(pubKey, nullptr); |
| 1294 | EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release()); |
| 1295 | *signingKey = std::move(pubKey); |
| 1296 | } |
| 1297 | |
Selene Huang | 31ab404 | 2020-04-29 04:22:39 -0700 | [diff] [blame] | 1298 | } // namespace test |
Shawn Willden | 08a7e43 | 2020-12-11 13:05:27 +0000 | [diff] [blame] | 1299 | |
Janis Danisevskis | 24c0470 | 2020-12-16 18:28:39 -0800 | [diff] [blame] | 1300 | } // namespace aidl::android::hardware::security::keymint |