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() { return Singleton
<SSLContext
>::get(); }
204 SSL_CTX
* ssl_ctx() { return ssl_ctx_
.get(); }
205 SSLClientSessionCacheOpenSSL
* session_cache() { return &session_cache_
; }
207 SSLClientSocketOpenSSL
* GetClientSocketFromSSL(const SSL
* ssl
) {
209 SSLClientSocketOpenSSL
* socket
= static_cast<SSLClientSocketOpenSSL
*>(
210 SSL_get_ex_data(ssl
, ssl_socket_data_index_
));
215 bool SetClientSocketForSSL(SSL
* ssl
, SSLClientSocketOpenSSL
* socket
) {
216 return SSL_set_ex_data(ssl
, ssl_socket_data_index_
, socket
) != 0;
219 static const SSL_PRIVATE_KEY_METHOD kPrivateKeyMethod
;
222 friend struct DefaultSingletonTraits
<SSLContext
>;
224 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
225 crypto::EnsureOpenSSLInit();
226 ssl_socket_data_index_
= SSL_get_ex_new_index(0, 0, 0, 0, 0);
227 DCHECK_NE(ssl_socket_data_index_
, -1);
228 ssl_ctx_
.reset(SSL_CTX_new(SSLv23_client_method()));
229 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
230 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
231 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
232 // This stops |SSL_shutdown| from generating the close_notify message, which
233 // is currently not sent on the network.
234 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
235 SSL_CTX_set_quiet_shutdown(ssl_ctx_
.get(), 1);
236 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
237 // It would be better if the callback were not a global setting,
238 // but that is an OpenSSL issue.
239 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
242 // Disable the internal session cache. Session caching is handled
243 // externally (i.e. by SSLClientSessionCacheOpenSSL).
244 SSL_CTX_set_session_cache_mode(
245 ssl_ctx_
.get(), SSL_SESS_CACHE_CLIENT
| SSL_SESS_CACHE_NO_INTERNAL
);
246 SSL_CTX_sess_set_new_cb(ssl_ctx_
.get(), NewSessionCallback
);
248 scoped_ptr
<base::Environment
> env(base::Environment::Create());
249 std::string ssl_keylog_file
;
250 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
251 !ssl_keylog_file
.empty()) {
252 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
253 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
255 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
256 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
258 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
263 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
264 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
266 return socket
->ClientCertRequestCallback(ssl
);
269 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
270 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
271 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
272 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
275 return socket
->CertVerifyCallback(store_ctx
);
278 static int SelectNextProtoCallback(SSL
* ssl
,
279 unsigned char** out
, unsigned char* outlen
,
280 const unsigned char* in
,
281 unsigned int inlen
, void* arg
) {
282 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
283 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
286 static int NewSessionCallback(SSL
* ssl
, SSL_SESSION
* session
) {
287 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
288 return socket
->NewSessionCallback(session
);
291 static int PrivateKeyTypeCallback(SSL
* ssl
) {
292 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
293 return socket
->PrivateKeyTypeCallback();
296 static int PrivateKeySupportsDigestCallback(SSL
* ssl
, const EVP_MD
* md
) {
297 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
298 return socket
->PrivateKeySupportsDigestCallback(md
);
301 static size_t PrivateKeyMaxSignatureLenCallback(SSL
* ssl
) {
302 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
303 return socket
->PrivateKeyMaxSignatureLenCallback();
306 static ssl_private_key_result_t
PrivateKeySignCallback(SSL
* ssl
,
313 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
314 return socket
->PrivateKeySignCallback(out
, out_len
, max_out
, md
, in
,
318 static ssl_private_key_result_t
PrivateKeySignCompleteCallback(
323 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
324 return socket
->PrivateKeySignCompleteCallback(out
, out_len
, max_out
);
327 // This is the index used with SSL_get_ex_data to retrieve the owner
328 // SSLClientSocketOpenSSL object from an SSL instance.
329 int ssl_socket_data_index_
;
331 ScopedSSL_CTX ssl_ctx_
;
333 // TODO(davidben): Use a separate cache per URLRequestContext.
334 // https://crbug.com/458365
336 // TODO(davidben): Sessions should be invalidated on fatal
337 // alerts. https://crbug.com/466352
338 SSLClientSessionCacheOpenSSL session_cache_
;
341 const SSL_PRIVATE_KEY_METHOD
342 SSLClientSocketOpenSSL::SSLContext::kPrivateKeyMethod
= {
343 &SSLClientSocketOpenSSL::SSLContext::PrivateKeyTypeCallback
,
344 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySupportsDigestCallback
,
345 &SSLClientSocketOpenSSL::SSLContext::PrivateKeyMaxSignatureLenCallback
,
346 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySignCallback
,
347 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySignCompleteCallback
,
350 // PeerCertificateChain is a helper object which extracts the certificate
351 // chain, as given by the server, from an OpenSSL socket and performs the needed
352 // resource management. The first element of the chain is the leaf certificate
353 // and the other elements are in the order given by the server.
354 class SSLClientSocketOpenSSL::PeerCertificateChain
{
356 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
357 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
358 ~PeerCertificateChain() {}
359 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
361 // Resets the PeerCertificateChain to the set of certificates in|chain|,
362 // which may be NULL, indicating to empty the store certificates.
363 // Note: If an error occurs, such as being unable to parse the certificates,
364 // this will behave as if Reset(NULL) was called.
365 void Reset(STACK_OF(X509
)* chain
);
367 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
368 scoped_refptr
<X509Certificate
> AsOSChain() const;
370 size_t size() const {
371 if (!openssl_chain_
.get())
373 return sk_X509_num(openssl_chain_
.get());
380 X509
* Get(size_t index
) const {
381 DCHECK_LT(index
, size());
382 return sk_X509_value(openssl_chain_
.get(), index
);
386 ScopedX509Stack openssl_chain_
;
389 SSLClientSocketOpenSSL::PeerCertificateChain
&
390 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
391 const PeerCertificateChain
& other
) {
395 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
399 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
400 STACK_OF(X509
)* chain
) {
401 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
404 scoped_refptr
<X509Certificate
>
405 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
406 #if defined(USE_OPENSSL_CERTS)
407 // When OSCertHandle is typedef'ed to X509, this implementation does a short
408 // cut to avoid converting back and forth between DER and the X509 struct.
409 X509Certificate::OSCertHandles intermediates
;
410 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
411 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
414 return make_scoped_refptr(X509Certificate::CreateFromHandle(
415 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
417 // DER-encode the chain and convert to a platform certificate handle.
418 std::vector
<base::StringPiece
> der_chain
;
419 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
420 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
421 base::StringPiece der
;
422 if (!x509_util::GetDER(x
, &der
))
424 der_chain
.push_back(der
);
427 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
432 void SSLClientSocket::ClearSessionCache() {
433 SSLClientSocketOpenSSL::SSLContext
* context
=
434 SSLClientSocketOpenSSL::SSLContext::GetInstance();
435 context
->session_cache()->Flush();
439 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
440 return SSL_PROTOCOL_VERSION_TLS1_2
;
443 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
444 scoped_ptr
<ClientSocketHandle
> transport_socket
,
445 const HostPortPair
& host_and_port
,
446 const SSLConfig
& ssl_config
,
447 const SSLClientSocketContext
& context
)
448 : transport_send_busy_(false),
449 transport_recv_busy_(false),
450 pending_read_error_(kNoPendingResult
),
451 pending_read_ssl_error_(SSL_ERROR_NONE
),
452 transport_read_error_(OK
),
453 transport_write_error_(OK
),
454 server_cert_chain_(new PeerCertificateChain(NULL
)),
455 completed_connect_(false),
456 was_ever_used_(false),
457 cert_verifier_(context
.cert_verifier
),
458 cert_transparency_verifier_(context
.cert_transparency_verifier
),
459 channel_id_service_(context
.channel_id_service
),
461 transport_bio_(NULL
),
462 transport_(transport_socket
.Pass()),
463 host_and_port_(host_and_port
),
464 ssl_config_(ssl_config
),
465 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
466 next_handshake_state_(STATE_NONE
),
467 disconnected_(false),
468 npn_status_(kNextProtoUnsupported
),
469 channel_id_sent_(false),
470 session_pending_(false),
471 certificate_verified_(false),
472 ssl_failure_state_(SSL_FAILURE_NONE
),
473 signature_result_(kNoPendingResult
),
474 transport_security_state_(context
.transport_security_state
),
475 policy_enforcer_(context
.cert_policy_enforcer
),
476 net_log_(transport_
->socket()->NetLog()),
477 weak_factory_(this) {
478 DCHECK(cert_verifier_
);
481 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
485 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
486 SSLCertRequestInfo
* cert_request_info
) {
487 cert_request_info
->host_and_port
= host_and_port_
;
488 cert_request_info
->cert_authorities
= cert_authorities_
;
489 cert_request_info
->cert_key_types
= cert_key_types_
;
492 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
493 std::string
* proto
) const {
499 SSLClientSocketOpenSSL::GetChannelIDService() const {
500 return channel_id_service_
;
503 SSLFailureState
SSLClientSocketOpenSSL::GetSSLFailureState() const {
504 return ssl_failure_state_
;
507 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
508 const base::StringPiece
& label
,
509 bool has_context
, const base::StringPiece
& context
,
510 unsigned char* out
, unsigned int outlen
) {
512 return ERR_SOCKET_NOT_CONNECTED
;
514 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
516 int rv
= SSL_export_keying_material(
517 ssl_
, out
, outlen
, label
.data(), label
.size(),
518 reinterpret_cast<const unsigned char*>(context
.data()), context
.length(),
519 has_context
? 1 : 0);
522 int ssl_error
= SSL_get_error(ssl_
, rv
);
523 LOG(ERROR
) << "Failed to export keying material;"
524 << " returned " << rv
525 << ", SSL error code " << ssl_error
;
526 return MapOpenSSLError(ssl_error
, err_tracer
);
531 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
533 return ERR_NOT_IMPLEMENTED
;
536 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
537 // It is an error to create an SSLClientSocket whose context has no
538 // TransportSecurityState.
539 DCHECK(transport_security_state_
);
541 // Although StreamSocket does allow calling Connect() after Disconnect(),
542 // this has never worked for layered sockets. CHECK to detect any consumers
543 // reconnecting an SSL socket.
545 // TODO(davidben,mmenke): Remove this API feature. See
546 // https://crbug.com/499289.
547 CHECK(!disconnected_
);
549 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
551 // Set up new ssl object.
554 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
558 // Set SSL to client mode. Handshake happens in the loop below.
559 SSL_set_connect_state(ssl_
);
561 GotoState(STATE_HANDSHAKE
);
562 rv
= DoHandshakeLoop(OK
);
563 if (rv
== ERR_IO_PENDING
) {
564 user_connect_callback_
= callback
;
566 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
569 return rv
> OK
? OK
: rv
;
572 void SSLClientSocketOpenSSL::Disconnect() {
574 // Calling SSL_shutdown prevents the session from being marked as
580 if (transport_bio_
) {
581 BIO_free_all(transport_bio_
);
582 transport_bio_
= NULL
;
585 disconnected_
= true;
587 // Shut down anything that may call us back.
588 cert_verifier_request_
.reset();
589 transport_
->socket()->Disconnect();
591 // Null all callbacks, delete all buffers.
592 transport_send_busy_
= false;
594 transport_recv_busy_
= false;
597 user_connect_callback_
.Reset();
598 user_read_callback_
.Reset();
599 user_write_callback_
.Reset();
600 user_read_buf_
= NULL
;
601 user_read_buf_len_
= 0;
602 user_write_buf_
= NULL
;
603 user_write_buf_len_
= 0;
605 pending_read_error_
= kNoPendingResult
;
606 pending_read_ssl_error_
= SSL_ERROR_NONE
;
607 pending_read_error_info_
= OpenSSLErrorInfo();
609 transport_read_error_
= OK
;
610 transport_write_error_
= OK
;
612 server_cert_verify_result_
.Reset();
613 completed_connect_
= false;
615 cert_authorities_
.clear();
616 cert_key_types_
.clear();
618 start_cert_verification_time_
= base::TimeTicks();
620 npn_status_
= kNextProtoUnsupported
;
623 channel_id_sent_
= false;
624 session_pending_
= false;
625 certificate_verified_
= false;
626 channel_id_request_
.Cancel();
627 ssl_failure_state_
= SSL_FAILURE_NONE
;
629 private_key_
.reset();
630 signature_result_
= kNoPendingResult
;
634 bool SSLClientSocketOpenSSL::IsConnected() const {
635 // If the handshake has not yet completed.
636 if (!completed_connect_
)
638 // If an asynchronous operation is still pending.
639 if (user_read_buf_
.get() || user_write_buf_
.get())
642 return transport_
->socket()->IsConnected();
645 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
646 // If the handshake has not yet completed.
647 if (!completed_connect_
)
649 // If an asynchronous operation is still pending.
650 if (user_read_buf_
.get() || user_write_buf_
.get())
653 // If there is data read from the network that has not yet been consumed, do
654 // not treat the connection as idle.
656 // Note that this does not check |BIO_pending|, whether there is ciphertext
657 // that has not yet been flushed to the network. |Write| returns early, so
658 // this can cause race conditions which cause a socket to not be treated
659 // reusable when it should be. See https://crbug.com/466147.
660 if (BIO_wpending(transport_bio_
) > 0)
663 return transport_
->socket()->IsConnectedAndIdle();
666 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
667 return transport_
->socket()->GetPeerAddress(addressList
);
670 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
671 return transport_
->socket()->GetLocalAddress(addressList
);
674 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
678 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
679 if (transport_
.get() && transport_
->socket()) {
680 transport_
->socket()->SetSubresourceSpeculation();
686 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
687 if (transport_
.get() && transport_
->socket()) {
688 transport_
->socket()->SetOmniboxSpeculation();
694 bool SSLClientSocketOpenSSL::WasEverUsed() const {
695 return was_ever_used_
;
698 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
699 if (transport_
.get() && transport_
->socket())
700 return transport_
->socket()->UsingTCPFastOpen();
706 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
708 if (server_cert_chain_
->empty())
711 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
712 ssl_info
->unverified_cert
= server_cert_
;
713 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
714 ssl_info
->is_issued_by_known_root
=
715 server_cert_verify_result_
.is_issued_by_known_root
;
716 ssl_info
->public_key_hashes
=
717 server_cert_verify_result_
.public_key_hashes
;
718 ssl_info
->client_cert_sent
=
719 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
720 ssl_info
->channel_id_sent
= channel_id_sent_
;
721 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
723 AddSCTInfoToSSLInfo(ssl_info
);
725 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
727 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
729 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
730 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
731 GetNetSSLVersion(ssl_
));
733 if (!SSL_get_secure_renegotiation_support(ssl_
))
734 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
736 if (ssl_config_
.version_fallback
)
737 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
739 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
740 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
742 DVLOG(3) << "Encoded connection status: cipher suite = "
743 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
745 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
749 void SSLClientSocketOpenSSL::GetConnectionAttempts(
750 ConnectionAttempts
* out
) const {
754 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
756 const CompletionCallback
& callback
) {
757 user_read_buf_
= buf
;
758 user_read_buf_len_
= buf_len
;
760 int rv
= DoReadLoop();
762 if (rv
== ERR_IO_PENDING
) {
763 user_read_callback_
= callback
;
766 was_ever_used_
= true;
767 user_read_buf_
= NULL
;
768 user_read_buf_len_
= 0;
774 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
776 const CompletionCallback
& callback
) {
777 user_write_buf_
= buf
;
778 user_write_buf_len_
= buf_len
;
780 int rv
= DoWriteLoop();
782 if (rv
== ERR_IO_PENDING
) {
783 user_write_callback_
= callback
;
786 was_ever_used_
= true;
787 user_write_buf_
= NULL
;
788 user_write_buf_len_
= 0;
794 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
795 return transport_
->socket()->SetReceiveBufferSize(size
);
798 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
799 return transport_
->socket()->SetSendBufferSize(size
);
802 int SSLClientSocketOpenSSL::Init() {
804 DCHECK(!transport_bio_
);
806 SSLContext
* context
= SSLContext::GetInstance();
807 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
809 ssl_
= SSL_new(context
->ssl_ctx());
810 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
811 return ERR_UNEXPECTED
;
813 // SNI should only contain valid DNS hostnames, not IP addresses (see RFC
816 // TODO(rsleevi): Should this code allow hostnames that violate the LDH rule?
817 // See https://crbug.com/496472 and https://crbug.com/496468 for discussion.
818 IPAddressNumber unused
;
819 if (!ParseIPLiteralToNumber(host_and_port_
.host(), &unused
) &&
820 !SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str())) {
821 return ERR_UNEXPECTED
;
824 SSL_SESSION
* session
= context
->session_cache()->Lookup(GetSessionCacheKey());
825 if (session
!= nullptr)
826 SSL_set_session(ssl_
, session
);
828 send_buffer_
= new GrowableIOBuffer();
829 send_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
830 recv_buffer_
= new GrowableIOBuffer();
831 recv_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
835 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
836 if (!BIO_new_bio_pair_external_buf(
837 &ssl_bio
, send_buffer_
->capacity(),
838 reinterpret_cast<uint8_t*>(send_buffer_
->data()), &transport_bio_
,
839 recv_buffer_
->capacity(),
840 reinterpret_cast<uint8_t*>(recv_buffer_
->data())))
841 return ERR_UNEXPECTED
;
843 DCHECK(transport_bio_
);
845 // Install a callback on OpenSSL's end to plumb transport errors through.
846 BIO_set_callback(ssl_bio
, &SSLClientSocketOpenSSL::BIOCallback
);
847 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
849 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
851 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_min
);
852 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_max
);
853 SSL_set_min_version(ssl_
, ssl_config_
.version_min
);
854 SSL_set_max_version(ssl_
, ssl_config_
.version_max
);
856 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
857 // set everything we care about to an absolute value.
858 SslSetClearMask options
;
859 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
861 // TODO(joth): Set this conditionally, see http://crbug.com/55410
862 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
864 SSL_set_options(ssl_
, options
.set_mask
);
865 SSL_clear_options(ssl_
, options
.clear_mask
);
867 // Same as above, this time for the SSL mode.
868 SslSetClearMask mode
;
870 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
871 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
873 mode
.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START
,
874 ssl_config_
.false_start_enabled
);
876 mode
.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV
, ssl_config_
.version_fallback
);
878 SSL_set_mode(ssl_
, mode
.set_mask
);
879 SSL_clear_mode(ssl_
, mode
.clear_mask
);
881 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
882 // textual name with SSL_set_cipher_list because there is no public API to
883 // directly remove a cipher by ID.
884 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
886 // See SSLConfig::disabled_cipher_suites for description of the suites
887 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
888 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
889 // as the handshake hash.
890 std::string
command("DEFAULT:!SHA256:!SHA384:!AESGCM+AES256:!aPSK");
891 // Walk through all the installed ciphers, seeing if any need to be
892 // appended to the cipher removal |command|.
893 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
894 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
895 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
896 bool disable
= false;
897 if (ssl_config_
.require_ecdhe
) {
898 base::StringPiece
kx_name(SSL_CIPHER_get_kx_name(cipher
));
899 disable
= kx_name
!= "ECDHE_RSA" && kx_name
!= "ECDHE_ECDSA";
902 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
903 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
904 ssl_config_
.disabled_cipher_suites
.end();
907 const char* name
= SSL_CIPHER_get_name(cipher
);
908 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
909 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
910 command
.append(":!");
911 command
.append(name
);
915 if (!ssl_config_
.enable_deprecated_cipher_suites
)
916 command
.append(":!RC4");
918 // Disable ECDSA cipher suites on platforms that do not support ECDSA
919 // signed certificates, as servers may use the presence of such
920 // ciphersuites as a hint to send an ECDSA certificate.
922 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
923 command
.append(":!ECDSA");
926 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
927 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
928 // This will almost certainly result in the socket failing to complete the
929 // handshake at which point the appropriate error is bubbled up to the client.
930 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
934 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
935 SSL_enable_tls_channel_id(ssl_
);
938 if (!ssl_config_
.next_protos
.empty()) {
939 // Get list of ciphers that are enabled.
940 STACK_OF(SSL_CIPHER
)* enabled_ciphers
= SSL_get_ciphers(ssl_
);
941 DCHECK(enabled_ciphers
);
942 std::vector
<uint16
> enabled_ciphers_vector
;
943 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(enabled_ciphers
); ++i
) {
944 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(enabled_ciphers
, i
);
945 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
946 enabled_ciphers_vector
.push_back(id
);
949 std::vector
<uint8_t> wire_protos
=
950 SerializeNextProtos(ssl_config_
.next_protos
,
951 HasCipherAdequateForHTTP2(enabled_ciphers_vector
) &&
952 IsTLSVersionAdequateForHTTP2(ssl_config_
));
953 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
957 if (ssl_config_
.signed_cert_timestamps_enabled
) {
958 SSL_enable_signed_cert_timestamps(ssl_
);
959 SSL_enable_ocsp_stapling(ssl_
);
962 if (cert_verifier_
->SupportsOCSPStapling())
963 SSL_enable_ocsp_stapling(ssl_
);
965 // By default, renegotiations are rejected. After the initial handshake
966 // completes, some application protocols may re-enable it.
967 SSL_set_reject_peer_renegotiations(ssl_
, 1);
972 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
973 // Since Run may result in Read being called, clear |user_read_callback_|
976 was_ever_used_
= true;
977 user_read_buf_
= NULL
;
978 user_read_buf_len_
= 0;
979 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
982 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
983 // Since Run may result in Write being called, clear |user_write_callback_|
986 was_ever_used_
= true;
987 user_write_buf_
= NULL
;
988 user_write_buf_len_
= 0;
989 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
992 bool SSLClientSocketOpenSSL::DoTransportIO() {
993 bool network_moved
= false;
995 // Read and write as much data as possible. The loop is necessary because
996 // Write() may return synchronously.
999 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
1000 network_moved
= true;
1002 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
1003 network_moved
= true;
1004 return network_moved
;
1007 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
1008 // g_first_run_completed once crbug.com/424386 is fixed.
1009 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
1010 LAZY_INSTANCE_INITIALIZER
;
1012 int SSLClientSocketOpenSSL::DoHandshake() {
1013 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1017 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
1019 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
1020 rv
= SSL_do_handshake(ssl_
);
1022 if (g_first_run_completed
.Get().Get()) {
1023 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
1025 tracked_objects::ScopedTracker
tracking_profile(
1026 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
1028 rv
= SSL_do_handshake(ssl_
);
1030 g_first_run_completed
.Get().Set(true);
1031 rv
= SSL_do_handshake(ssl_
);
1037 int ssl_error
= SSL_get_error(ssl_
, rv
);
1038 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
1039 // The server supports channel ID. Stop to look one up before returning to
1041 GotoState(STATE_CHANNEL_ID_LOOKUP
);
1044 if (ssl_error
== SSL_ERROR_WANT_X509_LOOKUP
&&
1045 !ssl_config_
.send_client_cert
) {
1046 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1048 if (ssl_error
== SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
) {
1049 DCHECK(private_key_
);
1050 DCHECK_NE(kNoPendingResult
, signature_result_
);
1051 GotoState(STATE_HANDSHAKE
);
1052 return ERR_IO_PENDING
;
1055 OpenSSLErrorInfo error_info
;
1056 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
1057 if (net_error
== ERR_IO_PENDING
) {
1058 // If not done, stay in this state
1059 GotoState(STATE_HANDSHAKE
);
1060 return ERR_IO_PENDING
;
1063 LOG(ERROR
) << "handshake failed; returned " << rv
<< ", SSL error code "
1064 << ssl_error
<< ", net_error " << net_error
;
1066 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1067 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1069 // Classify the handshake failure. This is used to determine causes of the
1070 // TLS version fallback.
1072 // |cipher| is the current outgoing cipher suite, so it is non-null iff
1073 // ChangeCipherSpec was sent.
1074 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
1075 if (SSL_get_state(ssl_
) == SSL3_ST_CR_SRVR_HELLO_A
) {
1076 ssl_failure_state_
= SSL_FAILURE_CLIENT_HELLO
;
1077 } else if (cipher
&& (SSL_CIPHER_get_id(cipher
) ==
1078 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256
||
1079 SSL_CIPHER_get_id(cipher
) ==
1080 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256
)) {
1081 ssl_failure_state_
= SSL_FAILURE_BUGGY_GCM
;
1082 } else if (cipher
&& ssl_config_
.send_client_cert
) {
1083 ssl_failure_state_
= SSL_FAILURE_CLIENT_AUTH
;
1084 } else if (ERR_GET_LIB(error_info
.error_code
) == ERR_LIB_SSL
&&
1085 ERR_GET_REASON(error_info
.error_code
) ==
1086 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED
) {
1087 ssl_failure_state_
= SSL_FAILURE_SESSION_MISMATCH
;
1088 } else if (cipher
&& npn_status_
!= kNextProtoUnsupported
) {
1089 ssl_failure_state_
= SSL_FAILURE_NEXT_PROTO
;
1091 ssl_failure_state_
= SSL_FAILURE_UNKNOWN
;
1095 GotoState(STATE_HANDSHAKE_COMPLETE
);
1099 int SSLClientSocketOpenSSL::DoHandshakeComplete(int result
) {
1103 if (ssl_config_
.version_fallback
&&
1104 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
1105 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
1108 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1109 if (npn_status_
== kNextProtoUnsupported
) {
1110 const uint8_t* alpn_proto
= NULL
;
1111 unsigned alpn_len
= 0;
1112 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
1114 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
1115 npn_status_
= kNextProtoNegotiated
;
1116 set_negotiation_extension(kExtensionALPN
);
1120 RecordNegotiationExtension();
1121 RecordChannelIDSupport(channel_id_service_
, channel_id_sent_
,
1122 ssl_config_
.channel_id_enabled
,
1123 crypto::ECPrivateKey::IsSupported());
1125 // Only record OCSP histograms if OCSP was requested.
1126 if (ssl_config_
.signed_cert_timestamps_enabled
||
1127 cert_verifier_
->SupportsOCSPStapling()) {
1128 const uint8_t* ocsp_response
;
1129 size_t ocsp_response_len
;
1130 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
1132 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
1133 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
1136 const uint8_t* sct_list
;
1137 size_t sct_list_len
;
1138 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
1139 set_signed_cert_timestamps_received(sct_list_len
!= 0);
1141 if (IsRenegotiationAllowed())
1142 SSL_set_reject_peer_renegotiations(ssl_
, 0);
1144 // Verify the certificate.
1146 GotoState(STATE_VERIFY_CERT
);
1150 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1151 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
);
1152 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1153 return channel_id_service_
->GetOrCreateChannelID(
1154 host_and_port_
.host(), &channel_id_key_
,
1155 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1156 base::Unretained(this)),
1157 &channel_id_request_
);
1160 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1164 if (!channel_id_key_
) {
1165 LOG(ERROR
) << "Failed to import Channel ID.";
1166 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1169 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1171 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1172 int rv
= SSL_set1_tls_channel_id(ssl_
, channel_id_key_
->key());
1174 LOG(ERROR
) << "Failed to set Channel ID.";
1175 int err
= SSL_get_error(ssl_
, rv
);
1176 return MapOpenSSLError(err
, err_tracer
);
1179 // Return to the handshake.
1180 channel_id_sent_
= true;
1181 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
);
1182 GotoState(STATE_HANDSHAKE
);
1186 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1187 DCHECK(!server_cert_chain_
->empty());
1188 DCHECK(start_cert_verification_time_
.is_null());
1190 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1192 // OpenSSL decoded the certificate, but the platform certificate
1193 // implementation could not. This is treated as a fatal SSL-level protocol
1194 // error rather than a certificate error. See https://crbug.com/91341.
1195 if (!server_cert_
.get())
1196 return ERR_SSL_SERVER_CERT_BAD_FORMAT
;
1198 // If the certificate is bad and has been previously accepted, use
1199 // the previous status and bypass the error.
1200 base::StringPiece der_cert
;
1201 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1203 return ERR_CERT_INVALID
;
1205 CertStatus cert_status
;
1206 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1207 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1208 server_cert_verify_result_
.Reset();
1209 server_cert_verify_result_
.cert_status
= cert_status
;
1210 server_cert_verify_result_
.verified_cert
= server_cert_
;
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_
, server_cert_verify_result_
.is_issued_by_known_root
,
1265 server_cert_verify_result_
.public_key_hashes
, server_cert_
.get(),
1266 server_cert_verify_result_
.verified_cert
.get(),
1267 TransportSecurityState::ENABLE_PIN_REPORTS
, &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
|=
1349 CERT_STATUS_CT_COMPLIANCE_FAILED
;
1350 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1355 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1356 int rv
= DoHandshakeLoop(result
);
1357 if (rv
!= ERR_IO_PENDING
) {
1358 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1359 DoConnectCallback(rv
);
1363 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1364 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1365 // In handshake phase.
1366 OnHandshakeIOComplete(result
);
1370 // During a renegotiation, a Read call may also be blocked on a transport
1371 // write, so retry both operations.
1372 PumpReadWriteEvents();
1375 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1376 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1377 // In handshake phase.
1378 OnHandshakeIOComplete(result
);
1382 // Network layer received some data, check if client requested to read
1384 if (!user_read_buf_
.get())
1387 int rv
= DoReadLoop();
1388 if (rv
!= ERR_IO_PENDING
)
1392 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1393 int rv
= last_io_result
;
1395 // Default to STATE_NONE for next state.
1396 // (This is a quirk carried over from the windows
1397 // implementation. It makes reading the logs a bit harder.)
1398 // State handlers can and often do call GotoState just
1399 // to stay in the current state.
1400 State state
= next_handshake_state_
;
1401 GotoState(STATE_NONE
);
1403 case STATE_HANDSHAKE
:
1406 case STATE_HANDSHAKE_COMPLETE
:
1407 rv
= DoHandshakeComplete(rv
);
1409 case STATE_CHANNEL_ID_LOOKUP
:
1411 rv
= DoChannelIDLookup();
1413 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1414 rv
= DoChannelIDLookupComplete(rv
);
1416 case STATE_VERIFY_CERT
:
1418 rv
= DoVerifyCert(rv
);
1420 case STATE_VERIFY_CERT_COMPLETE
:
1421 rv
= DoVerifyCertComplete(rv
);
1425 rv
= ERR_UNEXPECTED
;
1426 NOTREACHED() << "unexpected state" << state
;
1430 bool network_moved
= DoTransportIO();
1431 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1432 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1433 // special case we keep looping even if rv is ERR_IO_PENDING because
1434 // the transport IO may allow DoHandshake to make progress.
1435 rv
= OK
; // This causes us to stay in the loop.
1437 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1441 int SSLClientSocketOpenSSL::DoReadLoop() {
1445 rv
= DoPayloadRead();
1446 network_moved
= DoTransportIO();
1447 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1452 int SSLClientSocketOpenSSL::DoWriteLoop() {
1456 rv
= DoPayloadWrite();
1457 network_moved
= DoTransportIO();
1458 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1463 int SSLClientSocketOpenSSL::DoPayloadRead() {
1464 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1466 DCHECK_LT(0, user_read_buf_len_
);
1467 DCHECK(user_read_buf_
.get());
1470 if (pending_read_error_
!= kNoPendingResult
) {
1471 rv
= pending_read_error_
;
1472 pending_read_error_
= kNoPendingResult
;
1474 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1475 rv
, user_read_buf_
->data());
1478 NetLog::TYPE_SSL_READ_ERROR
,
1479 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1480 pending_read_error_info_
));
1482 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1483 pending_read_error_info_
= OpenSSLErrorInfo();
1487 int total_bytes_read
= 0;
1490 ssl_ret
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1491 user_read_buf_len_
- total_bytes_read
);
1493 total_bytes_read
+= ssl_ret
;
1494 } while (total_bytes_read
< user_read_buf_len_
&& ssl_ret
> 0);
1496 // Although only the final SSL_read call may have failed, the failure needs to
1497 // processed immediately, while the information still available in OpenSSL's
1500 // A zero return from SSL_read may mean any of:
1501 // - The underlying BIO_read returned 0.
1502 // - The peer sent a close_notify.
1503 // - Any arbitrary error. https://crbug.com/466303
1505 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1506 // error, so it does not occur. The second and third are distinguished by
1507 // SSL_ERROR_ZERO_RETURN.
1508 pending_read_ssl_error_
= SSL_get_error(ssl_
, ssl_ret
);
1509 if (pending_read_ssl_error_
== SSL_ERROR_ZERO_RETURN
) {
1510 pending_read_error_
= 0;
1511 } else if (pending_read_ssl_error_
== SSL_ERROR_WANT_X509_LOOKUP
&&
1512 !ssl_config_
.send_client_cert
) {
1513 pending_read_error_
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1514 } else if (pending_read_ssl_error_
==
1515 SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
) {
1516 DCHECK(private_key_
);
1517 DCHECK_NE(kNoPendingResult
, signature_result_
);
1518 pending_read_error_
= ERR_IO_PENDING
;
1520 pending_read_error_
= MapOpenSSLErrorWithDetails(
1521 pending_read_ssl_error_
, err_tracer
, &pending_read_error_info_
);
1524 // Many servers do not reliably send a close_notify alert when shutting down
1525 // a connection, and instead terminate the TCP connection. This is reported
1526 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1527 // graceful EOF, instead of treating it as an error as it should be.
1528 if (pending_read_error_
== ERR_CONNECTION_CLOSED
)
1529 pending_read_error_
= 0;
1532 if (total_bytes_read
> 0) {
1533 // Return any bytes read to the caller. The error will be deferred to the
1534 // next call of DoPayloadRead.
1535 rv
= total_bytes_read
;
1537 // Do not treat insufficient data as an error to return in the next call to
1538 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1539 // again. This is because DoTransportIO() may complete in between the next
1540 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1541 // subsequent invocations to see if a complete record may now be read.
1542 if (pending_read_error_
== ERR_IO_PENDING
)
1543 pending_read_error_
= kNoPendingResult
;
1545 // No bytes were returned. Return the pending read error immediately.
1546 DCHECK_NE(kNoPendingResult
, pending_read_error_
);
1547 rv
= pending_read_error_
;
1548 pending_read_error_
= kNoPendingResult
;
1552 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1553 user_read_buf_
->data());
1554 } else if (rv
!= ERR_IO_PENDING
) {
1556 NetLog::TYPE_SSL_READ_ERROR
,
1557 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1558 pending_read_error_info_
));
1559 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1560 pending_read_error_info_
= OpenSSLErrorInfo();
1565 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1566 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1567 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1570 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1571 user_write_buf_
->data());
1575 int ssl_error
= SSL_get_error(ssl_
, rv
);
1576 if (ssl_error
== SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
)
1577 return ERR_IO_PENDING
;
1578 OpenSSLErrorInfo error_info
;
1579 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1582 if (net_error
!= ERR_IO_PENDING
) {
1584 NetLog::TYPE_SSL_WRITE_ERROR
,
1585 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1590 void SSLClientSocketOpenSSL::PumpReadWriteEvents() {
1591 int rv_read
= ERR_IO_PENDING
;
1592 int rv_write
= ERR_IO_PENDING
;
1595 if (user_read_buf_
.get())
1596 rv_read
= DoPayloadRead();
1597 if (user_write_buf_
.get())
1598 rv_write
= DoPayloadWrite();
1599 network_moved
= DoTransportIO();
1600 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1601 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1603 // Performing the Read callback may cause |this| to be deleted. If this
1604 // happens, the Write callback should not be invoked. Guard against this by
1605 // holding a WeakPtr to |this| and ensuring it's still valid.
1606 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1607 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1608 DoReadCallback(rv_read
);
1613 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1614 DoWriteCallback(rv_write
);
1617 int SSLClientSocketOpenSSL::BufferSend(void) {
1618 if (transport_send_busy_
)
1619 return ERR_IO_PENDING
;
1621 size_t buffer_read_offset
;
1624 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1625 &buffer_read_offset
, &max_read
);
1626 DCHECK_EQ(status
, 1); // Should never fail.
1628 return 0; // Nothing pending in the OpenSSL write BIO.
1629 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1630 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1631 send_buffer_
->set_offset(buffer_read_offset
);
1633 int rv
= transport_
->socket()->Write(
1634 send_buffer_
.get(), max_read
,
1635 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1636 base::Unretained(this)));
1637 if (rv
== ERR_IO_PENDING
) {
1638 transport_send_busy_
= true;
1640 TransportWriteComplete(rv
);
1645 int SSLClientSocketOpenSSL::BufferRecv(void) {
1646 if (transport_recv_busy_
)
1647 return ERR_IO_PENDING
;
1649 // Determine how much was requested from |transport_bio_| that was not
1650 // actually available.
1651 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1652 if (requested
== 0) {
1653 // This is not a perfect match of error codes, as no operation is
1654 // actually pending. However, returning 0 would be interpreted as
1655 // a possible sign of EOF, which is also an inappropriate match.
1656 return ERR_IO_PENDING
;
1659 // Known Issue: While only reading |requested| data is the more correct
1660 // implementation, it has the downside of resulting in frequent reads:
1661 // One read for the SSL record header (~5 bytes) and one read for the SSL
1662 // record body. Rather than issuing these reads to the underlying socket
1663 // (and constantly allocating new IOBuffers), a single Read() request to
1664 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1665 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1666 // traffic, this over-subscribed Read()ing will not cause issues.
1668 size_t buffer_write_offset
;
1671 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1672 &buffer_write_offset
, &max_write
);
1673 DCHECK_EQ(status
, 1); // Should never fail.
1675 return ERR_IO_PENDING
;
1678 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1679 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1681 recv_buffer_
->set_offset(buffer_write_offset
);
1682 int rv
= transport_
->socket()->Read(
1685 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1686 base::Unretained(this)));
1687 if (rv
== ERR_IO_PENDING
) {
1688 transport_recv_busy_
= true;
1690 rv
= TransportReadComplete(rv
);
1695 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1696 TransportWriteComplete(result
);
1697 OnSendComplete(result
);
1700 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1701 result
= TransportReadComplete(result
);
1702 OnRecvComplete(result
);
1705 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1706 DCHECK(ERR_IO_PENDING
!= result
);
1707 int bytes_written
= 0;
1709 // Record the error. Save it to be reported in a future read or write on
1710 // transport_bio_'s peer.
1711 transport_write_error_
= result
;
1713 bytes_written
= result
;
1715 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1716 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1718 transport_send_busy_
= false;
1721 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1722 DCHECK(ERR_IO_PENDING
!= result
);
1723 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1724 // does not report success.
1726 result
= ERR_CONNECTION_CLOSED
;
1729 DVLOG(1) << "TransportReadComplete result " << result
;
1730 // Received an error. Save it to be reported in a future read on
1731 // transport_bio_'s peer.
1732 transport_read_error_
= result
;
1734 bytes_read
= result
;
1736 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1737 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1739 transport_recv_busy_
= false;
1743 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1744 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1745 DCHECK(ssl
== ssl_
);
1747 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1749 // Clear any currently configured certificates.
1750 SSL_certs_clear(ssl_
);
1753 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1754 LOG(WARNING
) << "Client auth is not supported";
1755 #else // !defined(OS_IOS)
1756 if (!ssl_config_
.send_client_cert
) {
1757 // First pass: we know that a client certificate is needed, but we do not
1758 // have one at hand.
1759 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1760 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1761 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1762 unsigned char* str
= NULL
;
1763 int length
= i2d_X509_NAME(ca_name
, &str
);
1764 cert_authorities_
.push_back(std::string(
1765 reinterpret_cast<const char*>(str
),
1766 static_cast<size_t>(length
)));
1770 const unsigned char* client_cert_types
;
1771 size_t num_client_cert_types
=
1772 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1773 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1774 cert_key_types_
.push_back(
1775 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1778 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1782 // Second pass: a client certificate should have been selected.
1783 if (ssl_config_
.client_cert
.get()) {
1784 ScopedX509 leaf_x509
=
1785 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1787 LOG(WARNING
) << "Failed to import certificate";
1788 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1792 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1793 ssl_config_
.client_cert
->GetIntermediateCertificates());
1795 LOG(WARNING
) << "Failed to import intermediate certificates";
1796 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1800 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1801 !SSL_set1_chain(ssl_
, chain
.get())) {
1802 LOG(WARNING
) << "Failed to set client certificate";
1806 #if defined(OS_NACL)
1807 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1810 // TODO(davidben): Lift this call up to the embedder so we can actually test
1811 // this code. https://crbug.com/394131
1812 private_key_
= FetchClientCertPrivateKey(
1813 ssl_config_
.client_cert
.get(),
1814 g_platform_key_task_runner
.Get().task_runner());
1815 if (!private_key_
) {
1816 // Could not find the private key. Fail the handshake and surface an
1817 // appropriate error to the caller.
1818 LOG(WARNING
) << "Client cert found without private key";
1819 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1823 SSL_set_private_key_method(ssl_
, &SSLContext::kPrivateKeyMethod
);
1826 int cert_count
= 1 + sk_X509_num(chain
.get());
1827 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1828 NetLog::IntegerCallback("cert_count", cert_count
));
1831 #endif // defined(OS_IOS)
1833 // Send no client certificate.
1834 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1835 NetLog::IntegerCallback("cert_count", 0));
1839 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1840 if (!completed_connect_
) {
1841 // If the first handshake hasn't completed then we accept any certificates
1842 // because we verify after the handshake.
1846 // Disallow the server certificate to change in a renegotiation.
1847 if (server_cert_chain_
->empty()) {
1848 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1851 base::StringPiece old_der
, new_der
;
1852 if (store_ctx
->cert
== NULL
||
1853 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1854 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1855 LOG(ERROR
) << "Failed to encode certificates";
1858 if (old_der
!= new_der
) {
1859 LOG(ERROR
) << "Server certificate changed between handshakes";
1866 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1867 // server supports NPN, selects a protocol from the list that the server
1868 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1869 // callback can assume that |in| is syntactically valid.
1870 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1871 unsigned char* outlen
,
1872 const unsigned char* in
,
1873 unsigned int inlen
) {
1874 if (ssl_config_
.next_protos
.empty()) {
1875 *out
= reinterpret_cast<uint8
*>(
1876 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1877 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1878 npn_status_
= kNextProtoUnsupported
;
1879 return SSL_TLSEXT_ERR_OK
;
1882 // Assume there's no overlap between our protocols and the server's list.
1883 npn_status_
= kNextProtoNoOverlap
;
1885 // For each protocol in server preference order, see if we support it.
1886 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1887 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1888 const std::string proto
= NextProtoToString(next_proto
);
1889 if (in
[i
] == proto
.size() &&
1890 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1891 // We found a match.
1892 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1894 npn_status_
= kNextProtoNegotiated
;
1898 if (npn_status_
== kNextProtoNegotiated
)
1902 // If we didn't find a protocol, we select the first one from our list.
1903 if (npn_status_
== kNextProtoNoOverlap
) {
1904 // NextProtoToString returns a pointer to a static string.
1905 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1906 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1907 *outlen
= strlen(proto
);
1910 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1911 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1912 set_negotiation_extension(kExtensionNPN
);
1913 return SSL_TLSEXT_ERR_OK
;
1916 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1919 const char *argp
, int argi
, long argl
,
1921 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1922 // If there is no more data in the buffer, report any pending errors that
1923 // were observed. Note that both the readbuf and the writebuf are checked
1924 // for errors, since the application may have encountered a socket error
1925 // while writing that would otherwise not be reported until the application
1926 // attempted to write again - which it may never do. See
1927 // https://crbug.com/249848.
1928 if (transport_read_error_
!= OK
) {
1929 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1932 if (transport_write_error_
!= OK
) {
1933 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1936 } else if (cmd
== BIO_CB_WRITE
) {
1937 // Because of the write buffer, this reports a failure from the previous
1938 // write payload. If the current payload fails to write, the error will be
1939 // reported in a future write or read to |bio|.
1940 if (transport_write_error_
!= OK
) {
1941 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1949 long SSLClientSocketOpenSSL::BIOCallback(
1952 const char *argp
, int argi
, long argl
,
1954 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1955 BIO_get_callback_arg(bio
));
1957 return socket
->MaybeReplayTransportError(
1958 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1961 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1962 // Only cache the session once both a new session has been established and the
1963 // certificate has been verified. Due to False Start, these events may happen
1965 if (!session_pending_
|| !certificate_verified_
)
1968 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1969 SSL_get_session(ssl_
));
1970 session_pending_
= false;
1973 int SSLClientSocketOpenSSL::NewSessionCallback(SSL_SESSION
* session
) {
1974 DCHECK_EQ(session
, SSL_get_session(ssl_
));
1976 // Only sessions from the initial handshake get cached. Note this callback may
1977 // be signaled on abbreviated handshakes if the ticket was renewed.
1978 session_pending_
= true;
1979 MaybeCacheSession();
1981 // OpenSSL passes a reference to |session|, but the session cache does not
1982 // take this reference, so release it.
1983 SSL_SESSION_free(session
);
1987 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
1988 for (ct::SCTList::const_iterator iter
=
1989 ct_verify_result_
.verified_scts
.begin();
1990 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
1991 ssl_info
->signed_certificate_timestamps
.push_back(
1992 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
1994 for (ct::SCTList::const_iterator iter
=
1995 ct_verify_result_
.invalid_scts
.begin();
1996 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
1997 ssl_info
->signed_certificate_timestamps
.push_back(
1998 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
2000 for (ct::SCTList::const_iterator iter
=
2001 ct_verify_result_
.unknown_logs_scts
.begin();
2002 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
2003 ssl_info
->signed_certificate_timestamps
.push_back(
2004 SignedCertificateTimestampAndStatus(*iter
,
2005 ct::SCT_STATUS_LOG_UNKNOWN
));
2009 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
2010 std::string result
= host_and_port_
.ToString();
2012 result
.append(ssl_session_cache_shard_
);
2014 // Shard the session cache based on maximum protocol version. This causes
2015 // fallback connections to use a separate session cache.
2017 switch (ssl_config_
.version_max
) {
2018 case SSL_PROTOCOL_VERSION_TLS1
:
2019 result
.append("tls1");
2021 case SSL_PROTOCOL_VERSION_TLS1_1
:
2022 result
.append("tls1.1");
2024 case SSL_PROTOCOL_VERSION_TLS1_2
:
2025 result
.append("tls1.2");
2032 if (ssl_config_
.enable_deprecated_cipher_suites
)
2033 result
.append("deprecated");
2038 bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
2039 if (npn_status_
== kNextProtoUnsupported
)
2040 return ssl_config_
.renego_allowed_default
;
2042 NextProto next_proto
= NextProtoFromString(npn_proto_
);
2043 for (NextProto allowed
: ssl_config_
.renego_allowed_for_protos
) {
2044 if (next_proto
== allowed
)
2050 int SSLClientSocketOpenSSL::PrivateKeyTypeCallback() {
2051 switch (private_key_
->GetType()) {
2052 case SSLPrivateKey::Type::RSA
:
2053 return EVP_PKEY_RSA
;
2054 case SSLPrivateKey::Type::ECDSA
:
2058 return EVP_PKEY_NONE
;
2061 int SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback(const EVP_MD
* md
) {
2062 SSLPrivateKey::Hash hash
;
2063 return EVP_MDToPrivateKeyHash(md
, &hash
) && private_key_
->SupportsHash(hash
);
2066 size_t SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback() {
2067 return private_key_
->GetMaxSignatureLengthInBytes();
2070 ssl_private_key_result_t
SSLClientSocketOpenSSL::PrivateKeySignCallback(
2077 DCHECK_EQ(kNoPendingResult
, signature_result_
);
2078 DCHECK(signature_
.empty());
2079 DCHECK(private_key_
);
2081 net_log_
.BeginEvent(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION
);
2083 SSLPrivateKey::Hash hash
;
2084 if (!EVP_MDToPrivateKeyHash(md
, &hash
)) {
2085 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
2086 return ssl_private_key_failure
;
2089 signature_result_
= ERR_IO_PENDING
;
2090 private_key_
->SignDigest(
2091 hash
, base::StringPiece(reinterpret_cast<const char*>(in
), in_len
),
2092 base::Bind(&SSLClientSocketOpenSSL::OnPrivateKeySignComplete
,
2093 weak_factory_
.GetWeakPtr()));
2094 return ssl_private_key_retry
;
2097 ssl_private_key_result_t
SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback(
2101 DCHECK_NE(kNoPendingResult
, signature_result_
);
2102 DCHECK(private_key_
);
2104 if (signature_result_
== ERR_IO_PENDING
)
2105 return ssl_private_key_retry
;
2106 if (signature_result_
!= OK
) {
2107 OpenSSLPutNetError(FROM_HERE
, signature_result_
);
2108 return ssl_private_key_failure
;
2110 if (signature_
.size() > max_out
) {
2111 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
2112 return ssl_private_key_failure
;
2114 memcpy(out
, vector_as_array(&signature_
), signature_
.size());
2115 *out_len
= signature_
.size();
2117 return ssl_private_key_success
;
2120 void SSLClientSocketOpenSSL::OnPrivateKeySignComplete(
2122 const std::vector
<uint8_t>& signature
) {
2123 DCHECK_EQ(ERR_IO_PENDING
, signature_result_
);
2124 DCHECK(signature_
.empty());
2125 DCHECK(private_key_
);
2127 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION
,
2130 signature_result_
= error
;
2131 if (signature_result_
== OK
)
2132 signature_
= signature
;
2134 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2135 OnHandshakeIOComplete(signature_result_
);
2139 // During a renegotiation, either Read or Write calls may be blocked on an
2140 // asynchronous private key operation.
2141 PumpReadWriteEvents();