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