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/memory/singleton.h"
21 #include "base/metrics/histogram_macros.h"
22 #include "base/profiler/scoped_tracker.h"
23 #include "base/strings/string_piece.h"
24 #include "base/synchronization/lock.h"
25 #include "base/threading/thread_local.h"
26 #include "base/values.h"
27 #include "crypto/ec_private_key.h"
28 #include "crypto/openssl_util.h"
29 #include "crypto/scoped_openssl_types.h"
30 #include "net/base/ip_address_number.h"
31 #include "net/base/net_errors.h"
32 #include "net/cert/cert_policy_enforcer.h"
33 #include "net/cert/cert_verifier.h"
34 #include "net/cert/ct_ev_whitelist.h"
35 #include "net/cert/ct_verifier.h"
36 #include "net/cert/x509_certificate_net_log_param.h"
37 #include "net/cert/x509_util_openssl.h"
38 #include "net/http/transport_security_state.h"
39 #include "net/ssl/scoped_openssl_types.h"
40 #include "net/ssl/ssl_cert_request_info.h"
41 #include "net/ssl/ssl_client_session_cache_openssl.h"
42 #include "net/ssl/ssl_connection_status_flags.h"
43 #include "net/ssl/ssl_failure_state.h"
44 #include "net/ssl/ssl_info.h"
47 #include "base/win/windows_version.h"
50 #if defined(USE_OPENSSL_CERTS)
51 #include "net/ssl/openssl_client_key_store.h"
53 #include "net/ssl/openssl_platform_key.h"
60 // Enable this to see logging for state machine state transitions.
62 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
63 " jump to state " << s; \
64 next_handshake_state_ = s; } while (0)
66 #define GotoState(s) next_handshake_state_ = s
69 // This constant can be any non-negative/non-zero value (eg: it does not
70 // overlap with any value of the net::Error range, including net::OK).
71 const int kNoPendingReadResult
= 1;
73 // If a client doesn't have a list of protocols that it supports, but
74 // the server supports NPN, choosing "http/1.1" is the best answer.
75 const char kDefaultSupportedNPNProtocol
[] = "http/1.1";
77 // Default size of the internal BoringSSL buffers.
78 const int KDefaultOpenSSLBufferSize
= 17 * 1024;
80 void FreeX509Stack(STACK_OF(X509
)* ptr
) {
81 sk_X509_pop_free(ptr
, X509_free
);
84 using ScopedX509Stack
= crypto::ScopedOpenSSL
<STACK_OF(X509
), FreeX509Stack
>;
86 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
87 // This method doesn't seem to have made it into the OpenSSL headers.
88 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER
* cipher
) { return cipher
->id
; }
91 // Used for encoding the |connection_status| field of an SSLInfo object.
92 int EncodeSSLConnectionStatus(uint16 cipher_suite
,
96 ((compression
& SSL_CONNECTION_COMPRESSION_MASK
) <<
97 SSL_CONNECTION_COMPRESSION_SHIFT
) |
98 ((version
& SSL_CONNECTION_VERSION_MASK
) <<
99 SSL_CONNECTION_VERSION_SHIFT
);
102 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
103 // this SSL connection.
104 int GetNetSSLVersion(SSL
* ssl
) {
105 switch (SSL_version(ssl
)) {
107 return SSL_CONNECTION_VERSION_TLS1
;
109 return SSL_CONNECTION_VERSION_TLS1_1
;
111 return SSL_CONNECTION_VERSION_TLS1_2
;
114 return SSL_CONNECTION_VERSION_UNKNOWN
;
118 ScopedX509
OSCertHandleToOpenSSL(
119 X509Certificate::OSCertHandle os_handle
) {
120 #if defined(USE_OPENSSL_CERTS)
121 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle
));
122 #else // !defined(USE_OPENSSL_CERTS)
123 std::string der_encoded
;
124 if (!X509Certificate::GetDEREncoded(os_handle
, &der_encoded
))
126 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
127 return ScopedX509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
128 #endif // defined(USE_OPENSSL_CERTS)
131 ScopedX509Stack
OSCertHandlesToOpenSSL(
132 const X509Certificate::OSCertHandles
& os_handles
) {
133 ScopedX509Stack
stack(sk_X509_new_null());
134 for (size_t i
= 0; i
< os_handles
.size(); i
++) {
135 ScopedX509 x509
= OSCertHandleToOpenSSL(os_handles
[i
]);
137 return ScopedX509Stack();
138 sk_X509_push(stack
.get(), x509
.release());
143 int LogErrorCallback(const char* str
, size_t len
, void* context
) {
144 LOG(ERROR
) << base::StringPiece(str
, len
);
150 class SSLClientSocketOpenSSL::SSLContext
{
152 static SSLContext
* GetInstance() { return Singleton
<SSLContext
>::get(); }
153 SSL_CTX
* ssl_ctx() { return ssl_ctx_
.get(); }
154 SSLClientSessionCacheOpenSSL
* session_cache() { return &session_cache_
; }
156 SSLClientSocketOpenSSL
* GetClientSocketFromSSL(const SSL
* ssl
) {
158 SSLClientSocketOpenSSL
* socket
= static_cast<SSLClientSocketOpenSSL
*>(
159 SSL_get_ex_data(ssl
, ssl_socket_data_index_
));
164 bool SetClientSocketForSSL(SSL
* ssl
, SSLClientSocketOpenSSL
* socket
) {
165 return SSL_set_ex_data(ssl
, ssl_socket_data_index_
, socket
) != 0;
169 friend struct DefaultSingletonTraits
<SSLContext
>;
171 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
172 crypto::EnsureOpenSSLInit();
173 ssl_socket_data_index_
= SSL_get_ex_new_index(0, 0, 0, 0, 0);
174 DCHECK_NE(ssl_socket_data_index_
, -1);
175 ssl_ctx_
.reset(SSL_CTX_new(SSLv23_client_method()));
176 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
177 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
178 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
179 // This stops |SSL_shutdown| from generating the close_notify message, which
180 // is currently not sent on the network.
181 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
182 SSL_CTX_set_quiet_shutdown(ssl_ctx_
.get(), 1);
183 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
184 // It would be better if the callback were not a global setting,
185 // but that is an OpenSSL issue.
186 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
188 ssl_ctx_
->tlsext_channel_id_enabled_new
= 1;
190 // Disable the internal session cache. Session caching is handled
191 // externally (i.e. by SSLClientSessionCacheOpenSSL).
192 SSL_CTX_set_session_cache_mode(
193 ssl_ctx_
.get(), SSL_SESS_CACHE_CLIENT
| SSL_SESS_CACHE_NO_INTERNAL
);
194 SSL_CTX_sess_set_new_cb(ssl_ctx_
.get(), NewSessionCallback
);
196 scoped_ptr
<base::Environment
> env(base::Environment::Create());
197 std::string ssl_keylog_file
;
198 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
199 !ssl_keylog_file
.empty()) {
200 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
201 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
203 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
204 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
206 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
211 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
212 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
214 return socket
->ClientCertRequestCallback(ssl
);
217 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
218 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
219 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
220 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
223 return socket
->CertVerifyCallback(store_ctx
);
226 static int SelectNextProtoCallback(SSL
* ssl
,
227 unsigned char** out
, unsigned char* outlen
,
228 const unsigned char* in
,
229 unsigned int inlen
, void* arg
) {
230 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
231 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
234 static int NewSessionCallback(SSL
* ssl
, SSL_SESSION
* session
) {
235 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
236 return socket
->NewSessionCallback(session
);
239 // This is the index used with SSL_get_ex_data to retrieve the owner
240 // SSLClientSocketOpenSSL object from an SSL instance.
241 int ssl_socket_data_index_
;
243 ScopedSSL_CTX ssl_ctx_
;
245 // TODO(davidben): Use a separate cache per URLRequestContext.
246 // https://crbug.com/458365
248 // TODO(davidben): Sessions should be invalidated on fatal
249 // alerts. https://crbug.com/466352
250 SSLClientSessionCacheOpenSSL session_cache_
;
253 // PeerCertificateChain is a helper object which extracts the certificate
254 // chain, as given by the server, from an OpenSSL socket and performs the needed
255 // resource management. The first element of the chain is the leaf certificate
256 // and the other elements are in the order given by the server.
257 class SSLClientSocketOpenSSL::PeerCertificateChain
{
259 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
260 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
261 ~PeerCertificateChain() {}
262 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
264 // Resets the PeerCertificateChain to the set of certificates in|chain|,
265 // which may be NULL, indicating to empty the store certificates.
266 // Note: If an error occurs, such as being unable to parse the certificates,
267 // this will behave as if Reset(NULL) was called.
268 void Reset(STACK_OF(X509
)* chain
);
270 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
271 scoped_refptr
<X509Certificate
> AsOSChain() const;
273 size_t size() const {
274 if (!openssl_chain_
.get())
276 return sk_X509_num(openssl_chain_
.get());
283 X509
* Get(size_t index
) const {
284 DCHECK_LT(index
, size());
285 return sk_X509_value(openssl_chain_
.get(), index
);
289 ScopedX509Stack openssl_chain_
;
292 SSLClientSocketOpenSSL::PeerCertificateChain
&
293 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
294 const PeerCertificateChain
& other
) {
298 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
302 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
303 STACK_OF(X509
)* chain
) {
304 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
307 scoped_refptr
<X509Certificate
>
308 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
309 #if defined(USE_OPENSSL_CERTS)
310 // When OSCertHandle is typedef'ed to X509, this implementation does a short
311 // cut to avoid converting back and forth between DER and the X509 struct.
312 X509Certificate::OSCertHandles intermediates
;
313 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
314 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
317 return make_scoped_refptr(X509Certificate::CreateFromHandle(
318 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
320 // DER-encode the chain and convert to a platform certificate handle.
321 std::vector
<base::StringPiece
> der_chain
;
322 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
323 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
324 base::StringPiece der
;
325 if (!x509_util::GetDER(x
, &der
))
327 der_chain
.push_back(der
);
330 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
335 void SSLClientSocket::ClearSessionCache() {
336 SSLClientSocketOpenSSL::SSLContext
* context
=
337 SSLClientSocketOpenSSL::SSLContext::GetInstance();
338 context
->session_cache()->Flush();
342 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
343 return SSL_PROTOCOL_VERSION_TLS1_2
;
346 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
347 scoped_ptr
<ClientSocketHandle
> transport_socket
,
348 const HostPortPair
& host_and_port
,
349 const SSLConfig
& ssl_config
,
350 const SSLClientSocketContext
& context
)
351 : transport_send_busy_(false),
352 transport_recv_busy_(false),
353 pending_read_error_(kNoPendingReadResult
),
354 pending_read_ssl_error_(SSL_ERROR_NONE
),
355 transport_read_error_(OK
),
356 transport_write_error_(OK
),
357 server_cert_chain_(new PeerCertificateChain(NULL
)),
358 completed_connect_(false),
359 was_ever_used_(false),
360 cert_verifier_(context
.cert_verifier
),
361 cert_transparency_verifier_(context
.cert_transparency_verifier
),
362 channel_id_service_(context
.channel_id_service
),
364 transport_bio_(NULL
),
365 transport_(transport_socket
.Pass()),
366 host_and_port_(host_and_port
),
367 ssl_config_(ssl_config
),
368 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
369 next_handshake_state_(STATE_NONE
),
370 npn_status_(kNextProtoUnsupported
),
371 channel_id_sent_(false),
372 session_pending_(false),
373 certificate_verified_(false),
374 ssl_failure_state_(SSL_FAILURE_NONE
),
375 transport_security_state_(context
.transport_security_state
),
376 policy_enforcer_(context
.cert_policy_enforcer
),
377 net_log_(transport_
->socket()->NetLog()),
378 weak_factory_(this) {
379 DCHECK(cert_verifier_
);
382 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
386 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
387 SSLCertRequestInfo
* cert_request_info
) {
388 cert_request_info
->host_and_port
= host_and_port_
;
389 cert_request_info
->cert_authorities
= cert_authorities_
;
390 cert_request_info
->cert_key_types
= cert_key_types_
;
393 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
394 std::string
* proto
) const {
400 SSLClientSocketOpenSSL::GetChannelIDService() const {
401 return channel_id_service_
;
404 SSLFailureState
SSLClientSocketOpenSSL::GetSSLFailureState() const {
405 return ssl_failure_state_
;
408 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
409 const base::StringPiece
& label
,
410 bool has_context
, const base::StringPiece
& context
,
411 unsigned char* out
, unsigned int outlen
) {
413 return ERR_SOCKET_NOT_CONNECTED
;
415 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
417 int rv
= SSL_export_keying_material(
418 ssl_
, out
, outlen
, label
.data(), label
.size(),
419 reinterpret_cast<const unsigned char*>(context
.data()), context
.length(),
420 has_context
? 1 : 0);
423 int ssl_error
= SSL_get_error(ssl_
, rv
);
424 LOG(ERROR
) << "Failed to export keying material;"
425 << " returned " << rv
426 << ", SSL error code " << ssl_error
;
427 return MapOpenSSLError(ssl_error
, err_tracer
);
432 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
434 return ERR_NOT_IMPLEMENTED
;
437 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
438 // It is an error to create an SSLClientSocket whose context has no
439 // TransportSecurityState.
440 DCHECK(transport_security_state_
);
442 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
444 // Set up new ssl object.
447 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
451 // Set SSL to client mode. Handshake happens in the loop below.
452 SSL_set_connect_state(ssl_
);
454 GotoState(STATE_HANDSHAKE
);
455 rv
= DoHandshakeLoop(OK
);
456 if (rv
== ERR_IO_PENDING
) {
457 user_connect_callback_
= callback
;
459 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
462 return rv
> OK
? OK
: rv
;
465 void SSLClientSocketOpenSSL::Disconnect() {
467 // Calling SSL_shutdown prevents the session from being marked as
473 if (transport_bio_
) {
474 BIO_free_all(transport_bio_
);
475 transport_bio_
= NULL
;
478 // Shut down anything that may call us back.
479 cert_verifier_request_
.reset();
480 transport_
->socket()->Disconnect();
482 // Null all callbacks, delete all buffers.
483 transport_send_busy_
= false;
485 transport_recv_busy_
= false;
488 user_connect_callback_
.Reset();
489 user_read_callback_
.Reset();
490 user_write_callback_
.Reset();
491 user_read_buf_
= NULL
;
492 user_read_buf_len_
= 0;
493 user_write_buf_
= NULL
;
494 user_write_buf_len_
= 0;
496 pending_read_error_
= kNoPendingReadResult
;
497 pending_read_ssl_error_
= SSL_ERROR_NONE
;
498 pending_read_error_info_
= OpenSSLErrorInfo();
500 transport_read_error_
= OK
;
501 transport_write_error_
= OK
;
503 server_cert_verify_result_
.Reset();
504 completed_connect_
= false;
506 cert_authorities_
.clear();
507 cert_key_types_
.clear();
509 start_cert_verification_time_
= base::TimeTicks();
511 npn_status_
= kNextProtoUnsupported
;
514 channel_id_sent_
= false;
515 session_pending_
= false;
516 certificate_verified_
= false;
517 channel_id_request_
.Cancel();
518 ssl_failure_state_
= SSL_FAILURE_NONE
;
521 bool SSLClientSocketOpenSSL::IsConnected() const {
522 // If the handshake has not yet completed.
523 if (!completed_connect_
)
525 // If an asynchronous operation is still pending.
526 if (user_read_buf_
.get() || user_write_buf_
.get())
529 return transport_
->socket()->IsConnected();
532 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
533 // If the handshake has not yet completed.
534 if (!completed_connect_
)
536 // If an asynchronous operation is still pending.
537 if (user_read_buf_
.get() || user_write_buf_
.get())
540 // If there is data read from the network that has not yet been consumed, do
541 // not treat the connection as idle.
543 // Note that this does not check |BIO_pending|, whether there is ciphertext
544 // that has not yet been flushed to the network. |Write| returns early, so
545 // this can cause race conditions which cause a socket to not be treated
546 // reusable when it should be. See https://crbug.com/466147.
547 if (BIO_wpending(transport_bio_
) > 0)
550 return transport_
->socket()->IsConnectedAndIdle();
553 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
554 return transport_
->socket()->GetPeerAddress(addressList
);
557 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
558 return transport_
->socket()->GetLocalAddress(addressList
);
561 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
565 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
566 if (transport_
.get() && transport_
->socket()) {
567 transport_
->socket()->SetSubresourceSpeculation();
573 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
574 if (transport_
.get() && transport_
->socket()) {
575 transport_
->socket()->SetOmniboxSpeculation();
581 bool SSLClientSocketOpenSSL::WasEverUsed() const {
582 return was_ever_used_
;
585 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
586 if (transport_
.get() && transport_
->socket())
587 return transport_
->socket()->UsingTCPFastOpen();
593 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
595 if (server_cert_chain_
->empty())
598 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
599 ssl_info
->unverified_cert
= server_cert_
;
600 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
601 ssl_info
->is_issued_by_known_root
=
602 server_cert_verify_result_
.is_issued_by_known_root
;
603 ssl_info
->public_key_hashes
=
604 server_cert_verify_result_
.public_key_hashes
;
605 ssl_info
->client_cert_sent
=
606 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
607 ssl_info
->channel_id_sent
= channel_id_sent_
;
608 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
610 AddSCTInfoToSSLInfo(ssl_info
);
612 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
614 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
616 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
617 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
618 GetNetSSLVersion(ssl_
));
620 if (!SSL_get_secure_renegotiation_support(ssl_
))
621 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
623 if (ssl_config_
.version_fallback
)
624 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
626 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
627 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
629 DVLOG(3) << "Encoded connection status: cipher suite = "
630 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
632 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
636 void SSLClientSocketOpenSSL::GetConnectionAttempts(
637 ConnectionAttempts
* out
) const {
641 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
643 const CompletionCallback
& callback
) {
644 user_read_buf_
= buf
;
645 user_read_buf_len_
= buf_len
;
647 int rv
= DoReadLoop();
649 if (rv
== ERR_IO_PENDING
) {
650 user_read_callback_
= callback
;
653 was_ever_used_
= true;
654 user_read_buf_
= NULL
;
655 user_read_buf_len_
= 0;
661 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
663 const CompletionCallback
& callback
) {
664 user_write_buf_
= buf
;
665 user_write_buf_len_
= buf_len
;
667 int rv
= DoWriteLoop();
669 if (rv
== ERR_IO_PENDING
) {
670 user_write_callback_
= callback
;
673 was_ever_used_
= true;
674 user_write_buf_
= NULL
;
675 user_write_buf_len_
= 0;
681 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
682 return transport_
->socket()->SetReceiveBufferSize(size
);
685 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
686 return transport_
->socket()->SetSendBufferSize(size
);
689 int SSLClientSocketOpenSSL::Init() {
691 DCHECK(!transport_bio_
);
693 SSLContext
* context
= SSLContext::GetInstance();
694 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
696 ssl_
= SSL_new(context
->ssl_ctx());
697 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
698 return ERR_UNEXPECTED
;
700 // SNI should only contain valid DNS hostnames, not IP addresses (see RFC
703 // TODO(rsleevi): Should this code allow hostnames that violate the LDH rule?
704 // See https://crbug.com/496472 and https://crbug.com/496468 for discussion.
705 IPAddressNumber unused
;
706 if (!ParseIPLiteralToNumber(host_and_port_
.host(), &unused
) &&
707 !SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str())) {
708 return ERR_UNEXPECTED
;
711 SSL_SESSION
* session
= context
->session_cache()->Lookup(GetSessionCacheKey());
712 if (session
!= nullptr)
713 SSL_set_session(ssl_
, session
);
715 send_buffer_
= new GrowableIOBuffer();
716 send_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
717 recv_buffer_
= new GrowableIOBuffer();
718 recv_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
722 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
723 if (!BIO_new_bio_pair_external_buf(
724 &ssl_bio
, send_buffer_
->capacity(),
725 reinterpret_cast<uint8_t*>(send_buffer_
->data()), &transport_bio_
,
726 recv_buffer_
->capacity(),
727 reinterpret_cast<uint8_t*>(recv_buffer_
->data())))
728 return ERR_UNEXPECTED
;
730 DCHECK(transport_bio_
);
732 // Install a callback on OpenSSL's end to plumb transport errors through.
733 BIO_set_callback(ssl_bio
, &SSLClientSocketOpenSSL::BIOCallback
);
734 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
736 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
738 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_min
);
739 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_max
);
740 SSL_set_min_version(ssl_
, ssl_config_
.version_min
);
741 SSL_set_max_version(ssl_
, ssl_config_
.version_max
);
743 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
744 // set everything we care about to an absolute value.
745 SslSetClearMask options
;
746 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
748 // TODO(joth): Set this conditionally, see http://crbug.com/55410
749 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
751 SSL_set_options(ssl_
, options
.set_mask
);
752 SSL_clear_options(ssl_
, options
.clear_mask
);
754 // Same as above, this time for the SSL mode.
755 SslSetClearMask mode
;
757 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
758 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
760 mode
.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START
,
761 ssl_config_
.false_start_enabled
);
763 mode
.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV
, ssl_config_
.version_fallback
);
765 SSL_set_mode(ssl_
, mode
.set_mask
);
766 SSL_clear_mode(ssl_
, mode
.clear_mask
);
768 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
769 // textual name with SSL_set_cipher_list because there is no public API to
770 // directly remove a cipher by ID.
771 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
773 // See SSLConfig::disabled_cipher_suites for description of the suites
774 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
775 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
776 // as the handshake hash.
777 std::string
command("DEFAULT:!SHA256:!SHA384:!AESGCM+AES256:!aPSK");
778 // Walk through all the installed ciphers, seeing if any need to be
779 // appended to the cipher removal |command|.
780 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
781 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
782 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
783 bool disable
= false;
784 if (ssl_config_
.require_ecdhe
) {
785 base::StringPiece
kx_name(SSL_CIPHER_get_kx_name(cipher
));
786 disable
= kx_name
!= "ECDHE_RSA" && kx_name
!= "ECDHE_ECDSA";
789 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
790 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
791 ssl_config_
.disabled_cipher_suites
.end();
794 const char* name
= SSL_CIPHER_get_name(cipher
);
795 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
796 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
797 command
.append(":!");
798 command
.append(name
);
802 if (!ssl_config_
.enable_deprecated_cipher_suites
)
803 command
.append(":!RC4");
805 // Disable ECDSA cipher suites on platforms that do not support ECDSA
806 // signed certificates, as servers may use the presence of such
807 // ciphersuites as a hint to send an ECDSA certificate.
809 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
810 command
.append(":!ECDSA");
813 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
814 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
815 // This will almost certainly result in the socket failing to complete the
816 // handshake at which point the appropriate error is bubbled up to the client.
817 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
821 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
822 SSL_enable_tls_channel_id(ssl_
);
825 if (!ssl_config_
.next_protos
.empty()) {
826 // Get list of ciphers that are enabled.
827 STACK_OF(SSL_CIPHER
)* enabled_ciphers
= SSL_get_ciphers(ssl_
);
828 DCHECK(enabled_ciphers
);
829 std::vector
<uint16
> enabled_ciphers_vector
;
830 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(enabled_ciphers
); ++i
) {
831 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(enabled_ciphers
, i
);
832 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
833 enabled_ciphers_vector
.push_back(id
);
836 std::vector
<uint8_t> wire_protos
=
837 SerializeNextProtos(ssl_config_
.next_protos
,
838 HasCipherAdequateForHTTP2(enabled_ciphers_vector
) &&
839 IsTLSVersionAdequateForHTTP2(ssl_config_
));
840 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
844 if (ssl_config_
.signed_cert_timestamps_enabled
) {
845 SSL_enable_signed_cert_timestamps(ssl_
);
846 SSL_enable_ocsp_stapling(ssl_
);
849 if (cert_verifier_
->SupportsOCSPStapling())
850 SSL_enable_ocsp_stapling(ssl_
);
852 // Enable fastradio padding.
853 SSL_enable_fastradio_padding(ssl_
,
854 ssl_config_
.fastradio_padding_enabled
&&
855 ssl_config_
.fastradio_padding_eligible
);
857 // By default, renegotiations are rejected. After the initial handshake
858 // completes, some application protocols may re-enable it.
859 SSL_set_reject_peer_renegotiations(ssl_
, 1);
864 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
865 // Since Run may result in Read being called, clear |user_read_callback_|
868 was_ever_used_
= true;
869 user_read_buf_
= NULL
;
870 user_read_buf_len_
= 0;
871 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
874 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
875 // Since Run may result in Write being called, clear |user_write_callback_|
878 was_ever_used_
= true;
879 user_write_buf_
= NULL
;
880 user_write_buf_len_
= 0;
881 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
884 bool SSLClientSocketOpenSSL::DoTransportIO() {
885 bool network_moved
= false;
887 // Read and write as much data as possible. The loop is necessary because
888 // Write() may return synchronously.
891 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
892 network_moved
= true;
894 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
895 network_moved
= true;
896 return network_moved
;
899 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
900 // g_first_run_completed once crbug.com/424386 is fixed.
901 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
902 LAZY_INSTANCE_INITIALIZER
;
904 int SSLClientSocketOpenSSL::DoHandshake() {
905 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
909 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
911 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
912 rv
= SSL_do_handshake(ssl_
);
914 if (g_first_run_completed
.Get().Get()) {
915 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
917 tracked_objects::ScopedTracker
tracking_profile(
918 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
920 rv
= SSL_do_handshake(ssl_
);
922 g_first_run_completed
.Get().Set(true);
923 rv
= SSL_do_handshake(ssl_
);
929 int ssl_error
= SSL_get_error(ssl_
, rv
);
930 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
931 // The server supports channel ID. Stop to look one up before returning to
933 GotoState(STATE_CHANNEL_ID_LOOKUP
);
936 if (ssl_error
== SSL_ERROR_WANT_X509_LOOKUP
&&
937 !ssl_config_
.send_client_cert
) {
938 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
941 OpenSSLErrorInfo error_info
;
942 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
943 if (net_error
== ERR_IO_PENDING
) {
944 // If not done, stay in this state
945 GotoState(STATE_HANDSHAKE
);
946 return ERR_IO_PENDING
;
949 LOG(ERROR
) << "handshake failed; returned " << rv
<< ", SSL error code "
950 << ssl_error
<< ", net_error " << net_error
;
952 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
953 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
955 // Classify the handshake failure. This is used to determine causes of the
956 // TLS version fallback.
958 // |cipher| is the current outgoing cipher suite, so it is non-null iff
959 // ChangeCipherSpec was sent.
960 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
961 if (SSL_get_state(ssl_
) == SSL3_ST_CR_SRVR_HELLO_A
) {
962 ssl_failure_state_
= SSL_FAILURE_CLIENT_HELLO
;
963 } else if (cipher
&& (SSL_CIPHER_get_id(cipher
) ==
964 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256
||
965 SSL_CIPHER_get_id(cipher
) ==
966 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256
)) {
967 ssl_failure_state_
= SSL_FAILURE_BUGGY_GCM
;
968 } else if (cipher
&& ssl_config_
.send_client_cert
) {
969 ssl_failure_state_
= SSL_FAILURE_CLIENT_AUTH
;
970 } else if (ERR_GET_LIB(error_info
.error_code
) == ERR_LIB_SSL
&&
971 ERR_GET_REASON(error_info
.error_code
) ==
972 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED
) {
973 ssl_failure_state_
= SSL_FAILURE_SESSION_MISMATCH
;
974 } else if (cipher
&& npn_status_
!= kNextProtoUnsupported
) {
975 ssl_failure_state_
= SSL_FAILURE_NEXT_PROTO
;
977 ssl_failure_state_
= SSL_FAILURE_UNKNOWN
;
981 GotoState(STATE_HANDSHAKE_COMPLETE
);
985 int SSLClientSocketOpenSSL::DoHandshakeComplete(int result
) {
989 if (ssl_config_
.version_fallback
&&
990 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
991 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
994 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
995 if (npn_status_
== kNextProtoUnsupported
) {
996 const uint8_t* alpn_proto
= NULL
;
997 unsigned alpn_len
= 0;
998 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
1000 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
1001 npn_status_
= kNextProtoNegotiated
;
1002 set_negotiation_extension(kExtensionALPN
);
1006 RecordNegotiationExtension();
1007 RecordChannelIDSupport(channel_id_service_
, channel_id_sent_
,
1008 ssl_config_
.channel_id_enabled
,
1009 crypto::ECPrivateKey::IsSupported());
1011 // Only record OCSP histograms if OCSP was requested.
1012 if (ssl_config_
.signed_cert_timestamps_enabled
||
1013 cert_verifier_
->SupportsOCSPStapling()) {
1014 const uint8_t* ocsp_response
;
1015 size_t ocsp_response_len
;
1016 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
1018 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
1019 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
1022 const uint8_t* sct_list
;
1023 size_t sct_list_len
;
1024 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
1025 set_signed_cert_timestamps_received(sct_list_len
!= 0);
1027 if (IsRenegotiationAllowed())
1028 SSL_set_reject_peer_renegotiations(ssl_
, 0);
1030 // Verify the certificate.
1032 GotoState(STATE_VERIFY_CERT
);
1036 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1037 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
);
1038 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1039 return channel_id_service_
->GetOrCreateChannelID(
1040 host_and_port_
.host(), &channel_id_key_
,
1041 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1042 base::Unretained(this)),
1043 &channel_id_request_
);
1046 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1050 if (!channel_id_key_
) {
1051 LOG(ERROR
) << "Failed to import Channel ID.";
1052 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1055 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1057 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1058 int rv
= SSL_set1_tls_channel_id(ssl_
, channel_id_key_
->key());
1060 LOG(ERROR
) << "Failed to set Channel ID.";
1061 int err
= SSL_get_error(ssl_
, rv
);
1062 return MapOpenSSLError(err
, err_tracer
);
1065 // Return to the handshake.
1066 channel_id_sent_
= true;
1067 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
);
1068 GotoState(STATE_HANDSHAKE
);
1072 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1073 DCHECK(!server_cert_chain_
->empty());
1074 DCHECK(start_cert_verification_time_
.is_null());
1076 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1078 // If the certificate is bad and has been previously accepted, use
1079 // the previous status and bypass the error.
1080 base::StringPiece der_cert
;
1081 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1083 return ERR_CERT_INVALID
;
1085 CertStatus cert_status
;
1086 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1087 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1088 server_cert_verify_result_
.Reset();
1089 server_cert_verify_result_
.cert_status
= cert_status
;
1090 server_cert_verify_result_
.verified_cert
= server_cert_
;
1094 // When running in a sandbox, it may not be possible to create an
1095 // X509Certificate*, as that may depend on OS functionality blocked
1097 if (!server_cert_
.get()) {
1098 server_cert_verify_result_
.Reset();
1099 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
1100 return ERR_CERT_INVALID
;
1103 std::string ocsp_response
;
1104 if (cert_verifier_
->SupportsOCSPStapling()) {
1105 const uint8_t* ocsp_response_raw
;
1106 size_t ocsp_response_len
;
1107 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1108 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1112 start_cert_verification_time_
= base::TimeTicks::Now();
1114 return cert_verifier_
->Verify(
1115 server_cert_
.get(), host_and_port_
.host(), ocsp_response
,
1116 ssl_config_
.GetCertVerifyFlags(),
1117 // TODO(davidben): Route the CRLSet through SSLConfig so
1118 // SSLClientSocket doesn't depend on SSLConfigService.
1119 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_
,
1120 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1121 base::Unretained(this)),
1122 &cert_verifier_request_
, net_log_
);
1125 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1126 cert_verifier_request_
.reset();
1128 if (!start_cert_verification_time_
.is_null()) {
1129 base::TimeDelta verify_time
=
1130 base::TimeTicks::Now() - start_cert_verification_time_
;
1132 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1134 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1139 if (SSL_session_reused(ssl_
)) {
1140 // Record whether or not the server tried to resume a session for a
1141 // different version. See https://crbug.com/441456.
1142 UMA_HISTOGRAM_BOOLEAN(
1143 "Net.SSLSessionVersionMatch",
1144 SSL_version(ssl_
) == SSL_get_session(ssl_
)->ssl_version
);
1148 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1149 if (transport_security_state_
&&
1151 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1152 !transport_security_state_
->CheckPublicKeyPins(
1153 host_and_port_
.host(),
1154 server_cert_verify_result_
.is_issued_by_known_root
,
1155 server_cert_verify_result_
.public_key_hashes
,
1156 &pinning_failure_log_
)) {
1157 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1161 // Only check Certificate Transparency if there were no other errors with
1165 DCHECK(!certificate_verified_
);
1166 certificate_verified_
= true;
1167 MaybeCacheSession();
1169 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1170 << " (" << result
<< ")";
1173 completed_connect_
= true;
1174 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1175 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1179 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1180 if (!user_connect_callback_
.is_null()) {
1181 CompletionCallback c
= user_connect_callback_
;
1182 user_connect_callback_
.Reset();
1183 c
.Run(rv
> OK
? OK
: rv
);
1187 void SSLClientSocketOpenSSL::UpdateServerCert() {
1188 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1189 server_cert_
= server_cert_chain_
->AsOSChain();
1190 if (server_cert_
.get()) {
1192 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
1193 base::Bind(&NetLogX509CertificateCallback
,
1194 base::Unretained(server_cert_
.get())));
1198 void SSLClientSocketOpenSSL::VerifyCT() {
1199 if (!cert_transparency_verifier_
)
1202 const uint8_t* ocsp_response_raw
;
1203 size_t ocsp_response_len
;
1204 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1205 std::string ocsp_response
;
1206 if (ocsp_response_len
> 0) {
1207 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1211 const uint8_t* sct_list_raw
;
1212 size_t sct_list_len
;
1213 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1214 std::string sct_list
;
1215 if (sct_list_len
> 0)
1216 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1218 // Note that this is a completely synchronous operation: The CT Log Verifier
1219 // gets all the data it needs for SCT verification and does not do any
1220 // external communication.
1221 cert_transparency_verifier_
->Verify(
1222 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1223 &ct_verify_result_
, net_log_
);
1225 if (policy_enforcer_
&&
1226 (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
)) {
1227 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1228 SSLConfigService::GetEVCertsWhitelist();
1229 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1230 server_cert_verify_result_
.verified_cert
.get(), ev_whitelist
.get(),
1231 ct_verify_result_
, net_log_
)) {
1232 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1233 VLOG(1) << "EV certificate for "
1234 << server_cert_verify_result_
.verified_cert
->subject()
1236 << " does not conform to CT policy, removing EV status.";
1237 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1242 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1243 int rv
= DoHandshakeLoop(result
);
1244 if (rv
!= ERR_IO_PENDING
) {
1245 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1246 DoConnectCallback(rv
);
1250 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1251 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1252 // In handshake phase.
1253 OnHandshakeIOComplete(result
);
1257 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1258 // handshake is in progress.
1259 int rv_read
= ERR_IO_PENDING
;
1260 int rv_write
= ERR_IO_PENDING
;
1263 if (user_read_buf_
.get())
1264 rv_read
= DoPayloadRead();
1265 if (user_write_buf_
.get())
1266 rv_write
= DoPayloadWrite();
1267 network_moved
= DoTransportIO();
1268 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1269 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1271 // Performing the Read callback may cause |this| to be deleted. If this
1272 // happens, the Write callback should not be invoked. Guard against this by
1273 // holding a WeakPtr to |this| and ensuring it's still valid.
1274 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1275 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1276 DoReadCallback(rv_read
);
1281 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1282 DoWriteCallback(rv_write
);
1285 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1286 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1287 // In handshake phase.
1288 OnHandshakeIOComplete(result
);
1292 // Network layer received some data, check if client requested to read
1294 if (!user_read_buf_
.get())
1297 int rv
= DoReadLoop();
1298 if (rv
!= ERR_IO_PENDING
)
1302 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1303 int rv
= last_io_result
;
1305 // Default to STATE_NONE for next state.
1306 // (This is a quirk carried over from the windows
1307 // implementation. It makes reading the logs a bit harder.)
1308 // State handlers can and often do call GotoState just
1309 // to stay in the current state.
1310 State state
= next_handshake_state_
;
1311 GotoState(STATE_NONE
);
1313 case STATE_HANDSHAKE
:
1316 case STATE_HANDSHAKE_COMPLETE
:
1317 rv
= DoHandshakeComplete(rv
);
1319 case STATE_CHANNEL_ID_LOOKUP
:
1321 rv
= DoChannelIDLookup();
1323 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1324 rv
= DoChannelIDLookupComplete(rv
);
1326 case STATE_VERIFY_CERT
:
1328 rv
= DoVerifyCert(rv
);
1330 case STATE_VERIFY_CERT_COMPLETE
:
1331 rv
= DoVerifyCertComplete(rv
);
1335 rv
= ERR_UNEXPECTED
;
1336 NOTREACHED() << "unexpected state" << state
;
1340 bool network_moved
= DoTransportIO();
1341 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1342 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1343 // special case we keep looping even if rv is ERR_IO_PENDING because
1344 // the transport IO may allow DoHandshake to make progress.
1345 rv
= OK
; // This causes us to stay in the loop.
1347 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1351 int SSLClientSocketOpenSSL::DoReadLoop() {
1355 rv
= DoPayloadRead();
1356 network_moved
= DoTransportIO();
1357 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1362 int SSLClientSocketOpenSSL::DoWriteLoop() {
1366 rv
= DoPayloadWrite();
1367 network_moved
= DoTransportIO();
1368 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1373 int SSLClientSocketOpenSSL::DoPayloadRead() {
1374 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1376 DCHECK_LT(0, user_read_buf_len_
);
1377 DCHECK(user_read_buf_
.get());
1380 if (pending_read_error_
!= kNoPendingReadResult
) {
1381 rv
= pending_read_error_
;
1382 pending_read_error_
= kNoPendingReadResult
;
1384 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1385 rv
, user_read_buf_
->data());
1388 NetLog::TYPE_SSL_READ_ERROR
,
1389 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1390 pending_read_error_info_
));
1392 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1393 pending_read_error_info_
= OpenSSLErrorInfo();
1397 int total_bytes_read
= 0;
1400 ssl_ret
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1401 user_read_buf_len_
- total_bytes_read
);
1403 total_bytes_read
+= ssl_ret
;
1404 } while (total_bytes_read
< user_read_buf_len_
&& ssl_ret
> 0);
1406 // Although only the final SSL_read call may have failed, the failure needs to
1407 // processed immediately, while the information still available in OpenSSL's
1410 // A zero return from SSL_read may mean any of:
1411 // - The underlying BIO_read returned 0.
1412 // - The peer sent a close_notify.
1413 // - Any arbitrary error. https://crbug.com/466303
1415 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1416 // error, so it does not occur. The second and third are distinguished by
1417 // SSL_ERROR_ZERO_RETURN.
1418 pending_read_ssl_error_
= SSL_get_error(ssl_
, ssl_ret
);
1419 if (pending_read_ssl_error_
== SSL_ERROR_ZERO_RETURN
) {
1420 pending_read_error_
= 0;
1421 } else if (pending_read_ssl_error_
== SSL_ERROR_WANT_X509_LOOKUP
&&
1422 !ssl_config_
.send_client_cert
) {
1423 pending_read_error_
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1425 pending_read_error_
= MapOpenSSLErrorWithDetails(
1426 pending_read_ssl_error_
, err_tracer
, &pending_read_error_info_
);
1429 // Many servers do not reliably send a close_notify alert when shutting down
1430 // a connection, and instead terminate the TCP connection. This is reported
1431 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1432 // graceful EOF, instead of treating it as an error as it should be.
1433 if (pending_read_error_
== ERR_CONNECTION_CLOSED
)
1434 pending_read_error_
= 0;
1437 if (total_bytes_read
> 0) {
1438 // Return any bytes read to the caller. The error will be deferred to the
1439 // next call of DoPayloadRead.
1440 rv
= total_bytes_read
;
1442 // Do not treat insufficient data as an error to return in the next call to
1443 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1444 // again. This is because DoTransportIO() may complete in between the next
1445 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1446 // subsequent invocations to see if a complete record may now be read.
1447 if (pending_read_error_
== ERR_IO_PENDING
)
1448 pending_read_error_
= kNoPendingReadResult
;
1450 // No bytes were returned. Return the pending read error immediately.
1451 DCHECK_NE(kNoPendingReadResult
, pending_read_error_
);
1452 rv
= pending_read_error_
;
1453 pending_read_error_
= kNoPendingReadResult
;
1457 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1458 user_read_buf_
->data());
1459 } else if (rv
!= ERR_IO_PENDING
) {
1461 NetLog::TYPE_SSL_READ_ERROR
,
1462 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1463 pending_read_error_info_
));
1464 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1465 pending_read_error_info_
= OpenSSLErrorInfo();
1470 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1471 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1472 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1475 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1476 user_write_buf_
->data());
1480 int ssl_error
= SSL_get_error(ssl_
, rv
);
1481 OpenSSLErrorInfo error_info
;
1482 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1485 if (net_error
!= ERR_IO_PENDING
) {
1487 NetLog::TYPE_SSL_WRITE_ERROR
,
1488 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1493 int SSLClientSocketOpenSSL::BufferSend(void) {
1494 if (transport_send_busy_
)
1495 return ERR_IO_PENDING
;
1497 size_t buffer_read_offset
;
1500 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1501 &buffer_read_offset
, &max_read
);
1502 DCHECK_EQ(status
, 1); // Should never fail.
1504 return 0; // Nothing pending in the OpenSSL write BIO.
1505 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1506 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1507 send_buffer_
->set_offset(buffer_read_offset
);
1509 int rv
= transport_
->socket()->Write(
1510 send_buffer_
.get(), max_read
,
1511 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1512 base::Unretained(this)));
1513 if (rv
== ERR_IO_PENDING
) {
1514 transport_send_busy_
= true;
1516 TransportWriteComplete(rv
);
1521 int SSLClientSocketOpenSSL::BufferRecv(void) {
1522 if (transport_recv_busy_
)
1523 return ERR_IO_PENDING
;
1525 // Determine how much was requested from |transport_bio_| that was not
1526 // actually available.
1527 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1528 if (requested
== 0) {
1529 // This is not a perfect match of error codes, as no operation is
1530 // actually pending. However, returning 0 would be interpreted as
1531 // a possible sign of EOF, which is also an inappropriate match.
1532 return ERR_IO_PENDING
;
1535 // Known Issue: While only reading |requested| data is the more correct
1536 // implementation, it has the downside of resulting in frequent reads:
1537 // One read for the SSL record header (~5 bytes) and one read for the SSL
1538 // record body. Rather than issuing these reads to the underlying socket
1539 // (and constantly allocating new IOBuffers), a single Read() request to
1540 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1541 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1542 // traffic, this over-subscribed Read()ing will not cause issues.
1544 size_t buffer_write_offset
;
1547 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1548 &buffer_write_offset
, &max_write
);
1549 DCHECK_EQ(status
, 1); // Should never fail.
1551 return ERR_IO_PENDING
;
1554 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1555 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1557 recv_buffer_
->set_offset(buffer_write_offset
);
1558 int rv
= transport_
->socket()->Read(
1561 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1562 base::Unretained(this)));
1563 if (rv
== ERR_IO_PENDING
) {
1564 transport_recv_busy_
= true;
1566 rv
= TransportReadComplete(rv
);
1571 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1572 TransportWriteComplete(result
);
1573 OnSendComplete(result
);
1576 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1577 result
= TransportReadComplete(result
);
1578 OnRecvComplete(result
);
1581 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1582 DCHECK(ERR_IO_PENDING
!= result
);
1583 int bytes_written
= 0;
1585 // Record the error. Save it to be reported in a future read or write on
1586 // transport_bio_'s peer.
1587 transport_write_error_
= result
;
1589 bytes_written
= result
;
1591 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1592 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1594 transport_send_busy_
= false;
1597 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1598 DCHECK(ERR_IO_PENDING
!= result
);
1599 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1600 // does not report success.
1602 result
= ERR_CONNECTION_CLOSED
;
1605 DVLOG(1) << "TransportReadComplete result " << result
;
1606 // Received an error. Save it to be reported in a future read on
1607 // transport_bio_'s peer.
1608 transport_read_error_
= result
;
1610 bytes_read
= result
;
1612 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1613 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1615 transport_recv_busy_
= false;
1619 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1620 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1621 DCHECK(ssl
== ssl_
);
1623 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1625 // Clear any currently configured certificates.
1626 SSL_certs_clear(ssl_
);
1629 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1630 LOG(WARNING
) << "Client auth is not supported";
1631 #else // !defined(OS_IOS)
1632 if (!ssl_config_
.send_client_cert
) {
1633 // First pass: we know that a client certificate is needed, but we do not
1634 // have one at hand.
1635 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1636 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1637 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1638 unsigned char* str
= NULL
;
1639 int length
= i2d_X509_NAME(ca_name
, &str
);
1640 cert_authorities_
.push_back(std::string(
1641 reinterpret_cast<const char*>(str
),
1642 static_cast<size_t>(length
)));
1646 const unsigned char* client_cert_types
;
1647 size_t num_client_cert_types
=
1648 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1649 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1650 cert_key_types_
.push_back(
1651 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1654 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1658 // Second pass: a client certificate should have been selected.
1659 if (ssl_config_
.client_cert
.get()) {
1660 ScopedX509 leaf_x509
=
1661 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1663 LOG(WARNING
) << "Failed to import certificate";
1664 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1668 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1669 ssl_config_
.client_cert
->GetIntermediateCertificates());
1671 LOG(WARNING
) << "Failed to import intermediate certificates";
1672 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1676 // TODO(davidben): With Linux client auth support, this should be
1677 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1678 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1679 // net/ client auth API lacking a private key handle.
1680 #if defined(USE_OPENSSL_CERTS)
1681 crypto::ScopedEVP_PKEY privkey
=
1682 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1683 ssl_config_
.client_cert
.get());
1684 #else // !defined(USE_OPENSSL_CERTS)
1685 crypto::ScopedEVP_PKEY privkey
=
1686 FetchClientCertPrivateKey(ssl_config_
.client_cert
.get());
1687 #endif // defined(USE_OPENSSL_CERTS)
1689 // Could not find the private key. Fail the handshake and surface an
1690 // appropriate error to the caller.
1691 LOG(WARNING
) << "Client cert found without private key";
1692 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1696 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1697 !SSL_use_PrivateKey(ssl_
, privkey
.get()) ||
1698 !SSL_set1_chain(ssl_
, chain
.get())) {
1699 LOG(WARNING
) << "Failed to set client certificate";
1703 int cert_count
= 1 + sk_X509_num(chain
.get());
1704 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1705 NetLog::IntegerCallback("cert_count", cert_count
));
1708 #endif // defined(OS_IOS)
1710 // Send no client certificate.
1711 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1712 NetLog::IntegerCallback("cert_count", 0));
1716 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1717 if (!completed_connect_
) {
1718 // If the first handshake hasn't completed then we accept any certificates
1719 // because we verify after the handshake.
1723 // Disallow the server certificate to change in a renegotiation.
1724 if (server_cert_chain_
->empty()) {
1725 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1728 base::StringPiece old_der
, new_der
;
1729 if (store_ctx
->cert
== NULL
||
1730 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1731 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1732 LOG(ERROR
) << "Failed to encode certificates";
1735 if (old_der
!= new_der
) {
1736 LOG(ERROR
) << "Server certificate changed between handshakes";
1743 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1744 // server supports NPN, selects a protocol from the list that the server
1745 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1746 // callback can assume that |in| is syntactically valid.
1747 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1748 unsigned char* outlen
,
1749 const unsigned char* in
,
1750 unsigned int inlen
) {
1751 if (ssl_config_
.next_protos
.empty()) {
1752 *out
= reinterpret_cast<uint8
*>(
1753 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1754 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1755 npn_status_
= kNextProtoUnsupported
;
1756 return SSL_TLSEXT_ERR_OK
;
1759 // Assume there's no overlap between our protocols and the server's list.
1760 npn_status_
= kNextProtoNoOverlap
;
1762 // For each protocol in server preference order, see if we support it.
1763 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1764 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1765 const std::string proto
= NextProtoToString(next_proto
);
1766 if (in
[i
] == proto
.size() &&
1767 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1768 // We found a match.
1769 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1771 npn_status_
= kNextProtoNegotiated
;
1775 if (npn_status_
== kNextProtoNegotiated
)
1779 // If we didn't find a protocol, we select the first one from our list.
1780 if (npn_status_
== kNextProtoNoOverlap
) {
1781 // NextProtoToString returns a pointer to a static string.
1782 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1783 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1784 *outlen
= strlen(proto
);
1787 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1788 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1789 set_negotiation_extension(kExtensionNPN
);
1790 return SSL_TLSEXT_ERR_OK
;
1793 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1796 const char *argp
, int argi
, long argl
,
1798 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1799 // If there is no more data in the buffer, report any pending errors that
1800 // were observed. Note that both the readbuf and the writebuf are checked
1801 // for errors, since the application may have encountered a socket error
1802 // while writing that would otherwise not be reported until the application
1803 // attempted to write again - which it may never do. See
1804 // https://crbug.com/249848.
1805 if (transport_read_error_
!= OK
) {
1806 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1809 if (transport_write_error_
!= OK
) {
1810 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1813 } else if (cmd
== BIO_CB_WRITE
) {
1814 // Because of the write buffer, this reports a failure from the previous
1815 // write payload. If the current payload fails to write, the error will be
1816 // reported in a future write or read to |bio|.
1817 if (transport_write_error_
!= OK
) {
1818 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1826 long SSLClientSocketOpenSSL::BIOCallback(
1829 const char *argp
, int argi
, long argl
,
1831 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1832 BIO_get_callback_arg(bio
));
1834 return socket
->MaybeReplayTransportError(
1835 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1838 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1839 // Only cache the session once both a new session has been established and the
1840 // certificate has been verified. Due to False Start, these events may happen
1842 if (!session_pending_
|| !certificate_verified_
)
1845 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1846 SSL_get_session(ssl_
));
1847 session_pending_
= false;
1850 int SSLClientSocketOpenSSL::NewSessionCallback(SSL_SESSION
* session
) {
1851 DCHECK_EQ(session
, SSL_get_session(ssl_
));
1853 // Only sessions from the initial handshake get cached. Note this callback may
1854 // be signaled on abbreviated handshakes if the ticket was renewed.
1855 session_pending_
= true;
1856 MaybeCacheSession();
1858 // OpenSSL passes a reference to |session|, but the session cache does not
1859 // take this reference, so release it.
1860 SSL_SESSION_free(session
);
1864 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
1865 for (ct::SCTList::const_iterator iter
=
1866 ct_verify_result_
.verified_scts
.begin();
1867 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
1868 ssl_info
->signed_certificate_timestamps
.push_back(
1869 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
1871 for (ct::SCTList::const_iterator iter
=
1872 ct_verify_result_
.invalid_scts
.begin();
1873 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
1874 ssl_info
->signed_certificate_timestamps
.push_back(
1875 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
1877 for (ct::SCTList::const_iterator iter
=
1878 ct_verify_result_
.unknown_logs_scts
.begin();
1879 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
1880 ssl_info
->signed_certificate_timestamps
.push_back(
1881 SignedCertificateTimestampAndStatus(*iter
,
1882 ct::SCT_STATUS_LOG_UNKNOWN
));
1886 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1887 std::string result
= host_and_port_
.ToString();
1889 result
.append(ssl_session_cache_shard_
);
1891 // Shard the session cache based on maximum protocol version. This causes
1892 // fallback connections to use a separate session cache.
1894 switch (ssl_config_
.version_max
) {
1895 case SSL_PROTOCOL_VERSION_TLS1
:
1896 result
.append("tls1");
1898 case SSL_PROTOCOL_VERSION_TLS1_1
:
1899 result
.append("tls1.1");
1901 case SSL_PROTOCOL_VERSION_TLS1_2
:
1902 result
.append("tls1.2");
1909 if (ssl_config_
.enable_deprecated_cipher_suites
)
1910 result
.append("deprecated");
1915 bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
1916 if (npn_status_
== kNextProtoUnsupported
)
1917 return ssl_config_
.renego_allowed_default
;
1919 NextProto next_proto
= NextProtoFromString(npn_proto_
);
1920 for (NextProto allowed
: ssl_config_
.renego_allowed_for_protos
) {
1921 if (next_proto
== allowed
)