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/win/windows_version.h"
33 #include "crypto/openssl_util.h"
34 #include "crypto/scoped_capi_types.h"
35 #include "crypto/wincrypt_shim.h"
36 #include "net/base/net_errors.h"
37 #include "net/cert/x509_certificate.h"
38 #include "net/ssl/openssl_ssl_util.h"
39 #include "net/ssl/scoped_openssl_types.h"
45 using NCryptFreeObjectFunc
= SECURITY_STATUS(WINAPI
*)(NCRYPT_HANDLE
);
46 using NCryptSignHashFunc
= SECURITY_STATUS(WINAPI
*)(NCRYPT_KEY_HANDLE
, // hKey
47 VOID
*, // pPaddingInfo
58 : ncrypt_free_object_(nullptr),
59 ncrypt_sign_hash_(nullptr) {
60 HMODULE ncrypt
= GetModuleHandle(L
"ncrypt.dll");
61 if (ncrypt
!= nullptr) {
62 ncrypt_free_object_
= reinterpret_cast<NCryptFreeObjectFunc
>(
63 GetProcAddress(ncrypt
, "NCryptFreeObject"));
64 ncrypt_sign_hash_
= reinterpret_cast<NCryptSignHashFunc
>(
65 GetProcAddress(ncrypt
, "NCryptSignHash"));
69 NCryptFreeObjectFunc
ncrypt_free_object() const {
70 return ncrypt_free_object_
;
73 NCryptSignHashFunc
ncrypt_sign_hash() const { return ncrypt_sign_hash_
; }
76 NCryptFreeObjectFunc ncrypt_free_object_
;
77 NCryptSignHashFunc ncrypt_sign_hash_
;
80 base::LazyInstance
<CNGFunctions
>::Leaky g_cng_functions
=
81 LAZY_INSTANCE_INITIALIZER
;
83 struct CERT_KEY_CONTEXTDeleter
{
84 void operator()(PCERT_KEY_CONTEXT key
) {
85 if (key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
86 g_cng_functions
.Get().ncrypt_free_object()(key
->hNCryptKey
);
88 CryptReleaseContext(key
->hCryptProv
, 0);
94 using ScopedCERT_KEY_CONTEXT
=
95 scoped_ptr
<CERT_KEY_CONTEXT
, CERT_KEY_CONTEXTDeleter
>;
97 // KeyExData contains the data that is contained in the EX_DATA of the
98 // RSA and ECDSA objects that are created to wrap Windows system keys.
100 KeyExData(ScopedCERT_KEY_CONTEXT key
, size_t key_length
)
101 : key(key
.Pass()), key_length(key_length
) {}
103 ScopedCERT_KEY_CONTEXT key
;
107 // ExDataDup is called when one of the RSA or EC_KEY objects is
108 // duplicated. This is not supported and should never happen.
109 int ExDataDup(CRYPTO_EX_DATA
* to
,
110 const CRYPTO_EX_DATA
* from
,
115 CHECK_EQ((void*)nullptr, *from_d
);
119 // ExDataFree is called when one of the RSA or EC_KEY objects is freed.
120 void ExDataFree(void* parent
,
122 CRYPTO_EX_DATA
* ex_data
,
126 KeyExData
* data
= reinterpret_cast<KeyExData
*>(ptr
);
130 extern const RSA_METHOD win_rsa_method
;
131 extern const ECDSA_METHOD win_ecdsa_method
;
133 // BoringSSLEngine is a BoringSSL ENGINE that implements RSA and ECDSA
134 // by forwarding the requested operations to CAPI or CNG.
135 class BoringSSLEngine
{
138 : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
140 nullptr /* new_func */,
143 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
145 nullptr /* new_func */,
148 engine_(ENGINE_new()) {
149 ENGINE_set_RSA_method(engine_
, &win_rsa_method
, sizeof(win_rsa_method
));
150 ENGINE_set_ECDSA_method(engine_
, &win_ecdsa_method
,
151 sizeof(win_ecdsa_method
));
154 int rsa_ex_index() const { return rsa_index_
; }
155 int ec_key_ex_index() const { return ec_key_index_
; }
157 const ENGINE
* engine() const { return engine_
; }
160 const int rsa_index_
;
161 const int ec_key_index_
;
162 ENGINE
* const engine_
;
165 base::LazyInstance
<BoringSSLEngine
>::Leaky global_boringssl_engine
=
166 LAZY_INSTANCE_INITIALIZER
;
168 // Signs |in| with |key|, writing the output to |out| and the size to |out_len|.
169 // Although the buffer is preallocated, this calls NCryptSignHash twice. Some
170 // smartcards are buggy and assume the two-call pattern. See
171 // https://crbug.com/470204. Returns true on success and false on error.
172 bool DoNCryptSignHash(NCRYPT_KEY_HANDLE key
,
180 // Determine the output length.
182 SECURITY_STATUS ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
183 key
, padding
, const_cast<BYTE
*>(in
), in_len
, nullptr, 0, &signature_len
,
185 if (FAILED(ncrypt_status
)) {
186 LOG(ERROR
) << "NCryptSignHash failed: " << ncrypt_status
;
189 // Check |max_out| externally rather than trust the smartcard.
190 if (signature_len
== 0 || signature_len
> max_out
) {
191 LOG(ERROR
) << "Bad signature length.";
194 // It is important that |signature_len| already be initialized with the
195 // correct size. Some smartcards are buggy and do not write to it on the
197 ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
198 key
, padding
, const_cast<BYTE
*>(in
), in_len
, out
, signature_len
,
199 &signature_len
, flags
);
200 if (FAILED(ncrypt_status
)) {
201 LOG(ERROR
) << "NCryptSignHash failed: " << ncrypt_status
;
204 if (signature_len
== 0) {
205 LOG(ERROR
) << "Bad signature length.";
208 *out_len
= signature_len
;
212 // Custom RSA_METHOD that uses the platform APIs for signing.
214 const KeyExData
* RsaGetExData(const RSA
* rsa
) {
215 return reinterpret_cast<const KeyExData
*>(
216 RSA_get_ex_data(rsa
, global_boringssl_engine
.Get().rsa_ex_index()));
219 size_t RsaMethodSize(const RSA
* rsa
) {
220 const KeyExData
* ex_data
= RsaGetExData(rsa
);
221 return (ex_data
->key_length
+ 7) / 8;
224 int RsaMethodSign(int hash_nid
,
230 // TODO(davidben): Switch BoringSSL's sign hook to using size_t rather than
232 const KeyExData
* ex_data
= RsaGetExData(rsa
);
235 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, ERR_R_INTERNAL_ERROR
);
239 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
240 BCRYPT_PKCS1_PADDING_INFO rsa_padding_info
;
243 rsa_padding_info
.pszAlgId
= nullptr;
246 rsa_padding_info
.pszAlgId
= BCRYPT_SHA1_ALGORITHM
;
249 rsa_padding_info
.pszAlgId
= BCRYPT_SHA256_ALGORITHM
;
252 rsa_padding_info
.pszAlgId
= BCRYPT_SHA384_ALGORITHM
;
255 rsa_padding_info
.pszAlgId
= BCRYPT_SHA512_ALGORITHM
;
258 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
263 if (!DoNCryptSignHash(ex_data
->key
->hNCryptKey
, &rsa_padding_info
, in
,
264 in_len
, out
, RSA_size(rsa
), &signature_len
,
266 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
269 *out_len
= signature_len
;
276 hash_alg
= CALG_SSL3_SHAMD5
;
279 hash_alg
= CALG_SHA1
;
282 hash_alg
= CALG_SHA_256
;
285 hash_alg
= CALG_SHA_384
;
288 hash_alg
= CALG_SHA_512
;
291 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
295 crypto::ScopedHCRYPTHASH hash
;
296 if (!CryptCreateHash(ex_data
->key
->hCryptProv
, hash_alg
, 0, 0,
298 PLOG(ERROR
) << "CreateCreateHash failed";
299 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
303 DWORD arg_len
= sizeof(hash_len
);
304 if (!CryptGetHashParam(hash
.get(), HP_HASHSIZE
,
305 reinterpret_cast<BYTE
*>(&hash_len
), &arg_len
, 0)) {
306 PLOG(ERROR
) << "CryptGetHashParam HP_HASHSIZE failed";
307 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
310 if (hash_len
!= in_len
) {
311 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
314 if (!CryptSetHashParam(hash
.get(), HP_HASHVAL
, const_cast<BYTE
*>(in
), 0)) {
315 PLOG(ERROR
) << "CryptSetHashParam HP_HASHVAL failed";
316 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
319 DWORD signature_len
= RSA_size(rsa
);
320 if (!CryptSignHash(hash
.get(), ex_data
->key
->dwKeySpec
, nullptr, 0, out
,
322 PLOG(ERROR
) << "CryptSignHash failed";
323 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
327 /* CryptoAPI signs in little-endian, so reverse it. */
328 std::reverse(out
, out
+ signature_len
);
329 *out_len
= signature_len
;
333 int RsaMethodEncrypt(RSA
* rsa
,
341 OPENSSL_PUT_ERROR(RSA
, encrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
345 int RsaMethodSignRaw(RSA
* rsa
,
353 OPENSSL_PUT_ERROR(RSA
, encrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
357 int RsaMethodDecrypt(RSA
* rsa
,
365 OPENSSL_PUT_ERROR(RSA
, decrypt
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
369 int RsaMethodVerifyRaw(RSA
* rsa
,
377 OPENSSL_PUT_ERROR(RSA
, verify_raw
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
381 int RsaMethodSupportsDigest(const RSA
* rsa
, const EVP_MD
* md
) {
382 const KeyExData
* ex_data
= RsaGetExData(rsa
);
388 int hash_nid
= EVP_MD_type(md
);
389 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
390 // Only hashes which appear in RsaSignPKCS1 are supported.
391 if (hash_nid
!= NID_sha1
&& hash_nid
!= NID_sha256
&&
392 hash_nid
!= NID_sha384
&& hash_nid
!= NID_sha512
) {
396 // If the key is a 1024-bit RSA, assume conservatively that it may only be
397 // able to sign SHA-1 hashes. This is the case for older Estonian ID cards
398 // that have 1024-bit RSA keys.
400 // CNG does provide NCryptIsAlgSupported and NCryptEnumAlgorithms functions,
401 // however they seem to both return NTE_NOT_SUPPORTED when querying the
402 // NCRYPT_PROV_HANDLE at the key's NCRYPT_PROVIDER_HANDLE_PROPERTY.
403 if (ex_data
->key_length
<= 1024 && hash_nid
!= NID_sha1
)
408 // If the key is in CAPI, assume conservatively that the CAPI service
409 // provider may only be able to sign SHA-1 hashes.
410 return hash_nid
== NID_sha1
;
414 const RSA_METHOD win_rsa_method
= {
430 nullptr, // private_transform
432 nullptr, // bn_mod_exp
435 RsaMethodSupportsDigest
,
438 // Custom ECDSA_METHOD that uses the platform APIs.
439 // Note that for now, only signing through ECDSA_sign() is really supported.
440 // all other method pointers are either stubs returning errors, or no-ops.
442 const KeyExData
* EcKeyGetExData(const EC_KEY
* ec_key
) {
443 return reinterpret_cast<const KeyExData
*>(EC_KEY_get_ex_data(
444 ec_key
, global_boringssl_engine
.Get().ec_key_ex_index()));
447 size_t EcdsaMethodGroupOrderSize(const EC_KEY
* ec_key
) {
448 const KeyExData
* ex_data
= EcKeyGetExData(ec_key
);
449 // key_length is the size of the group order for EC keys.
450 return (ex_data
->key_length
+ 7) / 8;
453 int EcdsaMethodSign(const uint8_t* digest
,
456 unsigned int* out_sig_len
,
458 const KeyExData
* ex_data
= EcKeyGetExData(ec_key
);
459 // Only CNG supports ECDSA.
460 if (!ex_data
|| ex_data
->key
->dwKeySpec
!= CERT_NCRYPT_KEY_SPEC
) {
462 OPENSSL_PUT_ERROR(RSA
, sign_raw
, ERR_R_INTERNAL_ERROR
);
466 // An ECDSA signature is two integers, modulo the order of the group.
467 size_t order_len
= (ex_data
->key_length
+ 7) / 8;
468 if (order_len
== 0) {
470 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
473 std::vector
<uint8_t> raw_sig(order_len
* 2);
476 if (!DoNCryptSignHash(ex_data
->key
->hNCryptKey
, nullptr, digest
, digest_len
,
477 &raw_sig
[0], raw_sig
.size(), &signature_len
, 0)) {
478 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
481 if (signature_len
!= raw_sig
.size()) {
482 LOG(ERROR
) << "Bad signature length";
483 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
487 // Convert the RAW ECDSA signature to a DER-encoded ECDSA-Sig-Value.
488 crypto::ScopedECDSA_SIG
sig(ECDSA_SIG_new());
490 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
493 sig
->r
= BN_bin2bn(&raw_sig
[0], order_len
, nullptr);
494 sig
->s
= BN_bin2bn(&raw_sig
[order_len
], order_len
, nullptr);
495 if (!sig
->r
|| !sig
->s
) {
496 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
500 // Ensure the DER-encoded signature fits in the bounds.
501 int len
= i2d_ECDSA_SIG(sig
.get(), nullptr);
502 if (len
< 0 || static_cast<size_t>(len
) > ECDSA_size(ec_key
)) {
503 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
507 len
= i2d_ECDSA_SIG(sig
.get(), &out_sig
);
509 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
516 int EcdsaMethodVerify(const uint8_t* digest
,
522 OPENSSL_PUT_ERROR(ECDSA
, ECDSA_do_verify
, ECDSA_R_NOT_IMPLEMENTED
);
526 const ECDSA_METHOD win_ecdsa_method
= {
535 EcdsaMethodGroupOrderSize
,
541 // Determines the key type and length of |certificate|'s public key. The type is
542 // returned as an OpenSSL EVP_PKEY type. The key length for RSA key is the size
543 // of the RSA modulus in bits. For an ECDSA key, it is the number of bits to
544 // represent the group order. It returns true on success and false on failure.
545 bool GetKeyInfo(const X509Certificate
* certificate
,
547 size_t* out_length
) {
548 crypto::OpenSSLErrStackTracer
tracker(FROM_HERE
);
550 std::string der_encoded
;
551 if (!X509Certificate::GetDEREncoded(certificate
->os_cert_handle(),
554 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
555 ScopedX509
x509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
558 crypto::ScopedEVP_PKEY
key(X509_get_pubkey(x509
.get()));
561 *out_type
= EVP_PKEY_id(key
.get());
562 *out_length
= EVP_PKEY_bits(key
.get());
566 crypto::ScopedEVP_PKEY
CreateRSAWrapper(ScopedCERT_KEY_CONTEXT key
,
568 crypto::ScopedRSA
rsa(RSA_new_method(global_boringssl_engine
.Get().engine()));
572 RSA_set_ex_data(rsa
.get(), global_boringssl_engine
.Get().rsa_ex_index(),
573 new KeyExData(key
.Pass(), key_length
));
575 crypto::ScopedEVP_PKEY
pkey(EVP_PKEY_new());
576 if (!pkey
|| !EVP_PKEY_set1_RSA(pkey
.get(), rsa
.get()))
581 crypto::ScopedEVP_PKEY
CreateECDSAWrapper(ScopedCERT_KEY_CONTEXT key
,
583 crypto::ScopedEC_KEY
ec_key(
584 EC_KEY_new_method(global_boringssl_engine
.Get().engine()));
588 EC_KEY_set_ex_data(ec_key
.get(),
589 global_boringssl_engine
.Get().ec_key_ex_index(),
590 new KeyExData(key
.Pass(), key_length
));
592 crypto::ScopedEVP_PKEY
pkey(EVP_PKEY_new());
593 if (!pkey
|| !EVP_PKEY_set1_EC_KEY(pkey
.get(), ec_key
.get()))
601 crypto::ScopedEVP_PKEY
FetchClientCertPrivateKey(
602 const X509Certificate
* certificate
) {
603 PCCERT_CONTEXT cert_context
= certificate
->os_cert_handle();
605 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
607 BOOL must_free
= FALSE
;
609 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
610 flags
|= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
;
612 if (!CryptAcquireCertificatePrivateKey(cert_context
, flags
, nullptr,
613 &crypt_prov
, &key_spec
, &must_free
)) {
614 PLOG(WARNING
) << "Could not acquire private key";
618 // Should never get a cached handle back - ownership must always be
620 CHECK_EQ(must_free
, TRUE
);
621 ScopedCERT_KEY_CONTEXT
key(new CERT_KEY_CONTEXT
);
622 key
->dwKeySpec
= key_spec
;
623 key
->hCryptProv
= crypt_prov
;
625 // Rather than query the private key for metadata, extract the public key from
626 // the certificate without using Windows APIs. CAPI and CNG do not
627 // consistently work depending on the system. See https://crbug.com/468345.
630 if (!GetKeyInfo(certificate
, &key_type
, &key_length
))
635 return CreateRSAWrapper(key
.Pass(), key_length
);
637 return CreateECDSAWrapper(key
.Pass(), key_length
);