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