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/socket/ssl_session_cache_openssl.h"
38 #include "net/ssl/scoped_openssl_types.h"
39 #include "net/ssl/ssl_cert_request_info.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 SSLSessionCacheOpenSSL
* 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
>;
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 session_cache_
.Reset(ssl_ctx_
.get(), kDefaultSessionCacheConfig
);
190 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
191 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
192 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
193 // This stops |SSL_shutdown| from generating the close_notify message, which
194 // is currently not sent on the network.
195 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
196 SSL_CTX_set_quiet_shutdown(ssl_ctx_
.get(), 1);
197 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
198 // It would be better if the callback were not a global setting,
199 // but that is an OpenSSL issue.
200 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
202 ssl_ctx_
->tlsext_channel_id_enabled_new
= 1;
204 scoped_ptr
<base::Environment
> env(base::Environment::Create());
205 std::string ssl_keylog_file
;
206 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
207 !ssl_keylog_file
.empty()) {
208 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
209 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
211 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
212 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
214 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
219 static std::string
GetSessionCacheKey(const SSL
* ssl
) {
220 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
222 return socket
->GetSessionCacheKey();
225 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig
;
227 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
228 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
230 return socket
->ClientCertRequestCallback(ssl
);
233 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
234 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
235 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
236 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
239 return socket
->CertVerifyCallback(store_ctx
);
242 static int SelectNextProtoCallback(SSL
* ssl
,
243 unsigned char** out
, unsigned char* outlen
,
244 const unsigned char* in
,
245 unsigned int inlen
, void* arg
) {
246 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
247 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
250 // This is the index used with SSL_get_ex_data to retrieve the owner
251 // SSLClientSocketOpenSSL object from an SSL instance.
252 int ssl_socket_data_index_
;
254 ScopedSSL_CTX ssl_ctx_
;
255 // |session_cache_| must be destroyed before |ssl_ctx_|.
256 SSLSessionCacheOpenSSL session_cache_
;
259 // PeerCertificateChain is a helper object which extracts the certificate
260 // chain, as given by the server, from an OpenSSL socket and performs the needed
261 // resource management. The first element of the chain is the leaf certificate
262 // and the other elements are in the order given by the server.
263 class SSLClientSocketOpenSSL::PeerCertificateChain
{
265 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
266 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
267 ~PeerCertificateChain() {}
268 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
270 // Resets the PeerCertificateChain to the set of certificates in|chain|,
271 // which may be NULL, indicating to empty the store certificates.
272 // Note: If an error occurs, such as being unable to parse the certificates,
273 // this will behave as if Reset(NULL) was called.
274 void Reset(STACK_OF(X509
)* chain
);
276 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
277 scoped_refptr
<X509Certificate
> AsOSChain() const;
279 size_t size() const {
280 if (!openssl_chain_
.get())
282 return sk_X509_num(openssl_chain_
.get());
289 X509
* Get(size_t index
) const {
290 DCHECK_LT(index
, size());
291 return sk_X509_value(openssl_chain_
.get(), index
);
295 ScopedX509Stack openssl_chain_
;
298 SSLClientSocketOpenSSL::PeerCertificateChain
&
299 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
300 const PeerCertificateChain
& other
) {
304 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
308 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
309 STACK_OF(X509
)* chain
) {
310 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
313 scoped_refptr
<X509Certificate
>
314 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
315 #if defined(USE_OPENSSL_CERTS)
316 // When OSCertHandle is typedef'ed to X509, this implementation does a short
317 // cut to avoid converting back and forth between DER and the X509 struct.
318 X509Certificate::OSCertHandles intermediates
;
319 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
320 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
323 return make_scoped_refptr(X509Certificate::CreateFromHandle(
324 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
326 // DER-encode the chain and convert to a platform certificate handle.
327 std::vector
<base::StringPiece
> der_chain
;
328 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
329 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
330 base::StringPiece der
;
331 if (!x509_util::GetDER(x
, &der
))
333 der_chain
.push_back(der
);
336 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
341 SSLSessionCacheOpenSSL::Config
342 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig
= {
343 &GetSessionCacheKey
, // key_func
345 256, // expiration_check_count
346 60 * 60, // timeout_seconds
350 void SSLClientSocket::ClearSessionCache() {
351 SSLClientSocketOpenSSL::SSLContext
* context
=
352 SSLClientSocketOpenSSL::SSLContext::GetInstance();
353 context
->session_cache()->Flush();
357 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
358 return SSL_PROTOCOL_VERSION_TLS1_2
;
361 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
362 scoped_ptr
<ClientSocketHandle
> transport_socket
,
363 const HostPortPair
& host_and_port
,
364 const SSLConfig
& ssl_config
,
365 const SSLClientSocketContext
& context
)
366 : transport_send_busy_(false),
367 transport_recv_busy_(false),
368 pending_read_error_(kNoPendingReadResult
),
369 pending_read_ssl_error_(SSL_ERROR_NONE
),
370 transport_read_error_(OK
),
371 transport_write_error_(OK
),
372 server_cert_chain_(new PeerCertificateChain(NULL
)),
373 completed_connect_(false),
374 was_ever_used_(false),
375 client_auth_cert_needed_(false),
376 cert_verifier_(context
.cert_verifier
),
377 cert_transparency_verifier_(context
.cert_transparency_verifier
),
378 channel_id_service_(context
.channel_id_service
),
380 transport_bio_(NULL
),
381 transport_(transport_socket
.Pass()),
382 host_and_port_(host_and_port
),
383 ssl_config_(ssl_config
),
384 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
385 trying_cached_session_(false),
386 next_handshake_state_(STATE_NONE
),
387 npn_status_(kNextProtoUnsupported
),
388 channel_id_xtn_negotiated_(false),
389 transport_security_state_(context
.transport_security_state
),
390 policy_enforcer_(context
.cert_policy_enforcer
),
391 net_log_(transport_
->socket()->NetLog()),
392 weak_factory_(this) {
395 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
399 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
400 SSLCertRequestInfo
* cert_request_info
) {
401 cert_request_info
->host_and_port
= host_and_port_
;
402 cert_request_info
->cert_authorities
= cert_authorities_
;
403 cert_request_info
->cert_key_types
= cert_key_types_
;
406 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
407 std::string
* proto
) {
413 SSLClientSocketOpenSSL::GetChannelIDService() const {
414 return channel_id_service_
;
417 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
418 const base::StringPiece
& label
,
419 bool has_context
, const base::StringPiece
& context
,
420 unsigned char* out
, unsigned int outlen
) {
421 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
423 int rv
= SSL_export_keying_material(
424 ssl_
, out
, outlen
, label
.data(), label
.size(),
425 reinterpret_cast<const unsigned char*>(context
.data()), context
.length(),
426 has_context
? 1 : 0);
429 int ssl_error
= SSL_get_error(ssl_
, rv
);
430 LOG(ERROR
) << "Failed to export keying material;"
431 << " returned " << rv
432 << ", SSL error code " << ssl_error
;
433 return MapOpenSSLError(ssl_error
, err_tracer
);
438 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
440 return ERR_NOT_IMPLEMENTED
;
443 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
444 // It is an error to create an SSLClientSocket whose context has no
445 // TransportSecurityState.
446 DCHECK(transport_security_state_
);
448 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
450 // Set up new ssl object.
453 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
457 // Set SSL to client mode. Handshake happens in the loop below.
458 SSL_set_connect_state(ssl_
);
460 // Enable fastradio padding.
461 SSL_enable_fastradio_padding(ssl_
,
462 ssl_config_
.fastradio_padding_enabled
&&
463 ssl_config_
.fastradio_padding_eligible
);
465 GotoState(STATE_HANDSHAKE
);
466 rv
= DoHandshakeLoop(OK
);
467 if (rv
== ERR_IO_PENDING
) {
468 user_connect_callback_
= callback
;
470 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
473 return rv
> OK
? OK
: rv
;
476 void SSLClientSocketOpenSSL::Disconnect() {
478 // Calling SSL_shutdown prevents the session from being marked as
484 if (transport_bio_
) {
485 BIO_free_all(transport_bio_
);
486 transport_bio_
= NULL
;
489 // Shut down anything that may call us back.
491 transport_
->socket()->Disconnect();
493 // Null all callbacks, delete all buffers.
494 transport_send_busy_
= false;
496 transport_recv_busy_
= false;
499 user_connect_callback_
.Reset();
500 user_read_callback_
.Reset();
501 user_write_callback_
.Reset();
502 user_read_buf_
= NULL
;
503 user_read_buf_len_
= 0;
504 user_write_buf_
= NULL
;
505 user_write_buf_len_
= 0;
507 pending_read_error_
= kNoPendingReadResult
;
508 pending_read_ssl_error_
= SSL_ERROR_NONE
;
509 pending_read_error_info_
= OpenSSLErrorInfo();
511 transport_read_error_
= OK
;
512 transport_write_error_
= OK
;
514 server_cert_verify_result_
.Reset();
515 completed_connect_
= false;
517 cert_authorities_
.clear();
518 cert_key_types_
.clear();
519 client_auth_cert_needed_
= false;
521 start_cert_verification_time_
= base::TimeTicks();
523 npn_status_
= kNextProtoUnsupported
;
526 channel_id_xtn_negotiated_
= false;
527 channel_id_request_handle_
.Cancel();
530 bool SSLClientSocketOpenSSL::IsConnected() const {
531 // If the handshake has not yet completed.
532 if (!completed_connect_
)
534 // If an asynchronous operation is still pending.
535 if (user_read_buf_
.get() || user_write_buf_
.get())
538 return transport_
->socket()->IsConnected();
541 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
542 // If the handshake has not yet completed.
543 if (!completed_connect_
)
545 // If an asynchronous operation is still pending.
546 if (user_read_buf_
.get() || user_write_buf_
.get())
548 // If there is data waiting to be sent, or data read from the network that
549 // has not yet been consumed.
550 if (BIO_pending(transport_bio_
) > 0 ||
551 BIO_wpending(transport_bio_
) > 0) {
555 return transport_
->socket()->IsConnectedAndIdle();
558 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
559 return transport_
->socket()->GetPeerAddress(addressList
);
562 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
563 return transport_
->socket()->GetLocalAddress(addressList
);
566 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
570 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
571 if (transport_
.get() && transport_
->socket()) {
572 transport_
->socket()->SetSubresourceSpeculation();
578 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
579 if (transport_
.get() && transport_
->socket()) {
580 transport_
->socket()->SetOmniboxSpeculation();
586 bool SSLClientSocketOpenSSL::WasEverUsed() const {
587 return was_ever_used_
;
590 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
591 if (transport_
.get() && transport_
->socket())
592 return transport_
->socket()->UsingTCPFastOpen();
598 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
600 if (server_cert_chain_
->empty())
603 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
604 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
605 ssl_info
->is_issued_by_known_root
=
606 server_cert_verify_result_
.is_issued_by_known_root
;
607 ssl_info
->public_key_hashes
=
608 server_cert_verify_result_
.public_key_hashes
;
609 ssl_info
->client_cert_sent
=
610 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
611 ssl_info
->channel_id_sent
= WasChannelIDSent();
612 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
614 AddSCTInfoToSSLInfo(ssl_info
);
616 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
618 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
620 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
621 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
622 GetNetSSLVersion(ssl_
));
624 if (!SSL_get_secure_renegotiation_support(ssl_
))
625 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
627 if (ssl_config_
.version_fallback
)
628 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
630 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
631 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
633 DVLOG(3) << "Encoded connection status: cipher suite = "
634 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
636 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
640 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
642 const CompletionCallback
& callback
) {
643 user_read_buf_
= buf
;
644 user_read_buf_len_
= buf_len
;
646 int rv
= DoReadLoop();
648 if (rv
== ERR_IO_PENDING
) {
649 user_read_callback_
= callback
;
652 was_ever_used_
= true;
653 user_read_buf_
= NULL
;
654 user_read_buf_len_
= 0;
660 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
662 const CompletionCallback
& callback
) {
663 user_write_buf_
= buf
;
664 user_write_buf_len_
= buf_len
;
666 int rv
= DoWriteLoop();
668 if (rv
== ERR_IO_PENDING
) {
669 user_write_callback_
= callback
;
672 was_ever_used_
= true;
673 user_write_buf_
= NULL
;
674 user_write_buf_len_
= 0;
680 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
681 return transport_
->socket()->SetReceiveBufferSize(size
);
684 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
685 return transport_
->socket()->SetSendBufferSize(size
);
688 int SSLClientSocketOpenSSL::Init() {
690 DCHECK(!transport_bio_
);
692 SSLContext
* context
= SSLContext::GetInstance();
693 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
695 ssl_
= SSL_new(context
->ssl_ctx());
696 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
697 return ERR_UNEXPECTED
;
699 if (!SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str()))
700 return ERR_UNEXPECTED
;
702 trying_cached_session_
= context
->session_cache()->SetSSLSessionWithKey(
703 ssl_
, GetSessionCacheKey());
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 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
729 // set everything we care about to an absolute value.
730 SslSetClearMask options
;
731 options
.ConfigureFlag(SSL_OP_NO_SSLv2
, true);
732 bool ssl3_enabled
= (ssl_config_
.version_min
== SSL_PROTOCOL_VERSION_SSL3
);
733 options
.ConfigureFlag(SSL_OP_NO_SSLv3
, !ssl3_enabled
);
734 bool tls1_enabled
= (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1
&&
735 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1
);
736 options
.ConfigureFlag(SSL_OP_NO_TLSv1
, !tls1_enabled
);
737 bool tls1_1_enabled
=
738 (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1_1
&&
739 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
);
740 options
.ConfigureFlag(SSL_OP_NO_TLSv1_1
, !tls1_1_enabled
);
741 bool tls1_2_enabled
=
742 (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1_2
&&
743 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_2
);
744 options
.ConfigureFlag(SSL_OP_NO_TLSv1_2
, !tls1_2_enabled
);
746 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
748 // TODO(joth): Set this conditionally, see http://crbug.com/55410
749 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
751 SSL_set_options(ssl_
, options
.set_mask
);
752 SSL_clear_options(ssl_
, options
.clear_mask
);
754 // Same as above, this time for the SSL mode.
755 SslSetClearMask mode
;
757 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
758 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
760 mode
.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START
,
761 ssl_config_
.false_start_enabled
);
763 mode
.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV
, ssl_config_
.version_fallback
);
765 SSL_set_mode(ssl_
, mode
.set_mask
);
766 SSL_clear_mode(ssl_
, mode
.clear_mask
);
768 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
769 // textual name with SSL_set_cipher_list because there is no public API to
770 // directly remove a cipher by ID.
771 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
773 // See SSLConfig::disabled_cipher_suites for description of the suites
774 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
775 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
776 // as the handshake hash.
778 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
779 // Walk through all the installed ciphers, seeing if any need to be
780 // appended to the cipher removal |command|.
781 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
782 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
783 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
784 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
785 // implementation uses "effective" bits here but OpenSSL does not provide
786 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
787 // both of which are greater than 80 anyway.
788 bool disable
= SSL_CIPHER_get_bits(cipher
, NULL
) < 80;
790 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
791 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
792 ssl_config_
.disabled_cipher_suites
.end();
795 const char* name
= SSL_CIPHER_get_name(cipher
);
796 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
797 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
798 command
.append(":!");
799 command
.append(name
);
803 if (!ssl_config_
.enable_deprecated_cipher_suites
)
804 command
.append(":!RC4");
806 // Disable ECDSA cipher suites on platforms that do not support ECDSA
807 // signed certificates, as servers may use the presence of such
808 // ciphersuites as a hint to send an ECDSA certificate.
810 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
811 command
.append(":!ECDSA");
814 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
815 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
816 // This will almost certainly result in the socket failing to complete the
817 // handshake at which point the appropriate error is bubbled up to the client.
818 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
822 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
823 SSL_enable_tls_channel_id(ssl_
);
826 if (!ssl_config_
.next_protos
.empty()) {
827 // Get list of ciphers that are enabled.
828 STACK_OF(SSL_CIPHER
)* enabled_ciphers
= SSL_get_ciphers(ssl_
);
829 DCHECK(enabled_ciphers
);
830 std::vector
<uint16
> enabled_ciphers_vector
;
831 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(enabled_ciphers
); ++i
) {
832 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(enabled_ciphers
, i
);
833 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
834 enabled_ciphers_vector
.push_back(id
);
837 std::vector
<uint8_t> wire_protos
=
838 SerializeNextProtos(ssl_config_
.next_protos
,
839 HasCipherAdequateForHTTP2(enabled_ciphers_vector
) &&
840 IsTLSVersionAdequateForHTTP2(ssl_config_
));
841 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
845 if (ssl_config_
.signed_cert_timestamps_enabled
) {
846 SSL_enable_signed_cert_timestamps(ssl_
);
847 SSL_enable_ocsp_stapling(ssl_
);
850 if (IsOCSPStaplingSupported())
851 SSL_enable_ocsp_stapling(ssl_
);
856 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
857 // Since Run may result in Read being called, clear |user_read_callback_|
860 was_ever_used_
= true;
861 user_read_buf_
= NULL
;
862 user_read_buf_len_
= 0;
863 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
866 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
867 // Since Run may result in Write being called, clear |user_write_callback_|
870 was_ever_used_
= true;
871 user_write_buf_
= NULL
;
872 user_write_buf_len_
= 0;
873 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
876 bool SSLClientSocketOpenSSL::DoTransportIO() {
877 bool network_moved
= false;
879 // Read and write as much data as possible. The loop is necessary because
880 // Write() may return synchronously.
883 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
884 network_moved
= true;
886 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
887 network_moved
= true;
888 return network_moved
;
891 // TODO(vadimt): Remove including "base/threading/thread_local.h" and
892 // g_first_run_completed once crbug.com/424386 is fixed.
893 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
894 LAZY_INSTANCE_INITIALIZER
;
896 int SSLClientSocketOpenSSL::DoHandshake() {
897 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
902 // TODO(vadimt): Leave only 1 call to SSL_do_handshake once crbug.com/424386
904 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
905 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
906 tracked_objects::ScopedTracker
tracking_profile1(
907 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 DoHandshake_WithCert"));
909 rv
= SSL_do_handshake(ssl_
);
911 if (g_first_run_completed
.Get().Get()) {
912 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
914 tracked_objects::ScopedTracker
tracking_profile1(
915 FROM_HERE_WITH_EXPLICIT_FUNCTION(
916 "424386 DoHandshake_WithoutCert Not First"));
918 rv
= SSL_do_handshake(ssl_
);
920 g_first_run_completed
.Get().Set(true);
922 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
924 tracked_objects::ScopedTracker
tracking_profile1(
925 FROM_HERE_WITH_EXPLICIT_FUNCTION(
926 "424386 DoHandshake_WithoutCert First"));
928 rv
= SSL_do_handshake(ssl_
);
933 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
934 tracked_objects::ScopedTracker
tracking_profile3(
935 FROM_HERE_WITH_EXPLICIT_FUNCTION(
936 "424386 SSLClientSocketOpenSSL::DoHandshake3"));
938 if (trying_cached_session_
&& logging::DEBUG_MODE
) {
939 DVLOG(2) << "Result of session reuse for " << host_and_port_
.ToString()
940 << " is: " << (SSL_session_reused(ssl_
) ? "Success" : "Fail");
943 if (ssl_config_
.version_fallback
&&
944 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
945 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
948 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
949 if (npn_status_
== kNextProtoUnsupported
) {
950 const uint8_t* alpn_proto
= NULL
;
951 unsigned alpn_len
= 0;
952 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
954 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
955 npn_status_
= kNextProtoNegotiated
;
956 set_negotiation_extension(kExtensionALPN
);
960 RecordChannelIDSupport(channel_id_service_
,
961 channel_id_xtn_negotiated_
,
962 ssl_config_
.channel_id_enabled
,
963 crypto::ECPrivateKey::IsSupported());
965 // Only record OCSP histograms if OCSP was requested.
966 if (ssl_config_
.signed_cert_timestamps_enabled
||
967 IsOCSPStaplingSupported()) {
968 const uint8_t* ocsp_response
;
969 size_t ocsp_response_len
;
970 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
972 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
973 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
976 const uint8_t* sct_list
;
978 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
979 set_signed_cert_timestamps_received(sct_list_len
!= 0);
981 // Verify the certificate.
983 GotoState(STATE_VERIFY_CERT
);
985 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
986 tracked_objects::ScopedTracker
tracking_profile4(
987 FROM_HERE_WITH_EXPLICIT_FUNCTION(
988 "424386 SSLClientSocketOpenSSL::DoHandshake4"));
990 if (client_auth_cert_needed_
)
991 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
993 int ssl_error
= SSL_get_error(ssl_
, rv
);
995 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
996 // The server supports channel ID. Stop to look one up before returning to
998 channel_id_xtn_negotiated_
= true;
999 GotoState(STATE_CHANNEL_ID_LOOKUP
);
1003 OpenSSLErrorInfo error_info
;
1004 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
1006 // If not done, stay in this state
1007 if (net_error
== ERR_IO_PENDING
) {
1008 GotoState(STATE_HANDSHAKE
);
1010 LOG(ERROR
) << "handshake failed; returned " << rv
1011 << ", SSL error code " << ssl_error
1012 << ", net_error " << net_error
;
1014 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1015 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1021 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1022 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
);
1023 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1024 return channel_id_service_
->GetOrCreateChannelID(
1025 host_and_port_
.host(),
1026 &channel_id_private_key_
,
1028 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1029 base::Unretained(this)),
1030 &channel_id_request_handle_
);
1033 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1037 DCHECK_LT(0u, channel_id_private_key_
.size());
1039 std::vector
<uint8
> encrypted_private_key_info
;
1040 std::vector
<uint8
> subject_public_key_info
;
1041 encrypted_private_key_info
.assign(
1042 channel_id_private_key_
.data(),
1043 channel_id_private_key_
.data() + channel_id_private_key_
.size());
1044 subject_public_key_info
.assign(
1045 channel_id_cert_
.data(),
1046 channel_id_cert_
.data() + channel_id_cert_
.size());
1047 scoped_ptr
<crypto::ECPrivateKey
> ec_private_key(
1048 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1049 ChannelIDService::kEPKIPassword
,
1050 encrypted_private_key_info
,
1051 subject_public_key_info
));
1052 if (!ec_private_key
) {
1053 LOG(ERROR
) << "Failed to import Channel ID.";
1054 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1057 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1059 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1060 int rv
= SSL_set1_tls_channel_id(ssl_
, ec_private_key
->key());
1062 LOG(ERROR
) << "Failed to set Channel ID.";
1063 int err
= SSL_get_error(ssl_
, rv
);
1064 return MapOpenSSLError(err
, err_tracer
);
1067 // Return to the handshake.
1068 set_channel_id_sent(true);
1069 net_log_
.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
);
1070 GotoState(STATE_HANDSHAKE
);
1074 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1075 DCHECK(!server_cert_chain_
->empty());
1076 DCHECK(start_cert_verification_time_
.is_null());
1078 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1080 // If the certificate is bad and has been previously accepted, use
1081 // the previous status and bypass the error.
1082 base::StringPiece der_cert
;
1083 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1085 return ERR_CERT_INVALID
;
1087 CertStatus cert_status
;
1088 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1089 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1090 server_cert_verify_result_
.Reset();
1091 server_cert_verify_result_
.cert_status
= cert_status
;
1092 server_cert_verify_result_
.verified_cert
= server_cert_
;
1096 // When running in a sandbox, it may not be possible to create an
1097 // X509Certificate*, as that may depend on OS functionality blocked
1099 if (!server_cert_
.get()) {
1100 server_cert_verify_result_
.Reset();
1101 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
1102 return ERR_CERT_INVALID
;
1105 start_cert_verification_time_
= base::TimeTicks::Now();
1108 if (ssl_config_
.rev_checking_enabled
)
1109 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
1110 if (ssl_config_
.verify_ev_cert
)
1111 flags
|= CertVerifier::VERIFY_EV_CERT
;
1112 if (ssl_config_
.cert_io_enabled
)
1113 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
1114 if (ssl_config_
.rev_checking_required_local_anchors
)
1115 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
1116 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
1117 return verifier_
->Verify(
1119 host_and_port_
.host(),
1121 // TODO(davidben): Route the CRLSet through SSLConfig so
1122 // SSLClientSocket doesn't depend on SSLConfigService.
1123 SSLConfigService::GetCRLSet().get(),
1124 &server_cert_verify_result_
,
1125 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1126 base::Unretained(this)),
1130 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1133 if (!start_cert_verification_time_
.is_null()) {
1134 base::TimeDelta verify_time
=
1135 base::TimeTicks::Now() - start_cert_verification_time_
;
1137 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1139 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1144 if (SSL_session_reused(ssl_
)) {
1145 // Record whether or not the server tried to resume a session for a
1146 // different version. See https://crbug.com/441456.
1147 UMA_HISTOGRAM_BOOLEAN(
1148 "Net.SSLSessionVersionMatch",
1149 SSL_version(ssl_
) == SSL_get_session(ssl_
)->ssl_version
);
1153 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1154 if (transport_security_state_
&&
1156 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1157 !transport_security_state_
->CheckPublicKeyPins(
1158 host_and_port_
.host(),
1159 server_cert_verify_result_
.is_issued_by_known_root
,
1160 server_cert_verify_result_
.public_key_hashes
,
1161 &pinning_failure_log_
)) {
1162 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1166 // Only check Certificate Transparency if there were no other errors with
1170 // TODO(joth): Work out if we need to remember the intermediate CA certs
1171 // when the server sends them to us, and do so here.
1172 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_
);
1174 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1175 << " (" << result
<< ")";
1178 completed_connect_
= true;
1179 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1180 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1184 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1185 if (!user_connect_callback_
.is_null()) {
1186 CompletionCallback c
= user_connect_callback_
;
1187 user_connect_callback_
.Reset();
1188 c
.Run(rv
> OK
? OK
: rv
);
1192 void SSLClientSocketOpenSSL::UpdateServerCert() {
1193 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1194 tracked_objects::ScopedTracker
tracking_profile(
1195 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1196 "424386 SSLClientSocketOpenSSL::UpdateServerCert"));
1198 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1200 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1201 tracked_objects::ScopedTracker
tracking_profile1(
1202 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1203 "424386 SSLClientSocketOpenSSL::UpdateServerCert1"));
1204 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())));
1212 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1213 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1214 if (IsOCSPStaplingSupported()) {
1216 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
1218 tracked_objects::ScopedTracker
tracking_profile2(
1219 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1220 "424386 SSLClientSocketOpenSSL::UpdateServerCert2"));
1222 const uint8_t* ocsp_response_raw
;
1223 size_t ocsp_response_len
;
1224 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1226 CRYPT_DATA_BLOB ocsp_response_blob
;
1227 ocsp_response_blob
.cbData
= ocsp_response_len
;
1228 ocsp_response_blob
.pbData
= const_cast<BYTE
*>(ocsp_response_raw
);
1229 BOOL ok
= CertSetCertificateContextProperty(
1230 server_cert_
->os_cert_handle(),
1231 CERT_OCSP_RESPONSE_PROP_ID
,
1232 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
1233 &ocsp_response_blob
);
1235 VLOG(1) << "Failed to set OCSP response property: "
1245 void SSLClientSocketOpenSSL::VerifyCT() {
1246 if (!cert_transparency_verifier_
)
1249 const uint8_t* ocsp_response_raw
;
1250 size_t ocsp_response_len
;
1251 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1252 std::string ocsp_response
;
1253 if (ocsp_response_len
> 0) {
1254 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1258 const uint8_t* sct_list_raw
;
1259 size_t sct_list_len
;
1260 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1261 std::string sct_list
;
1262 if (sct_list_len
> 0)
1263 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1265 // Note that this is a completely synchronous operation: The CT Log Verifier
1266 // gets all the data it needs for SCT verification and does not do any
1267 // external communication.
1268 cert_transparency_verifier_
->Verify(
1269 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1270 &ct_verify_result_
, net_log_
);
1272 if (!policy_enforcer_
) {
1273 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1275 if (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
) {
1276 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1277 SSLConfigService::GetEVCertsWhitelist();
1278 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1279 server_cert_verify_result_
.verified_cert
.get(),
1280 ev_whitelist
.get(), ct_verify_result_
, net_log_
)) {
1281 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1282 VLOG(1) << "EV certificate for "
1283 << server_cert_verify_result_
.verified_cert
->subject()
1285 << " does not conform to CT policy, removing EV status.";
1286 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1292 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1293 int rv
= DoHandshakeLoop(result
);
1294 if (rv
!= ERR_IO_PENDING
) {
1295 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1296 DoConnectCallback(rv
);
1300 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1301 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1302 // In handshake phase.
1303 OnHandshakeIOComplete(result
);
1307 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1308 // handshake is in progress.
1309 int rv_read
= ERR_IO_PENDING
;
1310 int rv_write
= ERR_IO_PENDING
;
1313 if (user_read_buf_
.get())
1314 rv_read
= DoPayloadRead();
1315 if (user_write_buf_
.get())
1316 rv_write
= DoPayloadWrite();
1317 network_moved
= DoTransportIO();
1318 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1319 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1321 // Performing the Read callback may cause |this| to be deleted. If this
1322 // happens, the Write callback should not be invoked. Guard against this by
1323 // holding a WeakPtr to |this| and ensuring it's still valid.
1324 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1325 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1326 DoReadCallback(rv_read
);
1331 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1332 DoWriteCallback(rv_write
);
1335 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1336 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1337 // In handshake phase.
1338 OnHandshakeIOComplete(result
);
1342 // Network layer received some data, check if client requested to read
1344 if (!user_read_buf_
.get())
1347 int rv
= DoReadLoop();
1348 if (rv
!= ERR_IO_PENDING
)
1352 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1353 int rv
= last_io_result
;
1355 // Default to STATE_NONE for next state.
1356 // (This is a quirk carried over from the windows
1357 // implementation. It makes reading the logs a bit harder.)
1358 // State handlers can and often do call GotoState just
1359 // to stay in the current state.
1360 State state
= next_handshake_state_
;
1361 GotoState(STATE_NONE
);
1363 case STATE_HANDSHAKE
:
1366 case STATE_CHANNEL_ID_LOOKUP
:
1368 rv
= DoChannelIDLookup();
1370 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1371 rv
= DoChannelIDLookupComplete(rv
);
1373 case STATE_VERIFY_CERT
:
1375 rv
= DoVerifyCert(rv
);
1377 case STATE_VERIFY_CERT_COMPLETE
:
1378 rv
= DoVerifyCertComplete(rv
);
1382 rv
= ERR_UNEXPECTED
;
1383 NOTREACHED() << "unexpected state" << state
;
1387 bool network_moved
= DoTransportIO();
1388 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1389 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1390 // special case we keep looping even if rv is ERR_IO_PENDING because
1391 // the transport IO may allow DoHandshake to make progress.
1392 rv
= OK
; // This causes us to stay in the loop.
1394 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1398 int SSLClientSocketOpenSSL::DoReadLoop() {
1402 rv
= DoPayloadRead();
1403 network_moved
= DoTransportIO();
1404 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1409 int SSLClientSocketOpenSSL::DoWriteLoop() {
1413 rv
= DoPayloadWrite();
1414 network_moved
= DoTransportIO();
1415 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1420 int SSLClientSocketOpenSSL::DoPayloadRead() {
1421 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1423 DCHECK_LT(0, user_read_buf_len_
);
1424 DCHECK(user_read_buf_
.get());
1427 if (pending_read_error_
!= kNoPendingReadResult
) {
1428 rv
= pending_read_error_
;
1429 pending_read_error_
= kNoPendingReadResult
;
1431 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1432 rv
, user_read_buf_
->data());
1435 NetLog::TYPE_SSL_READ_ERROR
,
1436 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1437 pending_read_error_info_
));
1439 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1440 pending_read_error_info_
= OpenSSLErrorInfo();
1444 int total_bytes_read
= 0;
1447 ssl_ret
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1448 user_read_buf_len_
- total_bytes_read
);
1450 total_bytes_read
+= ssl_ret
;
1451 } while (total_bytes_read
< user_read_buf_len_
&& ssl_ret
> 0);
1453 // Although only the final SSL_read call may have failed, the failure needs to
1454 // processed immediately, while the information still available in OpenSSL's
1456 if (client_auth_cert_needed_
) {
1457 pending_read_error_
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1458 } else if (ssl_ret
<= 0) {
1459 // A zero return from SSL_read may mean any of:
1460 // - The underlying BIO_read returned 0.
1461 // - The peer sent a close_notify.
1462 // - Any arbitrary error. https://crbug.com/466303
1464 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1465 // error, so it does not occur. The second and third are distinguished by
1466 // SSL_ERROR_ZERO_RETURN.
1467 pending_read_ssl_error_
= SSL_get_error(ssl_
, ssl_ret
);
1468 if (pending_read_ssl_error_
== SSL_ERROR_ZERO_RETURN
) {
1469 pending_read_error_
= 0;
1471 pending_read_error_
= MapOpenSSLErrorWithDetails(
1472 pending_read_ssl_error_
, err_tracer
, &pending_read_error_info_
);
1475 // Many servers do not reliably send a close_notify alert when shutting down
1476 // a connection, and instead terminate the TCP connection. This is reported
1477 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1478 // graceful EOF, instead of treating it as an error as it should be.
1479 if (pending_read_error_
== ERR_CONNECTION_CLOSED
)
1480 pending_read_error_
= 0;
1483 if (total_bytes_read
> 0) {
1484 // Return any bytes read to the caller. The error will be deferred to the
1485 // next call of DoPayloadRead.
1486 rv
= total_bytes_read
;
1488 // Do not treat insufficient data as an error to return in the next call to
1489 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1490 // again. This is because DoTransportIO() may complete in between the next
1491 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1492 // subsequent invocations to see if a complete record may now be read.
1493 if (pending_read_error_
== ERR_IO_PENDING
)
1494 pending_read_error_
= kNoPendingReadResult
;
1496 // No bytes were returned. Return the pending read error immediately.
1497 DCHECK_NE(kNoPendingReadResult
, pending_read_error_
);
1498 rv
= pending_read_error_
;
1499 pending_read_error_
= kNoPendingReadResult
;
1503 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1504 user_read_buf_
->data());
1505 } else if (rv
!= ERR_IO_PENDING
) {
1507 NetLog::TYPE_SSL_READ_ERROR
,
1508 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1509 pending_read_error_info_
));
1510 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1511 pending_read_error_info_
= OpenSSLErrorInfo();
1516 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1517 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1518 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1521 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1522 user_write_buf_
->data());
1526 int ssl_error
= SSL_get_error(ssl_
, rv
);
1527 OpenSSLErrorInfo error_info
;
1528 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1531 if (net_error
!= ERR_IO_PENDING
) {
1533 NetLog::TYPE_SSL_WRITE_ERROR
,
1534 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1539 int SSLClientSocketOpenSSL::BufferSend(void) {
1540 if (transport_send_busy_
)
1541 return ERR_IO_PENDING
;
1543 size_t buffer_read_offset
;
1546 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1547 &buffer_read_offset
, &max_read
);
1548 DCHECK_EQ(status
, 1); // Should never fail.
1550 return 0; // Nothing pending in the OpenSSL write BIO.
1551 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1552 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1553 send_buffer_
->set_offset(buffer_read_offset
);
1555 int rv
= transport_
->socket()->Write(
1556 send_buffer_
.get(), max_read
,
1557 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1558 base::Unretained(this)));
1559 if (rv
== ERR_IO_PENDING
) {
1560 transport_send_busy_
= true;
1562 TransportWriteComplete(rv
);
1567 int SSLClientSocketOpenSSL::BufferRecv(void) {
1568 if (transport_recv_busy_
)
1569 return ERR_IO_PENDING
;
1571 // Determine how much was requested from |transport_bio_| that was not
1572 // actually available.
1573 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1574 if (requested
== 0) {
1575 // This is not a perfect match of error codes, as no operation is
1576 // actually pending. However, returning 0 would be interpreted as
1577 // a possible sign of EOF, which is also an inappropriate match.
1578 return ERR_IO_PENDING
;
1581 // Known Issue: While only reading |requested| data is the more correct
1582 // implementation, it has the downside of resulting in frequent reads:
1583 // One read for the SSL record header (~5 bytes) and one read for the SSL
1584 // record body. Rather than issuing these reads to the underlying socket
1585 // (and constantly allocating new IOBuffers), a single Read() request to
1586 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1587 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1588 // traffic, this over-subscribed Read()ing will not cause issues.
1590 size_t buffer_write_offset
;
1593 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1594 &buffer_write_offset
, &max_write
);
1595 DCHECK_EQ(status
, 1); // Should never fail.
1597 return ERR_IO_PENDING
;
1600 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1601 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1603 recv_buffer_
->set_offset(buffer_write_offset
);
1604 int rv
= transport_
->socket()->Read(
1607 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1608 base::Unretained(this)));
1609 if (rv
== ERR_IO_PENDING
) {
1610 transport_recv_busy_
= true;
1612 rv
= TransportReadComplete(rv
);
1617 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1618 TransportWriteComplete(result
);
1619 OnSendComplete(result
);
1622 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1623 result
= TransportReadComplete(result
);
1624 OnRecvComplete(result
);
1627 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1628 DCHECK(ERR_IO_PENDING
!= result
);
1629 int bytes_written
= 0;
1631 // Record the error. Save it to be reported in a future read or write on
1632 // transport_bio_'s peer.
1633 transport_write_error_
= result
;
1635 bytes_written
= result
;
1637 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1638 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1640 transport_send_busy_
= false;
1643 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1644 DCHECK(ERR_IO_PENDING
!= result
);
1645 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1646 // does not report success.
1648 result
= ERR_CONNECTION_CLOSED
;
1651 DVLOG(1) << "TransportReadComplete result " << result
;
1652 // Received an error. Save it to be reported in a future read on
1653 // transport_bio_'s peer.
1654 transport_read_error_
= result
;
1656 bytes_read
= result
;
1658 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1659 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1661 transport_recv_busy_
= false;
1665 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1666 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1667 tracked_objects::ScopedTracker
tracking_profile(
1668 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1669 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1671 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1672 DCHECK(ssl
== ssl_
);
1674 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1676 // Clear any currently configured certificates.
1677 SSL_certs_clear(ssl_
);
1680 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1681 LOG(WARNING
) << "Client auth is not supported";
1682 #else // !defined(OS_IOS)
1683 if (!ssl_config_
.send_client_cert
) {
1684 // First pass: we know that a client certificate is needed, but we do not
1685 // have one at hand.
1686 client_auth_cert_needed_
= true;
1687 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1688 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1689 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1690 unsigned char* str
= NULL
;
1691 int length
= i2d_X509_NAME(ca_name
, &str
);
1692 cert_authorities_
.push_back(std::string(
1693 reinterpret_cast<const char*>(str
),
1694 static_cast<size_t>(length
)));
1698 const unsigned char* client_cert_types
;
1699 size_t num_client_cert_types
=
1700 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1701 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1702 cert_key_types_
.push_back(
1703 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1706 return -1; // Suspends handshake.
1709 // Second pass: a client certificate should have been selected.
1710 if (ssl_config_
.client_cert
.get()) {
1711 ScopedX509 leaf_x509
=
1712 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1714 LOG(WARNING
) << "Failed to import certificate";
1715 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1719 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1720 ssl_config_
.client_cert
->GetIntermediateCertificates());
1722 LOG(WARNING
) << "Failed to import intermediate certificates";
1723 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1727 // TODO(davidben): With Linux client auth support, this should be
1728 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1729 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1730 // net/ client auth API lacking a private key handle.
1731 #if defined(USE_OPENSSL_CERTS)
1732 crypto::ScopedEVP_PKEY privkey
=
1733 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1734 ssl_config_
.client_cert
.get());
1735 #else // !defined(USE_OPENSSL_CERTS)
1736 crypto::ScopedEVP_PKEY privkey
=
1737 FetchClientCertPrivateKey(ssl_config_
.client_cert
.get());
1738 #endif // defined(USE_OPENSSL_CERTS)
1740 // Could not find the private key. Fail the handshake and surface an
1741 // appropriate error to the caller.
1742 LOG(WARNING
) << "Client cert found without private key";
1743 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1747 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1748 !SSL_use_PrivateKey(ssl_
, privkey
.get()) ||
1749 !SSL_set1_chain(ssl_
, chain
.get())) {
1750 LOG(WARNING
) << "Failed to set client certificate";
1754 int cert_count
= 1 + sk_X509_num(chain
.get());
1755 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1756 NetLog::IntegerCallback("cert_count", cert_count
));
1759 #endif // defined(OS_IOS)
1761 // Send no client certificate.
1762 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1763 NetLog::IntegerCallback("cert_count", 0));
1767 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1768 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1769 tracked_objects::ScopedTracker
tracking_profile(
1770 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1771 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1773 if (!completed_connect_
) {
1774 // If the first handshake hasn't completed then we accept any certificates
1775 // because we verify after the handshake.
1779 // Disallow the server certificate to change in a renegotiation.
1780 if (server_cert_chain_
->empty()) {
1781 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1784 base::StringPiece old_der
, new_der
;
1785 if (store_ctx
->cert
== NULL
||
1786 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1787 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1788 LOG(ERROR
) << "Failed to encode certificates";
1791 if (old_der
!= new_der
) {
1792 LOG(ERROR
) << "Server certificate changed between handshakes";
1799 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1800 // server supports NPN, selects a protocol from the list that the server
1801 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1802 // callback can assume that |in| is syntactically valid.
1803 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1804 unsigned char* outlen
,
1805 const unsigned char* in
,
1806 unsigned int inlen
) {
1807 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1808 tracked_objects::ScopedTracker
tracking_profile(
1809 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1810 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1812 if (ssl_config_
.next_protos
.empty()) {
1813 *out
= reinterpret_cast<uint8
*>(
1814 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1815 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1816 npn_status_
= kNextProtoUnsupported
;
1817 return SSL_TLSEXT_ERR_OK
;
1820 // Assume there's no overlap between our protocols and the server's list.
1821 npn_status_
= kNextProtoNoOverlap
;
1823 // For each protocol in server preference order, see if we support it.
1824 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1825 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1826 const std::string proto
= NextProtoToString(next_proto
);
1827 if (in
[i
] == proto
.size() &&
1828 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1829 // We found a match.
1830 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1832 npn_status_
= kNextProtoNegotiated
;
1836 if (npn_status_
== kNextProtoNegotiated
)
1840 // If we didn't find a protocol, we select the first one from our list.
1841 if (npn_status_
== kNextProtoNoOverlap
) {
1842 // NextProtoToString returns a pointer to a static string.
1843 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1844 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1845 *outlen
= strlen(proto
);
1848 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1849 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1850 set_negotiation_extension(kExtensionNPN
);
1851 return SSL_TLSEXT_ERR_OK
;
1854 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1857 const char *argp
, int argi
, long argl
,
1859 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1860 // If there is no more data in the buffer, report any pending errors that
1861 // were observed. Note that both the readbuf and the writebuf are checked
1862 // for errors, since the application may have encountered a socket error
1863 // while writing that would otherwise not be reported until the application
1864 // attempted to write again - which it may never do. See
1865 // https://crbug.com/249848.
1866 if (transport_read_error_
!= OK
) {
1867 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1870 if (transport_write_error_
!= OK
) {
1871 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1874 } else if (cmd
== BIO_CB_WRITE
) {
1875 // Because of the write buffer, this reports a failure from the previous
1876 // write payload. If the current payload fails to write, the error will be
1877 // reported in a future write or read to |bio|.
1878 if (transport_write_error_
!= OK
) {
1879 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1887 long SSLClientSocketOpenSSL::BIOCallback(
1890 const char *argp
, int argi
, long argl
,
1892 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1893 tracked_objects::ScopedTracker
tracking_profile(
1894 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1895 "424386 SSLClientSocketOpenSSL::BIOCallback"));
1897 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1898 BIO_get_callback_arg(bio
));
1900 return socket
->MaybeReplayTransportError(
1901 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1904 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
1905 for (ct::SCTList::const_iterator iter
=
1906 ct_verify_result_
.verified_scts
.begin();
1907 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
1908 ssl_info
->signed_certificate_timestamps
.push_back(
1909 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
1911 for (ct::SCTList::const_iterator iter
=
1912 ct_verify_result_
.invalid_scts
.begin();
1913 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
1914 ssl_info
->signed_certificate_timestamps
.push_back(
1915 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
1917 for (ct::SCTList::const_iterator iter
=
1918 ct_verify_result_
.unknown_logs_scts
.begin();
1919 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
1920 ssl_info
->signed_certificate_timestamps
.push_back(
1921 SignedCertificateTimestampAndStatus(*iter
,
1922 ct::SCT_STATUS_LOG_UNKNOWN
));
1926 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1927 std::string result
= host_and_port_
.ToString();
1929 result
.append(ssl_session_cache_shard_
);
1931 // Shard the session cache based on maximum protocol version. This causes
1932 // fallback connections to use a separate session cache.
1934 switch (ssl_config_
.version_max
) {
1935 case SSL_PROTOCOL_VERSION_SSL3
:
1936 result
.append("ssl3");
1938 case SSL_PROTOCOL_VERSION_TLS1
:
1939 result
.append("tls1");
1941 case SSL_PROTOCOL_VERSION_TLS1_1
:
1942 result
.append("tls1.1");
1944 case SSL_PROTOCOL_VERSION_TLS1_2
:
1945 result
.append("tls1.2");
1952 if (ssl_config_
.enable_deprecated_cipher_suites
)
1953 result
.append("deprecated");
1958 scoped_refptr
<X509Certificate
>
1959 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1960 return server_cert_
;