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 MAC 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 97 using base::android::ScopedJavaGlobalRef; 98 99 namespace net { 100 namespace android { 101 102 namespace { 103 104 typedef crypto::ScopedOpenSSL<EVP_PKEY, EVP_PKEY_free> ScopedEVP_PKEY; 105 typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA; 106 typedef crypto::ScopedOpenSSL<DSA, DSA_free> ScopedDSA; 107 typedef crypto::ScopedOpenSSL<EC_KEY, EC_KEY_free> ScopedEC_KEY; 108 typedef crypto::ScopedOpenSSL<EC_GROUP, EC_GROUP_free> ScopedEC_GROUP; 109 typedef crypto::ScopedOpenSSL<X509_SIG, X509_SIG_free> ScopedX509_SIG; 110 111 // Custom RSA_METHOD that uses the platform APIs. 112 // Note that for now, only signing through RSA_sign() is really supported. 113 // all other method pointers are either stubs returning errors, or no-ops. 114 // See <openssl/rsa.h> for exact declaration of RSA_METHOD. 115 116 int RsaMethodPubEnc(int flen, 117 const unsigned char* from, 118 unsigned char* to, 119 RSA* rsa, 120 int padding) { 121 NOTIMPLEMENTED(); 122 RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); 123 return -1; 124 } 125 126 int RsaMethodPubDec(int flen, 127 const unsigned char* from, 128 unsigned char* to, 129 RSA* rsa, 130 int padding) { 131 NOTIMPLEMENTED(); 132 RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); 133 return -1; 134 } 135 136 int RsaMethodPrivEnc(int flen, 137 const unsigned char *from, 138 unsigned char *to, 139 RSA *rsa, 140 int padding) { 141 NOTIMPLEMENTED(); 142 RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); 143 return -1; 144 } 145 146 int RsaMethodPrivDec(int flen, 147 const unsigned char* from, 148 unsigned char* to, 149 RSA* rsa, 150 int padding) { 151 NOTIMPLEMENTED(); 152 RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); 153 return -1; 154 } 155 156 int RsaMethodInit(RSA* rsa) { 157 // Required to ensure that RsaMethodSign will be called. 158 rsa->flags |= RSA_FLAG_SIGN_VER; 159 return 0; 160 } 161 162 int RsaMethodFinish(RSA* rsa) { 163 // Ensure the global JNI reference created with this wrapper is 164 // properly destroyed with it. 165 jobject key = reinterpret_cast<jobject>(RSA_get_app_data(rsa)); 166 if (key != NULL) { 167 RSA_set_app_data(rsa, NULL); 168 JNIEnv* env = base::android::AttachCurrentThread(); 169 env->DeleteGlobalRef(key); 170 } 171 // Actual return value is ignored by OpenSSL. There are no docs 172 // explaining what this is supposed to be. 173 return 0; 174 } 175 176 // Although these parameters are, per OpenSSL, named |message| and 177 // |message_len|, RsaMethodSign is actually passed a message digest, 178 // not the original message. 179 int RsaMethodSign(int type, 180 const unsigned char* message, 181 unsigned int message_len, 182 unsigned char* signature, 183 unsigned int* signature_len, 184 const RSA* rsa) { 185 // Retrieve private key JNI reference. 186 jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa)); 187 if (!private_key) { 188 LOG(WARNING) << "Null JNI reference passed to RsaMethodSign!"; 189 return 0; 190 } 191 192 // See RSA_sign in third_party/openssl/openssl/crypto/rsa/rsa_sign.c. 193 base::StringPiece message_piece; 194 std::vector<uint8> buffer; // To store |message| wrapped in a DigestInfo. 195 if (type == NID_md5_sha1) { 196 // For TLS < 1.2, sign just |message|. 197 message_piece.set(message, static_cast<size_t>(message_len)); 198 } else { 199 // For TLS 1.2, wrap |message| in a PKCS #1 DigestInfo before signing. 200 ScopedX509_SIG sig(X509_SIG_new()); 201 if (!sig.get()) 202 return 0; 203 if (X509_ALGOR_set0(sig.get()->algor, 204 OBJ_nid2obj(type), V_ASN1_NULL, 0) != 1) { 205 return 0; 206 } 207 if (sig.get()->algor->algorithm == NULL) { 208 RSAerr(RSA_F_RSA_SIGN, RSA_R_UNKNOWN_ALGORITHM_TYPE); 209 return 0; 210 } 211 if (sig.get()->algor->algorithm->length == 0) { 212 RSAerr(RSA_F_RSA_SIGN, 213 RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD); 214 return 0; 215 } 216 if (ASN1_OCTET_STRING_set(sig.get()->digest, message, message_len) != 1) 217 return 0; 218 219 int len = i2d_X509_SIG(sig.get(), NULL); 220 if (len < 0) { 221 LOG(WARNING) << "Couldn't encode X509_SIG structure"; 222 return 0; 223 } 224 buffer.resize(len); 225 // OpenSSL takes a pointer to a pointer so it can kindly increment 226 // it for you. 227 unsigned char* p = &buffer[0]; 228 len = i2d_X509_SIG(sig.get(), &p); 229 if (len < 0) { 230 LOG(WARNING) << "Couldn't encode X509_SIG structure"; 231 return 0; 232 } 233 234 message_piece.set(&buffer[0], static_cast<size_t>(len)); 235 } 236 237 // Sanity-check the size. 238 // 239 // TODO(davidben): Do we need to do this? OpenSSL does, but 240 // RawSignDigestWithPrivateKey does error on sufficiently large 241 // input. However, it doesn't take the padding into account. 242 size_t expected_size = static_cast<size_t>(RSA_size(rsa)); 243 if (message_piece.size() > expected_size - RSA_PKCS1_PADDING_SIZE) { 244 RSAerr(RSA_F_RSA_SIGN, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); 245 return 0; 246 } 247 248 // Sign |message_piece| with the private key through JNI. 249 std::vector<uint8> result; 250 251 if (!RawSignDigestWithPrivateKey( 252 private_key, message_piece, &result)) { 253 LOG(WARNING) << "Could not sign message in RsaMethodSign!"; 254 return 0; 255 } 256 257 if (result.size() > expected_size) { 258 LOG(ERROR) << "RSA Signature size mismatch, actual: " 259 << result.size() << ", expected <= " << expected_size; 260 return 0; 261 } 262 263 // Copy result to OpenSSL-provided buffer 264 memcpy(signature, &result[0], result.size()); 265 *signature_len = static_cast<unsigned int>(result.size()); 266 return 1; 267 } 268 269 const RSA_METHOD android_rsa_method = { 270 /* .name = */ "Android signing-only RSA method", 271 /* .rsa_pub_enc = */ RsaMethodPubEnc, 272 /* .rsa_pub_dec = */ RsaMethodPubDec, 273 /* .rsa_priv_enc = */ RsaMethodPrivEnc, 274 /* .rsa_priv_dec = */ RsaMethodPrivDec, 275 /* .rsa_mod_exp = */ NULL, 276 /* .bn_mod_exp = */ NULL, 277 /* .init = */ RsaMethodInit, 278 /* .finish = */ RsaMethodFinish, 279 // This flag is necessary to tell OpenSSL to avoid checking the content 280 // (i.e. internal fields) of the private key. Otherwise, it will complain 281 // it's not valid for the certificate. 282 /* .flags = */ RSA_METHOD_FLAG_NO_CHECK, 283 /* .app_data = */ NULL, 284 /* .rsa_sign = */ RsaMethodSign, 285 /* .rsa_verify = */ NULL, 286 /* .rsa_keygen = */ NULL, 287 }; 288 289 // Copy the contents of an encoded big integer into an existing BIGNUM. 290 // This function modifies |*num| in-place. 291 // |new_bytes| is the byte encoding of the new value. 292 // |num| points to the BIGNUM which will be assigned with the new value. 293 // Returns true on success, false otherwise. On failure, |*num| is 294 // not modified. 295 bool CopyBigNumFromBytes(const std::vector<uint8>& new_bytes, 296 BIGNUM* num) { 297 BIGNUM* ret = BN_bin2bn( 298 reinterpret_cast<const unsigned char*>(&new_bytes[0]), 299 static_cast<int>(new_bytes.size()), 300 num); 301 return (ret != NULL); 302 } 303 304 // Decode the contents of an encoded big integer and either create a new 305 // BIGNUM object (if |*num_ptr| is NULL on input) or copy it (if 306 // |*num_ptr| is not NULL). 307 // |new_bytes| is the byte encoding of the new value. 308 // |num_ptr| is the address of a BIGNUM pointer. |*num_ptr| can be NULL. 309 // Returns true on success, false otherwise. On failure, |*num_ptr| is 310 // not modified. On success, |*num_ptr| will always be non-NULL and 311 // point to a valid BIGNUM object. 312 bool SwapBigNumPtrFromBytes(const std::vector<uint8>& new_bytes, 313 BIGNUM** num_ptr) { 314 BIGNUM* old_num = *num_ptr; 315 BIGNUM* new_num = BN_bin2bn( 316 reinterpret_cast<const unsigned char*>(&new_bytes[0]), 317 static_cast<int>(new_bytes.size()), 318 old_num); 319 if (new_num == NULL) 320 return false; 321 322 if (old_num == NULL) 323 *num_ptr = new_num; 324 return true; 325 } 326 327 // Setup an EVP_PKEY to wrap an existing platform RSA PrivateKey object. 328 // |private_key| is the JNI reference (local or global) to the object. 329 // |pkey| is the EVP_PKEY to setup as a wrapper. 330 // Returns true on success, false otherwise. 331 // On success, this creates a new global JNI reference to the object 332 // that is owned by and destroyed with the EVP_PKEY. I.e. caller can 333 // free |private_key| after the call. 334 // IMPORTANT: The EVP_PKEY will *only* work on Android >= 4.2. For older 335 // platforms, use GetRsaLegacyKey() instead. 336 bool GetRsaPkeyWrapper(jobject private_key, EVP_PKEY* pkey) { 337 ScopedRSA rsa(RSA_new()); 338 RSA_set_method(rsa.get(), &android_rsa_method); 339 340 // HACK: RSA_size() doesn't work with custom RSA_METHODs. To ensure that 341 // it will return the right value, set the 'n' field of the RSA object 342 // to match the private key's modulus. 343 std::vector<uint8> modulus; 344 if (!GetRSAKeyModulus(private_key, &modulus)) { 345 LOG(ERROR) << "Failed to get private key modulus"; 346 return false; 347 } 348 if (!SwapBigNumPtrFromBytes(modulus, &rsa.get()->n)) { 349 LOG(ERROR) << "Failed to decode private key modulus"; 350 return false; 351 } 352 353 ScopedJavaGlobalRef<jobject> global_key; 354 global_key.Reset(NULL, private_key); 355 if (global_key.is_null()) { 356 LOG(ERROR) << "Could not create global JNI reference"; 357 return false; 358 } 359 RSA_set_app_data(rsa.get(), global_key.Release()); 360 EVP_PKEY_assign_RSA(pkey, rsa.release()); 361 return true; 362 } 363 364 // Setup an EVP_PKEY to wrap an existing platform RSA PrivateKey object 365 // for Android 4.0 to 4.1.x. Must only be used on Android < 4.2. 366 // |private_key| is a JNI reference (local or global) to the object. 367 // |pkey| is the EVP_PKEY to setup as a wrapper. 368 // Returns true on success, false otherwise. 369 EVP_PKEY* GetRsaLegacyKey(jobject private_key) { 370 EVP_PKEY* sys_pkey = 371 GetOpenSSLSystemHandleForPrivateKey(private_key); 372 if (sys_pkey != NULL) { 373 CRYPTO_add(&sys_pkey->references, 1, CRYPTO_LOCK_EVP_PKEY); 374 } else { 375 // GetOpenSSLSystemHandleForPrivateKey() will fail on Android 376 // 4.0.3 and earlier. However, it is possible to get the key 377 // content with PrivateKey.getEncoded() on these platforms. 378 // Note that this method may return NULL on 4.0.4 and later. 379 std::vector<uint8> encoded; 380 if (!GetPrivateKeyEncodedBytes(private_key, &encoded)) { 381 LOG(ERROR) << "Can't get private key data!"; 382 return NULL; 383 } 384 const unsigned char* p = 385 reinterpret_cast<const unsigned char*>(&encoded[0]); 386 int len = static_cast<int>(encoded.size()); 387 sys_pkey = d2i_AutoPrivateKey(NULL, &p, len); 388 if (sys_pkey == NULL) { 389 LOG(ERROR) << "Can't convert private key data!"; 390 return NULL; 391 } 392 } 393 return sys_pkey; 394 } 395 396 // Custom DSA_METHOD that uses the platform APIs. 397 // Note that for now, only signing through DSA_sign() is really supported. 398 // all other method pointers are either stubs returning errors, or no-ops. 399 // See <openssl/dsa.h> for exact declaration of DSA_METHOD. 400 // 401 // Note: There is no DSA_set_app_data() and DSA_get_app_data() functions, 402 // but RSA_set_app_data() is defined as a simple macro that calls 403 // RSA_set_ex_data() with a hard-coded index of 0, so this code 404 // does the same thing here. 405 406 DSA_SIG* DsaMethodDoSign(const unsigned char* dgst, 407 int dlen, 408 DSA* dsa) { 409 // Extract the JNI reference to the PrivateKey object. 410 jobject private_key = reinterpret_cast<jobject>(DSA_get_ex_data(dsa, 0)); 411 if (private_key == NULL) 412 return NULL; 413 414 // Sign the message with it, calling platform APIs. 415 std::vector<uint8> signature; 416 if (!RawSignDigestWithPrivateKey( 417 private_key, 418 base::StringPiece( 419 reinterpret_cast<const char*>(dgst), 420 static_cast<size_t>(dlen)), 421 &signature)) { 422 return NULL; 423 } 424 425 // Note: With DSA, the actual signature might be smaller than DSA_size(). 426 size_t max_expected_size = static_cast<size_t>(DSA_size(dsa)); 427 if (signature.size() > max_expected_size) { 428 LOG(ERROR) << "DSA Signature size mismatch, actual: " 429 << signature.size() << ", expected <= " 430 << max_expected_size; 431 return NULL; 432 } 433 434 // Convert the signature into a DSA_SIG object. 435 const unsigned char* sigbuf = 436 reinterpret_cast<const unsigned char*>(&signature[0]); 437 int siglen = static_cast<size_t>(signature.size()); 438 DSA_SIG* dsa_sig = d2i_DSA_SIG(NULL, &sigbuf, siglen); 439 return dsa_sig; 440 } 441 442 int DsaMethodSignSetup(DSA* dsa, 443 BN_CTX* ctx_in, 444 BIGNUM** kinvp, 445 BIGNUM** rp) { 446 NOTIMPLEMENTED(); 447 DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_INVALID_DIGEST_TYPE); 448 return -1; 449 } 450 451 int DsaMethodDoVerify(const unsigned char* dgst, 452 int dgst_len, 453 DSA_SIG* sig, 454 DSA* dsa) { 455 NOTIMPLEMENTED(); 456 DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_INVALID_DIGEST_TYPE); 457 return -1; 458 } 459 460 int DsaMethodFinish(DSA* dsa) { 461 // Free the global JNI reference that was created with this 462 // wrapper key. 463 jobject key = reinterpret_cast<jobject>(DSA_get_ex_data(dsa,0)); 464 if (key != NULL) { 465 DSA_set_ex_data(dsa, 0, NULL); 466 JNIEnv* env = base::android::AttachCurrentThread(); 467 env->DeleteGlobalRef(key); 468 } 469 // Actual return value is ignored by OpenSSL. There are no docs 470 // explaining what this is supposed to be. 471 return 0; 472 } 473 474 const DSA_METHOD android_dsa_method = { 475 /* .name = */ "Android signing-only DSA method", 476 /* .dsa_do_sign = */ DsaMethodDoSign, 477 /* .dsa_sign_setup = */ DsaMethodSignSetup, 478 /* .dsa_do_verify = */ DsaMethodDoVerify, 479 /* .dsa_mod_exp = */ NULL, 480 /* .bn_mod_exp = */ NULL, 481 /* .init = */ NULL, // nothing to do here. 482 /* .finish = */ DsaMethodFinish, 483 /* .flags = */ 0, 484 /* .app_data = */ NULL, 485 /* .dsa_paramgem = */ NULL, 486 /* .dsa_keygen = */ NULL 487 }; 488 489 // Setup an EVP_PKEY to wrap an existing DSA platform PrivateKey object. 490 // |private_key| is a JNI reference (local or global) to the object. 491 // |pkey| is the EVP_PKEY to setup as a wrapper. 492 // Returns true on success, false otherwise. 493 // On success, this creates a global JNI reference to the same object 494 // that will be owned by and destroyed with the EVP_PKEY. 495 bool GetDsaPkeyWrapper(jobject private_key, EVP_PKEY* pkey) { 496 ScopedDSA dsa(DSA_new()); 497 DSA_set_method(dsa.get(), &android_dsa_method); 498 499 // DSA_size() doesn't work with custom DSA_METHODs. To ensure it 500 // returns the right value, set the 'q' field in the DSA object to 501 // match the parameter from the platform key. 502 std::vector<uint8> q; 503 if (!GetDSAKeyParamQ(private_key, &q)) { 504 LOG(ERROR) << "Can't extract Q parameter from DSA private key"; 505 return false; 506 } 507 if (!SwapBigNumPtrFromBytes(q, &dsa.get()->q)) { 508 LOG(ERROR) << "Can't decode Q parameter from DSA private key"; 509 return false; 510 } 511 512 ScopedJavaGlobalRef<jobject> global_key; 513 global_key.Reset(NULL, private_key); 514 if (global_key.is_null()) { 515 LOG(ERROR) << "Could not create global JNI reference"; 516 return false; 517 } 518 DSA_set_ex_data(dsa.get(), 0, global_key.Release()); 519 EVP_PKEY_assign_DSA(pkey, dsa.release()); 520 return true; 521 } 522 523 // Custom ECDSA_METHOD that uses the platform APIs. 524 // Note that for now, only signing through ECDSA_sign() is really supported. 525 // all other method pointers are either stubs returning errors, or no-ops. 526 // 527 // Note: The ECDSA_METHOD structure doesn't have init/finish 528 // methods. As such, the only way to to ensure the global 529 // JNI reference is properly released when the EVP_PKEY is 530 // destroyed is to use a custom EX_DATA type. 531 532 // Used to ensure that the global JNI reference associated with a custom 533 // EC_KEY + ECDSA_METHOD wrapper is released when its EX_DATA is destroyed 534 // (this function is called when EVP_PKEY_free() is called on the wrapper). 535 void ExDataFree(void* parent, 536 void* ptr, 537 CRYPTO_EX_DATA* ad, 538 int idx, 539 long argl, 540 void* argp) { 541 jobject private_key = reinterpret_cast<jobject>(ptr); 542 if (private_key == NULL) 543 return; 544 545 CRYPTO_set_ex_data(ad, idx, NULL); 546 547 JNIEnv* env = base::android::AttachCurrentThread(); 548 env->DeleteGlobalRef(private_key); 549 } 550 551 int ExDataDup(CRYPTO_EX_DATA* to, 552 CRYPTO_EX_DATA* from, 553 void* from_d, 554 int idx, 555 long argl, 556 void* argp) { 557 // This callback shall never be called with the current OpenSSL 558 // implementation (the library only ever duplicates EX_DATA items 559 // for SSL and BIO objects). But provide this to catch regressions 560 // in the future. 561 CHECK(false) << "ExDataDup was called for ECDSA custom key !?"; 562 // Return value is currently ignored by OpenSSL. 563 return 0; 564 } 565 566 class EcdsaExDataIndex { 567 public: 568 int ex_data_index() { return ex_data_index_; } 569 570 EcdsaExDataIndex() { 571 ex_data_index_ = ECDSA_get_ex_new_index(0, // argl 572 NULL, // argp 573 NULL, // new_func 574 ExDataDup, // dup_func 575 ExDataFree); // free_func 576 } 577 578 private: 579 int ex_data_index_; 580 }; 581 582 // Returns the index of the custom EX_DATA used to store the JNI reference. 583 int EcdsaGetExDataIndex(void) { 584 // Use a LazyInstance to perform thread-safe lazy initialization. 585 // Use a leaky one, since OpenSSL doesn't provide a way to release 586 // allocated EX_DATA indices. 587 static base::LazyInstance<EcdsaExDataIndex>::Leaky s_instance = 588 LAZY_INSTANCE_INITIALIZER; 589 return s_instance.Get().ex_data_index(); 590 } 591 592 ECDSA_SIG* EcdsaMethodDoSign(const unsigned char* dgst, 593 int dgst_len, 594 const BIGNUM* inv, 595 const BIGNUM* rp, 596 EC_KEY* eckey) { 597 // Retrieve private key JNI reference. 598 jobject private_key = reinterpret_cast<jobject>( 599 ECDSA_get_ex_data(eckey, EcdsaGetExDataIndex())); 600 if (!private_key) { 601 LOG(WARNING) << "Null JNI reference passed to EcdsaMethodDoSign!"; 602 return NULL; 603 } 604 // Sign message with it through JNI. 605 std::vector<uint8> signature; 606 base::StringPiece digest( 607 reinterpret_cast<const char*>(dgst), 608 static_cast<size_t>(dgst_len)); 609 if (!RawSignDigestWithPrivateKey( 610 private_key, digest, &signature)) { 611 LOG(WARNING) << "Could not sign message in EcdsaMethodDoSign!"; 612 return NULL; 613 } 614 615 // Note: With ECDSA, the actual signature may be smaller than 616 // ECDSA_size(). 617 size_t max_expected_size = static_cast<size_t>(ECDSA_size(eckey)); 618 if (signature.size() > max_expected_size) { 619 LOG(ERROR) << "ECDSA Signature size mismatch, actual: " 620 << signature.size() << ", expected <= " 621 << max_expected_size; 622 return NULL; 623 } 624 625 // Convert signature to ECDSA_SIG object 626 const unsigned char* sigbuf = 627 reinterpret_cast<const unsigned char*>(&signature[0]); 628 long siglen = static_cast<long>(signature.size()); 629 return d2i_ECDSA_SIG(NULL, &sigbuf, siglen); 630 } 631 632 int EcdsaMethodSignSetup(EC_KEY* eckey, 633 BN_CTX* ctx, 634 BIGNUM** kinv, 635 BIGNUM** r) { 636 NOTIMPLEMENTED(); 637 ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_ERR_EC_LIB); 638 return -1; 639 } 640 641 int EcdsaMethodDoVerify(const unsigned char* dgst, 642 int dgst_len, 643 const ECDSA_SIG* sig, 644 EC_KEY* eckey) { 645 NOTIMPLEMENTED(); 646 ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_ERR_EC_LIB); 647 return -1; 648 } 649 650 const ECDSA_METHOD android_ecdsa_method = { 651 /* .name = */ "Android signing-only ECDSA method", 652 /* .ecdsa_do_sign = */ EcdsaMethodDoSign, 653 /* .ecdsa_sign_setup = */ EcdsaMethodSignSetup, 654 /* .ecdsa_do_verify = */ EcdsaMethodDoVerify, 655 /* .flags = */ 0, 656 /* .app_data = */ NULL, 657 }; 658 659 // Setup an EVP_PKEY to wrap an existing platform PrivateKey object. 660 // |private_key| is the JNI reference (local or global) to the object. 661 // |pkey| is the EVP_PKEY to setup as a wrapper. 662 // Returns true on success, false otherwise. 663 // On success, this creates a global JNI reference to the object that 664 // is owned by and destroyed with the EVP_PKEY. I.e. the caller shall 665 // always free |private_key| after the call. 666 bool GetEcdsaPkeyWrapper(jobject private_key, EVP_PKEY* pkey) { 667 ScopedEC_KEY eckey(EC_KEY_new()); 668 ECDSA_set_method(eckey.get(), &android_ecdsa_method); 669 670 // To ensure that ECDSA_size() works properly, craft a custom EC_GROUP 671 // that has the same order than the private key. 672 std::vector<uint8> order; 673 if (!GetECKeyOrder(private_key, &order)) { 674 LOG(ERROR) << "Can't extract order parameter from EC private key"; 675 return false; 676 } 677 ScopedEC_GROUP group(EC_GROUP_new(EC_GFp_nist_method())); 678 if (!group.get()) { 679 LOG(ERROR) << "Can't create new EC_GROUP"; 680 return false; 681 } 682 if (!CopyBigNumFromBytes(order, &group.get()->order)) { 683 LOG(ERROR) << "Can't decode order from PrivateKey"; 684 return false; 685 } 686 EC_KEY_set_group(eckey.get(), group.release()); 687 688 ScopedJavaGlobalRef<jobject> global_key; 689 global_key.Reset(NULL, private_key); 690 if (global_key.is_null()) { 691 LOG(ERROR) << "Can't create global JNI reference"; 692 return false; 693 } 694 ECDSA_set_ex_data(eckey.get(), 695 EcdsaGetExDataIndex(), 696 global_key.Release()); 697 698 EVP_PKEY_assign_EC_KEY(pkey, eckey.release()); 699 return true; 700 } 701 702 } // namespace 703 704 EVP_PKEY* GetOpenSSLPrivateKeyWrapper(jobject private_key) { 705 // Create new empty EVP_PKEY instance. 706 ScopedEVP_PKEY pkey(EVP_PKEY_new()); 707 if (!pkey.get()) 708 return NULL; 709 710 // Create sub key type, depending on private key's algorithm type. 711 PrivateKeyType key_type = GetPrivateKeyType(private_key); 712 switch (key_type) { 713 case PRIVATE_KEY_TYPE_RSA: 714 { 715 // Route around platform bug: if Android < 4.2, then 716 // base::android::RawSignDigestWithPrivateKey() cannot work, so 717 // instead, obtain a raw EVP_PKEY* to the system object 718 // backing this PrivateKey object. 719 const int kAndroid42ApiLevel = 17; 720 if (base::android::BuildInfo::GetInstance()->sdk_int() < 721 kAndroid42ApiLevel) { 722 EVP_PKEY* legacy_key = GetRsaLegacyKey(private_key); 723 if (legacy_key == NULL) 724 return NULL; 725 pkey.reset(legacy_key); 726 } else { 727 // Running on Android 4.2. 728 if (!GetRsaPkeyWrapper(private_key, pkey.get())) 729 return NULL; 730 } 731 } 732 break; 733 case PRIVATE_KEY_TYPE_DSA: 734 if (!GetDsaPkeyWrapper(private_key, pkey.get())) 735 return NULL; 736 break; 737 case PRIVATE_KEY_TYPE_ECDSA: 738 if (!GetEcdsaPkeyWrapper(private_key, pkey.get())) 739 return NULL; 740 break; 741 default: 742 LOG(WARNING) 743 << "GetOpenSSLPrivateKeyWrapper() called with invalid key type"; 744 return NULL; 745 } 746 return pkey.release(); 747 } 748 749 } // namespace android 750 } // namespace net 751