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>
25 #include <openssl/x509.h>
27 #include "base/debug/debugger.h"
28 #include "base/debug/stack_trace.h"
29 #include "base/lazy_instance.h"
30 #include "base/logging.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/profiler/scoped_tracker.h"
33 #include "base/win/windows_version.h"
34 #include "crypto/openssl_util.h"
35 #include "crypto/scoped_capi_types.h"
36 #include "crypto/wincrypt_shim.h"
37 #include "net/base/net_errors.h"
38 #include "net/cert/x509_certificate.h"
39 #include "net/ssl/openssl_ssl_util.h"
40 #include "net/ssl/scoped_openssl_types.h"
46 using NCryptFreeObjectFunc
= SECURITY_STATUS(WINAPI
*)(NCRYPT_HANDLE
);
47 using NCryptSignHashFunc
=
48 SECURITY_STATUS(WINAPI
*)(NCRYPT_KEY_HANDLE
, // hKey
49 VOID
*, // pPaddingInfo
60 : ncrypt_free_object_(nullptr),
61 ncrypt_sign_hash_(nullptr) {
62 HMODULE ncrypt
= GetModuleHandle(L
"ncrypt.dll");
63 if (ncrypt
!= nullptr) {
64 ncrypt_free_object_
= reinterpret_cast<NCryptFreeObjectFunc
>(
65 GetProcAddress(ncrypt
, "NCryptFreeObject"));
66 ncrypt_sign_hash_
= reinterpret_cast<NCryptSignHashFunc
>(
67 GetProcAddress(ncrypt
, "NCryptSignHash"));
71 NCryptFreeObjectFunc
ncrypt_free_object() const {
72 return ncrypt_free_object_
;
75 NCryptSignHashFunc
ncrypt_sign_hash() const { return ncrypt_sign_hash_
; }
78 NCryptFreeObjectFunc ncrypt_free_object_
;
79 NCryptSignHashFunc ncrypt_sign_hash_
;
82 base::LazyInstance
<CNGFunctions
>::Leaky g_cng_functions
=
83 LAZY_INSTANCE_INITIALIZER
;
85 struct CERT_KEY_CONTEXTDeleter
{
86 void operator()(PCERT_KEY_CONTEXT key
) {
87 if (key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
88 g_cng_functions
.Get().ncrypt_free_object()(key
->hNCryptKey
);
90 CryptReleaseContext(key
->hCryptProv
, 0);
96 using ScopedCERT_KEY_CONTEXT
=
97 scoped_ptr
<CERT_KEY_CONTEXT
, CERT_KEY_CONTEXTDeleter
>;
99 // KeyExData contains the data that is contained in the EX_DATA of the
100 // RSA and ECDSA objects that are created to wrap Windows system keys.
102 KeyExData(ScopedCERT_KEY_CONTEXT key
, size_t key_length
)
103 : key(key
.Pass()), key_length(key_length
) {}
105 ScopedCERT_KEY_CONTEXT key
;
109 // ExDataDup is called when one of the RSA or EC_KEY objects is
110 // duplicated. This is not supported and should never happen.
111 int ExDataDup(CRYPTO_EX_DATA
* to
,
112 const CRYPTO_EX_DATA
* from
,
117 CHECK_EQ((void*)nullptr, *from_d
);
121 // ExDataFree is called when one of the RSA or EC_KEY objects is freed.
122 void ExDataFree(void* parent
,
124 CRYPTO_EX_DATA
* ex_data
,
128 KeyExData
* data
= reinterpret_cast<KeyExData
*>(ptr
);
132 extern const RSA_METHOD win_rsa_method
;
133 extern const ECDSA_METHOD win_ecdsa_method
;
135 // BoringSSLEngine is a BoringSSL ENGINE that implements RSA and ECDSA
136 // by forwarding the requested operations to CAPI or CNG.
137 class BoringSSLEngine
{
140 : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
142 nullptr /* new_func */,
145 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
147 nullptr /* new_func */,
150 engine_(ENGINE_new()) {
151 ENGINE_set_RSA_method(engine_
, &win_rsa_method
, sizeof(win_rsa_method
));
152 ENGINE_set_ECDSA_method(engine_
, &win_ecdsa_method
,
153 sizeof(win_ecdsa_method
));
156 int rsa_ex_index() const { return rsa_index_
; }
157 int ec_key_ex_index() const { return ec_key_index_
; }
159 const ENGINE
* engine() const { return engine_
; }
162 const int rsa_index_
;
163 const int ec_key_index_
;
164 ENGINE
* const engine_
;
167 base::LazyInstance
<BoringSSLEngine
>::Leaky global_boringssl_engine
=
168 LAZY_INSTANCE_INITIALIZER
;
170 // Signs |in| with |key|, writing the output to |out| and the size to |out_len|.
171 // Although the buffer is preallocated, this calls NCryptSignHash twice. Some
172 // smartcards are buggy and assume the two-call pattern. See
173 // https://crbug.com/470204. Returns true on success and false on error.
174 bool DoNCryptSignHash(NCRYPT_KEY_HANDLE key
,
182 // Determine the output length.
184 SECURITY_STATUS ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
185 key
, padding
, const_cast<BYTE
*>(in
), in_len
, nullptr, 0, &signature_len
,
187 if (FAILED(ncrypt_status
)) {
188 LOG(ERROR
) << "NCryptSignHash failed: " << ncrypt_status
;
191 // Check |max_out| externally rather than trust the smartcard.
192 if (signature_len
== 0 || signature_len
> max_out
) {
193 LOG(ERROR
) << "Bad signature length.";
196 // It is important that |signature_len| already be initialized with the
197 // correct size. Some smartcards are buggy and do not write to it on the
199 ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
200 key
, padding
, const_cast<PBYTE
>(in
), in_len
, out
, signature_len
,
201 &signature_len
, flags
);
202 if (FAILED(ncrypt_status
)) {
203 LOG(ERROR
) << "NCryptSignHash failed: " << ncrypt_status
;
206 if (signature_len
== 0) {
207 LOG(ERROR
) << "Bad signature length.";
210 *out_len
= signature_len
;
214 // Custom RSA_METHOD that uses the platform APIs for signing.
216 const KeyExData
* RsaGetExData(const RSA
* rsa
) {
217 return reinterpret_cast<const KeyExData
*>(
218 RSA_get_ex_data(rsa
, global_boringssl_engine
.Get().rsa_ex_index()));
221 size_t RsaMethodSize(const RSA
* rsa
) {
222 const KeyExData
* ex_data
= RsaGetExData(rsa
);
223 return (ex_data
->key_length
+ 7) / 8;
226 int RsaMethodSign(int hash_nid
,
232 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
233 tracked_objects::ScopedTracker
tracking_profile(
234 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 RsaMethodSign"));
236 // TODO(davidben): Switch BoringSSL's sign hook to using size_t rather than
238 const KeyExData
* ex_data
= RsaGetExData(rsa
);
241 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, ERR_R_INTERNAL_ERROR
);
245 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
246 BCRYPT_PKCS1_PADDING_INFO rsa_padding_info
;
249 rsa_padding_info
.pszAlgId
= nullptr;
252 rsa_padding_info
.pszAlgId
= BCRYPT_SHA1_ALGORITHM
;
255 rsa_padding_info
.pszAlgId
= BCRYPT_SHA256_ALGORITHM
;
258 rsa_padding_info
.pszAlgId
= BCRYPT_SHA384_ALGORITHM
;
261 rsa_padding_info
.pszAlgId
= BCRYPT_SHA512_ALGORITHM
;
264 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
269 if (!DoNCryptSignHash(ex_data
->key
->hNCryptKey
, &rsa_padding_info
, in
,
270 in_len
, out
, RSA_size(rsa
), &signature_len
,
272 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
275 *out_len
= signature_len
;
282 hash_alg
= CALG_SSL3_SHAMD5
;
285 hash_alg
= CALG_SHA1
;
288 hash_alg
= CALG_SHA_256
;
291 hash_alg
= CALG_SHA_384
;
294 hash_alg
= CALG_SHA_512
;
297 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
302 if (!CryptCreateHash(ex_data
->key
->hCryptProv
, hash_alg
, 0, 0, &hash
)) {
303 PLOG(ERROR
) << "CreateCreateHash failed";
304 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
308 DWORD arg_len
= sizeof(hash_len
);
309 if (!CryptGetHashParam(hash
, HP_HASHSIZE
, reinterpret_cast<BYTE
*>(&hash_len
),
311 PLOG(ERROR
) << "CryptGetHashParam HP_HASHSIZE failed";
312 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
315 if (hash_len
!= in_len
) {
316 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
319 if (!CryptSetHashParam(hash
, HP_HASHVAL
, const_cast<BYTE
*>(in
), 0)) {
320 PLOG(ERROR
) << "CryptSetHashParam HP_HASHVAL failed";
321 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
324 DWORD signature_len
= RSA_size(rsa
);
325 if (!CryptSignHash(hash
, ex_data
->key
->dwKeySpec
, nullptr, 0, out
,
327 PLOG(ERROR
) << "CryptSignHash failed";
328 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
332 /* CryptoAPI signs in little-endian, so reverse it. */
333 std::reverse(out
, out
+ signature_len
);
334 *out_len
= signature_len
;
338 int RsaMethodEncrypt(RSA
* rsa
,
346 OPENSSL_PUT_ERROR(RSA
, encrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
350 int RsaMethodSignRaw(RSA
* rsa
,
358 OPENSSL_PUT_ERROR(RSA
, encrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
362 int RsaMethodDecrypt(RSA
* rsa
,
370 OPENSSL_PUT_ERROR(RSA
, decrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
374 int RsaMethodVerifyRaw(RSA
* rsa
,
382 OPENSSL_PUT_ERROR(RSA
, verify_raw
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
386 int RsaMethodSupportsDigest(const RSA
* rsa
, const EVP_MD
* md
) {
387 const KeyExData
* ex_data
= RsaGetExData(rsa
);
393 int hash_nid
= EVP_MD_type(md
);
394 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
395 // Only hashes which appear in RsaSignPKCS1 are supported.
396 if (hash_nid
!= NID_sha1
&& hash_nid
!= NID_sha256
&&
397 hash_nid
!= NID_sha384
&& hash_nid
!= NID_sha512
) {
401 // If the key is a 1024-bit RSA, assume conservatively that it may only be
402 // able to sign SHA-1 hashes. This is the case for older Estonian ID cards
403 // that have 1024-bit RSA keys.
405 // CNG does provide NCryptIsAlgSupported and NCryptEnumAlgorithms functions,
406 // however they seem to both return NTE_NOT_SUPPORTED when querying the
407 // NCRYPT_PROV_HANDLE at the key's NCRYPT_PROVIDER_HANDLE_PROPERTY.
408 if (ex_data
->key_length
<= 1024 && hash_nid
!= NID_sha1
)
413 // If the key is in CAPI, assume conservatively that the CAPI service
414 // provider may only be able to sign SHA-1 hashes.
415 return hash_nid
== NID_sha1
;
419 const RSA_METHOD win_rsa_method
= {
435 nullptr, // private_transform
437 nullptr, // bn_mod_exp
440 RsaMethodSupportsDigest
,
443 // Custom ECDSA_METHOD that uses the platform APIs.
444 // Note that for now, only signing through ECDSA_sign() is really supported.
445 // all other method pointers are either stubs returning errors, or no-ops.
447 const KeyExData
* EcKeyGetExData(const EC_KEY
* ec_key
) {
448 return reinterpret_cast<const KeyExData
*>(EC_KEY_get_ex_data(
449 ec_key
, global_boringssl_engine
.Get().ec_key_ex_index()));
452 size_t EcdsaMethodGroupOrderSize(const EC_KEY
* ec_key
) {
453 const KeyExData
* ex_data
= EcKeyGetExData(ec_key
);
454 // key_length is the size of the group order for EC keys.
455 return (ex_data
->key_length
+ 7) / 8;
458 int EcdsaMethodSign(const uint8_t* digest
,
461 unsigned int* out_sig_len
,
463 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
464 tracked_objects::ScopedTracker
tracking_profile(
465 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 EcdsaMethodSign"));
467 const KeyExData
* ex_data
= EcKeyGetExData(ec_key
);
468 // Only CNG supports ECDSA.
469 if (!ex_data
|| ex_data
->key
->dwKeySpec
!= CERT_NCRYPT_KEY_SPEC
) {
471 OPENSSL_PUT_ERROR(RSA
, sign_raw
, ERR_R_INTERNAL_ERROR
);
475 // An ECDSA signature is two integers, modulo the order of the group.
476 size_t order_len
= (ex_data
->key_length
+ 7) / 8;
477 if (order_len
== 0) {
479 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
482 std::vector
<uint8_t> raw_sig(order_len
* 2);
485 if (!DoNCryptSignHash(ex_data
->key
->hNCryptKey
, nullptr, digest
, digest_len
,
486 &raw_sig
[0], raw_sig
.size(), &signature_len
, 0)) {
487 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
490 if (signature_len
!= raw_sig
.size()) {
491 LOG(ERROR
) << "Bad signature length";
492 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
496 // Convert the RAW ECDSA signature to a DER-encoded ECDSA-Sig-Value.
497 crypto::ScopedECDSA_SIG
sig(ECDSA_SIG_new());
499 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
502 sig
->r
= BN_bin2bn(&raw_sig
[0], order_len
, nullptr);
503 sig
->s
= BN_bin2bn(&raw_sig
[order_len
], order_len
, nullptr);
504 if (!sig
->r
|| !sig
->s
) {
505 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
509 // Ensure the DER-encoded signature fits in the bounds.
510 int len
= i2d_ECDSA_SIG(sig
.get(), nullptr);
511 if (len
< 0 || static_cast<size_t>(len
) > ECDSA_size(ec_key
)) {
512 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
516 len
= i2d_ECDSA_SIG(sig
.get(), &out_sig
);
518 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
525 int EcdsaMethodVerify(const uint8_t* digest
,
531 OPENSSL_PUT_ERROR(ECDSA
, ECDSA_do_verify
, ECDSA_R_NOT_IMPLEMENTED
);
535 const ECDSA_METHOD win_ecdsa_method
= {
544 EcdsaMethodGroupOrderSize
,
550 // Determines the key type and length of |certificate|'s public key. The type is
551 // returned as an OpenSSL EVP_PKEY type. The key length for RSA key is the size
552 // of the RSA modulus in bits. For an ECDSA key, it is the number of bits to
553 // represent the group order. It returns true on success and false on failure.
554 bool GetKeyInfo(const X509Certificate
* certificate
,
556 size_t* out_length
) {
557 crypto::OpenSSLErrStackTracer
tracker(FROM_HERE
);
559 std::string der_encoded
;
560 if (!X509Certificate::GetDEREncoded(certificate
->os_cert_handle(),
563 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
564 ScopedX509
x509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
567 crypto::ScopedEVP_PKEY
key(X509_get_pubkey(x509
.get()));
570 *out_type
= EVP_PKEY_id(key
.get());
571 *out_length
= EVP_PKEY_bits(key
.get());
575 crypto::ScopedEVP_PKEY
CreateRSAWrapper(ScopedCERT_KEY_CONTEXT key
,
577 crypto::ScopedRSA
rsa(RSA_new_method(global_boringssl_engine
.Get().engine()));
581 RSA_set_ex_data(rsa
.get(), global_boringssl_engine
.Get().rsa_ex_index(),
582 new KeyExData(key
.Pass(), key_length
));
584 crypto::ScopedEVP_PKEY
pkey(EVP_PKEY_new());
585 if (!pkey
|| !EVP_PKEY_set1_RSA(pkey
.get(), rsa
.get()))
590 crypto::ScopedEVP_PKEY
CreateECDSAWrapper(ScopedCERT_KEY_CONTEXT key
,
592 crypto::ScopedEC_KEY
ec_key(
593 EC_KEY_new_method(global_boringssl_engine
.Get().engine()));
597 EC_KEY_set_ex_data(ec_key
.get(),
598 global_boringssl_engine
.Get().ec_key_ex_index(),
599 new KeyExData(key
.Pass(), key_length
));
601 crypto::ScopedEVP_PKEY
pkey(EVP_PKEY_new());
602 if (!pkey
|| !EVP_PKEY_set1_EC_KEY(pkey
.get(), ec_key
.get()))
610 crypto::ScopedEVP_PKEY
FetchClientCertPrivateKey(
611 const X509Certificate
* certificate
) {
612 PCCERT_CONTEXT cert_context
= certificate
->os_cert_handle();
614 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
616 BOOL must_free
= FALSE
;
618 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
619 flags
|= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
;
621 if (!CryptAcquireCertificatePrivateKey(cert_context
, flags
, nullptr,
622 &crypt_prov
, &key_spec
, &must_free
)) {
623 PLOG(WARNING
) << "Could not acquire private key";
627 // Should never get a cached handle back - ownership must always be
629 CHECK_EQ(must_free
, TRUE
);
630 ScopedCERT_KEY_CONTEXT
key(new CERT_KEY_CONTEXT
);
631 key
->dwKeySpec
= key_spec
;
632 key
->hCryptProv
= crypt_prov
;
634 // Rather than query the private key for metadata, extract the public key from
635 // the certificate without using Windows APIs. CAPI and CNG do not
636 // consistently work depending on the system. See https://crbug.com/468345.
639 if (!GetKeyInfo(certificate
, &key_type
, &key_length
))
644 return CreateRSAWrapper(key
.Pass(), key_length
);
646 return CreateECDSAWrapper(key
.Pass(), key_length
);