diff options
author | Ricardo Cerqueira <cyanogenmod@cerqueira.org> | 2013-11-01 16:06:20 +0000 |
---|---|---|
committer | Ricardo Cerqueira <cyanogenmod@cerqueira.org> | 2013-11-01 16:06:20 +0000 |
commit | b5992b09a6f55d16f148fd6b405b6e8a8b0dc06b (patch) | |
tree | 9e7157b3333487e6c4e5101efc08a7bda4902e4b | |
parent | b57bd4a1d4c7e737a8a6e09f35aba1b93626c89f (diff) | |
parent | ee8068b9e7bfb2770635062fc9c2035be2142bd8 (diff) | |
download | android_system_security-stable/cm-11.0-XNF8Y.tar.gz android_system_security-stable/cm-11.0-XNF8Y.tar.bz2 android_system_security-stable/cm-11.0-XNF8Y.zip |
Merge tag 'android-4.4_r1' into cm-11.0cm-11.0-XNPH44S-bacon-5fa8c79c0bcm-11.0-XNPH33R-bacon-3628510d76cm-11.0-XNPH30O-bacon-4f280f505acm-11.0-XNPH25R-bacon-d22b777afacm-11.0-XNPH22R-bacon-03d77315eacm-11.0-XNPH05Q-tomato-9828f8e9cccm-11.0-XNPH05Q-bacon-5229c4ef56stable/cm-11.0-XNG3Cstable/cm-11.0-XNG2Sstable/cm-11.0-XNF9Xstable/cm-11.0-XNF8Ystable/cm-11.0shipping/cm-11.0
Android 4.4 Release 1.0
-rw-r--r-- | keystore-engine/Android.mk | 10 | ||||
-rw-r--r-- | keystore-engine/dsa_meth.cpp | 152 | ||||
-rw-r--r-- | keystore-engine/ecdsa_meth.cpp | 155 | ||||
-rw-r--r-- | keystore-engine/eng_keystore.cpp | 309 | ||||
-rw-r--r-- | keystore-engine/keyhandle.cpp | 76 | ||||
-rw-r--r-- | keystore-engine/methods.h | 74 | ||||
-rw-r--r-- | keystore-engine/rsa_meth.cpp | 242 | ||||
-rw-r--r-- | keystore/Android.mk | 10 | ||||
-rw-r--r-- | keystore/IKeystoreService.cpp | 53 | ||||
-rw-r--r-- | keystore/defaults.h | 42 | ||||
-rw-r--r-- | keystore/include/keystore/IKeystoreService.h | 18 | ||||
-rw-r--r-- | keystore/include/keystore/keystore.h | 3 | ||||
-rw-r--r-- | keystore/keyblob_utils.cpp | 6 | ||||
-rw-r--r-- | keystore/keystore.cpp | 262 | ||||
-rw-r--r-- | softkeymaster/Android.mk | 22 | ||||
-rw-r--r-- | softkeymaster/include/keymaster/softkeymaster.h | 46 | ||||
-rw-r--r-- | softkeymaster/keymaster_openssl.cpp | 476 | ||||
-rw-r--r-- | softkeymaster/module.cpp | 97 |
18 files changed, 1602 insertions, 451 deletions
diff --git a/keystore-engine/Android.mk b/keystore-engine/Android.mk index 40fb6c3..e7cab53 100644 --- a/keystore-engine/Android.mk +++ b/keystore-engine/Android.mk @@ -22,12 +22,18 @@ LOCAL_MODULE_TAGS := optional LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/ssl/engines -LOCAL_SRC_FILES := eng_keystore.cpp +LOCAL_SRC_FILES := \ + eng_keystore.cpp \ + keyhandle.cpp \ + ecdsa_meth.cpp \ + dsa_meth.cpp \ + rsa_meth.cpp LOCAL_CFLAGS := -fvisibility=hidden -Wall -Werror LOCAL_C_INCLUDES += \ - external/openssl/include + external/openssl/include \ + external/openssl LOCAL_SHARED_LIBRARIES += \ libcrypto \ diff --git a/keystore-engine/dsa_meth.cpp b/keystore-engine/dsa_meth.cpp new file mode 100644 index 0000000..6adfa2d --- /dev/null +++ b/keystore-engine/dsa_meth.cpp @@ -0,0 +1,152 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include <utils/UniquePtr.h> + +//#define LOG_NDEBUG 0 +#define LOG_TAG "OpenSSL-keystore-dsa" +#include <cutils/log.h> + +#include <binder/IServiceManager.h> +#include <keystore/IKeystoreService.h> + +#include <openssl/dsa.h> +#include <openssl/engine.h> + +#include "methods.h" + + +using namespace android; + +struct DSA_SIG_Delete { + void operator()(DSA_SIG* p) const { + DSA_SIG_free(p); + } +}; +typedef UniquePtr<DSA_SIG, struct DSA_SIG_Delete> Unique_DSA_SIG; + +static DSA_SIG* keystore_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) { + ALOGV("keystore_dsa_do_sign(%p, %d, %p)", dgst, dlen, dsa); + + uint8_t* key_id = reinterpret_cast<uint8_t*>(DSA_get_ex_data(dsa, dsa_key_handle)); + if (key_id == NULL) { + ALOGE("key had no key_id!"); + return 0; + } + + sp<IServiceManager> sm = defaultServiceManager(); + sp<IBinder> binder = sm->getService(String16("android.security.keystore")); + sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); + + if (service == NULL) { + ALOGE("could not contact keystore"); + return 0; + } + + int num = DSA_size(dsa); + + uint8_t* reply = NULL; + size_t replyLen; + int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), dgst, + dlen, &reply, &replyLen); + if (ret < 0) { + ALOGW("There was an error during dsa_do_sign: could not connect"); + return 0; + } else if (ret != 0) { + ALOGW("Error during sign from keystore: %d", ret); + return 0; + } else if (replyLen <= 0) { + ALOGW("No valid signature returned"); + return 0; + } else if (replyLen > (size_t) num) { + ALOGW("Signature is too large"); + return 0; + } + + Unique_DSA_SIG dsa_sig(d2i_DSA_SIG(NULL, + const_cast<const unsigned char**>(reinterpret_cast<unsigned char**>(&reply)), + replyLen)); + if (dsa_sig.get() == NULL) { + ALOGW("conversion from DER to DSA_SIG failed"); + return 0; + } + + ALOGV("keystore_dsa_do_sign(%p, %d, %p) => returning %p len %llu", dgst, dlen, dsa, + dsa_sig.get(), replyLen); + return dsa_sig.release(); +} + +static DSA_METHOD keystore_dsa_meth = { + kKeystoreEngineId, /* name */ + keystore_dsa_do_sign, /* dsa_do_sign */ + NULL, /* dsa_sign_setup */ + NULL, /* dsa_do_verify */ + NULL, /* dsa_mod_exp */ + NULL, /* bn_mod_exp */ + NULL, /* init */ + NULL, /* finish */ + 0, /* flags */ + NULL, /* app_data */ + NULL, /* dsa_paramgen */ + NULL, /* dsa_keygen */ +}; + +static int register_dsa_methods() { + const DSA_METHOD* dsa_meth = DSA_OpenSSL(); + + keystore_dsa_meth.dsa_do_verify = dsa_meth->dsa_do_verify; + + return 1; +} + +int dsa_pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) { + Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey)); + if (!DSA_set_ex_data(dsa.get(), dsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) { + ALOGW("Could not set ex_data for loaded DSA key"); + return 0; + } + + DSA_set_method(dsa.get(), &keystore_dsa_meth); + + /* + * "DSA_set_ENGINE()" should probably be an OpenSSL API. Since it isn't, + * and EVP_PKEY_free() calls ENGINE_finish(), we need to call ENGINE_init() + * here. + */ + ENGINE_init(e); + dsa->engine = e; + + return 1; +} + +int dsa_register(ENGINE* e) { + if (!ENGINE_set_DSA(e, &keystore_dsa_meth) + || !register_dsa_methods()) { + ALOGE("Could not set up keystore DSA methods"); + return 0; + } + + return 1; +} diff --git a/keystore-engine/ecdsa_meth.cpp b/keystore-engine/ecdsa_meth.cpp new file mode 100644 index 0000000..7b673a2 --- /dev/null +++ b/keystore-engine/ecdsa_meth.cpp @@ -0,0 +1,155 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include <utils/UniquePtr.h> + +//#define LOG_NDEBUG 0 +#define LOG_TAG "OpenSSL-keystore-ecdsa" +#include <cutils/log.h> + +#include <binder/IServiceManager.h> +#include <keystore/IKeystoreService.h> + +#include <openssl/ecdsa.h> +#include <openssl/engine.h> + +// TODO replace this with real OpenSSL API when it exists +#include "crypto/ec/ec_lcl.h" +#include "crypto/ecdsa/ecs_locl.h" + +#include "methods.h" + + +using namespace android; + +struct ECDSA_SIG_Delete { + void operator()(ECDSA_SIG* p) const { + ECDSA_SIG_free(p); + } +}; +typedef UniquePtr<ECDSA_SIG, struct ECDSA_SIG_Delete> Unique_ECDSA_SIG; + +static ECDSA_SIG* keystore_ecdsa_do_sign(const unsigned char *dgst, int dlen, + const BIGNUM*, const BIGNUM*, EC_KEY *eckey) { + ALOGV("keystore_ecdsa_do_sign(%p, %d, %p)", dgst, dlen, eckey); + + uint8_t* key_id = reinterpret_cast<uint8_t*>(EC_KEY_get_key_method_data(eckey, + ex_data_dup, ex_data_free, ex_data_clear_free)); + if (key_id == NULL) { + ALOGE("key had no key_id!"); + return 0; + } + + sp<IServiceManager> sm = defaultServiceManager(); + sp<IBinder> binder = sm->getService(String16("android.security.keystore")); + sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); + + if (service == NULL) { + ALOGE("could not contact keystore"); + return 0; + } + + int num = ECDSA_size(eckey); + + uint8_t* reply = NULL; + size_t replyLen; + int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), dgst, + dlen, &reply, &replyLen); + if (ret < 0) { + ALOGW("There was an error during dsa_do_sign: could not connect"); + return 0; + } else if (ret != 0) { + ALOGW("Error during sign from keystore: %d", ret); + return 0; + } else if (replyLen <= 0) { + ALOGW("No valid signature returned"); + return 0; + } else if (replyLen > (size_t) num) { + ALOGW("Signature is too large"); + return 0; + } + + Unique_ECDSA_SIG ecdsa_sig(d2i_ECDSA_SIG(NULL, + const_cast<const unsigned char**>(reinterpret_cast<unsigned char**>(&reply)), + replyLen)); + if (ecdsa_sig.get() == NULL) { + ALOGW("conversion from DER to ECDSA_SIG failed"); + return 0; + } + + ALOGV("keystore_ecdsa_do_sign(%p, %d, %p) => returning %p len %llu", dgst, dlen, eckey, + ecdsa_sig.get(), replyLen); + return ecdsa_sig.release(); +} + +static ECDSA_METHOD keystore_ecdsa_meth = { + kKeystoreEngineId, /* name */ + keystore_ecdsa_do_sign, /* ecdsa_do_sign */ + NULL, /* ecdsa_sign_setup */ + NULL, /* ecdsa_do_verify */ + 0, /* flags */ + NULL, /* app_data */ +}; + +static int register_ecdsa_methods() { + const ECDSA_METHOD* ecdsa_meth = ECDSA_OpenSSL(); + + keystore_ecdsa_meth.ecdsa_do_verify = ecdsa_meth->ecdsa_do_verify; + + return 1; +} + +int ecdsa_pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) { + Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey)); + void* oldData = EC_KEY_insert_key_method_data(eckey.get(), + reinterpret_cast<void*>(strdup(key_id)), ex_data_dup, ex_data_free, + ex_data_clear_free); + if (oldData != NULL) { + free(oldData); + } + + ECDSA_set_method(eckey.get(), &keystore_ecdsa_meth); + + /* + * "ECDSA_set_ENGINE()" should probably be an OpenSSL API. Since it isn't, + * and EC_KEY_free() calls ENGINE_finish(), we need to call ENGINE_init() + * here. + */ + ECDSA_DATA *ecdsa = ecdsa_check(eckey.get()); + ENGINE_init(e); + ecdsa->engine = e; + + return 1; +} + +int ecdsa_register(ENGINE* e) { + if (!ENGINE_set_ECDSA(e, &keystore_ecdsa_meth) + || !register_ecdsa_methods()) { + ALOGE("Could not set up keystore ECDSA methods"); + return 0; + } + + return 1; +} diff --git a/keystore-engine/eng_keystore.cpp b/keystore-engine/eng_keystore.cpp index e771c2e..6f5b01a 100644 --- a/keystore-engine/eng_keystore.cpp +++ b/keystore-engine/eng_keystore.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 The Android Open Source Project + * Copyright 2012 The Android Open Source Project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -30,9 +30,12 @@ #include <string.h> #include <unistd.h> -#include <openssl/objects.h> +#include <openssl/dsa.h> #include <openssl/engine.h> +#include <openssl/ec.h> #include <openssl/evp.h> +#include <openssl/objects.h> +#include <openssl/rsa.h> //#define LOG_NDEBUG 0 #define LOG_TAG "OpenSSL-keystore" @@ -42,11 +45,26 @@ #include <keystore/keystore.h> #include <keystore/IKeystoreService.h> +#include "methods.h" + using namespace android; #define DYNAMIC_ENGINE -#define KEYSTORE_ENGINE_ID "keystore" -#define KEYSTORE_ENGINE_NAME "Android keystore engine" +const char* kKeystoreEngineId = "keystore"; +static const char* kKeystoreEngineDesc = "Android keystore engine"; + + +/* + * ex_data index for keystore's key alias. + */ +int rsa_key_handle; +int dsa_key_handle; + + +/* + * Only initialize the *_key_handle once. + */ +static pthread_once_t key_handle_control = PTHREAD_ONCE_INIT; /** * Many OpenSSL APIs take ownership of an argument on success but don't free the argument @@ -56,6 +74,7 @@ using namespace android; #define OWNERSHIP_TRANSFERRED(obj) \ typeof (obj.release()) _dummy __attribute__((unused)) = obj.release() + struct ENGINE_Delete { void operator()(ENGINE* p) const { ENGINE_free(p); @@ -70,225 +89,13 @@ struct EVP_PKEY_Delete { }; typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY; -struct RSA_Delete { - void operator()(RSA* p) const { - RSA_free(p); - } -}; -typedef UniquePtr<RSA, RSA_Delete> Unique_RSA; - - -/* - * RSA ex_data index for keystore's key handle. - */ -static int rsa_key_handle; - -/* - * Only initialize the rsa_key_handle once. - */ -static pthread_once_t rsa_key_handle_control = PTHREAD_ONCE_INIT; - - /** - * Makes sure the ex_data for the keyhandle is initially set to NULL. - */ -int keyhandle_new(void*, void*, CRYPTO_EX_DATA* ad, int idx, long, void*) { - return CRYPTO_set_ex_data(ad, idx, NULL); -} - -/** - * Frees a previously allocated keyhandle stored in ex_data. - */ -void keyhandle_free(void *, void *ptr, CRYPTO_EX_DATA*, int, long, void*) { - char* keyhandle = reinterpret_cast<char*>(ptr); - if (keyhandle != NULL) { - free(keyhandle); - } -} - -/** - * Duplicates a keyhandle stored in ex_data in case we copy a key. + * Called to initialize RSA's ex_data for the key_id handle. This should + * only be called when protected by a lock. */ -int keyhandle_dup(CRYPTO_EX_DATA* to, CRYPTO_EX_DATA*, void *ptrRef, int idx, long, void *) { - // This appears to be a bug in OpenSSL. - void** ptr = reinterpret_cast<void**>(ptrRef); - char* keyhandle = reinterpret_cast<char*>(*ptr); - if (keyhandle != NULL) { - char* keyhandle_copy = strdup(keyhandle); - *ptr = keyhandle_copy; - - // Call this in case OpenSSL is fixed in the future. - (void) CRYPTO_set_ex_data(to, idx, keyhandle_copy); - } - return 1; -} - -int keystore_rsa_priv_enc(int flen, const unsigned char* from, unsigned char* to, RSA* rsa, - int padding) { - ALOGV("keystore_rsa_priv_enc(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding); - - int num = RSA_size(rsa); - UniquePtr<uint8_t> padded(new uint8_t[num]); - if (padded.get() == NULL) { - ALOGE("could not allocate padded signature"); - return 0; - } - - switch (padding) { - case RSA_PKCS1_PADDING: - if (!RSA_padding_add_PKCS1_type_1(padded.get(), num, from, flen)) { - return 0; - } - break; - case RSA_X931_PADDING: - if (!RSA_padding_add_X931(padded.get(), num, from, flen)) { - return 0; - } - break; - case RSA_NO_PADDING: - if (!RSA_padding_add_none(padded.get(), num, from, flen)) { - return 0; - } - break; - default: - ALOGE("Unknown padding type: %d", padding); - return 0; - } - - uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle)); - if (key_id == NULL) { - ALOGE("key had no key_id!"); - return 0; - } - - sp<IServiceManager> sm = defaultServiceManager(); - sp<IBinder> binder = sm->getService(String16("android.security.keystore")); - sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); - - if (service == NULL) { - ALOGE("could not contact keystore"); - return 0; - } - - uint8_t* reply = NULL; - size_t replyLen; - int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), padded.get(), - num, &reply, &replyLen); - if (ret < 0) { - ALOGW("There was an error during signing: could not connect"); - free(reply); - return 0; - } else if (ret != 0) { - ALOGW("Error during signing from keystore: %d", ret); - free(reply); - return 0; - } else if (replyLen <= 0) { - ALOGW("No valid signature returned"); - return 0; - } - - memcpy(to, reply, replyLen); - free(reply); - - ALOGV("rsa=%p keystore_rsa_priv_enc => returning %p len %llu", rsa, to, - (unsigned long long) replyLen); - return static_cast<int>(replyLen); -} - -int keystore_rsa_priv_dec(int flen, const unsigned char* from, unsigned char* to, RSA* rsa, - int padding) { - ALOGV("keystore_rsa_priv_dec(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding); - - uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle)); - if (key_id == NULL) { - ALOGE("key had no key_id!"); - return 0; - } - - sp<IServiceManager> sm = defaultServiceManager(); - sp<IBinder> binder = sm->getService(String16("android.security.keystore")); - sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); - - if (service == NULL) { - ALOGE("could not contact keystore"); - return 0; - } - - int num = RSA_size(rsa); - - uint8_t* reply = NULL; - size_t replyLen; - int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), from, - flen, &reply, &replyLen); - if (ret < 0) { - ALOGW("There was an error during rsa_mod_exp: could not connect"); - return 0; - } else if (ret != 0) { - ALOGW("Error during sign from keystore: %d", ret); - return 0; - } else if (replyLen <= 0) { - ALOGW("No valid signature returned"); - return 0; - } - - /* Trim off the top zero if it's there */ - uint8_t* alignedReply; - if (*reply == 0x00) { - alignedReply = reply + 1; - replyLen--; - } else { - alignedReply = reply; - } - - int outSize; - switch (padding) { - case RSA_PKCS1_PADDING: - outSize = RSA_padding_check_PKCS1_type_2(to, num, alignedReply, replyLen, num); - break; - case RSA_X931_PADDING: - outSize = RSA_padding_check_X931(to, num, alignedReply, replyLen, num); - break; - case RSA_NO_PADDING: - outSize = RSA_padding_check_none(to, num, alignedReply, replyLen, num); - break; - default: - ALOGE("Unknown padding type: %d", padding); - outSize = -1; - break; - } - - free(reply); - - ALOGV("rsa=%p keystore_rsa_priv_dec => returning %p len %llu", rsa, to, outSize); - return outSize; -} - -static RSA_METHOD keystore_rsa_meth = { - KEYSTORE_ENGINE_NAME, - NULL, /* rsa_pub_enc (wrap) */ - NULL, /* rsa_pub_dec (verification) */ - keystore_rsa_priv_enc, /* rsa_priv_enc (signing) */ - keystore_rsa_priv_dec, /* rsa_priv_dec (unwrap) */ - NULL, /* rsa_mod_exp */ - NULL, /* bn_mod_exp */ - NULL, /* init */ - NULL, /* finish */ - RSA_FLAG_EXT_PKEY | RSA_FLAG_NO_BLINDING, /* flags */ - NULL, /* app_data */ - NULL, /* rsa_sign */ - NULL, /* rsa_verify */ - NULL, /* rsa_keygen */ -}; - -static int register_rsa_methods() { - const RSA_METHOD* rsa_meth = RSA_PKCS1_SSLeay(); - - keystore_rsa_meth.rsa_pub_enc = rsa_meth->rsa_pub_enc; - keystore_rsa_meth.rsa_pub_dec = rsa_meth->rsa_pub_dec; - keystore_rsa_meth.rsa_mod_exp = rsa_meth->rsa_mod_exp; - keystore_rsa_meth.bn_mod_exp = rsa_meth->bn_mod_exp; - - return 1; +static void init_key_handle() { + rsa_key_handle = RSA_get_ex_new_index(0, NULL, keyhandle_new, keyhandle_dup, keyhandle_free); + dsa_key_handle = DSA_get_ex_new_index(0, NULL, keyhandle_new, keyhandle_dup, keyhandle_free); } static EVP_PKEY* keystore_loadkey(ENGINE* e, const char* key_id, UI_METHOD* ui_method, @@ -331,24 +138,16 @@ static EVP_PKEY* keystore_loadkey(ENGINE* e, const char* key_id, UI_METHOD* ui_m } switch (EVP_PKEY_type(pkey->type)) { + case EVP_PKEY_DSA: { + dsa_pkey_setup(e, pkey.get(), key_id); + break; + } case EVP_PKEY_RSA: { - Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get())); - if (!RSA_set_ex_data(rsa.get(), rsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) { - ALOGW("Could not set ex_data for loaded RSA key"); - return NULL; - } - - RSA_set_method(rsa.get(), &keystore_rsa_meth); - RSA_blinding_off(rsa.get()); - - /* - * This should probably be an OpenSSL API, but EVP_PKEY_free calls - * ENGINE_finish(), so we need to call ENGINE_init() here. - */ - ENGINE_init(e); - rsa->engine = e; - rsa->flags |= RSA_FLAG_EXT_PKEY; - + rsa_pkey_setup(e, pkey.get(), key_id); + break; + } + case EVP_PKEY_EC: { + ecdsa_pkey_setup(e, pkey.get(), key_id); break; } default: @@ -363,20 +162,11 @@ static const ENGINE_CMD_DEFN keystore_cmd_defns[] = { {0, NULL, NULL, 0} }; -/** - * Called to initialize RSA's ex_data for the key_id handle. This should - * only be called when protected by a lock. - */ -static void init_rsa_key_handle() { - rsa_key_handle = RSA_get_ex_new_index(0, NULL, keyhandle_new, keyhandle_dup, - keyhandle_free); -} - static int keystore_engine_setup(ENGINE* e) { ALOGV("keystore_engine_setup"); - if (!ENGINE_set_id(e, KEYSTORE_ENGINE_ID) - || !ENGINE_set_name(e, KEYSTORE_ENGINE_NAME) + if (!ENGINE_set_id(e, kKeystoreEngineId) + || !ENGINE_set_name(e, kKeystoreEngineDesc) || !ENGINE_set_load_privkey_function(e, keystore_loadkey) || !ENGINE_set_load_pubkey_function(e, keystore_loadkey) || !ENGINE_set_flags(e, 0) @@ -385,16 +175,21 @@ static int keystore_engine_setup(ENGINE* e) { return 0; } - if (!ENGINE_set_RSA(e, &keystore_rsa_meth) - || !register_rsa_methods()) { - ALOGE("Could not set up keystore RSA methods"); + /* We need a handle in the keys types as well for keygen if it's not already initialized. */ + pthread_once(&key_handle_control, init_key_handle); + if ((rsa_key_handle < 0) || (dsa_key_handle < 0)) { + ALOGE("Could not set up ex_data index"); return 0; } - /* We need a handle in the RSA keys as well for keygen if it's not already initialized. */ - pthread_once(&rsa_key_handle_control, init_rsa_key_handle); - if (rsa_key_handle < 0) { - ALOGE("Could not set up RSA ex_data index"); + if (!dsa_register(e)) { + ALOGE("DSA registration failed"); + return 0; + } else if (!ecdsa_register(e)) { + ALOGE("ECDSA registration failed"); + return 0; + } else if (!rsa_register(e)) { + ALOGE("RSA registration failed"); return 0; } @@ -423,7 +218,7 @@ static int keystore_bind_fn(ENGINE *e, const char *id) { return 0; } - if (strcmp(id, KEYSTORE_ENGINE_ID)) { + if (strcmp(id, kKeystoreEngineId)) { return 0; } diff --git a/keystore-engine/keyhandle.cpp b/keystore-engine/keyhandle.cpp new file mode 100644 index 0000000..1799735 --- /dev/null +++ b/keystore-engine/keyhandle.cpp @@ -0,0 +1,76 @@ +/* + * Copyright 2012 The Android Open Source Project + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include <openssl/engine.h> + +/** + * Makes sure the ex_data for the keyhandle is initially set to NULL. + */ +int keyhandle_new(void*, void*, CRYPTO_EX_DATA* ad, int idx, long, void*) { + return CRYPTO_set_ex_data(ad, idx, NULL); +} + +/** + * Frees a previously allocated keyhandle stored in ex_data. + */ +void keyhandle_free(void *, void *ptr, CRYPTO_EX_DATA*, int, long, void*) { + char* keyhandle = reinterpret_cast<char*>(ptr); + if (keyhandle != NULL) { + free(keyhandle); + } +} + +/** + * Duplicates a keyhandle stored in ex_data in case we copy a key. + */ +int keyhandle_dup(CRYPTO_EX_DATA* to, CRYPTO_EX_DATA*, void *ptrRef, int idx, long, void *) { + // This appears to be a bug in OpenSSL. + void** ptr = reinterpret_cast<void**>(ptrRef); + char* keyhandle = reinterpret_cast<char*>(*ptr); + if (keyhandle != NULL) { + char* keyhandle_copy = strdup(keyhandle); + *ptr = keyhandle_copy; + + // Call this in case OpenSSL is fixed in the future. + (void) CRYPTO_set_ex_data(to, idx, keyhandle_copy); + } + return 1; +} + +void *ex_data_dup(void *data) { + char* keyhandle = reinterpret_cast<char*>(data); + return strdup(keyhandle); +} + +void ex_data_free(void *data) { + char* keyhandle = reinterpret_cast<char*>(data); + free(keyhandle); +} + +void ex_data_clear_free(void *data) { + char* keyhandle = reinterpret_cast<char*>(data); + memset(data, '\0', strlen(keyhandle)); + free(keyhandle); +} diff --git a/keystore-engine/methods.h b/keystore-engine/methods.h new file mode 100644 index 0000000..fb85942 --- /dev/null +++ b/keystore-engine/methods.h @@ -0,0 +1,74 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* For ENGINE method registration purposes. */ +extern const char* kKeystoreEngineId; + +extern int dsa_key_handle; +extern int rsa_key_handle; + +struct DSA_Delete { + void operator()(DSA* p) const { + DSA_free(p); + } +}; +typedef UniquePtr<DSA, struct DSA_Delete> Unique_DSA; + +struct EC_KEY_Delete { + void operator()(EC_KEY* p) const { + EC_KEY_free(p); + } +}; +typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY; + +struct RSA_Delete { + void operator()(RSA* p) const { + RSA_free(p); + } +}; +typedef UniquePtr<RSA, struct RSA_Delete> Unique_RSA; + + +/* Keyhandles for ENGINE metadata */ +int keyhandle_new(void*, void*, CRYPTO_EX_DATA* ad, int idx, long, void*); +void keyhandle_free(void *, void *ptr, CRYPTO_EX_DATA*, int, long, void*); +int keyhandle_dup(CRYPTO_EX_DATA* to, CRYPTO_EX_DATA*, void *ptrRef, int idx, long, void *); + +/* For EC_EX_DATA stuff */ +void *ex_data_dup(void *); +void ex_data_free(void *); +void ex_data_clear_free(void *); + +/* ECDSA */ +int ecdsa_register(ENGINE *); +int ecdsa_pkey_setup(ENGINE *, EVP_PKEY*, const char*); + +/* DSA */ +int dsa_register(ENGINE *); +int dsa_pkey_setup(ENGINE *, EVP_PKEY*, const char*); + +/* RSA */ +int rsa_register(ENGINE *); +int rsa_pkey_setup(ENGINE *, EVP_PKEY*, const char*); diff --git a/keystore-engine/rsa_meth.cpp b/keystore-engine/rsa_meth.cpp new file mode 100644 index 0000000..b949fa4 --- /dev/null +++ b/keystore-engine/rsa_meth.cpp @@ -0,0 +1,242 @@ +/* + * Copyright 2012 The Android Open Source Project + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include <utils/UniquePtr.h> + +//#define LOG_NDEBUG 0 +#define LOG_TAG "OpenSSL-keystore-rsa" +#include <cutils/log.h> + +#include <binder/IServiceManager.h> +#include <keystore/IKeystoreService.h> + +#include <openssl/rsa.h> +#include <openssl/engine.h> + +#include "methods.h" + + +using namespace android; + + +int keystore_rsa_priv_enc(int flen, const unsigned char* from, unsigned char* to, RSA* rsa, + int padding) { + ALOGV("keystore_rsa_priv_enc(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding); + + int num = RSA_size(rsa); + UniquePtr<uint8_t> padded(new uint8_t[num]); + if (padded.get() == NULL) { + ALOGE("could not allocate padded signature"); + return 0; + } + + switch (padding) { + case RSA_PKCS1_PADDING: + if (!RSA_padding_add_PKCS1_type_1(padded.get(), num, from, flen)) { + return 0; + } + break; + case RSA_X931_PADDING: + if (!RSA_padding_add_X931(padded.get(), num, from, flen)) { + return 0; + } + break; + case RSA_NO_PADDING: + if (!RSA_padding_add_none(padded.get(), num, from, flen)) { + return 0; + } + break; + default: + ALOGE("Unknown padding type: %d", padding); + return 0; + } + + uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle)); + if (key_id == NULL) { + ALOGE("key had no key_id!"); + return 0; + } + + sp<IServiceManager> sm = defaultServiceManager(); + sp<IBinder> binder = sm->getService(String16("android.security.keystore")); + sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); + + if (service == NULL) { + ALOGE("could not contact keystore"); + return 0; + } + + uint8_t* reply = NULL; + size_t replyLen; + int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), padded.get(), + num, &reply, &replyLen); + if (ret < 0) { + ALOGW("There was an error during signing: could not connect"); + free(reply); + return 0; + } else if (ret != 0) { + ALOGW("Error during signing from keystore: %d", ret); + free(reply); + return 0; + } else if (replyLen <= 0) { + ALOGW("No valid signature returned"); + return 0; + } + + memcpy(to, reply, replyLen); + free(reply); + + ALOGV("rsa=%p keystore_rsa_priv_enc => returning %p len %llu", rsa, to, + (unsigned long long) replyLen); + return static_cast<int>(replyLen); +} + +int keystore_rsa_priv_dec(int flen, const unsigned char* from, unsigned char* to, RSA* rsa, + int padding) { + ALOGV("keystore_rsa_priv_dec(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding); + + uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle)); + if (key_id == NULL) { + ALOGE("key had no key_id!"); + return 0; + } + + sp<IServiceManager> sm = defaultServiceManager(); + sp<IBinder> binder = sm->getService(String16("android.security.keystore")); + sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); + + if (service == NULL) { + ALOGE("could not contact keystore"); + return 0; + } + + int num = RSA_size(rsa); + + uint8_t* reply = NULL; + size_t replyLen; + int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), from, + flen, &reply, &replyLen); + if (ret < 0) { + ALOGW("There was an error during rsa_mod_exp: could not connect"); + return 0; + } else if (ret != 0) { + ALOGW("Error during sign from keystore: %d", ret); + return 0; + } else if (replyLen <= 0) { + ALOGW("No valid signature returned"); + return 0; + } + + /* Trim off the top zero if it's there */ + uint8_t* alignedReply; + if (*reply == 0x00) { + alignedReply = reply + 1; + replyLen--; + } else { + alignedReply = reply; + } + + int outSize; + switch (padding) { + case RSA_PKCS1_PADDING: + outSize = RSA_padding_check_PKCS1_type_2(to, num, alignedReply, replyLen, num); + break; + case RSA_X931_PADDING: + outSize = RSA_padding_check_X931(to, num, alignedReply, replyLen, num); + break; + case RSA_NO_PADDING: + outSize = RSA_padding_check_none(to, num, alignedReply, replyLen, num); + break; + default: + ALOGE("Unknown padding type: %d", padding); + outSize = -1; + break; + } + + free(reply); + + ALOGV("rsa=%p keystore_rsa_priv_dec => returning %p len %llu", rsa, to, outSize); + return outSize; +} + +static RSA_METHOD keystore_rsa_meth = { + kKeystoreEngineId, + NULL, /* rsa_pub_enc (wrap) */ + NULL, /* rsa_pub_dec (verification) */ + keystore_rsa_priv_enc, /* rsa_priv_enc (signing) */ + keystore_rsa_priv_dec, /* rsa_priv_dec (unwrap) */ + NULL, /* rsa_mod_exp */ + NULL, /* bn_mod_exp */ + NULL, /* init */ + NULL, /* finish */ + RSA_FLAG_EXT_PKEY | RSA_FLAG_NO_BLINDING, /* flags */ + NULL, /* app_data */ + NULL, /* rsa_sign */ + NULL, /* rsa_verify */ + NULL, /* rsa_keygen */ +}; + +static int register_rsa_methods() { + const RSA_METHOD* rsa_meth = RSA_PKCS1_SSLeay(); + + keystore_rsa_meth.rsa_pub_enc = rsa_meth->rsa_pub_enc; + keystore_rsa_meth.rsa_pub_dec = rsa_meth->rsa_pub_dec; + keystore_rsa_meth.rsa_mod_exp = rsa_meth->rsa_mod_exp; + keystore_rsa_meth.bn_mod_exp = rsa_meth->bn_mod_exp; + + return 1; +} + +int rsa_pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) { + Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey)); + if (!RSA_set_ex_data(rsa.get(), rsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) { + ALOGW("Could not set ex_data for loaded RSA key"); + return 0; + } + + RSA_set_method(rsa.get(), &keystore_rsa_meth); + RSA_blinding_off(rsa.get()); + + /* + * "RSA_set_ENGINE()" should probably be an OpenSSL API. Since it isn't, + * and EVP_PKEY_free() calls ENGINE_finish(), we need to call ENGINE_init() + * here. + */ + ENGINE_init(e); + rsa->engine = e; + rsa->flags |= RSA_FLAG_EXT_PKEY; + + return 1; +} + +int rsa_register(ENGINE* e) { + if (!ENGINE_set_RSA(e, &keystore_rsa_meth) + || !register_rsa_methods()) { + ALOGE("Could not set up keystore RSA methods"); + return 0; + } + + return 1; +} diff --git a/keystore/Android.mk b/keystore/Android.mk index f495f34..47b7e84 100644 --- a/keystore/Android.mk +++ b/keystore/Android.mk @@ -20,7 +20,15 @@ include $(CLEAR_VARS) LOCAL_CFLAGS := -Wall -Wextra -Werror LOCAL_SRC_FILES := keystore.cpp keyblob_utils.cpp LOCAL_C_INCLUDES := external/openssl/include -LOCAL_SHARED_LIBRARIES := libcutils libcrypto libhardware libkeystore_binder libutils liblog libbinder +LOCAL_SHARED_LIBRARIES := \ + libbinder \ + libcutils \ + libcrypto \ + libhardware \ + libkeystore_binder \ + liblog \ + libsoftkeymaster \ + libutils LOCAL_MODULE := keystore LOCAL_MODULE_TAGS := optional LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk diff --git a/keystore/IKeystoreService.cpp b/keystore/IKeystoreService.cpp index 46f7244..727e746 100644 --- a/keystore/IKeystoreService.cpp +++ b/keystore/IKeystoreService.cpp @@ -29,6 +29,21 @@ namespace android { +KeystoreArg::KeystoreArg(const void* data, size_t len) + : mData(data), mSize(len) { +} + +KeystoreArg::~KeystoreArg() { +} + +const void *KeystoreArg::data() const { + return mData; +} + +size_t KeystoreArg::size() const { + return mSize; +} + class BpKeystoreService: public BpInterface<IKeystoreService> { public: @@ -270,13 +285,24 @@ public: return ret; } - virtual int32_t generate(const String16& name, int uid, int32_t flags) + virtual int32_t generate(const String16& name, int32_t uid, int32_t keyType, int32_t keySize, + int32_t flags, Vector<sp<KeystoreArg> >* args) { Parcel data, reply; data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor()); data.writeString16(name); data.writeInt32(uid); + data.writeInt32(keyType); + data.writeInt32(keySize); data.writeInt32(flags); + data.writeInt32(args->size()); + for (Vector<sp<KeystoreArg> >::iterator it = args->begin(); it != args->end(); ++it) { + sp<KeystoreArg> item = *it; + size_t keyLength = item->size(); + data.writeInt32(keyLength); + void* buf = data.writeInplace(keyLength); + memcpy(buf, item->data(), keyLength); + } status_t status = remote()->transact(BnKeystoreService::GENERATE, data, &reply); if (status != NO_ERROR) { ALOGD("generate() could not contact remote: %d\n", status); @@ -516,10 +542,11 @@ public: return ret; } - virtual int32_t is_hardware_backed() + virtual int32_t is_hardware_backed(const String16& keyType) { Parcel data, reply; data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor()); + data.writeString16(keyType); status_t status = remote()->transact(BnKeystoreService::IS_HARDWARE_BACKED, data, &reply); if (status != NO_ERROR) { ALOGD("is_hardware_backed() could not contact remote: %d\n", status); @@ -677,9 +704,24 @@ status_t BnKeystoreService::onTransact( case GENERATE: { CHECK_INTERFACE(IKeystoreService, data, reply); String16 name = data.readString16(); - int uid = data.readInt32(); + int32_t uid = data.readInt32(); + int32_t keyType = data.readInt32(); + int32_t keySize = data.readInt32(); int32_t flags = data.readInt32(); - int32_t ret = generate(name, uid, flags); + Vector<sp<KeystoreArg> > args; + ssize_t numArgs = data.readInt32(); + if (numArgs > 0) { + for (size_t i = 0; i < (size_t) numArgs; i++) { + ssize_t inSize = data.readInt32(); + if (inSize >= 0 && (size_t) inSize <= data.dataAvail()) { + sp<KeystoreArg> arg = new KeystoreArg(data.readInplace(inSize), inSize); + args.push_back(arg); + } else { + args.push_back(NULL); + } + } + } + int32_t ret = generate(name, uid, keyType, keySize, flags, &args); reply->writeNoException(); reply->writeInt32(ret); return NO_ERROR; @@ -819,7 +861,8 @@ status_t BnKeystoreService::onTransact( } break; case IS_HARDWARE_BACKED: { CHECK_INTERFACE(IKeystoreService, data, reply); - int32_t ret = is_hardware_backed(); + String16 keyType = data.readString16(); + int32_t ret = is_hardware_backed(keyType); reply->writeNoException(); reply->writeInt32(ret); return NO_ERROR; diff --git a/keystore/defaults.h b/keystore/defaults.h new file mode 100644 index 0000000..9232dd0 --- /dev/null +++ b/keystore/defaults.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef KEYSTORE_DEFAULTS_H_ +#define KEYSTORE_DEFAULTS_H_ + +/* + * These must be kept in sync with + * frameworks/base/keystore/java/android/security/KeyPairGeneratorSpec.java + */ + +/* DSA */ +#define DSA_DEFAULT_KEY_SIZE 1024 +#define DSA_MIN_KEY_SIZE 512 +#define DSA_MAX_KEY_SIZE 8192 + +/* EC */ +#define EC_DEFAULT_KEY_SIZE 256 +#define EC_MIN_KEY_SIZE 192 +#define EC_MAX_KEY_SIZE 521 + +/* RSA */ +#define RSA_DEFAULT_KEY_SIZE 2048 +#define RSA_DEFAULT_EXPONENT 0x10001 +#define RSA_MIN_KEY_SIZE 512 +#define RSA_MAX_KEY_SIZE 8192 + +#endif /* KEYSTORE_DEFAULTS_H_ */ diff --git a/keystore/include/keystore/IKeystoreService.h b/keystore/include/keystore/IKeystoreService.h index 9b54454..d7281e3 100644 --- a/keystore/include/keystore/IKeystoreService.h +++ b/keystore/include/keystore/IKeystoreService.h @@ -23,6 +23,19 @@ namespace android { +class KeystoreArg : public RefBase { +public: + KeystoreArg(const void *data, size_t len); + ~KeystoreArg(); + + const void* data() const; + size_t size() const; + +private: + const void* mData; + size_t mSize; +}; + /* * This must be kept manually in sync with frameworks/base's IKeystoreService.java */ @@ -79,7 +92,8 @@ public: virtual int32_t zero() = 0; - virtual int32_t generate(const String16& name, int uid, int32_t flags) = 0; + virtual int32_t generate(const String16& name, int32_t uid, int32_t keyType, int32_t keySize, + int32_t flags, Vector<sp<KeystoreArg> >* args) = 0; virtual int32_t import(const String16& name, const uint8_t* data, size_t length, int uid, int32_t flags) = 0; @@ -103,7 +117,7 @@ public: virtual int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey, int32_t destUid) = 0; - virtual int32_t is_hardware_backed() = 0; + virtual int32_t is_hardware_backed(const String16& keyType) = 0; virtual int32_t clear_uid(int64_t uid) = 0; }; diff --git a/keystore/include/keystore/keystore.h b/keystore/include/keystore/keystore.h index 973c447..32354df 100644 --- a/keystore/include/keystore/keystore.h +++ b/keystore/include/keystore/keystore.h @@ -48,7 +48,8 @@ enum ResponseCode { */ enum { KEYSTORE_FLAG_NONE = 0, - KEYSTORE_FLAG_ENCRYPTED = 1, + KEYSTORE_FLAG_ENCRYPTED = 1 << 0, + KEYSTORE_FLAG_FALLBACK = 1 << 1, }; /** diff --git a/keystore/keyblob_utils.cpp b/keystore/keyblob_utils.cpp index fd82d2a..b208073 100644 --- a/keystore/keyblob_utils.cpp +++ b/keystore/keyblob_utils.cpp @@ -26,9 +26,11 @@ * * 4-byte SOFT_KEY_MAGIC * - * 4-byte 32-bit integer big endian for public_key_length + * 4-byte 32-bit integer big endian for public_key_length. This may be zero + * length which indicates the public key should be derived from the + * private key. * - * public_key_length bytes of public key + * public_key_length bytes of public key (may be empty) * * 4-byte 32-bit integer big endian for private_key_length * diff --git a/keystore/keystore.cpp b/keystore/keystore.cpp index 9b08398..7366c34 100644 --- a/keystore/keystore.cpp +++ b/keystore/keystore.cpp @@ -42,6 +42,8 @@ #include <hardware/keymaster.h> +#include <keymaster/softkeymaster.h> + #include <utils/String8.h> #include <utils/UniquePtr.h> #include <utils/Vector.h> @@ -56,6 +58,8 @@ #include <keystore/keystore.h> +#include "defaults.h" + /* KeyStore is a secured storage for key-value pairs. In this implementation, * each file stores one key-value pair. Keys are encoded in file names, and * values are encrypted with checksums. The encryption key is protected by a @@ -67,6 +71,13 @@ #define PASSWORD_SIZE VALUE_SIZE +struct BIGNUM_Delete { + void operator()(BIGNUM* p) const { + BN_free(p); + } +}; +typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM; + struct BIO_Delete { void operator()(BIO* p) const { BIO_free(p); @@ -261,13 +272,6 @@ static int encode_key(char* out, const android::String8& keyName) { return length; } -static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) { - int n = snprintf(out, NAME_MAX, "%u_", uid); - out += n; - - return n + encode_key(out, keyName); -} - /* * Converts from the "escaped" format on disk to actual name. * This will be smaller than the input string. @@ -417,7 +421,11 @@ public: mBlob.version = CURRENT_BLOB_VERSION; mBlob.type = uint8_t(type); - mBlob.flags = KEYSTORE_FLAG_NONE; + if (type == TYPE_MASTER_KEY) { + mBlob.flags = KEYSTORE_FLAG_ENCRYPTED; + } else { + mBlob.flags = KEYSTORE_FLAG_NONE; + } } Blob(blob b) { @@ -462,6 +470,18 @@ public: } } + bool isFallback() const { + return mBlob.flags & KEYSTORE_FLAG_FALLBACK; + } + + void setFallback(bool fallback) { + if (fallback) { + mBlob.flags |= KEYSTORE_FLAG_FALLBACK; + } else { + mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK; + } + } + void setVersion(uint8_t version) { mBlob.version = version; } @@ -905,19 +925,19 @@ public: } android::String8 getKeyName(const android::String8& keyName) { - char encoded[encode_key_length(keyName)]; + char encoded[encode_key_length(keyName) + 1]; // add 1 for null char encode_key(encoded, keyName); return android::String8(encoded); } android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) { - char encoded[encode_key_length(keyName)]; + char encoded[encode_key_length(keyName) + 1]; // add 1 for null char encode_key(encoded, keyName); return android::String8::format("%u_%s", uid, encoded); } android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) { - char encoded[encode_key_length(keyName)]; + char encoded[encode_key_length(keyName) + 1]; // add 1 for null char encode_key(encoded, keyName); return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid, encoded); @@ -995,6 +1015,23 @@ public: } } + /* + * This will upgrade software-backed keys to hardware-backed keys when + * the HAL for the device supports the newer key types. + */ + if (rc == NO_ERROR && type == TYPE_KEY_PAIR + && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2 + && keyBlob->isFallback()) { + ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename, + uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE); + + // The HAL allowed the import, reget the key to have the "fresh" + // version. + if (imported == NO_ERROR) { + rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid); + } + } + if (type != TYPE_ANY && keyBlob->getType() != type) { ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type); return KEY_NOT_FOUND; @@ -1047,37 +1084,48 @@ public: return SYSTEM_ERROR; } + bool isFallback = false; rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength); if (rc) { - ALOGE("Error while importing keypair: %d", rc); - return SYSTEM_ERROR; + // If this is an old device HAL, try to fall back to an old version + if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) { + rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength); + isFallback = true; + } + + if (rc) { + ALOGE("Error while importing keypair: %d", rc); + return SYSTEM_ERROR; + } } Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR); free(data); keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); + keyBlob.setFallback(isFallback); return put(filename, &keyBlob, uid); } - bool isHardwareBacked() const { - return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0; + bool isHardwareBacked(const android::String16& keyType) const { + if (mDevice == NULL) { + ALOGW("can't get keymaster device"); + return false; + } + + if (sRSAKeyType == keyType) { + return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0; + } else { + return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 + && (mDevice->common.module->module_api_version + >= KEYMASTER_MODULE_API_VERSION_0_2); + } } ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid, const BlobType type) { - char filename[NAME_MAX]; - encode_key_for_uid(filename, uid, keyName); - - UserState* userState = getUserState(uid); - android::String8 filepath8; - - filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename); - if (filepath8.string() == NULL) { - ALOGW("can't create filepath for key %s", filename); - return SYSTEM_ERROR; - } + android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid)); ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid); if (responseCode == NO_ERROR) { @@ -1087,8 +1135,7 @@ public: // If this is one of the legacy UID->UID mappings, use it. uid_t euid = get_keystore_euid(uid); if (euid != uid) { - encode_key_for_uid(filename, euid, keyName); - filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename); + filepath8 = getKeyNameForUidWithDir(keyName, euid); responseCode = get(filepath8.string(), keyBlob, type, uid); if (responseCode == NO_ERROR) { return responseCode; @@ -1096,13 +1143,14 @@ public: } // They might be using a granted key. - encode_key(filename, keyName); + android::String8 filename8 = getKeyName(keyName); char* end; - strtoul(filename, &end, 10); + strtoul(filename8.string(), &end, 10); if (end[0] != '_' || end[1] == 0) { return KEY_NOT_FOUND; } - filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename); + filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(), + filename8.string()); if (!hasGrant(filepath8.string(), uid)) { return responseCode; } @@ -1157,6 +1205,7 @@ public: private: static const char* sOldMasterKey; static const char* sMetaDataFile; + static const android::String16 sRSAKeyType; Entropy* mEntropy; keymaster_device_t* mDevice; @@ -1373,6 +1422,8 @@ private: const char* KeyStore::sOldMasterKey = ".masterkey"; const char* KeyStore::sMetaDataFile = ".metadata"; +const android::String16 KeyStore::sRSAKeyType("RSA"); + namespace android { class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient { public: @@ -1445,6 +1496,8 @@ public: String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC); + keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); + return mKeyStore->put(filename.string(), &keyBlob, callingUid); } @@ -1656,7 +1709,8 @@ public: return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR; } - int32_t generate(const String16& name, int targetUid, int32_t flags) { + int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize, + int32_t flags, Vector<sp<KeystoreArg> >* args) { uid_t callingUid = IPCThreadState::self()->getCallingUid(); if (!has_permission(callingUid, P_INSERT)) { ALOGW("permission denied for %d: generate", callingUid); @@ -1678,6 +1732,7 @@ public: uint8_t* data; size_t dataLength; int rc; + bool isFallback = false; const keymaster_device_t* device = mKeyStore->getDevice(); if (device == NULL) { @@ -1688,11 +1743,107 @@ public: return ::SYSTEM_ERROR; } - keymaster_rsa_keygen_params_t rsa_params; - rsa_params.modulus_size = 2048; - rsa_params.public_exponent = 0x10001; + if (keyType == EVP_PKEY_DSA) { + keymaster_dsa_keygen_params_t dsa_params; + memset(&dsa_params, '\0', sizeof(dsa_params)); + + if (keySize == -1) { + keySize = DSA_DEFAULT_KEY_SIZE; + } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE + || keySize > DSA_MAX_KEY_SIZE) { + ALOGI("invalid key size %d", keySize); + return ::SYSTEM_ERROR; + } + dsa_params.key_size = keySize; + + if (args->size() == 3) { + sp<KeystoreArg> gArg = args->itemAt(0); + sp<KeystoreArg> pArg = args->itemAt(1); + sp<KeystoreArg> qArg = args->itemAt(2); + + if (gArg != NULL && pArg != NULL && qArg != NULL) { + dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data()); + dsa_params.generator_len = gArg->size(); + + dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data()); + dsa_params.prime_p_len = pArg->size(); + + dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data()); + dsa_params.prime_q_len = qArg->size(); + } else { + ALOGI("not all DSA parameters were read"); + return ::SYSTEM_ERROR; + } + } else if (args->size() != 0) { + ALOGI("DSA args must be 3"); + return ::SYSTEM_ERROR; + } + + if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) { + rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength); + } else { + isFallback = true; + rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength); + } + } else if (keyType == EVP_PKEY_EC) { + keymaster_ec_keygen_params_t ec_params; + memset(&ec_params, '\0', sizeof(ec_params)); + + if (keySize == -1) { + keySize = EC_DEFAULT_KEY_SIZE; + } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) { + ALOGI("invalid key size %d", keySize); + return ::SYSTEM_ERROR; + } + ec_params.field_size = keySize; + + if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) { + rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength); + } else { + isFallback = true; + rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength); + } + } else if (keyType == EVP_PKEY_RSA) { + keymaster_rsa_keygen_params_t rsa_params; + memset(&rsa_params, '\0', sizeof(rsa_params)); + rsa_params.public_exponent = RSA_DEFAULT_EXPONENT; + + if (keySize == -1) { + keySize = RSA_DEFAULT_KEY_SIZE; + } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) { + ALOGI("invalid key size %d", keySize); + return ::SYSTEM_ERROR; + } + rsa_params.modulus_size = keySize; + + if (args->size() > 1) { + ALOGI("invalid number of arguments: %d", args->size()); + return ::SYSTEM_ERROR; + } else if (args->size() == 1) { + sp<KeystoreArg> pubExpBlob = args->itemAt(0); + if (pubExpBlob != NULL) { + Unique_BIGNUM pubExpBn( + BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()), + pubExpBlob->size(), NULL)); + if (pubExpBn.get() == NULL) { + ALOGI("Could not convert public exponent to BN"); + return ::SYSTEM_ERROR; + } + unsigned long pubExp = BN_get_word(pubExpBn.get()); + if (pubExp == 0xFFFFFFFFL) { + ALOGI("cannot represent public exponent as a long value"); + return ::SYSTEM_ERROR; + } + rsa_params.public_exponent = pubExp; + } + } + + rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength); + } else { + ALOGW("Unsupported key type %d", keyType); + rc = -1; + } - rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength); if (rc) { return ::SYSTEM_ERROR; } @@ -1703,6 +1854,9 @@ public: Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR); free(data); + keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); + keyBlob.setFallback(isFallback); + return mKeyStore->put(filename.string(), &keyBlob, callingUid); } @@ -1767,8 +1921,13 @@ public: params.digest_type = DIGEST_NONE; params.padding_type = PADDING_NONE; - rc = device->sign_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), - data, length, out, outLength); + if (keyBlob.isFallback()) { + rc = openssl_sign_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, + length, out, outLength); + } else { + rc = device->sign_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, + length, out, outLength); + } if (rc) { ALOGW("device couldn't sign data"); return ::SYSTEM_ERROR; @@ -1814,8 +1973,13 @@ public: params.digest_type = DIGEST_NONE; params.padding_type = PADDING_NONE; - rc = device->verify_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), - data, dataLength, signature, signatureLength); + if (keyBlob.isFallback()) { + rc = openssl_verify_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, + dataLength, signature, signatureLength); + } else { + rc = device->verify_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, + dataLength, signature, signatureLength); + } if (rc) { return ::SYSTEM_ERROR; } else { @@ -1862,8 +2026,14 @@ public: return ::SYSTEM_ERROR; } - int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey, - pubkeyLength); + int rc; + if (keyBlob.isFallback()) { + rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey, + pubkeyLength); + } else { + rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey, + pubkeyLength); + } if (rc) { return ::SYSTEM_ERROR; } @@ -1901,7 +2071,7 @@ public: rc = ::SYSTEM_ERROR; } else { // A device doesn't have to implement delete_keypair. - if (device->delete_keypair != NULL) { + if (device->delete_keypair != NULL && !keyBlob.isFallback()) { if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) { rc = ::SYSTEM_ERROR; } @@ -2053,8 +2223,8 @@ public: return mKeyStore->put(targetFile.string(), &keyBlob, callingUid); } - int32_t is_hardware_backed() { - return mKeyStore->isHardwareBacked() ? 1 : 0; + int32_t is_hardware_backed(const String16& keyType) { + return mKeyStore->isHardwareBacked(keyType) ? 1 : 0; } int32_t clear_uid(int64_t targetUid) { @@ -2114,7 +2284,7 @@ public: if (keyBlob.getType() == ::TYPE_KEY_PAIR) { // A device doesn't have to implement delete_keypair. - if (device->delete_keypair != NULL) { + if (device->delete_keypair != NULL && !keyBlob.isFallback()) { if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) { rc = ::SYSTEM_ERROR; ALOGW("device couldn't remove %s", filename.string()); diff --git a/softkeymaster/Android.mk b/softkeymaster/Android.mk index 8e19a93..0064d01 100644 --- a/softkeymaster/Android.mk +++ b/softkeymaster/Android.mk @@ -15,23 +15,27 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) - LOCAL_MODULE := keystore.default - LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/hw +LOCAL_SRC_FILES := module.cpp +LOCAL_C_INCLUDES := \ + system/security/keystore \ + external/openssl/include +LOCAL_CFLAGS = -fvisibility=hidden -Wall -Werror +LOCAL_SHARED_LIBRARIES := libcrypto liblog libkeystore_binder libsoftkeymaster +LOCAL_MODULE_TAGS := optional +LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk +include $(BUILD_SHARED_LIBRARY) +include $(CLEAR_VARS) +LOCAL_MODULE := libsoftkeymaster LOCAL_SRC_FILES := keymaster_openssl.cpp - LOCAL_C_INCLUDES := \ system/security/keystore \ external/openssl/include - -LOCAL_C_FLAGS = -fvisibility=hidden -Wall -Werror - +LOCAL_CFLAGS = -fvisibility=hidden -Wall -Werror LOCAL_SHARED_LIBRARIES := libcrypto liblog libkeystore_binder - LOCAL_MODULE_TAGS := optional - +LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk - include $(BUILD_SHARED_LIBRARY) diff --git a/softkeymaster/include/keymaster/softkeymaster.h b/softkeymaster/include/keymaster/softkeymaster.h new file mode 100644 index 0000000..7d43099 --- /dev/null +++ b/softkeymaster/include/keymaster/softkeymaster.h @@ -0,0 +1,46 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <hardware/keymaster.h> + +#ifndef SOFTKEYMASTER_INCLUDE_KEYMASTER_SOFTKEYMASTER_H +#define SOFTKEYMASTER_INCLUDE_KEYMASTER_SOFTKEYMASTER_H + +int openssl_generate_keypair(const keymaster_device_t* dev, + const keymaster_keypair_t key_type, const void* key_params, + uint8_t** keyBlob, size_t* keyBlobLength); + +int openssl_import_keypair(const keymaster_device_t* dev, + const uint8_t* key, const size_t key_length, + uint8_t** key_blob, size_t* key_blob_length); + +int openssl_get_keypair_public(const struct keymaster_device* dev, + const uint8_t* key_blob, const size_t key_blob_length, + uint8_t** x509_data, size_t* x509_data_length); + +int openssl_sign_data(const keymaster_device_t* dev, + const void* params, + const uint8_t* keyBlob, const size_t keyBlobLength, + const uint8_t* data, const size_t dataLength, + uint8_t** signedData, size_t* signedDataLength); + +int openssl_verify_data(const keymaster_device_t* dev, + const void* params, + const uint8_t* keyBlob, const size_t keyBlobLength, + const uint8_t* signedData, const size_t signedDataLength, + const uint8_t* signature, const size_t signatureLength); + +#endif /* SOFTKEYMASTER_INCLUDE_KEYMASTER_SOFTKEYMASTER_H */ diff --git a/softkeymaster/keymaster_openssl.cpp b/softkeymaster/keymaster_openssl.cpp index 3620450..4aaaea2 100644 --- a/softkeymaster/keymaster_openssl.cpp +++ b/softkeymaster/keymaster_openssl.cpp @@ -57,6 +57,20 @@ struct PKCS8_PRIV_KEY_INFO_Delete { }; typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO; +struct DSA_Delete { + void operator()(DSA* p) const { + DSA_free(p); + } +}; +typedef UniquePtr<DSA, DSA_Delete> Unique_DSA; + +struct EC_KEY_Delete { + void operator()(EC_KEY* p) const { + EC_KEY_free(p); + } +}; +typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY; + struct RSA_Delete { void operator()(RSA* p) const { RSA_free(p); @@ -93,12 +107,15 @@ static void logOpenSSLError(const char* location) { } static int wrap_key(EVP_PKEY* pkey, int type, uint8_t** keyBlob, size_t* keyBlobLength) { - /* Find the length of each size */ - int publicLen = i2d_PublicKey(pkey, NULL); + /* + * Find the length of each size. Public key is not needed anymore but must be kept for + * alignment purposes. + */ + int publicLen = 0; int privateLen = i2d_PrivateKey(pkey, NULL); - if (privateLen <= 0 || publicLen <= 0) { - ALOGE("private or public key size was too big"); + if (privateLen <= 0) { + ALOGE("private key size was too big"); return -1; } @@ -106,7 +123,7 @@ static int wrap_key(EVP_PKEY* pkey, int type, uint8_t** keyBlob, size_t* keyBlob *keyBlobLength = get_softkey_header_size() + sizeof(int) + sizeof(int) + privateLen + sizeof(int) + publicLen; - UniquePtr<unsigned char[]> derData(new unsigned char[*keyBlobLength]); + UniquePtr<unsigned char> derData(new unsigned char[*keyBlobLength]); if (derData.get() == NULL) { ALOGE("could not allocate memory for key blob"); return -1; @@ -125,10 +142,6 @@ static int wrap_key(EVP_PKEY* pkey, int type, uint8_t** keyBlob, size_t* keyBlob for (int i = sizeof(int) - 1; i >= 0; i--) { *p++ = (publicLen >> (8*i)) & 0xFF; } - if (i2d_PublicKey(pkey, &p) != publicLen) { - logOpenSSLError("wrap_key"); - return -1; - } /* Write private key to allocated buffer */ for (int i = sizeof(int) - 1; i >= 0; i--) { @@ -174,12 +187,6 @@ static EVP_PKEY* unwrap_key(const uint8_t* keyBlob, const size_t keyBlobLength) type = (type << 8) | *p++; } - Unique_EVP_PKEY pkey(EVP_PKEY_new()); - if (pkey.get() == NULL) { - logOpenSSLError("unwrap_key"); - return NULL; - } - for (size_t i = 0; i < sizeof(int); i++) { publicLen = (publicLen << 8) | *p++; } @@ -187,9 +194,8 @@ static EVP_PKEY* unwrap_key(const uint8_t* keyBlob, const size_t keyBlobLength) ALOGE("public key length encoding error: size=%ld, end=%d", publicLen, end - p); return NULL; } - EVP_PKEY* tmp = pkey.get(); - d2i_PublicKey(type, &tmp, &p, publicLen); + p += publicLen; if (end - p < 2) { ALOGE("private key truncated"); return NULL; @@ -201,75 +207,217 @@ static EVP_PKEY* unwrap_key(const uint8_t* keyBlob, const size_t keyBlobLength) ALOGE("private key length encoding error: size=%ld, end=%d", privateLen, end - p); return NULL; } - d2i_PrivateKey(type, &tmp, &p, privateLen); + + Unique_EVP_PKEY pkey(EVP_PKEY_new()); + if (pkey.get() == NULL) { + logOpenSSLError("unwrap_key"); + return NULL; + } + EVP_PKEY* tmp = pkey.get(); + + if (d2i_PrivateKey(type, &tmp, &p, privateLen) == NULL) { + logOpenSSLError("unwrap_key"); + return NULL; + } return pkey.release(); } -static int openssl_generate_keypair(const keymaster_device_t* dev, - const keymaster_keypair_t key_type, const void* key_params, - uint8_t** keyBlob, size_t* keyBlobLength) { - ssize_t privateLen, publicLen; +static int generate_dsa_keypair(EVP_PKEY* pkey, const keymaster_dsa_keygen_params_t* dsa_params) +{ + if (dsa_params->key_size < 512) { + ALOGI("Requested DSA key size is too small (<512)"); + return -1; + } - if (key_type != TYPE_RSA) { - ALOGW("Unsupported key type %d", key_type); + Unique_DSA dsa(DSA_new()); + + if (dsa_params->generator_len == 0 || + dsa_params->prime_p_len == 0 || + dsa_params->prime_q_len == 0 || + dsa_params->generator == NULL|| + dsa_params->prime_p == NULL || + dsa_params->prime_q == NULL) { + if (DSA_generate_parameters_ex(dsa.get(), dsa_params->key_size, NULL, 0, NULL, NULL, + NULL) != 1) { + logOpenSSLError("generate_dsa_keypair"); + return -1; + } + } else { + dsa->g = BN_bin2bn(dsa_params->generator, + dsa_params->generator_len, + NULL); + if (dsa->g == NULL) { + logOpenSSLError("generate_dsa_keypair"); + return -1; + } + + dsa->p = BN_bin2bn(dsa_params->prime_p, + dsa_params->prime_p_len, + NULL); + if (dsa->p == NULL) { + logOpenSSLError("generate_dsa_keypair"); + return -1; + } + + dsa->q = BN_bin2bn(dsa_params->prime_q, + dsa_params->prime_q_len, + NULL); + if (dsa->q == NULL) { + logOpenSSLError("generate_dsa_keypair"); + return -1; + } + } + + if (DSA_generate_key(dsa.get()) != 1) { + logOpenSSLError("generate_dsa_keypair"); return -1; - } else if (key_params == NULL) { - ALOGW("key_params == null"); + } + + if (EVP_PKEY_assign_DSA(pkey, dsa.get()) == 0) { + logOpenSSLError("generate_dsa_keypair"); + return -1; + } + OWNERSHIP_TRANSFERRED(dsa); + + return 0; +} + +static int generate_ec_keypair(EVP_PKEY* pkey, const keymaster_ec_keygen_params_t* ec_params) +{ + EC_GROUP* group; + switch (ec_params->field_size) { + case 192: + group = EC_GROUP_new_by_curve_name(NID_X9_62_prime192v1); + break; + case 224: + group = EC_GROUP_new_by_curve_name(NID_secp224r1); + break; + case 256: + group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1); + break; + case 384: + group = EC_GROUP_new_by_curve_name(NID_secp384r1); + break; + case 521: + group = EC_GROUP_new_by_curve_name(NID_secp521r1); + break; + default: + group = NULL; + break; + } + + if (group == NULL) { + logOpenSSLError("generate_ec_keypair"); return -1; } - keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params; + EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED); + EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE); + /* initialize EC key */ + Unique_EC_KEY eckey(EC_KEY_new()); + if (eckey.get() == NULL) { + logOpenSSLError("generate_ec_keypair"); + return -1; + } + + if (EC_KEY_set_group(eckey.get(), group) != 1) { + logOpenSSLError("generate_ec_keypair"); + return -1; + } + + if (EC_KEY_generate_key(eckey.get()) != 1 + || EC_KEY_check_key(eckey.get()) < 0) { + logOpenSSLError("generate_ec_keypair"); + return -1; + } + + if (EVP_PKEY_assign_EC_KEY(pkey, eckey.get()) == 0) { + logOpenSSLError("generate_ec_keypair"); + return -1; + } + OWNERSHIP_TRANSFERRED(eckey); + + return 0; +} + +static int generate_rsa_keypair(EVP_PKEY* pkey, const keymaster_rsa_keygen_params_t* rsa_params) +{ Unique_BIGNUM bn(BN_new()); if (bn.get() == NULL) { - logOpenSSLError("openssl_generate_keypair"); + logOpenSSLError("generate_rsa_keypair"); return -1; } if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) { - logOpenSSLError("openssl_generate_keypair"); + logOpenSSLError("generate_rsa_keypair"); return -1; } /* initialize RSA */ Unique_RSA rsa(RSA_new()); if (rsa.get() == NULL) { - logOpenSSLError("openssl_generate_keypair"); + logOpenSSLError("generate_rsa_keypair"); return -1; } if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL) || RSA_check_key(rsa.get()) < 0) { - logOpenSSLError("openssl_generate_keypair"); + logOpenSSLError("generate_rsa_keypair"); return -1; } - /* assign to EVP */ + if (EVP_PKEY_assign_RSA(pkey, rsa.get()) == 0) { + logOpenSSLError("generate_rsa_keypair"); + return -1; + } + OWNERSHIP_TRANSFERRED(rsa); + + return 0; +} + +__attribute__ ((visibility ("default"))) +int openssl_generate_keypair(const keymaster_device_t*, + const keymaster_keypair_t key_type, const void* key_params, + uint8_t** keyBlob, size_t* keyBlobLength) { Unique_EVP_PKEY pkey(EVP_PKEY_new()); if (pkey.get() == NULL) { logOpenSSLError("openssl_generate_keypair"); return -1; } - if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) == 0) { - logOpenSSLError("openssl_generate_keypair"); + if (key_params == NULL) { + ALOGW("key_params == null"); + return -1; + } else if (key_type == TYPE_DSA) { + const keymaster_dsa_keygen_params_t* dsa_params = + (const keymaster_dsa_keygen_params_t*) key_params; + generate_dsa_keypair(pkey.get(), dsa_params); + } else if (key_type == TYPE_EC) { + const keymaster_ec_keygen_params_t* ec_params = + (const keymaster_ec_keygen_params_t*) key_params; + generate_ec_keypair(pkey.get(), ec_params); + } else if (key_type == TYPE_RSA) { + const keymaster_rsa_keygen_params_t* rsa_params = + (const keymaster_rsa_keygen_params_t*) key_params; + generate_rsa_keypair(pkey.get(), rsa_params); + } else { + ALOGW("Unsupported key type %d", key_type); return -1; } - OWNERSHIP_TRANSFERRED(rsa); - if (wrap_key(pkey.get(), EVP_PKEY_RSA, keyBlob, keyBlobLength)) { + if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), keyBlob, keyBlobLength)) { return -1; } return 0; } -static int openssl_import_keypair(const keymaster_device_t* dev, +__attribute__ ((visibility ("default"))) +int openssl_import_keypair(const keymaster_device_t*, const uint8_t* key, const size_t key_length, uint8_t** key_blob, size_t* key_blob_length) { - int response = -1; - if (key == NULL) { ALOGW("input key == NULL"); return -1; @@ -299,7 +447,8 @@ static int openssl_import_keypair(const keymaster_device_t* dev, return 0; } -static int openssl_get_keypair_public(const struct keymaster_device* dev, +__attribute__ ((visibility ("default"))) +int openssl_get_keypair_public(const struct keymaster_device*, const uint8_t* key_blob, const size_t key_blob_length, uint8_t** x509_data, size_t* x509_data_length) { @@ -338,35 +487,73 @@ static int openssl_get_keypair_public(const struct keymaster_device* dev, return 0; } -static int openssl_sign_data(const keymaster_device_t* dev, - const void* params, - const uint8_t* keyBlob, const size_t keyBlobLength, - const uint8_t* data, const size_t dataLength, - uint8_t** signedData, size_t* signedDataLength) { +static int sign_dsa(EVP_PKEY* pkey, keymaster_dsa_sign_params_t* sign_params, const uint8_t* data, + const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { + if (sign_params->digest_type != DIGEST_NONE) { + ALOGW("Cannot handle digest type %d", sign_params->digest_type); + return -1; + } - int result = -1; - EVP_MD_CTX ctx; - size_t maxSize; + Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey)); + if (dsa.get() == NULL) { + logOpenSSLError("openssl_sign_dsa"); + return -1; + } - if (data == NULL) { - ALOGW("input data to sign == NULL"); + unsigned int dsaSize = DSA_size(dsa.get()); + UniquePtr<uint8_t> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dsaSize))); + if (signedDataPtr.get() == NULL) { + logOpenSSLError("openssl_sign_dsa"); return -1; - } else if (signedData == NULL || signedDataLength == NULL) { - ALOGW("output signature buffer == NULL"); + } + + unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get()); + if (DSA_sign(0, data, dataLength, tmp, &dsaSize, dsa.get()) <= 0) { + logOpenSSLError("openssl_sign_dsa"); return -1; } - Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength)); - if (pkey.get() == NULL) { + *signedDataLength = dsaSize; + *signedData = signedDataPtr.release(); + + return 0; +} + +static int sign_ec(EVP_PKEY* pkey, keymaster_ec_sign_params_t* sign_params, const uint8_t* data, + const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { + if (sign_params->digest_type != DIGEST_NONE) { + ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } - if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) { - ALOGW("Cannot handle non-RSA keys yet"); + Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey)); + if (eckey.get() == NULL) { + logOpenSSLError("openssl_sign_ec"); return -1; } - keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; + unsigned int ecdsaSize = ECDSA_size(eckey.get()); + UniquePtr<uint8_t> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(ecdsaSize))); + if (signedDataPtr.get() == NULL) { + logOpenSSLError("openssl_sign_ec"); + return -1; + } + + unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get()); + if (ECDSA_sign(0, data, dataLength, tmp, &ecdsaSize, eckey.get()) <= 0) { + logOpenSSLError("openssl_sign_ec"); + return -1; + } + + *signedDataLength = ecdsaSize; + *signedData = signedDataPtr.release(); + + return 0; +} + + +static int sign_rsa(EVP_PKEY* pkey, keymaster_rsa_sign_params_t* sign_params, const uint8_t* data, + const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; @@ -375,37 +562,41 @@ static int openssl_sign_data(const keymaster_device_t* dev, return -1; } - Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get())); + Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey)); if (rsa.get() == NULL) { - logOpenSSLError("openssl_sign_data"); + logOpenSSLError("openssl_sign_rsa"); return -1; } UniquePtr<uint8_t> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dataLength))); if (signedDataPtr.get() == NULL) { - logOpenSSLError("openssl_sign_data"); + logOpenSSLError("openssl_sign_rsa"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get()); if (RSA_private_encrypt(dataLength, data, tmp, rsa.get(), RSA_NO_PADDING) <= 0) { - logOpenSSLError("openssl_sign_data"); + logOpenSSLError("openssl_sign_rsa"); return -1; } *signedDataLength = dataLength; *signedData = signedDataPtr.release(); + return 0; } -static int openssl_verify_data(const keymaster_device_t* dev, +__attribute__ ((visibility ("default"))) +int openssl_sign_data(const keymaster_device_t*, const void* params, const uint8_t* keyBlob, const size_t keyBlobLength, - const uint8_t* signedData, const size_t signedDataLength, - const uint8_t* signature, const size_t signatureLength) { - - if (signedData == NULL || signature == NULL) { - ALOGW("data or signature buffers == NULL"); + const uint8_t* data, const size_t dataLength, + uint8_t** signedData, size_t* signedDataLength) { + if (data == NULL) { + ALOGW("input data to sign == NULL"); + return -1; + } else if (signedData == NULL || signedDataLength == NULL) { + ALOGW("output signature buffer == NULL"); return -1; } @@ -414,12 +605,69 @@ static int openssl_verify_data(const keymaster_device_t* dev, return -1; } - if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) { - ALOGW("Cannot handle non-RSA keys yet"); + int type = EVP_PKEY_type(pkey->type); + if (type == EVP_PKEY_DSA) { + keymaster_dsa_sign_params_t* sign_params = (keymaster_dsa_sign_params_t*) params; + return sign_dsa(pkey.get(), sign_params, data, dataLength, signedData, signedDataLength); + } else if (type == EVP_PKEY_EC) { + keymaster_ec_sign_params_t* sign_params = (keymaster_ec_sign_params_t*) params; + return sign_ec(pkey.get(), sign_params, data, dataLength, signedData, signedDataLength); + } else if (type == EVP_PKEY_RSA) { + keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; + return sign_rsa(pkey.get(), sign_params, data, dataLength, signedData, signedDataLength); + } else { + ALOGW("Unsupported key type"); return -1; } +} - keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; +static int verify_dsa(EVP_PKEY* pkey, keymaster_dsa_sign_params_t* sign_params, + const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, + const size_t signatureLength) { + if (sign_params->digest_type != DIGEST_NONE) { + ALOGW("Cannot handle digest type %d", sign_params->digest_type); + return -1; + } + + Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey)); + if (dsa.get() == NULL) { + logOpenSSLError("openssl_verify_dsa"); + return -1; + } + + if (DSA_verify(0, signedData, signedDataLength, signature, signatureLength, dsa.get()) <= 0) { + logOpenSSLError("openssl_verify_dsa"); + return -1; + } + + return 0; +} + +static int verify_ec(EVP_PKEY* pkey, keymaster_ec_sign_params_t* sign_params, + const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, + const size_t signatureLength) { + if (sign_params->digest_type != DIGEST_NONE) { + ALOGW("Cannot handle digest type %d", sign_params->digest_type); + return -1; + } + + Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey)); + if (eckey.get() == NULL) { + logOpenSSLError("openssl_verify_ec"); + return -1; + } + + if (ECDSA_verify(0, signedData, signedDataLength, signature, signatureLength, eckey.get()) <= 0) { + logOpenSSLError("openssl_verify_ec"); + return -1; + } + + return 0; +} + +static int verify_rsa(EVP_PKEY* pkey, keymaster_rsa_sign_params_t* sign_params, + const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, + const size_t signatureLength) { if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; @@ -431,7 +679,7 @@ static int openssl_verify_data(const keymaster_device_t* dev, return -1; } - Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get())); + Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey)); if (rsa.get() == NULL) { logOpenSSLError("openssl_verify_data"); return -1; @@ -457,62 +705,38 @@ static int openssl_verify_data(const keymaster_device_t* dev, return result == 0 ? 0 : -1; } -/* Close an opened OpenSSL instance */ -static int openssl_close(hw_device_t *dev) { - free(dev); - return 0; -} - -/* - * Generic device handling - */ -static int openssl_open(const hw_module_t* module, const char* name, - hw_device_t** device) { - if (strcmp(name, KEYSTORE_KEYMASTER) != 0) - return -EINVAL; - - Unique_keymaster_device_t dev(new keymaster_device_t); - if (dev.get() == NULL) - return -ENOMEM; - - dev->common.tag = HARDWARE_DEVICE_TAG; - dev->common.version = 1; - dev->common.module = (struct hw_module_t*) module; - dev->common.close = openssl_close; - - dev->flags = KEYMASTER_SOFTWARE_ONLY; - - dev->generate_keypair = openssl_generate_keypair; - dev->import_keypair = openssl_import_keypair; - dev->get_keypair_public = openssl_get_keypair_public; - dev->delete_keypair = NULL; - dev->delete_all = NULL; - dev->sign_data = openssl_sign_data; - dev->verify_data = openssl_verify_data; +__attribute__ ((visibility ("default"))) +int openssl_verify_data(const keymaster_device_t*, + const void* params, + const uint8_t* keyBlob, const size_t keyBlobLength, + const uint8_t* signedData, const size_t signedDataLength, + const uint8_t* signature, const size_t signatureLength) { - ERR_load_crypto_strings(); - ERR_load_BIO_strings(); + if (signedData == NULL || signature == NULL) { + ALOGW("data or signature buffers == NULL"); + return -1; + } - *device = reinterpret_cast<hw_device_t*>(dev.release()); + Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength)); + if (pkey.get() == NULL) { + return -1; + } - return 0; + int type = EVP_PKEY_type(pkey->type); + if (type == EVP_PKEY_DSA) { + keymaster_dsa_sign_params_t* sign_params = (keymaster_dsa_sign_params_t*) params; + return verify_dsa(pkey.get(), sign_params, signedData, signedDataLength, signature, + signatureLength); + } else if (type == EVP_PKEY_RSA) { + keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; + return verify_rsa(pkey.get(), sign_params, signedData, signedDataLength, signature, + signatureLength); + } else if (type == EVP_PKEY_EC) { + keymaster_ec_sign_params_t* sign_params = (keymaster_ec_sign_params_t*) params; + return verify_ec(pkey.get(), sign_params, signedData, signedDataLength, signature, + signatureLength); + } else { + ALOGW("Unsupported key type %d", type); + return -1; + } } - -static struct hw_module_methods_t keystore_module_methods = { - open: openssl_open, -}; - -struct keystore_module HAL_MODULE_INFO_SYM -__attribute__ ((visibility ("default"))) = { - common: { - tag: HARDWARE_MODULE_TAG, - version_major: 1, - version_minor: 0, - id: KEYSTORE_HARDWARE_MODULE_ID, - name: "Keymaster OpenSSL HAL", - author: "The Android Open Source Project", - methods: &keystore_module_methods, - dso: 0, - reserved: {}, - }, -}; diff --git a/softkeymaster/module.cpp b/softkeymaster/module.cpp new file mode 100644 index 0000000..758dfe7 --- /dev/null +++ b/softkeymaster/module.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include <errno.h> +#include <string.h> +#include <stdint.h> + +#include <keymaster/softkeymaster.h> + +#include <keystore/keystore.h> + +#include <hardware/hardware.h> +#include <hardware/keymaster.h> + +#include <openssl/err.h> + +#include <utils/UniquePtr.h> + +// For debugging +//#define LOG_NDEBUG 0 + +#define LOG_TAG "OpenSSLKeyMaster" +#include <cutils/log.h> + +typedef UniquePtr<keymaster_device_t> Unique_keymaster_device_t; + +/* Close an opened OpenSSL instance */ +static int openssl_close(hw_device_t *dev) { + delete dev; + return 0; +} + +/* + * Generic device handling + */ +static int openssl_open(const hw_module_t* module, const char* name, + hw_device_t** device) { + if (strcmp(name, KEYSTORE_KEYMASTER) != 0) + return -EINVAL; + + Unique_keymaster_device_t dev(new keymaster_device_t); + if (dev.get() == NULL) + return -ENOMEM; + + dev->common.tag = HARDWARE_DEVICE_TAG; + dev->common.version = 1; + dev->common.module = (struct hw_module_t*) module; + dev->common.close = openssl_close; + + dev->flags = KEYMASTER_SOFTWARE_ONLY; + + dev->generate_keypair = openssl_generate_keypair; + dev->import_keypair = openssl_import_keypair; + dev->get_keypair_public = openssl_get_keypair_public; + dev->delete_keypair = NULL; + dev->delete_all = NULL; + dev->sign_data = openssl_sign_data; + dev->verify_data = openssl_verify_data; + + ERR_load_crypto_strings(); + ERR_load_BIO_strings(); + + *device = reinterpret_cast<hw_device_t*>(dev.release()); + + return 0; +} + +static struct hw_module_methods_t keystore_module_methods = { + open: openssl_open, +}; + +struct keystore_module HAL_MODULE_INFO_SYM +__attribute__ ((visibility ("default"))) = { + common: { + tag: HARDWARE_MODULE_TAG, + module_api_version: KEYMASTER_MODULE_API_VERSION_0_2, + hal_api_version: HARDWARE_HAL_API_VERSION, + id: KEYSTORE_HARDWARE_MODULE_ID, + name: "Keymaster OpenSSL HAL", + author: "The Android Open Source Project", + methods: &keystore_module_methods, + dso: 0, + reserved: {}, + }, +}; |