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"
55 #include "net/ssl/ssl_platform_key.h"
62 // Enable this to see logging for state machine state transitions.
64 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
65 " jump to state " << s; \
66 next_handshake_state_ = s; } while (0)
68 #define GotoState(s) next_handshake_state_ = s
71 // This constant can be any non-negative/non-zero value (eg: it does not
72 // overlap with any value of the net::Error range, including net::OK).
73 const int kNoPendingResult
= 1;
75 // If a client doesn't have a list of protocols that it supports, but
76 // the server supports NPN, choosing "http/1.1" is the best answer.
77 const char kDefaultSupportedNPNProtocol
[] = "http/1.1";
79 // Default size of the internal BoringSSL buffers.
80 const int KDefaultOpenSSLBufferSize
= 17 * 1024;
82 void FreeX509Stack(STACK_OF(X509
)* ptr
) {
83 sk_X509_pop_free(ptr
, X509_free
);
86 using ScopedX509Stack
= crypto::ScopedOpenSSL
<STACK_OF(X509
), FreeX509Stack
>;
88 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
89 // This method doesn't seem to have made it into the OpenSSL headers.
90 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER
* cipher
) { return cipher
->id
; }
93 // Used for encoding the |connection_status| field of an SSLInfo object.
94 int EncodeSSLConnectionStatus(uint16 cipher_suite
,
98 ((compression
& SSL_CONNECTION_COMPRESSION_MASK
) <<
99 SSL_CONNECTION_COMPRESSION_SHIFT
) |
100 ((version
& SSL_CONNECTION_VERSION_MASK
) <<
101 SSL_CONNECTION_VERSION_SHIFT
);
104 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
105 // this SSL connection.
106 int GetNetSSLVersion(SSL
* ssl
) {
107 switch (SSL_version(ssl
)) {
109 return SSL_CONNECTION_VERSION_TLS1
;
111 return SSL_CONNECTION_VERSION_TLS1_1
;
113 return SSL_CONNECTION_VERSION_TLS1_2
;
116 return SSL_CONNECTION_VERSION_UNKNOWN
;
120 ScopedX509
OSCertHandleToOpenSSL(
121 X509Certificate::OSCertHandle os_handle
) {
122 #if defined(USE_OPENSSL_CERTS)
123 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle
));
124 #else // !defined(USE_OPENSSL_CERTS)
125 std::string der_encoded
;
126 if (!X509Certificate::GetDEREncoded(os_handle
, &der_encoded
))
128 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
129 return ScopedX509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
130 #endif // defined(USE_OPENSSL_CERTS)
133 ScopedX509Stack
OSCertHandlesToOpenSSL(
134 const X509Certificate::OSCertHandles
& os_handles
) {
135 ScopedX509Stack
stack(sk_X509_new_null());
136 for (size_t i
= 0; i
< os_handles
.size(); i
++) {
137 ScopedX509 x509
= OSCertHandleToOpenSSL(os_handles
[i
]);
139 return ScopedX509Stack();
140 sk_X509_push(stack
.get(), x509
.release());
145 int LogErrorCallback(const char* str
, size_t len
, void* context
) {
146 LOG(ERROR
) << base::StringPiece(str
, len
);
150 bool EVP_MDToPrivateKeyHash(const EVP_MD
* md
, SSLPrivateKey::Hash
* hash
) {
151 switch (EVP_MD_type(md
)) {
153 *hash
= SSLPrivateKey::Hash::MD5_SHA1
;
156 *hash
= SSLPrivateKey::Hash::SHA1
;
159 *hash
= SSLPrivateKey::Hash::SHA256
;
162 *hash
= SSLPrivateKey::Hash::SHA384
;
165 *hash
= SSLPrivateKey::Hash::SHA512
;
172 #if !defined(OS_NACL)
173 class PlatformKeyTaskRunner
{
175 PlatformKeyTaskRunner() {
176 // Serialize all the private key operations on a single background
177 // thread to avoid problems with buggy smartcards.
178 worker_pool_
= new base::SequencedWorkerPool(1, "Platform Key Thread");
179 task_runner_
= worker_pool_
->GetSequencedTaskRunnerWithShutdownBehavior(
180 worker_pool_
->GetSequenceToken(),
181 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN
);
184 scoped_refptr
<base::SequencedTaskRunner
> task_runner() {
189 scoped_refptr
<base::SequencedWorkerPool
> worker_pool_
;
190 scoped_refptr
<base::SequencedTaskRunner
> task_runner_
;
192 DISALLOW_COPY_AND_ASSIGN(PlatformKeyTaskRunner
);
195 base::LazyInstance
<PlatformKeyTaskRunner
>::Leaky g_platform_key_task_runner
=
196 LAZY_INSTANCE_INITIALIZER
;
201 class SSLClientSocketOpenSSL::SSLContext
{
203 static SSLContext
* GetInstance() {
204 return base::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 base::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
,
244 // Disable the internal session cache. Session caching is handled
245 // externally (i.e. by SSLClientSessionCacheOpenSSL).
246 SSL_CTX_set_session_cache_mode(
247 ssl_ctx_
.get(), SSL_SESS_CACHE_CLIENT
| SSL_SESS_CACHE_NO_INTERNAL
);
248 SSL_CTX_sess_set_new_cb(ssl_ctx_
.get(), NewSessionCallback
);
250 scoped_ptr
<base::Environment
> env(base::Environment::Create());
251 std::string ssl_keylog_file
;
252 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
253 !ssl_keylog_file
.empty()) {
254 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
255 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
257 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
258 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
260 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
265 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
266 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
268 return socket
->ClientCertRequestCallback(ssl
);
271 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
272 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
273 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
274 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
277 return socket
->CertVerifyCallback(store_ctx
);
280 static int SelectNextProtoCallback(SSL
* ssl
,
281 unsigned char** out
, unsigned char* outlen
,
282 const unsigned char* in
,
283 unsigned int inlen
, void* arg
) {
284 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
285 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
288 static int NewSessionCallback(SSL
* ssl
, SSL_SESSION
* session
) {
289 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
290 return socket
->NewSessionCallback(session
);
293 static int PrivateKeyTypeCallback(SSL
* ssl
) {
294 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
295 return socket
->PrivateKeyTypeCallback();
298 static int PrivateKeySupportsDigestCallback(SSL
* ssl
, const EVP_MD
* md
) {
299 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
300 return socket
->PrivateKeySupportsDigestCallback(md
);
303 static size_t PrivateKeyMaxSignatureLenCallback(SSL
* ssl
) {
304 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
305 return socket
->PrivateKeyMaxSignatureLenCallback();
308 static ssl_private_key_result_t
PrivateKeySignCallback(SSL
* ssl
,
315 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
316 return socket
->PrivateKeySignCallback(out
, out_len
, max_out
, md
, in
,
320 static ssl_private_key_result_t
PrivateKeySignCompleteCallback(
325 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
326 return socket
->PrivateKeySignCompleteCallback(out
, out_len
, max_out
);
329 // This is the index used with SSL_get_ex_data to retrieve the owner
330 // SSLClientSocketOpenSSL object from an SSL instance.
331 int ssl_socket_data_index_
;
333 ScopedSSL_CTX ssl_ctx_
;
335 // TODO(davidben): Use a separate cache per URLRequestContext.
336 // https://crbug.com/458365
338 // TODO(davidben): Sessions should be invalidated on fatal
339 // alerts. https://crbug.com/466352
340 SSLClientSessionCacheOpenSSL session_cache_
;
343 const SSL_PRIVATE_KEY_METHOD
344 SSLClientSocketOpenSSL::SSLContext::kPrivateKeyMethod
= {
345 &SSLClientSocketOpenSSL::SSLContext::PrivateKeyTypeCallback
,
346 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySupportsDigestCallback
,
347 &SSLClientSocketOpenSSL::SSLContext::PrivateKeyMaxSignatureLenCallback
,
348 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySignCallback
,
349 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySignCompleteCallback
,
352 // PeerCertificateChain is a helper object which extracts the certificate
353 // chain, as given by the server, from an OpenSSL socket and performs the needed
354 // resource management. The first element of the chain is the leaf certificate
355 // and the other elements are in the order given by the server.
356 class SSLClientSocketOpenSSL::PeerCertificateChain
{
358 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
359 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
360 ~PeerCertificateChain() {}
361 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
363 // Resets the PeerCertificateChain to the set of certificates in|chain|,
364 // which may be NULL, indicating to empty the store certificates.
365 // Note: If an error occurs, such as being unable to parse the certificates,
366 // this will behave as if Reset(NULL) was called.
367 void Reset(STACK_OF(X509
)* chain
);
369 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
370 scoped_refptr
<X509Certificate
> AsOSChain() const;
372 size_t size() const {
373 if (!openssl_chain_
.get())
375 return sk_X509_num(openssl_chain_
.get());
382 X509
* Get(size_t index
) const {
383 DCHECK_LT(index
, size());
384 return sk_X509_value(openssl_chain_
.get(), index
);
388 ScopedX509Stack openssl_chain_
;
391 SSLClientSocketOpenSSL::PeerCertificateChain
&
392 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
393 const PeerCertificateChain
& other
) {
397 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
401 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
402 STACK_OF(X509
)* chain
) {
403 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
406 scoped_refptr
<X509Certificate
>
407 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
408 #if defined(USE_OPENSSL_CERTS)
409 // When OSCertHandle is typedef'ed to X509, this implementation does a short
410 // cut to avoid converting back and forth between DER and the X509 struct.
411 X509Certificate::OSCertHandles intermediates
;
412 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
413 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
416 return make_scoped_refptr(X509Certificate::CreateFromHandle(
417 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
419 // DER-encode the chain and convert to a platform certificate handle.
420 std::vector
<base::StringPiece
> der_chain
;
421 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
422 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
423 base::StringPiece der
;
424 if (!x509_util::GetDER(x
, &der
))
426 der_chain
.push_back(der
);
429 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
434 void SSLClientSocket::ClearSessionCache() {
435 SSLClientSocketOpenSSL::SSLContext
* context
=
436 SSLClientSocketOpenSSL::SSLContext::GetInstance();
437 context
->session_cache()->Flush();
441 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
442 return SSL_PROTOCOL_VERSION_TLS1_2
;
445 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
446 scoped_ptr
<ClientSocketHandle
> transport_socket
,
447 const HostPortPair
& host_and_port
,
448 const SSLConfig
& ssl_config
,
449 const SSLClientSocketContext
& context
)
450 : transport_send_busy_(false),
451 transport_recv_busy_(false),
452 pending_read_error_(kNoPendingResult
),
453 pending_read_ssl_error_(SSL_ERROR_NONE
),
454 transport_read_error_(OK
),
455 transport_write_error_(OK
),
456 server_cert_chain_(new PeerCertificateChain(NULL
)),
457 completed_connect_(false),
458 was_ever_used_(false),
459 cert_verifier_(context
.cert_verifier
),
460 cert_transparency_verifier_(context
.cert_transparency_verifier
),
461 channel_id_service_(context
.channel_id_service
),
463 transport_bio_(NULL
),
464 transport_(transport_socket
.Pass()),
465 host_and_port_(host_and_port
),
466 ssl_config_(ssl_config
),
467 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
468 next_handshake_state_(STATE_NONE
),
469 disconnected_(false),
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 // Although StreamSocket does allow calling Connect() after Disconnect(),
544 // this has never worked for layered sockets. CHECK to detect any consumers
545 // reconnecting an SSL socket.
547 // TODO(davidben,mmenke): Remove this API feature. See
548 // https://crbug.com/499289.
549 CHECK(!disconnected_
);
551 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
553 // Set up new ssl object.
556 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
560 // Set SSL to client mode. Handshake happens in the loop below.
561 SSL_set_connect_state(ssl_
);
563 GotoState(STATE_HANDSHAKE
);
564 rv
= DoHandshakeLoop(OK
);
565 if (rv
== ERR_IO_PENDING
) {
566 user_connect_callback_
= callback
;
568 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
571 return rv
> OK
? OK
: rv
;
574 void SSLClientSocketOpenSSL::Disconnect() {
576 // Calling SSL_shutdown prevents the session from being marked as
582 if (transport_bio_
) {
583 BIO_free_all(transport_bio_
);
584 transport_bio_
= NULL
;
587 disconnected_
= true;
589 // Shut down anything that may call us back.
590 cert_verifier_request_
.reset();
591 transport_
->socket()->Disconnect();
593 // Null all callbacks, delete all buffers.
594 transport_send_busy_
= false;
596 transport_recv_busy_
= false;
599 user_connect_callback_
.Reset();
600 user_read_callback_
.Reset();
601 user_write_callback_
.Reset();
602 user_read_buf_
= NULL
;
603 user_read_buf_len_
= 0;
604 user_write_buf_
= NULL
;
605 user_write_buf_len_
= 0;
607 pending_read_error_
= kNoPendingResult
;
608 pending_read_ssl_error_
= SSL_ERROR_NONE
;
609 pending_read_error_info_
= OpenSSLErrorInfo();
611 transport_read_error_
= OK
;
612 transport_write_error_
= OK
;
614 server_cert_verify_result_
.Reset();
615 completed_connect_
= false;
617 cert_authorities_
.clear();
618 cert_key_types_
.clear();
620 start_cert_verification_time_
= base::TimeTicks();
622 npn_status_
= kNextProtoUnsupported
;
625 channel_id_sent_
= false;
626 session_pending_
= false;
627 certificate_verified_
= false;
628 channel_id_request_
.Cancel();
629 ssl_failure_state_
= SSL_FAILURE_NONE
;
631 private_key_
.reset();
632 signature_result_
= kNoPendingResult
;
636 bool SSLClientSocketOpenSSL::IsConnected() const {
637 // If the handshake has not yet completed.
638 if (!completed_connect_
)
640 // If an asynchronous operation is still pending.
641 if (user_read_buf_
.get() || user_write_buf_
.get())
644 return transport_
->socket()->IsConnected();
647 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
648 // If the handshake has not yet completed.
649 if (!completed_connect_
)
651 // If an asynchronous operation is still pending.
652 if (user_read_buf_
.get() || user_write_buf_
.get())
655 // If there is data read from the network that has not yet been consumed, do
656 // not treat the connection as idle.
658 // Note that this does not check |BIO_pending|, whether there is ciphertext
659 // that has not yet been flushed to the network. |Write| returns early, so
660 // this can cause race conditions which cause a socket to not be treated
661 // reusable when it should be. See https://crbug.com/466147.
662 if (BIO_wpending(transport_bio_
) > 0)
665 return transport_
->socket()->IsConnectedAndIdle();
668 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
669 return transport_
->socket()->GetPeerAddress(addressList
);
672 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
673 return transport_
->socket()->GetLocalAddress(addressList
);
676 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
680 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
681 if (transport_
.get() && transport_
->socket()) {
682 transport_
->socket()->SetSubresourceSpeculation();
688 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
689 if (transport_
.get() && transport_
->socket()) {
690 transport_
->socket()->SetOmniboxSpeculation();
696 bool SSLClientSocketOpenSSL::WasEverUsed() const {
697 return was_ever_used_
;
700 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
701 if (transport_
.get() && transport_
->socket())
702 return transport_
->socket()->UsingTCPFastOpen();
708 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
710 if (server_cert_chain_
->empty())
713 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
714 ssl_info
->unverified_cert
= server_cert_
;
715 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
716 ssl_info
->is_issued_by_known_root
=
717 server_cert_verify_result_
.is_issued_by_known_root
;
718 ssl_info
->public_key_hashes
=
719 server_cert_verify_result_
.public_key_hashes
;
720 ssl_info
->client_cert_sent
=
721 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
722 ssl_info
->channel_id_sent
= channel_id_sent_
;
723 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
725 AddSCTInfoToSSLInfo(ssl_info
);
727 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
729 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
730 ssl_info
->key_exchange_info
=
731 SSL_SESSION_get_key_exchange_info(SSL_get_session(ssl_
));
733 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
734 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
735 GetNetSSLVersion(ssl_
));
737 if (!SSL_get_secure_renegotiation_support(ssl_
))
738 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
740 if (ssl_config_
.version_fallback
)
741 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
743 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
744 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
746 DVLOG(3) << "Encoded connection status: cipher suite = "
747 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
749 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
753 void SSLClientSocketOpenSSL::GetConnectionAttempts(
754 ConnectionAttempts
* out
) const {
758 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
760 const CompletionCallback
& callback
) {
761 user_read_buf_
= buf
;
762 user_read_buf_len_
= buf_len
;
764 int rv
= DoReadLoop();
766 if (rv
== ERR_IO_PENDING
) {
767 user_read_callback_
= callback
;
770 was_ever_used_
= true;
771 user_read_buf_
= NULL
;
772 user_read_buf_len_
= 0;
778 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
780 const CompletionCallback
& callback
) {
781 user_write_buf_
= buf
;
782 user_write_buf_len_
= buf_len
;
784 int rv
= DoWriteLoop();
786 if (rv
== ERR_IO_PENDING
) {
787 user_write_callback_
= callback
;
790 was_ever_used_
= true;
791 user_write_buf_
= NULL
;
792 user_write_buf_len_
= 0;
798 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
799 return transport_
->socket()->SetReceiveBufferSize(size
);
802 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
803 return transport_
->socket()->SetSendBufferSize(size
);
806 int SSLClientSocketOpenSSL::Init() {
808 DCHECK(!transport_bio_
);
810 SSLContext
* context
= SSLContext::GetInstance();
811 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
813 ssl_
= SSL_new(context
->ssl_ctx());
814 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
815 return ERR_UNEXPECTED
;
817 // SNI should only contain valid DNS hostnames, not IP addresses (see RFC
820 // TODO(rsleevi): Should this code allow hostnames that violate the LDH rule?
821 // See https://crbug.com/496472 and https://crbug.com/496468 for discussion.
822 IPAddressNumber unused
;
823 if (!ParseIPLiteralToNumber(host_and_port_
.host(), &unused
) &&
824 !SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str())) {
825 return ERR_UNEXPECTED
;
828 SSL_SESSION
* session
= context
->session_cache()->Lookup(GetSessionCacheKey());
829 if (session
!= nullptr)
830 SSL_set_session(ssl_
, session
);
832 send_buffer_
= new GrowableIOBuffer();
833 send_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
834 recv_buffer_
= new GrowableIOBuffer();
835 recv_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
839 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
840 if (!BIO_new_bio_pair_external_buf(
841 &ssl_bio
, send_buffer_
->capacity(),
842 reinterpret_cast<uint8_t*>(send_buffer_
->data()), &transport_bio_
,
843 recv_buffer_
->capacity(),
844 reinterpret_cast<uint8_t*>(recv_buffer_
->data())))
845 return ERR_UNEXPECTED
;
847 DCHECK(transport_bio_
);
849 // Install a callback on OpenSSL's end to plumb transport errors through.
850 BIO_set_callback(ssl_bio
, &SSLClientSocketOpenSSL::BIOCallback
);
851 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
853 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
855 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_min
);
856 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_max
);
857 SSL_set_min_version(ssl_
, ssl_config_
.version_min
);
858 SSL_set_max_version(ssl_
, ssl_config_
.version_max
);
860 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
861 // set everything we care about to an absolute value.
862 SslSetClearMask options
;
863 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
865 // TODO(joth): Set this conditionally, see http://crbug.com/55410
866 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
868 SSL_set_options(ssl_
, options
.set_mask
);
869 SSL_clear_options(ssl_
, options
.clear_mask
);
871 // Same as above, this time for the SSL mode.
872 SslSetClearMask mode
;
874 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
875 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
877 mode
.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START
,
878 ssl_config_
.false_start_enabled
);
880 mode
.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV
, ssl_config_
.version_fallback
);
882 SSL_set_mode(ssl_
, mode
.set_mask
);
883 SSL_clear_mode(ssl_
, mode
.clear_mask
);
885 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
886 // textual name with SSL_set_cipher_list because there is no public API to
887 // directly remove a cipher by ID.
888 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
890 // See SSLConfig::disabled_cipher_suites for description of the suites
891 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
892 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
893 // as the handshake hash.
894 std::string
command("DEFAULT:!SHA256:!SHA384:!AESGCM+AES256:!aPSK");
895 // Walk through all the installed ciphers, seeing if any need to be
896 // appended to the cipher removal |command|.
897 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
898 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
899 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
900 bool disable
= false;
901 if (ssl_config_
.require_ecdhe
) {
902 base::StringPiece
kx_name(SSL_CIPHER_get_kx_name(cipher
));
903 disable
= kx_name
!= "ECDHE_RSA" && kx_name
!= "ECDHE_ECDSA";
906 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
907 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
908 ssl_config_
.disabled_cipher_suites
.end();
911 const char* name
= SSL_CIPHER_get_name(cipher
);
912 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
913 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
914 command
.append(":!");
915 command
.append(name
);
919 if (!ssl_config_
.enable_deprecated_cipher_suites
)
920 command
.append(":!RC4");
922 // Disable ECDSA cipher suites on platforms that do not support ECDSA
923 // signed certificates, as servers may use the presence of such
924 // ciphersuites as a hint to send an ECDSA certificate.
926 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
927 command
.append(":!ECDSA");
930 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
931 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
932 // This will almost certainly result in the socket failing to complete the
933 // handshake at which point the appropriate error is bubbled up to the client.
934 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
938 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
939 SSL_enable_tls_channel_id(ssl_
);
942 if (!ssl_config_
.next_protos
.empty()) {
943 // Get list of ciphers that are enabled.
944 STACK_OF(SSL_CIPHER
)* enabled_ciphers
= SSL_get_ciphers(ssl_
);
945 DCHECK(enabled_ciphers
);
946 std::vector
<uint16
> enabled_ciphers_vector
;
947 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(enabled_ciphers
); ++i
) {
948 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(enabled_ciphers
, i
);
949 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
950 enabled_ciphers_vector
.push_back(id
);
953 std::vector
<uint8_t> wire_protos
=
954 SerializeNextProtos(ssl_config_
.next_protos
,
955 HasCipherAdequateForHTTP2(enabled_ciphers_vector
) &&
956 IsTLSVersionAdequateForHTTP2(ssl_config_
));
957 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
961 if (ssl_config_
.signed_cert_timestamps_enabled
) {
962 SSL_enable_signed_cert_timestamps(ssl_
);
963 SSL_enable_ocsp_stapling(ssl_
);
966 if (cert_verifier_
->SupportsOCSPStapling())
967 SSL_enable_ocsp_stapling(ssl_
);
969 // By default, renegotiations are rejected. After the initial handshake
970 // completes, some application protocols may re-enable it.
971 SSL_set_reject_peer_renegotiations(ssl_
, 1);
976 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
977 // Since Run may result in Read being called, clear |user_read_callback_|
980 was_ever_used_
= true;
981 user_read_buf_
= NULL
;
982 user_read_buf_len_
= 0;
983 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
986 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
987 // Since Run may result in Write being called, clear |user_write_callback_|
990 was_ever_used_
= true;
991 user_write_buf_
= NULL
;
992 user_write_buf_len_
= 0;
993 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
996 bool SSLClientSocketOpenSSL::DoTransportIO() {
997 bool network_moved
= false;
999 // Read and write as much data as possible. The loop is necessary because
1000 // Write() may return synchronously.
1003 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
1004 network_moved
= true;
1006 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
1007 network_moved
= true;
1008 return network_moved
;
1011 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
1012 // g_first_run_completed once crbug.com/424386 is fixed.
1013 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
1014 LAZY_INSTANCE_INITIALIZER
;
1016 int SSLClientSocketOpenSSL::DoHandshake() {
1017 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1021 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
1023 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
1024 rv
= SSL_do_handshake(ssl_
);
1026 if (g_first_run_completed
.Get().Get()) {
1027 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
1029 tracked_objects::ScopedTracker
tracking_profile(
1030 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
1032 rv
= SSL_do_handshake(ssl_
);
1034 g_first_run_completed
.Get().Set(true);
1035 rv
= SSL_do_handshake(ssl_
);
1041 int ssl_error
= SSL_get_error(ssl_
, rv
);
1042 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
1043 // The server supports channel ID. Stop to look one up before returning to
1045 GotoState(STATE_CHANNEL_ID_LOOKUP
);
1048 if (ssl_error
== SSL_ERROR_WANT_X509_LOOKUP
&&
1049 !ssl_config_
.send_client_cert
) {
1050 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1052 if (ssl_error
== SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
) {
1053 DCHECK(private_key_
);
1054 DCHECK_NE(kNoPendingResult
, signature_result_
);
1055 GotoState(STATE_HANDSHAKE
);
1056 return ERR_IO_PENDING
;
1059 OpenSSLErrorInfo error_info
;
1060 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
1061 if (net_error
== ERR_IO_PENDING
) {
1062 // If not done, stay in this state
1063 GotoState(STATE_HANDSHAKE
);
1064 return ERR_IO_PENDING
;
1067 LOG(ERROR
) << "handshake failed; returned " << rv
<< ", SSL error code "
1068 << ssl_error
<< ", net_error " << net_error
;
1070 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1071 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1073 // Classify the handshake failure. This is used to determine causes of the
1074 // TLS version fallback.
1076 // |cipher| is the current outgoing cipher suite, so it is non-null iff
1077 // ChangeCipherSpec was sent.
1078 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
1079 if (SSL_get_state(ssl_
) == SSL3_ST_CR_SRVR_HELLO_A
) {
1080 ssl_failure_state_
= SSL_FAILURE_CLIENT_HELLO
;
1081 } else if (cipher
&& (SSL_CIPHER_get_id(cipher
) ==
1082 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256
||
1083 SSL_CIPHER_get_id(cipher
) ==
1084 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256
)) {
1085 ssl_failure_state_
= SSL_FAILURE_BUGGY_GCM
;
1086 } else if (cipher
&& ssl_config_
.send_client_cert
) {
1087 ssl_failure_state_
= SSL_FAILURE_CLIENT_AUTH
;
1088 } else if (ERR_GET_LIB(error_info
.error_code
) == ERR_LIB_SSL
&&
1089 ERR_GET_REASON(error_info
.error_code
) ==
1090 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED
) {
1091 ssl_failure_state_
= SSL_FAILURE_SESSION_MISMATCH
;
1092 } else if (cipher
&& npn_status_
!= kNextProtoUnsupported
) {
1093 ssl_failure_state_
= SSL_FAILURE_NEXT_PROTO
;
1095 ssl_failure_state_
= SSL_FAILURE_UNKNOWN
;
1099 GotoState(STATE_HANDSHAKE_COMPLETE
);
1103 int SSLClientSocketOpenSSL::DoHandshakeComplete(int result
) {
1107 if (ssl_config_
.version_fallback
&&
1108 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
1109 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
1112 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1113 if (npn_status_
== kNextProtoUnsupported
) {
1114 const uint8_t* alpn_proto
= NULL
;
1115 unsigned alpn_len
= 0;
1116 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
1118 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
1119 npn_status_
= kNextProtoNegotiated
;
1120 set_negotiation_extension(kExtensionALPN
);
1124 RecordNegotiationExtension();
1125 RecordChannelIDSupport(channel_id_service_
, channel_id_sent_
,
1126 ssl_config_
.channel_id_enabled
,
1127 crypto::ECPrivateKey::IsSupported());
1129 // Only record OCSP histograms if OCSP was requested.
1130 if (ssl_config_
.signed_cert_timestamps_enabled
||
1131 cert_verifier_
->SupportsOCSPStapling()) {
1132 const uint8_t* ocsp_response
;
1133 size_t ocsp_response_len
;
1134 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
1136 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
1137 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
1140 const uint8_t* sct_list
;
1141 size_t sct_list_len
;
1142 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
1143 set_signed_cert_timestamps_received(sct_list_len
!= 0);
1145 if (IsRenegotiationAllowed())
1146 SSL_set_reject_peer_renegotiations(ssl_
, 0);
1148 // Verify the certificate.
1150 GotoState(STATE_VERIFY_CERT
);
1154 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1155 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
);
1156 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1157 return channel_id_service_
->GetOrCreateChannelID(
1158 host_and_port_
.host(), &channel_id_key_
,
1159 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1160 base::Unretained(this)),
1161 &channel_id_request_
);
1164 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1168 if (!channel_id_key_
) {
1169 LOG(ERROR
) << "Failed to import Channel ID.";
1170 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1173 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1175 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1176 int rv
= SSL_set1_tls_channel_id(ssl_
, channel_id_key_
->key());
1178 LOG(ERROR
) << "Failed to set Channel ID.";
1179 int err
= SSL_get_error(ssl_
, rv
);
1180 return MapOpenSSLError(err
, err_tracer
);
1183 // Return to the handshake.
1184 channel_id_sent_
= true;
1185 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
);
1186 GotoState(STATE_HANDSHAKE
);
1190 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1191 DCHECK(!server_cert_chain_
->empty());
1192 DCHECK(start_cert_verification_time_
.is_null());
1194 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1196 // OpenSSL decoded the certificate, but the platform certificate
1197 // implementation could not. This is treated as a fatal SSL-level protocol
1198 // error rather than a certificate error. See https://crbug.com/91341.
1199 if (!server_cert_
.get())
1200 return ERR_SSL_SERVER_CERT_BAD_FORMAT
;
1202 // If the certificate is bad and has been previously accepted, use
1203 // the previous status and bypass the error.
1204 base::StringPiece der_cert
;
1205 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1207 return ERR_CERT_INVALID
;
1209 CertStatus cert_status
;
1210 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1211 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1212 server_cert_verify_result_
.Reset();
1213 server_cert_verify_result_
.cert_status
= cert_status
;
1214 server_cert_verify_result_
.verified_cert
= server_cert_
;
1218 std::string ocsp_response
;
1219 if (cert_verifier_
->SupportsOCSPStapling()) {
1220 const uint8_t* ocsp_response_raw
;
1221 size_t ocsp_response_len
;
1222 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1223 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1227 start_cert_verification_time_
= base::TimeTicks::Now();
1229 return cert_verifier_
->Verify(
1230 server_cert_
.get(), host_and_port_
.host(), ocsp_response
,
1231 ssl_config_
.GetCertVerifyFlags(),
1232 // TODO(davidben): Route the CRLSet through SSLConfig so
1233 // SSLClientSocket doesn't depend on SSLConfigService.
1234 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_
,
1235 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1236 base::Unretained(this)),
1237 &cert_verifier_request_
, net_log_
);
1240 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1241 cert_verifier_request_
.reset();
1243 if (!start_cert_verification_time_
.is_null()) {
1244 base::TimeDelta verify_time
=
1245 base::TimeTicks::Now() - start_cert_verification_time_
;
1247 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1249 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1254 if (SSL_session_reused(ssl_
)) {
1255 // Record whether or not the server tried to resume a session for a
1256 // different version. See https://crbug.com/441456.
1257 UMA_HISTOGRAM_BOOLEAN(
1258 "Net.SSLSessionVersionMatch",
1259 SSL_version(ssl_
) == SSL_get_session(ssl_
)->ssl_version
);
1263 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1264 if (transport_security_state_
&&
1266 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1267 !transport_security_state_
->CheckPublicKeyPins(
1268 host_and_port_
, server_cert_verify_result_
.is_issued_by_known_root
,
1269 server_cert_verify_result_
.public_key_hashes
, server_cert_
.get(),
1270 server_cert_verify_result_
.verified_cert
.get(),
1271 TransportSecurityState::ENABLE_PIN_REPORTS
, &pinning_failure_log_
)) {
1272 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1276 // Only check Certificate Transparency if there were no other errors with
1280 DCHECK(!certificate_verified_
);
1281 certificate_verified_
= true;
1282 MaybeCacheSession();
1284 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1285 << " (" << result
<< ")";
1288 completed_connect_
= true;
1289 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1290 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1294 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1295 if (!user_connect_callback_
.is_null()) {
1296 CompletionCallback c
= user_connect_callback_
;
1297 user_connect_callback_
.Reset();
1298 c
.Run(rv
> OK
? OK
: rv
);
1302 void SSLClientSocketOpenSSL::UpdateServerCert() {
1303 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1304 server_cert_
= server_cert_chain_
->AsOSChain();
1305 if (server_cert_
.get()) {
1307 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
1308 base::Bind(&NetLogX509CertificateCallback
,
1309 base::Unretained(server_cert_
.get())));
1313 void SSLClientSocketOpenSSL::VerifyCT() {
1314 if (!cert_transparency_verifier_
)
1317 const uint8_t* ocsp_response_raw
;
1318 size_t ocsp_response_len
;
1319 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1320 std::string ocsp_response
;
1321 if (ocsp_response_len
> 0) {
1322 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1326 const uint8_t* sct_list_raw
;
1327 size_t sct_list_len
;
1328 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1329 std::string sct_list
;
1330 if (sct_list_len
> 0)
1331 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1333 // Note that this is a completely synchronous operation: The CT Log Verifier
1334 // gets all the data it needs for SCT verification and does not do any
1335 // external communication.
1336 cert_transparency_verifier_
->Verify(
1337 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1338 &ct_verify_result_
, net_log_
);
1340 if (policy_enforcer_
&&
1341 (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
)) {
1342 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1343 SSLConfigService::GetEVCertsWhitelist();
1344 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1345 server_cert_verify_result_
.verified_cert
.get(), ev_whitelist
.get(),
1346 ct_verify_result_
, net_log_
)) {
1347 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1348 VLOG(1) << "EV certificate for "
1349 << server_cert_verify_result_
.verified_cert
->subject()
1351 << " does not conform to CT policy, removing EV status.";
1352 server_cert_verify_result_
.cert_status
|=
1353 CERT_STATUS_CT_COMPLIANCE_FAILED
;
1354 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1359 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1360 int rv
= DoHandshakeLoop(result
);
1361 if (rv
!= ERR_IO_PENDING
) {
1362 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1363 DoConnectCallback(rv
);
1367 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1368 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1369 // In handshake phase.
1370 OnHandshakeIOComplete(result
);
1374 // During a renegotiation, a Read call may also be blocked on a transport
1375 // write, so retry both operations.
1376 PumpReadWriteEvents();
1379 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1380 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1381 // In handshake phase.
1382 OnHandshakeIOComplete(result
);
1386 // Network layer received some data, check if client requested to read
1388 if (!user_read_buf_
.get())
1391 int rv
= DoReadLoop();
1392 if (rv
!= ERR_IO_PENDING
)
1396 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1397 int rv
= last_io_result
;
1399 // Default to STATE_NONE for next state.
1400 // (This is a quirk carried over from the windows
1401 // implementation. It makes reading the logs a bit harder.)
1402 // State handlers can and often do call GotoState just
1403 // to stay in the current state.
1404 State state
= next_handshake_state_
;
1405 GotoState(STATE_NONE
);
1407 case STATE_HANDSHAKE
:
1410 case STATE_HANDSHAKE_COMPLETE
:
1411 rv
= DoHandshakeComplete(rv
);
1413 case STATE_CHANNEL_ID_LOOKUP
:
1415 rv
= DoChannelIDLookup();
1417 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1418 rv
= DoChannelIDLookupComplete(rv
);
1420 case STATE_VERIFY_CERT
:
1422 rv
= DoVerifyCert(rv
);
1424 case STATE_VERIFY_CERT_COMPLETE
:
1425 rv
= DoVerifyCertComplete(rv
);
1429 rv
= ERR_UNEXPECTED
;
1430 NOTREACHED() << "unexpected state" << state
;
1434 bool network_moved
= DoTransportIO();
1435 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1436 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1437 // special case we keep looping even if rv is ERR_IO_PENDING because
1438 // the transport IO may allow DoHandshake to make progress.
1439 rv
= OK
; // This causes us to stay in the loop.
1441 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1445 int SSLClientSocketOpenSSL::DoReadLoop() {
1449 rv
= DoPayloadRead();
1450 network_moved
= DoTransportIO();
1451 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1456 int SSLClientSocketOpenSSL::DoWriteLoop() {
1460 rv
= DoPayloadWrite();
1461 network_moved
= DoTransportIO();
1462 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1467 int SSLClientSocketOpenSSL::DoPayloadRead() {
1468 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1470 DCHECK_LT(0, user_read_buf_len_
);
1471 DCHECK(user_read_buf_
.get());
1474 if (pending_read_error_
!= kNoPendingResult
) {
1475 rv
= pending_read_error_
;
1476 pending_read_error_
= kNoPendingResult
;
1478 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1479 rv
, user_read_buf_
->data());
1482 NetLog::TYPE_SSL_READ_ERROR
,
1483 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1484 pending_read_error_info_
));
1486 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1487 pending_read_error_info_
= OpenSSLErrorInfo();
1491 int total_bytes_read
= 0;
1494 ssl_ret
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1495 user_read_buf_len_
- total_bytes_read
);
1497 total_bytes_read
+= ssl_ret
;
1498 } while (total_bytes_read
< user_read_buf_len_
&& ssl_ret
> 0);
1500 // Although only the final SSL_read call may have failed, the failure needs to
1501 // processed immediately, while the information still available in OpenSSL's
1504 // A zero return from SSL_read may mean any of:
1505 // - The underlying BIO_read returned 0.
1506 // - The peer sent a close_notify.
1507 // - Any arbitrary error. https://crbug.com/466303
1509 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1510 // error, so it does not occur. The second and third are distinguished by
1511 // SSL_ERROR_ZERO_RETURN.
1512 pending_read_ssl_error_
= SSL_get_error(ssl_
, ssl_ret
);
1513 if (pending_read_ssl_error_
== SSL_ERROR_ZERO_RETURN
) {
1514 pending_read_error_
= 0;
1515 } else if (pending_read_ssl_error_
== SSL_ERROR_WANT_X509_LOOKUP
&&
1516 !ssl_config_
.send_client_cert
) {
1517 pending_read_error_
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1518 } else if (pending_read_ssl_error_
==
1519 SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
) {
1520 DCHECK(private_key_
);
1521 DCHECK_NE(kNoPendingResult
, signature_result_
);
1522 pending_read_error_
= ERR_IO_PENDING
;
1524 pending_read_error_
= MapOpenSSLErrorWithDetails(
1525 pending_read_ssl_error_
, err_tracer
, &pending_read_error_info_
);
1528 // Many servers do not reliably send a close_notify alert when shutting down
1529 // a connection, and instead terminate the TCP connection. This is reported
1530 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1531 // graceful EOF, instead of treating it as an error as it should be.
1532 if (pending_read_error_
== ERR_CONNECTION_CLOSED
)
1533 pending_read_error_
= 0;
1536 if (total_bytes_read
> 0) {
1537 // Return any bytes read to the caller. The error will be deferred to the
1538 // next call of DoPayloadRead.
1539 rv
= total_bytes_read
;
1541 // Do not treat insufficient data as an error to return in the next call to
1542 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1543 // again. This is because DoTransportIO() may complete in between the next
1544 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1545 // subsequent invocations to see if a complete record may now be read.
1546 if (pending_read_error_
== ERR_IO_PENDING
)
1547 pending_read_error_
= kNoPendingResult
;
1549 // No bytes were returned. Return the pending read error immediately.
1550 DCHECK_NE(kNoPendingResult
, pending_read_error_
);
1551 rv
= pending_read_error_
;
1552 pending_read_error_
= kNoPendingResult
;
1556 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1557 user_read_buf_
->data());
1558 } else if (rv
!= ERR_IO_PENDING
) {
1560 NetLog::TYPE_SSL_READ_ERROR
,
1561 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1562 pending_read_error_info_
));
1563 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1564 pending_read_error_info_
= OpenSSLErrorInfo();
1569 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1570 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1571 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1574 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1575 user_write_buf_
->data());
1579 int ssl_error
= SSL_get_error(ssl_
, rv
);
1580 if (ssl_error
== SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
)
1581 return ERR_IO_PENDING
;
1582 OpenSSLErrorInfo error_info
;
1583 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1586 if (net_error
!= ERR_IO_PENDING
) {
1588 NetLog::TYPE_SSL_WRITE_ERROR
,
1589 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1594 void SSLClientSocketOpenSSL::PumpReadWriteEvents() {
1595 int rv_read
= ERR_IO_PENDING
;
1596 int rv_write
= ERR_IO_PENDING
;
1599 if (user_read_buf_
.get())
1600 rv_read
= DoPayloadRead();
1601 if (user_write_buf_
.get())
1602 rv_write
= DoPayloadWrite();
1603 network_moved
= DoTransportIO();
1604 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1605 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1607 // Performing the Read callback may cause |this| to be deleted. If this
1608 // happens, the Write callback should not be invoked. Guard against this by
1609 // holding a WeakPtr to |this| and ensuring it's still valid.
1610 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1611 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1612 DoReadCallback(rv_read
);
1617 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1618 DoWriteCallback(rv_write
);
1621 int SSLClientSocketOpenSSL::BufferSend(void) {
1622 if (transport_send_busy_
)
1623 return ERR_IO_PENDING
;
1625 size_t buffer_read_offset
;
1628 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1629 &buffer_read_offset
, &max_read
);
1630 DCHECK_EQ(status
, 1); // Should never fail.
1632 return 0; // Nothing pending in the OpenSSL write BIO.
1633 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1634 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1635 send_buffer_
->set_offset(buffer_read_offset
);
1637 int rv
= transport_
->socket()->Write(
1638 send_buffer_
.get(), max_read
,
1639 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1640 base::Unretained(this)));
1641 if (rv
== ERR_IO_PENDING
) {
1642 transport_send_busy_
= true;
1644 TransportWriteComplete(rv
);
1649 int SSLClientSocketOpenSSL::BufferRecv(void) {
1650 if (transport_recv_busy_
)
1651 return ERR_IO_PENDING
;
1653 // Determine how much was requested from |transport_bio_| that was not
1654 // actually available.
1655 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1656 if (requested
== 0) {
1657 // This is not a perfect match of error codes, as no operation is
1658 // actually pending. However, returning 0 would be interpreted as
1659 // a possible sign of EOF, which is also an inappropriate match.
1660 return ERR_IO_PENDING
;
1663 // Known Issue: While only reading |requested| data is the more correct
1664 // implementation, it has the downside of resulting in frequent reads:
1665 // One read for the SSL record header (~5 bytes) and one read for the SSL
1666 // record body. Rather than issuing these reads to the underlying socket
1667 // (and constantly allocating new IOBuffers), a single Read() request to
1668 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1669 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1670 // traffic, this over-subscribed Read()ing will not cause issues.
1672 size_t buffer_write_offset
;
1675 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1676 &buffer_write_offset
, &max_write
);
1677 DCHECK_EQ(status
, 1); // Should never fail.
1679 return ERR_IO_PENDING
;
1682 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1683 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1685 recv_buffer_
->set_offset(buffer_write_offset
);
1686 int rv
= transport_
->socket()->Read(
1689 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1690 base::Unretained(this)));
1691 if (rv
== ERR_IO_PENDING
) {
1692 transport_recv_busy_
= true;
1694 rv
= TransportReadComplete(rv
);
1699 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1700 TransportWriteComplete(result
);
1701 OnSendComplete(result
);
1704 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1705 result
= TransportReadComplete(result
);
1706 OnRecvComplete(result
);
1709 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1710 DCHECK(ERR_IO_PENDING
!= result
);
1711 int bytes_written
= 0;
1713 // Record the error. Save it to be reported in a future read or write on
1714 // transport_bio_'s peer.
1715 transport_write_error_
= result
;
1717 bytes_written
= result
;
1719 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1720 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1722 transport_send_busy_
= false;
1725 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1726 DCHECK(ERR_IO_PENDING
!= result
);
1727 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1728 // does not report success.
1730 result
= ERR_CONNECTION_CLOSED
;
1733 DVLOG(1) << "TransportReadComplete result " << result
;
1734 // Received an error. Save it to be reported in a future read on
1735 // transport_bio_'s peer.
1736 transport_read_error_
= result
;
1738 bytes_read
= result
;
1740 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1741 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1743 transport_recv_busy_
= false;
1747 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1748 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1749 DCHECK(ssl
== ssl_
);
1751 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1753 // Clear any currently configured certificates.
1754 SSL_certs_clear(ssl_
);
1757 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1758 LOG(WARNING
) << "Client auth is not supported";
1759 #else // !defined(OS_IOS)
1760 if (!ssl_config_
.send_client_cert
) {
1761 // First pass: we know that a client certificate is needed, but we do not
1762 // have one at hand.
1763 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1764 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1765 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1766 unsigned char* str
= NULL
;
1767 int length
= i2d_X509_NAME(ca_name
, &str
);
1768 cert_authorities_
.push_back(std::string(
1769 reinterpret_cast<const char*>(str
),
1770 static_cast<size_t>(length
)));
1774 const unsigned char* client_cert_types
;
1775 size_t num_client_cert_types
=
1776 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1777 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1778 cert_key_types_
.push_back(
1779 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1782 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1786 // Second pass: a client certificate should have been selected.
1787 if (ssl_config_
.client_cert
.get()) {
1788 ScopedX509 leaf_x509
=
1789 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1791 LOG(WARNING
) << "Failed to import certificate";
1792 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1796 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1797 ssl_config_
.client_cert
->GetIntermediateCertificates());
1799 LOG(WARNING
) << "Failed to import intermediate certificates";
1800 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1804 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1805 !SSL_set1_chain(ssl_
, chain
.get())) {
1806 LOG(WARNING
) << "Failed to set client certificate";
1810 #if defined(OS_NACL)
1811 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1814 // TODO(davidben): Lift this call up to the embedder so we can actually test
1815 // this code. https://crbug.com/394131
1816 private_key_
= FetchClientCertPrivateKey(
1817 ssl_config_
.client_cert
.get(),
1818 g_platform_key_task_runner
.Get().task_runner());
1819 if (!private_key_
) {
1820 // Could not find the private key. Fail the handshake and surface an
1821 // appropriate error to the caller.
1822 LOG(WARNING
) << "Client cert found without private key";
1823 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1827 SSL_set_private_key_method(ssl_
, &SSLContext::kPrivateKeyMethod
);
1830 int cert_count
= 1 + sk_X509_num(chain
.get());
1831 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1832 NetLog::IntegerCallback("cert_count", cert_count
));
1835 #endif // defined(OS_IOS)
1837 // Send no client certificate.
1838 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1839 NetLog::IntegerCallback("cert_count", 0));
1843 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1844 if (!completed_connect_
) {
1845 // If the first handshake hasn't completed then we accept any certificates
1846 // because we verify after the handshake.
1850 // Disallow the server certificate to change in a renegotiation.
1851 if (server_cert_chain_
->empty()) {
1852 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1855 base::StringPiece old_der
, new_der
;
1856 if (store_ctx
->cert
== NULL
||
1857 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1858 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1859 LOG(ERROR
) << "Failed to encode certificates";
1862 if (old_der
!= new_der
) {
1863 LOG(ERROR
) << "Server certificate changed between handshakes";
1870 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1871 // server supports NPN, selects a protocol from the list that the server
1872 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1873 // callback can assume that |in| is syntactically valid.
1874 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1875 unsigned char* outlen
,
1876 const unsigned char* in
,
1877 unsigned int inlen
) {
1878 if (ssl_config_
.next_protos
.empty()) {
1879 *out
= reinterpret_cast<uint8
*>(
1880 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1881 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1882 npn_status_
= kNextProtoUnsupported
;
1883 return SSL_TLSEXT_ERR_OK
;
1886 // Assume there's no overlap between our protocols and the server's list.
1887 npn_status_
= kNextProtoNoOverlap
;
1889 // For each protocol in server preference order, see if we support it.
1890 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1891 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1892 const std::string proto
= NextProtoToString(next_proto
);
1893 if (in
[i
] == proto
.size() &&
1894 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1895 // We found a match.
1896 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1898 npn_status_
= kNextProtoNegotiated
;
1902 if (npn_status_
== kNextProtoNegotiated
)
1906 // If we didn't find a protocol, we select the first one from our list.
1907 if (npn_status_
== kNextProtoNoOverlap
) {
1908 // NextProtoToString returns a pointer to a static string.
1909 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1910 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1911 *outlen
= strlen(proto
);
1914 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1915 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1916 set_negotiation_extension(kExtensionNPN
);
1917 return SSL_TLSEXT_ERR_OK
;
1920 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1923 const char *argp
, int argi
, long argl
,
1925 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1926 // If there is no more data in the buffer, report any pending errors that
1927 // were observed. Note that both the readbuf and the writebuf are checked
1928 // for errors, since the application may have encountered a socket error
1929 // while writing that would otherwise not be reported until the application
1930 // attempted to write again - which it may never do. See
1931 // https://crbug.com/249848.
1932 if (transport_read_error_
!= OK
) {
1933 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1936 if (transport_write_error_
!= OK
) {
1937 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1940 } else if (cmd
== BIO_CB_WRITE
) {
1941 // Because of the write buffer, this reports a failure from the previous
1942 // write payload. If the current payload fails to write, the error will be
1943 // reported in a future write or read to |bio|.
1944 if (transport_write_error_
!= OK
) {
1945 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1953 long SSLClientSocketOpenSSL::BIOCallback(
1956 const char *argp
, int argi
, long argl
,
1958 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1959 BIO_get_callback_arg(bio
));
1961 return socket
->MaybeReplayTransportError(
1962 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1965 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1966 // Only cache the session once both a new session has been established and the
1967 // certificate has been verified. Due to False Start, these events may happen
1969 if (!session_pending_
|| !certificate_verified_
)
1972 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1973 SSL_get_session(ssl_
));
1974 session_pending_
= false;
1977 int SSLClientSocketOpenSSL::NewSessionCallback(SSL_SESSION
* session
) {
1978 DCHECK_EQ(session
, SSL_get_session(ssl_
));
1980 // Only sessions from the initial handshake get cached. Note this callback may
1981 // be signaled on abbreviated handshakes if the ticket was renewed.
1982 session_pending_
= true;
1983 MaybeCacheSession();
1985 // OpenSSL passes a reference to |session|, but the session cache does not
1986 // take this reference, so release it.
1987 SSL_SESSION_free(session
);
1991 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
1992 for (ct::SCTList::const_iterator iter
=
1993 ct_verify_result_
.verified_scts
.begin();
1994 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
1995 ssl_info
->signed_certificate_timestamps
.push_back(
1996 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
1998 for (ct::SCTList::const_iterator iter
=
1999 ct_verify_result_
.invalid_scts
.begin();
2000 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
2001 ssl_info
->signed_certificate_timestamps
.push_back(
2002 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
2004 for (ct::SCTList::const_iterator iter
=
2005 ct_verify_result_
.unknown_logs_scts
.begin();
2006 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
2007 ssl_info
->signed_certificate_timestamps
.push_back(
2008 SignedCertificateTimestampAndStatus(*iter
,
2009 ct::SCT_STATUS_LOG_UNKNOWN
));
2013 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
2014 std::string result
= host_and_port_
.ToString();
2016 result
.append(ssl_session_cache_shard_
);
2018 // Shard the session cache based on maximum protocol version. This causes
2019 // fallback connections to use a separate session cache.
2021 switch (ssl_config_
.version_max
) {
2022 case SSL_PROTOCOL_VERSION_TLS1
:
2023 result
.append("tls1");
2025 case SSL_PROTOCOL_VERSION_TLS1_1
:
2026 result
.append("tls1.1");
2028 case SSL_PROTOCOL_VERSION_TLS1_2
:
2029 result
.append("tls1.2");
2036 if (ssl_config_
.enable_deprecated_cipher_suites
)
2037 result
.append("deprecated");
2042 bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
2043 if (npn_status_
== kNextProtoUnsupported
)
2044 return ssl_config_
.renego_allowed_default
;
2046 NextProto next_proto
= NextProtoFromString(npn_proto_
);
2047 for (NextProto allowed
: ssl_config_
.renego_allowed_for_protos
) {
2048 if (next_proto
== allowed
)
2054 int SSLClientSocketOpenSSL::PrivateKeyTypeCallback() {
2055 switch (private_key_
->GetType()) {
2056 case SSLPrivateKey::Type::RSA
:
2057 return EVP_PKEY_RSA
;
2058 case SSLPrivateKey::Type::ECDSA
:
2062 return EVP_PKEY_NONE
;
2065 int SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback(const EVP_MD
* md
) {
2066 SSLPrivateKey::Hash hash
;
2067 return EVP_MDToPrivateKeyHash(md
, &hash
) && private_key_
->SupportsHash(hash
);
2070 size_t SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback() {
2071 return private_key_
->GetMaxSignatureLengthInBytes();
2074 ssl_private_key_result_t
SSLClientSocketOpenSSL::PrivateKeySignCallback(
2081 DCHECK_EQ(kNoPendingResult
, signature_result_
);
2082 DCHECK(signature_
.empty());
2083 DCHECK(private_key_
);
2085 net_log_
.BeginEvent(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION
);
2087 SSLPrivateKey::Hash hash
;
2088 if (!EVP_MDToPrivateKeyHash(md
, &hash
)) {
2089 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
2090 return ssl_private_key_failure
;
2093 signature_result_
= ERR_IO_PENDING
;
2094 private_key_
->SignDigest(
2095 hash
, base::StringPiece(reinterpret_cast<const char*>(in
), in_len
),
2096 base::Bind(&SSLClientSocketOpenSSL::OnPrivateKeySignComplete
,
2097 weak_factory_
.GetWeakPtr()));
2098 return ssl_private_key_retry
;
2101 ssl_private_key_result_t
SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback(
2105 DCHECK_NE(kNoPendingResult
, signature_result_
);
2106 DCHECK(private_key_
);
2108 if (signature_result_
== ERR_IO_PENDING
)
2109 return ssl_private_key_retry
;
2110 if (signature_result_
!= OK
) {
2111 OpenSSLPutNetError(FROM_HERE
, signature_result_
);
2112 return ssl_private_key_failure
;
2114 if (signature_
.size() > max_out
) {
2115 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
2116 return ssl_private_key_failure
;
2118 memcpy(out
, vector_as_array(&signature_
), signature_
.size());
2119 *out_len
= signature_
.size();
2121 return ssl_private_key_success
;
2124 void SSLClientSocketOpenSSL::OnPrivateKeySignComplete(
2126 const std::vector
<uint8_t>& signature
) {
2127 DCHECK_EQ(ERR_IO_PENDING
, signature_result_
);
2128 DCHECK(signature_
.empty());
2129 DCHECK(private_key_
);
2131 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION
,
2134 signature_result_
= error
;
2135 if (signature_result_
== OK
)
2136 signature_
= signature
;
2138 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2139 OnHandshakeIOComplete(signature_result_
);
2143 // During a renegotiation, either Read or Write calls may be blocked on an
2144 // asynchronous private key operation.
2145 PumpReadWriteEvents();