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.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/net_errors.h"
31 #include "net/cert/cert_policy_enforcer.h"
32 #include "net/cert/cert_verifier.h"
33 #include "net/cert/ct_ev_whitelist.h"
34 #include "net/cert/ct_verifier.h"
35 #include "net/cert/x509_certificate_net_log_param.h"
36 #include "net/cert/x509_util_openssl.h"
37 #include "net/http/transport_security_state.h"
38 #include "net/ssl/scoped_openssl_types.h"
39 #include "net/ssl/ssl_cert_request_info.h"
40 #include "net/ssl/ssl_client_session_cache_openssl.h"
41 #include "net/ssl/ssl_connection_status_flags.h"
42 #include "net/ssl/ssl_failure_state.h"
43 #include "net/ssl/ssl_info.h"
46 #include "base/win/windows_version.h"
49 #if defined(USE_OPENSSL_CERTS)
50 #include "net/ssl/openssl_client_key_store.h"
52 #include "net/ssl/openssl_platform_key.h"
59 // Enable this to see logging for state machine state transitions.
61 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
62 " jump to state " << s; \
63 next_handshake_state_ = s; } while (0)
65 #define GotoState(s) next_handshake_state_ = s
68 // This constant can be any non-negative/non-zero value (eg: it does not
69 // overlap with any value of the net::Error range, including net::OK).
70 const int kNoPendingReadResult
= 1;
72 // If a client doesn't have a list of protocols that it supports, but
73 // the server supports NPN, choosing "http/1.1" is the best answer.
74 const char kDefaultSupportedNPNProtocol
[] = "http/1.1";
76 // Default size of the internal BoringSSL buffers.
77 const int KDefaultOpenSSLBufferSize
= 17 * 1024;
79 void FreeX509Stack(STACK_OF(X509
)* ptr
) {
80 sk_X509_pop_free(ptr
, X509_free
);
83 using ScopedX509Stack
= crypto::ScopedOpenSSL
<STACK_OF(X509
), FreeX509Stack
>;
85 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
86 // This method doesn't seem to have made it into the OpenSSL headers.
87 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER
* cipher
) { return cipher
->id
; }
90 // Used for encoding the |connection_status| field of an SSLInfo object.
91 int EncodeSSLConnectionStatus(uint16 cipher_suite
,
95 ((compression
& SSL_CONNECTION_COMPRESSION_MASK
) <<
96 SSL_CONNECTION_COMPRESSION_SHIFT
) |
97 ((version
& SSL_CONNECTION_VERSION_MASK
) <<
98 SSL_CONNECTION_VERSION_SHIFT
);
101 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
102 // this SSL connection.
103 int GetNetSSLVersion(SSL
* ssl
) {
104 switch (SSL_version(ssl
)) {
106 return SSL_CONNECTION_VERSION_TLS1
;
108 return SSL_CONNECTION_VERSION_TLS1_1
;
110 return SSL_CONNECTION_VERSION_TLS1_2
;
113 return SSL_CONNECTION_VERSION_UNKNOWN
;
117 ScopedX509
OSCertHandleToOpenSSL(
118 X509Certificate::OSCertHandle os_handle
) {
119 #if defined(USE_OPENSSL_CERTS)
120 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle
));
121 #else // !defined(USE_OPENSSL_CERTS)
122 std::string der_encoded
;
123 if (!X509Certificate::GetDEREncoded(os_handle
, &der_encoded
))
125 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
126 return ScopedX509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
127 #endif // defined(USE_OPENSSL_CERTS)
130 ScopedX509Stack
OSCertHandlesToOpenSSL(
131 const X509Certificate::OSCertHandles
& os_handles
) {
132 ScopedX509Stack
stack(sk_X509_new_null());
133 for (size_t i
= 0; i
< os_handles
.size(); i
++) {
134 ScopedX509 x509
= OSCertHandleToOpenSSL(os_handles
[i
]);
136 return ScopedX509Stack();
137 sk_X509_push(stack
.get(), x509
.release());
142 int LogErrorCallback(const char* str
, size_t len
, void* context
) {
143 LOG(ERROR
) << base::StringPiece(str
, len
);
149 class SSLClientSocketOpenSSL::SSLContext
{
151 static SSLContext
* GetInstance() { return Singleton
<SSLContext
>::get(); }
152 SSL_CTX
* ssl_ctx() { return ssl_ctx_
.get(); }
153 SSLClientSessionCacheOpenSSL
* session_cache() { return &session_cache_
; }
155 SSLClientSocketOpenSSL
* GetClientSocketFromSSL(const SSL
* ssl
) {
157 SSLClientSocketOpenSSL
* socket
= static_cast<SSLClientSocketOpenSSL
*>(
158 SSL_get_ex_data(ssl
, ssl_socket_data_index_
));
163 bool SetClientSocketForSSL(SSL
* ssl
, SSLClientSocketOpenSSL
* socket
) {
164 return SSL_set_ex_data(ssl
, ssl_socket_data_index_
, socket
) != 0;
168 friend struct DefaultSingletonTraits
<SSLContext
>;
170 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
171 crypto::EnsureOpenSSLInit();
172 ssl_socket_data_index_
= SSL_get_ex_new_index(0, 0, 0, 0, 0);
173 DCHECK_NE(ssl_socket_data_index_
, -1);
174 ssl_ctx_
.reset(SSL_CTX_new(SSLv23_client_method()));
175 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
176 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
177 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
178 // This stops |SSL_shutdown| from generating the close_notify message, which
179 // is currently not sent on the network.
180 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
181 SSL_CTX_set_quiet_shutdown(ssl_ctx_
.get(), 1);
182 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
183 // It would be better if the callback were not a global setting,
184 // but that is an OpenSSL issue.
185 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
187 ssl_ctx_
->tlsext_channel_id_enabled_new
= 1;
188 SSL_CTX_set_info_callback(ssl_ctx_
.get(), InfoCallback
);
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
);
195 scoped_ptr
<base::Environment
> env(base::Environment::Create());
196 std::string ssl_keylog_file
;
197 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
198 !ssl_keylog_file
.empty()) {
199 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
200 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
202 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
203 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
205 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
210 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
211 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
213 return socket
->ClientCertRequestCallback(ssl
);
216 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
217 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
218 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
219 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
222 return socket
->CertVerifyCallback(store_ctx
);
225 static int SelectNextProtoCallback(SSL
* ssl
,
226 unsigned char** out
, unsigned char* outlen
,
227 const unsigned char* in
,
228 unsigned int inlen
, void* arg
) {
229 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
230 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
233 static void InfoCallback(const SSL
* ssl
, int type
, int val
) {
234 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
235 socket
->InfoCallback(type
, val
);
238 // This is the index used with SSL_get_ex_data to retrieve the owner
239 // SSLClientSocketOpenSSL object from an SSL instance.
240 int ssl_socket_data_index_
;
242 ScopedSSL_CTX ssl_ctx_
;
244 // TODO(davidben): Use a separate cache per URLRequestContext.
245 // https://crbug.com/458365
247 // TODO(davidben): Sessions should be invalidated on fatal
248 // alerts. https://crbug.com/466352
249 SSLClientSessionCacheOpenSSL session_cache_
;
252 // PeerCertificateChain is a helper object which extracts the certificate
253 // chain, as given by the server, from an OpenSSL socket and performs the needed
254 // resource management. The first element of the chain is the leaf certificate
255 // and the other elements are in the order given by the server.
256 class SSLClientSocketOpenSSL::PeerCertificateChain
{
258 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
259 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
260 ~PeerCertificateChain() {}
261 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
263 // Resets the PeerCertificateChain to the set of certificates in|chain|,
264 // which may be NULL, indicating to empty the store certificates.
265 // Note: If an error occurs, such as being unable to parse the certificates,
266 // this will behave as if Reset(NULL) was called.
267 void Reset(STACK_OF(X509
)* chain
);
269 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
270 scoped_refptr
<X509Certificate
> AsOSChain() const;
272 size_t size() const {
273 if (!openssl_chain_
.get())
275 return sk_X509_num(openssl_chain_
.get());
282 X509
* Get(size_t index
) const {
283 DCHECK_LT(index
, size());
284 return sk_X509_value(openssl_chain_
.get(), index
);
288 ScopedX509Stack openssl_chain_
;
291 SSLClientSocketOpenSSL::PeerCertificateChain
&
292 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
293 const PeerCertificateChain
& other
) {
297 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
301 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
302 STACK_OF(X509
)* chain
) {
303 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
306 scoped_refptr
<X509Certificate
>
307 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
308 #if defined(USE_OPENSSL_CERTS)
309 // When OSCertHandle is typedef'ed to X509, this implementation does a short
310 // cut to avoid converting back and forth between DER and the X509 struct.
311 X509Certificate::OSCertHandles intermediates
;
312 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
313 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
316 return make_scoped_refptr(X509Certificate::CreateFromHandle(
317 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
319 // DER-encode the chain and convert to a platform certificate handle.
320 std::vector
<base::StringPiece
> der_chain
;
321 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
322 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
323 base::StringPiece der
;
324 if (!x509_util::GetDER(x
, &der
))
326 der_chain
.push_back(der
);
329 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
334 void SSLClientSocket::ClearSessionCache() {
335 SSLClientSocketOpenSSL::SSLContext
* context
=
336 SSLClientSocketOpenSSL::SSLContext::GetInstance();
337 context
->session_cache()->Flush();
341 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
342 return SSL_PROTOCOL_VERSION_TLS1_2
;
345 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
346 scoped_ptr
<ClientSocketHandle
> transport_socket
,
347 const HostPortPair
& host_and_port
,
348 const SSLConfig
& ssl_config
,
349 const SSLClientSocketContext
& context
)
350 : transport_send_busy_(false),
351 transport_recv_busy_(false),
352 pending_read_error_(kNoPendingReadResult
),
353 pending_read_ssl_error_(SSL_ERROR_NONE
),
354 transport_read_error_(OK
),
355 transport_write_error_(OK
),
356 server_cert_chain_(new PeerCertificateChain(NULL
)),
357 completed_connect_(false),
358 was_ever_used_(false),
359 cert_verifier_(context
.cert_verifier
),
360 cert_transparency_verifier_(context
.cert_transparency_verifier
),
361 channel_id_service_(context
.channel_id_service
),
363 transport_bio_(NULL
),
364 transport_(transport_socket
.Pass()),
365 host_and_port_(host_and_port
),
366 ssl_config_(ssl_config
),
367 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
368 next_handshake_state_(STATE_NONE
),
369 npn_status_(kNextProtoUnsupported
),
370 channel_id_sent_(false),
371 handshake_completed_(false),
372 certificate_verified_(false),
373 ssl_failure_state_(SSL_FAILURE_NONE
),
374 transport_security_state_(context
.transport_security_state
),
375 policy_enforcer_(context
.cert_policy_enforcer
),
376 net_log_(transport_
->socket()->NetLog()),
377 weak_factory_(this) {
378 DCHECK(cert_verifier_
);
381 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
385 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
386 SSLCertRequestInfo
* cert_request_info
) {
387 cert_request_info
->host_and_port
= host_and_port_
;
388 cert_request_info
->cert_authorities
= cert_authorities_
;
389 cert_request_info
->cert_key_types
= cert_key_types_
;
392 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
393 std::string
* proto
) const {
399 SSLClientSocketOpenSSL::GetChannelIDService() const {
400 return channel_id_service_
;
403 SSLFailureState
SSLClientSocketOpenSSL::GetSSLFailureState() const {
404 return ssl_failure_state_
;
407 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
408 const base::StringPiece
& label
,
409 bool has_context
, const base::StringPiece
& context
,
410 unsigned char* out
, unsigned int outlen
) {
412 return ERR_SOCKET_NOT_CONNECTED
;
414 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
416 int rv
= SSL_export_keying_material(
417 ssl_
, out
, outlen
, label
.data(), label
.size(),
418 reinterpret_cast<const unsigned char*>(context
.data()), context
.length(),
419 has_context
? 1 : 0);
422 int ssl_error
= SSL_get_error(ssl_
, rv
);
423 LOG(ERROR
) << "Failed to export keying material;"
424 << " returned " << rv
425 << ", SSL error code " << ssl_error
;
426 return MapOpenSSLError(ssl_error
, err_tracer
);
431 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
433 return ERR_NOT_IMPLEMENTED
;
436 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
437 // It is an error to create an SSLClientSocket whose context has no
438 // TransportSecurityState.
439 DCHECK(transport_security_state_
);
441 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
443 // Set up new ssl object.
446 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
450 // Set SSL to client mode. Handshake happens in the loop below.
451 SSL_set_connect_state(ssl_
);
453 GotoState(STATE_HANDSHAKE
);
454 rv
= DoHandshakeLoop(OK
);
455 if (rv
== ERR_IO_PENDING
) {
456 user_connect_callback_
= callback
;
458 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
461 return rv
> OK
? OK
: rv
;
464 void SSLClientSocketOpenSSL::Disconnect() {
466 // Calling SSL_shutdown prevents the session from being marked as
472 if (transport_bio_
) {
473 BIO_free_all(transport_bio_
);
474 transport_bio_
= NULL
;
477 // Shut down anything that may call us back.
478 cert_verifier_request_
.reset();
479 transport_
->socket()->Disconnect();
481 // Null all callbacks, delete all buffers.
482 transport_send_busy_
= false;
484 transport_recv_busy_
= false;
487 user_connect_callback_
.Reset();
488 user_read_callback_
.Reset();
489 user_write_callback_
.Reset();
490 user_read_buf_
= NULL
;
491 user_read_buf_len_
= 0;
492 user_write_buf_
= NULL
;
493 user_write_buf_len_
= 0;
495 pending_read_error_
= kNoPendingReadResult
;
496 pending_read_ssl_error_
= SSL_ERROR_NONE
;
497 pending_read_error_info_
= OpenSSLErrorInfo();
499 transport_read_error_
= OK
;
500 transport_write_error_
= OK
;
502 server_cert_verify_result_
.Reset();
503 completed_connect_
= false;
505 cert_authorities_
.clear();
506 cert_key_types_
.clear();
508 start_cert_verification_time_
= base::TimeTicks();
510 npn_status_
= kNextProtoUnsupported
;
513 channel_id_sent_
= false;
514 handshake_completed_
= false;
515 certificate_verified_
= false;
516 channel_id_request_handle_
.Cancel();
517 ssl_failure_state_
= SSL_FAILURE_NONE
;
520 bool SSLClientSocketOpenSSL::IsConnected() const {
521 // If the handshake has not yet completed.
522 if (!completed_connect_
)
524 // If an asynchronous operation is still pending.
525 if (user_read_buf_
.get() || user_write_buf_
.get())
528 return transport_
->socket()->IsConnected();
531 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
532 // If the handshake has not yet completed.
533 if (!completed_connect_
)
535 // If an asynchronous operation is still pending.
536 if (user_read_buf_
.get() || user_write_buf_
.get())
539 // If there is data read from the network that has not yet been consumed, do
540 // not treat the connection as idle.
542 // Note that this does not check |BIO_pending|, whether there is ciphertext
543 // that has not yet been flushed to the network. |Write| returns early, so
544 // this can cause race conditions which cause a socket to not be treated
545 // reusable when it should be. See https://crbug.com/466147.
546 if (BIO_wpending(transport_bio_
) > 0)
549 return transport_
->socket()->IsConnectedAndIdle();
552 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
553 return transport_
->socket()->GetPeerAddress(addressList
);
556 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
557 return transport_
->socket()->GetLocalAddress(addressList
);
560 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
564 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
565 if (transport_
.get() && transport_
->socket()) {
566 transport_
->socket()->SetSubresourceSpeculation();
572 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
573 if (transport_
.get() && transport_
->socket()) {
574 transport_
->socket()->SetOmniboxSpeculation();
580 bool SSLClientSocketOpenSSL::WasEverUsed() const {
581 return was_ever_used_
;
584 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
585 if (transport_
.get() && transport_
->socket())
586 return transport_
->socket()->UsingTCPFastOpen();
592 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
594 if (server_cert_chain_
->empty())
597 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
598 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
599 ssl_info
->is_issued_by_known_root
=
600 server_cert_verify_result_
.is_issued_by_known_root
;
601 ssl_info
->public_key_hashes
=
602 server_cert_verify_result_
.public_key_hashes
;
603 ssl_info
->client_cert_sent
=
604 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
605 ssl_info
->channel_id_sent
= channel_id_sent_
;
606 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
608 AddSCTInfoToSSLInfo(ssl_info
);
610 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
612 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
614 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
615 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
616 GetNetSSLVersion(ssl_
));
618 if (!SSL_get_secure_renegotiation_support(ssl_
))
619 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
621 if (ssl_config_
.version_fallback
)
622 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
624 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
625 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
627 DVLOG(3) << "Encoded connection status: cipher suite = "
628 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
630 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
634 void SSLClientSocketOpenSSL::GetConnectionAttempts(
635 ConnectionAttempts
* out
) const {
639 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
641 const CompletionCallback
& callback
) {
642 user_read_buf_
= buf
;
643 user_read_buf_len_
= buf_len
;
645 int rv
= DoReadLoop();
647 if (rv
== ERR_IO_PENDING
) {
648 user_read_callback_
= callback
;
651 was_ever_used_
= true;
652 user_read_buf_
= NULL
;
653 user_read_buf_len_
= 0;
659 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
661 const CompletionCallback
& callback
) {
662 user_write_buf_
= buf
;
663 user_write_buf_len_
= buf_len
;
665 int rv
= DoWriteLoop();
667 if (rv
== ERR_IO_PENDING
) {
668 user_write_callback_
= callback
;
671 was_ever_used_
= true;
672 user_write_buf_
= NULL
;
673 user_write_buf_len_
= 0;
679 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
680 return transport_
->socket()->SetReceiveBufferSize(size
);
683 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
684 return transport_
->socket()->SetSendBufferSize(size
);
687 int SSLClientSocketOpenSSL::Init() {
689 DCHECK(!transport_bio_
);
691 SSLContext
* context
= SSLContext::GetInstance();
692 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
694 ssl_
= SSL_new(context
->ssl_ctx());
695 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
696 return ERR_UNEXPECTED
;
698 if (!SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str()))
699 return ERR_UNEXPECTED
;
701 SSL_SESSION
* session
= context
->session_cache()->Lookup(GetSessionCacheKey());
702 if (session
!= nullptr)
703 SSL_set_session(ssl_
, session
);
705 send_buffer_
= new GrowableIOBuffer();
706 send_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
707 recv_buffer_
= new GrowableIOBuffer();
708 recv_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
712 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
713 if (!BIO_new_bio_pair_external_buf(
714 &ssl_bio
, send_buffer_
->capacity(),
715 reinterpret_cast<uint8_t*>(send_buffer_
->data()), &transport_bio_
,
716 recv_buffer_
->capacity(),
717 reinterpret_cast<uint8_t*>(recv_buffer_
->data())))
718 return ERR_UNEXPECTED
;
720 DCHECK(transport_bio_
);
722 // Install a callback on OpenSSL's end to plumb transport errors through.
723 BIO_set_callback(ssl_bio
, &SSLClientSocketOpenSSL::BIOCallback
);
724 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
726 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
728 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_min
);
729 DCHECK_LT(SSL3_VERSION
, ssl_config_
.version_max
);
730 SSL_set_min_version(ssl_
, ssl_config_
.version_min
);
731 SSL_set_max_version(ssl_
, ssl_config_
.version_max
);
733 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
734 // set everything we care about to an absolute value.
735 SslSetClearMask options
;
736 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
738 // TODO(joth): Set this conditionally, see http://crbug.com/55410
739 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
741 SSL_set_options(ssl_
, options
.set_mask
);
742 SSL_clear_options(ssl_
, options
.clear_mask
);
744 // Same as above, this time for the SSL mode.
745 SslSetClearMask mode
;
747 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
748 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
750 mode
.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START
,
751 ssl_config_
.false_start_enabled
);
753 mode
.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV
, ssl_config_
.version_fallback
);
755 SSL_set_mode(ssl_
, mode
.set_mask
);
756 SSL_clear_mode(ssl_
, mode
.clear_mask
);
758 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
759 // textual name with SSL_set_cipher_list because there is no public API to
760 // directly remove a cipher by ID.
761 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
763 // See SSLConfig::disabled_cipher_suites for description of the suites
764 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
765 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
766 // as the handshake hash.
768 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
769 // Walk through all the installed ciphers, seeing if any need to be
770 // appended to the cipher removal |command|.
771 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
772 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
773 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
774 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
775 // implementation uses "effective" bits here but OpenSSL does not provide
776 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
777 // both of which are greater than 80 anyway.
778 bool disable
= SSL_CIPHER_get_bits(cipher
, NULL
) < 80;
780 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
781 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
782 ssl_config_
.disabled_cipher_suites
.end();
785 const char* name
= SSL_CIPHER_get_name(cipher
);
786 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
787 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
788 command
.append(":!");
789 command
.append(name
);
793 if (!ssl_config_
.enable_deprecated_cipher_suites
)
794 command
.append(":!RC4");
796 // Disable ECDSA cipher suites on platforms that do not support ECDSA
797 // signed certificates, as servers may use the presence of such
798 // ciphersuites as a hint to send an ECDSA certificate.
800 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
801 command
.append(":!ECDSA");
804 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
805 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
806 // This will almost certainly result in the socket failing to complete the
807 // handshake at which point the appropriate error is bubbled up to the client.
808 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
812 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
813 SSL_enable_tls_channel_id(ssl_
);
816 if (!ssl_config_
.next_protos
.empty()) {
817 // Get list of ciphers that are enabled.
818 STACK_OF(SSL_CIPHER
)* enabled_ciphers
= SSL_get_ciphers(ssl_
);
819 DCHECK(enabled_ciphers
);
820 std::vector
<uint16
> enabled_ciphers_vector
;
821 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(enabled_ciphers
); ++i
) {
822 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(enabled_ciphers
, i
);
823 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
824 enabled_ciphers_vector
.push_back(id
);
827 std::vector
<uint8_t> wire_protos
=
828 SerializeNextProtos(ssl_config_
.next_protos
,
829 HasCipherAdequateForHTTP2(enabled_ciphers_vector
) &&
830 IsTLSVersionAdequateForHTTP2(ssl_config_
));
831 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
835 if (ssl_config_
.signed_cert_timestamps_enabled
) {
836 SSL_enable_signed_cert_timestamps(ssl_
);
837 SSL_enable_ocsp_stapling(ssl_
);
840 if (cert_verifier_
->SupportsOCSPStapling())
841 SSL_enable_ocsp_stapling(ssl_
);
843 // Enable fastradio padding.
844 SSL_enable_fastradio_padding(ssl_
,
845 ssl_config_
.fastradio_padding_enabled
&&
846 ssl_config_
.fastradio_padding_eligible
);
848 // By default, renegotiations are rejected. After the initial handshake
849 // completes, some application protocols may re-enable it.
850 SSL_set_reject_peer_renegotiations(ssl_
, 1);
855 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
856 // Since Run may result in Read being called, clear |user_read_callback_|
859 was_ever_used_
= true;
860 user_read_buf_
= NULL
;
861 user_read_buf_len_
= 0;
862 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
865 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
866 // Since Run may result in Write being called, clear |user_write_callback_|
869 was_ever_used_
= true;
870 user_write_buf_
= NULL
;
871 user_write_buf_len_
= 0;
872 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
875 bool SSLClientSocketOpenSSL::DoTransportIO() {
876 bool network_moved
= false;
878 // Read and write as much data as possible. The loop is necessary because
879 // Write() may return synchronously.
882 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
883 network_moved
= true;
885 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
886 network_moved
= true;
887 return network_moved
;
890 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
891 // g_first_run_completed once crbug.com/424386 is fixed.
892 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
893 LAZY_INSTANCE_INITIALIZER
;
895 int SSLClientSocketOpenSSL::DoHandshake() {
896 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
900 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
902 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
903 rv
= SSL_do_handshake(ssl_
);
905 if (g_first_run_completed
.Get().Get()) {
906 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
908 tracked_objects::ScopedTracker
tracking_profile(
909 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
911 rv
= SSL_do_handshake(ssl_
);
913 g_first_run_completed
.Get().Set(true);
914 rv
= SSL_do_handshake(ssl_
);
920 int ssl_error
= SSL_get_error(ssl_
, rv
);
921 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
922 // The server supports channel ID. Stop to look one up before returning to
924 GotoState(STATE_CHANNEL_ID_LOOKUP
);
927 if (ssl_error
== SSL_ERROR_WANT_X509_LOOKUP
&&
928 !ssl_config_
.send_client_cert
) {
929 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
932 OpenSSLErrorInfo error_info
;
933 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
934 if (net_error
== ERR_IO_PENDING
) {
935 // If not done, stay in this state
936 GotoState(STATE_HANDSHAKE
);
937 return ERR_IO_PENDING
;
940 LOG(ERROR
) << "handshake failed; returned " << rv
<< ", SSL error code "
941 << ssl_error
<< ", net_error " << net_error
;
943 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
944 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
946 // Classify the handshake failure. This is used to determine causes of the
947 // TLS version fallback.
949 // |cipher| is the current outgoing cipher suite, so it is non-null iff
950 // ChangeCipherSpec was sent.
951 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
952 if (SSL_get_state(ssl_
) == SSL3_ST_CR_SRVR_HELLO_A
) {
953 ssl_failure_state_
= SSL_FAILURE_CLIENT_HELLO
;
954 } else if (cipher
&& (SSL_CIPHER_get_id(cipher
) ==
955 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256
||
956 SSL_CIPHER_get_id(cipher
) ==
957 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256
)) {
958 ssl_failure_state_
= SSL_FAILURE_BUGGY_GCM
;
959 } else if (cipher
&& ssl_config_
.send_client_cert
) {
960 ssl_failure_state_
= SSL_FAILURE_CLIENT_AUTH
;
961 } else if (ERR_GET_LIB(error_info
.error_code
) == ERR_LIB_SSL
&&
962 ERR_GET_REASON(error_info
.error_code
) ==
963 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED
) {
964 ssl_failure_state_
= SSL_FAILURE_SESSION_MISMATCH
;
965 } else if (cipher
&& npn_status_
!= kNextProtoUnsupported
) {
966 ssl_failure_state_
= SSL_FAILURE_NEXT_PROTO
;
968 ssl_failure_state_
= SSL_FAILURE_UNKNOWN
;
972 GotoState(STATE_HANDSHAKE_COMPLETE
);
976 int SSLClientSocketOpenSSL::DoHandshakeComplete(int result
) {
980 if (ssl_config_
.version_fallback
&&
981 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
982 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
985 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
986 if (npn_status_
== kNextProtoUnsupported
) {
987 const uint8_t* alpn_proto
= NULL
;
988 unsigned alpn_len
= 0;
989 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
991 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
992 npn_status_
= kNextProtoNegotiated
;
993 set_negotiation_extension(kExtensionALPN
);
997 RecordNegotiationExtension();
998 RecordChannelIDSupport(channel_id_service_
, channel_id_sent_
,
999 ssl_config_
.channel_id_enabled
,
1000 crypto::ECPrivateKey::IsSupported());
1002 // Only record OCSP histograms if OCSP was requested.
1003 if (ssl_config_
.signed_cert_timestamps_enabled
||
1004 cert_verifier_
->SupportsOCSPStapling()) {
1005 const uint8_t* ocsp_response
;
1006 size_t ocsp_response_len
;
1007 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
1009 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
1010 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
1013 const uint8_t* sct_list
;
1014 size_t sct_list_len
;
1015 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
1016 set_signed_cert_timestamps_received(sct_list_len
!= 0);
1018 if (IsRenegotiationAllowed())
1019 SSL_set_reject_peer_renegotiations(ssl_
, 0);
1021 // Verify the certificate.
1023 GotoState(STATE_VERIFY_CERT
);
1027 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1028 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
);
1029 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1030 return channel_id_service_
->GetOrCreateChannelID(
1031 host_and_port_
.host(),
1032 &channel_id_private_key_
,
1034 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1035 base::Unretained(this)),
1036 &channel_id_request_handle_
);
1039 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1043 DCHECK_LT(0u, channel_id_private_key_
.size());
1045 std::vector
<uint8
> encrypted_private_key_info
;
1046 std::vector
<uint8
> subject_public_key_info
;
1047 encrypted_private_key_info
.assign(
1048 channel_id_private_key_
.data(),
1049 channel_id_private_key_
.data() + channel_id_private_key_
.size());
1050 subject_public_key_info
.assign(
1051 channel_id_cert_
.data(),
1052 channel_id_cert_
.data() + channel_id_cert_
.size());
1053 scoped_ptr
<crypto::ECPrivateKey
> ec_private_key(
1054 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1055 ChannelIDService::kEPKIPassword
,
1056 encrypted_private_key_info
,
1057 subject_public_key_info
));
1058 if (!ec_private_key
) {
1059 LOG(ERROR
) << "Failed to import Channel ID.";
1060 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1063 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1065 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1066 int rv
= SSL_set1_tls_channel_id(ssl_
, ec_private_key
->key());
1068 LOG(ERROR
) << "Failed to set Channel ID.";
1069 int err
= SSL_get_error(ssl_
, rv
);
1070 return MapOpenSSLError(err
, err_tracer
);
1073 // Return to the handshake.
1074 channel_id_sent_
= true;
1075 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
);
1076 GotoState(STATE_HANDSHAKE
);
1080 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1081 DCHECK(!server_cert_chain_
->empty());
1082 DCHECK(start_cert_verification_time_
.is_null());
1084 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1086 // If the certificate is bad and has been previously accepted, use
1087 // the previous status and bypass the error.
1088 base::StringPiece der_cert
;
1089 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1091 return ERR_CERT_INVALID
;
1093 CertStatus cert_status
;
1094 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1095 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1096 server_cert_verify_result_
.Reset();
1097 server_cert_verify_result_
.cert_status
= cert_status
;
1098 server_cert_verify_result_
.verified_cert
= server_cert_
;
1102 // When running in a sandbox, it may not be possible to create an
1103 // X509Certificate*, as that may depend on OS functionality blocked
1105 if (!server_cert_
.get()) {
1106 server_cert_verify_result_
.Reset();
1107 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
1108 return ERR_CERT_INVALID
;
1111 std::string ocsp_response
;
1112 if (cert_verifier_
->SupportsOCSPStapling()) {
1113 const uint8_t* ocsp_response_raw
;
1114 size_t ocsp_response_len
;
1115 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1116 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1120 start_cert_verification_time_
= base::TimeTicks::Now();
1123 if (ssl_config_
.rev_checking_enabled
)
1124 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
1125 if (ssl_config_
.verify_ev_cert
)
1126 flags
|= CertVerifier::VERIFY_EV_CERT
;
1127 if (ssl_config_
.cert_io_enabled
)
1128 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
1129 if (ssl_config_
.rev_checking_required_local_anchors
)
1130 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
1131 return cert_verifier_
->Verify(
1132 server_cert_
.get(), host_and_port_
.host(), ocsp_response
, flags
,
1133 // TODO(davidben): Route the CRLSet through SSLConfig so
1134 // SSLClientSocket doesn't depend on SSLConfigService.
1135 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_
,
1136 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1137 base::Unretained(this)),
1138 &cert_verifier_request_
, net_log_
);
1141 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1142 cert_verifier_request_
.reset();
1144 if (!start_cert_verification_time_
.is_null()) {
1145 base::TimeDelta verify_time
=
1146 base::TimeTicks::Now() - start_cert_verification_time_
;
1148 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1150 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1155 if (SSL_session_reused(ssl_
)) {
1156 // Record whether or not the server tried to resume a session for a
1157 // different version. See https://crbug.com/441456.
1158 UMA_HISTOGRAM_BOOLEAN(
1159 "Net.SSLSessionVersionMatch",
1160 SSL_version(ssl_
) == SSL_get_session(ssl_
)->ssl_version
);
1164 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1165 if (transport_security_state_
&&
1167 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1168 !transport_security_state_
->CheckPublicKeyPins(
1169 host_and_port_
.host(),
1170 server_cert_verify_result_
.is_issued_by_known_root
,
1171 server_cert_verify_result_
.public_key_hashes
,
1172 &pinning_failure_log_
)) {
1173 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1177 // Only check Certificate Transparency if there were no other errors with
1181 DCHECK(!certificate_verified_
);
1182 certificate_verified_
= true;
1183 MaybeCacheSession();
1185 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1186 << " (" << result
<< ")";
1189 completed_connect_
= true;
1190 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1191 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1195 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1196 if (!user_connect_callback_
.is_null()) {
1197 CompletionCallback c
= user_connect_callback_
;
1198 user_connect_callback_
.Reset();
1199 c
.Run(rv
> OK
? OK
: rv
);
1203 void SSLClientSocketOpenSSL::UpdateServerCert() {
1204 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1205 server_cert_
= server_cert_chain_
->AsOSChain();
1206 if (server_cert_
.get()) {
1208 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
1209 base::Bind(&NetLogX509CertificateCallback
,
1210 base::Unretained(server_cert_
.get())));
1214 void SSLClientSocketOpenSSL::VerifyCT() {
1215 if (!cert_transparency_verifier_
)
1218 const uint8_t* ocsp_response_raw
;
1219 size_t ocsp_response_len
;
1220 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1221 std::string ocsp_response
;
1222 if (ocsp_response_len
> 0) {
1223 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1227 const uint8_t* sct_list_raw
;
1228 size_t sct_list_len
;
1229 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1230 std::string sct_list
;
1231 if (sct_list_len
> 0)
1232 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1234 // Note that this is a completely synchronous operation: The CT Log Verifier
1235 // gets all the data it needs for SCT verification and does not do any
1236 // external communication.
1237 cert_transparency_verifier_
->Verify(
1238 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1239 &ct_verify_result_
, net_log_
);
1241 if (!policy_enforcer_
) {
1242 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1244 if (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
) {
1245 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1246 SSLConfigService::GetEVCertsWhitelist();
1247 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1248 server_cert_verify_result_
.verified_cert
.get(),
1249 ev_whitelist
.get(), ct_verify_result_
, net_log_
)) {
1250 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1251 VLOG(1) << "EV certificate for "
1252 << server_cert_verify_result_
.verified_cert
->subject()
1254 << " does not conform to CT policy, removing EV status.";
1255 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1261 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1262 int rv
= DoHandshakeLoop(result
);
1263 if (rv
!= ERR_IO_PENDING
) {
1264 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1265 DoConnectCallback(rv
);
1269 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1270 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1271 // In handshake phase.
1272 OnHandshakeIOComplete(result
);
1276 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1277 // handshake is in progress.
1278 int rv_read
= ERR_IO_PENDING
;
1279 int rv_write
= ERR_IO_PENDING
;
1282 if (user_read_buf_
.get())
1283 rv_read
= DoPayloadRead();
1284 if (user_write_buf_
.get())
1285 rv_write
= DoPayloadWrite();
1286 network_moved
= DoTransportIO();
1287 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1288 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1290 // Performing the Read callback may cause |this| to be deleted. If this
1291 // happens, the Write callback should not be invoked. Guard against this by
1292 // holding a WeakPtr to |this| and ensuring it's still valid.
1293 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1294 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1295 DoReadCallback(rv_read
);
1300 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1301 DoWriteCallback(rv_write
);
1304 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1305 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1306 // In handshake phase.
1307 OnHandshakeIOComplete(result
);
1311 // Network layer received some data, check if client requested to read
1313 if (!user_read_buf_
.get())
1316 int rv
= DoReadLoop();
1317 if (rv
!= ERR_IO_PENDING
)
1321 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1322 int rv
= last_io_result
;
1324 // Default to STATE_NONE for next state.
1325 // (This is a quirk carried over from the windows
1326 // implementation. It makes reading the logs a bit harder.)
1327 // State handlers can and often do call GotoState just
1328 // to stay in the current state.
1329 State state
= next_handshake_state_
;
1330 GotoState(STATE_NONE
);
1332 case STATE_HANDSHAKE
:
1335 case STATE_HANDSHAKE_COMPLETE
:
1336 rv
= DoHandshakeComplete(rv
);
1338 case STATE_CHANNEL_ID_LOOKUP
:
1340 rv
= DoChannelIDLookup();
1342 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1343 rv
= DoChannelIDLookupComplete(rv
);
1345 case STATE_VERIFY_CERT
:
1347 rv
= DoVerifyCert(rv
);
1349 case STATE_VERIFY_CERT_COMPLETE
:
1350 rv
= DoVerifyCertComplete(rv
);
1354 rv
= ERR_UNEXPECTED
;
1355 NOTREACHED() << "unexpected state" << state
;
1359 bool network_moved
= DoTransportIO();
1360 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1361 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1362 // special case we keep looping even if rv is ERR_IO_PENDING because
1363 // the transport IO may allow DoHandshake to make progress.
1364 rv
= OK
; // This causes us to stay in the loop.
1366 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1370 int SSLClientSocketOpenSSL::DoReadLoop() {
1374 rv
= DoPayloadRead();
1375 network_moved
= DoTransportIO();
1376 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1381 int SSLClientSocketOpenSSL::DoWriteLoop() {
1385 rv
= DoPayloadWrite();
1386 network_moved
= DoTransportIO();
1387 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1392 int SSLClientSocketOpenSSL::DoPayloadRead() {
1393 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1395 DCHECK_LT(0, user_read_buf_len_
);
1396 DCHECK(user_read_buf_
.get());
1399 if (pending_read_error_
!= kNoPendingReadResult
) {
1400 rv
= pending_read_error_
;
1401 pending_read_error_
= kNoPendingReadResult
;
1403 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1404 rv
, user_read_buf_
->data());
1407 NetLog::TYPE_SSL_READ_ERROR
,
1408 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1409 pending_read_error_info_
));
1411 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1412 pending_read_error_info_
= OpenSSLErrorInfo();
1416 int total_bytes_read
= 0;
1419 ssl_ret
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1420 user_read_buf_len_
- total_bytes_read
);
1422 total_bytes_read
+= ssl_ret
;
1423 } while (total_bytes_read
< user_read_buf_len_
&& ssl_ret
> 0);
1425 // Although only the final SSL_read call may have failed, the failure needs to
1426 // processed immediately, while the information still available in OpenSSL's
1429 // A zero return from SSL_read may mean any of:
1430 // - The underlying BIO_read returned 0.
1431 // - The peer sent a close_notify.
1432 // - Any arbitrary error. https://crbug.com/466303
1434 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1435 // error, so it does not occur. The second and third are distinguished by
1436 // SSL_ERROR_ZERO_RETURN.
1437 pending_read_ssl_error_
= SSL_get_error(ssl_
, ssl_ret
);
1438 if (pending_read_ssl_error_
== SSL_ERROR_ZERO_RETURN
) {
1439 pending_read_error_
= 0;
1440 } else if (pending_read_ssl_error_
== SSL_ERROR_WANT_X509_LOOKUP
&&
1441 !ssl_config_
.send_client_cert
) {
1442 pending_read_error_
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1444 pending_read_error_
= MapOpenSSLErrorWithDetails(
1445 pending_read_ssl_error_
, err_tracer
, &pending_read_error_info_
);
1448 // Many servers do not reliably send a close_notify alert when shutting down
1449 // a connection, and instead terminate the TCP connection. This is reported
1450 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1451 // graceful EOF, instead of treating it as an error as it should be.
1452 if (pending_read_error_
== ERR_CONNECTION_CLOSED
)
1453 pending_read_error_
= 0;
1456 if (total_bytes_read
> 0) {
1457 // Return any bytes read to the caller. The error will be deferred to the
1458 // next call of DoPayloadRead.
1459 rv
= total_bytes_read
;
1461 // Do not treat insufficient data as an error to return in the next call to
1462 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1463 // again. This is because DoTransportIO() may complete in between the next
1464 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1465 // subsequent invocations to see if a complete record may now be read.
1466 if (pending_read_error_
== ERR_IO_PENDING
)
1467 pending_read_error_
= kNoPendingReadResult
;
1469 // No bytes were returned. Return the pending read error immediately.
1470 DCHECK_NE(kNoPendingReadResult
, pending_read_error_
);
1471 rv
= pending_read_error_
;
1472 pending_read_error_
= kNoPendingReadResult
;
1476 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1477 user_read_buf_
->data());
1478 } else if (rv
!= ERR_IO_PENDING
) {
1480 NetLog::TYPE_SSL_READ_ERROR
,
1481 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1482 pending_read_error_info_
));
1483 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1484 pending_read_error_info_
= OpenSSLErrorInfo();
1489 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1490 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1491 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1494 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1495 user_write_buf_
->data());
1499 int ssl_error
= SSL_get_error(ssl_
, rv
);
1500 OpenSSLErrorInfo error_info
;
1501 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1504 if (net_error
!= ERR_IO_PENDING
) {
1506 NetLog::TYPE_SSL_WRITE_ERROR
,
1507 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1512 int SSLClientSocketOpenSSL::BufferSend(void) {
1513 if (transport_send_busy_
)
1514 return ERR_IO_PENDING
;
1516 size_t buffer_read_offset
;
1519 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1520 &buffer_read_offset
, &max_read
);
1521 DCHECK_EQ(status
, 1); // Should never fail.
1523 return 0; // Nothing pending in the OpenSSL write BIO.
1524 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1525 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1526 send_buffer_
->set_offset(buffer_read_offset
);
1528 int rv
= transport_
->socket()->Write(
1529 send_buffer_
.get(), max_read
,
1530 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1531 base::Unretained(this)));
1532 if (rv
== ERR_IO_PENDING
) {
1533 transport_send_busy_
= true;
1535 TransportWriteComplete(rv
);
1540 int SSLClientSocketOpenSSL::BufferRecv(void) {
1541 if (transport_recv_busy_
)
1542 return ERR_IO_PENDING
;
1544 // Determine how much was requested from |transport_bio_| that was not
1545 // actually available.
1546 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1547 if (requested
== 0) {
1548 // This is not a perfect match of error codes, as no operation is
1549 // actually pending. However, returning 0 would be interpreted as
1550 // a possible sign of EOF, which is also an inappropriate match.
1551 return ERR_IO_PENDING
;
1554 // Known Issue: While only reading |requested| data is the more correct
1555 // implementation, it has the downside of resulting in frequent reads:
1556 // One read for the SSL record header (~5 bytes) and one read for the SSL
1557 // record body. Rather than issuing these reads to the underlying socket
1558 // (and constantly allocating new IOBuffers), a single Read() request to
1559 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1560 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1561 // traffic, this over-subscribed Read()ing will not cause issues.
1563 size_t buffer_write_offset
;
1566 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1567 &buffer_write_offset
, &max_write
);
1568 DCHECK_EQ(status
, 1); // Should never fail.
1570 return ERR_IO_PENDING
;
1573 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1574 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1576 recv_buffer_
->set_offset(buffer_write_offset
);
1577 int rv
= transport_
->socket()->Read(
1580 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1581 base::Unretained(this)));
1582 if (rv
== ERR_IO_PENDING
) {
1583 transport_recv_busy_
= true;
1585 rv
= TransportReadComplete(rv
);
1590 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1591 TransportWriteComplete(result
);
1592 OnSendComplete(result
);
1595 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1596 result
= TransportReadComplete(result
);
1597 OnRecvComplete(result
);
1600 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1601 DCHECK(ERR_IO_PENDING
!= result
);
1602 int bytes_written
= 0;
1604 // Record the error. Save it to be reported in a future read or write on
1605 // transport_bio_'s peer.
1606 transport_write_error_
= result
;
1608 bytes_written
= result
;
1610 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1611 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1613 transport_send_busy_
= false;
1616 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1617 DCHECK(ERR_IO_PENDING
!= result
);
1618 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1619 // does not report success.
1621 result
= ERR_CONNECTION_CLOSED
;
1624 DVLOG(1) << "TransportReadComplete result " << result
;
1625 // Received an error. Save it to be reported in a future read on
1626 // transport_bio_'s peer.
1627 transport_read_error_
= result
;
1629 bytes_read
= result
;
1631 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1632 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1634 transport_recv_busy_
= false;
1638 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1639 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1640 DCHECK(ssl
== ssl_
);
1642 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1644 // Clear any currently configured certificates.
1645 SSL_certs_clear(ssl_
);
1648 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1649 LOG(WARNING
) << "Client auth is not supported";
1650 #else // !defined(OS_IOS)
1651 if (!ssl_config_
.send_client_cert
) {
1652 // First pass: we know that a client certificate is needed, but we do not
1653 // have one at hand.
1654 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1655 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1656 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1657 unsigned char* str
= NULL
;
1658 int length
= i2d_X509_NAME(ca_name
, &str
);
1659 cert_authorities_
.push_back(std::string(
1660 reinterpret_cast<const char*>(str
),
1661 static_cast<size_t>(length
)));
1665 const unsigned char* client_cert_types
;
1666 size_t num_client_cert_types
=
1667 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1668 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1669 cert_key_types_
.push_back(
1670 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1673 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1677 // Second pass: a client certificate should have been selected.
1678 if (ssl_config_
.client_cert
.get()) {
1679 ScopedX509 leaf_x509
=
1680 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1682 LOG(WARNING
) << "Failed to import certificate";
1683 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1687 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1688 ssl_config_
.client_cert
->GetIntermediateCertificates());
1690 LOG(WARNING
) << "Failed to import intermediate certificates";
1691 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1695 // TODO(davidben): With Linux client auth support, this should be
1696 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1697 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1698 // net/ client auth API lacking a private key handle.
1699 #if defined(USE_OPENSSL_CERTS)
1700 crypto::ScopedEVP_PKEY privkey
=
1701 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1702 ssl_config_
.client_cert
.get());
1703 #else // !defined(USE_OPENSSL_CERTS)
1704 crypto::ScopedEVP_PKEY privkey
=
1705 FetchClientCertPrivateKey(ssl_config_
.client_cert
.get());
1706 #endif // defined(USE_OPENSSL_CERTS)
1708 // Could not find the private key. Fail the handshake and surface an
1709 // appropriate error to the caller.
1710 LOG(WARNING
) << "Client cert found without private key";
1711 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1715 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1716 !SSL_use_PrivateKey(ssl_
, privkey
.get()) ||
1717 !SSL_set1_chain(ssl_
, chain
.get())) {
1718 LOG(WARNING
) << "Failed to set client certificate";
1722 int cert_count
= 1 + sk_X509_num(chain
.get());
1723 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1724 NetLog::IntegerCallback("cert_count", cert_count
));
1727 #endif // defined(OS_IOS)
1729 // Send no client certificate.
1730 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1731 NetLog::IntegerCallback("cert_count", 0));
1735 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1736 if (!completed_connect_
) {
1737 // If the first handshake hasn't completed then we accept any certificates
1738 // because we verify after the handshake.
1742 // Disallow the server certificate to change in a renegotiation.
1743 if (server_cert_chain_
->empty()) {
1744 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1747 base::StringPiece old_der
, new_der
;
1748 if (store_ctx
->cert
== NULL
||
1749 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1750 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1751 LOG(ERROR
) << "Failed to encode certificates";
1754 if (old_der
!= new_der
) {
1755 LOG(ERROR
) << "Server certificate changed between handshakes";
1762 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1763 // server supports NPN, selects a protocol from the list that the server
1764 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1765 // callback can assume that |in| is syntactically valid.
1766 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1767 unsigned char* outlen
,
1768 const unsigned char* in
,
1769 unsigned int inlen
) {
1770 if (ssl_config_
.next_protos
.empty()) {
1771 *out
= reinterpret_cast<uint8
*>(
1772 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1773 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1774 npn_status_
= kNextProtoUnsupported
;
1775 return SSL_TLSEXT_ERR_OK
;
1778 // Assume there's no overlap between our protocols and the server's list.
1779 npn_status_
= kNextProtoNoOverlap
;
1781 // For each protocol in server preference order, see if we support it.
1782 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1783 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1784 const std::string proto
= NextProtoToString(next_proto
);
1785 if (in
[i
] == proto
.size() &&
1786 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1787 // We found a match.
1788 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1790 npn_status_
= kNextProtoNegotiated
;
1794 if (npn_status_
== kNextProtoNegotiated
)
1798 // If we didn't find a protocol, we select the first one from our list.
1799 if (npn_status_
== kNextProtoNoOverlap
) {
1800 // NextProtoToString returns a pointer to a static string.
1801 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1802 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1803 *outlen
= strlen(proto
);
1806 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1807 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1808 set_negotiation_extension(kExtensionNPN
);
1809 return SSL_TLSEXT_ERR_OK
;
1812 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1815 const char *argp
, int argi
, long argl
,
1817 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1818 // If there is no more data in the buffer, report any pending errors that
1819 // were observed. Note that both the readbuf and the writebuf are checked
1820 // for errors, since the application may have encountered a socket error
1821 // while writing that would otherwise not be reported until the application
1822 // attempted to write again - which it may never do. See
1823 // https://crbug.com/249848.
1824 if (transport_read_error_
!= OK
) {
1825 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1828 if (transport_write_error_
!= OK
) {
1829 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1832 } else if (cmd
== BIO_CB_WRITE
) {
1833 // Because of the write buffer, this reports a failure from the previous
1834 // write payload. If the current payload fails to write, the error will be
1835 // reported in a future write or read to |bio|.
1836 if (transport_write_error_
!= OK
) {
1837 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1845 long SSLClientSocketOpenSSL::BIOCallback(
1848 const char *argp
, int argi
, long argl
,
1850 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1851 BIO_get_callback_arg(bio
));
1853 return socket
->MaybeReplayTransportError(
1854 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1857 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1858 // Only cache the session once both the handshake has completed and the
1859 // certificate has been verified.
1860 if (!handshake_completed_
|| !certificate_verified_
||
1861 SSL_session_reused(ssl_
)) {
1865 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1866 SSL_get_session(ssl_
));
1869 void SSLClientSocketOpenSSL::InfoCallback(int type
, int val
) {
1870 // Note that SSL_CB_HANDSHAKE_DONE may be signaled multiple times if the
1871 // socket renegotiates.
1872 if (type
!= SSL_CB_HANDSHAKE_DONE
|| handshake_completed_
)
1875 handshake_completed_
= true;
1876 MaybeCacheSession();
1879 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
1880 for (ct::SCTList::const_iterator iter
=
1881 ct_verify_result_
.verified_scts
.begin();
1882 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
1883 ssl_info
->signed_certificate_timestamps
.push_back(
1884 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
1886 for (ct::SCTList::const_iterator iter
=
1887 ct_verify_result_
.invalid_scts
.begin();
1888 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
1889 ssl_info
->signed_certificate_timestamps
.push_back(
1890 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
1892 for (ct::SCTList::const_iterator iter
=
1893 ct_verify_result_
.unknown_logs_scts
.begin();
1894 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
1895 ssl_info
->signed_certificate_timestamps
.push_back(
1896 SignedCertificateTimestampAndStatus(*iter
,
1897 ct::SCT_STATUS_LOG_UNKNOWN
));
1901 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1902 std::string result
= host_and_port_
.ToString();
1904 result
.append(ssl_session_cache_shard_
);
1906 // Shard the session cache based on maximum protocol version. This causes
1907 // fallback connections to use a separate session cache.
1909 switch (ssl_config_
.version_max
) {
1910 case SSL_PROTOCOL_VERSION_TLS1
:
1911 result
.append("tls1");
1913 case SSL_PROTOCOL_VERSION_TLS1_1
:
1914 result
.append("tls1.1");
1916 case SSL_PROTOCOL_VERSION_TLS1_2
:
1917 result
.append("tls1.2");
1924 if (ssl_config_
.enable_deprecated_cipher_suites
)
1925 result
.append("deprecated");
1930 bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
1931 if (npn_status_
== kNextProtoUnsupported
)
1932 return ssl_config_
.renego_allowed_default
;
1934 NextProto next_proto
= NextProtoFromString(npn_proto_
);
1935 for (NextProto allowed
: ssl_config_
.renego_allowed_for_protos
) {
1936 if (next_proto
== allowed
)
1942 scoped_refptr
<X509Certificate
>
1943 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1944 return server_cert_
;