1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // OpenSSL binding for SSLClientSocket. The class layout and general principle
6 // of operation is derived from SSLClientSocketNSS.
8 #include "net/socket/ssl_client_socket_openssl.h"
11 #include <openssl/bio.h>
12 #include <openssl/err.h>
13 #include <openssl/mem.h>
14 #include <openssl/ssl.h>
17 #include "base/bind.h"
18 #include "base/callback_helpers.h"
19 #include "base/environment.h"
20 #include "base/lazy_instance.h"
21 #include "base/memory/singleton.h"
22 #include "base/metrics/histogram_macros.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/stl_util.h"
25 #include "base/strings/string_piece.h"
26 #include "base/synchronization/lock.h"
27 #include "base/threading/sequenced_worker_pool.h"
28 #include "base/threading/thread_local.h"
29 #include "base/values.h"
30 #include "crypto/ec_private_key.h"
31 #include "crypto/openssl_util.h"
32 #include "crypto/scoped_openssl_types.h"
33 #include "net/base/ip_address_number.h"
34 #include "net/base/net_errors.h"
35 #include "net/cert/cert_policy_enforcer.h"
36 #include "net/cert/cert_verifier.h"
37 #include "net/cert/ct_ev_whitelist.h"
38 #include "net/cert/ct_verifier.h"
39 #include "net/cert/x509_certificate_net_log_param.h"
40 #include "net/cert/x509_util_openssl.h"
41 #include "net/http/transport_security_state.h"
42 #include "net/ssl/scoped_openssl_types.h"
43 #include "net/ssl/ssl_cert_request_info.h"
44 #include "net/ssl/ssl_client_session_cache_openssl.h"
45 #include "net/ssl/ssl_connection_status_flags.h"
46 #include "net/ssl/ssl_failure_state.h"
47 #include "net/ssl/ssl_info.h"
48 #include "net/ssl/ssl_private_key.h"
51 #include "base/win/windows_version.h"
54 #if defined(USE_OPENSSL_CERTS)
55 #include "net/ssl/openssl_client_key_store.h"
57 #include "net/ssl/ssl_platform_key.h"
64 // Enable this to see logging for state machine state transitions.
66 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
67 " jump to state " << s; \
68 next_handshake_state_ = s; } while (0)
70 #define GotoState(s) next_handshake_state_ = s
73 // This constant can be any non-negative/non-zero value (eg: it does not
74 // overlap with any value of the net::Error range, including net::OK).
75 const int kNoPendingResult
= 1;
77 // If a client doesn't have a list of protocols that it supports, but
78 // the server supports NPN, choosing "http/1.1" is the best answer.
79 const char kDefaultSupportedNPNProtocol
[] = "http/1.1";
81 // Default size of the internal BoringSSL buffers.
82 const int KDefaultOpenSSLBufferSize
= 17 * 1024;
84 void FreeX509Stack(STACK_OF(X509
)* ptr
) {
85 sk_X509_pop_free(ptr
, X509_free
);
88 using ScopedX509Stack
= crypto::ScopedOpenSSL
<STACK_OF(X509
), FreeX509Stack
>;
90 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
91 // This method doesn't seem to have made it into the OpenSSL headers.
92 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER
* cipher
) { return cipher
->id
; }
95 // Used for encoding the |connection_status| field of an SSLInfo object.
96 int EncodeSSLConnectionStatus(uint16 cipher_suite
,
100 ((compression
& SSL_CONNECTION_COMPRESSION_MASK
) <<
101 SSL_CONNECTION_COMPRESSION_SHIFT
) |
102 ((version
& SSL_CONNECTION_VERSION_MASK
) <<
103 SSL_CONNECTION_VERSION_SHIFT
);
106 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
107 // this SSL connection.
108 int GetNetSSLVersion(SSL
* ssl
) {
109 switch (SSL_version(ssl
)) {
111 return SSL_CONNECTION_VERSION_TLS1
;
113 return SSL_CONNECTION_VERSION_TLS1_1
;
115 return SSL_CONNECTION_VERSION_TLS1_2
;
118 return SSL_CONNECTION_VERSION_UNKNOWN
;
122 ScopedX509
OSCertHandleToOpenSSL(
123 X509Certificate::OSCertHandle os_handle
) {
124 #if defined(USE_OPENSSL_CERTS)
125 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle
));
126 #else // !defined(USE_OPENSSL_CERTS)
127 std::string der_encoded
;
128 if (!X509Certificate::GetDEREncoded(os_handle
, &der_encoded
))
130 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
131 return ScopedX509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
132 #endif // defined(USE_OPENSSL_CERTS)
135 ScopedX509Stack
OSCertHandlesToOpenSSL(
136 const X509Certificate::OSCertHandles
& os_handles
) {
137 ScopedX509Stack
stack(sk_X509_new_null());
138 for (size_t i
= 0; i
< os_handles
.size(); i
++) {
139 ScopedX509 x509
= OSCertHandleToOpenSSL(os_handles
[i
]);
141 return ScopedX509Stack();
142 sk_X509_push(stack
.get(), x509
.release());
147 int LogErrorCallback(const char* str
, size_t len
, void* context
) {
148 LOG(ERROR
) << base::StringPiece(str
, len
);
152 bool EVP_MDToPrivateKeyHash(const EVP_MD
* md
, SSLPrivateKey::Hash
* hash
) {
153 switch (EVP_MD_type(md
)) {
155 *hash
= SSLPrivateKey::Hash::MD5_SHA1
;
158 *hash
= SSLPrivateKey::Hash::SHA1
;
161 *hash
= SSLPrivateKey::Hash::SHA256
;
164 *hash
= SSLPrivateKey::Hash::SHA384
;
167 *hash
= SSLPrivateKey::Hash::SHA512
;
174 #if !defined(USE_OPENSSL_CERTS)
175 class PlatformKeyTaskRunner
{
177 PlatformKeyTaskRunner() {
178 // Serialize all the private key operations on a single background
179 // thread to avoid problems with buggy smartcards.
180 worker_pool_
= new base::SequencedWorkerPool(1, "Platform Key Thread");
181 task_runner_
= worker_pool_
->GetSequencedTaskRunnerWithShutdownBehavior(
182 worker_pool_
->GetSequenceToken(),
183 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN
);
186 scoped_refptr
<base::SequencedTaskRunner
> task_runner() {
191 scoped_refptr
<base::SequencedWorkerPool
> worker_pool_
;
192 scoped_refptr
<base::SequencedTaskRunner
> task_runner_
;
194 DISALLOW_COPY_AND_ASSIGN(PlatformKeyTaskRunner
);
197 base::LazyInstance
<PlatformKeyTaskRunner
>::Leaky g_platform_key_task_runner
=
198 LAZY_INSTANCE_INITIALIZER
;
199 #endif // !USE_OPENSSL_CERTS
203 class SSLClientSocketOpenSSL::SSLContext
{
205 static SSLContext
* GetInstance() { return Singleton
<SSLContext
>::get(); }
206 SSL_CTX
* ssl_ctx() { return ssl_ctx_
.get(); }
207 SSLClientSessionCacheOpenSSL
* session_cache() { return &session_cache_
; }
209 SSLClientSocketOpenSSL
* GetClientSocketFromSSL(const SSL
* ssl
) {
211 SSLClientSocketOpenSSL
* socket
= static_cast<SSLClientSocketOpenSSL
*>(
212 SSL_get_ex_data(ssl
, ssl_socket_data_index_
));
217 bool SetClientSocketForSSL(SSL
* ssl
, SSLClientSocketOpenSSL
* socket
) {
218 return SSL_set_ex_data(ssl
, ssl_socket_data_index_
, socket
) != 0;
221 static const SSL_PRIVATE_KEY_METHOD kPrivateKeyMethod
;
224 friend struct DefaultSingletonTraits
<SSLContext
>;
226 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
227 crypto::EnsureOpenSSLInit();
228 ssl_socket_data_index_
= SSL_get_ex_new_index(0, 0, 0, 0, 0);
229 DCHECK_NE(ssl_socket_data_index_
, -1);
230 ssl_ctx_
.reset(SSL_CTX_new(SSLv23_client_method()));
231 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
232 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
233 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
234 // This stops |SSL_shutdown| from generating the close_notify message, which
235 // is currently not sent on the network.
236 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
237 SSL_CTX_set_quiet_shutdown(ssl_ctx_
.get(), 1);
238 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
239 // It would be better if the callback were not a global setting,
240 // but that is an OpenSSL issue.
241 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
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 npn_status_(kNextProtoUnsupported
),
470 channel_id_sent_(false),
471 session_pending_(false),
472 certificate_verified_(false),
473 ssl_failure_state_(SSL_FAILURE_NONE
),
474 signature_result_(kNoPendingResult
),
475 transport_security_state_(context
.transport_security_state
),
476 policy_enforcer_(context
.cert_policy_enforcer
),
477 net_log_(transport_
->socket()->NetLog()),
478 weak_factory_(this) {
479 DCHECK(cert_verifier_
);
482 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
486 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
487 SSLCertRequestInfo
* cert_request_info
) {
488 cert_request_info
->host_and_port
= host_and_port_
;
489 cert_request_info
->cert_authorities
= cert_authorities_
;
490 cert_request_info
->cert_key_types
= cert_key_types_
;
493 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
494 std::string
* proto
) const {
500 SSLClientSocketOpenSSL::GetChannelIDService() const {
501 return channel_id_service_
;
504 SSLFailureState
SSLClientSocketOpenSSL::GetSSLFailureState() const {
505 return ssl_failure_state_
;
508 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
509 const base::StringPiece
& label
,
510 bool has_context
, const base::StringPiece
& context
,
511 unsigned char* out
, unsigned int outlen
) {
513 return ERR_SOCKET_NOT_CONNECTED
;
515 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
517 int rv
= SSL_export_keying_material(
518 ssl_
, out
, outlen
, label
.data(), label
.size(),
519 reinterpret_cast<const unsigned char*>(context
.data()), context
.length(),
520 has_context
? 1 : 0);
523 int ssl_error
= SSL_get_error(ssl_
, rv
);
524 LOG(ERROR
) << "Failed to export keying material;"
525 << " returned " << rv
526 << ", SSL error code " << ssl_error
;
527 return MapOpenSSLError(ssl_error
, err_tracer
);
532 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
534 return ERR_NOT_IMPLEMENTED
;
537 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
538 // It is an error to create an SSLClientSocket whose context has no
539 // TransportSecurityState.
540 DCHECK(transport_security_state_
);
542 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
544 // Set up new ssl object.
547 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
551 // Set SSL to client mode. Handshake happens in the loop below.
552 SSL_set_connect_state(ssl_
);
554 GotoState(STATE_HANDSHAKE
);
555 rv
= DoHandshakeLoop(OK
);
556 if (rv
== ERR_IO_PENDING
) {
557 user_connect_callback_
= callback
;
559 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
562 return rv
> OK
? OK
: rv
;
565 void SSLClientSocketOpenSSL::Disconnect() {
567 // Calling SSL_shutdown prevents the session from being marked as
573 if (transport_bio_
) {
574 BIO_free_all(transport_bio_
);
575 transport_bio_
= NULL
;
578 // Shut down anything that may call us back.
579 cert_verifier_request_
.reset();
580 transport_
->socket()->Disconnect();
582 // Null all callbacks, delete all buffers.
583 transport_send_busy_
= false;
585 transport_recv_busy_
= false;
588 user_connect_callback_
.Reset();
589 user_read_callback_
.Reset();
590 user_write_callback_
.Reset();
591 user_read_buf_
= NULL
;
592 user_read_buf_len_
= 0;
593 user_write_buf_
= NULL
;
594 user_write_buf_len_
= 0;
596 pending_read_error_
= kNoPendingResult
;
597 pending_read_ssl_error_
= SSL_ERROR_NONE
;
598 pending_read_error_info_
= OpenSSLErrorInfo();
600 transport_read_error_
= OK
;
601 transport_write_error_
= OK
;
603 server_cert_verify_result_
.Reset();
604 completed_connect_
= false;
606 cert_authorities_
.clear();
607 cert_key_types_
.clear();
609 start_cert_verification_time_
= base::TimeTicks();
611 npn_status_
= kNextProtoUnsupported
;
614 channel_id_sent_
= false;
615 session_pending_
= false;
616 certificate_verified_
= false;
617 channel_id_request_
.Cancel();
618 ssl_failure_state_
= SSL_FAILURE_NONE
;
620 private_key_
.reset();
621 signature_result_
= kNoPendingResult
;
625 bool SSLClientSocketOpenSSL::IsConnected() const {
626 // If the handshake has not yet completed.
627 if (!completed_connect_
)
629 // If an asynchronous operation is still pending.
630 if (user_read_buf_
.get() || user_write_buf_
.get())
633 return transport_
->socket()->IsConnected();
636 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() 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 // If there is data read from the network that has not yet been consumed, do
645 // not treat the connection as idle.
647 // Note that this does not check |BIO_pending|, whether there is ciphertext
648 // that has not yet been flushed to the network. |Write| returns early, so
649 // this can cause race conditions which cause a socket to not be treated
650 // reusable when it should be. See https://crbug.com/466147.
651 if (BIO_wpending(transport_bio_
) > 0)
654 return transport_
->socket()->IsConnectedAndIdle();
657 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
658 return transport_
->socket()->GetPeerAddress(addressList
);
661 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
662 return transport_
->socket()->GetLocalAddress(addressList
);
665 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
669 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
670 if (transport_
.get() && transport_
->socket()) {
671 transport_
->socket()->SetSubresourceSpeculation();
677 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
678 if (transport_
.get() && transport_
->socket()) {
679 transport_
->socket()->SetOmniboxSpeculation();
685 bool SSLClientSocketOpenSSL::WasEverUsed() const {
686 return was_ever_used_
;
689 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
690 if (transport_
.get() && transport_
->socket())
691 return transport_
->socket()->UsingTCPFastOpen();
697 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
699 if (server_cert_chain_
->empty())
702 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
703 ssl_info
->unverified_cert
= server_cert_
;
704 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
705 ssl_info
->is_issued_by_known_root
=
706 server_cert_verify_result_
.is_issued_by_known_root
;
707 ssl_info
->public_key_hashes
=
708 server_cert_verify_result_
.public_key_hashes
;
709 ssl_info
->client_cert_sent
=
710 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
711 ssl_info
->channel_id_sent
= channel_id_sent_
;
712 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
714 AddSCTInfoToSSLInfo(ssl_info
);
716 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
718 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
720 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
721 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
722 GetNetSSLVersion(ssl_
));
724 if (!SSL_get_secure_renegotiation_support(ssl_
))
725 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
727 if (ssl_config_
.version_fallback
)
728 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
730 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
731 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
733 DVLOG(3) << "Encoded connection status: cipher suite = "
734 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
736 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
740 void SSLClientSocketOpenSSL::GetConnectionAttempts(
741 ConnectionAttempts
* out
) const {
745 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
747 const CompletionCallback
& callback
) {
748 user_read_buf_
= buf
;
749 user_read_buf_len_
= buf_len
;
751 int rv
= DoReadLoop();
753 if (rv
== ERR_IO_PENDING
) {
754 user_read_callback_
= callback
;
757 was_ever_used_
= true;
758 user_read_buf_
= NULL
;
759 user_read_buf_len_
= 0;
765 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
767 const CompletionCallback
& callback
) {
768 user_write_buf_
= buf
;
769 user_write_buf_len_
= buf_len
;
771 int rv
= DoWriteLoop();
773 if (rv
== ERR_IO_PENDING
) {
774 user_write_callback_
= callback
;
777 was_ever_used_
= true;
778 user_write_buf_
= NULL
;
779 user_write_buf_len_
= 0;
785 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
786 return transport_
->socket()->SetReceiveBufferSize(size
);
789 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
790 return transport_
->socket()->SetSendBufferSize(size
);
793 int SSLClientSocketOpenSSL::Init() {
795 DCHECK(!transport_bio_
);
797 SSLContext
* context
= SSLContext::GetInstance();
798 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
800 ssl_
= SSL_new(context
->ssl_ctx());
801 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
802 return ERR_UNEXPECTED
;
804 // SNI should only contain valid DNS hostnames, not IP addresses (see RFC
807 // TODO(rsleevi): Should this code allow hostnames that violate the LDH rule?
808 // See https://crbug.com/496472 and https://crbug.com/496468 for discussion.
809 IPAddressNumber unused
;
810 if (!ParseIPLiteralToNumber(host_and_port_
.host(), &unused
) &&
811 !SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str())) {
812 return ERR_UNEXPECTED
;
815 SSL_SESSION
* session
= context
->session_cache()->Lookup(GetSessionCacheKey());
816 if (session
!= nullptr)
817 SSL_set_session(ssl_
, session
);
819 send_buffer_
= new GrowableIOBuffer();
820 send_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
821 recv_buffer_
= new GrowableIOBuffer();
822 recv_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
826 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
827 if (!BIO_new_bio_pair_external_buf(
828 &ssl_bio
, send_buffer_
->capacity(),
829 reinterpret_cast<uint8_t*>(send_buffer_
->data()), &transport_bio_
,
830 recv_buffer_
->capacity(),
831 reinterpret_cast<uint8_t*>(recv_buffer_
->data())))
832 return ERR_UNEXPECTED
;
834 DCHECK(transport_bio_
);
836 // Install a callback on OpenSSL's end to plumb transport errors through.
837 BIO_set_callback(ssl_bio
, &SSLClientSocketOpenSSL::BIOCallback
);
838 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
840 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
842 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_min
);
843 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_max
);
844 SSL_set_min_version(ssl_
, ssl_config_
.version_min
);
845 SSL_set_max_version(ssl_
, ssl_config_
.version_max
);
847 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
848 // set everything we care about to an absolute value.
849 SslSetClearMask options
;
850 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
852 // TODO(joth): Set this conditionally, see http://crbug.com/55410
853 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
855 SSL_set_options(ssl_
, options
.set_mask
);
856 SSL_clear_options(ssl_
, options
.clear_mask
);
858 // Same as above, this time for the SSL mode.
859 SslSetClearMask mode
;
861 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
862 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
864 mode
.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START
,
865 ssl_config_
.false_start_enabled
);
867 mode
.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV
, ssl_config_
.version_fallback
);
869 SSL_set_mode(ssl_
, mode
.set_mask
);
870 SSL_clear_mode(ssl_
, mode
.clear_mask
);
872 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
873 // textual name with SSL_set_cipher_list because there is no public API to
874 // directly remove a cipher by ID.
875 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
877 // See SSLConfig::disabled_cipher_suites for description of the suites
878 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
879 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
880 // as the handshake hash.
881 std::string
command("DEFAULT:!SHA256:!SHA384:!AESGCM+AES256:!aPSK");
882 // Walk through all the installed ciphers, seeing if any need to be
883 // appended to the cipher removal |command|.
884 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
885 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
886 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
887 bool disable
= false;
888 if (ssl_config_
.require_ecdhe
) {
889 base::StringPiece
kx_name(SSL_CIPHER_get_kx_name(cipher
));
890 disable
= kx_name
!= "ECDHE_RSA" && kx_name
!= "ECDHE_ECDSA";
893 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
894 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
895 ssl_config_
.disabled_cipher_suites
.end();
898 const char* name
= SSL_CIPHER_get_name(cipher
);
899 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
900 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
901 command
.append(":!");
902 command
.append(name
);
906 if (!ssl_config_
.enable_deprecated_cipher_suites
)
907 command
.append(":!RC4");
909 // Disable ECDSA cipher suites on platforms that do not support ECDSA
910 // signed certificates, as servers may use the presence of such
911 // ciphersuites as a hint to send an ECDSA certificate.
913 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
914 command
.append(":!ECDSA");
917 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
918 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
919 // This will almost certainly result in the socket failing to complete the
920 // handshake at which point the appropriate error is bubbled up to the client.
921 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
925 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
926 SSL_enable_tls_channel_id(ssl_
);
929 if (!ssl_config_
.next_protos
.empty()) {
930 // Get list of ciphers that are enabled.
931 STACK_OF(SSL_CIPHER
)* enabled_ciphers
= SSL_get_ciphers(ssl_
);
932 DCHECK(enabled_ciphers
);
933 std::vector
<uint16
> enabled_ciphers_vector
;
934 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(enabled_ciphers
); ++i
) {
935 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(enabled_ciphers
, i
);
936 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
937 enabled_ciphers_vector
.push_back(id
);
940 std::vector
<uint8_t> wire_protos
=
941 SerializeNextProtos(ssl_config_
.next_protos
,
942 HasCipherAdequateForHTTP2(enabled_ciphers_vector
) &&
943 IsTLSVersionAdequateForHTTP2(ssl_config_
));
944 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
948 if (ssl_config_
.signed_cert_timestamps_enabled
) {
949 SSL_enable_signed_cert_timestamps(ssl_
);
950 SSL_enable_ocsp_stapling(ssl_
);
953 if (cert_verifier_
->SupportsOCSPStapling())
954 SSL_enable_ocsp_stapling(ssl_
);
956 // By default, renegotiations are rejected. After the initial handshake
957 // completes, some application protocols may re-enable it.
958 SSL_set_reject_peer_renegotiations(ssl_
, 1);
963 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
964 // Since Run may result in Read being called, clear |user_read_callback_|
967 was_ever_used_
= true;
968 user_read_buf_
= NULL
;
969 user_read_buf_len_
= 0;
970 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
973 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
974 // Since Run may result in Write being called, clear |user_write_callback_|
977 was_ever_used_
= true;
978 user_write_buf_
= NULL
;
979 user_write_buf_len_
= 0;
980 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
983 bool SSLClientSocketOpenSSL::DoTransportIO() {
984 bool network_moved
= false;
986 // Read and write as much data as possible. The loop is necessary because
987 // Write() may return synchronously.
990 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
991 network_moved
= true;
993 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
994 network_moved
= true;
995 return network_moved
;
998 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
999 // g_first_run_completed once crbug.com/424386 is fixed.
1000 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
1001 LAZY_INSTANCE_INITIALIZER
;
1003 int SSLClientSocketOpenSSL::DoHandshake() {
1004 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1008 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
1010 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
1011 rv
= SSL_do_handshake(ssl_
);
1013 if (g_first_run_completed
.Get().Get()) {
1014 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
1016 tracked_objects::ScopedTracker
tracking_profile(
1017 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
1019 rv
= SSL_do_handshake(ssl_
);
1021 g_first_run_completed
.Get().Set(true);
1022 rv
= SSL_do_handshake(ssl_
);
1028 int ssl_error
= SSL_get_error(ssl_
, rv
);
1029 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
1030 // The server supports channel ID. Stop to look one up before returning to
1032 GotoState(STATE_CHANNEL_ID_LOOKUP
);
1035 if (ssl_error
== SSL_ERROR_WANT_X509_LOOKUP
&&
1036 !ssl_config_
.send_client_cert
) {
1037 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1039 if (ssl_error
== SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
) {
1040 DCHECK(private_key_
);
1041 DCHECK_NE(kNoPendingResult
, signature_result_
);
1042 GotoState(STATE_HANDSHAKE
);
1043 return ERR_IO_PENDING
;
1046 OpenSSLErrorInfo error_info
;
1047 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
1048 if (net_error
== ERR_IO_PENDING
) {
1049 // If not done, stay in this state
1050 GotoState(STATE_HANDSHAKE
);
1051 return ERR_IO_PENDING
;
1054 LOG(ERROR
) << "handshake failed; returned " << rv
<< ", SSL error code "
1055 << ssl_error
<< ", net_error " << net_error
;
1057 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1058 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1060 // Classify the handshake failure. This is used to determine causes of the
1061 // TLS version fallback.
1063 // |cipher| is the current outgoing cipher suite, so it is non-null iff
1064 // ChangeCipherSpec was sent.
1065 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
1066 if (SSL_get_state(ssl_
) == SSL3_ST_CR_SRVR_HELLO_A
) {
1067 ssl_failure_state_
= SSL_FAILURE_CLIENT_HELLO
;
1068 } else if (cipher
&& (SSL_CIPHER_get_id(cipher
) ==
1069 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256
||
1070 SSL_CIPHER_get_id(cipher
) ==
1071 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256
)) {
1072 ssl_failure_state_
= SSL_FAILURE_BUGGY_GCM
;
1073 } else if (cipher
&& ssl_config_
.send_client_cert
) {
1074 ssl_failure_state_
= SSL_FAILURE_CLIENT_AUTH
;
1075 } else if (ERR_GET_LIB(error_info
.error_code
) == ERR_LIB_SSL
&&
1076 ERR_GET_REASON(error_info
.error_code
) ==
1077 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED
) {
1078 ssl_failure_state_
= SSL_FAILURE_SESSION_MISMATCH
;
1079 } else if (cipher
&& npn_status_
!= kNextProtoUnsupported
) {
1080 ssl_failure_state_
= SSL_FAILURE_NEXT_PROTO
;
1082 ssl_failure_state_
= SSL_FAILURE_UNKNOWN
;
1086 GotoState(STATE_HANDSHAKE_COMPLETE
);
1090 int SSLClientSocketOpenSSL::DoHandshakeComplete(int result
) {
1094 if (ssl_config_
.version_fallback
&&
1095 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
1096 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
1099 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1100 if (npn_status_
== kNextProtoUnsupported
) {
1101 const uint8_t* alpn_proto
= NULL
;
1102 unsigned alpn_len
= 0;
1103 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
1105 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
1106 npn_status_
= kNextProtoNegotiated
;
1107 set_negotiation_extension(kExtensionALPN
);
1111 RecordNegotiationExtension();
1112 RecordChannelIDSupport(channel_id_service_
, channel_id_sent_
,
1113 ssl_config_
.channel_id_enabled
,
1114 crypto::ECPrivateKey::IsSupported());
1116 // Only record OCSP histograms if OCSP was requested.
1117 if (ssl_config_
.signed_cert_timestamps_enabled
||
1118 cert_verifier_
->SupportsOCSPStapling()) {
1119 const uint8_t* ocsp_response
;
1120 size_t ocsp_response_len
;
1121 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
1123 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
1124 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
1127 const uint8_t* sct_list
;
1128 size_t sct_list_len
;
1129 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
1130 set_signed_cert_timestamps_received(sct_list_len
!= 0);
1132 if (IsRenegotiationAllowed())
1133 SSL_set_reject_peer_renegotiations(ssl_
, 0);
1135 // Verify the certificate.
1137 GotoState(STATE_VERIFY_CERT
);
1141 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1142 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
);
1143 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1144 return channel_id_service_
->GetOrCreateChannelID(
1145 host_and_port_
.host(), &channel_id_key_
,
1146 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1147 base::Unretained(this)),
1148 &channel_id_request_
);
1151 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1155 if (!channel_id_key_
) {
1156 LOG(ERROR
) << "Failed to import Channel ID.";
1157 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1160 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1162 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1163 int rv
= SSL_set1_tls_channel_id(ssl_
, channel_id_key_
->key());
1165 LOG(ERROR
) << "Failed to set Channel ID.";
1166 int err
= SSL_get_error(ssl_
, rv
);
1167 return MapOpenSSLError(err
, err_tracer
);
1170 // Return to the handshake.
1171 channel_id_sent_
= true;
1172 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
);
1173 GotoState(STATE_HANDSHAKE
);
1177 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1178 DCHECK(!server_cert_chain_
->empty());
1179 DCHECK(start_cert_verification_time_
.is_null());
1181 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1183 // If the certificate is bad and has been previously accepted, use
1184 // the previous status and bypass the error.
1185 base::StringPiece der_cert
;
1186 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1188 return ERR_CERT_INVALID
;
1190 CertStatus cert_status
;
1191 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1192 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1193 server_cert_verify_result_
.Reset();
1194 server_cert_verify_result_
.cert_status
= cert_status
;
1195 server_cert_verify_result_
.verified_cert
= server_cert_
;
1199 // When running in a sandbox, it may not be possible to create an
1200 // X509Certificate*, as that may depend on OS functionality blocked
1202 if (!server_cert_
.get()) {
1203 server_cert_verify_result_
.Reset();
1204 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
1205 return ERR_CERT_INVALID
;
1208 std::string ocsp_response
;
1209 if (cert_verifier_
->SupportsOCSPStapling()) {
1210 const uint8_t* ocsp_response_raw
;
1211 size_t ocsp_response_len
;
1212 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1213 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1217 start_cert_verification_time_
= base::TimeTicks::Now();
1219 return cert_verifier_
->Verify(
1220 server_cert_
.get(), host_and_port_
.host(), ocsp_response
,
1221 ssl_config_
.GetCertVerifyFlags(),
1222 // TODO(davidben): Route the CRLSet through SSLConfig so
1223 // SSLClientSocket doesn't depend on SSLConfigService.
1224 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_
,
1225 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1226 base::Unretained(this)),
1227 &cert_verifier_request_
, net_log_
);
1230 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1231 cert_verifier_request_
.reset();
1233 if (!start_cert_verification_time_
.is_null()) {
1234 base::TimeDelta verify_time
=
1235 base::TimeTicks::Now() - start_cert_verification_time_
;
1237 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1239 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1244 if (SSL_session_reused(ssl_
)) {
1245 // Record whether or not the server tried to resume a session for a
1246 // different version. See https://crbug.com/441456.
1247 UMA_HISTOGRAM_BOOLEAN(
1248 "Net.SSLSessionVersionMatch",
1249 SSL_version(ssl_
) == SSL_get_session(ssl_
)->ssl_version
);
1253 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1254 if (transport_security_state_
&&
1256 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1257 !transport_security_state_
->CheckPublicKeyPins(
1258 host_and_port_
, server_cert_verify_result_
.is_issued_by_known_root
,
1259 server_cert_verify_result_
.public_key_hashes
, server_cert_
.get(),
1260 server_cert_verify_result_
.verified_cert
.get(),
1261 TransportSecurityState::ENABLE_PIN_REPORTS
, &pinning_failure_log_
)) {
1262 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1266 // Only check Certificate Transparency if there were no other errors with
1270 DCHECK(!certificate_verified_
);
1271 certificate_verified_
= true;
1272 MaybeCacheSession();
1274 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1275 << " (" << result
<< ")";
1278 completed_connect_
= true;
1279 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1280 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1284 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1285 if (!user_connect_callback_
.is_null()) {
1286 CompletionCallback c
= user_connect_callback_
;
1287 user_connect_callback_
.Reset();
1288 c
.Run(rv
> OK
? OK
: rv
);
1292 void SSLClientSocketOpenSSL::UpdateServerCert() {
1293 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1294 server_cert_
= server_cert_chain_
->AsOSChain();
1295 if (server_cert_
.get()) {
1297 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
1298 base::Bind(&NetLogX509CertificateCallback
,
1299 base::Unretained(server_cert_
.get())));
1303 void SSLClientSocketOpenSSL::VerifyCT() {
1304 if (!cert_transparency_verifier_
)
1307 const uint8_t* ocsp_response_raw
;
1308 size_t ocsp_response_len
;
1309 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1310 std::string ocsp_response
;
1311 if (ocsp_response_len
> 0) {
1312 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1316 const uint8_t* sct_list_raw
;
1317 size_t sct_list_len
;
1318 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1319 std::string sct_list
;
1320 if (sct_list_len
> 0)
1321 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1323 // Note that this is a completely synchronous operation: The CT Log Verifier
1324 // gets all the data it needs for SCT verification and does not do any
1325 // external communication.
1326 cert_transparency_verifier_
->Verify(
1327 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1328 &ct_verify_result_
, net_log_
);
1330 if (policy_enforcer_
&&
1331 (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
)) {
1332 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1333 SSLConfigService::GetEVCertsWhitelist();
1334 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1335 server_cert_verify_result_
.verified_cert
.get(), ev_whitelist
.get(),
1336 ct_verify_result_
, net_log_
)) {
1337 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1338 VLOG(1) << "EV certificate for "
1339 << server_cert_verify_result_
.verified_cert
->subject()
1341 << " does not conform to CT policy, removing EV status.";
1342 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1347 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1348 int rv
= DoHandshakeLoop(result
);
1349 if (rv
!= ERR_IO_PENDING
) {
1350 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1351 DoConnectCallback(rv
);
1355 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1356 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1357 // In handshake phase.
1358 OnHandshakeIOComplete(result
);
1362 // During a renegotiation, a Read call may also be blocked on a transport
1363 // write, so retry both operations.
1364 PumpReadWriteEvents();
1367 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1368 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1369 // In handshake phase.
1370 OnHandshakeIOComplete(result
);
1374 // Network layer received some data, check if client requested to read
1376 if (!user_read_buf_
.get())
1379 int rv
= DoReadLoop();
1380 if (rv
!= ERR_IO_PENDING
)
1384 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1385 int rv
= last_io_result
;
1387 // Default to STATE_NONE for next state.
1388 // (This is a quirk carried over from the windows
1389 // implementation. It makes reading the logs a bit harder.)
1390 // State handlers can and often do call GotoState just
1391 // to stay in the current state.
1392 State state
= next_handshake_state_
;
1393 GotoState(STATE_NONE
);
1395 case STATE_HANDSHAKE
:
1398 case STATE_HANDSHAKE_COMPLETE
:
1399 rv
= DoHandshakeComplete(rv
);
1401 case STATE_CHANNEL_ID_LOOKUP
:
1403 rv
= DoChannelIDLookup();
1405 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1406 rv
= DoChannelIDLookupComplete(rv
);
1408 case STATE_VERIFY_CERT
:
1410 rv
= DoVerifyCert(rv
);
1412 case STATE_VERIFY_CERT_COMPLETE
:
1413 rv
= DoVerifyCertComplete(rv
);
1417 rv
= ERR_UNEXPECTED
;
1418 NOTREACHED() << "unexpected state" << state
;
1422 bool network_moved
= DoTransportIO();
1423 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1424 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1425 // special case we keep looping even if rv is ERR_IO_PENDING because
1426 // the transport IO may allow DoHandshake to make progress.
1427 rv
= OK
; // This causes us to stay in the loop.
1429 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1433 int SSLClientSocketOpenSSL::DoReadLoop() {
1437 rv
= DoPayloadRead();
1438 network_moved
= DoTransportIO();
1439 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1444 int SSLClientSocketOpenSSL::DoWriteLoop() {
1448 rv
= DoPayloadWrite();
1449 network_moved
= DoTransportIO();
1450 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1455 int SSLClientSocketOpenSSL::DoPayloadRead() {
1456 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1458 DCHECK_LT(0, user_read_buf_len_
);
1459 DCHECK(user_read_buf_
.get());
1462 if (pending_read_error_
!= kNoPendingResult
) {
1463 rv
= pending_read_error_
;
1464 pending_read_error_
= kNoPendingResult
;
1466 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1467 rv
, user_read_buf_
->data());
1470 NetLog::TYPE_SSL_READ_ERROR
,
1471 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1472 pending_read_error_info_
));
1474 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1475 pending_read_error_info_
= OpenSSLErrorInfo();
1479 int total_bytes_read
= 0;
1482 ssl_ret
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1483 user_read_buf_len_
- total_bytes_read
);
1485 total_bytes_read
+= ssl_ret
;
1486 } while (total_bytes_read
< user_read_buf_len_
&& ssl_ret
> 0);
1488 // Although only the final SSL_read call may have failed, the failure needs to
1489 // processed immediately, while the information still available in OpenSSL's
1492 // A zero return from SSL_read may mean any of:
1493 // - The underlying BIO_read returned 0.
1494 // - The peer sent a close_notify.
1495 // - Any arbitrary error. https://crbug.com/466303
1497 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1498 // error, so it does not occur. The second and third are distinguished by
1499 // SSL_ERROR_ZERO_RETURN.
1500 pending_read_ssl_error_
= SSL_get_error(ssl_
, ssl_ret
);
1501 if (pending_read_ssl_error_
== SSL_ERROR_ZERO_RETURN
) {
1502 pending_read_error_
= 0;
1503 } else if (pending_read_ssl_error_
== SSL_ERROR_WANT_X509_LOOKUP
&&
1504 !ssl_config_
.send_client_cert
) {
1505 pending_read_error_
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1506 } else if (pending_read_ssl_error_
==
1507 SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
) {
1508 DCHECK(private_key_
);
1509 DCHECK_NE(kNoPendingResult
, signature_result_
);
1510 pending_read_error_
= ERR_IO_PENDING
;
1512 pending_read_error_
= MapOpenSSLErrorWithDetails(
1513 pending_read_ssl_error_
, err_tracer
, &pending_read_error_info_
);
1516 // Many servers do not reliably send a close_notify alert when shutting down
1517 // a connection, and instead terminate the TCP connection. This is reported
1518 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1519 // graceful EOF, instead of treating it as an error as it should be.
1520 if (pending_read_error_
== ERR_CONNECTION_CLOSED
)
1521 pending_read_error_
= 0;
1524 if (total_bytes_read
> 0) {
1525 // Return any bytes read to the caller. The error will be deferred to the
1526 // next call of DoPayloadRead.
1527 rv
= total_bytes_read
;
1529 // Do not treat insufficient data as an error to return in the next call to
1530 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1531 // again. This is because DoTransportIO() may complete in between the next
1532 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1533 // subsequent invocations to see if a complete record may now be read.
1534 if (pending_read_error_
== ERR_IO_PENDING
)
1535 pending_read_error_
= kNoPendingResult
;
1537 // No bytes were returned. Return the pending read error immediately.
1538 DCHECK_NE(kNoPendingResult
, pending_read_error_
);
1539 rv
= pending_read_error_
;
1540 pending_read_error_
= kNoPendingResult
;
1544 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1545 user_read_buf_
->data());
1546 } else if (rv
!= ERR_IO_PENDING
) {
1548 NetLog::TYPE_SSL_READ_ERROR
,
1549 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1550 pending_read_error_info_
));
1551 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1552 pending_read_error_info_
= OpenSSLErrorInfo();
1557 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1558 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1559 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1562 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1563 user_write_buf_
->data());
1567 int ssl_error
= SSL_get_error(ssl_
, rv
);
1568 if (ssl_error
== SSL_ERROR_WANT_PRIVATE_KEY_OPERATION
)
1569 return ERR_IO_PENDING
;
1570 OpenSSLErrorInfo error_info
;
1571 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1574 if (net_error
!= ERR_IO_PENDING
) {
1576 NetLog::TYPE_SSL_WRITE_ERROR
,
1577 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1582 void SSLClientSocketOpenSSL::PumpReadWriteEvents() {
1583 int rv_read
= ERR_IO_PENDING
;
1584 int rv_write
= ERR_IO_PENDING
;
1587 if (user_read_buf_
.get())
1588 rv_read
= DoPayloadRead();
1589 if (user_write_buf_
.get())
1590 rv_write
= DoPayloadWrite();
1591 network_moved
= DoTransportIO();
1592 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1593 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1595 // Performing the Read callback may cause |this| to be deleted. If this
1596 // happens, the Write callback should not be invoked. Guard against this by
1597 // holding a WeakPtr to |this| and ensuring it's still valid.
1598 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1599 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1600 DoReadCallback(rv_read
);
1605 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1606 DoWriteCallback(rv_write
);
1609 int SSLClientSocketOpenSSL::BufferSend(void) {
1610 if (transport_send_busy_
)
1611 return ERR_IO_PENDING
;
1613 size_t buffer_read_offset
;
1616 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1617 &buffer_read_offset
, &max_read
);
1618 DCHECK_EQ(status
, 1); // Should never fail.
1620 return 0; // Nothing pending in the OpenSSL write BIO.
1621 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1622 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1623 send_buffer_
->set_offset(buffer_read_offset
);
1625 int rv
= transport_
->socket()->Write(
1626 send_buffer_
.get(), max_read
,
1627 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1628 base::Unretained(this)));
1629 if (rv
== ERR_IO_PENDING
) {
1630 transport_send_busy_
= true;
1632 TransportWriteComplete(rv
);
1637 int SSLClientSocketOpenSSL::BufferRecv(void) {
1638 if (transport_recv_busy_
)
1639 return ERR_IO_PENDING
;
1641 // Determine how much was requested from |transport_bio_| that was not
1642 // actually available.
1643 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1644 if (requested
== 0) {
1645 // This is not a perfect match of error codes, as no operation is
1646 // actually pending. However, returning 0 would be interpreted as
1647 // a possible sign of EOF, which is also an inappropriate match.
1648 return ERR_IO_PENDING
;
1651 // Known Issue: While only reading |requested| data is the more correct
1652 // implementation, it has the downside of resulting in frequent reads:
1653 // One read for the SSL record header (~5 bytes) and one read for the SSL
1654 // record body. Rather than issuing these reads to the underlying socket
1655 // (and constantly allocating new IOBuffers), a single Read() request to
1656 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1657 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1658 // traffic, this over-subscribed Read()ing will not cause issues.
1660 size_t buffer_write_offset
;
1663 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1664 &buffer_write_offset
, &max_write
);
1665 DCHECK_EQ(status
, 1); // Should never fail.
1667 return ERR_IO_PENDING
;
1670 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1671 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1673 recv_buffer_
->set_offset(buffer_write_offset
);
1674 int rv
= transport_
->socket()->Read(
1677 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1678 base::Unretained(this)));
1679 if (rv
== ERR_IO_PENDING
) {
1680 transport_recv_busy_
= true;
1682 rv
= TransportReadComplete(rv
);
1687 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1688 TransportWriteComplete(result
);
1689 OnSendComplete(result
);
1692 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1693 result
= TransportReadComplete(result
);
1694 OnRecvComplete(result
);
1697 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1698 DCHECK(ERR_IO_PENDING
!= result
);
1699 int bytes_written
= 0;
1701 // Record the error. Save it to be reported in a future read or write on
1702 // transport_bio_'s peer.
1703 transport_write_error_
= result
;
1705 bytes_written
= result
;
1707 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1708 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1710 transport_send_busy_
= false;
1713 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1714 DCHECK(ERR_IO_PENDING
!= result
);
1715 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1716 // does not report success.
1718 result
= ERR_CONNECTION_CLOSED
;
1721 DVLOG(1) << "TransportReadComplete result " << result
;
1722 // Received an error. Save it to be reported in a future read on
1723 // transport_bio_'s peer.
1724 transport_read_error_
= result
;
1726 bytes_read
= result
;
1728 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1729 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1731 transport_recv_busy_
= false;
1735 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1736 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1737 DCHECK(ssl
== ssl_
);
1739 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1741 // Clear any currently configured certificates.
1742 SSL_certs_clear(ssl_
);
1745 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1746 LOG(WARNING
) << "Client auth is not supported";
1747 #else // !defined(OS_IOS)
1748 if (!ssl_config_
.send_client_cert
) {
1749 // First pass: we know that a client certificate is needed, but we do not
1750 // have one at hand.
1751 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1752 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1753 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1754 unsigned char* str
= NULL
;
1755 int length
= i2d_X509_NAME(ca_name
, &str
);
1756 cert_authorities_
.push_back(std::string(
1757 reinterpret_cast<const char*>(str
),
1758 static_cast<size_t>(length
)));
1762 const unsigned char* client_cert_types
;
1763 size_t num_client_cert_types
=
1764 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1765 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1766 cert_key_types_
.push_back(
1767 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1770 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1774 // Second pass: a client certificate should have been selected.
1775 if (ssl_config_
.client_cert
.get()) {
1776 ScopedX509 leaf_x509
=
1777 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1779 LOG(WARNING
) << "Failed to import certificate";
1780 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1784 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1785 ssl_config_
.client_cert
->GetIntermediateCertificates());
1787 LOG(WARNING
) << "Failed to import intermediate certificates";
1788 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1792 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1793 !SSL_set1_chain(ssl_
, chain
.get())) {
1794 LOG(WARNING
) << "Failed to set client certificate";
1798 #if defined(USE_OPENSSL_CERTS)
1799 // TODO(davidben): Move Android to the SSLPrivateKey codepath and disable
1800 // client auth on NaCl altogether.
1801 crypto::ScopedEVP_PKEY privkey
=
1802 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1803 ssl_config_
.client_cert
.get());
1805 // Could not find the private key. Fail the handshake and surface an
1806 // appropriate error to the caller.
1807 LOG(WARNING
) << "Client cert found without private key";
1808 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1811 if (!SSL_use_PrivateKey(ssl_
, privkey
.get())) {
1812 LOG(WARNING
) << "Failed to set private key";
1815 #else // !USE_OPENSSL_CERTS
1816 // TODO(davidben): Lift this call up to the embedder so we can actually test
1817 // this code. https://crbug.com/394131
1818 private_key_
= FetchClientCertPrivateKey(
1819 ssl_config_
.client_cert
.get(),
1820 g_platform_key_task_runner
.Get().task_runner());
1821 if (!private_key_
) {
1822 // Could not find the private key. Fail the handshake and surface an
1823 // appropriate error to the caller.
1824 LOG(WARNING
) << "Client cert found without private key";
1825 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1829 SSL_set_private_key_method(ssl_
, &SSLContext::kPrivateKeyMethod
);
1830 #endif // USE_OPENSSL_CERTS
1832 int cert_count
= 1 + sk_X509_num(chain
.get());
1833 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1834 NetLog::IntegerCallback("cert_count", cert_count
));
1837 #endif // defined(OS_IOS)
1839 // Send no client certificate.
1840 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1841 NetLog::IntegerCallback("cert_count", 0));
1845 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1846 if (!completed_connect_
) {
1847 // If the first handshake hasn't completed then we accept any certificates
1848 // because we verify after the handshake.
1852 // Disallow the server certificate to change in a renegotiation.
1853 if (server_cert_chain_
->empty()) {
1854 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1857 base::StringPiece old_der
, new_der
;
1858 if (store_ctx
->cert
== NULL
||
1859 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1860 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1861 LOG(ERROR
) << "Failed to encode certificates";
1864 if (old_der
!= new_der
) {
1865 LOG(ERROR
) << "Server certificate changed between handshakes";
1872 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1873 // server supports NPN, selects a protocol from the list that the server
1874 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1875 // callback can assume that |in| is syntactically valid.
1876 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1877 unsigned char* outlen
,
1878 const unsigned char* in
,
1879 unsigned int inlen
) {
1880 if (ssl_config_
.next_protos
.empty()) {
1881 *out
= reinterpret_cast<uint8
*>(
1882 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1883 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1884 npn_status_
= kNextProtoUnsupported
;
1885 return SSL_TLSEXT_ERR_OK
;
1888 // Assume there's no overlap between our protocols and the server's list.
1889 npn_status_
= kNextProtoNoOverlap
;
1891 // For each protocol in server preference order, see if we support it.
1892 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1893 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1894 const std::string proto
= NextProtoToString(next_proto
);
1895 if (in
[i
] == proto
.size() &&
1896 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1897 // We found a match.
1898 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1900 npn_status_
= kNextProtoNegotiated
;
1904 if (npn_status_
== kNextProtoNegotiated
)
1908 // If we didn't find a protocol, we select the first one from our list.
1909 if (npn_status_
== kNextProtoNoOverlap
) {
1910 // NextProtoToString returns a pointer to a static string.
1911 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1912 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1913 *outlen
= strlen(proto
);
1916 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1917 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1918 set_negotiation_extension(kExtensionNPN
);
1919 return SSL_TLSEXT_ERR_OK
;
1922 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1925 const char *argp
, int argi
, long argl
,
1927 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1928 // If there is no more data in the buffer, report any pending errors that
1929 // were observed. Note that both the readbuf and the writebuf are checked
1930 // for errors, since the application may have encountered a socket error
1931 // while writing that would otherwise not be reported until the application
1932 // attempted to write again - which it may never do. See
1933 // https://crbug.com/249848.
1934 if (transport_read_error_
!= OK
) {
1935 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1938 if (transport_write_error_
!= OK
) {
1939 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1942 } else if (cmd
== BIO_CB_WRITE
) {
1943 // Because of the write buffer, this reports a failure from the previous
1944 // write payload. If the current payload fails to write, the error will be
1945 // reported in a future write or read to |bio|.
1946 if (transport_write_error_
!= OK
) {
1947 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1955 long SSLClientSocketOpenSSL::BIOCallback(
1958 const char *argp
, int argi
, long argl
,
1960 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1961 BIO_get_callback_arg(bio
));
1963 return socket
->MaybeReplayTransportError(
1964 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1967 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1968 // Only cache the session once both a new session has been established and the
1969 // certificate has been verified. Due to False Start, these events may happen
1971 if (!session_pending_
|| !certificate_verified_
)
1974 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1975 SSL_get_session(ssl_
));
1976 session_pending_
= false;
1979 int SSLClientSocketOpenSSL::NewSessionCallback(SSL_SESSION
* session
) {
1980 DCHECK_EQ(session
, SSL_get_session(ssl_
));
1982 // Only sessions from the initial handshake get cached. Note this callback may
1983 // be signaled on abbreviated handshakes if the ticket was renewed.
1984 session_pending_
= true;
1985 MaybeCacheSession();
1987 // OpenSSL passes a reference to |session|, but the session cache does not
1988 // take this reference, so release it.
1989 SSL_SESSION_free(session
);
1993 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
1994 for (ct::SCTList::const_iterator iter
=
1995 ct_verify_result_
.verified_scts
.begin();
1996 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
1997 ssl_info
->signed_certificate_timestamps
.push_back(
1998 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
2000 for (ct::SCTList::const_iterator iter
=
2001 ct_verify_result_
.invalid_scts
.begin();
2002 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
2003 ssl_info
->signed_certificate_timestamps
.push_back(
2004 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
2006 for (ct::SCTList::const_iterator iter
=
2007 ct_verify_result_
.unknown_logs_scts
.begin();
2008 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
2009 ssl_info
->signed_certificate_timestamps
.push_back(
2010 SignedCertificateTimestampAndStatus(*iter
,
2011 ct::SCT_STATUS_LOG_UNKNOWN
));
2015 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
2016 std::string result
= host_and_port_
.ToString();
2018 result
.append(ssl_session_cache_shard_
);
2020 // Shard the session cache based on maximum protocol version. This causes
2021 // fallback connections to use a separate session cache.
2023 switch (ssl_config_
.version_max
) {
2024 case SSL_PROTOCOL_VERSION_TLS1
:
2025 result
.append("tls1");
2027 case SSL_PROTOCOL_VERSION_TLS1_1
:
2028 result
.append("tls1.1");
2030 case SSL_PROTOCOL_VERSION_TLS1_2
:
2031 result
.append("tls1.2");
2038 if (ssl_config_
.enable_deprecated_cipher_suites
)
2039 result
.append("deprecated");
2044 bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
2045 if (npn_status_
== kNextProtoUnsupported
)
2046 return ssl_config_
.renego_allowed_default
;
2048 NextProto next_proto
= NextProtoFromString(npn_proto_
);
2049 for (NextProto allowed
: ssl_config_
.renego_allowed_for_protos
) {
2050 if (next_proto
== allowed
)
2056 int SSLClientSocketOpenSSL::PrivateKeyTypeCallback() {
2057 switch (private_key_
->GetType()) {
2058 case SSLPrivateKey::Type::RSA
:
2059 return EVP_PKEY_RSA
;
2060 case SSLPrivateKey::Type::ECDSA
:
2064 return EVP_PKEY_NONE
;
2067 int SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback(const EVP_MD
* md
) {
2068 SSLPrivateKey::Hash hash
;
2069 return EVP_MDToPrivateKeyHash(md
, &hash
) && private_key_
->SupportsHash(hash
);
2072 size_t SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback() {
2073 return private_key_
->GetMaxSignatureLengthInBytes();
2076 ssl_private_key_result_t
SSLClientSocketOpenSSL::PrivateKeySignCallback(
2083 DCHECK_EQ(kNoPendingResult
, signature_result_
);
2084 DCHECK(signature_
.empty());
2085 DCHECK(private_key_
);
2087 net_log_
.BeginEvent(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION
);
2089 SSLPrivateKey::Hash hash
;
2090 if (!EVP_MDToPrivateKeyHash(md
, &hash
)) {
2091 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
2092 return ssl_private_key_failure
;
2095 signature_result_
= ERR_IO_PENDING
;
2096 private_key_
->SignDigest(
2097 hash
, base::StringPiece(reinterpret_cast<const char*>(in
), in_len
),
2098 base::Bind(&SSLClientSocketOpenSSL::OnPrivateKeySignComplete
,
2099 weak_factory_
.GetWeakPtr()));
2100 return ssl_private_key_retry
;
2103 ssl_private_key_result_t
SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback(
2107 DCHECK_NE(kNoPendingResult
, signature_result_
);
2108 DCHECK(private_key_
);
2110 if (signature_result_
== ERR_IO_PENDING
)
2111 return ssl_private_key_retry
;
2112 if (signature_result_
!= OK
) {
2113 OpenSSLPutNetError(FROM_HERE
, signature_result_
);
2114 return ssl_private_key_failure
;
2116 if (signature_
.size() > max_out
) {
2117 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
);
2118 return ssl_private_key_failure
;
2120 memcpy(out
, vector_as_array(&signature_
), signature_
.size());
2121 *out_len
= signature_
.size();
2123 return ssl_private_key_success
;
2126 void SSLClientSocketOpenSSL::OnPrivateKeySignComplete(
2128 const std::vector
<uint8_t>& signature
) {
2129 DCHECK_EQ(ERR_IO_PENDING
, signature_result_
);
2130 DCHECK(signature_
.empty());
2131 DCHECK(private_key_
);
2133 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION
,
2136 signature_result_
= error
;
2137 if (signature_result_
== OK
)
2138 signature_
= signature
;
2140 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2141 OnHandshakeIOComplete(signature_result_
);
2145 // During a renegotiation, either Read or Write calls may be blocked on an
2146 // asynchronous private key operation.
2147 PumpReadWriteEvents();