Add support for DSA and ECDSA key types

(cherry picked from commit 6071179a371fcd4c238375068ffd7d3cedea615d)

Bug: 10600582
Change-Id: I0d851bbe1230a31033614c9f9b9de94f1f842618
diff --git a/keystore-engine/Android.mk b/keystore-engine/Android.mk
index cb1a4b0..b975629 100644
--- a/keystore-engine/Android.mk
+++ b/keystore-engine/Android.mk
@@ -25,6 +25,7 @@
 LOCAL_SRC_FILES := \
 	eng_keystore.cpp \
 	keyhandle.cpp \
+	dsa_meth.cpp \
 	rsa_meth.cpp
 
 LOCAL_CFLAGS := -fvisibility=hidden -Wall -Werror
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/eng_keystore.cpp b/keystore-engine/eng_keystore.cpp
index 30cad7c..9397e53 100644
--- a/keystore-engine/eng_keystore.cpp
+++ b/keystore-engine/eng_keystore.cpp
@@ -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"
@@ -50,6 +53,24 @@
 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;
+
+/*
+ * Used for generic EVP_PKEY* handling (only for EC stuff currently)
+ */
+static EVP_PKEY_METHOD* keystore_pkey_ec_methods;
+
 /**
  * Many OpenSSL APIs take ownership of an argument on success but don't free the argument
  * on failure. This means we need to tell our scoped pointers when we've transferred ownership,
@@ -58,6 +79,7 @@
 #define OWNERSHIP_TRANSFERRED(obj) \
     typeof (obj.release()) _dummy __attribute__((unused)) = obj.release()
 
+
 struct ENGINE_Delete {
     void operator()(ENGINE* p) const {
         ENGINE_free(p);
@@ -72,6 +94,41 @@
 };
 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
 
+/**
+ * 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_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 int pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) {
+    int ret = 1;
+    switch (EVP_PKEY_type(pkey->type)) {
+    case EVP_PKEY_EC: {
+        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);
+        }
+    } break;
+    default:
+        ALOGW("Unsupported key type during setup %d", EVP_PKEY_type(pkey->type));
+        return 0;
+    }
+
+    if (ret != 1) {
+        return ret;
+    }
+
+    ENGINE_init(e);
+    pkey->engine = e;
+
+    return 1;
+}
 
 static EVP_PKEY* keystore_loadkey(ENGINE* e, const char* key_id, UI_METHOD* ui_method,
         void* callback_data) {
@@ -113,10 +170,18 @@
     }
 
     switch (EVP_PKEY_type(pkey->type)) {
+    case EVP_PKEY_DSA: {
+        dsa_pkey_setup(e, pkey.get(), key_id);
+        break;
+    }
     case EVP_PKEY_RSA: {
         rsa_pkey_setup(e, pkey.get(), key_id);
         break;
     }
+    case EVP_PKEY_EC: {
+        pkey_setup(e, pkey.get(), key_id);
+        break;
+    }
     default:
         ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type));
         return NULL;
@@ -129,11 +194,107 @@
     {0, NULL, NULL, 0}
 };
 
+static uint8_t* get_key_id(EVP_PKEY* pkey) {
+    switch (EVP_PKEY_type(pkey->type)) {
+    case EVP_PKEY_EC: {
+        Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
+        return reinterpret_cast<uint8_t*>(EC_KEY_get_key_method_data(eckey.get(),
+                ex_data_dup, ex_data_free, ex_data_clear_free));
+    } break;
+    }
+
+    return NULL;
+}
+
+static int keystore_pkey_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
+        const unsigned char *tbs, size_t tbs_len) {
+    EVP_PKEY* pkey = EVP_PKEY_CTX_get0_pkey(ctx);
+
+    const uint8_t* key_id = get_key_id(pkey);
+    if (key_id == NULL) {
+        ALOGW("key_id is empty");
+        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)), tbs, tbs_len,
+            &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(sig, reply, replyLen);
+    free(reply);
+    *siglen = replyLen;
+
+    return 1;
+}
+
+static int register_pkey_methods(EVP_PKEY_METHOD** meth, int nid) {
+    *meth = EVP_PKEY_meth_new(nid, 0);
+    if (*meth == NULL) {
+        ALOGE("Failure allocating PKEY methods for NID %d", nid);
+        return 0;
+    }
+
+    const EVP_PKEY_METHOD* orig = EVP_PKEY_meth_find(nid);
+    EVP_PKEY_meth_copy(*meth, orig);
+
+    EVP_PKEY_meth_set_sign(*meth, NULL, keystore_pkey_sign);
+
+    return 1;
+}
+
+static int keystore_nids[] = {
+    EVP_PKEY_EC,
+};
+
+static int keystore_pkey_meths(ENGINE*, EVP_PKEY_METHOD** meth, const int **nids, int nid) {
+    if (meth == NULL) {
+        *nids = keystore_nids;
+        return sizeof(keystore_nids) / sizeof(keystore_nids[0]);
+    }
+
+    switch (nid) {
+    case EVP_PKEY_EC:
+        *meth = keystore_pkey_ec_methods;
+        return 1;
+    }
+
+    *meth = NULL;
+    return 0;
+}
+
 static int keystore_engine_setup(ENGINE* e) {
     ALOGV("keystore_engine_setup");
 
+    if (!register_pkey_methods(&keystore_pkey_ec_methods, EVP_PKEY_EC)) {
+        ALOGE("Could not set up keystore engine");
+        return 0;
+    }
+
     if (!ENGINE_set_id(e, kKeystoreEngineId)
             || !ENGINE_set_name(e, kKeystoreEngineDesc)
+            || !ENGINE_set_pkey_meths(e, keystore_pkey_meths)
             || !ENGINE_set_load_privkey_function(e, keystore_loadkey)
             || !ENGINE_set_load_pubkey_function(e, keystore_loadkey)
             || !ENGINE_set_flags(e, 0)
@@ -142,7 +303,17 @@
         return 0;
     }
 
-    if (!rsa_register(e)) {
+    /* 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;
+    }
+
+    if (!dsa_register(e)) {
+        ALOGE("DSA registration failed");
+        return 0;
+    } else if (!rsa_register(e)) {
         ALOGE("RSA registration failed");
         return 0;
     }
diff --git a/keystore-engine/keyhandle.cpp b/keystore-engine/keyhandle.cpp
index 786934b..1799735 100644
--- a/keystore-engine/keyhandle.cpp
+++ b/keystore-engine/keyhandle.cpp
@@ -58,3 +58,19 @@
     }
     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
index 16a7ba8..8535ac9 100644
--- a/keystore-engine/methods.h
+++ b/keystore-engine/methods.h
@@ -26,11 +26,45 @@
 /* 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 *);
+
+/* 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
index c1d643c..b949fa4 100644
--- a/keystore-engine/rsa_meth.cpp
+++ b/keystore-engine/rsa_meth.cpp
@@ -38,34 +38,8 @@
 #include "methods.h"
 
 
-/*
- * 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;
-
-struct RSA_Delete {
-    void operator()(RSA* p) const {
-        RSA_free(p);
-    }
-};
-typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
-
-
 using namespace android;
 
-/**
- * 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);
-}
 
 int keystore_rsa_priv_enc(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
         int padding) {
@@ -246,8 +220,9 @@
     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.
+     * "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;
@@ -263,12 +238,5 @@
         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");
-        return 0;
-    }
-
     return 1;
 }