1 // Copyright 2014 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.
5 #include "net/ssl/openssl_platform_key.h"
15 #include <openssl/bn.h>
16 #include <openssl/digest.h>
17 #include <openssl/ec_key.h>
18 #include <openssl/err.h>
19 #include <openssl/engine.h>
20 #include <openssl/evp.h>
21 #include <openssl/md5.h>
22 #include <openssl/obj_mac.h>
23 #include <openssl/rsa.h>
24 #include <openssl/sha.h>
26 #include "base/debug/debugger.h"
27 #include "base/debug/stack_trace.h"
28 #include "base/lazy_instance.h"
29 #include "base/logging.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/profiler/scoped_tracker.h"
32 #include "base/win/windows_version.h"
33 #include "crypto/scoped_capi_types.h"
34 #include "crypto/wincrypt_shim.h"
35 #include "net/base/net_errors.h"
36 #include "net/cert/x509_certificate.h"
37 #include "net/ssl/openssl_ssl_util.h"
43 using NCryptFreeObjectFunc
= SECURITY_STATUS(WINAPI
*)(NCRYPT_HANDLE
);
44 using NCryptGetPropertyFunc
=
45 SECURITY_STATUS(WINAPI
*)(NCRYPT_HANDLE
, // hObject
46 LPCWSTR
, // pszProperty
51 using NCryptSignHashFunc
=
52 SECURITY_STATUS(WINAPI
*)(NCRYPT_KEY_HANDLE
, // hKey
53 VOID
*, // pPaddingInfo
64 : ncrypt_free_object_(nullptr),
65 ncrypt_get_property_(nullptr),
66 ncrypt_sign_hash_(nullptr) {
67 HMODULE ncrypt
= GetModuleHandle(L
"ncrypt.dll");
68 if (ncrypt
!= nullptr) {
69 ncrypt_free_object_
= reinterpret_cast<NCryptFreeObjectFunc
>(
70 GetProcAddress(ncrypt
, "NCryptFreeObject"));
71 ncrypt_get_property_
= reinterpret_cast<NCryptGetPropertyFunc
>(
72 GetProcAddress(ncrypt
, "NCryptGetProperty"));
73 ncrypt_sign_hash_
= reinterpret_cast<NCryptSignHashFunc
>(
74 GetProcAddress(ncrypt
, "NCryptSignHash"));
78 NCryptFreeObjectFunc
ncrypt_free_object() const {
79 return ncrypt_free_object_
;
82 NCryptGetPropertyFunc
ncrypt_get_property() const {
83 return ncrypt_get_property_
;
86 NCryptSignHashFunc
ncrypt_sign_hash() const { return ncrypt_sign_hash_
; }
89 NCryptFreeObjectFunc ncrypt_free_object_
;
90 NCryptGetPropertyFunc ncrypt_get_property_
;
91 NCryptSignHashFunc ncrypt_sign_hash_
;
94 base::LazyInstance
<CNGFunctions
>::Leaky g_cng_functions
=
95 LAZY_INSTANCE_INITIALIZER
;
97 struct CERT_KEY_CONTEXTDeleter
{
98 void operator()(PCERT_KEY_CONTEXT key
) {
99 if (key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
100 g_cng_functions
.Get().ncrypt_free_object()(key
->hNCryptKey
);
102 CryptReleaseContext(key
->hCryptProv
, 0);
108 using ScopedCERT_KEY_CONTEXT
=
109 scoped_ptr
<CERT_KEY_CONTEXT
, CERT_KEY_CONTEXTDeleter
>;
111 // KeyExData contains the data that is contained in the EX_DATA of the
112 // RSA and ECDSA objects that are created to wrap Windows system keys.
114 KeyExData(ScopedCERT_KEY_CONTEXT key
, DWORD key_length
)
115 : key(key
.Pass()), key_length(key_length
) {}
117 ScopedCERT_KEY_CONTEXT key
;
121 // ExDataDup is called when one of the RSA or EC_KEY objects is
122 // duplicated. This is not supported and should never happen.
123 int ExDataDup(CRYPTO_EX_DATA
* to
,
124 const CRYPTO_EX_DATA
* from
,
129 CHECK_EQ((void*)nullptr, *from_d
);
133 // ExDataFree is called when one of the RSA or EC_KEY objects is freed.
134 void ExDataFree(void* parent
,
136 CRYPTO_EX_DATA
* ex_data
,
140 KeyExData
* data
= reinterpret_cast<KeyExData
*>(ptr
);
144 extern const RSA_METHOD win_rsa_method
;
145 extern const ECDSA_METHOD win_ecdsa_method
;
147 // BoringSSLEngine is a BoringSSL ENGINE that implements RSA and ECDSA
148 // by forwarding the requested operations to CAPI or CNG.
149 class BoringSSLEngine
{
152 : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
154 nullptr /* new_func */,
157 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
159 nullptr /* new_func */,
162 engine_(ENGINE_new()) {
163 ENGINE_set_RSA_method(engine_
, &win_rsa_method
, sizeof(win_rsa_method
));
164 ENGINE_set_ECDSA_method(engine_
, &win_ecdsa_method
,
165 sizeof(win_ecdsa_method
));
168 int rsa_ex_index() const { return rsa_index_
; }
169 int ec_key_ex_index() const { return ec_key_index_
; }
171 const ENGINE
* engine() const { return engine_
; }
174 const int rsa_index_
;
175 const int ec_key_index_
;
176 ENGINE
* const engine_
;
179 base::LazyInstance
<BoringSSLEngine
>::Leaky global_boringssl_engine
=
180 LAZY_INSTANCE_INITIALIZER
;
182 // Custom RSA_METHOD that uses the platform APIs for signing.
184 const KeyExData
* RsaGetExData(const RSA
* rsa
) {
185 return reinterpret_cast<const KeyExData
*>(
186 RSA_get_ex_data(rsa
, global_boringssl_engine
.Get().rsa_ex_index()));
189 size_t RsaMethodSize(const RSA
* rsa
) {
190 const KeyExData
* ex_data
= RsaGetExData(rsa
);
191 return (ex_data
->key_length
+ 7) / 8;
194 int RsaMethodSign(int hash_nid
,
200 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
201 tracked_objects::ScopedTracker
tracking_profile(
202 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 RsaMethodSign"));
204 // TODO(davidben): Switch BoringSSL's sign hook to using size_t rather than
206 const KeyExData
* ex_data
= RsaGetExData(rsa
);
209 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, ERR_R_INTERNAL_ERROR
);
213 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
214 BCRYPT_PKCS1_PADDING_INFO rsa_padding_info
;
217 rsa_padding_info
.pszAlgId
= nullptr;
220 rsa_padding_info
.pszAlgId
= BCRYPT_SHA1_ALGORITHM
;
223 rsa_padding_info
.pszAlgId
= BCRYPT_SHA256_ALGORITHM
;
226 rsa_padding_info
.pszAlgId
= BCRYPT_SHA384_ALGORITHM
;
229 rsa_padding_info
.pszAlgId
= BCRYPT_SHA512_ALGORITHM
;
232 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
237 SECURITY_STATUS ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
238 ex_data
->key
->hNCryptKey
, &rsa_padding_info
, const_cast<PBYTE
>(in
),
239 in_len
, out
, RSA_size(rsa
), &signature_len
, BCRYPT_PAD_PKCS1
);
240 if (FAILED(ncrypt_status
) || signature_len
== 0) {
241 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
244 *out_len
= signature_len
;
251 hash_alg
= CALG_SSL3_SHAMD5
;
254 hash_alg
= CALG_SHA1
;
257 hash_alg
= CALG_SHA_256
;
260 hash_alg
= CALG_SHA_384
;
263 hash_alg
= CALG_SHA_512
;
266 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
271 if (!CryptCreateHash(ex_data
->key
->hCryptProv
, hash_alg
, 0, 0, &hash
)) {
272 PLOG(ERROR
) << "CreateCreateHash failed";
273 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
277 DWORD arg_len
= sizeof(hash_len
);
278 if (!CryptGetHashParam(hash
, HP_HASHSIZE
, reinterpret_cast<BYTE
*>(&hash_len
),
280 PLOG(ERROR
) << "CryptGetHashParam HP_HASHSIZE failed";
281 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
284 if (hash_len
!= in_len
) {
285 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
288 if (!CryptSetHashParam(hash
, HP_HASHVAL
, const_cast<BYTE
*>(in
), 0)) {
289 PLOG(ERROR
) << "CryptSetHashParam HP_HASHVAL failed";
290 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
293 DWORD signature_len
= RSA_size(rsa
);
294 if (!CryptSignHash(hash
, ex_data
->key
->dwKeySpec
, nullptr, 0, out
,
296 PLOG(ERROR
) << "CryptSignHash failed";
297 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
301 /* CryptoAPI signs in little-endian, so reverse it. */
302 std::reverse(out
, out
+ signature_len
);
303 *out_len
= signature_len
;
307 int RsaMethodEncrypt(RSA
* rsa
,
315 OPENSSL_PUT_ERROR(RSA
, encrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
319 int RsaMethodSignRaw(RSA
* rsa
,
327 OPENSSL_PUT_ERROR(RSA
, encrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
331 int RsaMethodDecrypt(RSA
* rsa
,
339 OPENSSL_PUT_ERROR(RSA
, decrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
343 int RsaMethodVerifyRaw(RSA
* rsa
,
351 OPENSSL_PUT_ERROR(RSA
, verify_raw
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
355 int RsaMethodSupportsDigest(const RSA
* rsa
, const EVP_MD
* md
) {
356 const KeyExData
* ex_data
= RsaGetExData(rsa
);
362 int hash_nid
= EVP_MD_type(md
);
363 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
364 // Only hashes which appear in RsaSignPKCS1 are supported.
365 if (hash_nid
!= NID_sha1
&& hash_nid
!= NID_sha256
&&
366 hash_nid
!= NID_sha384
&& hash_nid
!= NID_sha512
) {
370 // If the key is a 1024-bit RSA, assume conservatively that it may only be
371 // able to sign SHA-1 hashes. This is the case for older Estonian ID cards
372 // that have 1024-bit RSA keys.
374 // CNG does provide NCryptIsAlgSupported and NCryptEnumAlgorithms functions,
375 // however they seem to both return NTE_NOT_SUPPORTED when querying the
376 // NCRYPT_PROV_HANDLE at the key's NCRYPT_PROVIDER_HANDLE_PROPERTY.
377 if (ex_data
->key_length
<= 1024 && hash_nid
!= NID_sha1
)
382 // If the key is in CAPI, assume conservatively that the CAPI service
383 // provider may only be able to sign SHA-1 hashes.
384 return hash_nid
== NID_sha1
;
388 const RSA_METHOD win_rsa_method
= {
404 nullptr, // private_transform
406 nullptr, // bn_mod_exp
409 RsaMethodSupportsDigest
,
412 // Custom ECDSA_METHOD that uses the platform APIs.
413 // Note that for now, only signing through ECDSA_sign() is really supported.
414 // all other method pointers are either stubs returning errors, or no-ops.
416 const KeyExData
* EcKeyGetExData(const EC_KEY
* ec_key
) {
417 return reinterpret_cast<const KeyExData
*>(EC_KEY_get_ex_data(
418 ec_key
, global_boringssl_engine
.Get().ec_key_ex_index()));
421 size_t EcdsaMethodGroupOrderSize(const EC_KEY
* ec_key
) {
422 const KeyExData
* ex_data
= EcKeyGetExData(ec_key
);
423 // Windows doesn't distinguish the sizes of the curve's degree (which
424 // determines the size of a point on the curve) and the base point's order
425 // (which determines the size of a scalar). For P-256, P-384, and P-521, these
426 // two sizes are the same.
429 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375520(v=vs.85).aspx
430 // which uses the same length for both.
431 return (ex_data
->key_length
+ 7) / 8;
434 int EcdsaMethodSign(const uint8_t* digest
,
437 unsigned int* out_sig_len
,
439 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
440 tracked_objects::ScopedTracker
tracking_profile(
441 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 EcdsaMethodSign"));
443 const KeyExData
* ex_data
= EcKeyGetExData(ec_key
);
444 // Only CNG supports ECDSA.
445 if (!ex_data
|| ex_data
->key
->dwKeySpec
!= CERT_NCRYPT_KEY_SPEC
) {
447 OPENSSL_PUT_ERROR(RSA
, sign_raw
, ERR_R_INTERNAL_ERROR
);
451 size_t degree
= (ex_data
->key_length
+ 7) / 8;
454 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
457 std::vector
<uint8_t> raw_sig(degree
* 2);
460 SECURITY_STATUS ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
461 ex_data
->key
->hNCryptKey
, nullptr, const_cast<PBYTE
>(digest
), digest_len
,
462 &raw_sig
[0], raw_sig
.size(), &signature_len
, 0);
463 if (FAILED(ncrypt_status
) || signature_len
!= raw_sig
.size()) {
464 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
468 // Convert the RAW ECDSA signature to a DER-encoded ECDSA-Sig-Value.
469 crypto::ScopedECDSA_SIG
sig(ECDSA_SIG_new());
471 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
474 sig
->r
= BN_bin2bn(&raw_sig
[0], degree
, nullptr);
475 sig
->s
= BN_bin2bn(&raw_sig
[degree
], degree
, nullptr);
476 if (!sig
->r
|| !sig
->s
) {
477 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
481 // Ensure the DER-encoded signature fits in the bounds.
482 int len
= i2d_ECDSA_SIG(sig
.get(), nullptr);
483 if (len
< 0 || static_cast<size_t>(len
) > ECDSA_size(ec_key
)) {
484 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
488 len
= i2d_ECDSA_SIG(sig
.get(), &out_sig
);
490 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
497 int EcdsaMethodVerify(const uint8_t* digest
,
503 OPENSSL_PUT_ERROR(ECDSA
, ECDSA_do_verify
, ECDSA_R_NOT_IMPLEMENTED
);
507 const ECDSA_METHOD win_ecdsa_method
= {
516 EcdsaMethodGroupOrderSize
,
522 // Determines the key type and length of |key|. The type is returned as an
523 // OpenSSL EVP_PKEY type. The key length for RSA key is the size of the RSA
524 // modulus in bits. For an ECDSA key, it is the number of bits to represent the
525 // group order. It returns true on success and false on failure.
526 bool GetKeyInfo(PCERT_KEY_CONTEXT key
, int* out_type
, DWORD
* out_length
) {
527 if (key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
529 SECURITY_STATUS status
= g_cng_functions
.Get().ncrypt_get_property()(
530 key
->hNCryptKey
, NCRYPT_ALGORITHM_GROUP_PROPERTY
, nullptr, 0, &prop_len
,
532 if (FAILED(status
) || prop_len
== 0 || prop_len
% 2 != 0) {
533 LOG(ERROR
) << "Could not query CNG key type: " << status
;
537 std::vector
<BYTE
> prop_buf(prop_len
);
538 status
= g_cng_functions
.Get().ncrypt_get_property()(
539 key
->hNCryptKey
, NCRYPT_ALGORITHM_GROUP_PROPERTY
, &prop_buf
[0],
540 prop_buf
.size(), &prop_len
, 0);
541 if (FAILED(status
) || prop_len
== 0 || prop_len
% 2 != 0) {
542 LOG(ERROR
) << "Could not query CNG key type: " << status
;
547 const wchar_t* alg
= reinterpret_cast<const wchar_t*>(&prop_buf
[0]);
548 if (wcsncmp(NCRYPT_RSA_ALGORITHM_GROUP
, alg
, prop_len
/ 2) == 0) {
550 } else if (wcsncmp(NCRYPT_ECDSA_ALGORITHM_GROUP
, alg
, prop_len
/ 2) == 0 ||
551 wcsncmp(NCRYPT_ECDH_ALGORITHM_GROUP
, alg
, prop_len
/ 2) == 0) {
552 // Importing an ECDSA key via PKCS #12 seems to label it as ECDH rather
553 // than ECDSA, so also allow ECDH.
556 LOG(ERROR
) << "Unknown CNG key type: "
557 << std::wstring(alg
, wcsnlen(alg
, prop_len
/ 2));
563 status
= g_cng_functions
.Get().ncrypt_get_property()(
564 key
->hNCryptKey
, NCRYPT_LENGTH_PROPERTY
,
565 reinterpret_cast<BYTE
*>(&length
), sizeof(DWORD
), &prop_len
, 0);
566 if (FAILED(status
)) {
567 LOG(ERROR
) << "Could not get CNG key length " << status
;
570 DCHECK_EQ(sizeof(DWORD
), prop_len
);
573 *out_length
= length
;
577 crypto::ScopedHCRYPTKEY hcryptkey
;
578 if (!CryptGetUserKey(key
->hCryptProv
, key
->dwKeySpec
, hcryptkey
.receive())) {
579 PLOG(ERROR
) << "Could not get CAPI key handle";
584 DWORD prop_len
= sizeof(alg_id
);
585 if (!CryptGetKeyParam(hcryptkey
.get(), KP_ALGID
,
586 reinterpret_cast<BYTE
*>(&alg_id
), &prop_len
, 0)) {
587 PLOG(ERROR
) << "Could not query CAPI key type";
591 if (alg_id
!= CALG_RSA_SIGN
&& alg_id
!= CALG_RSA_KEYX
) {
592 LOG(ERROR
) << "Unknown CAPI key type: " << alg_id
;
597 prop_len
= sizeof(DWORD
);
598 if (!CryptGetKeyParam(hcryptkey
.get(), KP_KEYLEN
,
599 reinterpret_cast<BYTE
*>(&length
), &prop_len
, 0)) {
600 PLOG(ERROR
) << "Could not get CAPI key length";
603 DCHECK_EQ(sizeof(DWORD
), prop_len
);
605 *out_type
= EVP_PKEY_RSA
;
606 *out_length
= length
;
610 crypto::ScopedEVP_PKEY
CreateRSAWrapper(ScopedCERT_KEY_CONTEXT key
,
612 crypto::ScopedRSA
rsa(RSA_new_method(global_boringssl_engine
.Get().engine()));
616 RSA_set_ex_data(rsa
.get(), global_boringssl_engine
.Get().rsa_ex_index(),
617 new KeyExData(key
.Pass(), key_length
));
619 crypto::ScopedEVP_PKEY
pkey(EVP_PKEY_new());
620 if (!pkey
|| !EVP_PKEY_set1_RSA(pkey
.get(), rsa
.get()))
625 crypto::ScopedEVP_PKEY
CreateECDSAWrapper(ScopedCERT_KEY_CONTEXT key
,
627 crypto::ScopedEC_KEY
ec_key(
628 EC_KEY_new_method(global_boringssl_engine
.Get().engine()));
632 EC_KEY_set_ex_data(ec_key
.get(),
633 global_boringssl_engine
.Get().ec_key_ex_index(),
634 new KeyExData(key
.Pass(), key_length
));
636 crypto::ScopedEVP_PKEY
pkey(EVP_PKEY_new());
637 if (!pkey
|| !EVP_PKEY_set1_EC_KEY(pkey
.get(), ec_key
.get()))
645 crypto::ScopedEVP_PKEY
FetchClientCertPrivateKey(
646 const X509Certificate
* certificate
) {
647 PCCERT_CONTEXT cert_context
= certificate
->os_cert_handle();
649 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
651 BOOL must_free
= FALSE
;
653 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
654 flags
|= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
;
656 if (!CryptAcquireCertificatePrivateKey(cert_context
, flags
, nullptr,
657 &crypt_prov
, &key_spec
, &must_free
)) {
658 PLOG(WARNING
) << "Could not acquire private key";
662 // Should never get a cached handle back - ownership must always be
664 CHECK_EQ(must_free
, TRUE
);
665 ScopedCERT_KEY_CONTEXT
key(new CERT_KEY_CONTEXT
);
666 key
->dwKeySpec
= key_spec
;
667 key
->hCryptProv
= crypt_prov
;
671 if (!GetKeyInfo(key
.get(), &key_type
, &key_length
))
676 return CreateRSAWrapper(key
.Pass(), key_length
);
678 return CreateECDSAWrapper(key
.Pass(), key_length
);