1// Copyright (c) 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/android/keystore_openssl.h"
6
7#include <jni.h>
8#include <openssl/bn.h>
9// This include is required to get the ECDSA_METHOD structure definition
10// which isn't currently part of the OpenSSL official ABI. This should
11// not be a concern for Chromium which always links against its own
12// version of the library on Android.
13#include <openssl/crypto/ecdsa/ecs_locl.h>
14// And this one is needed for the EC_GROUP definition.
15#include <openssl/crypto/ec/ec_lcl.h>
16#include <openssl/dsa.h>
17#include <openssl/ec.h>
18#include <openssl/engine.h>
19#include <openssl/evp.h>
20#include <openssl/rsa.h>
21
22#include "base/android/build_info.h"
23#include "base/android/jni_android.h"
24#include "base/android/scoped_java_ref.h"
25#include "base/basictypes.h"
26#include "base/lazy_instance.h"
27#include "base/logging.h"
28#include "crypto/openssl_util.h"
29#include "net/android/keystore.h"
30#include "net/ssl/ssl_client_cert_type.h"
31
32// IMPORTANT NOTE: The following code will currently only work when used
33// to implement client certificate support with OpenSSL. That's because
34// only the signing operations used in this use case are implemented here.
35//
36// Generally speaking, OpenSSL provides many different ways to sign
37// digests. This code doesn't support all these cases, only the ones that
38// are required to sign the digest during the OpenSSL handshake for TLS.
39//
40// The OpenSSL EVP_PKEY type is a generic wrapper around key pairs.
41// Internally, it can hold a pointer to a RSA, DSA or ECDSA structure,
42// which model keypair implementations of each respective crypto
43// algorithm.
44//
45// The RSA type has a 'method' field pointer to a vtable-like structure
46// called a RSA_METHOD. This contains several function pointers that
47// correspond to operations on RSA keys (e.g. decode/encode with public
48// key, decode/encode with private key, signing, validation), as well as
49// a few flags.
50//
51// For example, the RSA_sign() function will call "method->rsa_sign()" if
52// method->rsa_sign is not NULL, otherwise, it will perform a regular
53// signing operation using the other fields in the RSA structure (which
54// are used to hold the typical modulus / exponent / parameters for the
55// key pair).
56//
57// This source file thus defines a custom RSA_METHOD structure whose
58// fields point to static methods used to implement the corresponding
59// RSA operation using platform Android APIs.
60//
61// However, the platform APIs require a jobject JNI reference to work.
62// It must be stored in the RSA instance, or made accessible when the
63// custom RSA methods are called. This is done by using RSA_set_app_data()
64// and RSA_get_app_data().
65//
66// One can thus _directly_ create a new EVP_PKEY that uses a custom RSA
67// object with the following:
68//
69//    RSA* rsa = RSA_new()
70//    RSA_set_method(&custom_rsa_method);
71//    RSA_set_app_data(rsa, jni_private_key);
72//
73//    EVP_PKEY* pkey = EVP_PKEY_new();
74//    EVP_PKEY_assign_RSA(pkey, rsa);
75//
76// Note that because EVP_PKEY_assign_RSA() is used, instead of
77// EVP_PKEY_set1_RSA(), the new EVP_PKEY now owns the RSA object, and
78// will destroy it when it is itself destroyed.
79//
80// Unfortunately, such objects cannot be used with RSA_size(), which
81// totally ignores the RSA_METHOD pointers. Instead, it is necessary
82// to manually setup the modulus field (n) in the RSA object, with a
83// value that matches the wrapped PrivateKey object. See GetRsaPkeyWrapper
84// for full details.
85//
86// Similarly, custom DSA_METHOD and ECDSA_METHOD are defined by this source
87// file, and appropriate field setups are performed to ensure that
88// DSA_size() and ECDSA_size() work properly with the wrapper EVP_PKEY.
89//
90// Note that there is no need to define an OpenSSL ENGINE here. These
91// are objects that can be used to expose custom methods (i.e. either
92// RSA_METHOD, DSA_METHOD, ECDSA_METHOD, and a large number of other ones
93// for types not related to this source file), and make them used by
94// default for a lot of operations. Very fortunately, this is not needed
95// here, which saves a lot of complexity.
96
97using base::android::ScopedJavaGlobalRef;
98
99namespace net {
100namespace android {
101
102namespace {
103
104typedef crypto::ScopedOpenSSL<EVP_PKEY, EVP_PKEY_free> ScopedEVP_PKEY;
105typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA;
106typedef crypto::ScopedOpenSSL<DSA, DSA_free> ScopedDSA;
107typedef crypto::ScopedOpenSSL<EC_KEY, EC_KEY_free> ScopedEC_KEY;
108typedef crypto::ScopedOpenSSL<EC_GROUP, EC_GROUP_free> ScopedEC_GROUP;
109
110// Custom RSA_METHOD that uses the platform APIs.
111// Note that for now, only signing through RSA_sign() is really supported.
112// all other method pointers are either stubs returning errors, or no-ops.
113// See <openssl/rsa.h> for exact declaration of RSA_METHOD.
114
115int RsaMethodPubEnc(int flen,
116                    const unsigned char* from,
117                    unsigned char* to,
118                    RSA* rsa,
119                    int padding) {
120  NOTIMPLEMENTED();
121  RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
122  return -1;
123}
124
125int RsaMethodPubDec(int flen,
126                    const unsigned char* from,
127                    unsigned char* to,
128                    RSA* rsa,
129                    int padding) {
130  NOTIMPLEMENTED();
131  RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
132  return -1;
133}
134
135// See RSA_eay_private_encrypt in
136// third_party/openssl/openssl/crypto/rsa/rsa_eay.c for the default
137// implementation of this function.
138int RsaMethodPrivEnc(int flen,
139                     const unsigned char *from,
140                     unsigned char *to,
141                     RSA *rsa,
142                     int padding) {
143  DCHECK_EQ(RSA_PKCS1_PADDING, padding);
144  if (padding != RSA_PKCS1_PADDING) {
145    // TODO(davidben): If we need to, we can implement RSA_NO_PADDING
146    // by using javax.crypto.Cipher and picking either the
147    // "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
148    // appropriate. I believe support for both of these was added in
149    // the same Android version as the "NONEwithRSA"
150    // java.security.Signature algorithm, so the same version checks
151    // for GetRsaLegacyKey should work.
152    RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
153    return -1;
154  }
155
156  // Retrieve private key JNI reference.
157  jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
158  if (!private_key) {
159    LOG(WARNING) << "Null JNI reference passed to RsaMethodPrivEnc!";
160    RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
161    return -1;
162  }
163
164  base::StringPiece from_piece(reinterpret_cast<const char*>(from), flen);
165  std::vector<uint8> result;
166  // For RSA keys, this function behaves as RSA_private_encrypt with
167  // PKCS#1 padding.
168  if (!RawSignDigestWithPrivateKey(private_key, from_piece, &result)) {
169    LOG(WARNING) << "Could not sign message in RsaMethodPrivEnc!";
170    RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
171    return -1;
172  }
173
174  size_t expected_size = static_cast<size_t>(RSA_size(rsa));
175  if (result.size() > expected_size) {
176    LOG(ERROR) << "RSA Signature size mismatch, actual: "
177               <<  result.size() << ", expected <= " << expected_size;
178    RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
179    return -1;
180  }
181
182  // Copy result to OpenSSL-provided buffer. RawSignDigestWithPrivateKey
183  // should pad with leading 0s, but if it doesn't, pad the result.
184  size_t zero_pad = expected_size - result.size();
185  memset(to, 0, zero_pad);
186  memcpy(to + zero_pad, &result[0], result.size());
187
188  return expected_size;
189}
190
191int RsaMethodPrivDec(int flen,
192                     const unsigned char* from,
193                     unsigned char* to,
194                     RSA* rsa,
195                     int padding) {
196  NOTIMPLEMENTED();
197  RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
198  return -1;
199}
200
201int RsaMethodInit(RSA* rsa) {
202  return 0;
203}
204
205int RsaMethodFinish(RSA* rsa) {
206  // Ensure the global JNI reference created with this wrapper is
207  // properly destroyed with it.
208  jobject key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
209  if (key != NULL) {
210    RSA_set_app_data(rsa, NULL);
211    JNIEnv* env = base::android::AttachCurrentThread();
212    env->DeleteGlobalRef(key);
213  }
214  // Actual return value is ignored by OpenSSL. There are no docs
215  // explaining what this is supposed to be.
216  return 0;
217}
218
219const RSA_METHOD android_rsa_method = {
220  /* .name = */ "Android signing-only RSA method",
221  /* .rsa_pub_enc = */ RsaMethodPubEnc,
222  /* .rsa_pub_dec = */ RsaMethodPubDec,
223  /* .rsa_priv_enc = */ RsaMethodPrivEnc,
224  /* .rsa_priv_dec = */ RsaMethodPrivDec,
225  /* .rsa_mod_exp = */ NULL,
226  /* .bn_mod_exp = */ NULL,
227  /* .init = */ RsaMethodInit,
228  /* .finish = */ RsaMethodFinish,
229  // This flag is necessary to tell OpenSSL to avoid checking the content
230  // (i.e. internal fields) of the private key. Otherwise, it will complain
231  // it's not valid for the certificate.
232  /* .flags = */ RSA_METHOD_FLAG_NO_CHECK,
233  /* .app_data = */ NULL,
234  /* .rsa_sign = */ NULL,
235  /* .rsa_verify = */ NULL,
236  /* .rsa_keygen = */ NULL,
237};
238
239// Copy the contents of an encoded big integer into an existing BIGNUM.
240// This function modifies |*num| in-place.
241// |new_bytes| is the byte encoding of the new value.
242// |num| points to the BIGNUM which will be assigned with the new value.
243// Returns true on success, false otherwise. On failure, |*num| is
244// not modified.
245bool CopyBigNumFromBytes(const std::vector<uint8>& new_bytes,
246                         BIGNUM* num) {
247  BIGNUM* ret = BN_bin2bn(
248      reinterpret_cast<const unsigned char*>(&new_bytes[0]),
249      static_cast<int>(new_bytes.size()),
250      num);
251  return (ret != NULL);
252}
253
254// Decode the contents of an encoded big integer and either create a new
255// BIGNUM object (if |*num_ptr| is NULL on input) or copy it (if
256// |*num_ptr| is not NULL).
257// |new_bytes| is the byte encoding of the new value.
258// |num_ptr| is the address of a BIGNUM pointer. |*num_ptr| can be NULL.
259// Returns true on success, false otherwise. On failure, |*num_ptr| is
260// not modified. On success, |*num_ptr| will always be non-NULL and
261// point to a valid BIGNUM object.
262bool SwapBigNumPtrFromBytes(const std::vector<uint8>& new_bytes,
263                            BIGNUM** num_ptr) {
264  BIGNUM* old_num = *num_ptr;
265  BIGNUM* new_num = BN_bin2bn(
266      reinterpret_cast<const unsigned char*>(&new_bytes[0]),
267      static_cast<int>(new_bytes.size()),
268      old_num);
269  if (new_num == NULL)
270    return false;
271
272  if (old_num == NULL)
273    *num_ptr = new_num;
274  return true;
275}
276
277// Setup an EVP_PKEY to wrap an existing platform RSA PrivateKey object.
278// |private_key| is the JNI reference (local or global) to the object.
279// |pkey| is the EVP_PKEY to setup as a wrapper.
280// Returns true on success, false otherwise.
281// On success, this creates a new global JNI reference to the object
282// that is owned by and destroyed with the EVP_PKEY. I.e. caller can
283// free |private_key| after the call.
284// IMPORTANT: The EVP_PKEY will *only* work on Android >= 4.2. For older
285// platforms, use GetRsaLegacyKey() instead.
286bool GetRsaPkeyWrapper(jobject private_key, EVP_PKEY* pkey) {
287  ScopedRSA rsa(RSA_new());
288  RSA_set_method(rsa.get(), &android_rsa_method);
289
290  // HACK: RSA_size() doesn't work with custom RSA_METHODs. To ensure that
291  // it will return the right value, set the 'n' field of the RSA object
292  // to match the private key's modulus.
293  std::vector<uint8> modulus;
294  if (!GetRSAKeyModulus(private_key, &modulus)) {
295    LOG(ERROR) << "Failed to get private key modulus";
296    return false;
297  }
298  if (!SwapBigNumPtrFromBytes(modulus, &rsa.get()->n)) {
299    LOG(ERROR) << "Failed to decode private key modulus";
300    return false;
301  }
302
303  ScopedJavaGlobalRef<jobject> global_key;
304  global_key.Reset(NULL, private_key);
305  if (global_key.is_null()) {
306    LOG(ERROR) << "Could not create global JNI reference";
307    return false;
308  }
309  RSA_set_app_data(rsa.get(), global_key.Release());
310  EVP_PKEY_assign_RSA(pkey, rsa.release());
311  return true;
312}
313
314// Setup an EVP_PKEY to wrap an existing platform RSA PrivateKey object
315// for Android 4.0 to 4.1.x. Must only be used on Android < 4.2.
316// |private_key| is a JNI reference (local or global) to the object.
317// |pkey| is the EVP_PKEY to setup as a wrapper.
318// Returns true on success, false otherwise.
319EVP_PKEY* GetRsaLegacyKey(jobject private_key) {
320  EVP_PKEY* sys_pkey =
321      GetOpenSSLSystemHandleForPrivateKey(private_key);
322  if (sys_pkey != NULL) {
323    CRYPTO_add(&sys_pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
324  } else {
325    // GetOpenSSLSystemHandleForPrivateKey() will fail on Android
326    // 4.0.3 and earlier. However, it is possible to get the key
327    // content with PrivateKey.getEncoded() on these platforms.
328    // Note that this method may return NULL on 4.0.4 and later.
329    std::vector<uint8> encoded;
330    if (!GetPrivateKeyEncodedBytes(private_key, &encoded)) {
331      LOG(ERROR) << "Can't get private key data!";
332      return NULL;
333    }
334    const unsigned char* p =
335        reinterpret_cast<const unsigned char*>(&encoded[0]);
336    int len = static_cast<int>(encoded.size());
337    sys_pkey = d2i_AutoPrivateKey(NULL, &p, len);
338    if (sys_pkey == NULL) {
339      LOG(ERROR) << "Can't convert private key data!";
340      return NULL;
341    }
342  }
343  return sys_pkey;
344}
345
346// Custom DSA_METHOD that uses the platform APIs.
347// Note that for now, only signing through DSA_sign() is really supported.
348// all other method pointers are either stubs returning errors, or no-ops.
349// See <openssl/dsa.h> for exact declaration of DSA_METHOD.
350//
351// Note: There is no DSA_set_app_data() and DSA_get_app_data() functions,
352//       but RSA_set_app_data() is defined as a simple macro that calls
353//       RSA_set_ex_data() with a hard-coded index of 0, so this code
354//       does the same thing here.
355
356DSA_SIG* DsaMethodDoSign(const unsigned char* dgst,
357                         int dlen,
358                         DSA* dsa) {
359  // Extract the JNI reference to the PrivateKey object.
360  jobject private_key = reinterpret_cast<jobject>(DSA_get_ex_data(dsa, 0));
361  if (private_key == NULL)
362    return NULL;
363
364  // Sign the message with it, calling platform APIs.
365  std::vector<uint8> signature;
366  if (!RawSignDigestWithPrivateKey(
367          private_key,
368          base::StringPiece(
369              reinterpret_cast<const char*>(dgst),
370              static_cast<size_t>(dlen)),
371          &signature)) {
372    return NULL;
373  }
374
375  // Note: With DSA, the actual signature might be smaller than DSA_size().
376  size_t max_expected_size = static_cast<size_t>(DSA_size(dsa));
377  if (signature.size() > max_expected_size) {
378    LOG(ERROR) << "DSA Signature size mismatch, actual: "
379               << signature.size() << ", expected <= "
380               << max_expected_size;
381    return NULL;
382  }
383
384  // Convert the signature into a DSA_SIG object.
385  const unsigned char* sigbuf =
386      reinterpret_cast<const unsigned char*>(&signature[0]);
387  int siglen = static_cast<size_t>(signature.size());
388  DSA_SIG* dsa_sig = d2i_DSA_SIG(NULL, &sigbuf, siglen);
389  return dsa_sig;
390}
391
392int DsaMethodSignSetup(DSA* dsa,
393                       BN_CTX* ctx_in,
394                       BIGNUM** kinvp,
395                       BIGNUM** rp) {
396  NOTIMPLEMENTED();
397  DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_INVALID_DIGEST_TYPE);
398  return -1;
399}
400
401int DsaMethodDoVerify(const unsigned char* dgst,
402                      int dgst_len,
403                      DSA_SIG* sig,
404                      DSA* dsa) {
405  NOTIMPLEMENTED();
406  DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_INVALID_DIGEST_TYPE);
407  return -1;
408}
409
410int DsaMethodFinish(DSA* dsa) {
411  // Free the global JNI reference that was created with this
412  // wrapper key.
413  jobject key = reinterpret_cast<jobject>(DSA_get_ex_data(dsa,0));
414  if (key != NULL) {
415    DSA_set_ex_data(dsa, 0, NULL);
416    JNIEnv* env = base::android::AttachCurrentThread();
417    env->DeleteGlobalRef(key);
418  }
419  // Actual return value is ignored by OpenSSL. There are no docs
420  // explaining what this is supposed to be.
421  return 0;
422}
423
424const DSA_METHOD android_dsa_method = {
425  /* .name = */ "Android signing-only DSA method",
426  /* .dsa_do_sign = */ DsaMethodDoSign,
427  /* .dsa_sign_setup = */ DsaMethodSignSetup,
428  /* .dsa_do_verify = */ DsaMethodDoVerify,
429  /* .dsa_mod_exp = */ NULL,
430  /* .bn_mod_exp = */ NULL,
431  /* .init = */ NULL,  // nothing to do here.
432  /* .finish = */ DsaMethodFinish,
433  /* .flags = */ 0,
434  /* .app_data = */ NULL,
435  /* .dsa_paramgem = */ NULL,
436  /* .dsa_keygen = */ NULL
437};
438
439// Setup an EVP_PKEY to wrap an existing DSA platform PrivateKey object.
440// |private_key| is a JNI reference (local or global) to the object.
441// |pkey| is the EVP_PKEY to setup as a wrapper.
442// Returns true on success, false otherwise.
443// On success, this creates a global JNI reference to the same object
444// that will be owned by and destroyed with the EVP_PKEY.
445bool GetDsaPkeyWrapper(jobject private_key, EVP_PKEY* pkey) {
446  ScopedDSA dsa(DSA_new());
447  DSA_set_method(dsa.get(), &android_dsa_method);
448
449  // DSA_size() doesn't work with custom DSA_METHODs. To ensure it
450  // returns the right value, set the 'q' field in the DSA object to
451  // match the parameter from the platform key.
452  std::vector<uint8> q;
453  if (!GetDSAKeyParamQ(private_key, &q)) {
454    LOG(ERROR) << "Can't extract Q parameter from DSA private key";
455    return false;
456  }
457  if (!SwapBigNumPtrFromBytes(q, &dsa.get()->q)) {
458    LOG(ERROR) << "Can't decode Q parameter from DSA private key";
459    return false;
460  }
461
462  ScopedJavaGlobalRef<jobject> global_key;
463  global_key.Reset(NULL, private_key);
464  if (global_key.is_null()) {
465    LOG(ERROR) << "Could not create global JNI reference";
466    return false;
467  }
468  DSA_set_ex_data(dsa.get(), 0, global_key.Release());
469  EVP_PKEY_assign_DSA(pkey, dsa.release());
470  return true;
471}
472
473// Custom ECDSA_METHOD that uses the platform APIs.
474// Note that for now, only signing through ECDSA_sign() is really supported.
475// all other method pointers are either stubs returning errors, or no-ops.
476//
477// Note: The ECDSA_METHOD structure doesn't have init/finish
478//       methods. As such, the only way to to ensure the global
479//       JNI reference is properly released when the EVP_PKEY is
480//       destroyed is to use a custom EX_DATA type.
481
482// Used to ensure that the global JNI reference associated with a custom
483// EC_KEY + ECDSA_METHOD wrapper is released when its EX_DATA is destroyed
484// (this function is called when EVP_PKEY_free() is called on the wrapper).
485void ExDataFree(void* parent,
486                void* ptr,
487                CRYPTO_EX_DATA* ad,
488                int idx,
489                long argl,
490                void* argp) {
491  jobject private_key = reinterpret_cast<jobject>(ptr);
492  if (private_key == NULL)
493    return;
494
495  CRYPTO_set_ex_data(ad, idx, NULL);
496
497  JNIEnv* env = base::android::AttachCurrentThread();
498  env->DeleteGlobalRef(private_key);
499}
500
501int ExDataDup(CRYPTO_EX_DATA* to,
502              CRYPTO_EX_DATA* from,
503              void* from_d,
504              int idx,
505              long argl,
506              void* argp) {
507  // This callback shall never be called with the current OpenSSL
508  // implementation (the library only ever duplicates EX_DATA items
509  // for SSL and BIO objects). But provide this to catch regressions
510  // in the future.
511  CHECK(false) << "ExDataDup was called for ECDSA custom key !?";
512  // Return value is currently ignored by OpenSSL.
513  return 0;
514}
515
516class EcdsaExDataIndex {
517public:
518  int ex_data_index() { return ex_data_index_; }
519
520  EcdsaExDataIndex() {
521    ex_data_index_ = ECDSA_get_ex_new_index(0,           // argl
522                                            NULL,        // argp
523                                            NULL,        // new_func
524                                            ExDataDup,   // dup_func
525                                            ExDataFree); // free_func
526  }
527
528private:
529  int ex_data_index_;
530};
531
532// Returns the index of the custom EX_DATA used to store the JNI reference.
533int EcdsaGetExDataIndex(void) {
534  // Use a LazyInstance to perform thread-safe lazy initialization.
535  // Use a leaky one, since OpenSSL doesn't provide a way to release
536  // allocated EX_DATA indices.
537  static base::LazyInstance<EcdsaExDataIndex>::Leaky s_instance =
538      LAZY_INSTANCE_INITIALIZER;
539  return s_instance.Get().ex_data_index();
540}
541
542ECDSA_SIG* EcdsaMethodDoSign(const unsigned char* dgst,
543                             int dgst_len,
544                             const BIGNUM* inv,
545                             const BIGNUM* rp,
546                             EC_KEY* eckey) {
547  // Retrieve private key JNI reference.
548  jobject private_key = reinterpret_cast<jobject>(
549      ECDSA_get_ex_data(eckey, EcdsaGetExDataIndex()));
550  if (!private_key) {
551    LOG(WARNING) << "Null JNI reference passed to EcdsaMethodDoSign!";
552    return NULL;
553  }
554  // Sign message with it through JNI.
555  std::vector<uint8> signature;
556  base::StringPiece digest(
557      reinterpret_cast<const char*>(dgst),
558      static_cast<size_t>(dgst_len));
559  if (!RawSignDigestWithPrivateKey(
560          private_key, digest, &signature)) {
561    LOG(WARNING) << "Could not sign message in EcdsaMethodDoSign!";
562    return NULL;
563  }
564
565  // Note: With ECDSA, the actual signature may be smaller than
566  // ECDSA_size().
567  size_t max_expected_size = static_cast<size_t>(ECDSA_size(eckey));
568  if (signature.size() > max_expected_size) {
569    LOG(ERROR) << "ECDSA Signature size mismatch, actual: "
570               <<  signature.size() << ", expected <= "
571               << max_expected_size;
572    return NULL;
573  }
574
575  // Convert signature to ECDSA_SIG object
576  const unsigned char* sigbuf =
577      reinterpret_cast<const unsigned char*>(&signature[0]);
578  long siglen = static_cast<long>(signature.size());
579  return d2i_ECDSA_SIG(NULL, &sigbuf, siglen);
580}
581
582int EcdsaMethodSignSetup(EC_KEY* eckey,
583                         BN_CTX* ctx,
584                         BIGNUM** kinv,
585                         BIGNUM** r) {
586  NOTIMPLEMENTED();
587  ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_ERR_EC_LIB);
588  return -1;
589}
590
591int EcdsaMethodDoVerify(const unsigned char* dgst,
592                        int dgst_len,
593                        const ECDSA_SIG* sig,
594                        EC_KEY* eckey) {
595  NOTIMPLEMENTED();
596  ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_ERR_EC_LIB);
597  return -1;
598}
599
600const ECDSA_METHOD android_ecdsa_method = {
601  /* .name = */ "Android signing-only ECDSA method",
602  /* .ecdsa_do_sign = */ EcdsaMethodDoSign,
603  /* .ecdsa_sign_setup = */ EcdsaMethodSignSetup,
604  /* .ecdsa_do_verify = */ EcdsaMethodDoVerify,
605  /* .flags = */ 0,
606  /* .app_data = */ NULL,
607};
608
609// Setup an EVP_PKEY to wrap an existing platform PrivateKey object.
610// |private_key| is the JNI reference (local or global) to the object.
611// |pkey| is the EVP_PKEY to setup as a wrapper.
612// Returns true on success, false otherwise.
613// On success, this creates a global JNI reference to the object that
614// is owned by and destroyed with the EVP_PKEY. I.e. the caller shall
615// always free |private_key| after the call.
616bool GetEcdsaPkeyWrapper(jobject private_key, EVP_PKEY* pkey) {
617  ScopedEC_KEY eckey(EC_KEY_new());
618  ECDSA_set_method(eckey.get(), &android_ecdsa_method);
619
620  // To ensure that ECDSA_size() works properly, craft a custom EC_GROUP
621  // that has the same order than the private key.
622  std::vector<uint8> order;
623  if (!GetECKeyOrder(private_key, &order)) {
624    LOG(ERROR) << "Can't extract order parameter from EC private key";
625    return false;
626  }
627  ScopedEC_GROUP group(EC_GROUP_new(EC_GFp_nist_method()));
628  if (!group.get()) {
629    LOG(ERROR) << "Can't create new EC_GROUP";
630    return false;
631  }
632  if (!CopyBigNumFromBytes(order, &group.get()->order)) {
633    LOG(ERROR) << "Can't decode order from PrivateKey";
634    return false;
635  }
636  EC_KEY_set_group(eckey.get(), group.release());
637
638  ScopedJavaGlobalRef<jobject> global_key;
639  global_key.Reset(NULL, private_key);
640  if (global_key.is_null()) {
641    LOG(ERROR) << "Can't create global JNI reference";
642    return false;
643  }
644  ECDSA_set_ex_data(eckey.get(),
645                    EcdsaGetExDataIndex(),
646                    global_key.Release());
647
648  EVP_PKEY_assign_EC_KEY(pkey, eckey.release());
649  return true;
650}
651
652}  // namespace
653
654EVP_PKEY* GetOpenSSLPrivateKeyWrapper(jobject private_key) {
655  // Create new empty EVP_PKEY instance.
656  ScopedEVP_PKEY pkey(EVP_PKEY_new());
657  if (!pkey.get())
658    return NULL;
659
660  // Create sub key type, depending on private key's algorithm type.
661  PrivateKeyType key_type = GetPrivateKeyType(private_key);
662  switch (key_type) {
663    case PRIVATE_KEY_TYPE_RSA:
664      {
665        // Route around platform bug: if Android < 4.2, then
666        // base::android::RawSignDigestWithPrivateKey() cannot work, so
667        // instead, obtain a raw EVP_PKEY* to the system object
668        // backing this PrivateKey object.
669        const int kAndroid42ApiLevel = 17;
670        if (base::android::BuildInfo::GetInstance()->sdk_int() <
671            kAndroid42ApiLevel) {
672          EVP_PKEY* legacy_key = GetRsaLegacyKey(private_key);
673          if (legacy_key == NULL)
674            return NULL;
675          pkey.reset(legacy_key);
676        } else {
677          // Running on Android 4.2.
678          if (!GetRsaPkeyWrapper(private_key, pkey.get()))
679            return NULL;
680        }
681      }
682      break;
683    case PRIVATE_KEY_TYPE_DSA:
684      if (!GetDsaPkeyWrapper(private_key, pkey.get()))
685        return NULL;
686      break;
687    case PRIVATE_KEY_TYPE_ECDSA:
688      if (!GetEcdsaPkeyWrapper(private_key, pkey.get()))
689        return NULL;
690      break;
691    default:
692      LOG(WARNING)
693          << "GetOpenSSLPrivateKeyWrapper() called with invalid key type";
694      return NULL;
695  }
696  return pkey.release();
697}
698
699}  // namespace android
700}  // namespace net
701