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