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/ssl.h>
16 #include "base/bind.h"
17 #include "base/callback_helpers.h"
18 #include "base/environment.h"
19 #include "base/memory/singleton.h"
20 #include "base/metrics/histogram.h"
21 #include "base/profiler/scoped_tracker.h"
22 #include "base/strings/string_piece.h"
23 #include "base/synchronization/lock.h"
24 #include "base/threading/thread_local.h"
25 #include "crypto/ec_private_key.h"
26 #include "crypto/openssl_util.h"
27 #include "crypto/scoped_openssl_types.h"
28 #include "net/base/net_errors.h"
29 #include "net/cert/cert_policy_enforcer.h"
30 #include "net/cert/cert_verifier.h"
31 #include "net/cert/ct_ev_whitelist.h"
32 #include "net/cert/ct_verifier.h"
33 #include "net/cert/single_request_cert_verifier.h"
34 #include "net/cert/x509_certificate_net_log_param.h"
35 #include "net/cert/x509_util_openssl.h"
36 #include "net/http/transport_security_state.h"
37 #include "net/ssl/scoped_openssl_types.h"
38 #include "net/ssl/ssl_cert_request_info.h"
39 #include "net/ssl/ssl_client_session_cache_openssl.h"
40 #include "net/ssl/ssl_connection_status_flags.h"
41 #include "net/ssl/ssl_info.h"
44 #include "base/win/windows_version.h"
47 #if defined(USE_OPENSSL_CERTS)
48 #include "net/ssl/openssl_client_key_store.h"
50 #include "net/ssl/openssl_platform_key.h"
57 // Enable this to see logging for state machine state transitions.
59 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
60 " jump to state " << s; \
61 next_handshake_state_ = s; } while (0)
63 #define GotoState(s) next_handshake_state_ = s
66 // This constant can be any non-negative/non-zero value (eg: it does not
67 // overlap with any value of the net::Error range, including net::OK).
68 const int kNoPendingReadResult
= 1;
70 // If a client doesn't have a list of protocols that it supports, but
71 // the server supports NPN, choosing "http/1.1" is the best answer.
72 const char kDefaultSupportedNPNProtocol
[] = "http/1.1";
74 // Default size of the internal BoringSSL buffers.
75 const int KDefaultOpenSSLBufferSize
= 17 * 1024;
77 void FreeX509Stack(STACK_OF(X509
)* ptr
) {
78 sk_X509_pop_free(ptr
, X509_free
);
81 using ScopedX509Stack
= crypto::ScopedOpenSSL
<STACK_OF(X509
), FreeX509Stack
>;
83 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
84 // This method doesn't seem to have made it into the OpenSSL headers.
85 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER
* cipher
) { return cipher
->id
; }
88 // Used for encoding the |connection_status| field of an SSLInfo object.
89 int EncodeSSLConnectionStatus(uint16 cipher_suite
,
93 ((compression
& SSL_CONNECTION_COMPRESSION_MASK
) <<
94 SSL_CONNECTION_COMPRESSION_SHIFT
) |
95 ((version
& SSL_CONNECTION_VERSION_MASK
) <<
96 SSL_CONNECTION_VERSION_SHIFT
);
99 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
100 // this SSL connection.
101 int GetNetSSLVersion(SSL
* ssl
) {
102 switch (SSL_version(ssl
)) {
104 return SSL_CONNECTION_VERSION_SSL2
;
106 return SSL_CONNECTION_VERSION_SSL3
;
108 return SSL_CONNECTION_VERSION_TLS1
;
110 return SSL_CONNECTION_VERSION_TLS1_1
;
112 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
);
148 bool IsOCSPStaplingSupported() {
150 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
151 // set on Windows XP without error. There is some overhead from the server
152 // sending the OCSP response if it supports the extension, for the subset of
153 // XP clients who will request it but be unable to use it, but this is an
154 // acceptable trade-off for simplicity of implementation.
163 class SSLClientSocketOpenSSL::SSLContext
{
165 static SSLContext
* GetInstance() { return Singleton
<SSLContext
>::get(); }
166 SSL_CTX
* ssl_ctx() { return ssl_ctx_
.get(); }
167 SSLClientSessionCacheOpenSSL
* session_cache() { return &session_cache_
; }
169 SSLClientSocketOpenSSL
* GetClientSocketFromSSL(const SSL
* ssl
) {
171 SSLClientSocketOpenSSL
* socket
= static_cast<SSLClientSocketOpenSSL
*>(
172 SSL_get_ex_data(ssl
, ssl_socket_data_index_
));
177 bool SetClientSocketForSSL(SSL
* ssl
, SSLClientSocketOpenSSL
* socket
) {
178 return SSL_set_ex_data(ssl
, ssl_socket_data_index_
, socket
) != 0;
182 friend struct DefaultSingletonTraits
<SSLContext
>;
184 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
185 crypto::EnsureOpenSSLInit();
186 ssl_socket_data_index_
= SSL_get_ex_new_index(0, 0, 0, 0, 0);
187 DCHECK_NE(ssl_socket_data_index_
, -1);
188 ssl_ctx_
.reset(SSL_CTX_new(SSLv23_client_method()));
189 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
190 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
191 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
192 // This stops |SSL_shutdown| from generating the close_notify message, which
193 // is currently not sent on the network.
194 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
195 SSL_CTX_set_quiet_shutdown(ssl_ctx_
.get(), 1);
196 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
197 // It would be better if the callback were not a global setting,
198 // but that is an OpenSSL issue.
199 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
201 ssl_ctx_
->tlsext_channel_id_enabled_new
= 1;
202 SSL_CTX_set_info_callback(ssl_ctx_
.get(), InfoCallback
);
204 // Disable the internal session cache. Session caching is handled
205 // externally (i.e. by SSLClientSessionCacheOpenSSL).
206 SSL_CTX_set_session_cache_mode(
207 ssl_ctx_
.get(), SSL_SESS_CACHE_CLIENT
| SSL_SESS_CACHE_NO_INTERNAL
);
209 scoped_ptr
<base::Environment
> env(base::Environment::Create());
210 std::string ssl_keylog_file
;
211 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
212 !ssl_keylog_file
.empty()) {
213 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
214 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
216 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
217 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
219 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
224 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
225 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
227 return socket
->ClientCertRequestCallback(ssl
);
230 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
231 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
232 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
233 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
236 return socket
->CertVerifyCallback(store_ctx
);
239 static int SelectNextProtoCallback(SSL
* ssl
,
240 unsigned char** out
, unsigned char* outlen
,
241 const unsigned char* in
,
242 unsigned int inlen
, void* arg
) {
243 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
244 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
247 static void InfoCallback(const SSL
* ssl
, int type
, int val
) {
248 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
249 socket
->InfoCallback(type
, val
);
252 // This is the index used with SSL_get_ex_data to retrieve the owner
253 // SSLClientSocketOpenSSL object from an SSL instance.
254 int ssl_socket_data_index_
;
256 ScopedSSL_CTX ssl_ctx_
;
258 // TODO(davidben): Use a separate cache per URLRequestContext.
259 // https://crbug.com/458365
261 // TODO(davidben): Sessions should be invalidated on fatal
262 // alerts. https://crbug.com/466352
263 SSLClientSessionCacheOpenSSL session_cache_
;
266 // PeerCertificateChain is a helper object which extracts the certificate
267 // chain, as given by the server, from an OpenSSL socket and performs the needed
268 // resource management. The first element of the chain is the leaf certificate
269 // and the other elements are in the order given by the server.
270 class SSLClientSocketOpenSSL::PeerCertificateChain
{
272 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
273 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
274 ~PeerCertificateChain() {}
275 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
277 // Resets the PeerCertificateChain to the set of certificates in|chain|,
278 // which may be NULL, indicating to empty the store certificates.
279 // Note: If an error occurs, such as being unable to parse the certificates,
280 // this will behave as if Reset(NULL) was called.
281 void Reset(STACK_OF(X509
)* chain
);
283 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
284 scoped_refptr
<X509Certificate
> AsOSChain() const;
286 size_t size() const {
287 if (!openssl_chain_
.get())
289 return sk_X509_num(openssl_chain_
.get());
296 X509
* Get(size_t index
) const {
297 DCHECK_LT(index
, size());
298 return sk_X509_value(openssl_chain_
.get(), index
);
302 ScopedX509Stack openssl_chain_
;
305 SSLClientSocketOpenSSL::PeerCertificateChain
&
306 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
307 const PeerCertificateChain
& other
) {
311 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
315 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
316 STACK_OF(X509
)* chain
) {
317 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
320 scoped_refptr
<X509Certificate
>
321 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
322 #if defined(USE_OPENSSL_CERTS)
323 // When OSCertHandle is typedef'ed to X509, this implementation does a short
324 // cut to avoid converting back and forth between DER and the X509 struct.
325 X509Certificate::OSCertHandles intermediates
;
326 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
327 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
330 return make_scoped_refptr(X509Certificate::CreateFromHandle(
331 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
333 // DER-encode the chain and convert to a platform certificate handle.
334 std::vector
<base::StringPiece
> der_chain
;
335 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
336 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
337 base::StringPiece der
;
338 if (!x509_util::GetDER(x
, &der
))
340 der_chain
.push_back(der
);
343 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
348 void SSLClientSocket::ClearSessionCache() {
349 SSLClientSocketOpenSSL::SSLContext
* context
=
350 SSLClientSocketOpenSSL::SSLContext::GetInstance();
351 context
->session_cache()->Flush();
355 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
356 return SSL_PROTOCOL_VERSION_TLS1_2
;
359 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
360 scoped_ptr
<ClientSocketHandle
> transport_socket
,
361 const HostPortPair
& host_and_port
,
362 const SSLConfig
& ssl_config
,
363 const SSLClientSocketContext
& context
)
364 : transport_send_busy_(false),
365 transport_recv_busy_(false),
366 pending_read_error_(kNoPendingReadResult
),
367 pending_read_ssl_error_(SSL_ERROR_NONE
),
368 transport_read_error_(OK
),
369 transport_write_error_(OK
),
370 server_cert_chain_(new PeerCertificateChain(NULL
)),
371 completed_connect_(false),
372 was_ever_used_(false),
373 client_auth_cert_needed_(false),
374 cert_verifier_(context
.cert_verifier
),
375 cert_transparency_verifier_(context
.cert_transparency_verifier
),
376 channel_id_service_(context
.channel_id_service
),
378 transport_bio_(NULL
),
379 transport_(transport_socket
.Pass()),
380 host_and_port_(host_and_port
),
381 ssl_config_(ssl_config
),
382 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
383 next_handshake_state_(STATE_NONE
),
384 npn_status_(kNextProtoUnsupported
),
385 channel_id_xtn_negotiated_(false),
386 handshake_completed_(false),
387 certificate_verified_(false),
388 transport_security_state_(context
.transport_security_state
),
389 policy_enforcer_(context
.cert_policy_enforcer
),
390 net_log_(transport_
->socket()->NetLog()),
391 weak_factory_(this) {
394 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
398 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
399 SSLCertRequestInfo
* cert_request_info
) {
400 cert_request_info
->host_and_port
= host_and_port_
;
401 cert_request_info
->cert_authorities
= cert_authorities_
;
402 cert_request_info
->cert_key_types
= cert_key_types_
;
405 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
406 std::string
* proto
) {
412 SSLClientSocketOpenSSL::GetChannelIDService() const {
413 return channel_id_service_
;
416 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
417 const base::StringPiece
& label
,
418 bool has_context
, const base::StringPiece
& context
,
419 unsigned char* out
, unsigned int outlen
) {
420 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
422 int rv
= SSL_export_keying_material(
423 ssl_
, out
, outlen
, label
.data(), label
.size(),
424 reinterpret_cast<const unsigned char*>(context
.data()), context
.length(),
425 has_context
? 1 : 0);
428 int ssl_error
= SSL_get_error(ssl_
, rv
);
429 LOG(ERROR
) << "Failed to export keying material;"
430 << " returned " << rv
431 << ", SSL error code " << ssl_error
;
432 return MapOpenSSLError(ssl_error
, err_tracer
);
437 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
439 return ERR_NOT_IMPLEMENTED
;
442 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
443 // It is an error to create an SSLClientSocket whose context has no
444 // TransportSecurityState.
445 DCHECK(transport_security_state_
);
447 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
449 // Set up new ssl object.
452 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
456 // Set SSL to client mode. Handshake happens in the loop below.
457 SSL_set_connect_state(ssl_
);
459 GotoState(STATE_HANDSHAKE
);
460 rv
= DoHandshakeLoop(OK
);
461 if (rv
== ERR_IO_PENDING
) {
462 user_connect_callback_
= callback
;
464 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
467 return rv
> OK
? OK
: rv
;
470 void SSLClientSocketOpenSSL::Disconnect() {
472 // Calling SSL_shutdown prevents the session from being marked as
478 if (transport_bio_
) {
479 BIO_free_all(transport_bio_
);
480 transport_bio_
= NULL
;
483 // Shut down anything that may call us back.
485 transport_
->socket()->Disconnect();
487 // Null all callbacks, delete all buffers.
488 transport_send_busy_
= false;
490 transport_recv_busy_
= false;
493 user_connect_callback_
.Reset();
494 user_read_callback_
.Reset();
495 user_write_callback_
.Reset();
496 user_read_buf_
= NULL
;
497 user_read_buf_len_
= 0;
498 user_write_buf_
= NULL
;
499 user_write_buf_len_
= 0;
501 pending_read_error_
= kNoPendingReadResult
;
502 pending_read_ssl_error_
= SSL_ERROR_NONE
;
503 pending_read_error_info_
= OpenSSLErrorInfo();
505 transport_read_error_
= OK
;
506 transport_write_error_
= OK
;
508 server_cert_verify_result_
.Reset();
509 completed_connect_
= false;
511 cert_authorities_
.clear();
512 cert_key_types_
.clear();
513 client_auth_cert_needed_
= false;
515 start_cert_verification_time_
= base::TimeTicks();
517 npn_status_
= kNextProtoUnsupported
;
520 channel_id_xtn_negotiated_
= false;
521 channel_id_request_handle_
.Cancel();
524 bool SSLClientSocketOpenSSL::IsConnected() const {
525 // If the handshake has not yet completed.
526 if (!completed_connect_
)
528 // If an asynchronous operation is still pending.
529 if (user_read_buf_
.get() || user_write_buf_
.get())
532 return transport_
->socket()->IsConnected();
535 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
536 // If the handshake has not yet completed.
537 if (!completed_connect_
)
539 // If an asynchronous operation is still pending.
540 if (user_read_buf_
.get() || user_write_buf_
.get())
543 // If there is data read from the network that has not yet been consumed, do
544 // not treat the connection as idle.
546 // Note that this does not check |BIO_pending|, whether there is ciphertext
547 // that has not yet been flushed to the network. |Write| returns early, so
548 // this can cause race conditions which cause a socket to not be treated
549 // reusable when it should be. See https://crbug.com/466147.
550 if (BIO_wpending(transport_bio_
) > 0)
553 return transport_
->socket()->IsConnectedAndIdle();
556 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
557 return transport_
->socket()->GetPeerAddress(addressList
);
560 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
561 return transport_
->socket()->GetLocalAddress(addressList
);
564 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
568 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
569 if (transport_
.get() && transport_
->socket()) {
570 transport_
->socket()->SetSubresourceSpeculation();
576 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
577 if (transport_
.get() && transport_
->socket()) {
578 transport_
->socket()->SetOmniboxSpeculation();
584 bool SSLClientSocketOpenSSL::WasEverUsed() const {
585 return was_ever_used_
;
588 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
589 if (transport_
.get() && transport_
->socket())
590 return transport_
->socket()->UsingTCPFastOpen();
596 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
598 if (server_cert_chain_
->empty())
601 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
602 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
603 ssl_info
->is_issued_by_known_root
=
604 server_cert_verify_result_
.is_issued_by_known_root
;
605 ssl_info
->public_key_hashes
=
606 server_cert_verify_result_
.public_key_hashes
;
607 ssl_info
->client_cert_sent
=
608 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
609 ssl_info
->channel_id_sent
= WasChannelIDSent();
610 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
612 AddSCTInfoToSSLInfo(ssl_info
);
614 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
616 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
618 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
619 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
620 GetNetSSLVersion(ssl_
));
622 if (!SSL_get_secure_renegotiation_support(ssl_
))
623 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
625 if (ssl_config_
.version_fallback
)
626 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
628 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
629 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
631 DVLOG(3) << "Encoded connection status: cipher suite = "
632 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
634 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
638 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
640 const CompletionCallback
& callback
) {
641 user_read_buf_
= buf
;
642 user_read_buf_len_
= buf_len
;
644 int rv
= DoReadLoop();
646 if (rv
== ERR_IO_PENDING
) {
647 user_read_callback_
= callback
;
650 was_ever_used_
= true;
651 user_read_buf_
= NULL
;
652 user_read_buf_len_
= 0;
658 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
660 const CompletionCallback
& callback
) {
661 user_write_buf_
= buf
;
662 user_write_buf_len_
= buf_len
;
664 int rv
= DoWriteLoop();
666 if (rv
== ERR_IO_PENDING
) {
667 user_write_callback_
= callback
;
670 was_ever_used_
= true;
671 user_write_buf_
= NULL
;
672 user_write_buf_len_
= 0;
678 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
679 return transport_
->socket()->SetReceiveBufferSize(size
);
682 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
683 return transport_
->socket()->SetSendBufferSize(size
);
686 int SSLClientSocketOpenSSL::Init() {
688 DCHECK(!transport_bio_
);
690 SSLContext
* context
= SSLContext::GetInstance();
691 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
693 ssl_
= SSL_new(context
->ssl_ctx());
694 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
695 return ERR_UNEXPECTED
;
697 if (!SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str()))
698 return ERR_UNEXPECTED
;
700 SSL_SESSION
* session
= context
->session_cache()->Lookup(GetSessionCacheKey());
701 if (session
!= nullptr)
702 SSL_set_session(ssl_
, session
);
704 send_buffer_
= new GrowableIOBuffer();
705 send_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
706 recv_buffer_
= new GrowableIOBuffer();
707 recv_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
711 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
712 if (!BIO_new_bio_pair_external_buf(
713 &ssl_bio
, send_buffer_
->capacity(),
714 reinterpret_cast<uint8_t*>(send_buffer_
->data()), &transport_bio_
,
715 recv_buffer_
->capacity(),
716 reinterpret_cast<uint8_t*>(recv_buffer_
->data())))
717 return ERR_UNEXPECTED
;
719 DCHECK(transport_bio_
);
721 // Install a callback on OpenSSL's end to plumb transport errors through.
722 BIO_set_callback(ssl_bio
, &SSLClientSocketOpenSSL::BIOCallback
);
723 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
725 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
727 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
728 // set everything we care about to an absolute value.
729 SslSetClearMask options
;
730 options
.ConfigureFlag(SSL_OP_NO_SSLv2
, true);
731 bool ssl3_enabled
= (ssl_config_
.version_min
== SSL_PROTOCOL_VERSION_SSL3
);
732 options
.ConfigureFlag(SSL_OP_NO_SSLv3
, !ssl3_enabled
);
733 bool tls1_enabled
= (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1
&&
734 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1
);
735 options
.ConfigureFlag(SSL_OP_NO_TLSv1
, !tls1_enabled
);
736 bool tls1_1_enabled
=
737 (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1_1
&&
738 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
);
739 options
.ConfigureFlag(SSL_OP_NO_TLSv1_1
, !tls1_1_enabled
);
740 bool tls1_2_enabled
=
741 (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1_2
&&
742 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_2
);
743 options
.ConfigureFlag(SSL_OP_NO_TLSv1_2
, !tls1_2_enabled
);
745 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
747 // TODO(joth): Set this conditionally, see http://crbug.com/55410
748 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
750 SSL_set_options(ssl_
, options
.set_mask
);
751 SSL_clear_options(ssl_
, options
.clear_mask
);
753 // Same as above, this time for the SSL mode.
754 SslSetClearMask mode
;
756 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
757 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
759 mode
.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START
,
760 ssl_config_
.false_start_enabled
);
762 mode
.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV
, ssl_config_
.version_fallback
);
764 SSL_set_mode(ssl_
, mode
.set_mask
);
765 SSL_clear_mode(ssl_
, mode
.clear_mask
);
767 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
768 // textual name with SSL_set_cipher_list because there is no public API to
769 // directly remove a cipher by ID.
770 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
772 // See SSLConfig::disabled_cipher_suites for description of the suites
773 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
774 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
775 // as the handshake hash.
777 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!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 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
784 // implementation uses "effective" bits here but OpenSSL does not provide
785 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
786 // both of which are greater than 80 anyway.
787 bool disable
= SSL_CIPHER_get_bits(cipher
, NULL
) < 80;
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 (IsOCSPStaplingSupported())
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
);
860 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
861 // Since Run may result in Read being called, clear |user_read_callback_|
864 was_ever_used_
= true;
865 user_read_buf_
= NULL
;
866 user_read_buf_len_
= 0;
867 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
870 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
871 // Since Run may result in Write being called, clear |user_write_callback_|
874 was_ever_used_
= true;
875 user_write_buf_
= NULL
;
876 user_write_buf_len_
= 0;
877 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
880 bool SSLClientSocketOpenSSL::DoTransportIO() {
881 bool network_moved
= false;
883 // Read and write as much data as possible. The loop is necessary because
884 // Write() may return synchronously.
887 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
888 network_moved
= true;
890 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
891 network_moved
= true;
892 return network_moved
;
895 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
896 // g_first_run_completed once crbug.com/424386 is fixed.
897 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
898 LAZY_INSTANCE_INITIALIZER
;
900 int SSLClientSocketOpenSSL::DoHandshake() {
901 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
906 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
908 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
909 rv
= SSL_do_handshake(ssl_
);
911 if (g_first_run_completed
.Get().Get()) {
912 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
914 tracked_objects::ScopedTracker
tracking_profile(
915 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
917 rv
= SSL_do_handshake(ssl_
);
919 g_first_run_completed
.Get().Set(true);
920 rv
= SSL_do_handshake(ssl_
);
925 if (ssl_config_
.version_fallback
&&
926 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
927 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
930 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
931 if (npn_status_
== kNextProtoUnsupported
) {
932 const uint8_t* alpn_proto
= NULL
;
933 unsigned alpn_len
= 0;
934 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
936 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
937 npn_status_
= kNextProtoNegotiated
;
938 set_negotiation_extension(kExtensionALPN
);
942 RecordChannelIDSupport(channel_id_service_
,
943 channel_id_xtn_negotiated_
,
944 ssl_config_
.channel_id_enabled
,
945 crypto::ECPrivateKey::IsSupported());
947 // Only record OCSP histograms if OCSP was requested.
948 if (ssl_config_
.signed_cert_timestamps_enabled
||
949 IsOCSPStaplingSupported()) {
950 const uint8_t* ocsp_response
;
951 size_t ocsp_response_len
;
952 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
954 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
955 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
958 const uint8_t* sct_list
;
960 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
961 set_signed_cert_timestamps_received(sct_list_len
!= 0);
963 // Verify the certificate.
965 GotoState(STATE_VERIFY_CERT
);
967 if (client_auth_cert_needed_
)
968 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
970 int ssl_error
= SSL_get_error(ssl_
, rv
);
972 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
973 // The server supports channel ID. Stop to look one up before returning to
975 channel_id_xtn_negotiated_
= true;
976 GotoState(STATE_CHANNEL_ID_LOOKUP
);
980 OpenSSLErrorInfo error_info
;
981 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
983 // If not done, stay in this state
984 if (net_error
== ERR_IO_PENDING
) {
985 GotoState(STATE_HANDSHAKE
);
987 LOG(ERROR
) << "handshake failed; returned " << rv
988 << ", SSL error code " << ssl_error
989 << ", net_error " << net_error
;
991 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
992 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
998 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
999 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
);
1000 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1001 return channel_id_service_
->GetOrCreateChannelID(
1002 host_and_port_
.host(),
1003 &channel_id_private_key_
,
1005 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1006 base::Unretained(this)),
1007 &channel_id_request_handle_
);
1010 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1014 DCHECK_LT(0u, channel_id_private_key_
.size());
1016 std::vector
<uint8
> encrypted_private_key_info
;
1017 std::vector
<uint8
> subject_public_key_info
;
1018 encrypted_private_key_info
.assign(
1019 channel_id_private_key_
.data(),
1020 channel_id_private_key_
.data() + channel_id_private_key_
.size());
1021 subject_public_key_info
.assign(
1022 channel_id_cert_
.data(),
1023 channel_id_cert_
.data() + channel_id_cert_
.size());
1024 scoped_ptr
<crypto::ECPrivateKey
> ec_private_key(
1025 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1026 ChannelIDService::kEPKIPassword
,
1027 encrypted_private_key_info
,
1028 subject_public_key_info
));
1029 if (!ec_private_key
) {
1030 LOG(ERROR
) << "Failed to import Channel ID.";
1031 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1034 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1036 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1037 int rv
= SSL_set1_tls_channel_id(ssl_
, ec_private_key
->key());
1039 LOG(ERROR
) << "Failed to set Channel ID.";
1040 int err
= SSL_get_error(ssl_
, rv
);
1041 return MapOpenSSLError(err
, err_tracer
);
1044 // Return to the handshake.
1045 set_channel_id_sent(true);
1046 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
);
1047 GotoState(STATE_HANDSHAKE
);
1051 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1052 DCHECK(!server_cert_chain_
->empty());
1053 DCHECK(start_cert_verification_time_
.is_null());
1055 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1057 // If the certificate is bad and has been previously accepted, use
1058 // the previous status and bypass the error.
1059 base::StringPiece der_cert
;
1060 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1062 return ERR_CERT_INVALID
;
1064 CertStatus cert_status
;
1065 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1066 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1067 server_cert_verify_result_
.Reset();
1068 server_cert_verify_result_
.cert_status
= cert_status
;
1069 server_cert_verify_result_
.verified_cert
= server_cert_
;
1073 // When running in a sandbox, it may not be possible to create an
1074 // X509Certificate*, as that may depend on OS functionality blocked
1076 if (!server_cert_
.get()) {
1077 server_cert_verify_result_
.Reset();
1078 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
1079 return ERR_CERT_INVALID
;
1082 start_cert_verification_time_
= base::TimeTicks::Now();
1085 if (ssl_config_
.rev_checking_enabled
)
1086 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
1087 if (ssl_config_
.verify_ev_cert
)
1088 flags
|= CertVerifier::VERIFY_EV_CERT
;
1089 if (ssl_config_
.cert_io_enabled
)
1090 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
1091 if (ssl_config_
.rev_checking_required_local_anchors
)
1092 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
1093 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
1094 return verifier_
->Verify(
1096 host_and_port_
.host(),
1098 // TODO(davidben): Route the CRLSet through SSLConfig so
1099 // SSLClientSocket doesn't depend on SSLConfigService.
1100 SSLConfigService::GetCRLSet().get(),
1101 &server_cert_verify_result_
,
1102 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1103 base::Unretained(this)),
1107 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1110 if (!start_cert_verification_time_
.is_null()) {
1111 base::TimeDelta verify_time
=
1112 base::TimeTicks::Now() - start_cert_verification_time_
;
1114 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1116 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1121 if (SSL_session_reused(ssl_
)) {
1122 // Record whether or not the server tried to resume a session for a
1123 // different version. See https://crbug.com/441456.
1124 UMA_HISTOGRAM_BOOLEAN(
1125 "Net.SSLSessionVersionMatch",
1126 SSL_version(ssl_
) == SSL_get_session(ssl_
)->ssl_version
);
1130 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1131 if (transport_security_state_
&&
1133 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1134 !transport_security_state_
->CheckPublicKeyPins(
1135 host_and_port_
.host(),
1136 server_cert_verify_result_
.is_issued_by_known_root
,
1137 server_cert_verify_result_
.public_key_hashes
,
1138 &pinning_failure_log_
)) {
1139 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1143 // Only check Certificate Transparency if there were no other errors with
1147 DCHECK(!certificate_verified_
);
1148 certificate_verified_
= true;
1149 MaybeCacheSession();
1151 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1152 << " (" << result
<< ")";
1155 completed_connect_
= true;
1156 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1157 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1161 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1162 if (!user_connect_callback_
.is_null()) {
1163 CompletionCallback c
= user_connect_callback_
;
1164 user_connect_callback_
.Reset();
1165 c
.Run(rv
> OK
? OK
: rv
);
1169 void SSLClientSocketOpenSSL::UpdateServerCert() {
1170 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1171 server_cert_
= server_cert_chain_
->AsOSChain();
1172 if (server_cert_
.get()) {
1174 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
1175 base::Bind(&NetLogX509CertificateCallback
,
1176 base::Unretained(server_cert_
.get())));
1178 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1179 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1180 if (IsOCSPStaplingSupported()) {
1182 const uint8_t* ocsp_response_raw
;
1183 size_t ocsp_response_len
;
1184 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1186 CRYPT_DATA_BLOB ocsp_response_blob
;
1187 ocsp_response_blob
.cbData
= ocsp_response_len
;
1188 ocsp_response_blob
.pbData
= const_cast<BYTE
*>(ocsp_response_raw
);
1189 BOOL ok
= CertSetCertificateContextProperty(
1190 server_cert_
->os_cert_handle(),
1191 CERT_OCSP_RESPONSE_PROP_ID
,
1192 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
1193 &ocsp_response_blob
);
1195 VLOG(1) << "Failed to set OCSP response property: "
1199 // TODO(davidben): Support OCSP stapling when NSS is the system
1200 // certificate verifier. https://crbug.com/479034.
1207 void SSLClientSocketOpenSSL::VerifyCT() {
1208 if (!cert_transparency_verifier_
)
1211 const uint8_t* ocsp_response_raw
;
1212 size_t ocsp_response_len
;
1213 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1214 std::string ocsp_response
;
1215 if (ocsp_response_len
> 0) {
1216 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1220 const uint8_t* sct_list_raw
;
1221 size_t sct_list_len
;
1222 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1223 std::string sct_list
;
1224 if (sct_list_len
> 0)
1225 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1227 // Note that this is a completely synchronous operation: The CT Log Verifier
1228 // gets all the data it needs for SCT verification and does not do any
1229 // external communication.
1230 cert_transparency_verifier_
->Verify(
1231 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1232 &ct_verify_result_
, net_log_
);
1234 if (!policy_enforcer_
) {
1235 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1237 if (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
) {
1238 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1239 SSLConfigService::GetEVCertsWhitelist();
1240 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1241 server_cert_verify_result_
.verified_cert
.get(),
1242 ev_whitelist
.get(), ct_verify_result_
, net_log_
)) {
1243 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1244 VLOG(1) << "EV certificate for "
1245 << server_cert_verify_result_
.verified_cert
->subject()
1247 << " does not conform to CT policy, removing EV status.";
1248 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1254 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1255 int rv
= DoHandshakeLoop(result
);
1256 if (rv
!= ERR_IO_PENDING
) {
1257 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1258 DoConnectCallback(rv
);
1262 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1263 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1264 // In handshake phase.
1265 OnHandshakeIOComplete(result
);
1269 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1270 // handshake is in progress.
1271 int rv_read
= ERR_IO_PENDING
;
1272 int rv_write
= ERR_IO_PENDING
;
1275 if (user_read_buf_
.get())
1276 rv_read
= DoPayloadRead();
1277 if (user_write_buf_
.get())
1278 rv_write
= DoPayloadWrite();
1279 network_moved
= DoTransportIO();
1280 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1281 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1283 // Performing the Read callback may cause |this| to be deleted. If this
1284 // happens, the Write callback should not be invoked. Guard against this by
1285 // holding a WeakPtr to |this| and ensuring it's still valid.
1286 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1287 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1288 DoReadCallback(rv_read
);
1293 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1294 DoWriteCallback(rv_write
);
1297 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1298 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1299 // In handshake phase.
1300 OnHandshakeIOComplete(result
);
1304 // Network layer received some data, check if client requested to read
1306 if (!user_read_buf_
.get())
1309 int rv
= DoReadLoop();
1310 if (rv
!= ERR_IO_PENDING
)
1314 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1315 int rv
= last_io_result
;
1317 // Default to STATE_NONE for next state.
1318 // (This is a quirk carried over from the windows
1319 // implementation. It makes reading the logs a bit harder.)
1320 // State handlers can and often do call GotoState just
1321 // to stay in the current state.
1322 State state
= next_handshake_state_
;
1323 GotoState(STATE_NONE
);
1325 case STATE_HANDSHAKE
:
1328 case STATE_CHANNEL_ID_LOOKUP
:
1330 rv
= DoChannelIDLookup();
1332 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1333 rv
= DoChannelIDLookupComplete(rv
);
1335 case STATE_VERIFY_CERT
:
1337 rv
= DoVerifyCert(rv
);
1339 case STATE_VERIFY_CERT_COMPLETE
:
1340 rv
= DoVerifyCertComplete(rv
);
1344 rv
= ERR_UNEXPECTED
;
1345 NOTREACHED() << "unexpected state" << state
;
1349 bool network_moved
= DoTransportIO();
1350 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1351 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1352 // special case we keep looping even if rv is ERR_IO_PENDING because
1353 // the transport IO may allow DoHandshake to make progress.
1354 rv
= OK
; // This causes us to stay in the loop.
1356 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1360 int SSLClientSocketOpenSSL::DoReadLoop() {
1364 rv
= DoPayloadRead();
1365 network_moved
= DoTransportIO();
1366 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1371 int SSLClientSocketOpenSSL::DoWriteLoop() {
1375 rv
= DoPayloadWrite();
1376 network_moved
= DoTransportIO();
1377 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1382 int SSLClientSocketOpenSSL::DoPayloadRead() {
1383 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1385 DCHECK_LT(0, user_read_buf_len_
);
1386 DCHECK(user_read_buf_
.get());
1389 if (pending_read_error_
!= kNoPendingReadResult
) {
1390 rv
= pending_read_error_
;
1391 pending_read_error_
= kNoPendingReadResult
;
1393 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1394 rv
, user_read_buf_
->data());
1397 NetLog::TYPE_SSL_READ_ERROR
,
1398 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1399 pending_read_error_info_
));
1401 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1402 pending_read_error_info_
= OpenSSLErrorInfo();
1406 int total_bytes_read
= 0;
1409 ssl_ret
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1410 user_read_buf_len_
- total_bytes_read
);
1412 total_bytes_read
+= ssl_ret
;
1413 } while (total_bytes_read
< user_read_buf_len_
&& ssl_ret
> 0);
1415 // Although only the final SSL_read call may have failed, the failure needs to
1416 // processed immediately, while the information still available in OpenSSL's
1418 if (client_auth_cert_needed_
) {
1419 pending_read_error_
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1420 } else if (ssl_ret
<= 0) {
1421 // A zero return from SSL_read may mean any of:
1422 // - The underlying BIO_read returned 0.
1423 // - The peer sent a close_notify.
1424 // - Any arbitrary error. https://crbug.com/466303
1426 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1427 // error, so it does not occur. The second and third are distinguished by
1428 // SSL_ERROR_ZERO_RETURN.
1429 pending_read_ssl_error_
= SSL_get_error(ssl_
, ssl_ret
);
1430 if (pending_read_ssl_error_
== SSL_ERROR_ZERO_RETURN
) {
1431 pending_read_error_
= 0;
1433 pending_read_error_
= MapOpenSSLErrorWithDetails(
1434 pending_read_ssl_error_
, err_tracer
, &pending_read_error_info_
);
1437 // Many servers do not reliably send a close_notify alert when shutting down
1438 // a connection, and instead terminate the TCP connection. This is reported
1439 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1440 // graceful EOF, instead of treating it as an error as it should be.
1441 if (pending_read_error_
== ERR_CONNECTION_CLOSED
)
1442 pending_read_error_
= 0;
1445 if (total_bytes_read
> 0) {
1446 // Return any bytes read to the caller. The error will be deferred to the
1447 // next call of DoPayloadRead.
1448 rv
= total_bytes_read
;
1450 // Do not treat insufficient data as an error to return in the next call to
1451 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1452 // again. This is because DoTransportIO() may complete in between the next
1453 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1454 // subsequent invocations to see if a complete record may now be read.
1455 if (pending_read_error_
== ERR_IO_PENDING
)
1456 pending_read_error_
= kNoPendingReadResult
;
1458 // No bytes were returned. Return the pending read error immediately.
1459 DCHECK_NE(kNoPendingReadResult
, pending_read_error_
);
1460 rv
= pending_read_error_
;
1461 pending_read_error_
= kNoPendingReadResult
;
1465 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1466 user_read_buf_
->data());
1467 } else if (rv
!= ERR_IO_PENDING
) {
1469 NetLog::TYPE_SSL_READ_ERROR
,
1470 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1471 pending_read_error_info_
));
1472 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1473 pending_read_error_info_
= OpenSSLErrorInfo();
1478 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1479 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1480 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1483 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1484 user_write_buf_
->data());
1488 int ssl_error
= SSL_get_error(ssl_
, rv
);
1489 OpenSSLErrorInfo error_info
;
1490 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1493 if (net_error
!= ERR_IO_PENDING
) {
1495 NetLog::TYPE_SSL_WRITE_ERROR
,
1496 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1501 int SSLClientSocketOpenSSL::BufferSend(void) {
1502 if (transport_send_busy_
)
1503 return ERR_IO_PENDING
;
1505 size_t buffer_read_offset
;
1508 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1509 &buffer_read_offset
, &max_read
);
1510 DCHECK_EQ(status
, 1); // Should never fail.
1512 return 0; // Nothing pending in the OpenSSL write BIO.
1513 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1514 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1515 send_buffer_
->set_offset(buffer_read_offset
);
1517 int rv
= transport_
->socket()->Write(
1518 send_buffer_
.get(), max_read
,
1519 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1520 base::Unretained(this)));
1521 if (rv
== ERR_IO_PENDING
) {
1522 transport_send_busy_
= true;
1524 TransportWriteComplete(rv
);
1529 int SSLClientSocketOpenSSL::BufferRecv(void) {
1530 if (transport_recv_busy_
)
1531 return ERR_IO_PENDING
;
1533 // Determine how much was requested from |transport_bio_| that was not
1534 // actually available.
1535 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1536 if (requested
== 0) {
1537 // This is not a perfect match of error codes, as no operation is
1538 // actually pending. However, returning 0 would be interpreted as
1539 // a possible sign of EOF, which is also an inappropriate match.
1540 return ERR_IO_PENDING
;
1543 // Known Issue: While only reading |requested| data is the more correct
1544 // implementation, it has the downside of resulting in frequent reads:
1545 // One read for the SSL record header (~5 bytes) and one read for the SSL
1546 // record body. Rather than issuing these reads to the underlying socket
1547 // (and constantly allocating new IOBuffers), a single Read() request to
1548 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1549 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1550 // traffic, this over-subscribed Read()ing will not cause issues.
1552 size_t buffer_write_offset
;
1555 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1556 &buffer_write_offset
, &max_write
);
1557 DCHECK_EQ(status
, 1); // Should never fail.
1559 return ERR_IO_PENDING
;
1562 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1563 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1565 recv_buffer_
->set_offset(buffer_write_offset
);
1566 int rv
= transport_
->socket()->Read(
1569 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1570 base::Unretained(this)));
1571 if (rv
== ERR_IO_PENDING
) {
1572 transport_recv_busy_
= true;
1574 rv
= TransportReadComplete(rv
);
1579 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1580 TransportWriteComplete(result
);
1581 OnSendComplete(result
);
1584 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1585 result
= TransportReadComplete(result
);
1586 OnRecvComplete(result
);
1589 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1590 DCHECK(ERR_IO_PENDING
!= result
);
1591 int bytes_written
= 0;
1593 // Record the error. Save it to be reported in a future read or write on
1594 // transport_bio_'s peer.
1595 transport_write_error_
= result
;
1597 bytes_written
= result
;
1599 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1600 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1602 transport_send_busy_
= false;
1605 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1606 DCHECK(ERR_IO_PENDING
!= result
);
1607 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1608 // does not report success.
1610 result
= ERR_CONNECTION_CLOSED
;
1613 DVLOG(1) << "TransportReadComplete result " << result
;
1614 // Received an error. Save it to be reported in a future read on
1615 // transport_bio_'s peer.
1616 transport_read_error_
= result
;
1618 bytes_read
= result
;
1620 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1621 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1623 transport_recv_busy_
= false;
1627 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1628 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1629 DCHECK(ssl
== ssl_
);
1631 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1633 // Clear any currently configured certificates.
1634 SSL_certs_clear(ssl_
);
1637 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1638 LOG(WARNING
) << "Client auth is not supported";
1639 #else // !defined(OS_IOS)
1640 if (!ssl_config_
.send_client_cert
) {
1641 // First pass: we know that a client certificate is needed, but we do not
1642 // have one at hand.
1643 client_auth_cert_needed_
= true;
1644 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1645 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1646 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1647 unsigned char* str
= NULL
;
1648 int length
= i2d_X509_NAME(ca_name
, &str
);
1649 cert_authorities_
.push_back(std::string(
1650 reinterpret_cast<const char*>(str
),
1651 static_cast<size_t>(length
)));
1655 const unsigned char* client_cert_types
;
1656 size_t num_client_cert_types
=
1657 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1658 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1659 cert_key_types_
.push_back(
1660 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1663 return -1; // Suspends handshake.
1666 // Second pass: a client certificate should have been selected.
1667 if (ssl_config_
.client_cert
.get()) {
1668 ScopedX509 leaf_x509
=
1669 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1671 LOG(WARNING
) << "Failed to import certificate";
1672 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1676 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1677 ssl_config_
.client_cert
->GetIntermediateCertificates());
1679 LOG(WARNING
) << "Failed to import intermediate certificates";
1680 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1684 // TODO(davidben): With Linux client auth support, this should be
1685 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1686 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1687 // net/ client auth API lacking a private key handle.
1688 #if defined(USE_OPENSSL_CERTS)
1689 crypto::ScopedEVP_PKEY privkey
=
1690 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1691 ssl_config_
.client_cert
.get());
1692 #else // !defined(USE_OPENSSL_CERTS)
1693 crypto::ScopedEVP_PKEY privkey
=
1694 FetchClientCertPrivateKey(ssl_config_
.client_cert
.get());
1695 #endif // defined(USE_OPENSSL_CERTS)
1697 // Could not find the private key. Fail the handshake and surface an
1698 // appropriate error to the caller.
1699 LOG(WARNING
) << "Client cert found without private key";
1700 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1704 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1705 !SSL_use_PrivateKey(ssl_
, privkey
.get()) ||
1706 !SSL_set1_chain(ssl_
, chain
.get())) {
1707 LOG(WARNING
) << "Failed to set client certificate";
1711 int cert_count
= 1 + sk_X509_num(chain
.get());
1712 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1713 NetLog::IntegerCallback("cert_count", cert_count
));
1716 #endif // defined(OS_IOS)
1718 // Send no client certificate.
1719 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1720 NetLog::IntegerCallback("cert_count", 0));
1724 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1725 if (!completed_connect_
) {
1726 // If the first handshake hasn't completed then we accept any certificates
1727 // because we verify after the handshake.
1731 // Disallow the server certificate to change in a renegotiation.
1732 if (server_cert_chain_
->empty()) {
1733 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1736 base::StringPiece old_der
, new_der
;
1737 if (store_ctx
->cert
== NULL
||
1738 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1739 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1740 LOG(ERROR
) << "Failed to encode certificates";
1743 if (old_der
!= new_der
) {
1744 LOG(ERROR
) << "Server certificate changed between handshakes";
1751 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1752 // server supports NPN, selects a protocol from the list that the server
1753 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1754 // callback can assume that |in| is syntactically valid.
1755 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1756 unsigned char* outlen
,
1757 const unsigned char* in
,
1758 unsigned int inlen
) {
1759 if (ssl_config_
.next_protos
.empty()) {
1760 *out
= reinterpret_cast<uint8
*>(
1761 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1762 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1763 npn_status_
= kNextProtoUnsupported
;
1764 return SSL_TLSEXT_ERR_OK
;
1767 // Assume there's no overlap between our protocols and the server's list.
1768 npn_status_
= kNextProtoNoOverlap
;
1770 // For each protocol in server preference order, see if we support it.
1771 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1772 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1773 const std::string proto
= NextProtoToString(next_proto
);
1774 if (in
[i
] == proto
.size() &&
1775 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1776 // We found a match.
1777 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1779 npn_status_
= kNextProtoNegotiated
;
1783 if (npn_status_
== kNextProtoNegotiated
)
1787 // If we didn't find a protocol, we select the first one from our list.
1788 if (npn_status_
== kNextProtoNoOverlap
) {
1789 // NextProtoToString returns a pointer to a static string.
1790 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1791 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1792 *outlen
= strlen(proto
);
1795 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1796 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1797 set_negotiation_extension(kExtensionNPN
);
1798 return SSL_TLSEXT_ERR_OK
;
1801 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1804 const char *argp
, int argi
, long argl
,
1806 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1807 // If there is no more data in the buffer, report any pending errors that
1808 // were observed. Note that both the readbuf and the writebuf are checked
1809 // for errors, since the application may have encountered a socket error
1810 // while writing that would otherwise not be reported until the application
1811 // attempted to write again - which it may never do. See
1812 // https://crbug.com/249848.
1813 if (transport_read_error_
!= OK
) {
1814 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1817 if (transport_write_error_
!= OK
) {
1818 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1821 } else if (cmd
== BIO_CB_WRITE
) {
1822 // Because of the write buffer, this reports a failure from the previous
1823 // write payload. If the current payload fails to write, the error will be
1824 // reported in a future write or read to |bio|.
1825 if (transport_write_error_
!= OK
) {
1826 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1834 long SSLClientSocketOpenSSL::BIOCallback(
1837 const char *argp
, int argi
, long argl
,
1839 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1840 BIO_get_callback_arg(bio
));
1842 return socket
->MaybeReplayTransportError(
1843 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1846 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1847 // Only cache the session once both the handshake has completed and the
1848 // certificate has been verified.
1849 if (!handshake_completed_
|| !certificate_verified_
||
1850 SSL_session_reused(ssl_
)) {
1854 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1855 SSL_get_session(ssl_
));
1858 void SSLClientSocketOpenSSL::InfoCallback(int type
, int val
) {
1859 // Note that SSL_CB_HANDSHAKE_DONE may be signaled multiple times if the
1860 // socket renegotiates.
1861 if (type
!= SSL_CB_HANDSHAKE_DONE
|| handshake_completed_
)
1864 handshake_completed_
= true;
1865 MaybeCacheSession();
1868 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
1869 for (ct::SCTList::const_iterator iter
=
1870 ct_verify_result_
.verified_scts
.begin();
1871 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
1872 ssl_info
->signed_certificate_timestamps
.push_back(
1873 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
1875 for (ct::SCTList::const_iterator iter
=
1876 ct_verify_result_
.invalid_scts
.begin();
1877 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
1878 ssl_info
->signed_certificate_timestamps
.push_back(
1879 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
1881 for (ct::SCTList::const_iterator iter
=
1882 ct_verify_result_
.unknown_logs_scts
.begin();
1883 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
1884 ssl_info
->signed_certificate_timestamps
.push_back(
1885 SignedCertificateTimestampAndStatus(*iter
,
1886 ct::SCT_STATUS_LOG_UNKNOWN
));
1890 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1891 std::string result
= host_and_port_
.ToString();
1893 result
.append(ssl_session_cache_shard_
);
1895 // Shard the session cache based on maximum protocol version. This causes
1896 // fallback connections to use a separate session cache.
1898 switch (ssl_config_
.version_max
) {
1899 case SSL_PROTOCOL_VERSION_SSL3
:
1900 result
.append("ssl3");
1902 case SSL_PROTOCOL_VERSION_TLS1
:
1903 result
.append("tls1");
1905 case SSL_PROTOCOL_VERSION_TLS1_1
:
1906 result
.append("tls1.1");
1908 case SSL_PROTOCOL_VERSION_TLS1_2
:
1909 result
.append("tls1.2");
1916 if (ssl_config_
.enable_deprecated_cipher_suites
)
1917 result
.append("deprecated");
1922 scoped_refptr
<X509Certificate
>
1923 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1924 return server_cert_
;