Chromium Code Reviews| Index: net/android/keystore_openssl.cc |
| diff --git a/net/android/keystore_openssl.cc b/net/android/keystore_openssl.cc |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..eeca4617d4e7e13d8dc99e643e40ecb2ffcb05b2 |
| --- /dev/null |
| +++ b/net/android/keystore_openssl.cc |
| @@ -0,0 +1,669 @@ |
| +// Copyright (c) 2013 The Chromium Authors. All rights reserved. |
| +// Use of this source code is governed by a BSD-style license that can be |
| +// found in the LICENSE file. |
| + |
| +#include "net/android/keystore_openssl.h" |
| + |
| +#include <jni.h> |
| +#include <openssl/bn.h> |
| +// This include is required to get the ECDSA_METHOD structure definition |
| +// which isn't currently part of the OpenSSL official ABI. This should |
| +// not be a concern for Chromium which always links against its own |
| +// version of the library on Android. |
| +#include <openssl/crypto/ecdsa/ecs_locl.h> |
| +// And this one is needed for the EC_GROUP definition. |
| +#include <openssl/crypto/ec/ec_lcl.h> |
| +#include <openssl/dsa.h> |
| +#include <openssl/ec.h> |
| +#include <openssl/engine.h> |
| +#include <openssl/evp.h> |
| +#include <openssl/rsa.h> |
| + |
| +#include <pthread.h> |
| + |
| +#include "base/android/build_info.h" |
| +#include "base/android/jni_android.h" |
| +#include "base/android/scoped_java_ref.h" |
| +#include "base/basictypes.h" |
| +#include "base/logging.h" |
| +#include "crypto/openssl_util.h" |
| +#include "net/android/keystore.h" |
| +#include "net/base/ssl_client_cert_type.h" |
| + |
| +// IMPORTANT NOTE: The following code will currently only work when used |
| +// to implement client certificate support with OpenSSL. That's because |
| +// only signing is implemented here. |
| +// |
|
Ryan Sleevi
2013/02/04 22:53:27
comment nit: Other types of signing may be useful
digit1
2013/02/05 14:31:58
OpenSSL provides many ways to sign messages, not a
|
| + |
| +// The OpenSSL EVP_PKEY type is a generic wrapper around key pairs. |
| +// Internally, it can hold a pointer to a RSA, DSA or ECDSA structure, |
| +// which model keypair implementations of each respective crypto |
| +// algorithm. |
| +// |
| +// The RSA type has a 'method' field pointer to a vtable-like structure |
| +// called a RSA_METHOD. This contains several function pointers that |
| +// correspond to operations on RSA keys (e.g. decode/encode with public |
| +// key, decode/encode with private key, signing, validation), as well as |
| +// a few flags. |
| +// |
| +// For example, the RSA_sign() function will call "method->rsa_sign()" if |
| +// method->rsa_sign is not NULL, otherwise, it will perform a regular |
| +// signing operation using the other fields in the RSA structure (which |
| +// are used to hold the typical modulus / exponent / parameters for the |
| +// key pair). |
| +// |
| +// This source file thus defines a custom RSA_METHOD structure, which |
| +// fields points to static methods used to implement the corresponding |
| +// RSA operation using platform Android APIs. |
| +// |
| +// However, the platform APIs require a jobject JNI reference to work. |
| +// It must be stored in the RSA instance, or made accessible when the |
| +// custom RSA methods are called. This is done by using RSA_set_app_data() |
| +// and RSA_get_app_data(). |
| +// |
| +// One can thus _directly_ create a new EVP_PKEY that uses a custom RSA |
| +// object with the following: |
| +// |
| +// RSA* rsa = RSA_new() |
| +// RSA_set_method(&custom_rsa_method); |
| +// RSA_set_app_data(rsa, jni_private_key); |
| +// |
| +// EVP_PKEY* pkey = EVP_PKEY_new(); |
| +// EVP_PKEY_assign_RSA(pkey, rsa); |
| +// |
| +// Note that because EVP_PKEY_assign_RSA() is used, instead of |
| +// EVP_PKEY_set1_RSA(), the new EVP_PKEY now owns the RSA object, and |
| +// will destroy it when it is itself destroyed. |
| +// |
| +// Similarly, custom DSA_METHOD and ECDSA_METHOD are defined by this source |
| +// file. |
| +// |
| +// Note that there is no need to define an OpenSSL ENGINE here. These |
| +// are objects that can be used to expose custom methods (i.e. either |
| +// RSA_METHOD, DSA_METHOD, ECDSA_METHOD, and a large number of other ones |
| +// for types not related to this source file), and make them used by |
| +// default for a lot of operations. Very fortunately, this is not needed |
| +// here, which saves a lot of complexity. |
| + |
| +using base::android::ScopedJavaGlobalRef; |
| + |
| +namespace { |
| + |
| +typedef crypto::ScopedOpenSSL<EVP_PKEY, EVP_PKEY_free> ScopedEVP_PKEY; |
| +typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA; |
| +typedef crypto::ScopedOpenSSL<DSA, DSA_free> ScopedDSA; |
| +typedef crypto::ScopedOpenSSL<EC_KEY, EC_KEY_free> ScopedEC_KEY; |
| +typedef crypto::ScopedOpenSSL<EC_GROUP, EC_GROUP_free> ScopedEC_GROUP; |
| + |
| +/////////////////////////////////////////////////////////////////////////// |
| +// |
|
Ryan Sleevi
2013/02/04 22:53:27
comment nit: superflous pretty-formatting is disco
digit1
2013/02/05 14:31:58
Done.
|
| +// Custom RSA_METHOD that uses the platform APIs. |
| +// Note that for now, only signing through RSA_sign() is really supported. |
| +// all other method pointers are either stubs returning errors, or no-ops. |
| +// |
| +// See <openssl/rsa.h> for exact declaration of RSA_METHOD. |
| +// |
| + |
| +int RsaMethodPubEnc(int flen, |
| + const unsigned char* from, |
| + unsigned char* to, |
| + RSA* rsa, |
| + int padding) { |
| + NOTIMPLEMENTED(); |
| + RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); |
| + return -1; |
| +} |
| + |
| +int RsaMethodPubDec(int flen, |
| + const unsigned char* from, |
| + unsigned char* to, |
| + RSA* rsa, |
| + int padding) { |
| + NOTIMPLEMENTED(); |
| + RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); |
| + return -1; |
| +} |
| + |
| +int RsaMethodPrivEnc(int flen, |
| + const unsigned char *from, |
| + unsigned char *to, |
| + RSA *rsa, |
| + int padding) { |
| + NOTIMPLEMENTED(); |
| + RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); |
| + return -1; |
| +} |
| + |
| +int RsaMethodPrivDec(int flen, |
| + const unsigned char* from, |
| + unsigned char* to, |
| + RSA* rsa, |
| + int padding) { |
| + NOTIMPLEMENTED(); |
| + RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); |
| + return -1; |
| +} |
| + |
| +int RsaMethodInit(RSA* rsa) { |
| + // Required to ensure that RsaMethodSign will be called. |
| + rsa->flags |= RSA_FLAG_SIGN_VER; |
| + return 0; |
| +} |
| + |
| +int RsaMethodFinish(RSA* rsa) { |
| + // Ensure the global JNI reference is destroyed with this key. |
| + jobject key = reinterpret_cast<jobject>(RSA_get_app_data(rsa)); |
| + if (key != NULL) { |
| + RSA_set_app_data(rsa, NULL); |
| + JNIEnv* env = base::android::AttachCurrentThread(); |
| + env->DeleteGlobalRef(key); |
| + } |
| + // Actual return value is ignored by OpenSSL. There are no docs |
| + // explaining what this is supposed to be. |
| + return 0; |
| +} |
| + |
| +int RsaMethodSign(int type, |
| + const unsigned char* message, |
| + unsigned int message_len, |
| + unsigned char* signature, |
| + unsigned int* signature_len, |
| + const RSA* rsa) { |
| + // This is only used for client certificate support, which |
| + // will always pass the NID_md5_sha1 |type| value. |
| + DCHECK_EQ(NID_md5_sha1, type); |
| + if (type != NID_md5_sha1) { |
| + RSAerr(RSA_F_RSA_SIGN, RSA_R_UNKNOWN_ALGORITHM_TYPE); |
| + return 0; |
| + } |
| + // Retrieve private key JNI reference. |
| + jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa)); |
| + if (!private_key) { |
| + LOG(WARNING) << "Null JNI reference passed to RsaMethodSign!"; |
| + return 0; |
| + } |
| + // Sign message with it through JNI. |
| + base::StringPiece message_piece(reinterpret_cast<const char*>(message), |
| + static_cast<size_t>(message_len)); |
| + std::vector<uint8> result; |
| + |
| + if (!net::android::RawSignDigestWithPrivateKey( |
| + private_key, message_piece, &result)) { |
| + LOG(WARNING) << "Could not sign message in RsaMethodSign!"; |
| + return 0; |
| + } |
| + |
| + size_t expected_size = static_cast<size_t>(RSA_size(rsa)); |
| + if (expected_size != result.size()) { |
|
Ryan Sleevi
2013/02/04 22:53:27
Are you sure != is correct? I think this should be
digit1
2013/02/05 14:31:58
Done.
|
| + LOG(ERROR) << "RSA Signature size mismatch, actual: " << |
| + result.size() << ", expected " << expected_size; |
|
Ryan Sleevi
2013/02/04 22:53:27
See http://dev.chromium.org/developers/coding-styl
digit1
2013/02/05 14:31:58
Done.
|
| + return 0; |
| + } |
| + |
| + // Copy result to OpenSSL-provided buffer |
| + memcpy(signature, &result[0], result.size()); |
| + *signature_len = static_cast<unsigned int>(result.size()); |
| + return 1; |
| +} |
| + |
| +const RSA_METHOD android_rsa_method = { |
| + /* .name = */ "Android signing-only RSA method", |
| + /* .rsa_pub_enc = */ RsaMethodPubEnc, |
| + /* .rsa_pub_dec = */ RsaMethodPubDec, |
| + /* .rsa_priv_enc = */ RsaMethodPrivEnc, |
| + /* .rsa_priv_dec = */ RsaMethodPrivDec, |
| + /* .rsa_mod_exp = */ NULL, |
| + /* .bn_mod_exp = */ NULL, |
| + /* .init = */ RsaMethodInit, |
| + /* .finish = */ RsaMethodFinish, |
| + /* .flags = */ RSA_FLAG_SIGN_VER, // indicates that rsa_sign is usable. |
| + /* .app_data = */ NULL, |
| + /* .rsa_sign = */ RsaMethodSign, |
| + /* .rsa_verify = */ NULL, |
| + /* .rsa_keygen = */ NULL, |
| +}; |
| + |
| +// Copy the contents of an encoded big integer into an existing BIGNUM. |
| +// This function modifies |*num| in-place. |
| +// |num| points to the BIGNUM which will be assigned with the new value. |
| +// |new_bytes| is the byte encoding of the new value. |
| +// Returns true on success, false otherwise. On failure, |*num| is |
| +// not modified. |
| +bool CopyBigNumFromBytes(BIGNUM* num, |
| + const std::vector<uint8>& new_bytes) { |
|
Ryan Sleevi
2013/02/04 22:53:27
STYLE: These functions follow the wrong order, as
digit1
2013/02/05 14:31:58
Done.
|
| + BIGNUM* new_num = BN_bin2bn( |
| + reinterpret_cast<const unsigned char*>(&new_bytes[0]), |
| + static_cast<int>(new_bytes.size()), |
| + NULL); |
| + if (new_num == NULL) |
| + return false; |
| + |
| + BN_copy(num, new_num); |
| + BN_free(new_num); |
|
Ryan Sleevi
2013/02/04 22:53:27
Why not BN_swap?
Or even more, why not just the
digit1
2013/02/05 14:31:58
Yes, that seems preferrable. Thanks. Done.
|
| + return true; |
| +} |
| + |
| +// Swap the contents a BIGNUM pointer with the value corresponding to |
| +// an encoded big integer. The difference with CopyBigNumFromBytes is |
| +// that the former modifies the target BIGNUM object in place, while |
| +// this function swaps pointer values instead. |
| +// |num_ptr| is the address of a BIGNUM pointer. |*num_ptr| can be NULL. |
| +// |new_bytes| is the byte encoding of the new value. |
| +// Returns true on success, false otherwise. On failure, |*num_ptr| is |
| +// not modified. |
| +bool SwapBigNumPtrFromBytes(BIGNUM** num_ptr, |
| + const std::vector<uint8>& new_bytes) { |
| + BIGNUM* old_num = *num_ptr; |
| + BIGNUM* new_num = BN_bin2bn( |
| + reinterpret_cast<const unsigned char*>(&new_bytes[0]), |
| + static_cast<int>(new_bytes.size()), |
| + NULL); |
| + if (new_num == NULL) |
| + return false; |
| + |
| + *num_ptr = new_num; |
| + BN_free(old_num); |
| + return true; |
|
Ryan Sleevi
2013/02/04 22:53:27
I'm nervous about the correctness of this, in the
digit1
2013/02/05 14:31:58
I've changed the code to use BN_bin2bn(...,old_num
|
| +} |
| + |
| +// This method only works on Android >= 4.2. |
| +void GetRsaPkeyWrapper(ScopedEVP_PKEY& pkey, |
|
Ryan Sleevi
2013/02/04 22:53:27
STYLE: non-const references are no good
http://go
digit1
2013/02/05 14:31:58
Done.
|
| + ScopedJavaGlobalRef<jobject>& private_key) { |
| + ScopedRSA rsa(RSA_new()); |
| + RSA_set_method(rsa.get(), &android_rsa_method); |
| + |
| + // HACK: RSA_size() doesn't work with custom RSA_METHODs. To ensure that |
| + // it will return the right value, set the 'n' field of the RSA object |
| + // to match the private key's modulus. |
| + // If this fails, simply exit, since this will let pkey.get() |
| + // unchanged, it will stay at NULL. |
| + std::vector<uint8> modulus; |
| + if (!net::android::GetRSAKeyModulus(private_key.obj(), &modulus)) { |
| + LOG(ERROR) << "Failed to get private key modulus"; |
| + return; |
| + } |
| + if (!SwapBigNumPtrFromBytes(&rsa.get()->n, modulus)) { |
| + LOG(ERROR) << "Failed to decode private key modululs"; |
| + return; |
| + } |
| + |
| + RSA_set_app_data(rsa.get(), private_key.Release()); |
| + EVP_PKEY_assign_RSA(pkey.get(), rsa.release()); |
| +} |
| + |
| +// This method can be used on Android < 4.2 instead. |
| +// It first tries to get the system OpenSSL pointer directly. |
| +void GetRsaLegacyKey(ScopedEVP_PKEY& pkey, |
| + ScopedJavaGlobalRef<jobject>& private_key) { |
|
Ryan Sleevi
2013/02/04 22:53:27
STYLE: same here re: non-const refs.
digit1
2013/02/05 14:31:58
Done.
|
| + EVP_PKEY* sys_pkey = |
| + net::android::GetOpenSSLSystemHandleForPrivateKey(private_key.obj()); |
| + if (sys_pkey != NULL) { |
| + CRYPTO_add(&sys_pkey->references, 1, CRYPTO_LOCK_EVP_PKEY); |
| + } else { |
| + // GetOpenSSLSystemHandleForPrivateKey() will fail on Android |
| + // 4.0.3 and earlier. However, it is possible to get the key |
| + // content with PrivateKey.getEncoded() on these platforms. |
| + // Note that this method may return NULL on 4.0.4 and later. |
| + std::vector<uint8> encoded; |
| + if (!net::android::GetPrivateKeyEncodedBytes( |
| + private_key.obj(), &encoded)) { |
|
Ryan Sleevi
2013/02/04 22:53:27
style: indent an additional four spaces.
digit1
2013/02/05 14:31:58
Done.
|
| + LOG(ERROR) << "Can't get private key data!"; |
| + return; |
| + } |
| + const unsigned char* p = |
| + reinterpret_cast<const unsigned char*>(&encoded[0]); |
| + int len = static_cast<int>(encoded.size()); |
| + sys_pkey = d2i_AutoPrivateKey(NULL, &p, len); |
| + if (sys_pkey == NULL) { |
| + LOG(ERROR) << "Can't convert private key data!"; |
| + return; |
| + } |
| + } |
| + pkey.reset(sys_pkey); |
| +} |
| + |
| +/////////////////////////////////////////////////////////////////////////// |
| +// |
| +// Custom DSA_METHOD that uses the platform APIs. |
| +// Note that for now, only signing through DSA_sign() is really supported. |
| +// all other method pointers are either stubs returning errors, or no-ops. |
| +// |
| +// See <openssl/dsa.h> for exact declaration of DSA_METHOD. |
| +// |
| +// Note: There is no DSA_set_app_data() and DSA_get_app_data() functions, |
| +// but RSA_set_app_data() is defined as a simple macro that calls |
| +// RSA_set_ex_data() with a hard-coded index of 0, so this code |
| +// does the same thing here. |
| + |
| +static DSA_SIG* DsaMethodDoSign(const unsigned char* dgst, |
| + int dlen, |
| + DSA* dsa) { |
| + // Extract the JNI reference to the PrivateKey object. |
| + jobject private_key = reinterpret_cast<jobject>(DSA_get_ex_data(dsa, 0)); |
| + if (private_key == NULL) |
| + return NULL; |
| + |
| + // Sign the message with it, calling platform APIs. |
| + std::vector<uint8> signature; |
| + if (!net::android::RawSignDigestWithPrivateKey( |
| + private_key, |
| + base::StringPiece( |
| + reinterpret_cast<const char*>(dgst), |
| + static_cast<size_t>(dlen)), |
| + &signature)) { |
|
Ryan Sleevi
2013/02/04 22:53:27
style: indent an additional four spaces.
digit1
2013/02/05 14:31:58
Done.
|
| + return NULL; |
| + } |
| + |
| + // Note: With DSA, the actual signature might be smaller than DSA_size(). |
| + size_t max_expected_size = static_cast<size_t>(DSA_size(dsa)); |
| + if (signature.size() > max_expected_size) { |
| + LOG(ERROR) << "DSA Signature size mismatch, actual: " << |
| + signature.size() << ", expected <= " << max_expected_size; |
|
Ryan Sleevi
2013/02/04 22:53:27
style: same comments as before regarding << wrappi
digit1
2013/02/05 14:31:58
Done.
|
| + return 0; |
|
Ryan Sleevi
2013/02/04 22:53:27
style: return NULL, not 0.
digit1
2013/02/05 14:31:58
Done.
|
| + } |
| + |
| + // Convert the signature into a DSA_SIG object. |
| + const unsigned char* sigbuf = |
| + reinterpret_cast<const unsigned char*>(&signature[0]); |
| + int siglen = static_cast<size_t>(signature.size()); |
| + DSA_SIG* dsa_sig = d2i_DSA_SIG(NULL, &sigbuf, siglen); |
| + return dsa_sig; |
| +} |
| + |
| +static int DsaMethodSignSetup(DSA* dsa, |
| + BN_CTX* ctx_in, |
| + BIGNUM** kinvp, |
| + BIGNUM** rp) { |
| + NOTIMPLEMENTED(); |
| + DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_INVALID_DIGEST_TYPE); |
| + return -1; |
| +} |
| + |
| +static int DsaMethodDoVerify(const unsigned char* dgst, |
| + int dgst_len, |
| + DSA_SIG* sig, |
| + DSA* dsa) { |
| + NOTIMPLEMENTED(); |
| + DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_INVALID_DIGEST_TYPE); |
| + return -1; |
| +} |
| + |
| +static int DsaMethodFinish(DSA* dsa) { |
| + // Free the global JNI reference. |
| + jobject key = reinterpret_cast<jobject>(DSA_get_ex_data(dsa,0)); |
| + if (key != NULL) { |
| + DSA_set_ex_data(dsa, 0, NULL); |
| + JNIEnv* env = base::android::AttachCurrentThread(); |
| + env->DeleteGlobalRef(key); |
| + } |
| + // Actual return value is ignored by OpenSSL. There are no docs |
| + // explaining what this is supposed to be. |
| + return 0; |
| +} |
| + |
| +const DSA_METHOD android_dsa_method = { |
| + /* .name = */ "Android signing-only DSA method", |
| + /* .dsa_do_sign = */ DsaMethodDoSign, |
| + /* .dsa_sign_setup = */ DsaMethodSignSetup, |
| + /* .dsa_do_verify = */ DsaMethodDoVerify, |
| + /* .dsa_mod_exp = */ NULL, |
| + /* .bn_mod_exp = */ NULL, |
| + /* .init = */ NULL, // nothing to do here. |
| + /* .finish = */ DsaMethodFinish, |
| + /* .flags = */ 0, |
| + /* .app_data = */ NULL, |
| + /* .dsa_paramgem = */ NULL, |
| + /* .dsa_keygen = */ NULL |
| +}; |
| + |
| +void GetDsaPkeyWrapper(ScopedEVP_PKEY& pkey, |
| + ScopedJavaGlobalRef<jobject>& private_key) { |
| + ScopedDSA dsa(DSA_new()); |
| + DSA_set_method(dsa.get(), &android_dsa_method); |
| + |
| + // HACK: DSA_size() doesn't work with custom DSA_METHODs. To ensure it |
| + // returns the right value, set the 'q' field in the DSA object to |
| + // match the parameter from the platform key. |
| + std::vector<uint8> q; |
| + if (!net::android::GetDSAKeyParamQ(private_key.obj(), &q)) { |
| + LOG(ERROR) << "Can't extract Q parameter from DSA private key"; |
| + return; |
| + } |
| + if (!SwapBigNumPtrFromBytes(&dsa.get()->q, q)) { |
| + LOG(ERROR) << "Can't decode Q parameter from DSA private key"; |
| + return; |
| + } |
| + |
| + DSA_set_ex_data(dsa.get(), 0, private_key.Release()); |
| + EVP_PKEY_assign_DSA(pkey.get(), dsa.release()); |
| +} |
| + |
| +/////////////////////////////////////////////////////////////////////////// |
| +// |
| +// Custom ECDSA_METHOD that uses the platform APIs. |
| +// Note that for now, only signing through ECDSA_sign() is really supported. |
| +// all other method pointers are either stubs returning errors, or no-ops. |
| +// |
| +// Note: The ECDSA_METHOD structure doesn't have init/finish |
| +// methods. As such, the only way to to ensure the global |
| +// JNI reference is properly released when the EVP_PKEY is |
| +// destroyed is to use a custom EX_DATA type. |
| + |
| +// Used to ensure that the global JNI reference associated with a |
| +// custom EC_KEY + ECDSA_METHOD is released when the key is destroyed. |
| +void ExDataFree(void* parent, |
| + void* ptr, |
| + CRYPTO_EX_DATA* ad, |
| + int idx, |
| + long argl, |
| + void* argp) { |
| + jobject private_key = reinterpret_cast<jobject>(ptr); |
| + if (private_key == NULL) |
| + return; |
| + |
| + CRYPTO_set_ex_data(ad, idx, NULL); |
| + |
| + JNIEnv* env = base::android::AttachCurrentThread(); |
| + env->DeleteGlobalRef(private_key); |
| +} |
| + |
| +int ExDataDup(CRYPTO_EX_DATA* to, |
| + CRYPTO_EX_DATA* from, |
| + void* from_d, |
| + int idx, |
| + long argl, |
| + void* argp) { |
| + // This callback shall never be called with the current OpenSSL |
| + // implementation (the library only ever duplicates EX_DATA items |
| + // for SSL and BIO objects). But provide this to catch regressions |
| + // in the future. |
|
Ryan Sleevi
2013/02/04 22:53:27
This sort of subtlety leaves me afraid of a double
digit1
2013/02/05 14:31:58
Done.
|
| + NOTIMPLEMENTED(); |
| + LOG(WARNING) << "ExDataDup for was called for ECDSA custom key !?"; |
| + // Return value is currently ignored by OpenSSL. |
| + return 0; |
| +} |
| + |
| +int s_ecdsa_ex_data_index; |
| + |
| +void EcdsaInitExDataIndex(void) { |
| + // Note that OpenSSL does not provide a way to unregister these |
| + // indices, so don't worry about releasing them on program exit. |
| + // There is also no need for an ExDataNew function. |
| + s_ecdsa_ex_data_index = ECDSA_get_ex_new_index(0, // argl |
| + NULL, // argp |
| + NULL, // new_func |
| + ExDataDup, // dup_func |
| + ExDataFree); // free_func |
| +} |
| + |
| +// Returns the index of the custom EX_DATA used to store the JNI reference. |
| +int EcdsaGetExDataIndex(void) { |
| + // The index must be initialized once per processs, and this function |
| + // can be called from distinct threads. Use a pthread_once_t to perform |
| + // proper lazy initialization. |
| + static pthread_once_t once = PTHREAD_ONCE_INIT; |
| + pthread_once(&once, EcdsaInitExDataIndex); |
| + return s_ecdsa_ex_data_index; |
|
Ryan Sleevi
2013/02/04 22:53:27
So it's clear for general reference, I don't think
digit1
2013/02/05 14:31:58
I'm not sure I understand. Are you saying it's not
Ryan Sleevi
2013/02/06 22:48:02
I'm saying I don't know, but that I hadn't seen th
|
| +} |
| + |
| +ECDSA_SIG* EcdsaMethodDoSign(const unsigned char* dgst, |
| + int dgst_len, |
| + const BIGNUM* inv, |
| + const BIGNUM* rp, |
| + EC_KEY* eckey) { |
| + // Retrieve private key JNI reference. |
| + jobject private_key = reinterpret_cast<jobject>( |
| + ECDSA_get_ex_data(eckey, EcdsaGetExDataIndex())); |
| + if (!private_key) { |
| + LOG(WARNING) << "Null JNI reference passed to EcdsaMethodDoSign!"; |
| + return NULL; |
| + } |
| + // Sign message with it through JNI. |
| + std::vector<uint8> signature; |
| + if (!net::android::RawSignDigestWithPrivateKey( |
| + private_key, |
| + base::StringPiece( |
| + reinterpret_cast<const char*>(dgst), |
| + static_cast<size_t>(dgst_len)), |
| + &signature)) { |
|
Ryan Sleevi
2013/02/04 22:53:27
style: indents are wrong
digit1
2013/02/05 14:31:58
Done.
|
| + LOG(WARNING) << "Could not sign message in EcdsaMethodDoSign!"; |
| + return NULL; |
| + } |
| + |
| + // Note: With ECDSA, the actual signature may be smaller than |
| + // ECDSA_size(). |
| + size_t max_expected_size = static_cast<size_t>(ECDSA_size(eckey)); |
| + if (signature.size() > max_expected_size) { |
| + LOG(ERROR) << "ECDSA Signature size mismatch, actual: " << |
| + signature.size() << ", expected <= " << max_expected_size; |
|
Ryan Sleevi
2013/02/04 22:53:27
style: << is wrong
digit1
2013/02/05 14:31:58
Done.
|
| + return 0; |
| + } |
| + |
| + // Convert signature to ECDSA_SIG object |
| + const unsigned char* sigbuf = |
| + reinterpret_cast<const unsigned char*>(&signature[0]); |
| + long siglen = static_cast<long>(signature.size()); |
| + return d2i_ECDSA_SIG(NULL, &sigbuf, siglen); |
| +} |
| + |
| +int EcdsaMethodSignSetup(EC_KEY* eckey, |
| + BN_CTX* ctx, |
| + BIGNUM** kinv, |
| + BIGNUM** r) { |
| + NOTIMPLEMENTED(); |
| + ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_ERR_EC_LIB); |
| + return -1; |
| +} |
| + |
| +int EcdsaMethodDoVerify(const unsigned char* dgst, |
| + int dgst_len, |
| + const ECDSA_SIG* sig, |
| + EC_KEY* eckey) { |
| + NOTIMPLEMENTED(); |
| + ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_ERR_EC_LIB); |
| + return -1; |
| +} |
| + |
| +const ECDSA_METHOD android_ecdsa_method = { |
| + /* .name = */ "Android signing-only ECDSA method", |
| + /* .ecdsa_do_sign = */ EcdsaMethodDoSign, |
| + /* .ecdsa_sign_setup = */ EcdsaMethodSignSetup, |
| + /* .ecdsa_do_verify = */ EcdsaMethodDoVerify, |
| + /* .flags = */ 0, |
| + /* .app_data = */ NULL, |
| +}; |
| + |
| +void GetEcdsaPkeyWrapper(ScopedEVP_PKEY& pkey, |
| + ScopedJavaGlobalRef<jobject>& private_key) { |
| + ScopedEC_KEY eckey(EC_KEY_new()); |
| + ECDSA_set_method(eckey.get(), &android_ecdsa_method); |
| + |
| + // To ensure that ECDSA_size() works properly, craft a custom EC_GROUP |
| + // that has the same order than the private key. |
| + // In case of error, return directly, since pkey will be left untouched |
| + // (and still set to NULL). |
| + { |
| + std::vector<uint8> order; |
| + if (!net::android::GetECKeyOrder(private_key.obj(), &order)) { |
| + LOG(ERROR) << "Can't extract order parameter from EC private key"; |
| + return; |
| + } |
| + ScopedEC_GROUP group(EC_GROUP_new(EC_GFp_nist_method())); |
| + if (!group.get()) { |
| + LOG(ERROR) << "Can't create new EC_GROUP"; |
| + return; |
| + } |
| + if (!CopyBigNumFromBytes(&group.get()->order, order)) { |
| + LOG(ERROR) << "Can't decode order from PrivateKey"; |
| + return; |
| + } |
| + EC_KEY_set_group(eckey.get(), group.release()); |
| + } |
|
Ryan Sleevi
2013/02/04 22:53:27
style: Don't use the extra function-level block. I
digit1
2013/02/05 14:31:58
Done.
|
| + |
| + ECDSA_set_ex_data(eckey.get(), |
| + EcdsaGetExDataIndex(), |
| + private_key.Release()); |
| + |
| + EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.release()); |
| +} |
| + |
| +} // namespace |
| + |
| + |
| +namespace net { |
| +namespace android { |
| + |
| +EVP_PKEY* GetOpenSSLPrivateKeyWrapper(jobject private_key) { |
| + // Create scoped JNI global reference from the private key. |
| + // This ensure that it will be usable from any thread, not only |
| + // from the caller's. |
| + // |
| + // Note: "ScopedJavaGlobalRef<jobject> ref(a_jobject)" doesn't |
| + // compile. Route around this by creating an empty object first, |
| + // then resetting it. |
| + ScopedJavaGlobalRef<jobject> global_key; |
| + global_key.Reset(NULL, private_key); |
| + if (global_key.is_null()) |
| + return NULL; |
| + |
| + // Create new empty EVP_PKEY instance. |
| + ScopedEVP_PKEY pkey(EVP_PKEY_new()); |
| + if (!pkey.get()) |
| + return NULL; |
| + |
| + // Create sub key type, depending on private key's algorithm type. |
| + PrivateKeyType key_type = GetPrivateKeyType(global_key.obj()); |
| + switch (key_type) { |
| + case PRIVATE_KEY_TYPE_RSA: |
| + { |
| + // Route around platform bug: if Android < 4.2, then |
| + // base::android::RawSignDigestWithPrivateKey() cannot work, so |
| + // instead, obtain a raw EVP_PKEY* to the system object |
| + // backing this PrivateKey object. |
| + const int kAndroid42ApiLevel = 17; |
| + if (base::android::BuildInfo::GetInstance()->sdk_int() < |
| + kAndroid42ApiLevel) { |
| + GetRsaLegacyKey(pkey, global_key); |
| + } else { |
| + // Running on Android 4.2. |
| + GetRsaPkeyWrapper(pkey, global_key); |
| + } |
| + } |
| + break; |
| + case PRIVATE_KEY_TYPE_DSA: |
| + GetDsaPkeyWrapper(pkey, global_key); |
| + break; |
| + case PRIVATE_KEY_TYPE_ECDSA: |
| + GetEcdsaPkeyWrapper(pkey, global_key); |
| + break; |
| + default: |
| + LOG(WARNING) |
| + << "GetOpenSSLPrivateKeyWrapper() called with invalid key type"; |
| + return NULL; |
| + } |
| + |
| + return pkey.release(); |
| +} |
| + |
| +} // namespace android |
| +} // namespace net |