1/* 2 * Copyright (C) 2016 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#define LOG_TAG "keymaster_hidl_hal_test" 18#include <cutils/log.h> 19 20#include <iostream> 21 22#include <openssl/evp.h> 23#include <openssl/x509.h> 24 25#include <android/hardware/keymaster/3.0/IKeymasterDevice.h> 26#include <android/hardware/keymaster/3.0/types.h> 27 28#include <cutils/properties.h> 29 30#include <keymaster/keymaster_configuration.h> 31 32#include "authorization_set.h" 33#include "key_param_output.h" 34 35#include <VtsHalHidlTargetTestBase.h> 36 37#include "attestation_record.h" 38#include "openssl_utils.h" 39 40using ::android::sp; 41 42using ::std::string; 43 44// This service_name will be passed to getService when retrieving the keymaster service to test. To 45// change it from "default" specify the selected service name on the command line. The first 46// non-gtest argument will be used as the service name. 47string service_name = "default"; 48 49static bool arm_deleteAllKeys = false; 50static bool dump_Attestations = false; 51 52namespace android { 53namespace hardware { 54 55template <typename T> bool operator==(const hidl_vec<T>& a, const hidl_vec<T>& b) { 56 if (a.size() != b.size()) { 57 return false; 58 } 59 for (size_t i = 0; i < a.size(); ++i) { 60 if (a[i] != b[i]) { 61 return false; 62 } 63 } 64 return true; 65} 66 67namespace keymaster { 68namespace V3_0 { 69 70bool operator==(const KeyParameter& a, const KeyParameter& b) { 71 if (a.tag != b.tag) { 72 return false; 73 } 74 75 switch (a.tag) { 76 77 /* Boolean tags */ 78 case Tag::INVALID: 79 case Tag::CALLER_NONCE: 80 case Tag::INCLUDE_UNIQUE_ID: 81 case Tag::ECIES_SINGLE_HASH_MODE: 82 case Tag::BOOTLOADER_ONLY: 83 case Tag::NO_AUTH_REQUIRED: 84 case Tag::ALLOW_WHILE_ON_BODY: 85 case Tag::EXPORTABLE: 86 case Tag::ALL_APPLICATIONS: 87 case Tag::ROLLBACK_RESISTANT: 88 case Tag::RESET_SINCE_ID_ROTATION: 89 return true; 90 91 /* Integer tags */ 92 case Tag::KEY_SIZE: 93 case Tag::MIN_MAC_LENGTH: 94 case Tag::MIN_SECONDS_BETWEEN_OPS: 95 case Tag::MAX_USES_PER_BOOT: 96 case Tag::ALL_USERS: 97 case Tag::USER_ID: 98 case Tag::OS_VERSION: 99 case Tag::OS_PATCHLEVEL: 100 case Tag::MAC_LENGTH: 101 case Tag::AUTH_TIMEOUT: 102 return a.f.integer == b.f.integer; 103 104 /* Long integer tags */ 105 case Tag::RSA_PUBLIC_EXPONENT: 106 case Tag::USER_SECURE_ID: 107 return a.f.longInteger == b.f.longInteger; 108 109 /* Date-time tags */ 110 case Tag::ACTIVE_DATETIME: 111 case Tag::ORIGINATION_EXPIRE_DATETIME: 112 case Tag::USAGE_EXPIRE_DATETIME: 113 case Tag::CREATION_DATETIME: 114 return a.f.dateTime == b.f.dateTime; 115 116 /* Bytes tags */ 117 case Tag::APPLICATION_ID: 118 case Tag::APPLICATION_DATA: 119 case Tag::ROOT_OF_TRUST: 120 case Tag::UNIQUE_ID: 121 case Tag::ATTESTATION_CHALLENGE: 122 case Tag::ATTESTATION_APPLICATION_ID: 123 case Tag::ATTESTATION_ID_BRAND: 124 case Tag::ATTESTATION_ID_DEVICE: 125 case Tag::ATTESTATION_ID_PRODUCT: 126 case Tag::ATTESTATION_ID_SERIAL: 127 case Tag::ATTESTATION_ID_IMEI: 128 case Tag::ATTESTATION_ID_MEID: 129 case Tag::ATTESTATION_ID_MANUFACTURER: 130 case Tag::ATTESTATION_ID_MODEL: 131 case Tag::ASSOCIATED_DATA: 132 case Tag::NONCE: 133 case Tag::AUTH_TOKEN: 134 return a.blob == b.blob; 135 136 /* Enum tags */ 137 case Tag::PURPOSE: 138 return a.f.purpose == b.f.purpose; 139 case Tag::ALGORITHM: 140 return a.f.algorithm == b.f.algorithm; 141 case Tag::BLOCK_MODE: 142 return a.f.blockMode == b.f.blockMode; 143 case Tag::DIGEST: 144 return a.f.digest == b.f.digest; 145 case Tag::PADDING: 146 return a.f.paddingMode == b.f.paddingMode; 147 case Tag::EC_CURVE: 148 return a.f.ecCurve == b.f.ecCurve; 149 case Tag::BLOB_USAGE_REQUIREMENTS: 150 return a.f.keyBlobUsageRequirements == b.f.keyBlobUsageRequirements; 151 case Tag::USER_AUTH_TYPE: 152 return a.f.integer == b.f.integer; 153 case Tag::ORIGIN: 154 return a.f.origin == b.f.origin; 155 156 /* Unsupported tags */ 157 case Tag::KDF: 158 return false; 159 } 160} 161 162bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) { 163 return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin()); 164} 165 166bool operator==(const KeyCharacteristics& a, const KeyCharacteristics& b) { 167 // This isn't very efficient. Oh, well. 168 AuthorizationSet a_sw(a.softwareEnforced); 169 AuthorizationSet b_sw(b.softwareEnforced); 170 AuthorizationSet a_tee(b.teeEnforced); 171 AuthorizationSet b_tee(b.teeEnforced); 172 173 a_sw.Sort(); 174 b_sw.Sort(); 175 a_tee.Sort(); 176 b_tee.Sort(); 177 178 return a_sw == b_sw && a_tee == b_sw; 179} 180 181::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) { 182 if (set.size() == 0) 183 os << "(Empty)" << ::std::endl; 184 else { 185 os << "\n"; 186 for (size_t i = 0; i < set.size(); ++i) 187 os << set[i] << ::std::endl; 188 } 189 return os; 190} 191 192namespace test { 193namespace { 194 195template <TagType tag_type, Tag tag, typename ValueT> 196bool contains(hidl_vec<KeyParameter>& set, TypedTag<tag_type, tag> ttag, ValueT expected_value) { 197 size_t count = std::count_if(set.begin(), set.end(), [&](const KeyParameter& param) { 198 return param.tag == tag && accessTagValue(ttag, param) == expected_value; 199 }); 200 return count == 1; 201} 202 203template <TagType tag_type, Tag tag> 204bool contains(hidl_vec<KeyParameter>& set, TypedTag<tag_type, tag>) { 205 size_t count = std::count_if(set.begin(), set.end(), 206 [&](const KeyParameter& param) { return param.tag == tag; }); 207 return count > 0; 208} 209 210constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 211 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 212 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 213 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9' 214 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F' 215 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 216 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f' 217 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 218 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 219 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 221 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 222 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 223 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 224 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 225 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 226 227string hex2str(string a) { 228 string b; 229 size_t num = a.size() / 2; 230 b.resize(num); 231 for (size_t i = 0; i < num; i++) { 232 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]); 233 } 234 return b; 235} 236 237char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', 238 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 239 240string bin2hex(const hidl_vec<uint8_t>& data) { 241 string retval; 242 retval.reserve(data.size() * 2 + 1); 243 for (uint8_t byte : data) { 244 retval.push_back(nibble2hex[0x0F & (byte >> 4)]); 245 retval.push_back(nibble2hex[0x0F & byte]); 246 } 247 return retval; 248} 249 250string rsa_key = hex2str( 251 "30820275020100300d06092a864886f70d01010105000482025f3082025b" 252 "02010002818100c6095409047d8634812d5a218176e45c41d60a75b13901" 253 "f234226cffe776521c5a77b9e389417b71c0b6a44d13afe4e4a2805d46c9" 254 "da2935adb1ff0c1f24ea06e62b20d776430a4d435157233c6f916783c30e" 255 "310fcbd89b85c2d56771169785ac12bca244abda72bfb19fc44d27c81e1d" 256 "92de284f4061edfd99280745ea6d2502030100010281801be0f04d9cae37" 257 "18691f035338308e91564b55899ffb5084d2460e6630257e05b3ceab0297" 258 "2dfabcd6ce5f6ee2589eb67911ed0fac16e43a444b8c861e544a05933657" 259 "72f8baf6b22fc9e3c5f1024b063ac080a7b2234cf8aee8f6c47bbf4fd3ac" 260 "e7240290bef16c0b3f7f3cdd64ce3ab5912cf6e32f39ab188358afcccd80" 261 "81024100e4b49ef50f765d3b24dde01aceaaf130f2c76670a91a61ae08af" 262 "497b4a82be6dee8fcdd5e3f7ba1cfb1f0c926b88f88c92bfab137fba2285" 263 "227b83c342ff7c55024100ddabb5839c4c7f6bf3d4183231f005b31aa58a" 264 "ffdda5c79e4cce217f6bc930dbe563d480706c24e9ebfcab28a6cdefd324" 265 "b77e1bf7251b709092c24ff501fd91024023d4340eda3445d8cd26c14411" 266 "da6fdca63c1ccd4b80a98ad52b78cc8ad8beb2842c1d280405bc2f6c1bea" 267 "214a1d742ab996b35b63a82a5e470fa88dbf823cdd02401b7b57449ad30d" 268 "1518249a5f56bb98294d4b6ac12ffc86940497a5a5837a6cf946262b4945" 269 "26d328c11e1126380fde04c24f916dec250892db09a6d77cdba351024077" 270 "62cd8f4d050da56bd591adb515d24d7ccd32cca0d05f866d583514bd7324" 271 "d5f33645e8ed8b4a1cb3cc4a1d67987399f2a09f5b3fb68c88d5e5d90ac3" 272 "3492d6"); 273 274string ec_256_key = hex2str( 275 "308187020100301306072a8648ce3d020106082a8648ce3d030107046d30" 276 "6b0201010420737c2ecd7b8d1940bf2930aa9b4ed3ff941eed09366bc032" 277 "99986481f3a4d859a14403420004bf85d7720d07c25461683bc648b4778a" 278 "9a14dd8a024e3bdd8c7ddd9ab2b528bbc7aa1b51f14ebbbb0bd0ce21bcc4" 279 "1c6eb00083cf3376d11fd44949e0b2183bfe"); 280 281string ec_521_key = hex2str( 282 "3081EE020100301006072A8648CE3D020106052B810400230481D63081D3" 283 "02010104420011458C586DB5DAA92AFAB03F4FE46AA9D9C3CE9A9B7A006A" 284 "8384BEC4C78E8E9D18D7D08B5BCFA0E53C75B064AD51C449BAE0258D54B9" 285 "4B1E885DED08ED4FB25CE9A1818903818600040149EC11C6DF0FA122C6A9" 286 "AFD9754A4FA9513A627CA329E349535A5629875A8ADFBE27DCB932C05198" 287 "6377108D054C28C6F39B6F2C9AF81802F9F326B842FF2E5F3C00AB7635CF" 288 "B36157FC0882D574A10D839C1A0C049DC5E0D775E2EE50671A208431BB45" 289 "E78E70BEFE930DB34818EE4D5C26259F5C6B8E28A652950F9F88D7B4B2C9" 290 "D9"); 291 292struct RSA_Delete { 293 void operator()(RSA* p) { RSA_free(p); } 294}; 295 296X509* parse_cert_blob(const hidl_vec<uint8_t>& blob) { 297 const uint8_t* p = blob.data(); 298 return d2i_X509(nullptr, &p, blob.size()); 299} 300 301bool verify_chain(const hidl_vec<hidl_vec<uint8_t>>& chain) { 302 for (size_t i = 0; i < chain.size() - 1; ++i) { 303 X509_Ptr key_cert(parse_cert_blob(chain[i])); 304 X509_Ptr signing_cert; 305 if (i < chain.size() - 1) { 306 signing_cert.reset(parse_cert_blob(chain[i + 1])); 307 } else { 308 signing_cert.reset(parse_cert_blob(chain[i])); 309 } 310 EXPECT_TRUE(!!key_cert.get() && !!signing_cert.get()); 311 if (!key_cert.get() || !signing_cert.get()) return false; 312 313 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get())); 314 EXPECT_TRUE(!!signing_pubkey.get()); 315 if (!signing_pubkey.get()) return false; 316 317 EXPECT_EQ(1, X509_verify(key_cert.get(), signing_pubkey.get())) 318 << "Verification of certificate " << i << " failed"; 319 320 char* cert_issuer = // 321 X509_NAME_oneline(X509_get_issuer_name(key_cert.get()), nullptr, 0); 322 char* signer_subj = 323 X509_NAME_oneline(X509_get_subject_name(signing_cert.get()), nullptr, 0); 324 EXPECT_STREQ(cert_issuer, signer_subj) << "Cert " << i 325 << " has wrong issuer. (Possibly b/38394614)"; 326 if (i == 0) { 327 char* cert_sub = X509_NAME_oneline(X509_get_subject_name(key_cert.get()), nullptr, 0); 328 EXPECT_STREQ("/CN=Android Keystore Key", cert_sub) 329 << "Cert " << i << " has wrong subject. (Possibly b/38394614)"; 330 free(cert_sub); 331 } 332 333 free(cert_issuer); 334 free(signer_subj); 335 336 if (dump_Attestations) std::cout << bin2hex(chain[i]) << std::endl; 337 } 338 339 return true; 340} 341 342// Extract attestation record from cert. Returned object is still part of cert; don't free it 343// separately. 344ASN1_OCTET_STRING* get_attestation_record(X509* certificate) { 345 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */)); 346 EXPECT_TRUE(!!oid.get()); 347 if (!oid.get()) return nullptr; 348 349 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */); 350 EXPECT_NE(-1, location); 351 if (location == -1) return nullptr; 352 353 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location); 354 EXPECT_TRUE(!!attest_rec_ext); 355 if (!attest_rec_ext) return nullptr; 356 357 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext); 358 EXPECT_TRUE(!!attest_rec); 359 return attest_rec; 360} 361 362bool tag_in_list(const KeyParameter& entry) { 363 // Attestations don't contain everything in key authorization lists, so we need to filter 364 // the key lists to produce the lists that we expect to match the attestations. 365 auto tag_list = { 366 Tag::USER_ID, Tag::INCLUDE_UNIQUE_ID, Tag::BLOB_USAGE_REQUIREMENTS, 367 Tag::EC_CURVE /* Tag::EC_CURVE will be included by KM2 implementations */, 368 }; 369 return std::find(tag_list.begin(), tag_list.end(), entry.tag) != tag_list.end(); 370} 371 372AuthorizationSet filter_tags(const AuthorizationSet& set) { 373 AuthorizationSet filtered; 374 std::remove_copy_if(set.begin(), set.end(), std::back_inserter(filtered), tag_in_list); 375 return filtered; 376} 377 378std::string make_string(const uint8_t* data, size_t length) { 379 return std::string(reinterpret_cast<const char*>(data), length); 380} 381 382template <size_t N> std::string make_string(const uint8_t (&a)[N]) { 383 return make_string(a, N); 384} 385 386class HidlBuf : public hidl_vec<uint8_t> { 387 typedef hidl_vec<uint8_t> super; 388 389 public: 390 HidlBuf() {} 391 HidlBuf(const super& other) : super(other) {} 392 HidlBuf(super&& other) : super(std::move(other)) {} 393 explicit HidlBuf(const std::string& other) : HidlBuf() { *this = other; } 394 395 HidlBuf& operator=(const super& other) { 396 super::operator=(other); 397 return *this; 398 } 399 400 HidlBuf& operator=(super&& other) { 401 super::operator=(std::move(other)); 402 return *this; 403 } 404 405 HidlBuf& operator=(const string& other) { 406 resize(other.size()); 407 for (size_t i = 0; i < other.size(); ++i) { 408 (*this)[i] = static_cast<uint8_t>(other[i]); 409 } 410 return *this; 411 } 412 413 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); } 414}; 415 416constexpr uint64_t kOpHandleSentinel = 0xFFFFFFFFFFFFFFFF; 417 418} // namespace 419 420class KeymasterHidlTest : public ::testing::VtsHalHidlTargetTestBase { 421 public: 422 void TearDown() override { 423 if (key_blob_.size()) { 424 CheckedDeleteKey(); 425 } 426 AbortIfNeeded(); 427 } 428 429 // SetUpTestCase runs only once per test case, not once per test. 430 static void SetUpTestCase() { 431 keymaster_ = IKeymasterDevice::getService(service_name); 432 ASSERT_NE(keymaster_, nullptr); 433 434 ASSERT_TRUE( 435 keymaster_ 436 ->getHardwareFeatures([&](bool isSecure, bool supportsEc, bool supportsSymmetric, 437 bool supportsAttestation, bool supportsAllDigests, 438 const hidl_string& name, const hidl_string& author) { 439 is_secure_ = isSecure; 440 supports_ec_ = supportsEc; 441 supports_symmetric_ = supportsSymmetric; 442 supports_attestation_ = supportsAttestation; 443 supports_all_digests_ = supportsAllDigests; 444 name_ = name; 445 author_ = author; 446 }) 447 .isOk()); 448 449 os_version_ = ::keymaster::GetOsVersion(); 450 os_patch_level_ = ::keymaster::GetOsPatchlevel(); 451 } 452 453 static void TearDownTestCase() { keymaster_.clear(); } 454 455 static IKeymasterDevice& keymaster() { return *keymaster_; } 456 static uint32_t os_version() { return os_version_; } 457 static uint32_t os_patch_level() { return os_patch_level_; } 458 459 AuthorizationSet UserAuths() { return AuthorizationSetBuilder().Authorization(TAG_USER_ID, 7); } 460 461 ErrorCode GenerateKey(const AuthorizationSet& key_desc, HidlBuf* key_blob, 462 KeyCharacteristics* key_characteristics) { 463 EXPECT_NE(key_blob, nullptr); 464 EXPECT_NE(key_characteristics, nullptr); 465 EXPECT_EQ(0U, key_blob->size()); 466 467 ErrorCode error; 468 EXPECT_TRUE(keymaster_ 469 ->generateKey(key_desc.hidl_data(), 470 [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob, 471 const KeyCharacteristics& hidl_key_characteristics) { 472 error = hidl_error; 473 *key_blob = hidl_key_blob; 474 *key_characteristics = hidl_key_characteristics; 475 }) 476 .isOk()); 477 // On error, blob & characteristics should be empty. 478 if (error != ErrorCode::OK) { 479 EXPECT_EQ(0U, key_blob->size()); 480 EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() + 481 key_characteristics->teeEnforced.size())); 482 } 483 return error; 484 } 485 486 ErrorCode GenerateKey(const AuthorizationSet& key_desc) { 487 return GenerateKey(key_desc, &key_blob_, &key_characteristics_); 488 } 489 490 ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format, 491 const string& key_material, HidlBuf* key_blob, 492 KeyCharacteristics* key_characteristics) { 493 ErrorCode error; 494 EXPECT_TRUE(keymaster_ 495 ->importKey(key_desc.hidl_data(), format, HidlBuf(key_material), 496 [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob, 497 const KeyCharacteristics& hidl_key_characteristics) { 498 error = hidl_error; 499 *key_blob = hidl_key_blob; 500 *key_characteristics = hidl_key_characteristics; 501 }) 502 .isOk()); 503 // On error, blob & characteristics should be empty. 504 if (error != ErrorCode::OK) { 505 EXPECT_EQ(0U, key_blob->size()); 506 EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() + 507 key_characteristics->teeEnforced.size())); 508 } 509 return error; 510 } 511 512 ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format, 513 const string& key_material) { 514 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_); 515 } 516 517 ErrorCode ExportKey(KeyFormat format, const HidlBuf& key_blob, const HidlBuf& client_id, 518 const HidlBuf& app_data, HidlBuf* key_material) { 519 ErrorCode error; 520 EXPECT_TRUE( 521 keymaster_ 522 ->exportKey(format, key_blob, client_id, app_data, 523 [&](ErrorCode hidl_error_code, const HidlBuf& hidl_key_material) { 524 error = hidl_error_code; 525 *key_material = hidl_key_material; 526 }) 527 .isOk()); 528 // On error, blob should be empty. 529 if (error != ErrorCode::OK) { 530 EXPECT_EQ(0U, key_material->size()); 531 } 532 return error; 533 } 534 535 ErrorCode ExportKey(KeyFormat format, HidlBuf* key_material) { 536 HidlBuf client_id, app_data; 537 return ExportKey(format, key_blob_, client_id, app_data, key_material); 538 } 539 540 ErrorCode DeleteKey(HidlBuf* key_blob, bool keep_key_blob = false) { 541 auto rc = keymaster_->deleteKey(*key_blob); 542 if (!keep_key_blob) *key_blob = HidlBuf(); 543 if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR; 544 return rc; 545 } 546 547 ErrorCode DeleteKey(bool keep_key_blob = false) { 548 return DeleteKey(&key_blob_, keep_key_blob); 549 } 550 551 ErrorCode DeleteAllKeys() { 552 ErrorCode error = keymaster_->deleteAllKeys(); 553 return error; 554 } 555 556 void CheckedDeleteKey(HidlBuf* key_blob, bool keep_key_blob = false) { 557 auto rc = DeleteKey(key_blob, keep_key_blob); 558 EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED); 559 } 560 561 void CheckedDeleteKey() { CheckedDeleteKey(&key_blob_); } 562 563 ErrorCode GetCharacteristics(const HidlBuf& key_blob, const HidlBuf& client_id, 564 const HidlBuf& app_data, KeyCharacteristics* key_characteristics) { 565 ErrorCode error = ErrorCode::UNKNOWN_ERROR; 566 EXPECT_TRUE( 567 keymaster_ 568 ->getKeyCharacteristics( 569 key_blob, client_id, app_data, 570 [&](ErrorCode hidl_error, const KeyCharacteristics& hidl_key_characteristics) { 571 error = hidl_error, *key_characteristics = hidl_key_characteristics; 572 }) 573 .isOk()); 574 return error; 575 } 576 577 ErrorCode GetCharacteristics(const HidlBuf& key_blob, KeyCharacteristics* key_characteristics) { 578 HidlBuf client_id, app_data; 579 return GetCharacteristics(key_blob, client_id, app_data, key_characteristics); 580 } 581 582 ErrorCode Begin(KeyPurpose purpose, const HidlBuf& key_blob, const AuthorizationSet& in_params, 583 AuthorizationSet* out_params, OperationHandle* op_handle) { 584 SCOPED_TRACE("Begin"); 585 ErrorCode error; 586 OperationHandle saved_handle = *op_handle; 587 EXPECT_TRUE( 588 keymaster_ 589 ->begin(purpose, key_blob, in_params.hidl_data(), 590 [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params, 591 uint64_t hidl_op_handle) { 592 error = hidl_error; 593 *out_params = hidl_out_params; 594 *op_handle = hidl_op_handle; 595 }) 596 .isOk()); 597 if (error != ErrorCode::OK) { 598 // Some implementations may modify *op_handle on error. 599 *op_handle = saved_handle; 600 } 601 return error; 602 } 603 604 ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params, 605 AuthorizationSet* out_params) { 606 SCOPED_TRACE("Begin"); 607 EXPECT_EQ(kOpHandleSentinel, op_handle_); 608 return Begin(purpose, key_blob_, in_params, out_params, &op_handle_); 609 } 610 611 ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params) { 612 SCOPED_TRACE("Begin"); 613 AuthorizationSet out_params; 614 ErrorCode error = Begin(purpose, in_params, &out_params); 615 EXPECT_TRUE(out_params.empty()); 616 return error; 617 } 618 619 ErrorCode Update(OperationHandle op_handle, const AuthorizationSet& in_params, 620 const string& input, AuthorizationSet* out_params, string* output, 621 size_t* input_consumed) { 622 SCOPED_TRACE("Update"); 623 ErrorCode error; 624 EXPECT_TRUE(keymaster_ 625 ->update(op_handle, in_params.hidl_data(), HidlBuf(input), 626 [&](ErrorCode hidl_error, uint32_t hidl_input_consumed, 627 const hidl_vec<KeyParameter>& hidl_out_params, 628 const HidlBuf& hidl_output) { 629 error = hidl_error; 630 out_params->push_back(AuthorizationSet(hidl_out_params)); 631 output->append(hidl_output.to_string()); 632 *input_consumed = hidl_input_consumed; 633 }) 634 .isOk()); 635 return error; 636 } 637 638 ErrorCode Update(const string& input, string* out, size_t* input_consumed) { 639 SCOPED_TRACE("Update"); 640 AuthorizationSet out_params; 641 ErrorCode error = Update(op_handle_, AuthorizationSet() /* in_params */, input, &out_params, 642 out, input_consumed); 643 EXPECT_TRUE(out_params.empty()); 644 return error; 645 } 646 647 ErrorCode Finish(OperationHandle op_handle, const AuthorizationSet& in_params, 648 const string& input, const string& signature, AuthorizationSet* out_params, 649 string* output) { 650 SCOPED_TRACE("Finish"); 651 ErrorCode error; 652 EXPECT_TRUE( 653 keymaster_ 654 ->finish(op_handle, in_params.hidl_data(), HidlBuf(input), HidlBuf(signature), 655 [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params, 656 const HidlBuf& hidl_output) { 657 error = hidl_error; 658 *out_params = hidl_out_params; 659 output->append(hidl_output.to_string()); 660 }) 661 .isOk()); 662 op_handle_ = kOpHandleSentinel; // So dtor doesn't Abort(). 663 return error; 664 } 665 666 ErrorCode Finish(const string& message, string* output) { 667 SCOPED_TRACE("Finish"); 668 AuthorizationSet out_params; 669 string finish_output; 670 ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message, 671 "" /* signature */, &out_params, output); 672 if (error != ErrorCode::OK) { 673 return error; 674 } 675 EXPECT_EQ(0U, out_params.size()); 676 return error; 677 } 678 679 ErrorCode Finish(const string& message, const string& signature, string* output) { 680 SCOPED_TRACE("Finish"); 681 AuthorizationSet out_params; 682 ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message, signature, 683 &out_params, output); 684 op_handle_ = kOpHandleSentinel; // So dtor doesn't Abort(). 685 if (error != ErrorCode::OK) { 686 return error; 687 } 688 EXPECT_EQ(0U, out_params.size()); 689 return error; 690 } 691 692 ErrorCode Abort(OperationHandle op_handle) { 693 SCOPED_TRACE("Abort"); 694 auto retval = keymaster_->abort(op_handle); 695 EXPECT_TRUE(retval.isOk()); 696 return retval; 697 } 698 699 void AbortIfNeeded() { 700 SCOPED_TRACE("AbortIfNeeded"); 701 if (op_handle_ != kOpHandleSentinel) { 702 EXPECT_EQ(ErrorCode::OK, Abort(op_handle_)); 703 op_handle_ = kOpHandleSentinel; 704 } 705 } 706 707 ErrorCode AttestKey(const HidlBuf& key_blob, const AuthorizationSet& attest_params, 708 hidl_vec<hidl_vec<uint8_t>>* cert_chain) { 709 SCOPED_TRACE("AttestKey"); 710 ErrorCode error; 711 auto rc = keymaster_->attestKey( 712 key_blob, attest_params.hidl_data(), 713 [&](ErrorCode hidl_error, const hidl_vec<hidl_vec<uint8_t>>& hidl_cert_chain) { 714 error = hidl_error; 715 *cert_chain = hidl_cert_chain; 716 }); 717 718 EXPECT_TRUE(rc.isOk()) << rc.description(); 719 if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR; 720 721 return error; 722 } 723 724 ErrorCode AttestKey(const AuthorizationSet& attest_params, 725 hidl_vec<hidl_vec<uint8_t>>* cert_chain) { 726 SCOPED_TRACE("AttestKey"); 727 return AttestKey(key_blob_, attest_params, cert_chain); 728 } 729 730 string ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation, const string& message, 731 const AuthorizationSet& in_params, AuthorizationSet* out_params) { 732 SCOPED_TRACE("ProcessMessage"); 733 AuthorizationSet begin_out_params; 734 EXPECT_EQ(ErrorCode::OK, 735 Begin(operation, key_blob, in_params, &begin_out_params, &op_handle_)); 736 737 string unused; 738 AuthorizationSet finish_params; 739 AuthorizationSet finish_out_params; 740 string output; 741 EXPECT_EQ(ErrorCode::OK, 742 Finish(op_handle_, finish_params, message, unused, &finish_out_params, &output)); 743 op_handle_ = kOpHandleSentinel; 744 745 out_params->push_back(begin_out_params); 746 out_params->push_back(finish_out_params); 747 return output; 748 } 749 750 string SignMessage(const HidlBuf& key_blob, const string& message, 751 const AuthorizationSet& params) { 752 SCOPED_TRACE("SignMessage"); 753 AuthorizationSet out_params; 754 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params); 755 EXPECT_TRUE(out_params.empty()); 756 return signature; 757 } 758 759 string SignMessage(const string& message, const AuthorizationSet& params) { 760 SCOPED_TRACE("SignMessage"); 761 return SignMessage(key_blob_, message, params); 762 } 763 764 string MacMessage(const string& message, Digest digest, size_t mac_length) { 765 SCOPED_TRACE("MacMessage"); 766 return SignMessage( 767 key_blob_, message, 768 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length)); 769 } 770 771 void CheckHmacTestVector(const string& key, const string& message, Digest digest, 772 const string& expected_mac) { 773 SCOPED_TRACE("CheckHmacTestVector"); 774 ASSERT_EQ(ErrorCode::OK, 775 ImportKey(AuthorizationSetBuilder() 776 .Authorization(TAG_NO_AUTH_REQUIRED) 777 .HmacKey(key.size() * 8) 778 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8) 779 .Digest(digest), 780 KeyFormat::RAW, key)); 781 string signature = MacMessage(message, digest, expected_mac.size() * 8); 782 EXPECT_EQ(expected_mac, signature) << "Test vector didn't match for digest " << (int)digest; 783 CheckedDeleteKey(); 784 } 785 786 void CheckAesCtrTestVector(const string& key, const string& nonce, const string& message, 787 const string& expected_ciphertext) { 788 SCOPED_TRACE("CheckAesCtrTestVector"); 789 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() 790 .Authorization(TAG_NO_AUTH_REQUIRED) 791 .AesEncryptionKey(key.size() * 8) 792 .BlockMode(BlockMode::CTR) 793 .Authorization(TAG_CALLER_NONCE) 794 .Padding(PaddingMode::NONE), 795 KeyFormat::RAW, key)); 796 797 auto params = AuthorizationSetBuilder() 798 .Authorization(TAG_NONCE, nonce.data(), nonce.size()) 799 .BlockMode(BlockMode::CTR) 800 .Padding(PaddingMode::NONE); 801 AuthorizationSet out_params; 802 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params); 803 EXPECT_EQ(expected_ciphertext, ciphertext); 804 } 805 806 void VerifyMessage(const HidlBuf& key_blob, const string& message, const string& signature, 807 const AuthorizationSet& params) { 808 SCOPED_TRACE("VerifyMessage"); 809 AuthorizationSet begin_out_params; 810 ASSERT_EQ(ErrorCode::OK, 811 Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params, &op_handle_)); 812 813 string unused; 814 AuthorizationSet finish_params; 815 AuthorizationSet finish_out_params; 816 string output; 817 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, signature, 818 &finish_out_params, &output)); 819 op_handle_ = kOpHandleSentinel; 820 EXPECT_TRUE(output.empty()); 821 } 822 823 void VerifyMessage(const string& message, const string& signature, 824 const AuthorizationSet& params) { 825 SCOPED_TRACE("VerifyMessage"); 826 VerifyMessage(key_blob_, message, signature, params); 827 } 828 829 string EncryptMessage(const HidlBuf& key_blob, const string& message, 830 const AuthorizationSet& in_params, AuthorizationSet* out_params) { 831 SCOPED_TRACE("EncryptMessage"); 832 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params); 833 } 834 835 string EncryptMessage(const string& message, const AuthorizationSet& params, 836 AuthorizationSet* out_params) { 837 SCOPED_TRACE("EncryptMessage"); 838 return EncryptMessage(key_blob_, message, params, out_params); 839 } 840 841 string EncryptMessage(const string& message, const AuthorizationSet& params) { 842 SCOPED_TRACE("EncryptMessage"); 843 AuthorizationSet out_params; 844 string ciphertext = EncryptMessage(message, params, &out_params); 845 EXPECT_TRUE(out_params.empty()) 846 << "Output params should be empty. Contained: " << out_params; 847 return ciphertext; 848 } 849 850 string DecryptMessage(const HidlBuf& key_blob, const string& ciphertext, 851 const AuthorizationSet& params) { 852 SCOPED_TRACE("DecryptMessage"); 853 AuthorizationSet out_params; 854 string plaintext = 855 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params); 856 EXPECT_TRUE(out_params.empty()); 857 return plaintext; 858 } 859 860 string DecryptMessage(const string& ciphertext, const AuthorizationSet& params) { 861 SCOPED_TRACE("DecryptMessage"); 862 return DecryptMessage(key_blob_, ciphertext, params); 863 } 864 865 template <TagType tag_type, Tag tag, typename ValueT> 866 void CheckKm0CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) { 867 SCOPED_TRACE("CheckKm0CryptoParam"); 868 if (is_secure_) { 869 EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected)); 870 EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag)); 871 } else { 872 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected)); 873 EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag)); 874 } 875 } 876 877 template <TagType tag_type, Tag tag, typename ValueT> 878 void CheckKm1CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) { 879 SCOPED_TRACE("CheckKm1CryptoParam"); 880 if (is_secure_ && supports_symmetric_) { 881 EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected)); 882 EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag)); 883 } else { 884 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected)); 885 EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag)); 886 } 887 } 888 889 template <TagType tag_type, Tag tag, typename ValueT> 890 void CheckKm2CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) { 891 SCOPED_TRACE("CheckKm2CryptoParam"); 892 if (supports_attestation_) { 893 EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected)); 894 EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag)); 895 } else if (!supports_symmetric_ /* KM version < 1 or SW */) { 896 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected)); 897 EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag)); 898 } 899 } 900 901 void CheckOrigin() { 902 SCOPED_TRACE("CheckOrigin"); 903 if (is_secure_ && supports_symmetric_) { 904 EXPECT_TRUE( 905 contains(key_characteristics_.teeEnforced, TAG_ORIGIN, KeyOrigin::IMPORTED)); 906 } else if (is_secure_) { 907 EXPECT_TRUE(contains(key_characteristics_.teeEnforced, TAG_ORIGIN, KeyOrigin::UNKNOWN)); 908 } else { 909 EXPECT_TRUE( 910 contains(key_characteristics_.softwareEnforced, TAG_ORIGIN, KeyOrigin::IMPORTED)); 911 } 912 } 913 914 static bool IsSecure() { return is_secure_; } 915 static bool SupportsEc() { return supports_ec_; } 916 static bool SupportsSymmetric() { return supports_symmetric_; } 917 static bool SupportsAllDigests() { return supports_all_digests_; } 918 static bool SupportsAttestation() { return supports_attestation_; } 919 920 static bool Km2Profile() { 921 return SupportsAttestation() && SupportsAllDigests() && SupportsSymmetric() && 922 SupportsEc() && IsSecure(); 923 } 924 925 static bool Km1Profile() { 926 return !SupportsAttestation() && SupportsSymmetric() && SupportsEc() && IsSecure(); 927 } 928 929 static bool Km0Profile() { 930 return !SupportsAttestation() && !SupportsAllDigests() && !SupportsSymmetric() && 931 IsSecure(); 932 } 933 934 static bool SwOnlyProfile() { 935 return !SupportsAttestation() && !SupportsAllDigests() && !SupportsSymmetric() && 936 !SupportsEc() && !IsSecure(); 937 } 938 939 HidlBuf key_blob_; 940 KeyCharacteristics key_characteristics_; 941 OperationHandle op_handle_ = kOpHandleSentinel; 942 943 private: 944 static sp<IKeymasterDevice> keymaster_; 945 static uint32_t os_version_; 946 static uint32_t os_patch_level_; 947 948 static bool is_secure_; 949 static bool supports_ec_; 950 static bool supports_symmetric_; 951 static bool supports_attestation_; 952 static bool supports_all_digests_; 953 static hidl_string name_; 954 static hidl_string author_; 955}; 956 957bool verify_attestation_record(const string& challenge, const string& app_id, 958 AuthorizationSet expected_sw_enforced, 959 AuthorizationSet expected_tee_enforced, 960 const hidl_vec<uint8_t>& attestation_cert) { 961 X509_Ptr cert(parse_cert_blob(attestation_cert)); 962 EXPECT_TRUE(!!cert.get()); 963 if (!cert.get()) return false; 964 965 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get()); 966 EXPECT_TRUE(!!attest_rec); 967 if (!attest_rec) return false; 968 969 AuthorizationSet att_sw_enforced; 970 AuthorizationSet att_tee_enforced; 971 uint32_t att_attestation_version; 972 uint32_t att_keymaster_version; 973 SecurityLevel att_attestation_security_level; 974 SecurityLevel att_keymaster_security_level; 975 HidlBuf att_challenge; 976 HidlBuf att_unique_id; 977 HidlBuf att_app_id; 978 EXPECT_EQ(ErrorCode::OK, 979 parse_attestation_record(attest_rec->data, // 980 attest_rec->length, // 981 &att_attestation_version, // 982 &att_attestation_security_level, // 983 &att_keymaster_version, // 984 &att_keymaster_security_level, // 985 &att_challenge, // 986 &att_sw_enforced, // 987 &att_tee_enforced, // 988 &att_unique_id)); 989 990 EXPECT_TRUE(att_attestation_version == 1 || att_attestation_version == 2); 991 992 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, 993 HidlBuf(app_id)); 994 995 if (!KeymasterHidlTest::IsSecure()) { 996 // SW is KM2 997 EXPECT_EQ(att_keymaster_version, 2U); 998 } 999 1000 if (KeymasterHidlTest::SupportsSymmetric()) { 1001 EXPECT_GE(att_keymaster_version, 1U); 1002 } 1003 1004 if (KeymasterHidlTest::SupportsAttestation()) { 1005 EXPECT_GE(att_keymaster_version, 2U); 1006 } 1007 1008 EXPECT_EQ(KeymasterHidlTest::IsSecure() ? SecurityLevel::TRUSTED_ENVIRONMENT 1009 : SecurityLevel::SOFTWARE, 1010 att_keymaster_security_level); 1011 EXPECT_EQ(KeymasterHidlTest::SupportsAttestation() ? SecurityLevel::TRUSTED_ENVIRONMENT 1012 : SecurityLevel::SOFTWARE, 1013 att_attestation_security_level); 1014 1015 EXPECT_EQ(challenge.length(), att_challenge.size()); 1016 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length())); 1017 1018 att_sw_enforced.Sort(); 1019 expected_sw_enforced.Sort(); 1020 EXPECT_EQ(filter_tags(expected_sw_enforced), filter_tags(att_sw_enforced)) 1021 << "(Possibly b/38394619)"; 1022 1023 att_tee_enforced.Sort(); 1024 expected_tee_enforced.Sort(); 1025 EXPECT_EQ(filter_tags(expected_tee_enforced), filter_tags(att_tee_enforced)) 1026 << "(Possibly b/38394619)"; 1027 1028 return true; 1029} 1030 1031sp<IKeymasterDevice> KeymasterHidlTest::keymaster_; 1032uint32_t KeymasterHidlTest::os_version_; 1033uint32_t KeymasterHidlTest::os_patch_level_; 1034bool KeymasterHidlTest::is_secure_; 1035bool KeymasterHidlTest::supports_ec_; 1036bool KeymasterHidlTest::supports_symmetric_; 1037bool KeymasterHidlTest::supports_all_digests_; 1038bool KeymasterHidlTest::supports_attestation_; 1039hidl_string KeymasterHidlTest::name_; 1040hidl_string KeymasterHidlTest::author_; 1041 1042typedef KeymasterHidlTest KeymasterVersionTest; 1043 1044/* 1045 * KeymasterVersionTest.SensibleFeatures: 1046 * 1047 * Queries keymaster to find the set of features it supports. Fails if the combination doesn't 1048 * correspond to any well-defined keymaster version. 1049 */ 1050TEST_F(KeymasterVersionTest, SensibleFeatures) { 1051 EXPECT_TRUE(Km2Profile() || Km1Profile() || Km0Profile() || SwOnlyProfile()) 1052 << "Keymaster feature set doesn't fit any reasonable profile. Reported features:" 1053 << "SupportsAttestation [" << SupportsAttestation() << "], " 1054 << "SupportsSymmetric [" << SupportsSymmetric() << "], " 1055 << "SupportsAllDigests [" << SupportsAllDigests() << "], " 1056 << "SupportsEc [" << SupportsEc() << "], " 1057 << "IsSecure [" << IsSecure() << "]"; 1058} 1059 1060class NewKeyGenerationTest : public KeymasterHidlTest { 1061 protected: 1062 void CheckBaseParams(const KeyCharacteristics& keyCharacteristics) { 1063 // TODO(swillden): Distinguish which params should be in which auth list. 1064 1065 AuthorizationSet auths(keyCharacteristics.teeEnforced); 1066 auths.push_back(AuthorizationSet(keyCharacteristics.softwareEnforced)); 1067 1068 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED)); 1069 1070 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN)); 1071 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY)); 1072 EXPECT_TRUE(auths.Contains(TAG_USER_ID, 7)) 1073 << "User ID should be 7, was " << auths.GetTagValue(TAG_USER_ID); 1074 1075 // Verify that App ID, App data and ROT are NOT included. 1076 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST)); 1077 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_ID)); 1078 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA)); 1079 1080 // Check that some unexpected tags/values are NOT present. 1081 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT)); 1082 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT)); 1083 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301)); 1084 1085 // Now check that unspecified, defaulted tags are correct. 1086 EXPECT_TRUE(auths.Contains(TAG_CREATION_DATETIME)); 1087 1088 if (SupportsAttestation()) { 1089 EXPECT_TRUE(auths.Contains(TAG_OS_VERSION, os_version())) 1090 << "OS version is " << os_version() << " key reported " 1091 << auths.GetTagValue(TAG_OS_VERSION); 1092 EXPECT_TRUE(auths.Contains(TAG_OS_PATCHLEVEL, os_patch_level())) 1093 << "OS patch level is " << os_patch_level() << " key reported " 1094 << auths.GetTagValue(TAG_OS_PATCHLEVEL); 1095 } 1096 } 1097}; 1098 1099/* 1100 * NewKeyGenerationTest.Rsa 1101 * 1102 * Verifies that keymaster can generate all required RSA key sizes, and that the resulting keys have 1103 * correct characteristics. 1104 */ 1105TEST_F(NewKeyGenerationTest, Rsa) { 1106 for (auto key_size : {1024, 2048, 3072, 4096}) { 1107 HidlBuf key_blob; 1108 KeyCharacteristics key_characteristics; 1109 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1110 .RsaSigningKey(key_size, 3) 1111 .Digest(Digest::NONE) 1112 .Padding(PaddingMode::NONE) 1113 .Authorizations(UserAuths()), 1114 &key_blob, &key_characteristics)); 1115 1116 ASSERT_GT(key_blob.size(), 0U); 1117 CheckBaseParams(key_characteristics); 1118 1119 AuthorizationSet crypto_params; 1120 if (IsSecure()) { 1121 crypto_params = key_characteristics.teeEnforced; 1122 } else { 1123 crypto_params = key_characteristics.softwareEnforced; 1124 } 1125 1126 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, KM_ALGORITHM_RSA)); 1127 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size)); 1128 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 3)); 1129 1130 CheckedDeleteKey(&key_blob); 1131 } 1132} 1133 1134/* 1135 * NewKeyGenerationTest.RsaNoDefaultSize 1136 * 1137 * Verifies that failing to specify a key size for RSA key generation returns UNSUPPORTED_KEY_SIZE. 1138 */ 1139TEST_F(NewKeyGenerationTest, RsaNoDefaultSize) { 1140 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, 1141 GenerateKey(AuthorizationSetBuilder() 1142 .Authorization(TAG_ALGORITHM, Algorithm::RSA) 1143 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3) 1144 .SigningKey())); 1145} 1146 1147/* 1148 * NewKeyGenerationTest.Ecdsa 1149 * 1150 * Verifies that keymaster can generate all required EC key sizes, and that the resulting keys have 1151 * correct characteristics. 1152 */ 1153TEST_F(NewKeyGenerationTest, Ecdsa) { 1154 for (auto key_size : {224, 256, 384, 521}) { 1155 HidlBuf key_blob; 1156 KeyCharacteristics key_characteristics; 1157 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1158 .EcdsaSigningKey(key_size) 1159 .Digest(Digest::NONE) 1160 .Authorizations(UserAuths()), 1161 &key_blob, &key_characteristics)); 1162 ASSERT_GT(key_blob.size(), 0U); 1163 CheckBaseParams(key_characteristics); 1164 1165 AuthorizationSet crypto_params; 1166 if (IsSecure()) { 1167 crypto_params = key_characteristics.teeEnforced; 1168 } else { 1169 crypto_params = key_characteristics.softwareEnforced; 1170 } 1171 1172 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC)); 1173 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size)); 1174 1175 CheckedDeleteKey(&key_blob); 1176 } 1177} 1178 1179/* 1180 * NewKeyGenerationTest.EcdsaDefaultSize 1181 * 1182 * Verifies that failing to specify a key size for EC key generation returns UNSUPPORTED_KEY_SIZE. 1183 */ 1184TEST_F(NewKeyGenerationTest, EcdsaDefaultSize) { 1185 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, 1186 GenerateKey(AuthorizationSetBuilder() 1187 .Authorization(TAG_ALGORITHM, Algorithm::EC) 1188 .SigningKey() 1189 .Digest(Digest::NONE))); 1190} 1191 1192/* 1193 * NewKeyGenerationTest.EcdsaInvalidSize 1194 * 1195 * Verifies that failing to specify an invalid key size for EC key generation returns 1196 * UNSUPPORTED_KEY_SIZE. 1197 */ 1198TEST_F(NewKeyGenerationTest, EcdsaInvalidSize) { 1199 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, 1200 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(Digest::NONE))); 1201} 1202 1203/* 1204 * NewKeyGenerationTest.EcdsaMismatchKeySize 1205 * 1206 * Verifies that specifying mismatched key size and curve for EC key generation returns 1207 * INVALID_ARGUMENT. 1208 */ 1209TEST_F(NewKeyGenerationTest, EcdsaMismatchKeySize) { 1210 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, 1211 GenerateKey(AuthorizationSetBuilder() 1212 .EcdsaSigningKey(224) 1213 .Authorization(TAG_EC_CURVE, EcCurve::P_256) 1214 .Digest(Digest::NONE))) 1215 << "(Possibly b/36233343)"; 1216} 1217 1218TEST_F(NewKeyGenerationTest, EcdsaAllValidSizes) { 1219 size_t valid_sizes[] = {224, 256, 384, 521}; 1220 for (size_t size : valid_sizes) { 1221 EXPECT_EQ(ErrorCode::OK, 1222 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(Digest::NONE))) 1223 << "Failed to generate size: " << size; 1224 CheckedDeleteKey(); 1225 } 1226} 1227 1228/* 1229 * NewKeyGenerationTest.EcdsaAllValidCurves 1230 * 1231 * Verifies that keymaster supports all required EC curves. 1232 */ 1233TEST_F(NewKeyGenerationTest, EcdsaAllValidCurves) { 1234 EcCurve curves[] = {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}; 1235 for (auto curve : curves) { 1236 EXPECT_EQ( 1237 ErrorCode::OK, 1238 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(curve).Digest(Digest::SHA_2_512))) 1239 << "Failed to generate key on curve: " << curve; 1240 CheckedDeleteKey(); 1241 } 1242} 1243 1244/* 1245 * NewKeyGenerationTest.Hmac 1246 * 1247 * Verifies that keymaster supports all required digests, and that the resulting keys have correct 1248 * characteristics. 1249 */ 1250TEST_F(NewKeyGenerationTest, Hmac) { 1251 for (auto digest : {Digest::MD5, Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, 1252 Digest::SHA_2_384, Digest::SHA_2_512}) { 1253 HidlBuf key_blob; 1254 KeyCharacteristics key_characteristics; 1255 constexpr size_t key_size = 128; 1256 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1257 .HmacKey(key_size) 1258 .Digest(digest) 1259 .Authorization(TAG_MIN_MAC_LENGTH, 128) 1260 .Authorizations(UserAuths()), 1261 &key_blob, &key_characteristics)); 1262 1263 ASSERT_GT(key_blob.size(), 0U); 1264 CheckBaseParams(key_characteristics); 1265 1266 AuthorizationSet teeEnforced = key_characteristics.teeEnforced; 1267 AuthorizationSet softwareEnforced = key_characteristics.softwareEnforced; 1268 if (SupportsAttestation() || SupportsAllDigests()) { 1269 // Either KM2, which must support all, or KM1 that claims full support 1270 EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC)); 1271 EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size)); 1272 } else if (SupportsSymmetric()) { 1273 if (digest == Digest::SHA1 || digest == Digest::SHA_2_256) { 1274 // KM1 must support SHA1 and SHA256 in hardware 1275 EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC)); 1276 EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size)); 1277 } else { 1278 // Othere digests may or may not be supported 1279 EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC) || 1280 softwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC)); 1281 EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size) || 1282 softwareEnforced.Contains(TAG_KEY_SIZE, key_size)); 1283 } 1284 } else { 1285 // KM0 and SW KM do all digests in SW. 1286 EXPECT_TRUE(softwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC)); 1287 EXPECT_TRUE(softwareEnforced.Contains(TAG_KEY_SIZE, key_size)); 1288 } 1289 1290 CheckedDeleteKey(&key_blob); 1291 } 1292} 1293 1294/* 1295 * NewKeyGenerationTest.HmacCheckKeySizes 1296 * 1297 * Verifies that keymaster supports all key sizes, and rejects all invalid key sizes. 1298 */ 1299TEST_F(NewKeyGenerationTest, HmacCheckKeySizes) { 1300 for (size_t key_size = 0; key_size <= 512; ++key_size) { 1301 if (key_size < 64 || key_size % 8 != 0) { 1302 // To keep this test from being very slow, we only test a random fraction of non-byte 1303 // key sizes. We test only ~10% of such cases. Since there are 392 of them, we expect 1304 // to run ~40 of them in each run. 1305 if (key_size % 8 == 0 || random() % 10 == 0) { 1306 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, 1307 GenerateKey(AuthorizationSetBuilder() 1308 .HmacKey(key_size) 1309 .Digest(Digest::SHA_2_256) 1310 .Authorization(TAG_MIN_MAC_LENGTH, 256))) 1311 << "HMAC key size " << key_size << " invalid (Possibly b/33462346)"; 1312 } 1313 } else { 1314 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1315 .HmacKey(key_size) 1316 .Digest(Digest::SHA_2_256) 1317 .Authorization(TAG_MIN_MAC_LENGTH, 256))); 1318 CheckedDeleteKey(); 1319 } 1320 } 1321} 1322 1323/* 1324 * NewKeyGenerationTest.HmacCheckMinMacLengths 1325 * 1326 * Verifies that keymaster supports all required MAC lengths and rejects all invalid lengths. This 1327 * test is probabilistic in order to keep the runtime down, but any failure prints out the specific 1328 * MAC length that failed, so reproducing a failed run will be easy. 1329 */ 1330TEST_F(NewKeyGenerationTest, HmacCheckMinMacLengths) { 1331 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) { 1332 if (min_mac_length < 64 || min_mac_length % 8 != 0) { 1333 // To keep this test from being very long, we only test a random fraction of non-byte 1334 // lengths. We test only ~10% of such cases. Since there are 172 of them, we expect to 1335 // run ~17 of them in each run. 1336 if (min_mac_length % 8 == 0 || random() % 10 == 0) { 1337 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH, 1338 GenerateKey(AuthorizationSetBuilder() 1339 .HmacKey(128) 1340 .Digest(Digest::SHA_2_256) 1341 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length))) 1342 << "HMAC min mac length " << min_mac_length << " invalid."; 1343 } 1344 } else { 1345 EXPECT_EQ(ErrorCode::OK, 1346 GenerateKey(AuthorizationSetBuilder() 1347 .HmacKey(128) 1348 .Digest(Digest::SHA_2_256) 1349 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length))); 1350 CheckedDeleteKey(); 1351 } 1352 } 1353} 1354 1355/* 1356 * NewKeyGenerationTest.HmacMultipleDigests 1357 * 1358 * Verifies that keymaster rejects HMAC key generation with multiple specified digest algorithms. 1359 */ 1360TEST_F(NewKeyGenerationTest, HmacMultipleDigests) { 1361 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST, 1362 GenerateKey(AuthorizationSetBuilder() 1363 .HmacKey(128) 1364 .Digest(Digest::SHA1) 1365 .Digest(Digest::SHA_2_256) 1366 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 1367} 1368 1369/* 1370 * NewKeyGenerationTest.HmacDigestNone 1371 * 1372 * Verifies that keymaster rejects HMAC key generation with no digest or Digest::NONE 1373 */ 1374TEST_F(NewKeyGenerationTest, HmacDigestNone) { 1375 ASSERT_EQ( 1376 ErrorCode::UNSUPPORTED_DIGEST, 1377 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH, 128))); 1378 1379 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST, 1380 GenerateKey(AuthorizationSetBuilder() 1381 .HmacKey(128) 1382 .Digest(Digest::NONE) 1383 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 1384} 1385 1386typedef KeymasterHidlTest GetKeyCharacteristicsTest; 1387 1388/* 1389 * GetKeyCharacteristicsTest.HmacDigestNone 1390 * 1391 * Verifies that getKeyCharacteristics functions, and that generated and retrieved key 1392 * characteristics match. 1393 */ 1394TEST_F(GetKeyCharacteristicsTest, SimpleRsa) { 1395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1396 .RsaSigningKey(1024, 3) 1397 .Digest(Digest::NONE) 1398 .Padding(PaddingMode::NONE))); 1399 1400 KeyCharacteristics retrieved_chars; 1401 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob_, &retrieved_chars)); 1402 1403 AuthorizationSet gen_sw = key_characteristics_.softwareEnforced; 1404 AuthorizationSet gen_tee = key_characteristics_.teeEnforced; 1405 AuthorizationSet retrieved_sw = retrieved_chars.softwareEnforced; 1406 AuthorizationSet retrieved_tee = retrieved_chars.teeEnforced; 1407 1408 EXPECT_EQ(gen_sw, retrieved_sw); 1409 EXPECT_EQ(gen_tee, retrieved_tee); 1410} 1411 1412typedef KeymasterHidlTest SigningOperationsTest; 1413 1414/* 1415 * SigningOperationsTest.RsaSuccess 1416 * 1417 * Verifies that raw RSA signature operations succeed. 1418 */ 1419TEST_F(SigningOperationsTest, RsaSuccess) { 1420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1421 .RsaSigningKey(1024, 3) 1422 .Digest(Digest::NONE) 1423 .Padding(PaddingMode::NONE) 1424 .Authorization(TAG_NO_AUTH_REQUIRED))); 1425 string message = "12345678901234567890123456789012"; 1426 string signature = SignMessage( 1427 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)); 1428} 1429 1430/* 1431 * SigningOperationsTest.RsaPssSha256Success 1432 * 1433 * Verifies that RSA-PSS signature operations succeed. 1434 */ 1435TEST_F(SigningOperationsTest, RsaPssSha256Success) { 1436 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1437 .RsaSigningKey(1024, 3) 1438 .Digest(Digest::SHA_2_256) 1439 .Padding(PaddingMode::RSA_PSS) 1440 .Authorization(TAG_NO_AUTH_REQUIRED))); 1441 // Use large message, which won't work without digesting. 1442 string message(1024, 'a'); 1443 string signature = SignMessage( 1444 message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS)); 1445} 1446 1447/* 1448 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther 1449 * 1450 * Verifies that keymaster rejects signature operations that specify a padding mode when the key 1451 * supports only unpadded operations. 1452 */ 1453TEST_F(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) { 1454 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1455 .RsaSigningKey(1024, 3) 1456 .Digest(Digest::NONE) 1457 .Authorization(TAG_NO_AUTH_REQUIRED) 1458 .Padding(PaddingMode::NONE))); 1459 string message = "12345678901234567890123456789012"; 1460 string signature; 1461 1462 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, 1463 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder() 1464 .Digest(Digest::NONE) 1465 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 1466} 1467 1468/* 1469 * SigningOperationsTest.RsaPkcs1Sha256Success 1470 * 1471 * Verifies that digested RSA-PKCS1 signature operations succeed. 1472 */ 1473TEST_F(SigningOperationsTest, RsaPkcs1Sha256Success) { 1474 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1475 .RsaSigningKey(1024, 3) 1476 .Digest(Digest::SHA_2_256) 1477 .Authorization(TAG_NO_AUTH_REQUIRED) 1478 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 1479 string message(1024, 'a'); 1480 string signature = SignMessage(message, AuthorizationSetBuilder() 1481 .Digest(Digest::SHA_2_256) 1482 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)); 1483} 1484 1485/* 1486 * SigningOperationsTest.RsaPkcs1NoDigestSuccess 1487 * 1488 * Verifies that undigested RSA-PKCS1 signature operations succeed. 1489 */ 1490TEST_F(SigningOperationsTest, RsaPkcs1NoDigestSuccess) { 1491 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1492 .RsaSigningKey(1024, 3) 1493 .Digest(Digest::NONE) 1494 .Authorization(TAG_NO_AUTH_REQUIRED) 1495 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 1496 string message(53, 'a'); 1497 string signature = SignMessage( 1498 message, 1499 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)); 1500} 1501 1502/* 1503 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge 1504 * 1505 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when 1506 * given a too-long message. 1507 */ 1508TEST_F(SigningOperationsTest, RsaPkcs1NoDigestTooLong) { 1509 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1510 .RsaSigningKey(1024, 3) 1511 .Digest(Digest::NONE) 1512 .Authorization(TAG_NO_AUTH_REQUIRED) 1513 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 1514 string message(129, 'a'); 1515 1516 EXPECT_EQ(ErrorCode::OK, 1517 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder() 1518 .Digest(Digest::NONE) 1519 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 1520 string signature; 1521 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature)); 1522} 1523 1524/* 1525 * SigningOperationsTest.RsaPssSha512TooSmallKey 1526 * 1527 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when 1528 * used with a key that is too small for the message. 1529 * 1530 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the keymaster 1531 * specification requires that salt_size == digest_size, so the message will be digest_size * 2 + 1532 * 16. Such a message can only be signed by a given key if the key is at least that size. This test 1533 * uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large for a 1534 * 1024-bit key. 1535 */ 1536TEST_F(SigningOperationsTest, RsaPssSha512TooSmallKey) { 1537 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1538 .RsaSigningKey(1024, 3) 1539 .Digest(Digest::SHA_2_512) 1540 .Authorization(TAG_NO_AUTH_REQUIRED) 1541 .Padding(PaddingMode::RSA_PSS))); 1542 EXPECT_EQ( 1543 ErrorCode::INCOMPATIBLE_DIGEST, 1544 Begin(KeyPurpose::SIGN, 1545 AuthorizationSetBuilder().Digest(Digest::SHA_2_512).Padding(PaddingMode::RSA_PSS))) 1546 << "(Possibly b/33346750)"; 1547} 1548 1549/* 1550 * SigningOperationsTest.RsaNoPaddingTooLong 1551 * 1552 * Verifies that raw RSA signature operations fail with the correct error code when 1553 * given a too-long message. 1554 */ 1555TEST_F(SigningOperationsTest, RsaNoPaddingTooLong) { 1556 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1557 .RsaSigningKey(1024, 3) 1558 .Digest(Digest::NONE) 1559 .Authorization(TAG_NO_AUTH_REQUIRED) 1560 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 1561 // One byte too long 1562 string message(1024 / 8 + 1, 'a'); 1563 ASSERT_EQ(ErrorCode::OK, 1564 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder() 1565 .Digest(Digest::NONE) 1566 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 1567 string result; 1568 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result)); 1569 1570 // Very large message that should exceed the transfer buffer size of any reasonable TEE. 1571 message = string(128 * 1024, 'a'); 1572 ASSERT_EQ(ErrorCode::OK, 1573 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder() 1574 .Digest(Digest::NONE) 1575 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 1576 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result)); 1577} 1578 1579/* 1580 * SigningOperationsTest.RsaAbort 1581 * 1582 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the test, 1583 * but the behavior should be algorithm and purpose-independent. 1584 */ 1585TEST_F(SigningOperationsTest, RsaAbort) { 1586 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1587 .RsaSigningKey(1024, 3) 1588 .Digest(Digest::NONE) 1589 .Authorization(TAG_NO_AUTH_REQUIRED) 1590 .Padding(PaddingMode::NONE))); 1591 1592 ASSERT_EQ(ErrorCode::OK, 1593 Begin(KeyPurpose::SIGN, 1594 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE))); 1595 EXPECT_EQ(ErrorCode::OK, Abort(op_handle_)); 1596 1597 // Another abort should fail 1598 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort(op_handle_)); 1599 1600 // Set to sentinel, so TearDown() doesn't try to abort again. 1601 op_handle_ = kOpHandleSentinel; 1602} 1603 1604/* 1605 * SigningOperationsTest.RsaUnsupportedPadding 1606 * 1607 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used with a 1608 * padding mode inappropriate for RSA. 1609 */ 1610TEST_F(SigningOperationsTest, RsaUnsupportedPadding) { 1611 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1612 .RsaSigningKey(1024, 3) 1613 .Authorization(TAG_NO_AUTH_REQUIRED) 1614 .Digest(Digest::SHA_2_256 /* supported digest */) 1615 .Padding(PaddingMode::PKCS7))); 1616 ASSERT_EQ( 1617 ErrorCode::UNSUPPORTED_PADDING_MODE, 1618 Begin(KeyPurpose::SIGN, 1619 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7))); 1620} 1621 1622/* 1623 * SigningOperationsTest.RsaPssNoDigest 1624 * 1625 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest. 1626 */ 1627TEST_F(SigningOperationsTest, RsaNoDigest) { 1628 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1629 .RsaSigningKey(1024, 3) 1630 .Authorization(TAG_NO_AUTH_REQUIRED) 1631 .Digest(Digest::NONE) 1632 .Padding(PaddingMode::RSA_PSS))); 1633 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, 1634 Begin(KeyPurpose::SIGN, 1635 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS))); 1636 1637 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST, 1638 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS))); 1639} 1640 1641/* 1642 * SigningOperationsTest.RsaPssNoDigest 1643 * 1644 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is 1645 * supported in some cases (as validated in other tests), but a mode must be specified. 1646 */ 1647TEST_F(SigningOperationsTest, RsaNoPadding) { 1648 // Padding must be specified 1649 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1650 .RsaKey(1024, 3) 1651 .Authorization(TAG_NO_AUTH_REQUIRED) 1652 .SigningKey() 1653 .Digest(Digest::NONE))); 1654 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, 1655 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE))); 1656} 1657 1658/* 1659 * SigningOperationsTest.RsaShortMessage 1660 * 1661 * Verifies that raw RSA signatures succeed with a message shorter than the key size. 1662 */ 1663TEST_F(SigningOperationsTest, RsaTooShortMessage) { 1664 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1665 .Authorization(TAG_NO_AUTH_REQUIRED) 1666 .RsaSigningKey(1024, 3) 1667 .Digest(Digest::NONE) 1668 .Padding(PaddingMode::NONE))); 1669 1670 // Barely shorter 1671 string message(1024 / 8 - 1, 'a'); 1672 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)); 1673 1674 // Much shorter 1675 message = "a"; 1676 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)); 1677} 1678 1679/* 1680 * SigningOperationsTest.RsaSignWithEncryptionKey 1681 * 1682 * Verifies that RSA encryption keys cannot be used to sign. 1683 */ 1684TEST_F(SigningOperationsTest, RsaSignWithEncryptionKey) { 1685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1686 .Authorization(TAG_NO_AUTH_REQUIRED) 1687 .RsaEncryptionKey(1024, 3) 1688 .Digest(Digest::NONE) 1689 .Padding(PaddingMode::NONE))); 1690 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, 1691 Begin(KeyPurpose::SIGN, 1692 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE))); 1693} 1694 1695/* 1696 * SigningOperationsTest.RsaSignTooLargeMessage 1697 * 1698 * Verifies that attempting a raw signature of a message which is the same length as the key, but 1699 * numerically larger than the public modulus, fails with the correct error. 1700 */ 1701TEST_F(SigningOperationsTest, RsaSignTooLargeMessage) { 1702 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1703 .Authorization(TAG_NO_AUTH_REQUIRED) 1704 .RsaSigningKey(1024, 3) 1705 .Digest(Digest::NONE) 1706 .Padding(PaddingMode::NONE))); 1707 1708 // Largest possible message will always be larger than the public modulus. 1709 string message(1024 / 8, static_cast<char>(0xff)); 1710 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder() 1711 .Authorization(TAG_NO_AUTH_REQUIRED) 1712 .Digest(Digest::NONE) 1713 .Padding(PaddingMode::NONE))); 1714 string signature; 1715 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature)); 1716} 1717 1718/* 1719 * SigningOperationsTest.EcdsaAllSizesAndHashes 1720 * 1721 * Verifies that ECDSA operations succeed with all possible key sizes and hashes. 1722 */ 1723TEST_F(SigningOperationsTest, EcdsaAllSizesAndHashes) { 1724 for (auto key_size : {224, 256, 384, 521}) { 1725 for (auto digest : { 1726 Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384, 1727 Digest::SHA_2_512, 1728 }) { 1729 ErrorCode error = GenerateKey(AuthorizationSetBuilder() 1730 .Authorization(TAG_NO_AUTH_REQUIRED) 1731 .EcdsaSigningKey(key_size) 1732 .Digest(digest)); 1733 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size 1734 << " and digest " << digest; 1735 if (error != ErrorCode::OK) continue; 1736 1737 string message(1024, 'a'); 1738 if (digest == Digest::NONE) message.resize(key_size / 8); 1739 SignMessage(message, AuthorizationSetBuilder().Digest(digest)); 1740 CheckedDeleteKey(); 1741 } 1742 } 1743} 1744 1745/* 1746 * SigningOperationsTest.EcdsaAllCurves 1747 * 1748 * Verifies that ECDSA operations succeed with all possible curves. 1749 */ 1750TEST_F(SigningOperationsTest, EcdsaAllCurves) { 1751 for (auto curve : {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}) { 1752 ErrorCode error = GenerateKey(AuthorizationSetBuilder() 1753 .Authorization(TAG_NO_AUTH_REQUIRED) 1754 .EcdsaSigningKey(curve) 1755 .Digest(Digest::SHA_2_256)); 1756 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve; 1757 if (error != ErrorCode::OK) continue; 1758 1759 string message(1024, 'a'); 1760 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)); 1761 CheckedDeleteKey(); 1762 } 1763} 1764 1765/* 1766 * SigningOperationsTest.EcdsaNoDigestHugeData 1767 * 1768 * Verifies that ECDSA operations support very large messages, even without digesting. This should 1769 * work because ECDSA actually only signs the leftmost L_n bits of the message, however large it may 1770 * be. Not using digesting is a bad idea, but in some cases digesting is done by the framework. 1771 */ 1772TEST_F(SigningOperationsTest, EcdsaNoDigestHugeData) { 1773 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1774 .Authorization(TAG_NO_AUTH_REQUIRED) 1775 .EcdsaSigningKey(224) 1776 .Digest(Digest::NONE))); 1777 string message(2 * 1024, 'a'); 1778 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE)); 1779} 1780 1781/* 1782 * SigningOperationsTest.AesEcbSign 1783 * 1784 * Verifies that attempts to use AES keys to sign fail in the correct way. 1785 */ 1786TEST_F(SigningOperationsTest, AesEcbSign) { 1787 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1788 .Authorization(TAG_NO_AUTH_REQUIRED) 1789 .SigningKey() 1790 .AesEncryptionKey(128) 1791 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB))) 1792 << "(Possibly b/36252957)"; 1793 1794 AuthorizationSet out_params; 1795 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, 1796 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params)) 1797 << "(Possibly b/36233187)"; 1798 1799 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, 1800 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params)) 1801 << "(Possibly b/36233187)"; 1802} 1803 1804/* 1805 * SigningOperationsTest.HmacAllDigests 1806 * 1807 * Verifies that HMAC works with all digests. 1808 */ 1809TEST_F(SigningOperationsTest, HmacAllDigests) { 1810 for (auto digest : {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384, 1811 Digest::SHA_2_512}) { 1812 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1813 .Authorization(TAG_NO_AUTH_REQUIRED) 1814 .HmacKey(128) 1815 .Digest(digest) 1816 .Authorization(TAG_MIN_MAC_LENGTH, 160))) 1817 << "Failed to create HMAC key with digest " << digest; 1818 string message = "12345678901234567890123456789012"; 1819 string signature = MacMessage(message, digest, 160); 1820 EXPECT_EQ(160U / 8U, signature.size()) 1821 << "Failed to sign with HMAC key with digest " << digest; 1822 CheckedDeleteKey(); 1823 } 1824} 1825 1826/* 1827 * SigningOperationsTest.HmacSha256TooLargeMacLength 1828 * 1829 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the digest 1830 * size. 1831 */ 1832TEST_F(SigningOperationsTest, HmacSha256TooLargeMacLength) { 1833 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1834 .Authorization(TAG_NO_AUTH_REQUIRED) 1835 .HmacKey(128) 1836 .Digest(Digest::SHA_2_256) 1837 .Authorization(TAG_MIN_MAC_LENGTH, 256))); 1838 AuthorizationSet output_params; 1839 EXPECT_EQ( 1840 ErrorCode::UNSUPPORTED_MAC_LENGTH, 1841 Begin( 1842 KeyPurpose::SIGN, key_blob_, 1843 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 264), 1844 &output_params, &op_handle_)); 1845} 1846 1847/* 1848 * SigningOperationsTest.HmacSha256TooSmallMacLength 1849 * 1850 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the 1851 * specified minimum MAC length. 1852 */ 1853TEST_F(SigningOperationsTest, HmacSha256TooSmallMacLength) { 1854 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 1855 .Authorization(TAG_NO_AUTH_REQUIRED) 1856 .HmacKey(128) 1857 .Digest(Digest::SHA_2_256) 1858 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 1859 AuthorizationSet output_params; 1860 EXPECT_EQ( 1861 ErrorCode::INVALID_MAC_LENGTH, 1862 Begin( 1863 KeyPurpose::SIGN, key_blob_, 1864 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 120), 1865 &output_params, &op_handle_)); 1866} 1867 1868/* 1869 * SigningOperationsTest.HmacRfc4231TestCase3 1870 * 1871 * Validates against the test vectors from RFC 4231 test case 3. 1872 */ 1873TEST_F(SigningOperationsTest, HmacRfc4231TestCase3) { 1874 string key(20, 0xaa); 1875 string message(50, 0xdd); 1876 uint8_t sha_224_expected[] = { 1877 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a, 1878 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea, 1879 }; 1880 uint8_t sha_256_expected[] = { 1881 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8, 1882 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8, 1883 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe, 1884 }; 1885 uint8_t sha_384_expected[] = { 1886 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0, 1887 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb, 1888 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d, 1889 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27, 1890 }; 1891 uint8_t sha_512_expected[] = { 1892 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c, 1893 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8, 1894 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22, 1895 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37, 1896 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb, 1897 }; 1898 1899 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected)); 1900 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected)); 1901 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected)); 1902 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected)); 1903} 1904 1905/* 1906 * SigningOperationsTest.HmacRfc4231TestCase5 1907 * 1908 * Validates against the test vectors from RFC 4231 test case 5. 1909 */ 1910TEST_F(SigningOperationsTest, HmacRfc4231TestCase5) { 1911 string key(20, 0x0c); 1912 string message = "Test With Truncation"; 1913 1914 uint8_t sha_224_expected[] = { 1915 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37, 1916 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8, 1917 }; 1918 uint8_t sha_256_expected[] = { 1919 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0, 1920 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b, 1921 }; 1922 uint8_t sha_384_expected[] = { 1923 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23, 1924 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97, 1925 }; 1926 uint8_t sha_512_expected[] = { 1927 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53, 1928 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6, 1929 }; 1930 1931 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected)); 1932 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected)); 1933 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected)); 1934 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected)); 1935} 1936 1937/* 1938 * SigningOperationsTest.HmacRfc4231TestCase6 1939 * 1940 * Validates against the test vectors from RFC 4231 test case 6. 1941 */ 1942TEST_F(SigningOperationsTest, HmacRfc4231TestCase6) { 1943 string key(131, 0xaa); 1944 string message = "Test Using Larger Than Block-Size Key - Hash Key First"; 1945 1946 uint8_t sha_224_expected[] = { 1947 0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d, 1948 0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e, 1949 }; 1950 uint8_t sha_256_expected[] = { 1951 0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 1952 0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 1953 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54, 1954 }; 1955 uint8_t sha_384_expected[] = { 1956 0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a, 1957 0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f, 1958 0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab, 1959 0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52, 1960 }; 1961 uint8_t sha_512_expected[] = { 1962 0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd, 1963 0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b, 1964 0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25, 1965 0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73, 1966 0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98, 1967 }; 1968 1969 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected)); 1970 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected)); 1971 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected)); 1972 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected)); 1973} 1974 1975/* 1976 * SigningOperationsTest.HmacRfc4231TestCase7 1977 * 1978 * Validates against the test vectors from RFC 4231 test case 7. 1979 */ 1980TEST_F(SigningOperationsTest, HmacRfc4231TestCase7) { 1981 string key(131, 0xaa); 1982 string message = "This is a test using a larger than block-size key and a larger than " 1983 "block-size data. The key needs to be hashed before being used by the HMAC " 1984 "algorithm."; 1985 1986 uint8_t sha_224_expected[] = { 1987 0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3, 1988 0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1, 1989 }; 1990 uint8_t sha_256_expected[] = { 1991 0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f, 1992 0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07, 1993 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2, 1994 }; 1995 uint8_t sha_384_expected[] = { 1996 0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25, 1997 0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a, 1998 0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31, 1999 0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e, 2000 }; 2001 uint8_t sha_512_expected[] = { 2002 0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e, 2003 0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5, 2004 0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82, 2005 0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb, 2006 0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58, 2007 }; 2008 2009 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected)); 2010 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected)); 2011 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected)); 2012 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected)); 2013} 2014 2015typedef KeymasterHidlTest VerificationOperationsTest; 2016 2017/* 2018 * VerificationOperationsTest.RsaSuccess 2019 * 2020 * Verifies that a simple RSA signature/verification sequence succeeds. 2021 */ 2022TEST_F(VerificationOperationsTest, RsaSuccess) { 2023 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2024 .Authorization(TAG_NO_AUTH_REQUIRED) 2025 .RsaSigningKey(1024, 3) 2026 .Digest(Digest::NONE) 2027 .Padding(PaddingMode::NONE))); 2028 string message = "12345678901234567890123456789012"; 2029 string signature = SignMessage( 2030 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)); 2031 VerifyMessage(message, signature, 2032 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)); 2033} 2034 2035/* 2036 * VerificationOperationsTest.RsaSuccess 2037 * 2038 * Verifies RSA signature/verification for all padding modes and digests. 2039 */ 2040TEST_F(VerificationOperationsTest, RsaAllPaddingsAndDigests) { 2041 ASSERT_EQ(ErrorCode::OK, 2042 GenerateKey(AuthorizationSetBuilder() 2043 .Authorization(TAG_NO_AUTH_REQUIRED) 2044 .RsaSigningKey(2048, 3) 2045 .Digest(Digest::NONE, Digest::MD5, Digest::SHA1, Digest::SHA_2_224, 2046 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512) 2047 .Padding(PaddingMode::NONE) 2048 .Padding(PaddingMode::RSA_PSS) 2049 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN))); 2050 2051 string message(128, 'a'); 2052 string corrupt_message(message); 2053 ++corrupt_message[corrupt_message.size() / 2]; 2054 2055 for (auto padding : 2056 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) { 2057 2058 for (auto digest : {Digest::NONE, Digest::MD5, Digest::SHA1, Digest::SHA_2_224, 2059 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}) { 2060 if (padding == PaddingMode::NONE && digest != Digest::NONE) { 2061 // Digesting only makes sense with padding. 2062 continue; 2063 } 2064 2065 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) { 2066 // PSS requires digesting. 2067 continue; 2068 } 2069 2070 string signature = 2071 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding)); 2072 VerifyMessage(message, signature, 2073 AuthorizationSetBuilder().Digest(digest).Padding(padding)); 2074 2075 if (digest != Digest::NONE) { 2076 // Verify with OpenSSL. 2077 HidlBuf pubkey; 2078 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey)); 2079 2080 const uint8_t* p = pubkey.data(); 2081 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size())); 2082 ASSERT_TRUE(pkey.get()); 2083 2084 EVP_MD_CTX digest_ctx; 2085 EVP_MD_CTX_init(&digest_ctx); 2086 EVP_PKEY_CTX* pkey_ctx; 2087 const EVP_MD* md = openssl_digest(digest); 2088 ASSERT_NE(md, nullptr); 2089 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr /* engine */, 2090 pkey.get())); 2091 2092 switch (padding) { 2093 case PaddingMode::RSA_PSS: 2094 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0); 2095 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0); 2096 break; 2097 case PaddingMode::RSA_PKCS1_1_5_SIGN: 2098 // PKCS1 is the default; don't need to set anything. 2099 break; 2100 default: 2101 FAIL(); 2102 break; 2103 } 2104 2105 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size())); 2106 EXPECT_EQ(1, EVP_DigestVerifyFinal( 2107 &digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()), 2108 signature.size())); 2109 EVP_MD_CTX_cleanup(&digest_ctx); 2110 } 2111 2112 // Corrupt signature shouldn't verify. 2113 string corrupt_signature(signature); 2114 ++corrupt_signature[corrupt_signature.size() / 2]; 2115 2116 EXPECT_EQ(ErrorCode::OK, 2117 Begin(KeyPurpose::VERIFY, 2118 AuthorizationSetBuilder().Digest(digest).Padding(padding))); 2119 string result; 2120 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result)); 2121 2122 // Corrupt message shouldn't verify 2123 EXPECT_EQ(ErrorCode::OK, 2124 Begin(KeyPurpose::VERIFY, 2125 AuthorizationSetBuilder().Digest(digest).Padding(padding))); 2126 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result)); 2127 } 2128 } 2129} 2130 2131/* 2132 * VerificationOperationsTest.RsaSuccess 2133 * 2134 * Verifies ECDSA signature/verification for all digests and curves. 2135 */ 2136TEST_F(VerificationOperationsTest, EcdsaAllDigestsAndCurves) { 2137 auto digests = { 2138 Digest::NONE, Digest::SHA1, Digest::SHA_2_224, 2139 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512, 2140 }; 2141 2142 string message = "1234567890"; 2143 string corrupt_message = "2234567890"; 2144 for (auto curve : {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}) { 2145 ErrorCode error = GenerateKey(AuthorizationSetBuilder() 2146 .Authorization(TAG_NO_AUTH_REQUIRED) 2147 .EcdsaSigningKey(curve) 2148 .Digest(digests)); 2149 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve; 2150 if (error != ErrorCode::OK) { 2151 continue; 2152 } 2153 2154 for (auto digest : digests) { 2155 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest)); 2156 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest)); 2157 2158 // Verify with OpenSSL 2159 if (digest != Digest::NONE) { 2160 HidlBuf pubkey; 2161 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey)) 2162 << curve << ' ' << digest; 2163 2164 const uint8_t* p = pubkey.data(); 2165 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size())); 2166 ASSERT_TRUE(pkey.get()); 2167 2168 EVP_MD_CTX digest_ctx; 2169 EVP_MD_CTX_init(&digest_ctx); 2170 EVP_PKEY_CTX* pkey_ctx; 2171 const EVP_MD* md = openssl_digest(digest); 2172 2173 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr /* engine */, 2174 pkey.get())) 2175 << curve << ' ' << digest; 2176 2177 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size())) 2178 << curve << ' ' << digest; 2179 2180 EXPECT_EQ(1, EVP_DigestVerifyFinal( 2181 &digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()), 2182 signature.size())) 2183 << curve << ' ' << digest; 2184 2185 EVP_MD_CTX_cleanup(&digest_ctx); 2186 } 2187 2188 // Corrupt signature shouldn't verify. 2189 string corrupt_signature(signature); 2190 ++corrupt_signature[corrupt_signature.size() / 2]; 2191 2192 EXPECT_EQ(ErrorCode::OK, 2193 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest))) 2194 << curve << ' ' << digest; 2195 2196 string result; 2197 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result)) 2198 << curve << ' ' << digest; 2199 2200 // Corrupt message shouldn't verify 2201 EXPECT_EQ(ErrorCode::OK, 2202 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest))) 2203 << curve << ' ' << digest; 2204 2205 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result)) 2206 << curve << ' ' << digest; 2207 } 2208 2209 auto rc = DeleteKey(); 2210 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED); 2211 } 2212} 2213 2214/* 2215 * VerificationOperationsTest.HmacSigningKeyCannotVerify 2216 * 2217 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify. 2218 */ 2219TEST_F(VerificationOperationsTest, HmacSigningKeyCannotVerify) { 2220 string key_material = "HelloThisIsAKey"; 2221 2222 HidlBuf signing_key, verification_key; 2223 KeyCharacteristics signing_key_chars, verification_key_chars; 2224 EXPECT_EQ(ErrorCode::OK, 2225 ImportKey(AuthorizationSetBuilder() 2226 .Authorization(TAG_NO_AUTH_REQUIRED) 2227 .Authorization(TAG_ALGORITHM, Algorithm::HMAC) 2228 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN) 2229 .Digest(Digest::SHA1) 2230 .Authorization(TAG_MIN_MAC_LENGTH, 160), 2231 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars)); 2232 EXPECT_EQ(ErrorCode::OK, 2233 ImportKey(AuthorizationSetBuilder() 2234 .Authorization(TAG_NO_AUTH_REQUIRED) 2235 .Authorization(TAG_ALGORITHM, Algorithm::HMAC) 2236 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY) 2237 .Digest(Digest::SHA1) 2238 .Authorization(TAG_MIN_MAC_LENGTH, 160), 2239 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars)); 2240 2241 string message = "This is a message."; 2242 string signature = SignMessage( 2243 signing_key, message, 2244 AuthorizationSetBuilder().Digest(Digest::SHA1).Authorization(TAG_MAC_LENGTH, 160)); 2245 2246 // Signing key should not work. 2247 AuthorizationSet out_params; 2248 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, 2249 Begin(KeyPurpose::VERIFY, signing_key, AuthorizationSetBuilder().Digest(Digest::SHA1), 2250 &out_params, &op_handle_)); 2251 2252 // Verification key should work. 2253 VerifyMessage(verification_key, message, signature, 2254 AuthorizationSetBuilder().Digest(Digest::SHA1)); 2255 2256 CheckedDeleteKey(&signing_key); 2257 CheckedDeleteKey(&verification_key); 2258} 2259 2260typedef KeymasterHidlTest ExportKeyTest; 2261 2262/* 2263 * ExportKeyTest.RsaUnsupportedKeyFormat 2264 * 2265 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error. 2266 */ 2267TEST_F(ExportKeyTest, RsaUnsupportedKeyFormat) { 2268 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2269 .RsaSigningKey(1024, 3) 2270 .Digest(Digest::NONE) 2271 .Padding(PaddingMode::NONE))); 2272 HidlBuf export_data; 2273 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::PKCS8, &export_data)); 2274} 2275 2276/* 2277 * ExportKeyTest.RsaCorruptedKeyBlob 2278 * 2279 * Verifies that attempting to export RSA keys from corrupted key blobs fails. This is essentially 2280 * a poor-man's key blob fuzzer. 2281 */ 2282// Disabled due to b/33385206 2283TEST_F(ExportKeyTest, DISABLED_RsaCorruptedKeyBlob) { 2284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2285 .Authorization(TAG_NO_AUTH_REQUIRED) 2286 .RsaSigningKey(1024, 3) 2287 .Digest(Digest::NONE) 2288 .Padding(PaddingMode::NONE))); 2289 for (size_t i = 0; i < key_blob_.size(); ++i) { 2290 HidlBuf corrupted(key_blob_); 2291 ++corrupted[i]; 2292 2293 HidlBuf export_data; 2294 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, 2295 ExportKey(KeyFormat::X509, corrupted, HidlBuf(), HidlBuf(), &export_data)) 2296 << "Blob corrupted at offset " << i << " erroneously accepted as valid"; 2297 } 2298} 2299 2300/* 2301 * ExportKeyTest.RsaCorruptedKeyBlob 2302 * 2303 * Verifies that attempting to export ECDSA keys from corrupted key blobs fails. This is 2304 * essentially a poor-man's key blob fuzzer. 2305 */ 2306// Disabled due to b/33385206 2307TEST_F(ExportKeyTest, DISABLED_EcCorruptedKeyBlob) { 2308 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2309 .Authorization(TAG_NO_AUTH_REQUIRED) 2310 .EcdsaSigningKey(EcCurve::P_256) 2311 .Digest(Digest::NONE))); 2312 for (size_t i = 0; i < key_blob_.size(); ++i) { 2313 HidlBuf corrupted(key_blob_); 2314 ++corrupted[i]; 2315 2316 HidlBuf export_data; 2317 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, 2318 ExportKey(KeyFormat::X509, corrupted, HidlBuf(), HidlBuf(), &export_data)) 2319 << "Blob corrupted at offset " << i << " erroneously accepted as valid"; 2320 } 2321} 2322 2323/* 2324 * ExportKeyTest.AesKeyUnexportable 2325 * 2326 * Verifies that attempting to export AES keys fails in the expected way. 2327 */ 2328TEST_F(ExportKeyTest, AesKeyUnexportable) { 2329 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2330 .Authorization(TAG_NO_AUTH_REQUIRED) 2331 .AesEncryptionKey(128) 2332 .EcbMode() 2333 .Padding(PaddingMode::NONE))); 2334 2335 HidlBuf export_data; 2336 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::X509, &export_data)); 2337 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::PKCS8, &export_data)); 2338 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::RAW, &export_data)); 2339} 2340typedef KeymasterHidlTest ImportKeyTest; 2341 2342/* 2343 * ImportKeyTest.RsaSuccess 2344 * 2345 * Verifies that importing and using an RSA key pair works correctly. 2346 */ 2347TEST_F(ImportKeyTest, RsaSuccess) { 2348 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() 2349 .Authorization(TAG_NO_AUTH_REQUIRED) 2350 .RsaSigningKey(1024, 65537) 2351 .Digest(Digest::SHA_2_256) 2352 .Padding(PaddingMode::RSA_PSS), 2353 KeyFormat::PKCS8, rsa_key)); 2354 2355 CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::RSA); 2356 CheckKm0CryptoParam(TAG_KEY_SIZE, 1024U); 2357 CheckKm0CryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U); 2358 CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256); 2359 CheckKm1CryptoParam(TAG_PADDING, PaddingMode::RSA_PSS); 2360 CheckOrigin(); 2361 2362 string message(1024 / 8, 'a'); 2363 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS); 2364 string signature = SignMessage(message, params); 2365 VerifyMessage(message, signature, params); 2366} 2367 2368/* 2369 * ImportKeyTest.RsaKeySizeMismatch 2370 * 2371 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the 2372 * correct way. 2373 */ 2374TEST_F(ImportKeyTest, RsaKeySizeMismatch) { 2375 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH, 2376 ImportKey(AuthorizationSetBuilder() 2377 .RsaSigningKey(2048 /* Doesn't match key */, 65537) 2378 .Digest(Digest::NONE) 2379 .Padding(PaddingMode::NONE), 2380 KeyFormat::PKCS8, rsa_key)); 2381} 2382 2383/* 2384 * ImportKeyTest.RsaPublicExponentMismatch 2385 * 2386 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key fails 2387 * in the correct way. 2388 */ 2389TEST_F(ImportKeyTest, RsaPublicExponentMismatch) { 2390 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH, 2391 ImportKey(AuthorizationSetBuilder() 2392 .RsaSigningKey(1024, 3 /* Doesn't match key */) 2393 .Digest(Digest::NONE) 2394 .Padding(PaddingMode::NONE), 2395 KeyFormat::PKCS8, rsa_key)); 2396} 2397 2398/* 2399 * ImportKeyTest.EcdsaSuccess 2400 * 2401 * Verifies that importing and using an ECDSA P-256 key pair works correctly. 2402 */ 2403TEST_F(ImportKeyTest, EcdsaSuccess) { 2404 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() 2405 .Authorization(TAG_NO_AUTH_REQUIRED) 2406 .EcdsaSigningKey(256) 2407 .Digest(Digest::SHA_2_256), 2408 KeyFormat::PKCS8, ec_256_key)) 2409 << "(Possibly b/33945114)"; 2410 2411 CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::EC); 2412 CheckKm0CryptoParam(TAG_KEY_SIZE, 256U); 2413 CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256); 2414 CheckKm2CryptoParam(TAG_EC_CURVE, EcCurve::P_256); 2415 2416 CheckOrigin(); 2417 2418 string message(32, 'a'); 2419 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256); 2420 string signature = SignMessage(message, params); 2421 VerifyMessage(message, signature, params); 2422} 2423 2424/* 2425 * ImportKeyTest.Ecdsa521Success 2426 * 2427 * Verifies that importing and using an ECDSA P-521 key pair works correctly. 2428 */ 2429TEST_F(ImportKeyTest, Ecdsa521Success) { 2430 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() 2431 .Authorization(TAG_NO_AUTH_REQUIRED) 2432 .EcdsaSigningKey(521) 2433 .Digest(Digest::SHA_2_256), 2434 KeyFormat::PKCS8, ec_521_key)) 2435 << "(Possibly b/33945114)"; 2436 2437 CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::EC); 2438 CheckKm0CryptoParam(TAG_KEY_SIZE, 521U); 2439 CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256); 2440 CheckKm2CryptoParam(TAG_EC_CURVE, EcCurve::P_521); 2441 2442 CheckOrigin(); 2443 2444 string message(32, 'a'); 2445 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256); 2446 string signature = SignMessage(message, params); 2447 VerifyMessage(message, signature, params); 2448} 2449 2450/* 2451 * ImportKeyTest.EcdsaSizeMismatch 2452 * 2453 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the 2454 * correct way. 2455 */ 2456TEST_F(ImportKeyTest, EcdsaSizeMismatch) { 2457 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH, 2458 ImportKey(AuthorizationSetBuilder() 2459 .EcdsaSigningKey(224 /* Doesn't match key */) 2460 .Digest(Digest::NONE), 2461 KeyFormat::PKCS8, ec_256_key)); 2462} 2463 2464/* 2465 * ImportKeyTest.EcdsaCurveMismatch 2466 * 2467 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in the 2468 * correct way. 2469 */ 2470TEST_F(ImportKeyTest, EcdsaCurveMismatch) { 2471 if (SupportsSymmetric() && !SupportsAttestation()) { 2472 // KM1 hardware doesn't know about curves 2473 return; 2474 } 2475 2476 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH, 2477 ImportKey(AuthorizationSetBuilder() 2478 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */) 2479 .Digest(Digest::NONE), 2480 KeyFormat::PKCS8, ec_256_key)) 2481 << "(Possibly b/36233241)"; 2482} 2483 2484/* 2485 * ImportKeyTest.AesSuccess 2486 * 2487 * Verifies that importing and using an AES key works. 2488 */ 2489TEST_F(ImportKeyTest, AesSuccess) { 2490 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 2491 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() 2492 .Authorization(TAG_NO_AUTH_REQUIRED) 2493 .AesEncryptionKey(key.size() * 8) 2494 .EcbMode() 2495 .Padding(PaddingMode::PKCS7), 2496 KeyFormat::RAW, key)); 2497 2498 CheckKm1CryptoParam(TAG_ALGORITHM, Algorithm::AES); 2499 CheckKm1CryptoParam(TAG_KEY_SIZE, 128U); 2500 CheckKm1CryptoParam(TAG_PADDING, PaddingMode::PKCS7); 2501 CheckKm1CryptoParam(TAG_BLOCK_MODE, BlockMode::ECB); 2502 CheckOrigin(); 2503 2504 string message = "Hello World!"; 2505 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7); 2506 string ciphertext = EncryptMessage(message, params); 2507 string plaintext = DecryptMessage(ciphertext, params); 2508 EXPECT_EQ(message, plaintext); 2509} 2510 2511/* 2512 * ImportKeyTest.AesSuccess 2513 * 2514 * Verifies that importing and using an HMAC key works. 2515 */ 2516TEST_F(ImportKeyTest, HmacKeySuccess) { 2517 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 2518 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder() 2519 .Authorization(TAG_NO_AUTH_REQUIRED) 2520 .HmacKey(key.size() * 8) 2521 .Digest(Digest::SHA_2_256) 2522 .Authorization(TAG_MIN_MAC_LENGTH, 256), 2523 KeyFormat::RAW, key)); 2524 2525 CheckKm1CryptoParam(TAG_ALGORITHM, Algorithm::HMAC); 2526 CheckKm1CryptoParam(TAG_KEY_SIZE, 128U); 2527 CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256); 2528 CheckOrigin(); 2529 2530 string message = "Hello World!"; 2531 string signature = MacMessage(message, Digest::SHA_2_256, 256); 2532 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)); 2533} 2534 2535typedef KeymasterHidlTest EncryptionOperationsTest; 2536 2537/* 2538 * EncryptionOperationsTest.RsaNoPaddingSuccess 2539 * 2540 * Verifies that raw RSA encryption works. 2541 */ 2542TEST_F(EncryptionOperationsTest, RsaNoPaddingSuccess) { 2543 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2544 .Authorization(TAG_NO_AUTH_REQUIRED) 2545 .RsaEncryptionKey(1024, 3) 2546 .Padding(PaddingMode::NONE))); 2547 2548 string message = string(1024 / 8, 'a'); 2549 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE); 2550 string ciphertext1 = EncryptMessage(message, params); 2551 EXPECT_EQ(1024U / 8, ciphertext1.size()); 2552 2553 string ciphertext2 = EncryptMessage(message, params); 2554 EXPECT_EQ(1024U / 8, ciphertext2.size()); 2555 2556 // Unpadded RSA is deterministic 2557 EXPECT_EQ(ciphertext1, ciphertext2); 2558} 2559 2560/* 2561 * EncryptionOperationsTest.RsaNoPaddingShortMessage 2562 * 2563 * Verifies that raw RSA encryption of short messages works. 2564 */ 2565TEST_F(EncryptionOperationsTest, RsaNoPaddingShortMessage) { 2566 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2567 .Authorization(TAG_NO_AUTH_REQUIRED) 2568 .RsaEncryptionKey(1024, 3) 2569 .Padding(PaddingMode::NONE))); 2570 2571 string message = "1"; 2572 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE); 2573 2574 string ciphertext = EncryptMessage(message, params); 2575 EXPECT_EQ(1024U / 8, ciphertext.size()); 2576 2577 string expected_plaintext = string(1024 / 8 - 1, 0) + message; 2578 string plaintext = DecryptMessage(ciphertext, params); 2579 2580 EXPECT_EQ(expected_plaintext, plaintext); 2581 2582 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext. 2583 message = static_cast<char>(1); 2584 ciphertext = EncryptMessage(message, params); 2585 EXPECT_EQ(1024U / 8, ciphertext.size()); 2586 EXPECT_EQ(ciphertext, string(1024 / 8 - 1, 0) + message); 2587} 2588 2589/* 2590 * EncryptionOperationsTest.RsaNoPaddingTooLong 2591 * 2592 * Verifies that raw RSA encryption of too-long messages fails in the expected way. 2593 */ 2594TEST_F(EncryptionOperationsTest, RsaNoPaddingTooLong) { 2595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2596 .Authorization(TAG_NO_AUTH_REQUIRED) 2597 .RsaEncryptionKey(1024, 3) 2598 .Padding(PaddingMode::NONE))); 2599 2600 string message(1024 / 8 + 1, 'a'); 2601 2602 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE); 2603 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params)); 2604 2605 string result; 2606 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result)); 2607} 2608 2609/* 2610 * EncryptionOperationsTest.RsaNoPaddingTooLarge 2611 * 2612 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected way. 2613 */ 2614TEST_F(EncryptionOperationsTest, RsaNoPaddingTooLarge) { 2615 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2616 .Authorization(TAG_NO_AUTH_REQUIRED) 2617 .RsaEncryptionKey(1024, 3) 2618 .Padding(PaddingMode::NONE))); 2619 2620 HidlBuf exported; 2621 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &exported)); 2622 2623 const uint8_t* p = exported.data(); 2624 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size())); 2625 RSA_Ptr rsa(EVP_PKEY_get1_RSA(pkey.get())); 2626 2627 size_t modulus_len = BN_num_bytes(rsa->n); 2628 ASSERT_EQ(1024U / 8, modulus_len); 2629 std::unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]); 2630 BN_bn2bin(rsa->n, modulus_buf.get()); 2631 2632 // The modulus is too big to encrypt. 2633 string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len); 2634 2635 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE); 2636 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params)); 2637 2638 string result; 2639 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &result)); 2640 2641 // One smaller than the modulus is okay. 2642 BN_sub(rsa->n, rsa->n, BN_value_one()); 2643 modulus_len = BN_num_bytes(rsa->n); 2644 ASSERT_EQ(1024U / 8, modulus_len); 2645 BN_bn2bin(rsa->n, modulus_buf.get()); 2646 message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len); 2647 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params)); 2648 EXPECT_EQ(ErrorCode::OK, Finish(message, &result)); 2649} 2650 2651/* 2652 * EncryptionOperationsTest.RsaOaepSuccess 2653 * 2654 * Verifies that RSA-OAEP encryption operations work, with all digests. 2655 */ 2656TEST_F(EncryptionOperationsTest, RsaOaepSuccess) { 2657 auto digests = {Digest::MD5, Digest::SHA1, Digest::SHA_2_224, 2658 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}; 2659 2660 size_t key_size = 2048; // Need largish key for SHA-512 test. 2661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2662 .Authorization(TAG_NO_AUTH_REQUIRED) 2663 .RsaEncryptionKey(key_size, 3) 2664 .Padding(PaddingMode::RSA_OAEP) 2665 .Digest(digests))); 2666 2667 string message = "Hello"; 2668 2669 for (auto digest : digests) { 2670 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP); 2671 string ciphertext1 = EncryptMessage(message, params); 2672 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl; 2673 EXPECT_EQ(key_size / 8, ciphertext1.size()); 2674 2675 string ciphertext2 = EncryptMessage(message, params); 2676 EXPECT_EQ(key_size / 8, ciphertext2.size()); 2677 2678 // OAEP randomizes padding so every result should be different (with astronomically high 2679 // probability). 2680 EXPECT_NE(ciphertext1, ciphertext2); 2681 2682 string plaintext1 = DecryptMessage(ciphertext1, params); 2683 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest; 2684 string plaintext2 = DecryptMessage(ciphertext2, params); 2685 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest; 2686 2687 // Decrypting corrupted ciphertext should fail. 2688 size_t offset_to_corrupt = random() % ciphertext1.size(); 2689 char corrupt_byte; 2690 do { 2691 corrupt_byte = static_cast<char>(random() % 256); 2692 } while (corrupt_byte == ciphertext1[offset_to_corrupt]); 2693 ciphertext1[offset_to_corrupt] = corrupt_byte; 2694 2695 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params)); 2696 string result; 2697 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result)); 2698 EXPECT_EQ(0U, result.size()); 2699 } 2700} 2701 2702/* 2703 * EncryptionOperationsTest.RsaOaepInvalidDigest 2704 * 2705 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate 2706 * without a digest. 2707 */ 2708TEST_F(EncryptionOperationsTest, RsaOaepInvalidDigest) { 2709 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2710 .Authorization(TAG_NO_AUTH_REQUIRED) 2711 .RsaEncryptionKey(1024, 3) 2712 .Padding(PaddingMode::RSA_OAEP) 2713 .Digest(Digest::NONE))); 2714 string message = "Hello World!"; 2715 2716 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE); 2717 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params)); 2718} 2719 2720/* 2721 * EncryptionOperationsTest.RsaOaepInvalidDigest 2722 * 2723 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt with a 2724 * different digest than was used to encrypt. 2725 */ 2726TEST_F(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) { 2727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2728 .Authorization(TAG_NO_AUTH_REQUIRED) 2729 .RsaEncryptionKey(1024, 3) 2730 .Padding(PaddingMode::RSA_OAEP) 2731 .Digest(Digest::SHA_2_256, Digest::SHA_2_224))); 2732 string message = "Hello World!"; 2733 string ciphertext = EncryptMessage( 2734 message, 2735 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP)); 2736 2737 EXPECT_EQ( 2738 ErrorCode::OK, 2739 Begin(KeyPurpose::DECRYPT, 2740 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP))); 2741 string result; 2742 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result)); 2743 EXPECT_EQ(0U, result.size()); 2744} 2745 2746/* 2747 * EncryptionOperationsTest.RsaOaepTooLarge 2748 * 2749 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a 2750 * too-large message. 2751 */ 2752TEST_F(EncryptionOperationsTest, RsaOaepTooLarge) { 2753 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2754 .Authorization(TAG_NO_AUTH_REQUIRED) 2755 .RsaEncryptionKey(1024, 3) 2756 .Padding(PaddingMode::RSA_OAEP) 2757 .Digest(Digest::SHA1))); 2758 constexpr size_t digest_size = 160 /* SHA1 */ / 8; 2759 constexpr size_t oaep_overhead = 2 * digest_size + 2; 2760 string message(1024 / 8 - oaep_overhead + 1, 'a'); 2761 EXPECT_EQ(ErrorCode::OK, 2762 Begin(KeyPurpose::ENCRYPT, 2763 AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::SHA1))); 2764 string result; 2765 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result)); 2766 EXPECT_EQ(0U, result.size()); 2767} 2768 2769/* 2770 * EncryptionOperationsTest.RsaPkcs1Success 2771 * 2772 * Verifies that RSA PKCS encryption/decrypts works. 2773 */ 2774TEST_F(EncryptionOperationsTest, RsaPkcs1Success) { 2775 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2776 .Authorization(TAG_NO_AUTH_REQUIRED) 2777 .RsaEncryptionKey(1024, 3) 2778 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT))); 2779 2780 string message = "Hello World!"; 2781 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT); 2782 string ciphertext1 = EncryptMessage(message, params); 2783 EXPECT_EQ(1024U / 8, ciphertext1.size()); 2784 2785 string ciphertext2 = EncryptMessage(message, params); 2786 EXPECT_EQ(1024U / 8, ciphertext2.size()); 2787 2788 // PKCS1 v1.5 randomizes padding so every result should be different. 2789 EXPECT_NE(ciphertext1, ciphertext2); 2790 2791 string plaintext = DecryptMessage(ciphertext1, params); 2792 EXPECT_EQ(message, plaintext); 2793 2794 // Decrypting corrupted ciphertext should fail. 2795 size_t offset_to_corrupt = random() % ciphertext1.size(); 2796 char corrupt_byte; 2797 do { 2798 corrupt_byte = static_cast<char>(random() % 256); 2799 } while (corrupt_byte == ciphertext1[offset_to_corrupt]); 2800 ciphertext1[offset_to_corrupt] = corrupt_byte; 2801 2802 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params)); 2803 string result; 2804 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result)); 2805 EXPECT_EQ(0U, result.size()); 2806} 2807 2808/* 2809 * EncryptionOperationsTest.RsaPkcs1TooLarge 2810 * 2811 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large. 2812 */ 2813TEST_F(EncryptionOperationsTest, RsaPkcs1TooLarge) { 2814 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2815 .Authorization(TAG_NO_AUTH_REQUIRED) 2816 .RsaEncryptionKey(1024, 3) 2817 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT))); 2818 string message(1024 / 8 - 10, 'a'); 2819 2820 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT); 2821 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params)); 2822 string result; 2823 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result)); 2824 EXPECT_EQ(0U, result.size()); 2825} 2826 2827/* 2828 * EncryptionOperationsTest.EcdsaEncrypt 2829 * 2830 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way. 2831 */ 2832TEST_F(EncryptionOperationsTest, EcdsaEncrypt) { 2833 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2834 .Authorization(TAG_NO_AUTH_REQUIRED) 2835 .EcdsaSigningKey(224) 2836 .Digest(Digest::NONE))); 2837 auto params = AuthorizationSetBuilder().Digest(Digest::NONE); 2838 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params)) 2839 << "(Possibly b/33543625)"; 2840 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params)) 2841 << "(Possibly b/33543625)"; 2842} 2843 2844/* 2845 * EncryptionOperationsTest.HmacEncrypt 2846 * 2847 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way. 2848 */ 2849TEST_F(EncryptionOperationsTest, HmacEncrypt) { 2850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2851 .Authorization(TAG_NO_AUTH_REQUIRED) 2852 .HmacKey(128) 2853 .Digest(Digest::SHA_2_256) 2854 .Padding(PaddingMode::NONE) 2855 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 2856 auto params = AuthorizationSetBuilder() 2857 .Digest(Digest::SHA_2_256) 2858 .Padding(PaddingMode::NONE) 2859 .Authorization(TAG_MAC_LENGTH, 128); 2860 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params)) 2861 << "(Possibly b/33543625)"; 2862 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params)) 2863 << "(Possibly b/33543625)"; 2864} 2865 2866/* 2867 * EncryptionOperationsTest.AesEcbRoundTripSuccess 2868 * 2869 * Verifies that AES ECB mode works. 2870 */ 2871TEST_F(EncryptionOperationsTest, AesEcbRoundTripSuccess) { 2872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2873 .Authorization(TAG_NO_AUTH_REQUIRED) 2874 .AesEncryptionKey(128) 2875 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB) 2876 .Padding(PaddingMode::NONE))); 2877 2878 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE); 2879 2880 // Two-block message. 2881 string message = "12345678901234567890123456789012"; 2882 string ciphertext1 = EncryptMessage(message, params); 2883 EXPECT_EQ(message.size(), ciphertext1.size()); 2884 2885 string ciphertext2 = EncryptMessage(string(message), params); 2886 EXPECT_EQ(message.size(), ciphertext2.size()); 2887 2888 // ECB is deterministic. 2889 EXPECT_EQ(ciphertext1, ciphertext2); 2890 2891 string plaintext = DecryptMessage(ciphertext1, params); 2892 EXPECT_EQ(message, plaintext); 2893} 2894 2895/* 2896 * EncryptionOperationsTest.AesEcbRoundTripSuccess 2897 * 2898 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified. 2899 */ 2900TEST_F(EncryptionOperationsTest, AesWrongMode) { 2901 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2902 .Authorization(TAG_NO_AUTH_REQUIRED) 2903 .AesEncryptionKey(128) 2904 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC) 2905 .Padding(PaddingMode::NONE))); 2906 // Two-block message. 2907 string message = "12345678901234567890123456789012"; 2908 EXPECT_EQ( 2909 ErrorCode::INCOMPATIBLE_BLOCK_MODE, 2910 Begin(KeyPurpose::ENCRYPT, 2911 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE))); 2912} 2913 2914/* 2915 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize 2916 * 2917 * Verifies that AES encryption fails in the correct way when provided an input that is not a 2918 * multiple of the block size and no padding is specified. 2919 */ 2920TEST_F(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) { 2921 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2922 .Authorization(TAG_NO_AUTH_REQUIRED) 2923 .AesEncryptionKey(128) 2924 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB) 2925 .Padding(PaddingMode::NONE))); 2926 // Message is slightly shorter than two blocks. 2927 string message(16 * 2 - 1, 'a'); 2928 2929 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE); 2930 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params)); 2931 string ciphertext; 2932 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext)); 2933 EXPECT_EQ(0U, ciphertext.size()); 2934} 2935 2936/* 2937 * EncryptionOperationsTest.AesEcbPkcs7Padding 2938 * 2939 * Verifies that AES PKCS7 padding works for any message length. 2940 */ 2941TEST_F(EncryptionOperationsTest, AesEcbPkcs7Padding) { 2942 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2943 .Authorization(TAG_NO_AUTH_REQUIRED) 2944 .AesEncryptionKey(128) 2945 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB) 2946 .Padding(PaddingMode::PKCS7))); 2947 2948 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7); 2949 2950 // Try various message lengths; all should work. 2951 for (size_t i = 0; i < 32; ++i) { 2952 string message(i, 'a'); 2953 string ciphertext = EncryptMessage(message, params); 2954 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size()); 2955 string plaintext = DecryptMessage(ciphertext, params); 2956 EXPECT_EQ(message, plaintext); 2957 } 2958} 2959 2960/* 2961 * EncryptionOperationsTest.AesEcbWrongPadding 2962 * 2963 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is 2964 * specified. 2965 */ 2966TEST_F(EncryptionOperationsTest, AesEcbWrongPadding) { 2967 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2968 .Authorization(TAG_NO_AUTH_REQUIRED) 2969 .AesEncryptionKey(128) 2970 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB) 2971 .Padding(PaddingMode::NONE))); 2972 2973 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7); 2974 2975 // Try various message lengths; all should fail 2976 for (size_t i = 0; i < 32; ++i) { 2977 string message(i, 'a'); 2978 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params)); 2979 } 2980} 2981 2982/* 2983 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted 2984 * 2985 * Verifies that AES decryption fails in the correct way when the padding is corrupted. 2986 */ 2987TEST_F(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) { 2988 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 2989 .Authorization(TAG_NO_AUTH_REQUIRED) 2990 .AesEncryptionKey(128) 2991 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB) 2992 .Padding(PaddingMode::PKCS7))); 2993 2994 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7); 2995 2996 string message = "a"; 2997 string ciphertext = EncryptMessage(message, params); 2998 EXPECT_EQ(16U, ciphertext.size()); 2999 EXPECT_NE(ciphertext, message); 3000 ++ciphertext[ciphertext.size() / 2]; 3001 3002 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params)); 3003 string plaintext; 3004 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext)); 3005} 3006 3007HidlBuf CopyIv(const AuthorizationSet& set) { 3008 auto iv = set.GetTagValue(TAG_NONCE); 3009 EXPECT_TRUE(iv.isOk()); 3010 return iv.value(); 3011} 3012 3013/* 3014 * EncryptionOperationsTest.AesCtrRoundTripSuccess 3015 * 3016 * Verifies that AES CTR mode works. 3017 */ 3018TEST_F(EncryptionOperationsTest, AesCtrRoundTripSuccess) { 3019 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3020 .Authorization(TAG_NO_AUTH_REQUIRED) 3021 .AesEncryptionKey(128) 3022 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR) 3023 .Padding(PaddingMode::NONE))); 3024 3025 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE); 3026 3027 string message = "123"; 3028 AuthorizationSet out_params; 3029 string ciphertext1 = EncryptMessage(message, params, &out_params); 3030 HidlBuf iv1 = CopyIv(out_params); 3031 EXPECT_EQ(16U, iv1.size()); 3032 3033 EXPECT_EQ(message.size(), ciphertext1.size()); 3034 3035 out_params.Clear(); 3036 string ciphertext2 = EncryptMessage(message, params, &out_params); 3037 HidlBuf iv2 = CopyIv(out_params); 3038 EXPECT_EQ(16U, iv2.size()); 3039 3040 // IVs should be random, so ciphertexts should differ. 3041 EXPECT_NE(ciphertext1, ciphertext2); 3042 3043 auto params_iv1 = 3044 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1); 3045 auto params_iv2 = 3046 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2); 3047 3048 string plaintext = DecryptMessage(ciphertext1, params_iv1); 3049 EXPECT_EQ(message, plaintext); 3050 plaintext = DecryptMessage(ciphertext2, params_iv2); 3051 EXPECT_EQ(message, plaintext); 3052 3053 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage. 3054 plaintext = DecryptMessage(ciphertext1, params_iv2); 3055 EXPECT_NE(message, plaintext); 3056 plaintext = DecryptMessage(ciphertext2, params_iv1); 3057 EXPECT_NE(message, plaintext); 3058} 3059 3060/* 3061 * EncryptionOperationsTest.AesIncremental 3062 * 3063 * Verifies that AES works, all modes, when provided data in various size increments. 3064 */ 3065TEST_F(EncryptionOperationsTest, AesIncremental) { 3066 auto block_modes = { 3067 BlockMode::ECB, BlockMode::CBC, BlockMode::CTR, BlockMode::GCM, 3068 }; 3069 3070 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3071 .Authorization(TAG_NO_AUTH_REQUIRED) 3072 .AesEncryptionKey(128) 3073 .BlockMode(block_modes) 3074 .Padding(PaddingMode::NONE) 3075 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3076 3077 for (int increment = 1; increment <= 240; ++increment) { 3078 for (auto block_mode : block_modes) { 3079 string message(240, 'a'); 3080 auto params = AuthorizationSetBuilder() 3081 .BlockMode(block_mode) 3082 .Padding(PaddingMode::NONE) 3083 .Authorization(TAG_MAC_LENGTH, 128) /* for GCM */; 3084 3085 AuthorizationSet output_params; 3086 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params)); 3087 3088 string ciphertext; 3089 size_t input_consumed; 3090 string to_send; 3091 for (size_t i = 0; i < message.size(); i += increment) { 3092 to_send.append(message.substr(i, increment)); 3093 EXPECT_EQ(ErrorCode::OK, Update(to_send, &ciphertext, &input_consumed)); 3094 to_send = to_send.substr(input_consumed); 3095 3096 switch (block_mode) { 3097 case BlockMode::ECB: 3098 case BlockMode::CBC: 3099 // Implementations must take as many blocks as possible, leaving less than 3100 // a block. 3101 EXPECT_LE(to_send.length(), 16U); 3102 break; 3103 case BlockMode::GCM: 3104 case BlockMode::CTR: 3105 // Implementations must always take all the data. 3106 EXPECT_EQ(0U, to_send.length()); 3107 break; 3108 } 3109 } 3110 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) << "Error sending " << to_send; 3111 3112 switch (block_mode) { 3113 case BlockMode::GCM: 3114 EXPECT_EQ(message.size() + 16, ciphertext.size()); 3115 break; 3116 case BlockMode::CTR: 3117 EXPECT_EQ(message.size(), ciphertext.size()); 3118 break; 3119 case BlockMode::CBC: 3120 case BlockMode::ECB: 3121 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size()); 3122 break; 3123 } 3124 3125 auto iv = output_params.GetTagValue(TAG_NONCE); 3126 switch (block_mode) { 3127 case BlockMode::CBC: 3128 case BlockMode::GCM: 3129 case BlockMode::CTR: 3130 ASSERT_TRUE(iv.isOk()) << "No IV for block mode " << block_mode; 3131 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv.value().size()); 3132 params.push_back(TAG_NONCE, iv.value()); 3133 break; 3134 3135 case BlockMode::ECB: 3136 EXPECT_FALSE(iv.isOk()) << "ECB mode should not generate IV"; 3137 break; 3138 } 3139 3140 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params)) 3141 << "Decrypt begin() failed for block mode " << block_mode; 3142 3143 string plaintext; 3144 for (size_t i = 0; i < ciphertext.size(); i += increment) { 3145 to_send.append(ciphertext.substr(i, increment)); 3146 EXPECT_EQ(ErrorCode::OK, Update(to_send, &plaintext, &input_consumed)); 3147 to_send = to_send.substr(input_consumed); 3148 } 3149 ErrorCode error = Finish(to_send, &plaintext); 3150 ASSERT_EQ(ErrorCode::OK, error) 3151 << "Decryption failed for block mode " << block_mode << " and increment " 3152 << increment << " (Possibly b/33584622)"; 3153 if (error == ErrorCode::OK) { 3154 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " 3155 << block_mode << " and increment " << increment; 3156 } 3157 } 3158 } 3159} 3160 3161struct AesCtrSp80038aTestVector { 3162 const char* key; 3163 const char* nonce; 3164 const char* plaintext; 3165 const char* ciphertext; 3166}; 3167 3168// These test vectors are taken from 3169// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5. 3170static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = { 3171 // AES-128 3172 { 3173 "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", 3174 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51" 3175 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", 3176 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff" 3177 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee", 3178 }, 3179 // AES-192 3180 { 3181 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", 3182 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51" 3183 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", 3184 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94" 3185 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050", 3186 }, 3187 // AES-256 3188 { 3189 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", 3190 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", 3191 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51" 3192 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", 3193 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5" 3194 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6", 3195 }, 3196}; 3197 3198/* 3199 * EncryptionOperationsTest.AesCtrSp80038aTestVector 3200 * 3201 * Verifies AES CTR implementation against SP800-38A test vectors. 3202 */ 3203TEST_F(EncryptionOperationsTest, AesCtrSp80038aTestVector) { 3204 for (size_t i = 0; i < 3; i++) { 3205 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]); 3206 const string key = hex2str(test.key); 3207 const string nonce = hex2str(test.nonce); 3208 const string plaintext = hex2str(test.plaintext); 3209 const string ciphertext = hex2str(test.ciphertext); 3210 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext); 3211 } 3212} 3213 3214/* 3215 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode 3216 * 3217 * Verifies that keymaster rejects use of CTR mode with PKCS7 padding in the correct way. 3218 */ 3219TEST_F(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) { 3220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3221 .Authorization(TAG_NO_AUTH_REQUIRED) 3222 .AesEncryptionKey(128) 3223 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR) 3224 .Padding(PaddingMode::PKCS7))); 3225 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE); 3226 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params)); 3227} 3228 3229/* 3230 * EncryptionOperationsTest.AesCtrInvalidCallerNonce 3231 * 3232 * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce. 3233 */ 3234TEST_F(EncryptionOperationsTest, AesCtrInvalidCallerNonce) { 3235 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3236 .Authorization(TAG_NO_AUTH_REQUIRED) 3237 .AesEncryptionKey(128) 3238 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR) 3239 .Authorization(TAG_CALLER_NONCE) 3240 .Padding(PaddingMode::NONE))); 3241 3242 auto params = AuthorizationSetBuilder() 3243 .BlockMode(BlockMode::CTR) 3244 .Padding(PaddingMode::NONE) 3245 .Authorization(TAG_NONCE, HidlBuf(string(1, 'a'))); 3246 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params)); 3247 3248 params = AuthorizationSetBuilder() 3249 .BlockMode(BlockMode::CTR) 3250 .Padding(PaddingMode::NONE) 3251 .Authorization(TAG_NONCE, HidlBuf(string(15, 'a'))); 3252 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params)); 3253 3254 params = AuthorizationSetBuilder() 3255 .BlockMode(BlockMode::CTR) 3256 .Padding(PaddingMode::NONE) 3257 .Authorization(TAG_NONCE, HidlBuf(string(17, 'a'))); 3258 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params)); 3259} 3260 3261/* 3262 * EncryptionOperationsTest.AesCtrInvalidCallerNonce 3263 * 3264 * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce. 3265 */ 3266TEST_F(EncryptionOperationsTest, AesCbcRoundTripSuccess) { 3267 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3268 .Authorization(TAG_NO_AUTH_REQUIRED) 3269 .AesEncryptionKey(128) 3270 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC) 3271 .Padding(PaddingMode::NONE))); 3272 // Two-block message. 3273 string message = "12345678901234567890123456789012"; 3274 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE); 3275 AuthorizationSet out_params; 3276 string ciphertext1 = EncryptMessage(message, params, &out_params); 3277 HidlBuf iv1 = CopyIv(out_params); 3278 EXPECT_EQ(message.size(), ciphertext1.size()); 3279 3280 out_params.Clear(); 3281 3282 string ciphertext2 = EncryptMessage(message, params, &out_params); 3283 HidlBuf iv2 = CopyIv(out_params); 3284 EXPECT_EQ(message.size(), ciphertext2.size()); 3285 3286 // IVs should be random, so ciphertexts should differ. 3287 EXPECT_NE(ciphertext1, ciphertext2); 3288 3289 params.push_back(TAG_NONCE, iv1); 3290 string plaintext = DecryptMessage(ciphertext1, params); 3291 EXPECT_EQ(message, plaintext); 3292} 3293 3294/* 3295 * EncryptionOperationsTest.AesCallerNonce 3296 * 3297 * Verifies that AES caller-provided nonces work correctly. 3298 */ 3299TEST_F(EncryptionOperationsTest, AesCallerNonce) { 3300 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3301 .Authorization(TAG_NO_AUTH_REQUIRED) 3302 .AesEncryptionKey(128) 3303 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC) 3304 .Authorization(TAG_CALLER_NONCE) 3305 .Padding(PaddingMode::NONE))); 3306 3307 string message = "12345678901234567890123456789012"; 3308 3309 // Don't specify nonce, should get a random one. 3310 AuthorizationSetBuilder params = 3311 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE); 3312 AuthorizationSet out_params; 3313 string ciphertext = EncryptMessage(message, params, &out_params); 3314 EXPECT_EQ(message.size(), ciphertext.size()); 3315 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size()); 3316 3317 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value()); 3318 string plaintext = DecryptMessage(ciphertext, params); 3319 EXPECT_EQ(message, plaintext); 3320 3321 // Now specify a nonce, should also work. 3322 params = AuthorizationSetBuilder() 3323 .BlockMode(BlockMode::CBC) 3324 .Padding(PaddingMode::NONE) 3325 .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop")); 3326 out_params.Clear(); 3327 ciphertext = EncryptMessage(message, params, &out_params); 3328 3329 // Decrypt with correct nonce. 3330 plaintext = DecryptMessage(ciphertext, params); 3331 EXPECT_EQ(message, plaintext); 3332 3333 // Try with wrong nonce. 3334 params = AuthorizationSetBuilder() 3335 .BlockMode(BlockMode::CBC) 3336 .Padding(PaddingMode::NONE) 3337 .Authorization(TAG_NONCE, HidlBuf("aaaaaaaaaaaaaaaa")); 3338 plaintext = DecryptMessage(ciphertext, params); 3339 EXPECT_NE(message, plaintext); 3340} 3341 3342/* 3343 * EncryptionOperationsTest.AesCallerNonceProhibited 3344 * 3345 * Verifies that caller-provided nonces are not permitted when not specified in the key 3346 * authorizations. 3347 */ 3348TEST_F(EncryptionOperationsTest, AesCallerNonceProhibited) { 3349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3350 .Authorization(TAG_NO_AUTH_REQUIRED) 3351 .AesEncryptionKey(128) 3352 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC) 3353 .Padding(PaddingMode::NONE))); 3354 3355 string message = "12345678901234567890123456789012"; 3356 3357 // Don't specify nonce, should get a random one. 3358 AuthorizationSetBuilder params = 3359 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE); 3360 AuthorizationSet out_params; 3361 string ciphertext = EncryptMessage(message, params, &out_params); 3362 EXPECT_EQ(message.size(), ciphertext.size()); 3363 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size()); 3364 3365 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value()); 3366 string plaintext = DecryptMessage(ciphertext, params); 3367 EXPECT_EQ(message, plaintext); 3368 3369 // Now specify a nonce, should fail 3370 params = AuthorizationSetBuilder() 3371 .BlockMode(BlockMode::CBC) 3372 .Padding(PaddingMode::NONE) 3373 .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop")); 3374 out_params.Clear(); 3375 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params)); 3376} 3377 3378/* 3379 * EncryptionOperationsTest.AesGcmRoundTripSuccess 3380 * 3381 * Verifies that AES GCM mode works. 3382 */ 3383TEST_F(EncryptionOperationsTest, AesGcmRoundTripSuccess) { 3384 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3385 .Authorization(TAG_NO_AUTH_REQUIRED) 3386 .AesEncryptionKey(128) 3387 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM) 3388 .Padding(PaddingMode::NONE) 3389 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3390 3391 string aad = "foobar"; 3392 string message = "123456789012345678901234567890123456"; 3393 3394 auto begin_params = AuthorizationSetBuilder() 3395 .BlockMode(BlockMode::GCM) 3396 .Padding(PaddingMode::NONE) 3397 .Authorization(TAG_MAC_LENGTH, 128); 3398 3399 auto update_params = 3400 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size()); 3401 3402 // Encrypt 3403 AuthorizationSet begin_out_params; 3404 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params)) 3405 << "Begin encrypt"; 3406 string ciphertext; 3407 AuthorizationSet update_out_params; 3408 ASSERT_EQ(ErrorCode::OK, 3409 Finish(op_handle_, update_params, message, "", &update_out_params, &ciphertext)); 3410 3411 // Grab nonce 3412 begin_params.push_back(begin_out_params); 3413 3414 // Decrypt. 3415 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt"; 3416 string plaintext; 3417 size_t input_consumed; 3418 ASSERT_EQ(ErrorCode::OK, Update(op_handle_, update_params, ciphertext, &update_out_params, 3419 &plaintext, &input_consumed)); 3420 EXPECT_EQ(ciphertext.size(), input_consumed); 3421 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext)); 3422 3423 EXPECT_EQ(message, plaintext); 3424} 3425 3426/* 3427 * EncryptionOperationsTest.AesGcmTooShortTag 3428 * 3429 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified. 3430 */ 3431TEST_F(EncryptionOperationsTest, AesGcmTooShortTag) { 3432 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3433 .Authorization(TAG_NO_AUTH_REQUIRED) 3434 .AesEncryptionKey(128) 3435 .BlockMode(BlockMode::GCM) 3436 .Padding(PaddingMode::NONE) 3437 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3438 string message = "123456789012345678901234567890123456"; 3439 auto params = AuthorizationSetBuilder() 3440 .BlockMode(BlockMode::GCM) 3441 .Padding(PaddingMode::NONE) 3442 .Authorization(TAG_MAC_LENGTH, 96); 3443 3444 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params)); 3445} 3446 3447/* 3448 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt 3449 * 3450 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption. 3451 */ 3452TEST_F(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) { 3453 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3454 .Authorization(TAG_NO_AUTH_REQUIRED) 3455 .AesEncryptionKey(128) 3456 .BlockMode(BlockMode::GCM) 3457 .Padding(PaddingMode::NONE) 3458 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3459 string aad = "foobar"; 3460 string message = "123456789012345678901234567890123456"; 3461 auto params = AuthorizationSetBuilder() 3462 .BlockMode(BlockMode::GCM) 3463 .Padding(PaddingMode::NONE) 3464 .Authorization(TAG_MAC_LENGTH, 128); 3465 3466 auto finish_params = 3467 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size()); 3468 3469 // Encrypt 3470 AuthorizationSet begin_out_params; 3471 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params)); 3472 EXPECT_EQ(1U, begin_out_params.size()); 3473 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE).isOk()); 3474 3475 AuthorizationSet finish_out_params; 3476 string ciphertext; 3477 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */, 3478 &finish_out_params, &ciphertext)); 3479 3480 params = AuthorizationSetBuilder() 3481 .Authorizations(begin_out_params) 3482 .BlockMode(BlockMode::GCM) 3483 .Padding(PaddingMode::NONE) 3484 .Authorization(TAG_MAC_LENGTH, 96); 3485 3486 // Decrypt. 3487 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params)); 3488} 3489 3490/* 3491 * EncryptionOperationsTest.AesGcmCorruptKey 3492 * 3493 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect. 3494 */ 3495TEST_F(EncryptionOperationsTest, AesGcmCorruptKey) { 3496 const uint8_t nonce_bytes[] = { 3497 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f, 3498 }; 3499 string nonce = make_string(nonce_bytes); 3500 const uint8_t ciphertext_bytes[] = { 3501 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16, 3502 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 3503 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 3504 0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd, 3505 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0, 3506 }; 3507 string ciphertext = make_string(ciphertext_bytes); 3508 3509 auto params = AuthorizationSetBuilder() 3510 .BlockMode(BlockMode::GCM) 3511 .Padding(PaddingMode::NONE) 3512 .Authorization(TAG_MAC_LENGTH, 128) 3513 .Authorization(TAG_NONCE, nonce.data(), nonce.size()); 3514 3515 auto import_params = AuthorizationSetBuilder() 3516 .Authorization(TAG_NO_AUTH_REQUIRED) 3517 .AesEncryptionKey(128) 3518 .BlockMode(BlockMode::GCM) 3519 .Padding(PaddingMode::NONE) 3520 .Authorization(TAG_CALLER_NONCE) 3521 .Authorization(TAG_MIN_MAC_LENGTH, 128); 3522 3523 // Import correct key and decrypt 3524 const uint8_t key_bytes[] = { 3525 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d, 3526 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb, 3527 }; 3528 string key = make_string(key_bytes); 3529 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key)); 3530 string plaintext = DecryptMessage(ciphertext, params); 3531 CheckedDeleteKey(); 3532 3533 // Corrupt key and attempt to decrypt 3534 key[0] = 0; 3535 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key)); 3536 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params)); 3537 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext)); 3538 CheckedDeleteKey(); 3539} 3540 3541/* 3542 * EncryptionOperationsTest.AesGcmAadNoData 3543 * 3544 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to 3545 * encrypt. 3546 */ 3547TEST_F(EncryptionOperationsTest, AesGcmAadNoData) { 3548 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3549 .Authorization(TAG_NO_AUTH_REQUIRED) 3550 .AesEncryptionKey(128) 3551 .BlockMode(BlockMode::GCM) 3552 .Padding(PaddingMode::NONE) 3553 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3554 3555 string aad = "1234567890123456"; 3556 auto params = AuthorizationSetBuilder() 3557 .BlockMode(BlockMode::GCM) 3558 .Padding(PaddingMode::NONE) 3559 .Authorization(TAG_MAC_LENGTH, 128); 3560 3561 auto finish_params = 3562 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size()); 3563 3564 // Encrypt 3565 AuthorizationSet begin_out_params; 3566 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params)); 3567 string ciphertext; 3568 AuthorizationSet finish_out_params; 3569 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, "" /* input */, "" /* signature */, 3570 &finish_out_params, &ciphertext)); 3571 EXPECT_TRUE(finish_out_params.empty()); 3572 3573 // Grab nonce 3574 params.push_back(begin_out_params); 3575 3576 // Decrypt. 3577 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params)); 3578 string plaintext; 3579 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, ciphertext, "" /* signature */, 3580 &finish_out_params, &plaintext)) 3581 << "(Possibly b/33615032)"; 3582 3583 EXPECT_TRUE(finish_out_params.empty()); 3584 3585 EXPECT_EQ("", plaintext); 3586} 3587 3588/* 3589 * EncryptionOperationsTest.AesGcmMultiPartAad 3590 * 3591 * Verifies that AES GCM mode works when provided additional authenticated data in multiple chunks. 3592 */ 3593TEST_F(EncryptionOperationsTest, AesGcmMultiPartAad) { 3594 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3595 .Authorization(TAG_NO_AUTH_REQUIRED) 3596 .AesEncryptionKey(128) 3597 .BlockMode(BlockMode::GCM) 3598 .Padding(PaddingMode::NONE) 3599 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3600 3601 string message = "123456789012345678901234567890123456"; 3602 auto begin_params = AuthorizationSetBuilder() 3603 .BlockMode(BlockMode::GCM) 3604 .Padding(PaddingMode::NONE) 3605 .Authorization(TAG_MAC_LENGTH, 128); 3606 AuthorizationSet begin_out_params; 3607 3608 auto update_params = 3609 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3); 3610 3611 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params)); 3612 3613 // No data, AAD only. 3614 string ciphertext; 3615 size_t input_consumed; 3616 AuthorizationSet update_out_params; 3617 EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params, 3618 &ciphertext, &input_consumed)); 3619 EXPECT_EQ(0U, input_consumed); 3620 EXPECT_EQ(0U, ciphertext.size()); 3621 EXPECT_TRUE(update_out_params.empty()); 3622 3623 // AAD and data. 3624 EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params, 3625 &ciphertext, &input_consumed)); 3626 EXPECT_EQ(message.size(), input_consumed); 3627 EXPECT_EQ(message.size(), ciphertext.size()); 3628 EXPECT_TRUE(update_out_params.empty()); 3629 3630 EXPECT_EQ(ErrorCode::OK, Finish("" /* input */, &ciphertext)); 3631 3632 // Grab nonce. 3633 begin_params.push_back(begin_out_params); 3634 3635 // Decrypt 3636 update_params = 3637 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foofoo", (size_t)6); 3638 3639 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)); 3640 string plaintext; 3641 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, update_params, ciphertext, "" /* signature */, 3642 &update_out_params, &plaintext)); 3643 EXPECT_TRUE(update_out_params.empty()); 3644 EXPECT_EQ(message, plaintext); 3645} 3646 3647/* 3648 * EncryptionOperationsTest.AesGcmAadOutOfOrder 3649 * 3650 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher. 3651 */ 3652TEST_F(EncryptionOperationsTest, AesGcmAadOutOfOrder) { 3653 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3654 .Authorization(TAG_NO_AUTH_REQUIRED) 3655 .AesEncryptionKey(128) 3656 .BlockMode(BlockMode::GCM) 3657 .Padding(PaddingMode::NONE) 3658 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3659 3660 string message = "123456789012345678901234567890123456"; 3661 auto begin_params = AuthorizationSetBuilder() 3662 .BlockMode(BlockMode::GCM) 3663 .Padding(PaddingMode::NONE) 3664 .Authorization(TAG_MAC_LENGTH, 128); 3665 AuthorizationSet begin_out_params; 3666 3667 auto update_params = 3668 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3); 3669 3670 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params)); 3671 3672 // No data, AAD only. 3673 string ciphertext; 3674 size_t input_consumed; 3675 AuthorizationSet update_out_params; 3676 EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params, 3677 &ciphertext, &input_consumed)); 3678 EXPECT_EQ(0U, input_consumed); 3679 EXPECT_EQ(0U, ciphertext.size()); 3680 EXPECT_TRUE(update_out_params.empty()); 3681 3682 // AAD and data. 3683 EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params, 3684 &ciphertext, &input_consumed)); 3685 EXPECT_EQ(message.size(), input_consumed); 3686 EXPECT_EQ(message.size(), ciphertext.size()); 3687 EXPECT_TRUE(update_out_params.empty()); 3688 3689 // More AAD 3690 EXPECT_EQ(ErrorCode::INVALID_TAG, Update(op_handle_, update_params, "", &update_out_params, 3691 &ciphertext, &input_consumed)); 3692 3693 op_handle_ = kOpHandleSentinel; 3694} 3695 3696/* 3697 * EncryptionOperationsTest.AesGcmBadAad 3698 * 3699 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong. 3700 */ 3701TEST_F(EncryptionOperationsTest, AesGcmBadAad) { 3702 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3703 .Authorization(TAG_NO_AUTH_REQUIRED) 3704 .AesEncryptionKey(128) 3705 .BlockMode(BlockMode::GCM) 3706 .Padding(PaddingMode::NONE) 3707 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3708 3709 string message = "12345678901234567890123456789012"; 3710 auto begin_params = AuthorizationSetBuilder() 3711 .BlockMode(BlockMode::GCM) 3712 .Padding(PaddingMode::NONE) 3713 .Authorization(TAG_MAC_LENGTH, 128); 3714 3715 auto finish_params = 3716 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6); 3717 3718 // Encrypt 3719 AuthorizationSet begin_out_params; 3720 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params)); 3721 string ciphertext; 3722 AuthorizationSet finish_out_params; 3723 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */, 3724 &finish_out_params, &ciphertext)); 3725 3726 // Grab nonce 3727 begin_params.push_back(begin_out_params); 3728 3729 finish_params = AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, 3730 "barfoo" /* Wrong AAD */, (size_t)6); 3731 3732 // Decrypt. 3733 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params)); 3734 string plaintext; 3735 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, 3736 Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params, 3737 &plaintext)); 3738} 3739 3740/* 3741 * EncryptionOperationsTest.AesGcmWrongNonce 3742 * 3743 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect. 3744 */ 3745TEST_F(EncryptionOperationsTest, AesGcmWrongNonce) { 3746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3747 .Authorization(TAG_NO_AUTH_REQUIRED) 3748 .AesEncryptionKey(128) 3749 .BlockMode(BlockMode::GCM) 3750 .Padding(PaddingMode::NONE) 3751 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3752 3753 string message = "12345678901234567890123456789012"; 3754 auto begin_params = AuthorizationSetBuilder() 3755 .BlockMode(BlockMode::GCM) 3756 .Padding(PaddingMode::NONE) 3757 .Authorization(TAG_MAC_LENGTH, 128); 3758 3759 auto finish_params = 3760 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6); 3761 3762 // Encrypt 3763 AuthorizationSet begin_out_params; 3764 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params)); 3765 string ciphertext; 3766 AuthorizationSet finish_out_params; 3767 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */, 3768 &finish_out_params, &ciphertext)); 3769 3770 // Wrong nonce 3771 begin_params.push_back(TAG_NONCE, HidlBuf("123456789012")); 3772 3773 // Decrypt. 3774 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params)); 3775 string plaintext; 3776 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, 3777 Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params, 3778 &plaintext)); 3779 3780 // With wrong nonce, should have gotten garbage plaintext (or none). 3781 EXPECT_NE(message, plaintext); 3782} 3783 3784/* 3785 * EncryptionOperationsTest.AesGcmCorruptTag 3786 * 3787 * Verifies that AES GCM decryption fails correctly when the tag is wrong. 3788 */ 3789TEST_F(EncryptionOperationsTest, AesGcmCorruptTag) { 3790 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3791 .Authorization(TAG_NO_AUTH_REQUIRED) 3792 .AesEncryptionKey(128) 3793 .BlockMode(BlockMode::GCM) 3794 .Padding(PaddingMode::NONE) 3795 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 3796 3797 string aad = "1234567890123456"; 3798 string message = "123456789012345678901234567890123456"; 3799 3800 auto params = AuthorizationSetBuilder() 3801 .BlockMode(BlockMode::GCM) 3802 .Padding(PaddingMode::NONE) 3803 .Authorization(TAG_MAC_LENGTH, 128); 3804 3805 auto finish_params = 3806 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size()); 3807 3808 // Encrypt 3809 AuthorizationSet begin_out_params; 3810 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params)); 3811 string ciphertext; 3812 AuthorizationSet finish_out_params; 3813 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */, 3814 &finish_out_params, &ciphertext)); 3815 EXPECT_TRUE(finish_out_params.empty()); 3816 3817 // Corrupt tag 3818 ++(*ciphertext.rbegin()); 3819 3820 // Grab nonce 3821 params.push_back(begin_out_params); 3822 3823 // Decrypt. 3824 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params)); 3825 string plaintext; 3826 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, 3827 Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params, 3828 &plaintext)); 3829 EXPECT_TRUE(finish_out_params.empty()); 3830} 3831 3832typedef KeymasterHidlTest MaxOperationsTest; 3833 3834/* 3835 * MaxOperationsTest.TestLimitAes 3836 * 3837 * Verifies that the max uses per boot tag works correctly with AES keys. 3838 */ 3839TEST_F(MaxOperationsTest, TestLimitAes) { 3840 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3841 .Authorization(TAG_NO_AUTH_REQUIRED) 3842 .AesEncryptionKey(128) 3843 .EcbMode() 3844 .Padding(PaddingMode::NONE) 3845 .Authorization(TAG_MAX_USES_PER_BOOT, 3))); 3846 3847 string message = "1234567890123456"; 3848 3849 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE); 3850 3851 EncryptMessage(message, params); 3852 EncryptMessage(message, params); 3853 EncryptMessage(message, params); 3854 3855 // Fourth time should fail. 3856 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params)); 3857} 3858 3859/* 3860 * MaxOperationsTest.TestLimitAes 3861 * 3862 * Verifies that the max uses per boot tag works correctly with RSA keys. 3863 */ 3864TEST_F(MaxOperationsTest, TestLimitRsa) { 3865 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3866 .Authorization(TAG_NO_AUTH_REQUIRED) 3867 .RsaSigningKey(1024, 3) 3868 .NoDigestOrPadding() 3869 .Authorization(TAG_MAX_USES_PER_BOOT, 3))); 3870 3871 string message = "1234567890123456"; 3872 3873 auto params = AuthorizationSetBuilder().NoDigestOrPadding(); 3874 3875 SignMessage(message, params); 3876 SignMessage(message, params); 3877 SignMessage(message, params); 3878 3879 // Fourth time should fail. 3880 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params)); 3881} 3882 3883typedef KeymasterHidlTest AddEntropyTest; 3884 3885/* 3886 * AddEntropyTest.AddEntropy 3887 * 3888 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy is 3889 * actually added. 3890 */ 3891TEST_F(AddEntropyTest, AddEntropy) { 3892 EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf("foo"))); 3893} 3894 3895/* 3896 * AddEntropyTest.AddEmptyEntropy 3897 * 3898 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer. 3899 */ 3900TEST_F(AddEntropyTest, AddEmptyEntropy) { 3901 EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf())); 3902} 3903 3904/* 3905 * AddEntropyTest.AddLargeEntropy 3906 * 3907 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data. 3908 */ 3909TEST_F(AddEntropyTest, AddLargeEntropy) { 3910 EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf(string(2 * 1024, 'a')))); 3911} 3912 3913typedef KeymasterHidlTest AttestationTest; 3914 3915/* 3916 * AttestationTest.RsaAttestation 3917 * 3918 * Verifies that attesting to RSA keys works and generates the expected output. 3919 */ 3920TEST_F(AttestationTest, RsaAttestation) { 3921 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3922 .Authorization(TAG_NO_AUTH_REQUIRED) 3923 .RsaSigningKey(1024, 3) 3924 .Digest(Digest::NONE) 3925 .Padding(PaddingMode::NONE) 3926 .Authorization(TAG_INCLUDE_UNIQUE_ID))); 3927 3928 hidl_vec<hidl_vec<uint8_t>> cert_chain; 3929 ASSERT_EQ(ErrorCode::OK, 3930 AttestKey(AuthorizationSetBuilder() 3931 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")) 3932 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")), 3933 &cert_chain)); 3934 EXPECT_GE(cert_chain.size(), 2U); 3935 EXPECT_TRUE(verify_chain(cert_chain)); 3936 EXPECT_TRUE( 3937 verify_attestation_record("challenge", "foo", // 3938 key_characteristics_.softwareEnforced, // 3939 key_characteristics_.teeEnforced, // 3940 cert_chain[0])); 3941} 3942 3943/* 3944 * AttestationTest.RsaAttestationRequiresAppId 3945 * 3946 * Verifies that attesting to RSA requires app ID. 3947 */ 3948TEST_F(AttestationTest, RsaAttestationRequiresAppId) { 3949 ASSERT_EQ(ErrorCode::OK, 3950 GenerateKey(AuthorizationSetBuilder() 3951 .Authorization(TAG_NO_AUTH_REQUIRED) 3952 .RsaSigningKey(1024, 3) 3953 .Digest(Digest::NONE) 3954 .Padding(PaddingMode::NONE) 3955 .Authorization(TAG_INCLUDE_UNIQUE_ID))); 3956 3957 hidl_vec<hidl_vec<uint8_t>> cert_chain; 3958 EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, 3959 AttestKey(AuthorizationSetBuilder().Authorization( 3960 TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")), 3961 &cert_chain)); 3962} 3963 3964/* 3965 * AttestationTest.EcAttestation 3966 * 3967 * Verifies that attesting to EC keys works and generates the expected output. 3968 */ 3969TEST_F(AttestationTest, EcAttestation) { 3970 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 3971 .Authorization(TAG_NO_AUTH_REQUIRED) 3972 .EcdsaSigningKey(EcCurve::P_256) 3973 .Digest(Digest::SHA_2_256) 3974 .Authorization(TAG_INCLUDE_UNIQUE_ID))); 3975 3976 hidl_vec<hidl_vec<uint8_t>> cert_chain; 3977 ASSERT_EQ(ErrorCode::OK, 3978 AttestKey(AuthorizationSetBuilder() 3979 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")) 3980 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")), 3981 &cert_chain)); 3982 EXPECT_GE(cert_chain.size(), 2U); 3983 EXPECT_TRUE(verify_chain(cert_chain)); 3984 3985 EXPECT_TRUE( 3986 verify_attestation_record("challenge", "foo", // 3987 key_characteristics_.softwareEnforced, // 3988 key_characteristics_.teeEnforced, // 3989 cert_chain[0])); 3990} 3991 3992/* 3993 * AttestationTest.EcAttestationRequiresAttestationAppId 3994 * 3995 * Verifies that attesting to EC keys requires app ID 3996 */ 3997TEST_F(AttestationTest, EcAttestationRequiresAttestationAppId) { 3998 ASSERT_EQ(ErrorCode::OK, 3999 GenerateKey(AuthorizationSetBuilder() 4000 .Authorization(TAG_NO_AUTH_REQUIRED) 4001 .EcdsaSigningKey(EcCurve::P_256) 4002 .Digest(Digest::SHA_2_256) 4003 .Authorization(TAG_INCLUDE_UNIQUE_ID))); 4004 4005 hidl_vec<hidl_vec<uint8_t>> cert_chain; 4006 EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, 4007 AttestKey(AuthorizationSetBuilder().Authorization( 4008 TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")), 4009 &cert_chain)); 4010} 4011 4012/* 4013 * AttestationTest.AesAttestation 4014 * 4015 * Verifies that attesting to AES keys fails in the expected way. 4016 */ 4017TEST_F(AttestationTest, AesAttestation) { 4018 ASSERT_EQ(ErrorCode::OK, 4019 GenerateKey(AuthorizationSetBuilder() 4020 .Authorization(TAG_NO_AUTH_REQUIRED) 4021 .AesEncryptionKey(128) 4022 .EcbMode() 4023 .Padding(PaddingMode::PKCS7))); 4024 4025 hidl_vec<hidl_vec<uint8_t>> cert_chain; 4026 EXPECT_EQ( 4027 ErrorCode::INCOMPATIBLE_ALGORITHM, 4028 AttestKey( 4029 AuthorizationSetBuilder() 4030 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")) 4031 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")), 4032 &cert_chain)); 4033} 4034 4035/* 4036 * AttestationTest.HmacAttestation 4037 * 4038 * Verifies that attesting to HMAC keys fails in the expected way. 4039 */ 4040TEST_F(AttestationTest, HmacAttestation) { 4041 ASSERT_EQ(ErrorCode::OK, 4042 GenerateKey(AuthorizationSetBuilder() 4043 .Authorization(TAG_NO_AUTH_REQUIRED) 4044 .HmacKey(128) 4045 .EcbMode() 4046 .Digest(Digest::SHA_2_256) 4047 .Authorization(TAG_MIN_MAC_LENGTH, 128))); 4048 4049 hidl_vec<hidl_vec<uint8_t>> cert_chain; 4050 EXPECT_EQ( 4051 ErrorCode::INCOMPATIBLE_ALGORITHM, 4052 AttestKey( 4053 AuthorizationSetBuilder() 4054 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")) 4055 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")), 4056 &cert_chain)); 4057} 4058 4059typedef KeymasterHidlTest KeyDeletionTest; 4060 4061/** 4062 * KeyDeletionTest.DeleteKey 4063 * 4064 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly 4065 * valid key blob. 4066 */ 4067TEST_F(KeyDeletionTest, DeleteKey) { 4068 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 4069 .RsaSigningKey(1024, 3) 4070 .Digest(Digest::NONE) 4071 .Padding(PaddingMode::NONE) 4072 .Authorization(TAG_NO_AUTH_REQUIRED))); 4073 4074 // Delete must work if rollback protection is implemented 4075 AuthorizationSet teeEnforced(key_characteristics_.teeEnforced); 4076 bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT); 4077 4078 if (rollback_protected) { 4079 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */)); 4080 } else { 4081 auto delete_result = DeleteKey(true /* keep key blob */); 4082 ASSERT_TRUE(delete_result == ErrorCode::OK | delete_result == ErrorCode::UNIMPLEMENTED); 4083 } 4084 4085 string message = "12345678901234567890123456789012"; 4086 AuthorizationSet begin_out_params; 4087 4088 if (rollback_protected) { 4089 EXPECT_EQ( 4090 ErrorCode::INVALID_KEY_BLOB, 4091 Begin(KeyPurpose::SIGN, key_blob_, AuthorizationSetBuilder() 4092 .Digest(Digest::NONE) 4093 .Padding(PaddingMode::NONE), 4094 &begin_out_params, &op_handle_)) 4095 << " (Possibly b/37623742)"; 4096 } else { 4097 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, 4098 AuthorizationSetBuilder() 4099 .Digest(Digest::NONE) 4100 .Padding(PaddingMode::NONE), 4101 &begin_out_params, &op_handle_)); 4102 } 4103 AbortIfNeeded(); 4104 key_blob_ = HidlBuf(); 4105} 4106 4107/** 4108 * KeyDeletionTest.DeleteInvalidKey 4109 * 4110 * This test checks that the HAL excepts invalid key blobs. 4111 */ 4112TEST_F(KeyDeletionTest, DeleteInvalidKey) { 4113 // Generate key just to check if rollback protection is implemented 4114 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 4115 .RsaSigningKey(1024, 3) 4116 .Digest(Digest::NONE) 4117 .Padding(PaddingMode::NONE) 4118 .Authorization(TAG_NO_AUTH_REQUIRED))); 4119 4120 // Delete must work if rollback protection is implemented 4121 AuthorizationSet teeEnforced(key_characteristics_.teeEnforced); 4122 bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT); 4123 4124 // Delete the key we don't care about the result at this point. 4125 DeleteKey(); 4126 4127 // Now create an invalid key blob and delete it. 4128 key_blob_ = HidlBuf("just some garbage data which is not a valid key blob"); 4129 4130 if (rollback_protected) { 4131 ASSERT_EQ(ErrorCode::OK, DeleteKey()); 4132 } else { 4133 auto delete_result = DeleteKey(); 4134 ASSERT_TRUE(delete_result == ErrorCode::OK | delete_result == ErrorCode::UNIMPLEMENTED); 4135 } 4136} 4137 4138/** 4139 * KeyDeletionTest.DeleteAllKeys 4140 * 4141 * This test is disarmed by default. To arm it use --arm_deleteAllKeys. 4142 * 4143 * BEWARE: This test has serious side effects. All user keys will be lost! This includes 4144 * FBE/FDE encryption keys, which means that the device will not even boot until after the 4145 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have 4146 * been provisioned. Use this test only on dedicated testing devices that have no valuable 4147 * credentials stored in Keystore/Keymaster. 4148 */ 4149TEST_F(KeyDeletionTest, DeleteAllKeys) { 4150 if (!arm_deleteAllKeys) return; 4151 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder() 4152 .RsaSigningKey(1024, 3) 4153 .Digest(Digest::NONE) 4154 .Padding(PaddingMode::NONE) 4155 .Authorization(TAG_NO_AUTH_REQUIRED))); 4156 4157 // Delete must work if rollback protection is implemented 4158 AuthorizationSet teeEnforced(key_characteristics_.teeEnforced); 4159 bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT); 4160 4161 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys()); 4162 4163 string message = "12345678901234567890123456789012"; 4164 AuthorizationSet begin_out_params; 4165 4166 if (rollback_protected) { 4167 EXPECT_EQ( 4168 ErrorCode::INVALID_KEY_BLOB, 4169 Begin(KeyPurpose::SIGN, key_blob_, AuthorizationSetBuilder() 4170 .Digest(Digest::NONE) 4171 .Padding(PaddingMode::NONE), 4172 &begin_out_params, &op_handle_)); 4173 } else { 4174 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, 4175 AuthorizationSetBuilder() 4176 .Digest(Digest::NONE) 4177 .Padding(PaddingMode::NONE), 4178 &begin_out_params, &op_handle_)); 4179 } 4180 AbortIfNeeded(); 4181 key_blob_ = HidlBuf(); 4182} 4183 4184} // namespace test 4185} // namespace V3_0 4186} // namespace keymaster 4187} // namespace hardware 4188} // namespace android 4189 4190int main(int argc, char** argv) { 4191 ::testing::InitGoogleTest(&argc, argv); 4192 std::vector<std::string> positional_args; 4193 for (int i = 1; i < argc; ++i) { 4194 if (argv[i][0] == '-') { 4195 if (std::string(argv[i]) == "--arm_deleteAllKeys") { 4196 arm_deleteAllKeys = true; 4197 } 4198 if (std::string(argv[i]) == "--dump_attestations") { 4199 dump_Attestations = true; 4200 } 4201 } else { 4202 positional_args.push_back(argv[i]); 4203 } 4204 } 4205 if (positional_args.size()) { 4206 ALOGI("Running keymaster VTS against service \"%s\"", positional_args[0].c_str()); 4207 service_name = positional_args[0]; 4208 } 4209 int status = RUN_ALL_TESTS(); 4210 ALOGI("Test result = %d", status); 4211 return status; 4212} 4213