1 /* 2 * Copyright (C) 2011 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 #include <errno.h> 17 #include <string.h> 18 #include <stdint.h> 19 20 // For debugging 21 #define LOG_NDEBUG 0 22 23 // TEE is the Trusted Execution Environment 24 #define LOG_TAG "TEEKeyMaster" 25 #include <cutils/log.h> 26 27 #include <hardware/hardware.h> 28 #include <hardware/keymaster.h> 29 30 #include <openssl/bn.h> 31 #include <openssl/err.h> 32 #include <openssl/evp.h> 33 #include <openssl/rand.h> 34 #include <openssl/x509.h> 35 36 #include <cryptoki.h> 37 #include <pkcs11.h> 38 39 #include <utils/UniquePtr.h> 40 41 42 /** The size of a key ID in bytes */ 43 #define ID_LENGTH 32 44 45 /** The current stored key version. */ 46 const static uint32_t KEY_VERSION = 1; 47 48 49 struct EVP_PKEY_Delete { 50 void operator()(EVP_PKEY* p) const { 51 EVP_PKEY_free(p); 52 } 53 }; 54 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY; 55 56 struct RSA_Delete { 57 void operator()(RSA* p) const { 58 RSA_free(p); 59 } 60 }; 61 typedef UniquePtr<RSA, RSA_Delete> Unique_RSA; 62 63 struct PKCS8_PRIV_KEY_INFO_Delete { 64 void operator()(PKCS8_PRIV_KEY_INFO* p) const { 65 PKCS8_PRIV_KEY_INFO_free(p); 66 } 67 }; 68 typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO; 69 70 typedef UniquePtr<keymaster_device_t> Unique_keymaster_device_t; 71 72 typedef UniquePtr<CK_BYTE[]> Unique_CK_BYTE; 73 74 typedef UniquePtr<CK_ATTRIBUTE[]> Unique_CK_ATTRIBUTE; 75 76 class ByteArray { 77 public: 78 ByteArray(CK_BYTE* array, size_t len) : 79 mArray(array), mLength(len) { 80 } 81 82 ByteArray(size_t len) : 83 mLength(len) { 84 mArray = new CK_BYTE[len]; 85 } 86 87 ~ByteArray() { 88 if (mArray != NULL) { 89 delete[] mArray; 90 } 91 } 92 93 CK_BYTE* get() const { 94 return mArray; 95 } 96 97 size_t length() const { 98 return mLength; 99 } 100 101 CK_BYTE* release() { 102 CK_BYTE* array = mArray; 103 mArray = NULL; 104 return array; 105 } 106 107 private: 108 CK_BYTE* mArray; 109 size_t mLength; 110 }; 111 typedef UniquePtr<ByteArray> Unique_ByteArray; 112 113 class CryptoSession { 114 public: 115 CryptoSession(CK_SESSION_HANDLE masterHandle) : 116 mHandle(masterHandle), mSubsession(CK_INVALID_HANDLE) { 117 CK_SESSION_HANDLE subsessionHandle = mHandle; 118 CK_RV openSessionRV = C_OpenSession(CKV_TOKEN_USER, 119 CKF_SERIAL_SESSION | CKF_RW_SESSION | CKVF_OPEN_SUB_SESSION, 120 NULL, 121 NULL, 122 &subsessionHandle); 123 124 if (openSessionRV != CKR_OK || subsessionHandle == CK_INVALID_HANDLE) { 125 (void) C_Finalize(NULL_PTR); 126 ALOGE("Error opening secondary session with TEE: 0x%x", openSessionRV); 127 } else { 128 ALOGV("Opening subsession 0x%x", subsessionHandle); 129 mSubsession = subsessionHandle; 130 } 131 } 132 133 ~CryptoSession() { 134 if (mSubsession != CK_INVALID_HANDLE) { 135 CK_RV rv = C_CloseSession(mSubsession); 136 ALOGV("Closing subsession 0x%x: 0x%x", mSubsession, rv); 137 mSubsession = CK_INVALID_HANDLE; 138 } 139 } 140 141 CK_SESSION_HANDLE get() const { 142 return mSubsession; 143 } 144 145 CK_SESSION_HANDLE getPrimary() const { 146 return mHandle; 147 } 148 149 private: 150 CK_SESSION_HANDLE mHandle; 151 CK_SESSION_HANDLE mSubsession; 152 }; 153 154 class ObjectHandle { 155 public: 156 ObjectHandle(const CryptoSession* session, CK_OBJECT_HANDLE handle = CK_INVALID_HANDLE) : 157 mSession(session), mHandle(handle) { 158 } 159 160 ~ObjectHandle() { 161 if (mHandle != CK_INVALID_HANDLE) { 162 CK_RV rv = C_CloseObjectHandle(mSession->getPrimary(), mHandle); 163 if (rv != CKR_OK) { 164 ALOGW("Couldn't close object handle 0x%x: 0x%x", mHandle, rv); 165 } else { 166 ALOGV("Closing object handle 0x%x", mHandle); 167 mHandle = CK_INVALID_HANDLE; 168 } 169 } 170 } 171 172 CK_OBJECT_HANDLE get() const { 173 return mHandle; 174 } 175 176 void reset(CK_OBJECT_HANDLE handle) { 177 mHandle = handle; 178 } 179 180 private: 181 const CryptoSession* mSession; 182 CK_OBJECT_HANDLE mHandle; 183 }; 184 185 186 /** 187 * Many OpenSSL APIs take ownership of an argument on success but don't free the argument 188 * on failure. This means we need to tell our scoped pointers when we've transferred ownership, 189 * without triggering a warning by not using the result of release(). 190 */ 191 #define OWNERSHIP_TRANSFERRED(obj) \ 192 typeof (obj.release()) _dummy __attribute__((unused)) = obj.release() 193 194 195 /* 196 * Checks this thread's OpenSSL error queue and logs if 197 * necessary. 198 */ 199 static void logOpenSSLError(const char* location) { 200 int error = ERR_get_error(); 201 202 if (error != 0) { 203 char message[256]; 204 ERR_error_string_n(error, message, sizeof(message)); 205 ALOGE("OpenSSL error in %s %d: %s", location, error, message); 206 } 207 208 ERR_clear_error(); 209 ERR_remove_state(0); 210 } 211 212 213 /** 214 * Convert from OpenSSL's BIGNUM format to TEE's Big Integer format. 215 */ 216 static ByteArray* bignum_to_array(const BIGNUM* bn) { 217 const int bignumSize = BN_num_bytes(bn); 218 219 Unique_CK_BYTE bytes(new CK_BYTE[bignumSize]); 220 221 unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get()); 222 if (BN_bn2bin(bn, tmp) != bignumSize) { 223 ALOGE("public exponent size wasn't what was expected"); 224 return NULL; 225 } 226 227 return new ByteArray(bytes.release(), bignumSize); 228 } 229 230 static void set_attribute(CK_ATTRIBUTE* attrib, CK_ATTRIBUTE_TYPE type, void* pValue, 231 CK_ULONG ulValueLen) { 232 attrib->type = type; 233 attrib->pValue = pValue; 234 attrib->ulValueLen = ulValueLen; 235 } 236 237 static ByteArray* generate_random_id() { 238 Unique_ByteArray id(new ByteArray(ID_LENGTH)); 239 if (RAND_pseudo_bytes(reinterpret_cast<unsigned char*>(id->get()), id->length()) < 0) { 240 return NULL; 241 } 242 243 return id.release(); 244 } 245 246 static int keyblob_save(ByteArray* objId, uint8_t** key_blob, size_t* key_blob_length) { 247 Unique_ByteArray handleBlob(new ByteArray(sizeof(uint32_t) + objId->length())); 248 if (handleBlob.get() == NULL) { 249 ALOGE("Could not allocate key blob"); 250 return -1; 251 } 252 uint8_t* tmp = handleBlob->get(); 253 for (size_t i = 0; i < sizeof(uint32_t); i++) { 254 *tmp++ = KEY_VERSION >> ((sizeof(uint32_t) - i - 1) * 8); 255 } 256 memcpy(tmp, objId->get(), objId->length()); 257 258 *key_blob_length = handleBlob->length(); 259 *key_blob = handleBlob->get(); 260 ByteArray* unused __attribute__((unused)) = handleBlob.release(); 261 262 return 0; 263 } 264 265 static int find_single_object(const uint8_t* obj_id, const size_t obj_id_length, 266 CK_OBJECT_CLASS obj_class, const CryptoSession* session, ObjectHandle* object) { 267 268 // Note that the CKA_ID attribute is never written, so we can cast away const here. 269 void* obj_id_ptr = reinterpret_cast<void*>(const_cast<uint8_t*>(obj_id)); 270 CK_ATTRIBUTE attributes[] = { 271 { CKA_ID, obj_id_ptr, obj_id_length }, 272 { CKA_CLASS, &obj_class, sizeof(obj_class) }, 273 }; 274 275 CK_RV rv = C_FindObjectsInit(session->get(), attributes, 276 sizeof(attributes) / sizeof(CK_ATTRIBUTE)); 277 if (rv != CKR_OK) { 278 ALOGE("Error in C_FindObjectsInit: 0x%x", rv); 279 return -1; 280 } 281 282 CK_OBJECT_HANDLE tmpHandle; 283 CK_ULONG tmpCount; 284 285 rv = C_FindObjects(session->get(), &tmpHandle, 1, &tmpCount); 286 ALOGV("Found %d object 0x%x : class 0x%x", tmpCount, tmpHandle, obj_class); 287 if (rv != CKR_OK || tmpCount != 1) { 288 C_FindObjectsFinal(session->get()); 289 ALOGE("Couldn't find key!"); 290 return -1; 291 } 292 C_FindObjectsFinal(session->get()); 293 294 object->reset(tmpHandle); 295 return 0; 296 } 297 298 static int keyblob_restore(const CryptoSession* session, const uint8_t* keyBlob, 299 const size_t keyBlobLength, ObjectHandle* public_key, ObjectHandle* private_key) { 300 if (keyBlob == NULL) { 301 ALOGE("key blob was null"); 302 return -1; 303 } 304 305 if (keyBlobLength < (sizeof(KEY_VERSION) + ID_LENGTH)) { 306 ALOGE("key blob is not correct size"); 307 return -1; 308 } 309 310 uint32_t keyVersion = 0; 311 312 const uint8_t* p = keyBlob; 313 for (size_t i = 0; i < sizeof(keyVersion); i++) { 314 keyVersion = (keyVersion << 8) | *p++; 315 } 316 317 if (keyVersion != 1) { 318 ALOGE("Invalid key version %d", keyVersion); 319 return -1; 320 } 321 322 return find_single_object(p, ID_LENGTH, CKO_PUBLIC_KEY, session, public_key) 323 || find_single_object(p, ID_LENGTH, CKO_PRIVATE_KEY, session, private_key); 324 } 325 326 static int tee_generate_keypair(const keymaster_device_t* dev, 327 const keymaster_keypair_t type, const void* key_params, 328 uint8_t** key_blob, size_t* key_blob_length) { 329 CK_BBOOL bTRUE = CK_TRUE; 330 331 if (type != TYPE_RSA) { 332 ALOGW("Unknown key type %d", type); 333 return -1; 334 } 335 336 if (key_params == NULL) { 337 ALOGW("generate_keypair params were NULL"); 338 return -1; 339 } 340 341 keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params; 342 343 CK_MECHANISM mechanism = { 344 CKM_RSA_PKCS_KEY_PAIR_GEN, NULL, 0, 345 }; 346 CK_ULONG modulusBits = (CK_ULONG) rsa_params->modulus_size; 347 348 /** 349 * Convert our unsigned 64-bit integer to the TEE Big Integer class. It's 350 * an unsigned array of bytes with MSB first. 351 */ 352 CK_BYTE publicExponent[sizeof(uint64_t)]; 353 const uint64_t exp = rsa_params->public_exponent; 354 size_t offset = sizeof(publicExponent) - 1; 355 for (size_t i = 0; i < sizeof(publicExponent); i++) { 356 publicExponent[offset--] = (exp >> (i * CHAR_BIT)) & 0xFF; 357 } 358 359 Unique_ByteArray objId(generate_random_id()); 360 if (objId.get() == NULL) { 361 ALOGE("Couldn't generate random key ID"); 362 return -1; 363 } 364 365 CK_ATTRIBUTE publicKeyTemplate[] = { 366 {CKA_ID, objId->get(), objId->length()}, 367 {CKA_TOKEN, &bTRUE, sizeof(bTRUE)}, 368 {CKA_ENCRYPT, &bTRUE, sizeof(bTRUE)}, 369 {CKA_VERIFY, &bTRUE, sizeof(bTRUE)}, 370 {CKA_MODULUS_BITS, &modulusBits, sizeof(modulusBits)}, 371 {CKA_PUBLIC_EXPONENT, publicExponent, sizeof(publicExponent)}, 372 }; 373 374 CK_ATTRIBUTE privateKeyTemplate[] = { 375 {CKA_ID, objId->get(), objId->length()}, 376 {CKA_TOKEN, &bTRUE, sizeof(bTRUE)}, 377 {CKA_DECRYPT, &bTRUE, sizeof(bTRUE)}, 378 {CKA_SIGN, &bTRUE, sizeof(bTRUE)}, 379 }; 380 381 CryptoSession session(reinterpret_cast<CK_SESSION_HANDLE>(dev->context)); 382 383 CK_OBJECT_HANDLE hPublicKey, hPrivateKey; 384 CK_RV rv = C_GenerateKeyPair(session.get(), 385 &mechanism, 386 publicKeyTemplate, 387 sizeof(publicKeyTemplate)/sizeof(CK_ATTRIBUTE), 388 privateKeyTemplate, 389 sizeof(privateKeyTemplate)/sizeof(CK_ATTRIBUTE), 390 &hPublicKey, 391 &hPrivateKey); 392 393 if (rv != CKR_OK) { 394 ALOGE("Generate keypair failed: 0x%x", rv); 395 return -1; 396 } 397 398 ObjectHandle publicKey(&session, hPublicKey); 399 ObjectHandle privateKey(&session, hPrivateKey); 400 ALOGV("public handle = 0x%x, private handle = 0x%x", publicKey.get(), privateKey.get()); 401 402 return keyblob_save(objId.get(), key_blob, key_blob_length); 403 } 404 405 static int tee_import_keypair(const keymaster_device_t* dev, 406 const uint8_t* key, const size_t key_length, 407 uint8_t** key_blob, size_t* key_blob_length) { 408 CK_RV rv; 409 CK_BBOOL bTRUE = CK_TRUE; 410 411 if (key == NULL) { 412 ALOGW("provided key is null"); 413 return -1; 414 } 415 416 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length)); 417 if (pkcs8.get() == NULL) { 418 logOpenSSLError("tee_import_keypair"); 419 return -1; 420 } 421 422 /* assign to EVP */ 423 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get())); 424 if (pkey.get() == NULL) { 425 logOpenSSLError("tee_import_keypair"); 426 return -1; 427 } 428 429 if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) { 430 ALOGE("Unsupported key type: %d", EVP_PKEY_type(pkey->type)); 431 return -1; 432 } 433 434 Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get())); 435 if (rsa.get() == NULL) { 436 logOpenSSLError("tee_import_keypair"); 437 return -1; 438 } 439 440 Unique_ByteArray modulus(bignum_to_array(rsa->n)); 441 if (modulus.get() == NULL) { 442 ALOGW("Could not convert modulus to array"); 443 return -1; 444 } 445 446 Unique_ByteArray publicExponent(bignum_to_array(rsa->e)); 447 if (publicExponent.get() == NULL) { 448 ALOGW("Could not convert publicExponent to array"); 449 return -1; 450 } 451 452 CK_KEY_TYPE rsaType = CKK_RSA; 453 454 CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY; 455 456 Unique_ByteArray objId(generate_random_id()); 457 if (objId.get() == NULL) { 458 ALOGE("Couldn't generate random key ID"); 459 return -1; 460 } 461 462 CK_ATTRIBUTE publicKeyTemplate[] = { 463 {CKA_ID, objId->get(), objId->length()}, 464 {CKA_TOKEN, &bTRUE, sizeof(bTRUE)}, 465 {CKA_CLASS, &pubClass, sizeof(pubClass)}, 466 {CKA_KEY_TYPE, &rsaType, sizeof(rsaType)}, 467 {CKA_ENCRYPT, &bTRUE, sizeof(bTRUE)}, 468 {CKA_VERIFY, &bTRUE, sizeof(bTRUE)}, 469 {CKA_MODULUS, modulus->get(), modulus->length()}, 470 {CKA_PUBLIC_EXPONENT, publicExponent->get(), publicExponent->length()}, 471 }; 472 473 CryptoSession session(reinterpret_cast<CK_SESSION_HANDLE>(dev->context)); 474 475 CK_OBJECT_HANDLE hPublicKey; 476 rv = C_CreateObject(session.get(), 477 publicKeyTemplate, 478 sizeof(publicKeyTemplate)/sizeof(CK_ATTRIBUTE), 479 &hPublicKey); 480 if (rv != CKR_OK) { 481 ALOGE("Creation of public key failed: 0x%x", rv); 482 return -1; 483 } 484 ObjectHandle publicKey(&session, hPublicKey); 485 486 Unique_ByteArray privateExponent(bignum_to_array(rsa->d)); 487 if (privateExponent.get() == NULL) { 488 ALOGW("Could not convert private exponent"); 489 return -1; 490 } 491 492 493 /* 494 * Normally we need: 495 * CKA_ID 496 * CKA_TOKEN 497 * CKA_CLASS 498 * CKA_KEY_TYPE 499 * 500 * CKA_DECRYPT 501 * CKA_SIGN 502 * 503 * CKA_MODULUS 504 * CKA_PUBLIC_EXPONENT 505 * CKA_PRIVATE_EXPONENT 506 */ 507 #define PRIV_ATTRIB_NORMAL_NUM (4 + 2 + 3) 508 509 /* 510 * For additional private key values: 511 * CKA_PRIME_1 512 * CKA_PRIME_2 513 * 514 * CKA_EXPONENT_1 515 * CKA_EXPONENT_2 516 * 517 * CKA_COEFFICIENT 518 */ 519 #define PRIV_ATTRIB_EXTENDED_NUM (PRIV_ATTRIB_NORMAL_NUM + 5) 520 521 /* 522 * If we have the prime, prime exponents, and coefficient, we can 523 * copy them in. 524 */ 525 bool has_extra_data = (rsa->p != NULL) && (rsa->q != NULL) && (rsa->dmp1 != NULL) && 526 (rsa->dmq1 != NULL) && (rsa->iqmp != NULL); 527 528 Unique_CK_ATTRIBUTE privateKeyTemplate(new CK_ATTRIBUTE[ 529 has_extra_data ? PRIV_ATTRIB_EXTENDED_NUM : PRIV_ATTRIB_NORMAL_NUM]); 530 531 CK_OBJECT_CLASS privClass = CKO_PRIVATE_KEY; 532 533 size_t templateOffset = 0; 534 535 set_attribute(&privateKeyTemplate[templateOffset++], CKA_ID, objId->get(), objId->length()); 536 set_attribute(&privateKeyTemplate[templateOffset++], CKA_TOKEN, &bTRUE, sizeof(bTRUE)); 537 set_attribute(&privateKeyTemplate[templateOffset++], CKA_CLASS, &privClass, sizeof(privClass)); 538 set_attribute(&privateKeyTemplate[templateOffset++], CKA_KEY_TYPE, &rsaType, sizeof(rsaType)); 539 540 set_attribute(&privateKeyTemplate[templateOffset++], CKA_DECRYPT, &bTRUE, sizeof(bTRUE)); 541 set_attribute(&privateKeyTemplate[templateOffset++], CKA_SIGN, &bTRUE, sizeof(bTRUE)); 542 543 set_attribute(&privateKeyTemplate[templateOffset++], CKA_MODULUS, modulus->get(), 544 modulus->length()); 545 set_attribute(&privateKeyTemplate[templateOffset++], CKA_PUBLIC_EXPONENT, 546 publicExponent->get(), publicExponent->length()); 547 set_attribute(&privateKeyTemplate[templateOffset++], CKA_PRIVATE_EXPONENT, 548 privateExponent->get(), privateExponent->length()); 549 550 Unique_ByteArray prime1, prime2, exp1, exp2, coeff; 551 if (has_extra_data) { 552 prime1.reset(bignum_to_array(rsa->p)); 553 if (prime1->get() == NULL) { 554 ALOGW("Could not convert prime1"); 555 return -1; 556 } 557 set_attribute(&privateKeyTemplate[templateOffset++], CKA_PRIME_1, prime1->get(), 558 prime1->length()); 559 560 prime2.reset(bignum_to_array(rsa->q)); 561 if (prime2->get() == NULL) { 562 ALOGW("Could not convert prime2"); 563 return -1; 564 } 565 set_attribute(&privateKeyTemplate[templateOffset++], CKA_PRIME_2, prime2->get(), 566 prime2->length()); 567 568 exp1.reset(bignum_to_array(rsa->dmp1)); 569 if (exp1->get() == NULL) { 570 ALOGW("Could not convert exponent 1"); 571 return -1; 572 } 573 set_attribute(&privateKeyTemplate[templateOffset++], CKA_EXPONENT_1, exp1->get(), 574 exp1->length()); 575 576 exp2.reset(bignum_to_array(rsa->dmq1)); 577 if (exp2->get() == NULL) { 578 ALOGW("Could not convert exponent 2"); 579 return -1; 580 } 581 set_attribute(&privateKeyTemplate[templateOffset++], CKA_EXPONENT_2, exp2->get(), 582 exp2->length()); 583 584 coeff.reset(bignum_to_array(rsa->iqmp)); 585 if (coeff->get() == NULL) { 586 ALOGW("Could not convert coefficient"); 587 return -1; 588 } 589 set_attribute(&privateKeyTemplate[templateOffset++], CKA_COEFFICIENT, coeff->get(), 590 coeff->length()); 591 } 592 593 CK_OBJECT_HANDLE hPrivateKey; 594 rv = C_CreateObject(session.get(), 595 privateKeyTemplate.get(), 596 templateOffset, 597 &hPrivateKey); 598 if (rv != CKR_OK) { 599 ALOGE("Creation of private key failed: 0x%x", rv); 600 return -1; 601 } 602 ObjectHandle privateKey(&session, hPrivateKey); 603 604 ALOGV("public handle = 0x%x, private handle = 0x%x", publicKey.get(), privateKey.get()); 605 606 return keyblob_save(objId.get(), key_blob, key_blob_length); 607 } 608 609 static int tee_get_keypair_public(const struct keymaster_device* dev, 610 const uint8_t* key_blob, const size_t key_blob_length, 611 uint8_t** x509_data, size_t* x509_data_length) { 612 613 CryptoSession session(reinterpret_cast<CK_SESSION_HANDLE>(dev->context)); 614 615 ObjectHandle publicKey(&session); 616 ObjectHandle privateKey(&session); 617 618 if (keyblob_restore(&session, key_blob, key_blob_length, &publicKey, &privateKey)) { 619 return -1; 620 } 621 622 if (x509_data == NULL || x509_data_length == NULL) { 623 ALOGW("Provided destination variables were null"); 624 return -1; 625 } 626 627 CK_ATTRIBUTE attributes[] = { 628 {CKA_MODULUS, NULL, 0}, 629 {CKA_PUBLIC_EXPONENT, NULL, 0}, 630 }; 631 632 // Call first to get the sizes of the values. 633 CK_RV rv = C_GetAttributeValue(session.get(), publicKey.get(), attributes, 634 sizeof(attributes)/sizeof(CK_ATTRIBUTE)); 635 if (rv != CKR_OK) { 636 ALOGW("Could not query attribute value sizes: 0x%02x", rv); 637 return -1; 638 } 639 640 ByteArray modulus(new CK_BYTE[attributes[0].ulValueLen], attributes[0].ulValueLen); 641 ByteArray exponent(new CK_BYTE[attributes[1].ulValueLen], attributes[1].ulValueLen); 642 643 attributes[0].pValue = modulus.get(); 644 attributes[1].pValue = exponent.get(); 645 646 rv = C_GetAttributeValue(session.get(), publicKey.get(), attributes, 647 sizeof(attributes) / sizeof(CK_ATTRIBUTE)); 648 if (rv != CKR_OK) { 649 ALOGW("Could not query attribute values: 0x%02x", rv); 650 return -1; 651 } 652 653 ALOGV("modulus is %d, exponent is %d", modulus.length(), exponent.length()); 654 655 Unique_RSA rsa(RSA_new()); 656 if (rsa.get() == NULL) { 657 ALOGE("Could not allocate RSA structure"); 658 return -1; 659 } 660 661 rsa->n = BN_bin2bn(reinterpret_cast<const unsigned char*>(modulus.get()), modulus.length(), 662 NULL); 663 if (rsa->n == NULL) { 664 logOpenSSLError("tee_get_keypair_public"); 665 return -1; 666 } 667 668 rsa->e = BN_bin2bn(reinterpret_cast<const unsigned char*>(exponent.get()), exponent.length(), 669 NULL); 670 if (rsa->e == NULL) { 671 logOpenSSLError("tee_get_keypair_public"); 672 return -1; 673 } 674 675 Unique_EVP_PKEY pkey(EVP_PKEY_new()); 676 if (pkey.get() == NULL) { 677 ALOGE("Could not allocate EVP_PKEY structure"); 678 return -1; 679 } 680 if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) { 681 logOpenSSLError("tee_get_keypair_public"); 682 return -1; 683 } 684 OWNERSHIP_TRANSFERRED(rsa); 685 686 int len = i2d_PUBKEY(pkey.get(), NULL); 687 if (len <= 0) { 688 logOpenSSLError("tee_get_keypair_public"); 689 return -1; 690 } 691 692 UniquePtr<uint8_t> key(static_cast<uint8_t*>(malloc(len))); 693 if (key.get() == NULL) { 694 ALOGE("Could not allocate memory for public key data"); 695 return -1; 696 } 697 698 unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get()); 699 if (i2d_PUBKEY(pkey.get(), &tmp) != len) { 700 logOpenSSLError("tee_get_keypair_public"); 701 return -1; 702 } 703 704 ALOGV("Length of x509 data is %d", len); 705 *x509_data_length = len; 706 *x509_data = key.release(); 707 708 return 0; 709 } 710 711 static int tee_delete_keypair(const struct keymaster_device* dev, 712 const uint8_t* key_blob, const size_t key_blob_length) { 713 714 CryptoSession session(reinterpret_cast<CK_SESSION_HANDLE>(dev->context)); 715 716 ObjectHandle publicKey(&session); 717 ObjectHandle privateKey(&session); 718 719 if (keyblob_restore(&session, key_blob, key_blob_length, &publicKey, &privateKey)) { 720 return -1; 721 } 722 723 // Delete the private key. 724 CK_RV rv = C_DestroyObject(session.get(), privateKey.get()); 725 if (rv != CKR_OK) { 726 ALOGW("Could destroy private key object: 0x%02x", rv); 727 return -1; 728 } 729 730 // Delete the public key. 731 rv = C_DestroyObject(session.get(), publicKey.get()); 732 if (rv != CKR_OK) { 733 ALOGW("Could destroy public key object: 0x%02x", rv); 734 return -1; 735 } 736 737 return 0; 738 } 739 740 static int tee_sign_data(const keymaster_device_t* dev, 741 const void* params, 742 const uint8_t* key_blob, const size_t key_blob_length, 743 const uint8_t* data, const size_t dataLength, 744 uint8_t** signedData, size_t* signedDataLength) { 745 ALOGV("tee_sign_data(%p, %p, %llu, %p, %llu, %p, %p)", dev, key_blob, 746 (unsigned long long) key_blob_length, data, (unsigned long long) dataLength, signedData, 747 signedDataLength); 748 749 if (params == NULL) { 750 ALOGW("Signing params were null"); 751 return -1; 752 } 753 754 CryptoSession session(reinterpret_cast<CK_SESSION_HANDLE>(dev->context)); 755 756 ObjectHandle publicKey(&session); 757 ObjectHandle privateKey(&session); 758 759 if (keyblob_restore(&session, key_blob, key_blob_length, &publicKey, &privateKey)) { 760 return -1; 761 } 762 ALOGV("public handle = 0x%x, private handle = 0x%x", publicKey.get(), privateKey.get()); 763 764 keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; 765 if (sign_params->digest_type != DIGEST_NONE) { 766 ALOGW("Cannot handle digest type %d", sign_params->digest_type); 767 return -1; 768 } else if (sign_params->padding_type != PADDING_NONE) { 769 ALOGW("Cannot handle padding type %d", sign_params->padding_type); 770 return -1; 771 } 772 773 CK_MECHANISM rawRsaMechanism = { 774 CKM_RSA_X_509, NULL, 0 775 }; 776 777 CK_RV rv = C_SignInit(session.get(), &rawRsaMechanism, privateKey.get()); 778 if (rv != CKR_OK) { 779 ALOGV("C_SignInit failed: 0x%x", rv); 780 return -1; 781 } 782 783 CK_BYTE signature[1024]; 784 CK_ULONG signatureLength = 1024; 785 786 rv = C_Sign(session.get(), data, dataLength, signature, &signatureLength); 787 if (rv != CKR_OK) { 788 ALOGV("C_SignFinal failed: 0x%x", rv); 789 return -1; 790 } 791 792 UniquePtr<uint8_t[]> finalSignature(new uint8_t[signatureLength]); 793 if (finalSignature.get() == NULL) { 794 ALOGE("Couldn't allocate memory to copy signature"); 795 return -1; 796 } 797 798 memcpy(finalSignature.get(), signature, signatureLength); 799 800 *signedData = finalSignature.release(); 801 *signedDataLength = static_cast<size_t>(signatureLength); 802 803 ALOGV("tee_sign_data(%p, %p, %llu, %p, %llu, %p, %p) => %p size %llu", dev, key_blob, 804 (unsigned long long) key_blob_length, data, (unsigned long long) dataLength, signedData, 805 signedDataLength, *signedData, (unsigned long long) *signedDataLength); 806 807 return 0; 808 } 809 810 static int tee_verify_data(const keymaster_device_t* dev, 811 const void* params, 812 const uint8_t* keyBlob, const size_t keyBlobLength, 813 const uint8_t* signedData, const size_t signedDataLength, 814 const uint8_t* signature, const size_t signatureLength) { 815 ALOGV("tee_verify_data(%p, %p, %llu, %p, %llu, %p, %llu)", dev, keyBlob, 816 (unsigned long long) keyBlobLength, signedData, (unsigned long long) signedDataLength, 817 signature, (unsigned long long) signatureLength); 818 819 if (params == NULL) { 820 ALOGW("Verification params were null"); 821 return -1; 822 } 823 824 CryptoSession session(reinterpret_cast<CK_SESSION_HANDLE>(dev->context)); 825 826 ObjectHandle publicKey(&session); 827 ObjectHandle privateKey(&session); 828 829 if (keyblob_restore(&session, keyBlob, keyBlobLength, &publicKey, &privateKey)) { 830 return -1; 831 } 832 ALOGV("public handle = 0x%x, private handle = 0x%x", publicKey.get(), privateKey.get()); 833 834 keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; 835 if (sign_params->digest_type != DIGEST_NONE) { 836 ALOGW("Cannot handle digest type %d", sign_params->digest_type); 837 return -1; 838 } else if (sign_params->padding_type != PADDING_NONE) { 839 ALOGW("Cannot handle padding type %d", sign_params->padding_type); 840 return -1; 841 } 842 843 CK_MECHANISM rawRsaMechanism = { 844 CKM_RSA_X_509, NULL, 0 845 }; 846 847 CK_RV rv = C_VerifyInit(session.get(), &rawRsaMechanism, publicKey.get()); 848 if (rv != CKR_OK) { 849 ALOGV("C_VerifyInit failed: 0x%x", rv); 850 return -1; 851 } 852 853 // This is a bad prototype for this function. C_Verify should have only const args. 854 rv = C_Verify(session.get(), signedData, signedDataLength, 855 const_cast<unsigned char*>(signature), signatureLength); 856 if (rv != CKR_OK) { 857 ALOGV("C_Verify failed: 0x%x", rv); 858 return -1; 859 } 860 861 return 0; 862 } 863 864 /* Close an opened OpenSSL instance */ 865 static int tee_close(hw_device_t *dev) { 866 keymaster_device_t *keymaster_dev = (keymaster_device_t *) dev; 867 if (keymaster_dev != NULL) { 868 CK_SESSION_HANDLE handle = reinterpret_cast<CK_SESSION_HANDLE>(keymaster_dev->context); 869 if (handle != CK_INVALID_HANDLE) { 870 C_CloseSession(handle); 871 } 872 } 873 874 CK_RV finalizeRV = C_Finalize(NULL_PTR); 875 if (finalizeRV != CKR_OK) { 876 ALOGE("Error closing the TEE"); 877 } 878 free(dev); 879 880 return 0; 881 } 882 883 /* 884 * Generic device handling 885 */ 886 static int tee_open(const hw_module_t* module, const char* name, 887 hw_device_t** device) { 888 if (strcmp(name, KEYSTORE_KEYMASTER) != 0) 889 return -EINVAL; 890 891 Unique_keymaster_device_t dev(new keymaster_device_t); 892 if (dev.get() == NULL) 893 return -ENOMEM; 894 895 dev->common.tag = HARDWARE_DEVICE_TAG; 896 dev->common.version = 1; 897 dev->common.module = (struct hw_module_t*) module; 898 dev->common.close = tee_close; 899 900 dev->generate_keypair = tee_generate_keypair; 901 dev->import_keypair = tee_import_keypair; 902 dev->get_keypair_public = tee_get_keypair_public; 903 dev->delete_keypair = tee_delete_keypair; 904 dev->sign_data = tee_sign_data; 905 dev->verify_data = tee_verify_data; 906 dev->delete_all = NULL; 907 908 CK_RV initializeRV = C_Initialize(NULL); 909 if (initializeRV != CKR_OK) { 910 ALOGE("Error initializing TEE: 0x%x", initializeRV); 911 return -ENODEV; 912 } 913 914 CK_INFO info; 915 CK_RV infoRV = C_GetInfo(&info); 916 if (infoRV != CKR_OK) { 917 (void) C_Finalize(NULL_PTR); 918 ALOGE("Error getting information about TEE during initialization: 0x%x", infoRV); 919 return -ENODEV; 920 } 921 922 ALOGI("C_GetInfo cryptokiVer=%d.%d manufID=%s flags=%d libDesc=%s libVer=%d.%d\n", 923 info.cryptokiVersion.major, info.cryptokiVersion.minor, 924 info.manufacturerID, info.flags, info.libraryDescription, 925 info.libraryVersion.major, info.libraryVersion.minor); 926 927 CK_SESSION_HANDLE sessionHandle = CK_INVALID_HANDLE; 928 929 CK_RV openSessionRV = C_OpenSession(CKV_TOKEN_USER, 930 CKF_SERIAL_SESSION | CKF_RW_SESSION, 931 NULL, 932 NULL, 933 &sessionHandle); 934 935 if (openSessionRV != CKR_OK || sessionHandle == CK_INVALID_HANDLE) { 936 (void) C_Finalize(NULL_PTR); 937 ALOGE("Error opening primary session with TEE: 0x%x", openSessionRV); 938 return -1; 939 } 940 941 ERR_load_crypto_strings(); 942 ERR_load_BIO_strings(); 943 944 dev->context = reinterpret_cast<void*>(sessionHandle); 945 *device = reinterpret_cast<hw_device_t*>(dev.release()); 946 947 return 0; 948 } 949 950 static struct hw_module_methods_t keystore_module_methods = { 951 open: tee_open, 952 }; 953 954 struct keystore_module HAL_MODULE_INFO_SYM 955 __attribute__ ((visibility ("default"))) = { 956 common: { 957 tag: HARDWARE_MODULE_TAG, 958 version_major: 1, 959 version_minor: 0, 960 id: KEYSTORE_HARDWARE_MODULE_ID, 961 name: "Keymaster TEE HAL", 962 author: "The Android Open Source Project", 963 methods: &keystore_module_methods, 964 dso: 0, 965 reserved: {}, 966 }, 967 }; 968