1 // Copyright (c) 2012 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 // OpenSSL binding for SSLClientSocket. The class layout and general principle
6 // of operation is derived from SSLClientSocketNSS.
8 #include "net/socket/ssl_client_socket_openssl.h"
11 #include <openssl/bio.h>
12 #include <openssl/err.h>
13 #include <openssl/mem.h>
14 #include <openssl/ssl.h>
17 #include "base/bind.h"
18 #include "base/callback_helpers.h"
19 #include "base/environment.h"
20 #include "base/lazy_instance.h"
21 #include "base/memory/singleton.h"
22 #include "base/metrics/histogram_macros.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/stl_util.h"
25 #include "base/strings/string_piece.h"
26 #include "base/synchronization/lock.h"
27 #include "base/threading/sequenced_worker_pool.h"
28 #include "base/threading/thread_local.h"
29 #include "base/values.h"
30 #include "crypto/ec_private_key.h"
31 #include "crypto/openssl_util.h"
32 #include "crypto/scoped_openssl_types.h"
33 #include "net/base/ip_address_number.h"
34 #include "net/base/net_errors.h"
35 #include "net/cert/cert_policy_enforcer.h"
36 #include "net/cert/cert_verifier.h"
37 #include "net/cert/ct_ev_whitelist.h"
38 #include "net/cert/ct_verifier.h"
39 #include "net/cert/x509_certificate_net_log_param.h"
40 #include "net/cert/x509_util_openssl.h"
41 #include "net/http/transport_security_state.h"
42 #include "net/ssl/scoped_openssl_types.h"
43 #include "net/ssl/ssl_cert_request_info.h"
44 #include "net/ssl/ssl_client_session_cache_openssl.h"
45 #include "net/ssl/ssl_connection_status_flags.h"
46 #include "net/ssl/ssl_failure_state.h"
47 #include "net/ssl/ssl_info.h"
48 #include "net/ssl/ssl_private_key.h"
51 #include "base/win/windows_version.h"
54 #if defined(USE_OPENSSL_CERTS)
55 #include "net/ssl/openssl_client_key_store.h"
57 #include "net/ssl/ssl_platform_key.h"
64 // Enable this to see logging for state machine state transitions.
66 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
67 " jump to state " << s; \
68 next_handshake_state_ = s; } while (0)
70 #define GotoState(s) next_handshake_state_ = s
73 // This constant can be any non-negative/non-zero value (eg: it does not
74 // overlap with any value of the net::Error range, including net::OK).
75 const int kNoPendingResult
= 1;
77 // If a client doesn't have a list of protocols that it supports, but
78 // the server supports NPN, choosing "http/1.1" is the best answer.
79 const char kDefaultSupportedNPNProtocol
[] = "http/1.1";
81 // Default size of the internal BoringSSL buffers.
82 const int KDefaultOpenSSLBufferSize
= 17 * 1024;
84 void FreeX509Stack(STACK_OF(X509
)* ptr
) {
85 sk_X509_pop_free(ptr
, X509_free
);
88 using ScopedX509Stack
= crypto::ScopedOpenSSL
<STACK_OF(X509
), FreeX509Stack
>;
90 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
91 // This method doesn't seem to have made it into the OpenSSL headers.
92 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER
* cipher
) { return cipher
->id
; }
95 // Used for encoding the |connection_status| field of an SSLInfo object.
96 int EncodeSSLConnectionStatus(uint16 cipher_suite
,
100 ((compression
& SSL_CONNECTION_COMPRESSION_MASK
) <<
101 SSL_CONNECTION_COMPRESSION_SHIFT
) |
102 ((version
& SSL_CONNECTION_VERSION_MASK
) <<
103 SSL_CONNECTION_VERSION_SHIFT
);
106 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
107 // this SSL connection.
108 int GetNetSSLVersion(SSL
* ssl
) {
109 switch (SSL_version(ssl
)) {
111 return SSL_CONNECTION_VERSION_TLS1
;
113 return SSL_CONNECTION_VERSION_TLS1_1
;
115 return SSL_CONNECTION_VERSION_TLS1_2
;
118 return SSL_CONNECTION_VERSION_UNKNOWN
;
122 ScopedX509
OSCertHandleToOpenSSL(
123 X509Certificate::OSCertHandle os_handle
) {
124 #if defined(USE_OPENSSL_CERTS)
125 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle
));
126 #else // !defined(USE_OPENSSL_CERTS)
127 std::string der_encoded
;
128 if (!X509Certificate::GetDEREncoded(os_handle
, &der_encoded
))
130 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
131 return ScopedX509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
132 #endif // defined(USE_OPENSSL_CERTS)
135 ScopedX509Stack
OSCertHandlesToOpenSSL(
136 const X509Certificate::OSCertHandles
& os_handles
) {
137 ScopedX509Stack
stack(sk_X509_new_null());
138 for (size_t i
= 0; i
< os_handles
.size(); i
++) {
139 ScopedX509 x509
= OSCertHandleToOpenSSL(os_handles
[i
]);
141 return ScopedX509Stack();
142 sk_X509_push(stack
.get(), x509
.release());
147 int LogErrorCallback(const char* str
, size_t len
, void* context
) {
148 LOG(ERROR
) << base::StringPiece(str
, len
);
152 bool EVP_MDToPrivateKeyHash(const EVP_MD
* md
, SSLPrivateKey::Hash
* hash
) {
153 switch (EVP_MD_type(md
)) {
155 *hash
= SSLPrivateKey::Hash::MD5_SHA1
;
158 *hash
= SSLPrivateKey::Hash::SHA1
;
161 *hash
= SSLPrivateKey::Hash::SHA256
;
164 *hash
= SSLPrivateKey::Hash::SHA384
;
167 *hash
= SSLPrivateKey::Hash::SHA512
;
174 #if !defined(USE_OPENSSL_CERTS)
175 class PlatformKeyTaskRunner
{
177 PlatformKeyTaskRunner() {
178 // Serialize all the private key operations on a single background
179 // thread to avoid problems with buggy smartcards.
180 worker_pool_
= new base::SequencedWorkerPool(1, "Platform Key Thread");
181 task_runner_
= worker_pool_
->GetSequencedTaskRunnerWithShutdownBehavior(
182 worker_pool_
->GetSequenceToken(),
183 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN
);
186 scoped_refptr
<base::SequencedTaskRunner
> task_runner() {
191 scoped_refptr
<base::SequencedWorkerPool
> worker_pool_
;
192 scoped_refptr
<base::SequencedTaskRunner
> task_runner_
;
194 DISALLOW_COPY_AND_ASSIGN(PlatformKeyTaskRunner
);
197 base::LazyInstance
<PlatformKeyTaskRunner
>::Leaky g_platform_key_task_runner
=
198 LAZY_INSTANCE_INITIALIZER
;
199 #endif // !USE_OPENSSL_CERTS
203 class SSLClientSocketOpenSSL::SSLContext
{
205 static SSLContext
* GetInstance() { return Singleton
<SSLContext
>::get(); }
206 SSL_CTX
* ssl_ctx() { return ssl_ctx_
.get(); }
207 SSLClientSessionCacheOpenSSL
* session_cache() { return &session_cache_
; }
209 SSLClientSocketOpenSSL
* GetClientSocketFromSSL(const SSL
* ssl
) {
211 SSLClientSocketOpenSSL
* socket
= static_cast<SSLClientSocketOpenSSL
*>(
212 SSL_get_ex_data(ssl
, ssl_socket_data_index_
));
217 bool SetClientSocketForSSL(SSL
* ssl
, SSLClientSocketOpenSSL
* socket
) {
218 return SSL_set_ex_data(ssl
, ssl_socket_data_index_
, socket
) != 0;
221 static const SSL_PRIVATE_KEY_METHOD kPrivateKeyMethod
;
224 friend struct DefaultSingletonTraits
<SSLContext
>;
226 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
227 crypto::EnsureOpenSSLInit();
228 ssl_socket_data_index_
= SSL_get_ex_new_index(0, 0, 0, 0, 0);
229 DCHECK_NE(ssl_socket_data_index_
, -1);
230 ssl_ctx_
.reset(SSL_CTX_new(SSLv23_client_method()));
231 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
232 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
233 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
234 // This stops |SSL_shutdown| from generating the close_notify message, which
235 // is currently not sent on the network.
236 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
237 SSL_CTX_set_quiet_shutdown(ssl_ctx_
.get(), 1);
238 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
239 // It would be better if the callback were not a global setting,
240 // but that is an OpenSSL issue.
241 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
243 ssl_ctx_
->tlsext_channel_id_enabled_new
= 1;
245 // Disable the internal session cache. Session caching is handled
246 // externally (i.e. by SSLClientSessionCacheOpenSSL).
247 SSL_CTX_set_session_cache_mode(
248 ssl_ctx_
.get(), SSL_SESS_CACHE_CLIENT
| SSL_SESS_CACHE_NO_INTERNAL
);
249 SSL_CTX_sess_set_new_cb(ssl_ctx_
.get(), NewSessionCallback
);
251 scoped_ptr
<base::Environment
> env(base::Environment::Create());
252 std::string ssl_keylog_file
;
253 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
254 !ssl_keylog_file
.empty()) {
255 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
256 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
258 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
259 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
261 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
266 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
267 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
269 return socket
->ClientCertRequestCallback(ssl
);
272 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
273 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
274 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
275 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
278 return socket
->CertVerifyCallback(store_ctx
);
281 static int SelectNextProtoCallback(SSL
* ssl
,
282 unsigned char** out
, unsigned char* outlen
,
283 const unsigned char* in
,
284 unsigned int inlen
, void* arg
) {
285 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
286 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
289 static int NewSessionCallback(SSL
* ssl
, SSL_SESSION
* session
) {
290 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
291 return socket
->NewSessionCallback(session
);
294 static int PrivateKeyTypeCallback(SSL
* ssl
) {
295 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
296 return socket
->PrivateKeyTypeCallback();
299 static int PrivateKeySupportsDigestCallback(SSL
* ssl
, const EVP_MD
* md
) {
300 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
301 return socket
->PrivateKeySupportsDigestCallback(md
);
304 static size_t PrivateKeyMaxSignatureLenCallback(SSL
* ssl
) {
305 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
306 return socket
->PrivateKeyMaxSignatureLenCallback();
309 static ssl_private_key_result_t
PrivateKeySignCallback(SSL
* ssl
,
316 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
317 return socket
->PrivateKeySignCallback(out
, out_len
, max_out
, md
, in
,
321 static ssl_private_key_result_t
PrivateKeySignCompleteCallback(
326 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
327 return socket
->PrivateKeySignCompleteCallback(out
, out_len
, max_out
);
330 // This is the index used with SSL_get_ex_data to retrieve the owner
331 // SSLClientSocketOpenSSL object from an SSL instance.
332 int ssl_socket_data_index_
;
334 ScopedSSL_CTX ssl_ctx_
;
336 // TODO(davidben): Use a separate cache per URLRequestContext.
337 // https://crbug.com/458365
339 // TODO(davidben): Sessions should be invalidated on fatal
340 // alerts. https://crbug.com/466352
341 SSLClientSessionCacheOpenSSL session_cache_
;
344 const SSL_PRIVATE_KEY_METHOD
345 SSLClientSocketOpenSSL::SSLContext::kPrivateKeyMethod
= {
346 &SSLClientSocketOpenSSL::SSLContext::PrivateKeyTypeCallback
,
347 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySupportsDigestCallback
,
348 &SSLClientSocketOpenSSL::SSLContext::PrivateKeyMaxSignatureLenCallback
,
349 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySignCallback
,
350 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySignCompleteCallback
,
353 // PeerCertificateChain is a helper object which extracts the certificate
354 // chain, as given by the server, from an OpenSSL socket and performs the needed
355 // resource management. The first element of the chain is the leaf certificate
356 // and the other elements are in the order given by the server.
357 class SSLClientSocketOpenSSL::PeerCertificateChain
{
359 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
360 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
361 ~PeerCertificateChain() {}
362 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
364 // Resets the PeerCertificateChain to the set of certificates in|chain|,
365 // which may be NULL, indicating to empty the store certificates.
366 // Note: If an error occurs, such as being unable to parse the certificates,
367 // this will behave as if Reset(NULL) was called.
368 void Reset(STACK_OF(X509
)* chain
);
370 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
371 scoped_refptr
<X509Certificate
> AsOSChain() const;
373 size_t size() const {
374 if (!openssl_chain_
.get())
376 return sk_X509_num(openssl_chain_
.get());
383 X509
* Get(size_t index
) const {
384 DCHECK_LT(index
, size());
385 return sk_X509_value(openssl_chain_
.get(), index
);
389 ScopedX509Stack openssl_chain_
;
392 SSLClientSocketOpenSSL::PeerCertificateChain
&
393 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
394 const PeerCertificateChain
& other
) {
398 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
402 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
403 STACK_OF(X509
)* chain
) {
404 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
407 scoped_refptr
<X509Certificate
>
408 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
409 #if defined(USE_OPENSSL_CERTS)
410 // When OSCertHandle is typedef'ed to X509, this implementation does a short
411 // cut to avoid converting back and forth between DER and the X509 struct.
412 X509Certificate::OSCertHandles intermediates
;
413 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
414 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
417 return make_scoped_refptr(X509Certificate::CreateFromHandle(
418 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
420 // DER-encode the chain and convert to a platform certificate handle.
421 std::vector
<base::StringPiece
> der_chain
;
422 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
423 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
424 base::StringPiece der
;
425 if (!x509_util::GetDER(x
, &der
))
427 der_chain
.push_back(der
);
430 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
435 void SSLClientSocket::ClearSessionCache() {
436 SSLClientSocketOpenSSL::SSLContext
* context
=
437 SSLClientSocketOpenSSL::SSLContext::GetInstance();
438 context
->session_cache()->Flush();
442 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
443 return SSL_PROTOCOL_VERSION_TLS1_2
;
446 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
447 scoped_ptr
<ClientSocketHandle
> transport_socket
,
448 const HostPortPair
& host_and_port
,
449 const SSLConfig
& ssl_config
,
450 const SSLClientSocketContext
& context
)
451 : transport_send_busy_(false),
452 transport_recv_busy_(false),
453 pending_read_error_(kNoPendingResult
),
454 pending_read_ssl_error_(SSL_ERROR_NONE
),
455 transport_read_error_(OK
),
456 transport_write_error_(OK
),
457 server_cert_chain_(new PeerCertificateChain(NULL
)),
458 completed_connect_(false),
459 was_ever_used_(false),
460 cert_verifier_(context
.cert_verifier
),
461 cert_transparency_verifier_(context
.cert_transparency_verifier
),
462 channel_id_service_(context
.channel_id_service
),
464 transport_bio_(NULL
),
465 transport_(transport_socket
.Pass()),
466 host_and_port_(host_and_port
),
467 ssl_config_(ssl_config
),
468 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
469 next_handshake_state_(STATE_NONE
),
470 npn_status_(kNextProtoUnsupported
),
471 channel_id_sent_(false),
472 session_pending_(false),
473 certificate_verified_(false),
474 ssl_failure_state_(SSL_FAILURE_NONE
),
475 signature_result_(kNoPendingResult
),
476 transport_security_state_(context
.transport_security_state
),
477 policy_enforcer_(context
.cert_policy_enforcer
),
478 net_log_(transport_
->socket()->NetLog()),
479 weak_factory_(this) {
480 DCHECK(cert_verifier_
);
483 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
487 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
488 SSLCertRequestInfo
* cert_request_info
) {
489 cert_request_info
->host_and_port
= host_and_port_
;
490 cert_request_info
->cert_authorities
= cert_authorities_
;
491 cert_request_info
->cert_key_types
= cert_key_types_
;
494 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
495 std::string
* proto
) const {
501 SSLClientSocketOpenSSL::GetChannelIDService() const {
502 return channel_id_service_
;
505 SSLFailureState
SSLClientSocketOpenSSL::GetSSLFailureState() const {
506 return ssl_failure_state_
;
509 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
510 const base::StringPiece
& label
,
511 bool has_context
, const base::StringPiece
& context
,
512 unsigned char* out
, unsigned int outlen
) {
514 return ERR_SOCKET_NOT_CONNECTED
;
516 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
518 int rv
= SSL_export_keying_material(
519 ssl_
, out
, outlen
, label
.data(), label
.size(),
520 reinterpret_cast<const unsigned char*>(context
.data()), context
.length(),
521 has_context
? 1 : 0);
524 int ssl_error
= SSL_get_error(ssl_
, rv
);
525 LOG(ERROR
) << "Failed to export keying material;"
526 << " returned " << rv
527 << ", SSL error code " << ssl_error
;
528 return MapOpenSSLError(ssl_error
, err_tracer
);
533 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
535 return ERR_NOT_IMPLEMENTED
;
538 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
539 // It is an error to create an SSLClientSocket whose context has no
540 // TransportSecurityState.
541 DCHECK(transport_security_state_
);
543 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
545 // Set up new ssl object.
548 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
552 // Set SSL to client mode. Handshake happens in the loop below.
553 SSL_set_connect_state(ssl_
);
555 GotoState(STATE_HANDSHAKE
);
556 rv
= DoHandshakeLoop(OK
);
557 if (rv
== ERR_IO_PENDING
) {
558 user_connect_callback_
= callback
;
560 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
563 return rv
> OK
? OK
: rv
;
566 void SSLClientSocketOpenSSL::Disconnect() {
568 // Calling SSL_shutdown prevents the session from being marked as
574 if (transport_bio_
) {
575 BIO_free_all(transport_bio_
);
576 transport_bio_
= NULL
;
579 // Shut down anything that may call us back.
580 cert_verifier_request_
.reset();
581 transport_
->socket()->Disconnect();
583 // Null all callbacks, delete all buffers.
584 transport_send_busy_
= false;
586 transport_recv_busy_
= false;
589 user_connect_callback_
.Reset();
590 user_read_callback_
.Reset();
591 user_write_callback_
.Reset();
592 user_read_buf_
= NULL
;
593 user_read_buf_len_
= 0;
594 user_write_buf_
= NULL
;
595 user_write_buf_len_
= 0;
597 pending_read_error_
= kNoPendingResult
;
598 pending_read_ssl_error_
= SSL_ERROR_NONE
;
599 pending_read_error_info_
= OpenSSLErrorInfo();
601 transport_read_error_
= OK
;
602 transport_write_error_
= OK
;
604 server_cert_verify_result_
.Reset();
605 completed_connect_
= false;
607 cert_authorities_
.clear();
608 cert_key_types_
.clear();
610 start_cert_verification_time_
= base::TimeTicks();
612 npn_status_
= kNextProtoUnsupported
;
615 channel_id_sent_
= false;
616 session_pending_
= false;
617 certificate_verified_
= false;
618 channel_id_request_
.Cancel();
619 ssl_failure_state_
= SSL_FAILURE_NONE
;
621 private_key_
.reset();
622 signature_result_
= kNoPendingResult
;
626 bool SSLClientSocketOpenSSL::IsConnected() const {
627 // If the handshake has not yet completed.
628 if (!completed_connect_
)
630 // If an asynchronous operation is still pending.
631 if (user_read_buf_
.get() || user_write_buf_
.get())
634 return transport_
->socket()->IsConnected();
637 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
638 // If the handshake has not yet completed.
639 if (!completed_connect_
)
641 // If an asynchronous operation is still pending.
642 if (user_read_buf_
.get() || user_write_buf_
.get())
645 // If there is data read from the network that has not yet been consumed, do
646 // not treat the connection as idle.
648 // Note that this does not check |BIO_pending|, whether there is ciphertext
649 // that has not yet been flushed to the network. |Write| returns early, so
650 // this can cause race conditions which cause a socket to not be treated
651 // reusable when it should be. See https://crbug.com/466147.
652 if (BIO_wpending(transport_bio_
) > 0)
655 return transport_
->socket()->IsConnectedAndIdle();
658 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
659 return transport_
->socket()->GetPeerAddress(addressList
);
662 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
663 return transport_
->socket()->GetLocalAddress(addressList
);
666 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
670 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
671 if (transport_
.get() && transport_
->socket()) {
672 transport_
->socket()->SetSubresourceSpeculation();
678 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
679 if (transport_
.get() && transport_
->socket()) {
680 transport_
->socket()->SetOmniboxSpeculation();
686 bool SSLClientSocketOpenSSL::WasEverUsed() const {
687 return was_ever_used_
;
690 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
691 if (transport_
.get() && transport_
->socket())
692 return transport_
->socket()->UsingTCPFastOpen();
698 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
700 if (server_cert_chain_
->empty())
703 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
704 ssl_info
->unverified_cert
= server_cert_
;
705 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
706 ssl_info
->is_issued_by_known_root
=
707 server_cert_verify_result_
.is_issued_by_known_root
;
708 ssl_info
->public_key_hashes
=
709 server_cert_verify_result_
.public_key_hashes
;
710 ssl_info
->client_cert_sent
=
711 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
712 ssl_info
->channel_id_sent
= channel_id_sent_
;
713 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
715 AddSCTInfoToSSLInfo(ssl_info
);
717 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
719 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
721 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
722 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
723 GetNetSSLVersion(ssl_
));
725 if (!SSL_get_secure_renegotiation_support(ssl_
))
726 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
728 if (ssl_config_
.version_fallback
)
729 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
731 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
732 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
734 DVLOG(3) << "Encoded connection status: cipher suite = "
735 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
737 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
741 void SSLClientSocketOpenSSL::GetConnectionAttempts(
742 ConnectionAttempts
* out
) const {
746 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
748 const CompletionCallback
& callback
) {
749 user_read_buf_
= buf
;
750 user_read_buf_len_
= buf_len
;
752 int rv
= DoReadLoop();
754 if (rv
== ERR_IO_PENDING
) {
755 user_read_callback_
= callback
;
758 was_ever_used_
= true;
759 user_read_buf_
= NULL
;
760 user_read_buf_len_
= 0;
766 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
768 const CompletionCallback
& callback
) {
769 user_write_buf_
= buf
;
770 user_write_buf_len_
= buf_len
;
772 int rv
= DoWriteLoop();
774 if (rv
== ERR_IO_PENDING
) {
775 user_write_callback_
= callback
;
778 was_ever_used_
= true;
779 user_write_buf_
= NULL
;
780 user_write_buf_len_
= 0;
786 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
787 return transport_
->socket()->SetReceiveBufferSize(size
);
790 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
791 return transport_
->socket()->SetSendBufferSize(size
);
794 int SSLClientSocketOpenSSL::Init() {
796 DCHECK(!transport_bio_
);
798 SSLContext
* context
= SSLContext::GetInstance();
799 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
801 ssl_
= SSL_new(context
->ssl_ctx());
802 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
803 return ERR_UNEXPECTED
;
805 // SNI should only contain valid DNS hostnames, not IP addresses (see RFC
808 // TODO(rsleevi): Should this code allow hostnames that violate the LDH rule?
809 // See https://crbug.com/496472 and https://crbug.com/496468 for discussion.
810 IPAddressNumber unused
;
811 if (!ParseIPLiteralToNumber(host_and_port_
.host(), &unused
) &&
812 !SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str())) {
813 return ERR_UNEXPECTED
;
816 SSL_SESSION
* session
= context
->session_cache()->Lookup(GetSessionCacheKey());
817 if (session
!= nullptr)
818 SSL_set_session(ssl_
, session
);
820 send_buffer_
= new GrowableIOBuffer();
821 send_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
822 recv_buffer_
= new GrowableIOBuffer();
823 recv_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
827 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
828 if (!BIO_new_bio_pair_external_buf(
829 &ssl_bio
, send_buffer_
->capacity(),
830 reinterpret_cast<uint8_t*>(send_buffer_
->data()), &transport_bio_
,
831 recv_buffer_
->capacity(),
832 reinterpret_cast<uint8_t*>(recv_buffer_
->data())))
833 return ERR_UNEXPECTED
;
835 DCHECK(transport_bio_
);
837 // Install a callback on OpenSSL's end to plumb transport errors through.
838 BIO_set_callback(ssl_bio
, &SSLClientSocketOpenSSL::BIOCallback
);
839 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
841 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
843 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_min
);
844 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_max
);
845 SSL_set_min_version(ssl_
, ssl_config_
.version_min
);
846 SSL_set_max_version(ssl_
, ssl_config_
.version_max
);
848 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
849 // set everything we care about to an absolute value.
850 SslSetClearMask options
;
851 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
853 // TODO(joth): Set this conditionally, see http://crbug.com/55410
854 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
856 SSL_set_options(ssl_
, options
.set_mask
);
857 SSL_clear_options(ssl_
, options
.clear_mask
);
859 // Same as above, this time for the SSL mode.
860 SslSetClearMask mode
;
862 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
863 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
865 mode
.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START
,
866 ssl_config_
.false_start_enabled
);
868 mode
.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV
, ssl_config_
.version_fallback
);
870 SSL_set_mode(ssl_
, mode
.set_mask
);
871 SSL_clear_mode(ssl_
, mode
.clear_mask
);
873 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
874 // textual name with SSL_set_cipher_list because there is no public API to
875 // directly remove a cipher by ID.
876 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
878 // See SSLConfig::disabled_cipher_suites for description of the suites
879 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
880 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
881 // as the handshake hash.
882 std::string
command("DEFAULT:!SHA256:!SHA384:!AESGCM+AES256:!aPSK");
883 // Walk through all the installed ciphers, seeing if any need to be
884 // appended to the cipher removal |command|.
885 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
886 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
887 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
888 bool disable
= false;
889 if (ssl_config_
.require_ecdhe
) {
890 base::StringPiece
kx_name(SSL_CIPHER_get_kx_name(cipher
));
891 disable
= kx_name
!= "ECDHE_RSA" && kx_name
!= "ECDHE_ECDSA";
894 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
895 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
896 ssl_config_
.disabled_cipher_suites
.end();
899 const char* name
= SSL_CIPHER_get_name(cipher
);
900 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
901 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
902 command
.append(":!");
903 command
.append(name
);
907 if (!ssl_config_
.enable_deprecated_cipher_suites
)
908 command
.append(":!RC4");
910 // Disable ECDSA cipher suites on platforms that do not support ECDSA
911 // signed certificates, as servers may use the presence of such
912 // ciphersuites as a hint to send an ECDSA certificate.
914 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
915 command
.append(":!ECDSA");
918 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
919 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
920 // This will almost certainly result in the socket failing to complete the
921 // handshake at which point the appropriate error is bubbled up to the client.
922 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
926 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
927 SSL_enable_tls_channel_id(ssl_
);
930 if (!ssl_config_
.next_protos
.empty()) {
931 // Get list of ciphers that are enabled.
932 STACK_OF(SSL_CIPHER
)* enabled_ciphers
= SSL_get_ciphers(ssl_
);
933 DCHECK(enabled_ciphers
);
934 std::vector
<uint16
> enabled_ciphers_vector
;
935 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(enabled_ciphers
); ++i
) {
936 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(enabled_ciphers
, i
);
937 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
938 enabled_ciphers_vector
.push_back(id
);
941 std::vector
<uint8_t> wire_protos
=
942 SerializeNextProtos(ssl_config_
.next_protos
,
943 HasCipherAdequateForHTTP2(enabled_ciphers_vector
) &&
944 IsTLSVersionAdequateForHTTP2(ssl_config_
));
945 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
949 if (ssl_config_
.signed_cert_timestamps_enabled
) {
950 SSL_enable_signed_cert_timestamps(ssl_
);
951 SSL_enable_ocsp_stapling(ssl_
);
954 if (cert_verifier_
->SupportsOCSPStapling())
955 SSL_enable_ocsp_stapling(ssl_
);
957 // Enable fastradio padding.
958 SSL_enable_fastradio_padding(ssl_
,
959 ssl_config_
.fastradio_padding_enabled
&&
960 ssl_config_
.fastradio_padding_eligible
);
962 // By default, renegotiations are rejected. After the initial handshake
963 // completes, some application protocols may re-enable it.
964 SSL_set_reject_peer_renegotiations(ssl_
, 1);
969 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
970 // Since Run may result in Read being called, clear |user_read_callback_|
973 was_ever_used_
= true;
974 user_read_buf_
= NULL
;
975 user_read_buf_len_
= 0;
976 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
979 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
980 // Since Run may result in Write being called, clear |user_write_callback_|
983 was_ever_used_
= true;
984 user_write_buf_
= NULL
;
985 user_write_buf_len_
= 0;
986 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
989 bool SSLClientSocketOpenSSL::DoTransportIO() {
990 bool network_moved
= false;
992 // Read and write as much data as possible. The loop is necessary because
993 // Write() may return synchronously.
996 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
997 network_moved
= true;
999 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
1000 network_moved
= true;
1001 return network_moved
;
1004 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
1005 // g_first_run_completed once crbug.com/424386 is fixed.
1006 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
1007 LAZY_INSTANCE_INITIALIZER
;
1009 int SSLClientSocketOpenSSL::DoHandshake() {
1010 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1014 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
1016 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
1017 rv
= SSL_do_handshake(ssl_
);
1019 if (g_first_run_completed
.Get().Get()) {
1020 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
1022 tracked_objects::ScopedTracker
tracking_profile(
1023 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
1025 rv
= SSL_do_handshake(ssl_
);
1027 g_first_run_completed
.Get().Set(true);
1028 rv
= SSL_do_handshake(ssl_
);
1034 int ssl_error
= SSL_get_error(ssl_
, rv
);
1035 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
1036 // The server supports channel ID. Stop to look one up before returning to
1038 GotoState(STATE_CHANNEL_ID_LOOKUP
);
1041 if (ssl_error
== SSL_ERROR_WANT_X509_LOOKUP
&&
1042 !ssl_config_
.send_client_cert
) {
1043 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1045 if (ssl_error
== SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
) {
1046 DCHECK(private_key_
);
1047 DCHECK_NE(kNoPendingResult
, signature_result_
);
1048 GotoState(STATE_HANDSHAKE
);
1049 return ERR_IO_PENDING
;
1052 OpenSSLErrorInfo error_info
;
1053 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
1054 if (net_error
== ERR_IO_PENDING
) {
1055 // If not done, stay in this state
1056 GotoState(STATE_HANDSHAKE
);
1057 return ERR_IO_PENDING
;
1060 LOG(ERROR
) << "handshake failed; returned " << rv
<< ", SSL error code "
1061 << ssl_error
<< ", net_error " << net_error
;
1063 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1064 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1066 // Classify the handshake failure. This is used to determine causes of the
1067 // TLS version fallback.
1069 // |cipher| is the current outgoing cipher suite, so it is non-null iff
1070 // ChangeCipherSpec was sent.
1071 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
1072 if (SSL_get_state(ssl_
) == SSL3_ST_CR_SRVR_HELLO_A
) {
1073 ssl_failure_state_
= SSL_FAILURE_CLIENT_HELLO
;
1074 } else if (cipher
&& (SSL_CIPHER_get_id(cipher
) ==
1075 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256
||
1076 SSL_CIPHER_get_id(cipher
) ==
1077 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256
)) {
1078 ssl_failure_state_
= SSL_FAILURE_BUGGY_GCM
;
1079 } else if (cipher
&& ssl_config_
.send_client_cert
) {
1080 ssl_failure_state_
= SSL_FAILURE_CLIENT_AUTH
;
1081 } else if (ERR_GET_LIB(error_info
.error_code
) == ERR_LIB_SSL
&&
1082 ERR_GET_REASON(error_info
.error_code
) ==
1083 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED
) {
1084 ssl_failure_state_
= SSL_FAILURE_SESSION_MISMATCH
;
1085 } else if (cipher
&& npn_status_
!= kNextProtoUnsupported
) {
1086 ssl_failure_state_
= SSL_FAILURE_NEXT_PROTO
;
1088 ssl_failure_state_
= SSL_FAILURE_UNKNOWN
;
1092 GotoState(STATE_HANDSHAKE_COMPLETE
);
1096 int SSLClientSocketOpenSSL::DoHandshakeComplete(int result
) {
1100 if (ssl_config_
.version_fallback
&&
1101 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
1102 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
1105 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1106 if (npn_status_
== kNextProtoUnsupported
) {
1107 const uint8_t* alpn_proto
= NULL
;
1108 unsigned alpn_len
= 0;
1109 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
1111 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
1112 npn_status_
= kNextProtoNegotiated
;
1113 set_negotiation_extension(kExtensionALPN
);
1117 RecordNegotiationExtension();
1118 RecordChannelIDSupport(channel_id_service_
, channel_id_sent_
,
1119 ssl_config_
.channel_id_enabled
,
1120 crypto::ECPrivateKey::IsSupported());
1122 // Only record OCSP histograms if OCSP was requested.
1123 if (ssl_config_
.signed_cert_timestamps_enabled
||
1124 cert_verifier_
->SupportsOCSPStapling()) {
1125 const uint8_t* ocsp_response
;
1126 size_t ocsp_response_len
;
1127 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
1129 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
1130 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
1133 const uint8_t* sct_list
;
1134 size_t sct_list_len
;
1135 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
1136 set_signed_cert_timestamps_received(sct_list_len
!= 0);
1138 if (IsRenegotiationAllowed())
1139 SSL_set_reject_peer_renegotiations(ssl_
, 0);
1141 // Verify the certificate.
1143 GotoState(STATE_VERIFY_CERT
);
1147 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1148 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
);
1149 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1150 return channel_id_service_
->GetOrCreateChannelID(
1151 host_and_port_
.host(), &channel_id_key_
,
1152 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1153 base::Unretained(this)),
1154 &channel_id_request_
);
1157 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1161 if (!channel_id_key_
) {
1162 LOG(ERROR
) << "Failed to import Channel ID.";
1163 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1166 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1168 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1169 int rv
= SSL_set1_tls_channel_id(ssl_
, channel_id_key_
->key());
1171 LOG(ERROR
) << "Failed to set Channel ID.";
1172 int err
= SSL_get_error(ssl_
, rv
);
1173 return MapOpenSSLError(err
, err_tracer
);
1176 // Return to the handshake.
1177 channel_id_sent_
= true;
1178 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
);
1179 GotoState(STATE_HANDSHAKE
);
1183 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1184 DCHECK(!server_cert_chain_
->empty());
1185 DCHECK(start_cert_verification_time_
.is_null());
1187 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1189 // If the certificate is bad and has been previously accepted, use
1190 // the previous status and bypass the error.
1191 base::StringPiece der_cert
;
1192 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1194 return ERR_CERT_INVALID
;
1196 CertStatus cert_status
;
1197 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1198 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1199 server_cert_verify_result_
.Reset();
1200 server_cert_verify_result_
.cert_status
= cert_status
;
1201 server_cert_verify_result_
.verified_cert
= server_cert_
;
1205 // When running in a sandbox, it may not be possible to create an
1206 // X509Certificate*, as that may depend on OS functionality blocked
1208 if (!server_cert_
.get()) {
1209 server_cert_verify_result_
.Reset();
1210 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
1211 return ERR_CERT_INVALID
;
1214 std::string ocsp_response
;
1215 if (cert_verifier_
->SupportsOCSPStapling()) {
1216 const uint8_t* ocsp_response_raw
;
1217 size_t ocsp_response_len
;
1218 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1219 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1223 start_cert_verification_time_
= base::TimeTicks::Now();
1225 return cert_verifier_
->Verify(
1226 server_cert_
.get(), host_and_port_
.host(), ocsp_response
,
1227 ssl_config_
.GetCertVerifyFlags(),
1228 // TODO(davidben): Route the CRLSet through SSLConfig so
1229 // SSLClientSocket doesn't depend on SSLConfigService.
1230 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_
,
1231 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1232 base::Unretained(this)),
1233 &cert_verifier_request_
, net_log_
);
1236 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1237 cert_verifier_request_
.reset();
1239 if (!start_cert_verification_time_
.is_null()) {
1240 base::TimeDelta verify_time
=
1241 base::TimeTicks::Now() - start_cert_verification_time_
;
1243 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1245 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1250 if (SSL_session_reused(ssl_
)) {
1251 // Record whether or not the server tried to resume a session for a
1252 // different version. See https://crbug.com/441456.
1253 UMA_HISTOGRAM_BOOLEAN(
1254 "Net.SSLSessionVersionMatch",
1255 SSL_version(ssl_
) == SSL_get_session(ssl_
)->ssl_version
);
1259 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1260 if (transport_security_state_
&&
1262 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1263 !transport_security_state_
->CheckPublicKeyPins(
1264 host_and_port_
.host(),
1265 server_cert_verify_result_
.is_issued_by_known_root
,
1266 server_cert_verify_result_
.public_key_hashes
,
1267 &pinning_failure_log_
)) {
1268 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1272 // Only check Certificate Transparency if there were no other errors with
1276 DCHECK(!certificate_verified_
);
1277 certificate_verified_
= true;
1278 MaybeCacheSession();
1280 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1281 << " (" << result
<< ")";
1284 completed_connect_
= true;
1285 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1286 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1290 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1291 if (!user_connect_callback_
.is_null()) {
1292 CompletionCallback c
= user_connect_callback_
;
1293 user_connect_callback_
.Reset();
1294 c
.Run(rv
> OK
? OK
: rv
);
1298 void SSLClientSocketOpenSSL::UpdateServerCert() {
1299 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1300 server_cert_
= server_cert_chain_
->AsOSChain();
1301 if (server_cert_
.get()) {
1303 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
1304 base::Bind(&NetLogX509CertificateCallback
,
1305 base::Unretained(server_cert_
.get())));
1309 void SSLClientSocketOpenSSL::VerifyCT() {
1310 if (!cert_transparency_verifier_
)
1313 const uint8_t* ocsp_response_raw
;
1314 size_t ocsp_response_len
;
1315 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1316 std::string ocsp_response
;
1317 if (ocsp_response_len
> 0) {
1318 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1322 const uint8_t* sct_list_raw
;
1323 size_t sct_list_len
;
1324 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1325 std::string sct_list
;
1326 if (sct_list_len
> 0)
1327 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1329 // Note that this is a completely synchronous operation: The CT Log Verifier
1330 // gets all the data it needs for SCT verification and does not do any
1331 // external communication.
1332 cert_transparency_verifier_
->Verify(
1333 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1334 &ct_verify_result_
, net_log_
);
1336 if (policy_enforcer_
&&
1337 (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
)) {
1338 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1339 SSLConfigService::GetEVCertsWhitelist();
1340 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1341 server_cert_verify_result_
.verified_cert
.get(), ev_whitelist
.get(),
1342 ct_verify_result_
, net_log_
)) {
1343 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1344 VLOG(1) << "EV certificate for "
1345 << server_cert_verify_result_
.verified_cert
->subject()
1347 << " does not conform to CT policy, removing EV status.";
1348 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1353 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1354 int rv
= DoHandshakeLoop(result
);
1355 if (rv
!= ERR_IO_PENDING
) {
1356 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1357 DoConnectCallback(rv
);
1361 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1362 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1363 // In handshake phase.
1364 OnHandshakeIOComplete(result
);
1368 // During a renegotiation, a Read call may also be blocked on a transport
1369 // write, so retry both operations.
1370 PumpReadWriteEvents();
1373 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1374 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1375 // In handshake phase.
1376 OnHandshakeIOComplete(result
);
1380 // Network layer received some data, check if client requested to read
1382 if (!user_read_buf_
.get())
1385 int rv
= DoReadLoop();
1386 if (rv
!= ERR_IO_PENDING
)
1390 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1391 int rv
= last_io_result
;
1393 // Default to STATE_NONE for next state.
1394 // (This is a quirk carried over from the windows
1395 // implementation. It makes reading the logs a bit harder.)
1396 // State handlers can and often do call GotoState just
1397 // to stay in the current state.
1398 State state
= next_handshake_state_
;
1399 GotoState(STATE_NONE
);
1401 case STATE_HANDSHAKE
:
1404 case STATE_HANDSHAKE_COMPLETE
:
1405 rv
= DoHandshakeComplete(rv
);
1407 case STATE_CHANNEL_ID_LOOKUP
:
1409 rv
= DoChannelIDLookup();
1411 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1412 rv
= DoChannelIDLookupComplete(rv
);
1414 case STATE_VERIFY_CERT
:
1416 rv
= DoVerifyCert(rv
);
1418 case STATE_VERIFY_CERT_COMPLETE
:
1419 rv
= DoVerifyCertComplete(rv
);
1423 rv
= ERR_UNEXPECTED
;
1424 NOTREACHED() << "unexpected state" << state
;
1428 bool network_moved
= DoTransportIO();
1429 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1430 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1431 // special case we keep looping even if rv is ERR_IO_PENDING because
1432 // the transport IO may allow DoHandshake to make progress.
1433 rv
= OK
; // This causes us to stay in the loop.
1435 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1439 int SSLClientSocketOpenSSL::DoReadLoop() {
1443 rv
= DoPayloadRead();
1444 network_moved
= DoTransportIO();
1445 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1450 int SSLClientSocketOpenSSL::DoWriteLoop() {
1454 rv
= DoPayloadWrite();
1455 network_moved
= DoTransportIO();
1456 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1461 int SSLClientSocketOpenSSL::DoPayloadRead() {
1462 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1464 DCHECK_LT(0, user_read_buf_len_
);
1465 DCHECK(user_read_buf_
.get());
1468 if (pending_read_error_
!= kNoPendingResult
) {
1469 rv
= pending_read_error_
;
1470 pending_read_error_
= kNoPendingResult
;
1472 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1473 rv
, user_read_buf_
->data());
1476 NetLog::TYPE_SSL_READ_ERROR
,
1477 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1478 pending_read_error_info_
));
1480 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1481 pending_read_error_info_
= OpenSSLErrorInfo();
1485 int total_bytes_read
= 0;
1488 ssl_ret
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1489 user_read_buf_len_
- total_bytes_read
);
1491 total_bytes_read
+= ssl_ret
;
1492 } while (total_bytes_read
< user_read_buf_len_
&& ssl_ret
> 0);
1494 // Although only the final SSL_read call may have failed, the failure needs to
1495 // processed immediately, while the information still available in OpenSSL's
1498 // A zero return from SSL_read may mean any of:
1499 // - The underlying BIO_read returned 0.
1500 // - The peer sent a close_notify.
1501 // - Any arbitrary error. https://crbug.com/466303
1503 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1504 // error, so it does not occur. The second and third are distinguished by
1505 // SSL_ERROR_ZERO_RETURN.
1506 pending_read_ssl_error_
= SSL_get_error(ssl_
, ssl_ret
);
1507 if (pending_read_ssl_error_
== SSL_ERROR_ZERO_RETURN
) {
1508 pending_read_error_
= 0;
1509 } else if (pending_read_ssl_error_
== SSL_ERROR_WANT_X509_LOOKUP
&&
1510 !ssl_config_
.send_client_cert
) {
1511 pending_read_error_
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1512 } else if (pending_read_ssl_error_
==
1513 SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
) {
1514 DCHECK(private_key_
);
1515 DCHECK_NE(kNoPendingResult
, signature_result_
);
1516 pending_read_error_
= ERR_IO_PENDING
;
1518 pending_read_error_
= MapOpenSSLErrorWithDetails(
1519 pending_read_ssl_error_
, err_tracer
, &pending_read_error_info_
);
1522 // Many servers do not reliably send a close_notify alert when shutting down
1523 // a connection, and instead terminate the TCP connection. This is reported
1524 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1525 // graceful EOF, instead of treating it as an error as it should be.
1526 if (pending_read_error_
== ERR_CONNECTION_CLOSED
)
1527 pending_read_error_
= 0;
1530 if (total_bytes_read
> 0) {
1531 // Return any bytes read to the caller. The error will be deferred to the
1532 // next call of DoPayloadRead.
1533 rv
= total_bytes_read
;
1535 // Do not treat insufficient data as an error to return in the next call to
1536 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1537 // again. This is because DoTransportIO() may complete in between the next
1538 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1539 // subsequent invocations to see if a complete record may now be read.
1540 if (pending_read_error_
== ERR_IO_PENDING
)
1541 pending_read_error_
= kNoPendingResult
;
1543 // No bytes were returned. Return the pending read error immediately.
1544 DCHECK_NE(kNoPendingResult
, pending_read_error_
);
1545 rv
= pending_read_error_
;
1546 pending_read_error_
= kNoPendingResult
;
1550 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1551 user_read_buf_
->data());
1552 } else if (rv
!= ERR_IO_PENDING
) {
1554 NetLog::TYPE_SSL_READ_ERROR
,
1555 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1556 pending_read_error_info_
));
1557 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1558 pending_read_error_info_
= OpenSSLErrorInfo();
1563 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1564 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1565 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1568 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1569 user_write_buf_
->data());
1573 int ssl_error
= SSL_get_error(ssl_
, rv
);
1574 if (ssl_error
== SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
)
1575 return ERR_IO_PENDING
;
1576 OpenSSLErrorInfo error_info
;
1577 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1580 if (net_error
!= ERR_IO_PENDING
) {
1582 NetLog::TYPE_SSL_WRITE_ERROR
,
1583 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1588 void SSLClientSocketOpenSSL::PumpReadWriteEvents() {
1589 int rv_read
= ERR_IO_PENDING
;
1590 int rv_write
= ERR_IO_PENDING
;
1593 if (user_read_buf_
.get())
1594 rv_read
= DoPayloadRead();
1595 if (user_write_buf_
.get())
1596 rv_write
= DoPayloadWrite();
1597 network_moved
= DoTransportIO();
1598 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1599 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1601 // Performing the Read callback may cause |this| to be deleted. If this
1602 // happens, the Write callback should not be invoked. Guard against this by
1603 // holding a WeakPtr to |this| and ensuring it's still valid.
1604 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1605 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1606 DoReadCallback(rv_read
);
1611 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1612 DoWriteCallback(rv_write
);
1615 int SSLClientSocketOpenSSL::BufferSend(void) {
1616 if (transport_send_busy_
)
1617 return ERR_IO_PENDING
;
1619 size_t buffer_read_offset
;
1622 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1623 &buffer_read_offset
, &max_read
);
1624 DCHECK_EQ(status
, 1); // Should never fail.
1626 return 0; // Nothing pending in the OpenSSL write BIO.
1627 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1628 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1629 send_buffer_
->set_offset(buffer_read_offset
);
1631 int rv
= transport_
->socket()->Write(
1632 send_buffer_
.get(), max_read
,
1633 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1634 base::Unretained(this)));
1635 if (rv
== ERR_IO_PENDING
) {
1636 transport_send_busy_
= true;
1638 TransportWriteComplete(rv
);
1643 int SSLClientSocketOpenSSL::BufferRecv(void) {
1644 if (transport_recv_busy_
)
1645 return ERR_IO_PENDING
;
1647 // Determine how much was requested from |transport_bio_| that was not
1648 // actually available.
1649 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1650 if (requested
== 0) {
1651 // This is not a perfect match of error codes, as no operation is
1652 // actually pending. However, returning 0 would be interpreted as
1653 // a possible sign of EOF, which is also an inappropriate match.
1654 return ERR_IO_PENDING
;
1657 // Known Issue: While only reading |requested| data is the more correct
1658 // implementation, it has the downside of resulting in frequent reads:
1659 // One read for the SSL record header (~5 bytes) and one read for the SSL
1660 // record body. Rather than issuing these reads to the underlying socket
1661 // (and constantly allocating new IOBuffers), a single Read() request to
1662 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1663 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1664 // traffic, this over-subscribed Read()ing will not cause issues.
1666 size_t buffer_write_offset
;
1669 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1670 &buffer_write_offset
, &max_write
);
1671 DCHECK_EQ(status
, 1); // Should never fail.
1673 return ERR_IO_PENDING
;
1676 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1677 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1679 recv_buffer_
->set_offset(buffer_write_offset
);
1680 int rv
= transport_
->socket()->Read(
1683 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1684 base::Unretained(this)));
1685 if (rv
== ERR_IO_PENDING
) {
1686 transport_recv_busy_
= true;
1688 rv
= TransportReadComplete(rv
);
1693 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1694 TransportWriteComplete(result
);
1695 OnSendComplete(result
);
1698 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1699 result
= TransportReadComplete(result
);
1700 OnRecvComplete(result
);
1703 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1704 DCHECK(ERR_IO_PENDING
!= result
);
1705 int bytes_written
= 0;
1707 // Record the error. Save it to be reported in a future read or write on
1708 // transport_bio_'s peer.
1709 transport_write_error_
= result
;
1711 bytes_written
= result
;
1713 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1714 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1716 transport_send_busy_
= false;
1719 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1720 DCHECK(ERR_IO_PENDING
!= result
);
1721 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1722 // does not report success.
1724 result
= ERR_CONNECTION_CLOSED
;
1727 DVLOG(1) << "TransportReadComplete result " << result
;
1728 // Received an error. Save it to be reported in a future read on
1729 // transport_bio_'s peer.
1730 transport_read_error_
= result
;
1732 bytes_read
= result
;
1734 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1735 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1737 transport_recv_busy_
= false;
1741 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1742 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1743 DCHECK(ssl
== ssl_
);
1745 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1747 // Clear any currently configured certificates.
1748 SSL_certs_clear(ssl_
);
1751 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1752 LOG(WARNING
) << "Client auth is not supported";
1753 #else // !defined(OS_IOS)
1754 if (!ssl_config_
.send_client_cert
) {
1755 // First pass: we know that a client certificate is needed, but we do not
1756 // have one at hand.
1757 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1758 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1759 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1760 unsigned char* str
= NULL
;
1761 int length
= i2d_X509_NAME(ca_name
, &str
);
1762 cert_authorities_
.push_back(std::string(
1763 reinterpret_cast<const char*>(str
),
1764 static_cast<size_t>(length
)));
1768 const unsigned char* client_cert_types
;
1769 size_t num_client_cert_types
=
1770 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1771 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1772 cert_key_types_
.push_back(
1773 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1776 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1780 // Second pass: a client certificate should have been selected.
1781 if (ssl_config_
.client_cert
.get()) {
1782 ScopedX509 leaf_x509
=
1783 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1785 LOG(WARNING
) << "Failed to import certificate";
1786 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1790 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1791 ssl_config_
.client_cert
->GetIntermediateCertificates());
1793 LOG(WARNING
) << "Failed to import intermediate certificates";
1794 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1798 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1799 !SSL_set1_chain(ssl_
, chain
.get())) {
1800 LOG(WARNING
) << "Failed to set client certificate";
1804 #if defined(USE_OPENSSL_CERTS)
1805 // TODO(davidben): Move Android to the SSLPrivateKey codepath and disable
1806 // client auth on NaCl altogether.
1807 crypto::ScopedEVP_PKEY privkey
=
1808 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1809 ssl_config_
.client_cert
.get());
1811 // Could not find the private key. Fail the handshake and surface an
1812 // appropriate error to the caller.
1813 LOG(WARNING
) << "Client cert found without private key";
1814 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1817 if (!SSL_use_PrivateKey(ssl_
, privkey
.get())) {
1818 LOG(WARNING
) << "Failed to set private key";
1821 #else // !USE_OPENSSL_CERTS
1822 // TODO(davidben): Lift this call up to the embedder so we can actually test
1823 // this code. https://crbug.com/394131
1824 private_key_
= FetchClientCertPrivateKey(
1825 ssl_config_
.client_cert
.get(),
1826 g_platform_key_task_runner
.Get().task_runner());
1827 if (!private_key_
) {
1828 // Could not find the private key. Fail the handshake and surface an
1829 // appropriate error to the caller.
1830 LOG(WARNING
) << "Client cert found without private key";
1831 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1835 SSL_set_private_key_method(ssl_
, &SSLContext::kPrivateKeyMethod
);
1836 #endif // USE_OPENSSL_CERTS
1838 int cert_count
= 1 + sk_X509_num(chain
.get());
1839 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1840 NetLog::IntegerCallback("cert_count", cert_count
));
1843 #endif // defined(OS_IOS)
1845 // Send no client certificate.
1846 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1847 NetLog::IntegerCallback("cert_count", 0));
1851 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1852 if (!completed_connect_
) {
1853 // If the first handshake hasn't completed then we accept any certificates
1854 // because we verify after the handshake.
1858 // Disallow the server certificate to change in a renegotiation.
1859 if (server_cert_chain_
->empty()) {
1860 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1863 base::StringPiece old_der
, new_der
;
1864 if (store_ctx
->cert
== NULL
||
1865 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1866 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1867 LOG(ERROR
) << "Failed to encode certificates";
1870 if (old_der
!= new_der
) {
1871 LOG(ERROR
) << "Server certificate changed between handshakes";
1878 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1879 // server supports NPN, selects a protocol from the list that the server
1880 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1881 // callback can assume that |in| is syntactically valid.
1882 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1883 unsigned char* outlen
,
1884 const unsigned char* in
,
1885 unsigned int inlen
) {
1886 if (ssl_config_
.next_protos
.empty()) {
1887 *out
= reinterpret_cast<uint8
*>(
1888 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1889 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1890 npn_status_
= kNextProtoUnsupported
;
1891 return SSL_TLSEXT_ERR_OK
;
1894 // Assume there's no overlap between our protocols and the server's list.
1895 npn_status_
= kNextProtoNoOverlap
;
1897 // For each protocol in server preference order, see if we support it.
1898 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1899 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1900 const std::string proto
= NextProtoToString(next_proto
);
1901 if (in
[i
] == proto
.size() &&
1902 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1903 // We found a match.
1904 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1906 npn_status_
= kNextProtoNegotiated
;
1910 if (npn_status_
== kNextProtoNegotiated
)
1914 // If we didn't find a protocol, we select the first one from our list.
1915 if (npn_status_
== kNextProtoNoOverlap
) {
1916 // NextProtoToString returns a pointer to a static string.
1917 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1918 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1919 *outlen
= strlen(proto
);
1922 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1923 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1924 set_negotiation_extension(kExtensionNPN
);
1925 return SSL_TLSEXT_ERR_OK
;
1928 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1931 const char *argp
, int argi
, long argl
,
1933 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1934 // If there is no more data in the buffer, report any pending errors that
1935 // were observed. Note that both the readbuf and the writebuf are checked
1936 // for errors, since the application may have encountered a socket error
1937 // while writing that would otherwise not be reported until the application
1938 // attempted to write again - which it may never do. See
1939 // https://crbug.com/249848.
1940 if (transport_read_error_
!= OK
) {
1941 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1944 if (transport_write_error_
!= OK
) {
1945 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1948 } else if (cmd
== BIO_CB_WRITE
) {
1949 // Because of the write buffer, this reports a failure from the previous
1950 // write payload. If the current payload fails to write, the error will be
1951 // reported in a future write or read to |bio|.
1952 if (transport_write_error_
!= OK
) {
1953 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1961 long SSLClientSocketOpenSSL::BIOCallback(
1964 const char *argp
, int argi
, long argl
,
1966 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1967 BIO_get_callback_arg(bio
));
1969 return socket
->MaybeReplayTransportError(
1970 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1973 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1974 // Only cache the session once both a new session has been established and the
1975 // certificate has been verified. Due to False Start, these events may happen
1977 if (!session_pending_
|| !certificate_verified_
)
1980 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1981 SSL_get_session(ssl_
));
1982 session_pending_
= false;
1985 int SSLClientSocketOpenSSL::NewSessionCallback(SSL_SESSION
* session
) {
1986 DCHECK_EQ(session
, SSL_get_session(ssl_
));
1988 // Only sessions from the initial handshake get cached. Note this callback may
1989 // be signaled on abbreviated handshakes if the ticket was renewed.
1990 session_pending_
= true;
1991 MaybeCacheSession();
1993 // OpenSSL passes a reference to |session|, but the session cache does not
1994 // take this reference, so release it.
1995 SSL_SESSION_free(session
);
1999 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
2000 for (ct::SCTList::const_iterator iter
=
2001 ct_verify_result_
.verified_scts
.begin();
2002 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
2003 ssl_info
->signed_certificate_timestamps
.push_back(
2004 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
2006 for (ct::SCTList::const_iterator iter
=
2007 ct_verify_result_
.invalid_scts
.begin();
2008 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
2009 ssl_info
->signed_certificate_timestamps
.push_back(
2010 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
2012 for (ct::SCTList::const_iterator iter
=
2013 ct_verify_result_
.unknown_logs_scts
.begin();
2014 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
2015 ssl_info
->signed_certificate_timestamps
.push_back(
2016 SignedCertificateTimestampAndStatus(*iter
,
2017 ct::SCT_STATUS_LOG_UNKNOWN
));
2021 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
2022 std::string result
= host_and_port_
.ToString();
2024 result
.append(ssl_session_cache_shard_
);
2026 // Shard the session cache based on maximum protocol version. This causes
2027 // fallback connections to use a separate session cache.
2029 switch (ssl_config_
.version_max
) {
2030 case SSL_PROTOCOL_VERSION_TLS1
:
2031 result
.append("tls1");
2033 case SSL_PROTOCOL_VERSION_TLS1_1
:
2034 result
.append("tls1.1");
2036 case SSL_PROTOCOL_VERSION_TLS1_2
:
2037 result
.append("tls1.2");
2044 if (ssl_config_
.enable_deprecated_cipher_suites
)
2045 result
.append("deprecated");
2050 bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
2051 if (npn_status_
== kNextProtoUnsupported
)
2052 return ssl_config_
.renego_allowed_default
;
2054 NextProto next_proto
= NextProtoFromString(npn_proto_
);
2055 for (NextProto allowed
: ssl_config_
.renego_allowed_for_protos
) {
2056 if (next_proto
== allowed
)
2062 int SSLClientSocketOpenSSL::PrivateKeyTypeCallback() {
2063 switch (private_key_
->GetType()) {
2064 case SSLPrivateKey::Type::RSA
:
2065 return EVP_PKEY_RSA
;
2066 case SSLPrivateKey::Type::ECDSA
:
2070 return EVP_PKEY_NONE
;
2073 int SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback(const EVP_MD
* md
) {
2074 SSLPrivateKey::Hash hash
;
2075 return EVP_MDToPrivateKeyHash(md
, &hash
) && private_key_
->SupportsHash(hash
);
2078 size_t SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback() {
2079 return private_key_
->GetMaxSignatureLengthInBytes();
2082 ssl_private_key_result_t
SSLClientSocketOpenSSL::PrivateKeySignCallback(
2089 DCHECK_EQ(kNoPendingResult
, signature_result_
);
2090 DCHECK(signature_
.empty());
2091 DCHECK(private_key_
);
2093 net_log_
.BeginEvent(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION
);
2095 SSLPrivateKey::Hash hash
;
2096 if (!EVP_MDToPrivateKeyHash(md
, &hash
)) {
2097 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
2098 return ssl_private_key_failure
;
2101 signature_result_
= ERR_IO_PENDING
;
2102 private_key_
->SignDigest(
2103 hash
, base::StringPiece(reinterpret_cast<const char*>(in
), in_len
),
2104 base::Bind(&SSLClientSocketOpenSSL::OnPrivateKeySignComplete
,
2105 weak_factory_
.GetWeakPtr()));
2106 return ssl_private_key_retry
;
2109 ssl_private_key_result_t
SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback(
2113 DCHECK_NE(kNoPendingResult
, signature_result_
);
2114 DCHECK(private_key_
);
2116 if (signature_result_
== ERR_IO_PENDING
)
2117 return ssl_private_key_retry
;
2118 if (signature_result_
!= OK
) {
2119 OpenSSLPutNetError(FROM_HERE
, signature_result_
);
2120 return ssl_private_key_failure
;
2122 if (signature_
.size() > max_out
) {
2123 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
2124 return ssl_private_key_failure
;
2126 memcpy(out
, vector_as_array(&signature_
), signature_
.size());
2127 *out_len
= signature_
.size();
2129 return ssl_private_key_success
;
2132 void SSLClientSocketOpenSSL::OnPrivateKeySignComplete(
2134 const std::vector
<uint8_t>& signature
) {
2135 DCHECK_EQ(ERR_IO_PENDING
, signature_result_
);
2136 DCHECK(signature_
.empty());
2137 DCHECK(private_key_
);
2139 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION
,
2142 signature_result_
= error
;
2143 if (signature_result_
== OK
)
2144 signature_
= signature
;
2146 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2147 OnHandshakeIOComplete(signature_result_
);
2151 // During a renegotiation, either Read or Write calls may be blocked on an
2152 // asynchronous private key operation.
2153 PumpReadWriteEvents();