Home | History | Annotate | Download | only in libkeymaster
      1 /*
      2  * Copyright (C) 2012 Samsung Electronics Co., LTD
      3  * Copyright (C) 2012 The Android Open Source Project
      4  *
      5  * Licensed under the Apache License, Version 2.0 (the "License");
      6  * you may not use this file except in compliance with the License.
      7  * You may obtain a copy of the License at
      8  *
      9  *      http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16  */
     17 
     18 #include <errno.h>
     19 #include <string.h>
     20 #include <stdint.h>
     21 
     22 #include <hardware/hardware.h>
     23 #include <hardware/keymaster.h>
     24 
     25 #include <openssl/evp.h>
     26 #include <openssl/bio.h>
     27 #include <openssl/rsa.h>
     28 #include <openssl/err.h>
     29 #include <openssl/x509.h>
     30 
     31 #include <utils/UniquePtr.h>
     32 
     33 #define LOG_TAG "ExynosKeyMaster"
     34 #include <cutils/log.h>
     35 
     36 #include <tlcTeeKeymaster_if.h>
     37 
     38 #define RSA_KEY_BUFFER_SIZE   1536
     39 #define RSA_KEY_MAX_SIZE      (2048 >> 3)
     40 
     41 struct BIGNUM_Delete {
     42     void operator()(BIGNUM* p) const {
     43         BN_free(p);
     44     }
     45 };
     46 typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
     47 
     48 struct EVP_PKEY_Delete {
     49     void operator()(EVP_PKEY* p) const {
     50         EVP_PKEY_free(p);
     51     }
     52 };
     53 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
     54 
     55 struct PKCS8_PRIV_KEY_INFO_Delete {
     56     void operator()(PKCS8_PRIV_KEY_INFO* p) const {
     57         PKCS8_PRIV_KEY_INFO_free(p);
     58     }
     59 };
     60 typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
     61 
     62 struct RSA_Delete {
     63     void operator()(RSA* p) const {
     64         RSA_free(p);
     65     }
     66 };
     67 typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
     68 
     69 typedef UniquePtr<keymaster_device_t> Unique_keymaster_device_t;
     70 
     71 /**
     72  * Many OpenSSL APIs take ownership of an argument on success but don't free the argument
     73  * on failure. This means we need to tell our scoped pointers when we've transferred ownership,
     74  * without triggering a warning by not using the result of release().
     75  */
     76 #define OWNERSHIP_TRANSFERRED(obj) \
     77     typeof (obj.release()) _dummy __attribute__((unused)) = obj.release()
     78 
     79 /*
     80  * Checks this thread's error queue and logs if necessary.
     81  */
     82 static void logOpenSSLError(const char* location) {
     83     int error = ERR_get_error();
     84 
     85     if (error != 0) {
     86         char message[256];
     87         ERR_error_string_n(error, message, sizeof(message));
     88         ALOGE("OpenSSL error in %s %d: %s", location, error, message);
     89     }
     90 
     91     ERR_clear_error();
     92     ERR_remove_state(0);
     93 }
     94 
     95 static int exynos_km_generate_keypair(const keymaster_device_t* dev,
     96         const keymaster_keypair_t key_type, const void* key_params,
     97         uint8_t** keyBlob, size_t* keyBlobLength) {
     98     teeResult_t ret = TEE_ERR_NONE;
     99 
    100     if (key_type != TYPE_RSA) {
    101         ALOGE("Unsupported key type %d", key_type);
    102         return -1;
    103     } else if (key_params == NULL) {
    104         ALOGE("key_params == null");
    105         return -1;
    106     }
    107 
    108     keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params;
    109 
    110     if ((rsa_params->modulus_size != 512) &&
    111         (rsa_params->modulus_size != 1024) &&
    112         (rsa_params->modulus_size != 2048)) {
    113         ALOGE("key size(%d) is not supported\n", rsa_params->modulus_size);
    114         return -1;
    115     }
    116 
    117     UniquePtr<uint8_t> keyDataPtr(reinterpret_cast<uint8_t*>(malloc(RSA_KEY_BUFFER_SIZE)));
    118     if (keyDataPtr.get() == NULL) {
    119         ALOGE("memory allocation is failed");
    120         return -1;
    121     }
    122 
    123     ret = TEE_RSAGenerateKeyPair(TEE_KEYPAIR_RSACRT, keyDataPtr.get(), RSA_KEY_BUFFER_SIZE,
    124 				rsa_params->modulus_size, (uint32_t)rsa_params->public_exponent,
    125 				keyBlobLength);
    126     if (ret != TEE_ERR_NONE) {
    127         ALOGE("TEE_RSAGenerateKeyPair() is failed: %d", ret);
    128         return -1;
    129     }
    130 
    131    *keyBlob = keyDataPtr.release();
    132 
    133     return 0;
    134 }
    135 
    136 static int exynos_km_import_keypair(const keymaster_device_t* dev,
    137         const uint8_t* key, const size_t key_length,
    138         uint8_t** key_blob, size_t* key_blob_length) {
    139     uint8_t kbuf[RSA_KEY_BUFFER_SIZE];
    140     teeRsaKeyMeta_t metadata;
    141     uint32_t key_len = 0;
    142     teeResult_t ret = TEE_ERR_NONE;
    143 
    144     if (key == NULL) {
    145         ALOGE("input key == NULL");
    146         return -1;
    147     } else if (key_blob == NULL || key_blob_length == NULL) {
    148         ALOGE("output key blob or length == NULL");
    149         return -1;
    150     }
    151 
    152     /* decoding */
    153     Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length));
    154     if (pkcs8.get() == NULL) {
    155         logOpenSSLError("pkcs4.get");
    156         return -1;
    157     }
    158 
    159     /* assign to EVP */
    160     Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
    161     if (pkey.get() == NULL) {
    162         logOpenSSLError("pkey.get");
    163         return -1;
    164     }
    165     OWNERSHIP_TRANSFERRED(pkcs8);
    166 
    167     /* change key format */
    168     Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get()));
    169     if (rsa.get() == NULL) {
    170         logOpenSSLError("get rsa key format");
    171 	return -1;
    172     }
    173 
    174     key_len += sizeof(metadata);
    175 
    176     metadata.lenpubmod = BN_bn2bin(rsa->n, kbuf + key_len);
    177     key_len += metadata.lenpubmod;
    178     if (metadata.lenpubmod == (512 >> 3))
    179         metadata.keysize = TEE_RSA_KEY_SIZE_512;
    180     else if (metadata.lenpubmod == (1024 >> 3))
    181         metadata.keysize = TEE_RSA_KEY_SIZE_1024;
    182     else if (metadata.lenpubmod == (2048 >> 3))
    183         metadata.keysize = TEE_RSA_KEY_SIZE_2048;
    184     else {
    185         ALOGE("key size(%d) is not supported\n", metadata.lenpubmod << 3);
    186         return -1;
    187     }
    188 
    189     metadata.lenpubexp = BN_bn2bin(rsa->e, kbuf + key_len);
    190     key_len += metadata.lenpubexp;
    191 
    192     if ((rsa->p != NULL) && (rsa->q != NULL) && (rsa->dmp1 != NULL) &&
    193 	(rsa->dmq1 != NULL) && (rsa->iqmp != NULL))
    194     {
    195            metadata.keytype = TEE_KEYPAIR_RSACRT;
    196 	   metadata.rsacrtpriv.lenp = BN_bn2bin(rsa->p, kbuf + key_len);
    197 	   key_len += metadata.rsacrtpriv.lenp;
    198 	   metadata.rsacrtpriv.lenq = BN_bn2bin(rsa->q, kbuf + key_len);
    199 	   key_len += metadata.rsacrtpriv.lenq;
    200 	   metadata.rsacrtpriv.lendp = BN_bn2bin(rsa->dmp1, kbuf + key_len);
    201 	   key_len += metadata.rsacrtpriv.lendp;
    202 	   metadata.rsacrtpriv.lendq = BN_bn2bin(rsa->dmq1, kbuf + key_len);
    203 	   key_len += metadata.rsacrtpriv.lendq;
    204 	   metadata.rsacrtpriv.lenqinv = BN_bn2bin(rsa->iqmp, kbuf + key_len);
    205 	   key_len += metadata.rsacrtpriv.lenqinv;
    206     } else {
    207            metadata.keytype = TEE_KEYPAIR_RSA;
    208 	   metadata.rsapriv.lenpriexp = BN_bn2bin(rsa->p, kbuf + key_len);
    209 	   key_len += metadata.rsapriv.lenprimod;
    210     }
    211     memcpy(kbuf, &metadata, sizeof(metadata));
    212 
    213     UniquePtr<uint8_t> outPtr(reinterpret_cast<uint8_t*>(malloc(RSA_KEY_BUFFER_SIZE)));
    214     if (outPtr.get() == NULL) {
    215         ALOGE("memory allocation is failed");
    216         return -1;
    217     }
    218 
    219     *key_blob_length = RSA_KEY_BUFFER_SIZE;
    220 
    221     ret = TEE_KeyImport(kbuf, key_len, outPtr.get(), key_blob_length);
    222     if (ret != TEE_ERR_NONE) {
    223         ALOGE("TEE_KeyImport() is failed: %d", ret);
    224         return -1;
    225     }
    226 
    227     *key_blob = outPtr.release();
    228 
    229     return 0;
    230 }
    231 
    232 static int exynos_km_get_keypair_public(const struct keymaster_device* dev,
    233         const uint8_t* key_blob, const size_t key_blob_length,
    234         uint8_t** x509_data, size_t* x509_data_length) {
    235     uint32_t bin_mod_len;
    236     uint32_t bin_exp_len;
    237     teeResult_t ret = TEE_ERR_NONE;
    238 
    239     if (x509_data == NULL || x509_data_length == NULL) {
    240         ALOGE("output public key buffer == NULL");
    241         return -1;
    242     }
    243 
    244     UniquePtr<uint8_t> binModPtr(reinterpret_cast<uint8_t*>(malloc(RSA_KEY_MAX_SIZE)));
    245     if (binModPtr.get() == NULL) {
    246         ALOGE("memory allocation is failed");
    247         return -1;
    248     }
    249 
    250     UniquePtr<uint8_t> binExpPtr(reinterpret_cast<uint8_t*>(malloc(sizeof(uint32_t))));
    251     if (binExpPtr.get() == NULL) {
    252         ALOGE("memory allocation is failed");
    253         return -1;
    254     }
    255 
    256     bin_mod_len = RSA_KEY_MAX_SIZE;
    257     bin_exp_len = sizeof(uint32_t);
    258 
    259     ret = TEE_GetPubKey(key_blob, key_blob_length, binModPtr.get(), &bin_mod_len, binExpPtr.get(),
    260 			&bin_exp_len);
    261     if (ret != TEE_ERR_NONE) {
    262         ALOGE("TEE_GetPubKey() is failed: %d", ret);
    263         return -1;
    264     }
    265 
    266     Unique_BIGNUM bn_mod(BN_new());
    267     if (bn_mod.get() == NULL) {
    268         ALOGE("memory allocation is failed");
    269         return -1;
    270     }
    271 
    272     Unique_BIGNUM bn_exp(BN_new());
    273     if (bn_exp.get() == NULL) {
    274         ALOGE("memory allocation is failed");
    275         return -1;
    276     }
    277 
    278     BN_bin2bn(binModPtr.get(), bin_mod_len, bn_mod.get());
    279     BN_bin2bn(binExpPtr.get(), bin_exp_len, bn_exp.get());
    280 
    281     /* assign to RSA */
    282     Unique_RSA rsa(RSA_new());
    283     if (rsa.get() == NULL) {
    284         logOpenSSLError("rsa.get");
    285         return -1;
    286     }
    287 
    288     RSA* rsa_tmp = rsa.get();
    289 
    290     rsa_tmp->n = bn_mod.release();
    291     rsa_tmp->e = bn_exp.release();
    292 
    293     /* assign to EVP */
    294     Unique_EVP_PKEY pkey(EVP_PKEY_new());
    295     if (pkey.get() == NULL) {
    296         logOpenSSLError("allocate EVP_PKEY");
    297         return -1;
    298     }
    299 
    300     if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) == 0) {
    301         logOpenSSLError("assing RSA to EVP_PKEY");
    302         return -1;
    303     }
    304     OWNERSHIP_TRANSFERRED(rsa);
    305 
    306     /* change to x.509 format */
    307     int len = i2d_PUBKEY(pkey.get(), NULL);
    308     if (len <= 0) {
    309         logOpenSSLError("i2d_PUBKEY");
    310         return -1;
    311     }
    312 
    313     UniquePtr<uint8_t> key(static_cast<uint8_t*>(malloc(len)));
    314     if (key.get() == NULL) {
    315         ALOGE("Could not allocate memory for public key data");
    316         return -1;
    317     }
    318 
    319     unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get());
    320     if (i2d_PUBKEY(pkey.get(), &tmp) != len) {
    321         logOpenSSLError("Compare results");
    322         return -1;
    323     }
    324 
    325     *x509_data_length = len;
    326     *x509_data = key.release();
    327 
    328     return 0;
    329 }
    330 
    331 static int exynos_km_sign_data(const keymaster_device_t* dev,
    332         const void* params,
    333         const uint8_t* keyBlob, const size_t keyBlobLength,
    334         const uint8_t* data, const size_t dataLength,
    335         uint8_t** signedData, size_t* signedDataLength) {
    336     teeResult_t ret = TEE_ERR_NONE;
    337 
    338     if (data == NULL) {
    339         ALOGE("input data to sign == NULL");
    340         return -1;
    341     } else if (signedData == NULL || signedDataLength == NULL) {
    342         ALOGE("output signature buffer == NULL");
    343         return -1;
    344     }
    345 
    346     keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params;
    347     if (sign_params->digest_type != DIGEST_NONE) {
    348         ALOGE("Cannot handle digest type %d", sign_params->digest_type);
    349         return -1;
    350     } else if (sign_params->padding_type != PADDING_NONE) {
    351         ALOGE("Cannot handle padding type %d", sign_params->padding_type);
    352         return -1;
    353     }
    354 
    355     UniquePtr<uint8_t> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(RSA_KEY_MAX_SIZE)));
    356     if (signedDataPtr.get() == NULL) {
    357         ALOGE("memory allocation is failed");
    358         return -1;
    359     }
    360 
    361     *signedDataLength = RSA_KEY_MAX_SIZE;
    362 
    363     /* binder gives us read-only mappings we can't use with mobicore */
    364     void *tmpData = malloc(dataLength);
    365     memcpy(tmpData, data, dataLength);
    366     ret = TEE_RSASign(keyBlob, keyBlobLength, (const uint8_t *)tmpData, dataLength, signedDataPtr.get(),
    367 			signedDataLength, TEE_RSA_NODIGEST_NOPADDING);
    368     free(tmpData);
    369     if (ret != TEE_ERR_NONE) {
    370         ALOGE("TEE_RSASign() is failed: %d", ret);
    371         return -1;
    372     }
    373 
    374     *signedData = signedDataPtr.release();
    375 
    376     return 0;
    377 }
    378 
    379 static int exynos_km_verify_data(const keymaster_device_t* dev,
    380         const void* params,
    381         const uint8_t* keyBlob, const size_t keyBlobLength,
    382         const uint8_t* signedData, const size_t signedDataLength,
    383         const uint8_t* signature, const size_t signatureLength) {
    384     bool result;
    385     teeResult_t ret = TEE_ERR_NONE;
    386 
    387     if (signedData == NULL || signature == NULL) {
    388         ALOGE("data or signature buffers == NULL");
    389         return -1;
    390     }
    391 
    392     keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params;
    393     if (sign_params->digest_type != DIGEST_NONE) {
    394         ALOGE("Cannot handle digest type %d", sign_params->digest_type);
    395         return -1;
    396     } else if (sign_params->padding_type != PADDING_NONE) {
    397         ALOGE("Cannot handle padding type %d", sign_params->padding_type);
    398         return -1;
    399     } else if (signatureLength != signedDataLength) {
    400         ALOGE("signed data length must be signature length");
    401         return -1;
    402     }
    403 
    404     void *tmpSignedData = malloc(signedDataLength);
    405     memcpy(tmpSignedData, signedData, signedDataLength);
    406     void *tmpSig = malloc(signatureLength);
    407     memcpy(tmpSig, signature, signatureLength);
    408     ret = TEE_RSAVerify(keyBlob, keyBlobLength, (const uint8_t*)tmpSignedData, signedDataLength, (const uint8_t *)tmpSig,
    409 			signatureLength, TEE_RSA_NODIGEST_NOPADDING, &result);
    410     free(tmpSignedData);
    411     free(tmpSig);
    412     if (ret != TEE_ERR_NONE) {
    413         ALOGE("TEE_RSAVerify() is failed: %d", ret);
    414         return -1;
    415     }
    416 
    417     return (result == true) ? 0 : -1;
    418 }
    419 
    420 /* Close an opened Exynos KM instance */
    421 static int exynos_km_close(hw_device_t *dev) {
    422     free(dev);
    423     return 0;
    424 }
    425 
    426 /*
    427  * Generic device handling
    428  */
    429 static int exynos_km_open(const hw_module_t* module, const char* name,
    430         hw_device_t** device) {
    431     if (strcmp(name, KEYSTORE_KEYMASTER) != 0)
    432         return -EINVAL;
    433 
    434     Unique_keymaster_device_t dev(new keymaster_device_t);
    435     if (dev.get() == NULL)
    436         return -ENOMEM;
    437 
    438     dev->common.tag = HARDWARE_DEVICE_TAG;
    439     dev->common.version = 1;
    440     dev->common.module = (struct hw_module_t*) module;
    441     dev->common.close = exynos_km_close;
    442 
    443     dev->flags = 0;
    444 
    445     dev->generate_keypair = exynos_km_generate_keypair;
    446     dev->import_keypair = exynos_km_import_keypair;
    447     dev->get_keypair_public = exynos_km_get_keypair_public;
    448     dev->delete_keypair = NULL;
    449     dev->delete_all = NULL;
    450     dev->sign_data = exynos_km_sign_data;
    451     dev->verify_data = exynos_km_verify_data;
    452 
    453     ERR_load_crypto_strings();
    454     ERR_load_BIO_strings();
    455 
    456     *device = reinterpret_cast<hw_device_t*>(dev.release());
    457 
    458     return 0;
    459 }
    460 
    461 static struct hw_module_methods_t keystore_module_methods = {
    462     open: exynos_km_open,
    463 };
    464 
    465 struct keystore_module HAL_MODULE_INFO_SYM
    466 __attribute__ ((visibility ("default"))) = {
    467     common: {
    468         tag: HARDWARE_MODULE_TAG,
    469         version_major: 1,
    470         version_minor: 0,
    471         id: KEYSTORE_HARDWARE_MODULE_ID,
    472         name: "Keymaster Exynos HAL",
    473         author: "Samsung S.LSI",
    474         methods: &keystore_module_methods,
    475         dso: 0,
    476         reserved: {},
    477     },
    478 };
    479