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/win/windows_version.h"
32 #include "crypto/scoped_capi_types.h"
33 #include "crypto/wincrypt_shim.h"
34 #include "net/base/net_errors.h"
35 #include "net/cert/x509_certificate.h"
36 #include "net/ssl/openssl_ssl_util.h"
42 using NCryptFreeObjectFunc
= SECURITY_STATUS(WINAPI
*)(NCRYPT_HANDLE
);
43 using NCryptGetPropertyFunc
=
44 SECURITY_STATUS(WINAPI
*)(NCRYPT_HANDLE
, // hObject
45 LPCWSTR
, // pszProperty
50 using NCryptSignHashFunc
=
51 SECURITY_STATUS(WINAPI
*)(NCRYPT_KEY_HANDLE
, // hKey
52 VOID
*, // pPaddingInfo
63 : ncrypt_free_object_(nullptr),
64 ncrypt_get_property_(nullptr),
65 ncrypt_sign_hash_(nullptr) {
66 HMODULE ncrypt
= GetModuleHandle(L
"ncrypt.dll");
67 if (ncrypt
!= nullptr) {
68 ncrypt_free_object_
= reinterpret_cast<NCryptFreeObjectFunc
>(
69 GetProcAddress(ncrypt
, "NCryptFreeObject"));
70 ncrypt_get_property_
= reinterpret_cast<NCryptGetPropertyFunc
>(
71 GetProcAddress(ncrypt
, "NCryptGetProperty"));
72 ncrypt_sign_hash_
= reinterpret_cast<NCryptSignHashFunc
>(
73 GetProcAddress(ncrypt
, "NCryptSignHash"));
77 NCryptFreeObjectFunc
ncrypt_free_object() const {
78 return ncrypt_free_object_
;
81 NCryptGetPropertyFunc
ncrypt_get_property() const {
82 return ncrypt_get_property_
;
85 NCryptSignHashFunc
ncrypt_sign_hash() const { return ncrypt_sign_hash_
; }
88 NCryptFreeObjectFunc ncrypt_free_object_
;
89 NCryptGetPropertyFunc ncrypt_get_property_
;
90 NCryptSignHashFunc ncrypt_sign_hash_
;
93 base::LazyInstance
<CNGFunctions
>::Leaky g_cng_functions
=
94 LAZY_INSTANCE_INITIALIZER
;
96 struct CERT_KEY_CONTEXTDeleter
{
97 void operator()(PCERT_KEY_CONTEXT key
) {
98 if (key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
99 g_cng_functions
.Get().ncrypt_free_object()(key
->hNCryptKey
);
101 CryptReleaseContext(key
->hCryptProv
, 0);
107 using ScopedCERT_KEY_CONTEXT
=
108 scoped_ptr
<CERT_KEY_CONTEXT
, CERT_KEY_CONTEXTDeleter
>;
110 // KeyExData contains the data that is contained in the EX_DATA of the
111 // RSA and ECDSA objects that are created to wrap Windows system keys.
113 KeyExData(ScopedCERT_KEY_CONTEXT key
, DWORD key_length
)
114 : key(key
.Pass()), key_length(key_length
) {}
116 ScopedCERT_KEY_CONTEXT key
;
120 // ExDataDup is called when one of the RSA or EC_KEY objects is
121 // duplicated. This is not supported and should never happen.
122 int ExDataDup(CRYPTO_EX_DATA
* to
,
123 const CRYPTO_EX_DATA
* from
,
128 CHECK_EQ((void*)nullptr, *from_d
);
132 // ExDataFree is called when one of the RSA or EC_KEY objects is freed.
133 void ExDataFree(void* parent
,
135 CRYPTO_EX_DATA
* ex_data
,
139 KeyExData
* data
= reinterpret_cast<KeyExData
*>(ptr
);
143 extern const RSA_METHOD win_rsa_method
;
144 extern const ECDSA_METHOD win_ecdsa_method
;
146 // BoringSSLEngine is a BoringSSL ENGINE that implements RSA and ECDSA
147 // by forwarding the requested operations to CAPI or CNG.
148 class BoringSSLEngine
{
151 : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
153 nullptr /* new_func */,
156 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
158 nullptr /* new_func */,
161 engine_(ENGINE_new()) {
162 ENGINE_set_RSA_method(engine_
, &win_rsa_method
, sizeof(win_rsa_method
));
163 ENGINE_set_ECDSA_method(engine_
, &win_ecdsa_method
,
164 sizeof(win_ecdsa_method
));
167 int rsa_ex_index() const { return rsa_index_
; }
168 int ec_key_ex_index() const { return ec_key_index_
; }
170 const ENGINE
* engine() const { return engine_
; }
173 const int rsa_index_
;
174 const int ec_key_index_
;
175 ENGINE
* const engine_
;
178 base::LazyInstance
<BoringSSLEngine
>::Leaky global_boringssl_engine
=
179 LAZY_INSTANCE_INITIALIZER
;
181 // Custom RSA_METHOD that uses the platform APIs for signing.
183 const KeyExData
* RsaGetExData(const RSA
* rsa
) {
184 return reinterpret_cast<const KeyExData
*>(
185 RSA_get_ex_data(rsa
, global_boringssl_engine
.Get().rsa_ex_index()));
188 size_t RsaMethodSize(const RSA
* rsa
) {
189 const KeyExData
* ex_data
= RsaGetExData(rsa
);
190 return (ex_data
->key_length
+ 7) / 8;
193 int RsaMethodSign(int hash_nid
,
199 // TODO(davidben): Switch BoringSSL's sign hook to using size_t rather than
201 const KeyExData
* ex_data
= RsaGetExData(rsa
);
204 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, ERR_R_INTERNAL_ERROR
);
208 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
209 BCRYPT_PKCS1_PADDING_INFO rsa_padding_info
;
212 rsa_padding_info
.pszAlgId
= nullptr;
215 rsa_padding_info
.pszAlgId
= BCRYPT_SHA1_ALGORITHM
;
218 rsa_padding_info
.pszAlgId
= BCRYPT_SHA256_ALGORITHM
;
221 rsa_padding_info
.pszAlgId
= BCRYPT_SHA384_ALGORITHM
;
224 rsa_padding_info
.pszAlgId
= BCRYPT_SHA512_ALGORITHM
;
227 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
232 SECURITY_STATUS ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
233 ex_data
->key
->hNCryptKey
, &rsa_padding_info
, const_cast<PBYTE
>(in
),
234 in_len
, out
, RSA_size(rsa
), &signature_len
, BCRYPT_PAD_PKCS1
);
235 if (FAILED(ncrypt_status
) || signature_len
== 0) {
236 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
239 *out_len
= signature_len
;
246 hash_alg
= CALG_SSL3_SHAMD5
;
249 hash_alg
= CALG_SHA1
;
252 hash_alg
= CALG_SHA_256
;
255 hash_alg
= CALG_SHA_384
;
258 hash_alg
= CALG_SHA_512
;
261 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
266 if (!CryptCreateHash(ex_data
->key
->hCryptProv
, hash_alg
, 0, 0, &hash
)) {
267 PLOG(ERROR
) << "CreateCreateHash failed";
268 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
272 DWORD arg_len
= sizeof(hash_len
);
273 if (!CryptGetHashParam(hash
, HP_HASHSIZE
, reinterpret_cast<BYTE
*>(&hash_len
),
275 PLOG(ERROR
) << "CryptGetHashParam HP_HASHSIZE failed";
276 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
279 if (hash_len
!= in_len
) {
280 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
283 if (!CryptSetHashParam(hash
, HP_HASHVAL
, const_cast<BYTE
*>(in
), 0)) {
284 PLOG(ERROR
) << "CryptSetHashParam HP_HASHVAL failed";
285 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
288 DWORD signature_len
= RSA_size(rsa
);
289 if (!CryptSignHash(hash
, ex_data
->key
->dwKeySpec
, nullptr, 0, out
,
291 PLOG(ERROR
) << "CryptSignHash failed";
292 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
296 /* CryptoAPI signs in little-endian, so reverse it. */
297 std::reverse(out
, out
+ signature_len
);
298 *out_len
= signature_len
;
302 int RsaMethodEncrypt(RSA
* rsa
,
310 OPENSSL_PUT_ERROR(RSA
, encrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
314 int RsaMethodSignRaw(RSA
* rsa
,
322 OPENSSL_PUT_ERROR(RSA
, encrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
326 int RsaMethodDecrypt(RSA
* rsa
,
334 OPENSSL_PUT_ERROR(RSA
, decrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
338 int RsaMethodVerifyRaw(RSA
* rsa
,
346 OPENSSL_PUT_ERROR(RSA
, verify_raw
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
350 int RsaMethodSupportsDigest(const RSA
* rsa
, const EVP_MD
* md
) {
351 const KeyExData
* ex_data
= RsaGetExData(rsa
);
357 int hash_nid
= EVP_MD_type(md
);
358 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
359 // Only hashes which appear in RsaSignPKCS1 are supported.
360 if (hash_nid
!= NID_sha1
&& hash_nid
!= NID_sha256
&&
361 hash_nid
!= NID_sha384
&& hash_nid
!= NID_sha512
) {
365 // If the key is a 1024-bit RSA, assume conservatively that it may only be
366 // able to sign SHA-1 hashes. This is the case for older Estonian ID cards
367 // that have 1024-bit RSA keys.
369 // CNG does provide NCryptIsAlgSupported and NCryptEnumAlgorithms functions,
370 // however they seem to both return NTE_NOT_SUPPORTED when querying the
371 // NCRYPT_PROV_HANDLE at the key's NCRYPT_PROVIDER_HANDLE_PROPERTY.
372 if (ex_data
->key_length
<= 1024 && hash_nid
!= NID_sha1
)
377 // If the key is in CAPI, assume conservatively that the CAPI service
378 // provider may only be able to sign SHA-1 hashes.
379 return hash_nid
== NID_sha1
;
383 const RSA_METHOD win_rsa_method
= {
399 nullptr, // private_transform
401 nullptr, // bn_mod_exp
404 RsaMethodSupportsDigest
,
407 // Custom ECDSA_METHOD that uses the platform APIs.
408 // Note that for now, only signing through ECDSA_sign() is really supported.
409 // all other method pointers are either stubs returning errors, or no-ops.
411 const KeyExData
* EcKeyGetExData(const EC_KEY
* ec_key
) {
412 return reinterpret_cast<const KeyExData
*>(EC_KEY_get_ex_data(
413 ec_key
, global_boringssl_engine
.Get().ec_key_ex_index()));
416 size_t EcdsaMethodGroupOrderSize(const EC_KEY
* ec_key
) {
417 const KeyExData
* ex_data
= EcKeyGetExData(ec_key
);
418 // Windows doesn't distinguish the sizes of the curve's degree (which
419 // determines the size of a point on the curve) and the base point's order
420 // (which determines the size of a scalar). For P-256, P-384, and P-521, these
421 // two sizes are the same.
424 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375520(v=vs.85).aspx
425 // which uses the same length for both.
426 return (ex_data
->key_length
+ 7) / 8;
429 int EcdsaMethodSign(const uint8_t* digest
,
432 unsigned int* out_sig_len
,
434 const KeyExData
* ex_data
= EcKeyGetExData(ec_key
);
435 // Only CNG supports ECDSA.
436 if (!ex_data
|| ex_data
->key
->dwKeySpec
!= CERT_NCRYPT_KEY_SPEC
) {
438 OPENSSL_PUT_ERROR(RSA
, sign_raw
, ERR_R_INTERNAL_ERROR
);
442 size_t degree
= (ex_data
->key_length
+ 7) / 8;
445 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
448 std::vector
<uint8_t> raw_sig(degree
* 2);
451 SECURITY_STATUS ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
452 ex_data
->key
->hNCryptKey
, nullptr, const_cast<PBYTE
>(digest
), digest_len
,
453 &raw_sig
[0], raw_sig
.size(), &signature_len
, 0);
454 if (FAILED(ncrypt_status
) || signature_len
!= raw_sig
.size()) {
455 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
459 // Convert the RAW ECDSA signature to a DER-encoded ECDSA-Sig-Value.
460 crypto::ScopedECDSA_SIG
sig(ECDSA_SIG_new());
462 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
465 sig
->r
= BN_bin2bn(&raw_sig
[0], degree
, nullptr);
466 sig
->s
= BN_bin2bn(&raw_sig
[degree
], degree
, nullptr);
467 if (!sig
->r
|| !sig
->s
) {
468 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
472 // Ensure the DER-encoded signature fits in the bounds.
473 int len
= i2d_ECDSA_SIG(sig
.get(), nullptr);
474 if (len
< 0 || static_cast<size_t>(len
) > ECDSA_size(ec_key
)) {
475 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
479 len
= i2d_ECDSA_SIG(sig
.get(), &out_sig
);
481 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
488 int EcdsaMethodVerify(const uint8_t* digest
,
494 OPENSSL_PUT_ERROR(ECDSA
, ECDSA_do_verify
, ECDSA_R_NOT_IMPLEMENTED
);
498 const ECDSA_METHOD win_ecdsa_method
= {
507 EcdsaMethodGroupOrderSize
,
513 // Determines the key type and length of |key|. The type is returned as an
514 // OpenSSL EVP_PKEY type. The key length for RSA key is the size of the RSA
515 // modulus in bits. For an ECDSA key, it is the number of bits to represent the
516 // group order. It returns true on success and false on failure.
517 bool GetKeyInfo(PCERT_KEY_CONTEXT key
, int* out_type
, DWORD
* out_length
) {
518 if (key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
520 SECURITY_STATUS status
= g_cng_functions
.Get().ncrypt_get_property()(
521 key
->hNCryptKey
, NCRYPT_ALGORITHM_GROUP_PROPERTY
, nullptr, 0, &prop_len
,
523 if (FAILED(status
) || prop_len
== 0 || prop_len
% 2 != 0) {
524 LOG(ERROR
) << "Could not query CNG key type: " << status
;
528 std::vector
<BYTE
> prop_buf(prop_len
);
529 status
= g_cng_functions
.Get().ncrypt_get_property()(
530 key
->hNCryptKey
, NCRYPT_ALGORITHM_GROUP_PROPERTY
, &prop_buf
[0],
531 prop_buf
.size(), &prop_len
, 0);
532 if (FAILED(status
) || prop_len
== 0 || prop_len
% 2 != 0) {
533 LOG(ERROR
) << "Could not query CNG key type: " << status
;
538 const wchar_t* alg
= reinterpret_cast<const wchar_t*>(&prop_buf
[0]);
539 if (wcsncmp(NCRYPT_RSA_ALGORITHM_GROUP
, alg
, prop_len
/ 2) == 0) {
541 } else if (wcsncmp(NCRYPT_ECDSA_ALGORITHM_GROUP
, alg
, prop_len
/ 2) == 0 ||
542 wcsncmp(NCRYPT_ECDH_ALGORITHM_GROUP
, alg
, prop_len
/ 2) == 0) {
543 // Importing an ECDSA key via PKCS #12 seems to label it as ECDH rather
544 // than ECDSA, so also allow ECDH.
547 LOG(ERROR
) << "Unknown CNG key type: "
548 << std::wstring(alg
, wcsnlen(alg
, prop_len
/ 2));
554 status
= g_cng_functions
.Get().ncrypt_get_property()(
555 key
->hNCryptKey
, NCRYPT_LENGTH_PROPERTY
,
556 reinterpret_cast<BYTE
*>(&length
), sizeof(DWORD
), &prop_len
, 0);
557 if (FAILED(status
)) {
558 LOG(ERROR
) << "Could not get CNG key length " << status
;
561 DCHECK_EQ(sizeof(DWORD
), prop_len
);
564 *out_length
= length
;
568 crypto::ScopedHCRYPTKEY hcryptkey
;
569 if (!CryptGetUserKey(key
->hCryptProv
, key
->dwKeySpec
, hcryptkey
.receive())) {
570 PLOG(ERROR
) << "Could not get CAPI key handle";
575 DWORD prop_len
= sizeof(alg_id
);
576 if (!CryptGetKeyParam(hcryptkey
.get(), KP_ALGID
,
577 reinterpret_cast<BYTE
*>(&alg_id
), &prop_len
, 0)) {
578 PLOG(ERROR
) << "Could not query CAPI key type";
582 if (alg_id
!= CALG_RSA_SIGN
&& alg_id
!= CALG_RSA_KEYX
) {
583 LOG(ERROR
) << "Unknown CAPI key type: " << alg_id
;
588 prop_len
= sizeof(DWORD
);
589 if (!CryptGetKeyParam(hcryptkey
.get(), KP_KEYLEN
,
590 reinterpret_cast<BYTE
*>(&length
), &prop_len
, 0)) {
591 PLOG(ERROR
) << "Could not get CAPI key length";
594 DCHECK_EQ(sizeof(DWORD
), prop_len
);
596 *out_type
= EVP_PKEY_RSA
;
597 *out_length
= length
;
601 crypto::ScopedEVP_PKEY
CreateRSAWrapper(ScopedCERT_KEY_CONTEXT key
,
603 crypto::ScopedRSA
rsa(RSA_new_method(global_boringssl_engine
.Get().engine()));
607 RSA_set_ex_data(rsa
.get(), global_boringssl_engine
.Get().rsa_ex_index(),
608 new KeyExData(key
.Pass(), key_length
));
610 crypto::ScopedEVP_PKEY
pkey(EVP_PKEY_new());
611 if (!pkey
|| !EVP_PKEY_set1_RSA(pkey
.get(), rsa
.get()))
616 crypto::ScopedEVP_PKEY
CreateECDSAWrapper(ScopedCERT_KEY_CONTEXT key
,
618 crypto::ScopedEC_KEY
ec_key(
619 EC_KEY_new_method(global_boringssl_engine
.Get().engine()));
623 EC_KEY_set_ex_data(ec_key
.get(),
624 global_boringssl_engine
.Get().ec_key_ex_index(),
625 new KeyExData(key
.Pass(), key_length
));
627 crypto::ScopedEVP_PKEY
pkey(EVP_PKEY_new());
628 if (!pkey
|| !EVP_PKEY_set1_EC_KEY(pkey
.get(), ec_key
.get()))
636 crypto::ScopedEVP_PKEY
FetchClientCertPrivateKey(
637 const X509Certificate
* certificate
) {
638 PCCERT_CONTEXT cert_context
= certificate
->os_cert_handle();
640 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
642 BOOL must_free
= FALSE
;
644 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
645 flags
|= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
;
647 if (!CryptAcquireCertificatePrivateKey(cert_context
, flags
, nullptr,
648 &crypt_prov
, &key_spec
, &must_free
)) {
649 PLOG(WARNING
) << "Could not acquire private key";
653 // Should never get a cached handle back - ownership must always be
655 CHECK_EQ(must_free
, TRUE
);
656 ScopedCERT_KEY_CONTEXT
key(new CERT_KEY_CONTEXT
);
657 key
->dwKeySpec
= key_spec
;
658 key
->hCryptProv
= crypt_prov
;
662 if (!GetKeyInfo(key
.get(), &key_type
, &key_length
))
667 return CreateRSAWrapper(key
.Pass(), key_length
);
669 return CreateECDSAWrapper(key
.Pass(), key_length
);