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
=
47 SECURITY_STATUS(WINAPI
*)(NCRYPT_KEY_HANDLE
, // hKey
48 VOID
*, // pPaddingInfo
59 : ncrypt_free_object_(nullptr),
60 ncrypt_sign_hash_(nullptr) {
61 HMODULE ncrypt
= GetModuleHandle(L
"ncrypt.dll");
62 if (ncrypt
!= nullptr) {
63 ncrypt_free_object_
= reinterpret_cast<NCryptFreeObjectFunc
>(
64 GetProcAddress(ncrypt
, "NCryptFreeObject"));
65 ncrypt_sign_hash_
= reinterpret_cast<NCryptSignHashFunc
>(
66 GetProcAddress(ncrypt
, "NCryptSignHash"));
70 NCryptFreeObjectFunc
ncrypt_free_object() const {
71 return ncrypt_free_object_
;
74 NCryptSignHashFunc
ncrypt_sign_hash() const { return ncrypt_sign_hash_
; }
77 NCryptFreeObjectFunc ncrypt_free_object_
;
78 NCryptSignHashFunc ncrypt_sign_hash_
;
81 base::LazyInstance
<CNGFunctions
>::Leaky g_cng_functions
=
82 LAZY_INSTANCE_INITIALIZER
;
84 struct CERT_KEY_CONTEXTDeleter
{
85 void operator()(PCERT_KEY_CONTEXT key
) {
86 if (key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
87 g_cng_functions
.Get().ncrypt_free_object()(key
->hNCryptKey
);
89 CryptReleaseContext(key
->hCryptProv
, 0);
95 using ScopedCERT_KEY_CONTEXT
=
96 scoped_ptr
<CERT_KEY_CONTEXT
, CERT_KEY_CONTEXTDeleter
>;
98 // KeyExData contains the data that is contained in the EX_DATA of the
99 // RSA and ECDSA objects that are created to wrap Windows system keys.
101 KeyExData(ScopedCERT_KEY_CONTEXT key
, size_t key_length
)
102 : key(key
.Pass()), key_length(key_length
) {}
104 ScopedCERT_KEY_CONTEXT key
;
108 // ExDataDup is called when one of the RSA or EC_KEY objects is
109 // duplicated. This is not supported and should never happen.
110 int ExDataDup(CRYPTO_EX_DATA
* to
,
111 const CRYPTO_EX_DATA
* from
,
116 CHECK_EQ((void*)nullptr, *from_d
);
120 // ExDataFree is called when one of the RSA or EC_KEY objects is freed.
121 void ExDataFree(void* parent
,
123 CRYPTO_EX_DATA
* ex_data
,
127 KeyExData
* data
= reinterpret_cast<KeyExData
*>(ptr
);
131 extern const RSA_METHOD win_rsa_method
;
132 extern const ECDSA_METHOD win_ecdsa_method
;
134 // BoringSSLEngine is a BoringSSL ENGINE that implements RSA and ECDSA
135 // by forwarding the requested operations to CAPI or CNG.
136 class BoringSSLEngine
{
139 : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
141 nullptr /* new_func */,
144 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
146 nullptr /* new_func */,
149 engine_(ENGINE_new()) {
150 ENGINE_set_RSA_method(engine_
, &win_rsa_method
, sizeof(win_rsa_method
));
151 ENGINE_set_ECDSA_method(engine_
, &win_ecdsa_method
,
152 sizeof(win_ecdsa_method
));
155 int rsa_ex_index() const { return rsa_index_
; }
156 int ec_key_ex_index() const { return ec_key_index_
; }
158 const ENGINE
* engine() const { return engine_
; }
161 const int rsa_index_
;
162 const int ec_key_index_
;
163 ENGINE
* const engine_
;
166 base::LazyInstance
<BoringSSLEngine
>::Leaky global_boringssl_engine
=
167 LAZY_INSTANCE_INITIALIZER
;
169 // Signs |in| with |key|, writing the output to |out| and the size to |out_len|.
170 // Although the buffer is preallocated, this calls NCryptSignHash twice. Some
171 // smartcards are buggy and assume the two-call pattern. See
172 // https://crbug.com/470204. Returns true on success and false on error.
173 bool DoNCryptSignHash(NCRYPT_KEY_HANDLE key
,
181 // Determine the output length.
183 SECURITY_STATUS ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
184 key
, padding
, const_cast<BYTE
*>(in
), in_len
, nullptr, 0, &signature_len
,
186 if (FAILED(ncrypt_status
)) {
187 LOG(ERROR
) << "NCryptSignHash failed: " << ncrypt_status
;
190 // Check |max_out| externally rather than trust the smartcard.
191 if (signature_len
== 0 || signature_len
> max_out
) {
192 LOG(ERROR
) << "Bad signature length.";
195 // It is important that |signature_len| already be initialized with the
196 // correct size. Some smartcards are buggy and do not write to it on the
198 ncrypt_status
= g_cng_functions
.Get().ncrypt_sign_hash()(
199 key
, padding
, const_cast<PBYTE
>(in
), in_len
, out
, signature_len
,
200 &signature_len
, flags
);
201 if (FAILED(ncrypt_status
)) {
202 LOG(ERROR
) << "NCryptSignHash failed: " << ncrypt_status
;
205 if (signature_len
== 0) {
206 LOG(ERROR
) << "Bad signature length.";
209 *out_len
= signature_len
;
213 // Custom RSA_METHOD that uses the platform APIs for signing.
215 const KeyExData
* RsaGetExData(const RSA
* rsa
) {
216 return reinterpret_cast<const KeyExData
*>(
217 RSA_get_ex_data(rsa
, global_boringssl_engine
.Get().rsa_ex_index()));
220 size_t RsaMethodSize(const RSA
* rsa
) {
221 const KeyExData
* ex_data
= RsaGetExData(rsa
);
222 return (ex_data
->key_length
+ 7) / 8;
225 int RsaMethodSign(int hash_nid
,
231 // TODO(davidben): Switch BoringSSL's sign hook to using size_t rather than
233 const KeyExData
* ex_data
= RsaGetExData(rsa
);
236 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, ERR_R_INTERNAL_ERROR
);
240 if (ex_data
->key
->dwKeySpec
== CERT_NCRYPT_KEY_SPEC
) {
241 BCRYPT_PKCS1_PADDING_INFO rsa_padding_info
;
244 rsa_padding_info
.pszAlgId
= nullptr;
247 rsa_padding_info
.pszAlgId
= BCRYPT_SHA1_ALGORITHM
;
250 rsa_padding_info
.pszAlgId
= BCRYPT_SHA256_ALGORITHM
;
253 rsa_padding_info
.pszAlgId
= BCRYPT_SHA384_ALGORITHM
;
256 rsa_padding_info
.pszAlgId
= BCRYPT_SHA512_ALGORITHM
;
259 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
264 if (!DoNCryptSignHash(ex_data
->key
->hNCryptKey
, &rsa_padding_info
, in
,
265 in_len
, out
, RSA_size(rsa
), &signature_len
,
267 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
270 *out_len
= signature_len
;
277 hash_alg
= CALG_SSL3_SHAMD5
;
280 hash_alg
= CALG_SHA1
;
283 hash_alg
= CALG_SHA_256
;
286 hash_alg
= CALG_SHA_384
;
289 hash_alg
= CALG_SHA_512
;
292 OPENSSL_PUT_ERROR(RSA
, RSA_sign
, RSA_R_UNKNOWN_ALGORITHM_TYPE
);
297 if (!CryptCreateHash(ex_data
->key
->hCryptProv
, hash_alg
, 0, 0, &hash
)) {
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
, HP_HASHSIZE
, reinterpret_cast<BYTE
*>(&hash_len
),
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
, 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
, 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
);