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/metrics/sparse_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 "crypto/ec_private_key.h"
27 #include "crypto/openssl_util.h"
28 #include "crypto/scoped_openssl_types.h"
29 #include "net/base/net_errors.h"
30 #include "net/cert/cert_policy_enforcer.h"
31 #include "net/cert/cert_verifier.h"
32 #include "net/cert/ct_ev_whitelist.h"
33 #include "net/cert/ct_verifier.h"
34 #include "net/cert/single_request_cert_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/socket/ssl_session_cache_openssl.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 typedef crypto::ScopedOpenSSL
<X509
, X509_free
>::Type ScopedX509
;
82 typedef crypto::ScopedOpenSSL
<STACK_OF(X509
), FreeX509Stack
>::Type
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_SSL2
;
108 return SSL_CONNECTION_VERSION_SSL3
;
110 return SSL_CONNECTION_VERSION_TLS1
;
112 return SSL_CONNECTION_VERSION_TLS1_1
;
114 return SSL_CONNECTION_VERSION_TLS1_2
;
116 return SSL_CONNECTION_VERSION_UNKNOWN
;
120 ScopedX509
OSCertHandleToOpenSSL(
121 X509Certificate::OSCertHandle os_handle
) {
122 #if defined(USE_OPENSSL_CERTS)
123 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle
));
124 #else // !defined(USE_OPENSSL_CERTS)
125 std::string der_encoded
;
126 if (!X509Certificate::GetDEREncoded(os_handle
, &der_encoded
))
128 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
129 return ScopedX509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
130 #endif // defined(USE_OPENSSL_CERTS)
133 ScopedX509Stack
OSCertHandlesToOpenSSL(
134 const X509Certificate::OSCertHandles
& os_handles
) {
135 ScopedX509Stack
stack(sk_X509_new_null());
136 for (size_t i
= 0; i
< os_handles
.size(); i
++) {
137 ScopedX509 x509
= OSCertHandleToOpenSSL(os_handles
[i
]);
139 return ScopedX509Stack();
140 sk_X509_push(stack
.get(), x509
.release());
145 int LogErrorCallback(const char* str
, size_t len
, void* context
) {
146 LOG(ERROR
) << base::StringPiece(str
, len
);
150 bool IsOCSPStaplingSupported() {
152 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
153 // set on Windows XP without error. There is some overhead from the server
154 // sending the OCSP response if it supports the extension, for the subset of
155 // XP clients who will request it but be unable to use it, but this is an
156 // acceptable trade-off for simplicity of implementation.
165 class SSLClientSocketOpenSSL::SSLContext
{
167 static SSLContext
* GetInstance() { return Singleton
<SSLContext
>::get(); }
168 SSL_CTX
* ssl_ctx() { return ssl_ctx_
.get(); }
169 SSLSessionCacheOpenSSL
* session_cache() { return &session_cache_
; }
171 SSLClientSocketOpenSSL
* GetClientSocketFromSSL(const SSL
* ssl
) {
173 SSLClientSocketOpenSSL
* socket
= static_cast<SSLClientSocketOpenSSL
*>(
174 SSL_get_ex_data(ssl
, ssl_socket_data_index_
));
179 bool SetClientSocketForSSL(SSL
* ssl
, SSLClientSocketOpenSSL
* socket
) {
180 return SSL_set_ex_data(ssl
, ssl_socket_data_index_
, socket
) != 0;
184 friend struct DefaultSingletonTraits
<SSLContext
>;
187 crypto::EnsureOpenSSLInit();
188 ssl_socket_data_index_
= SSL_get_ex_new_index(0, 0, 0, 0, 0);
189 DCHECK_NE(ssl_socket_data_index_
, -1);
190 ssl_ctx_
.reset(SSL_CTX_new(SSLv23_client_method()));
191 session_cache_
.Reset(ssl_ctx_
.get(), kDefaultSessionCacheConfig
);
192 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
193 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
194 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
195 // This stops |SSL_shutdown| from generating the close_notify message, which
196 // is currently not sent on the network.
197 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
198 SSL_CTX_set_quiet_shutdown(ssl_ctx_
.get(), 1);
199 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
200 // It would be better if the callback were not a global setting,
201 // but that is an OpenSSL issue.
202 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
204 ssl_ctx_
->tlsext_channel_id_enabled_new
= 1;
206 scoped_ptr
<base::Environment
> env(base::Environment::Create());
207 std::string ssl_keylog_file
;
208 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
209 !ssl_keylog_file
.empty()) {
210 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
211 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
213 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
214 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
216 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
221 static std::string
GetSessionCacheKey(const SSL
* ssl
) {
222 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
224 return socket
->GetSessionCacheKey();
227 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig
;
229 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
230 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
232 return socket
->ClientCertRequestCallback(ssl
);
235 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
236 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
237 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
238 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
241 return socket
->CertVerifyCallback(store_ctx
);
244 static int SelectNextProtoCallback(SSL
* ssl
,
245 unsigned char** out
, unsigned char* outlen
,
246 const unsigned char* in
,
247 unsigned int inlen
, void* arg
) {
248 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
249 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
252 // This is the index used with SSL_get_ex_data to retrieve the owner
253 // SSLClientSocketOpenSSL object from an SSL instance.
254 int ssl_socket_data_index_
;
256 crypto::ScopedOpenSSL
<SSL_CTX
, SSL_CTX_free
>::Type ssl_ctx_
;
257 // |session_cache_| must be destroyed before |ssl_ctx_|.
258 SSLSessionCacheOpenSSL session_cache_
;
261 // PeerCertificateChain is a helper object which extracts the certificate
262 // chain, as given by the server, from an OpenSSL socket and performs the needed
263 // resource management. The first element of the chain is the leaf certificate
264 // and the other elements are in the order given by the server.
265 class SSLClientSocketOpenSSL::PeerCertificateChain
{
267 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
268 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
269 ~PeerCertificateChain() {}
270 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
272 // Resets the PeerCertificateChain to the set of certificates in|chain|,
273 // which may be NULL, indicating to empty the store certificates.
274 // Note: If an error occurs, such as being unable to parse the certificates,
275 // this will behave as if Reset(NULL) was called.
276 void Reset(STACK_OF(X509
)* chain
);
278 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
279 scoped_refptr
<X509Certificate
> AsOSChain() const;
281 size_t size() const {
282 if (!openssl_chain_
.get())
284 return sk_X509_num(openssl_chain_
.get());
291 X509
* Get(size_t index
) const {
292 DCHECK_LT(index
, size());
293 return sk_X509_value(openssl_chain_
.get(), index
);
297 ScopedX509Stack openssl_chain_
;
300 SSLClientSocketOpenSSL::PeerCertificateChain
&
301 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
302 const PeerCertificateChain
& other
) {
306 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
310 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
311 STACK_OF(X509
)* chain
) {
312 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
315 scoped_refptr
<X509Certificate
>
316 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
317 #if defined(USE_OPENSSL_CERTS)
318 // When OSCertHandle is typedef'ed to X509, this implementation does a short
319 // cut to avoid converting back and forth between DER and the X509 struct.
320 X509Certificate::OSCertHandles intermediates
;
321 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
322 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
325 return make_scoped_refptr(X509Certificate::CreateFromHandle(
326 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
328 // DER-encode the chain and convert to a platform certificate handle.
329 std::vector
<base::StringPiece
> der_chain
;
330 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
331 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
332 base::StringPiece der
;
333 if (!x509_util::GetDER(x
, &der
))
335 der_chain
.push_back(der
);
338 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
343 SSLSessionCacheOpenSSL::Config
344 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig
= {
345 &GetSessionCacheKey
, // key_func
347 256, // expiration_check_count
348 60 * 60, // timeout_seconds
352 void SSLClientSocket::ClearSessionCache() {
353 SSLClientSocketOpenSSL::SSLContext
* context
=
354 SSLClientSocketOpenSSL::SSLContext::GetInstance();
355 context
->session_cache()->Flush();
359 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
360 return SSL_PROTOCOL_VERSION_TLS1_2
;
363 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
364 scoped_ptr
<ClientSocketHandle
> transport_socket
,
365 const HostPortPair
& host_and_port
,
366 const SSLConfig
& ssl_config
,
367 const SSLClientSocketContext
& context
)
368 : transport_send_busy_(false),
369 transport_recv_busy_(false),
370 pending_read_error_(kNoPendingReadResult
),
371 pending_read_ssl_error_(SSL_ERROR_NONE
),
372 transport_read_error_(OK
),
373 transport_write_error_(OK
),
374 server_cert_chain_(new PeerCertificateChain(NULL
)),
375 completed_connect_(false),
376 was_ever_used_(false),
377 client_auth_cert_needed_(false),
378 cert_verifier_(context
.cert_verifier
),
379 cert_transparency_verifier_(context
.cert_transparency_verifier
),
380 channel_id_service_(context
.channel_id_service
),
382 transport_bio_(NULL
),
383 transport_(transport_socket
.Pass()),
384 host_and_port_(host_and_port
),
385 ssl_config_(ssl_config
),
386 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
387 trying_cached_session_(false),
388 next_handshake_state_(STATE_NONE
),
389 npn_status_(kNextProtoUnsupported
),
390 channel_id_xtn_negotiated_(false),
391 handshake_succeeded_(false),
392 marked_session_as_good_(false),
393 transport_security_state_(context
.transport_security_state
),
394 policy_enforcer_(context
.cert_policy_enforcer
),
395 net_log_(transport_
->socket()->NetLog()),
396 weak_factory_(this) {
399 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
403 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
404 std::string result
= host_and_port_
.ToString();
406 result
.append(ssl_session_cache_shard_
);
410 bool SSLClientSocketOpenSSL::InSessionCache() const {
411 SSLContext
* context
= SSLContext::GetInstance();
412 std::string cache_key
= GetSessionCacheKey();
413 return context
->session_cache()->SSLSessionIsInCache(cache_key
);
416 void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
417 const base::Closure
& callback
) {
418 handshake_completion_callback_
= callback
;
421 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
422 SSLCertRequestInfo
* cert_request_info
) {
423 cert_request_info
->host_and_port
= host_and_port_
;
424 cert_request_info
->cert_authorities
= cert_authorities_
;
425 cert_request_info
->cert_key_types
= cert_key_types_
;
428 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
429 std::string
* proto
) {
435 SSLClientSocketOpenSSL::GetChannelIDService() const {
436 return channel_id_service_
;
439 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
440 const base::StringPiece
& label
,
441 bool has_context
, const base::StringPiece
& context
,
442 unsigned char* out
, unsigned int outlen
) {
443 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
445 int rv
= SSL_export_keying_material(
446 ssl_
, out
, outlen
, label
.data(), label
.size(),
447 reinterpret_cast<const unsigned char*>(context
.data()),
448 context
.length(), context
.length() > 0);
451 int ssl_error
= SSL_get_error(ssl_
, rv
);
452 LOG(ERROR
) << "Failed to export keying material;"
453 << " returned " << rv
454 << ", SSL error code " << ssl_error
;
455 return MapOpenSSLError(ssl_error
, err_tracer
);
460 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
462 return ERR_NOT_IMPLEMENTED
;
465 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
466 // It is an error to create an SSLClientSocket whose context has no
467 // TransportSecurityState.
468 DCHECK(transport_security_state_
);
470 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
472 // Set up new ssl object.
475 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
476 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.SSL_Connection_Error", std::abs(rv
));
480 // Set SSL to client mode. Handshake happens in the loop below.
481 SSL_set_connect_state(ssl_
);
483 GotoState(STATE_HANDSHAKE
);
484 rv
= DoHandshakeLoop(OK
);
485 if (rv
== ERR_IO_PENDING
) {
486 user_connect_callback_
= callback
;
488 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
489 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.SSL_Connection_Error", std::abs(rv
));
491 OnHandshakeCompletion();
494 return rv
> OK
? OK
: rv
;
497 void SSLClientSocketOpenSSL::Disconnect() {
498 // If a handshake was pending (Connect() had been called), notify interested
499 // parties that it's been aborted now. If the handshake had already
500 // completed, this is a no-op.
501 OnHandshakeCompletion();
503 // Calling SSL_shutdown prevents the session from being marked as
509 if (transport_bio_
) {
510 BIO_free_all(transport_bio_
);
511 transport_bio_
= NULL
;
514 // Shut down anything that may call us back.
516 transport_
->socket()->Disconnect();
518 // Null all callbacks, delete all buffers.
519 transport_send_busy_
= false;
521 transport_recv_busy_
= false;
524 user_connect_callback_
.Reset();
525 user_read_callback_
.Reset();
526 user_write_callback_
.Reset();
527 user_read_buf_
= NULL
;
528 user_read_buf_len_
= 0;
529 user_write_buf_
= NULL
;
530 user_write_buf_len_
= 0;
532 pending_read_error_
= kNoPendingReadResult
;
533 pending_read_ssl_error_
= SSL_ERROR_NONE
;
534 pending_read_error_info_
= OpenSSLErrorInfo();
536 transport_read_error_
= OK
;
537 transport_write_error_
= OK
;
539 server_cert_verify_result_
.Reset();
540 completed_connect_
= false;
542 cert_authorities_
.clear();
543 cert_key_types_
.clear();
544 client_auth_cert_needed_
= false;
546 start_cert_verification_time_
= base::TimeTicks();
548 npn_status_
= kNextProtoUnsupported
;
551 channel_id_xtn_negotiated_
= false;
552 channel_id_request_handle_
.Cancel();
555 bool SSLClientSocketOpenSSL::IsConnected() const {
556 // If the handshake has not yet completed.
557 if (!completed_connect_
)
559 // If an asynchronous operation is still pending.
560 if (user_read_buf_
.get() || user_write_buf_
.get())
563 return transport_
->socket()->IsConnected();
566 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
567 // If the handshake has not yet completed.
568 if (!completed_connect_
)
570 // If an asynchronous operation is still pending.
571 if (user_read_buf_
.get() || user_write_buf_
.get())
573 // If there is data waiting to be sent, or data read from the network that
574 // has not yet been consumed.
575 if (BIO_pending(transport_bio_
) > 0 ||
576 BIO_wpending(transport_bio_
) > 0) {
580 return transport_
->socket()->IsConnectedAndIdle();
583 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
584 return transport_
->socket()->GetPeerAddress(addressList
);
587 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
588 return transport_
->socket()->GetLocalAddress(addressList
);
591 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
595 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
596 if (transport_
.get() && transport_
->socket()) {
597 transport_
->socket()->SetSubresourceSpeculation();
603 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
604 if (transport_
.get() && transport_
->socket()) {
605 transport_
->socket()->SetOmniboxSpeculation();
611 bool SSLClientSocketOpenSSL::WasEverUsed() const {
612 return was_ever_used_
;
615 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
616 if (transport_
.get() && transport_
->socket())
617 return transport_
->socket()->UsingTCPFastOpen();
623 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
625 if (server_cert_chain_
->empty())
628 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
629 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
630 ssl_info
->is_issued_by_known_root
=
631 server_cert_verify_result_
.is_issued_by_known_root
;
632 ssl_info
->public_key_hashes
=
633 server_cert_verify_result_
.public_key_hashes
;
634 ssl_info
->client_cert_sent
=
635 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
636 ssl_info
->channel_id_sent
= WasChannelIDSent();
637 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
639 AddSCTInfoToSSLInfo(ssl_info
);
641 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
643 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
645 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
646 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
647 GetNetSSLVersion(ssl_
));
649 if (!SSL_get_secure_renegotiation_support(ssl_
))
650 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
652 if (ssl_config_
.version_fallback
)
653 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
655 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
656 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
658 DVLOG(3) << "Encoded connection status: cipher suite = "
659 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
661 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
665 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
667 const CompletionCallback
& callback
) {
668 user_read_buf_
= buf
;
669 user_read_buf_len_
= buf_len
;
671 int rv
= DoReadLoop();
673 if (rv
== ERR_IO_PENDING
) {
674 user_read_callback_
= callback
;
677 was_ever_used_
= true;
678 user_read_buf_
= NULL
;
679 user_read_buf_len_
= 0;
681 // Failure of a read attempt may indicate a failed false start
683 OnHandshakeCompletion();
690 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
692 const CompletionCallback
& callback
) {
693 user_write_buf_
= buf
;
694 user_write_buf_len_
= buf_len
;
696 int rv
= DoWriteLoop();
698 if (rv
== ERR_IO_PENDING
) {
699 user_write_callback_
= callback
;
702 was_ever_used_
= true;
703 user_write_buf_
= NULL
;
704 user_write_buf_len_
= 0;
706 // Failure of a write attempt may indicate a failed false start
708 OnHandshakeCompletion();
715 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
716 return transport_
->socket()->SetReceiveBufferSize(size
);
719 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
720 return transport_
->socket()->SetSendBufferSize(size
);
723 int SSLClientSocketOpenSSL::Init() {
725 DCHECK(!transport_bio_
);
727 SSLContext
* context
= SSLContext::GetInstance();
728 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
730 ssl_
= SSL_new(context
->ssl_ctx());
731 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
732 return ERR_UNEXPECTED
;
734 if (!SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str()))
735 return ERR_UNEXPECTED
;
737 // Set an OpenSSL callback to monitor this SSL*'s connection.
738 SSL_set_info_callback(ssl_
, &InfoCallback
);
740 trying_cached_session_
= context
->session_cache()->SetSSLSessionWithKey(
741 ssl_
, GetSessionCacheKey());
743 send_buffer_
= new GrowableIOBuffer();
744 send_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
745 recv_buffer_
= new GrowableIOBuffer();
746 recv_buffer_
->SetCapacity(KDefaultOpenSSLBufferSize
);
750 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
751 if (!BIO_new_bio_pair_external_buf(
752 &ssl_bio
, send_buffer_
->capacity(),
753 reinterpret_cast<uint8_t*>(send_buffer_
->data()), &transport_bio_
,
754 recv_buffer_
->capacity(),
755 reinterpret_cast<uint8_t*>(recv_buffer_
->data())))
756 return ERR_UNEXPECTED
;
758 DCHECK(transport_bio_
);
760 // Install a callback on OpenSSL's end to plumb transport errors through.
761 BIO_set_callback(ssl_bio
, BIOCallback
);
762 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
764 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
766 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
767 // set everything we care about to an absolute value.
768 SslSetClearMask options
;
769 options
.ConfigureFlag(SSL_OP_NO_SSLv2
, true);
770 bool ssl3_enabled
= (ssl_config_
.version_min
== SSL_PROTOCOL_VERSION_SSL3
);
771 options
.ConfigureFlag(SSL_OP_NO_SSLv3
, !ssl3_enabled
);
772 bool tls1_enabled
= (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1
&&
773 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1
);
774 options
.ConfigureFlag(SSL_OP_NO_TLSv1
, !tls1_enabled
);
775 bool tls1_1_enabled
=
776 (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1_1
&&
777 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
);
778 options
.ConfigureFlag(SSL_OP_NO_TLSv1_1
, !tls1_1_enabled
);
779 bool tls1_2_enabled
=
780 (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1_2
&&
781 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_2
);
782 options
.ConfigureFlag(SSL_OP_NO_TLSv1_2
, !tls1_2_enabled
);
784 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
786 // TODO(joth): Set this conditionally, see http://crbug.com/55410
787 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
789 SSL_set_options(ssl_
, options
.set_mask
);
790 SSL_clear_options(ssl_
, options
.clear_mask
);
792 // Same as above, this time for the SSL mode.
793 SslSetClearMask mode
;
795 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
796 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
798 mode
.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH
,
799 ssl_config_
.false_start_enabled
);
801 SSL_set_mode(ssl_
, mode
.set_mask
);
802 SSL_clear_mode(ssl_
, mode
.clear_mask
);
804 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
805 // textual name with SSL_set_cipher_list because there is no public API to
806 // directly remove a cipher by ID.
807 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
809 // See SSLConfig::disabled_cipher_suites for description of the suites
810 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
811 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
812 // as the handshake hash.
814 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
815 // Walk through all the installed ciphers, seeing if any need to be
816 // appended to the cipher removal |command|.
817 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
818 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
819 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
820 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
821 // implementation uses "effective" bits here but OpenSSL does not provide
822 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
823 // both of which are greater than 80 anyway.
824 bool disable
= SSL_CIPHER_get_bits(cipher
, NULL
) < 80;
826 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
827 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
828 ssl_config_
.disabled_cipher_suites
.end();
831 const char* name
= SSL_CIPHER_get_name(cipher
);
832 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
833 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
834 command
.append(":!");
835 command
.append(name
);
839 // Disable ECDSA cipher suites on platforms that do not support ECDSA
840 // signed certificates, as servers may use the presence of such
841 // ciphersuites as a hint to send an ECDSA certificate.
843 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
844 command
.append(":!ECDSA");
847 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
848 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
849 // This will almost certainly result in the socket failing to complete the
850 // handshake at which point the appropriate error is bubbled up to the client.
851 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
854 if (ssl_config_
.version_fallback
)
855 SSL_enable_fallback_scsv(ssl_
);
858 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
859 SSL_enable_tls_channel_id(ssl_
);
862 if (!ssl_config_
.next_protos
.empty()) {
863 // Get list of ciphers that are enabled.
864 STACK_OF(SSL_CIPHER
)* enabled_ciphers
= SSL_get_ciphers(ssl_
);
865 DCHECK(enabled_ciphers
);
866 std::vector
<uint16
> enabled_ciphers_vector
;
867 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(enabled_ciphers
); ++i
) {
868 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(enabled_ciphers
, i
);
869 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
870 enabled_ciphers_vector
.push_back(id
);
873 std::vector
<uint8_t> wire_protos
=
874 SerializeNextProtos(ssl_config_
.next_protos
,
875 HasCipherAdequateForHTTP2(enabled_ciphers_vector
) &&
876 IsTLSVersionAdequateForHTTP2(ssl_config_
));
877 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
881 if (ssl_config_
.signed_cert_timestamps_enabled
) {
882 SSL_enable_signed_cert_timestamps(ssl_
);
883 SSL_enable_ocsp_stapling(ssl_
);
886 if (IsOCSPStaplingSupported())
887 SSL_enable_ocsp_stapling(ssl_
);
892 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
893 // Since Run may result in Read being called, clear |user_read_callback_|
896 was_ever_used_
= true;
897 user_read_buf_
= NULL
;
898 user_read_buf_len_
= 0;
900 // Failure of a read attempt may indicate a failed false start
902 OnHandshakeCompletion();
904 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
907 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
908 // Since Run may result in Write being called, clear |user_write_callback_|
911 was_ever_used_
= true;
912 user_write_buf_
= NULL
;
913 user_write_buf_len_
= 0;
915 // Failure of a write attempt may indicate a failed false start
917 OnHandshakeCompletion();
919 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
922 void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
923 if (!handshake_completion_callback_
.is_null())
924 base::ResetAndReturn(&handshake_completion_callback_
).Run();
927 bool SSLClientSocketOpenSSL::DoTransportIO() {
928 bool network_moved
= false;
930 // Read and write as much data as possible. The loop is necessary because
931 // Write() may return synchronously.
934 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
935 network_moved
= true;
937 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
938 network_moved
= true;
939 return network_moved
;
942 // TODO(vadimt): Remove including "base/threading/thread_local.h" and
943 // g_first_run_completed once crbug.com/424386 is fixed.
944 base::LazyInstance
<base::ThreadLocalBoolean
>::Leaky g_first_run_completed
=
945 LAZY_INSTANCE_INITIALIZER
;
947 int SSLClientSocketOpenSSL::DoHandshake() {
948 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
953 // TODO(vadimt): Leave only 1 call to SSL_do_handshake once crbug.com/424386
955 if (ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
956 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
957 tracked_objects::ScopedTracker
tracking_profile1(
958 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 DoHandshake_WithCert"));
960 rv
= SSL_do_handshake(ssl_
);
962 if (g_first_run_completed
.Get().Get()) {
963 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
965 tracked_objects::ScopedTracker
tracking_profile1(
966 FROM_HERE_WITH_EXPLICIT_FUNCTION(
967 "424386 DoHandshake_WithoutCert Not First"));
969 rv
= SSL_do_handshake(ssl_
);
971 g_first_run_completed
.Get().Set(true);
973 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
975 tracked_objects::ScopedTracker
tracking_profile1(
976 FROM_HERE_WITH_EXPLICIT_FUNCTION(
977 "424386 DoHandshake_WithoutCert First"));
979 rv
= SSL_do_handshake(ssl_
);
983 if (client_auth_cert_needed_
) {
984 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
985 tracked_objects::ScopedTracker
tracking_profile2(
986 FROM_HERE_WITH_EXPLICIT_FUNCTION(
987 "424386 SSLClientSocketOpenSSL::DoHandshake2"));
989 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
990 // If the handshake already succeeded (because the server requests but
991 // doesn't require a client cert), we need to invalidate the SSL session
992 // so that we won't try to resume the non-client-authenticated session in
993 // the next handshake. This will cause the server to ask for a client
996 // Remove from session cache but don't clear this connection.
997 SSL_SESSION
* session
= SSL_get_session(ssl_
);
999 int rv
= SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_
), session
);
1000 LOG_IF(WARNING
, !rv
) << "Couldn't invalidate SSL session: " << session
;
1003 } else if (rv
== 1) {
1004 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1005 tracked_objects::ScopedTracker
tracking_profile3(
1006 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1007 "424386 SSLClientSocketOpenSSL::DoHandshake3"));
1009 if (trying_cached_session_
&& logging::DEBUG_MODE
) {
1010 DVLOG(2) << "Result of session reuse for " << host_and_port_
.ToString()
1011 << " is: " << (SSL_session_reused(ssl_
) ? "Success" : "Fail");
1014 if (ssl_config_
.version_fallback
&&
1015 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
1016 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
1019 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1020 if (npn_status_
== kNextProtoUnsupported
) {
1021 const uint8_t* alpn_proto
= NULL
;
1022 unsigned alpn_len
= 0;
1023 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
1025 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
1026 npn_status_
= kNextProtoNegotiated
;
1027 set_negotiation_extension(kExtensionALPN
);
1031 RecordChannelIDSupport(channel_id_service_
,
1032 channel_id_xtn_negotiated_
,
1033 ssl_config_
.channel_id_enabled
,
1034 crypto::ECPrivateKey::IsSupported());
1036 // Only record OCSP histograms if OCSP was requested.
1037 if (ssl_config_
.signed_cert_timestamps_enabled
||
1038 IsOCSPStaplingSupported()) {
1039 const uint8_t* ocsp_response
;
1040 size_t ocsp_response_len
;
1041 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
1043 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
1044 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
1047 const uint8_t* sct_list
;
1048 size_t sct_list_len
;
1049 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
1050 set_signed_cert_timestamps_received(sct_list_len
!= 0);
1052 // Verify the certificate.
1054 GotoState(STATE_VERIFY_CERT
);
1056 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1057 tracked_objects::ScopedTracker
tracking_profile4(
1058 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1059 "424386 SSLClientSocketOpenSSL::DoHandshake4"));
1061 int ssl_error
= SSL_get_error(ssl_
, rv
);
1063 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
1064 // The server supports channel ID. Stop to look one up before returning to
1066 channel_id_xtn_negotiated_
= true;
1067 GotoState(STATE_CHANNEL_ID_LOOKUP
);
1071 OpenSSLErrorInfo error_info
;
1072 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
1074 // If not done, stay in this state
1075 if (net_error
== ERR_IO_PENDING
) {
1076 GotoState(STATE_HANDSHAKE
);
1078 LOG(ERROR
) << "handshake failed; returned " << rv
1079 << ", SSL error code " << ssl_error
1080 << ", net_error " << net_error
;
1082 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1083 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1089 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1090 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1091 return channel_id_service_
->GetOrCreateChannelID(
1092 host_and_port_
.host(),
1093 &channel_id_private_key_
,
1095 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1096 base::Unretained(this)),
1097 &channel_id_request_handle_
);
1100 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1104 DCHECK_LT(0u, channel_id_private_key_
.size());
1106 std::vector
<uint8
> encrypted_private_key_info
;
1107 std::vector
<uint8
> subject_public_key_info
;
1108 encrypted_private_key_info
.assign(
1109 channel_id_private_key_
.data(),
1110 channel_id_private_key_
.data() + channel_id_private_key_
.size());
1111 subject_public_key_info
.assign(
1112 channel_id_cert_
.data(),
1113 channel_id_cert_
.data() + channel_id_cert_
.size());
1114 scoped_ptr
<crypto::ECPrivateKey
> ec_private_key(
1115 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1116 ChannelIDService::kEPKIPassword
,
1117 encrypted_private_key_info
,
1118 subject_public_key_info
));
1119 if (!ec_private_key
) {
1120 LOG(ERROR
) << "Failed to import Channel ID.";
1121 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1124 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1126 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1127 int rv
= SSL_set1_tls_channel_id(ssl_
, ec_private_key
->key());
1129 LOG(ERROR
) << "Failed to set Channel ID.";
1130 int err
= SSL_get_error(ssl_
, rv
);
1131 return MapOpenSSLError(err
, err_tracer
);
1134 // Return to the handshake.
1135 set_channel_id_sent(true);
1136 GotoState(STATE_HANDSHAKE
);
1140 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1141 DCHECK(!server_cert_chain_
->empty());
1142 DCHECK(start_cert_verification_time_
.is_null());
1144 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1146 // If the certificate is bad and has been previously accepted, use
1147 // the previous status and bypass the error.
1148 base::StringPiece der_cert
;
1149 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1151 return ERR_CERT_INVALID
;
1153 CertStatus cert_status
;
1154 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1155 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1156 server_cert_verify_result_
.Reset();
1157 server_cert_verify_result_
.cert_status
= cert_status
;
1158 server_cert_verify_result_
.verified_cert
= server_cert_
;
1162 // When running in a sandbox, it may not be possible to create an
1163 // X509Certificate*, as that may depend on OS functionality blocked
1165 if (!server_cert_
.get()) {
1166 server_cert_verify_result_
.Reset();
1167 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
1168 return ERR_CERT_INVALID
;
1171 start_cert_verification_time_
= base::TimeTicks::Now();
1174 if (ssl_config_
.rev_checking_enabled
)
1175 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
1176 if (ssl_config_
.verify_ev_cert
)
1177 flags
|= CertVerifier::VERIFY_EV_CERT
;
1178 if (ssl_config_
.cert_io_enabled
)
1179 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
1180 if (ssl_config_
.rev_checking_required_local_anchors
)
1181 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
1182 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
1183 return verifier_
->Verify(
1185 host_and_port_
.host(),
1187 // TODO(davidben): Route the CRLSet through SSLConfig so
1188 // SSLClientSocket doesn't depend on SSLConfigService.
1189 SSLConfigService::GetCRLSet().get(),
1190 &server_cert_verify_result_
,
1191 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1192 base::Unretained(this)),
1196 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1199 if (!start_cert_verification_time_
.is_null()) {
1200 base::TimeDelta verify_time
=
1201 base::TimeTicks::Now() - start_cert_verification_time_
;
1203 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1205 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1210 RecordConnectionTypeMetrics(GetNetSSLVersion(ssl_
));
1212 if (SSL_session_reused(ssl_
)) {
1213 // Record whether or not the server tried to resume a session for a
1214 // different version. See https://crbug.com/441456.
1215 UMA_HISTOGRAM_BOOLEAN(
1216 "Net.SSLSessionVersionMatch",
1217 SSL_version(ssl_
) == SSL_get_session(ssl_
)->ssl_version
);
1221 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1222 if (transport_security_state_
&&
1224 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1225 !transport_security_state_
->CheckPublicKeyPins(
1226 host_and_port_
.host(),
1227 server_cert_verify_result_
.is_issued_by_known_root
,
1228 server_cert_verify_result_
.public_key_hashes
,
1229 &pinning_failure_log_
)) {
1230 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1234 // Only check Certificate Transparency if there were no other errors with
1238 // TODO(joth): Work out if we need to remember the intermediate CA certs
1239 // when the server sends them to us, and do so here.
1240 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_
);
1241 marked_session_as_good_
= true;
1242 CheckIfHandshakeFinished();
1244 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1245 << " (" << result
<< ")";
1248 completed_connect_
= true;
1250 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1251 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1255 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1257 OnHandshakeCompletion();
1258 if (!user_connect_callback_
.is_null()) {
1259 CompletionCallback c
= user_connect_callback_
;
1260 user_connect_callback_
.Reset();
1261 c
.Run(rv
> OK
? OK
: rv
);
1265 void SSLClientSocketOpenSSL::UpdateServerCert() {
1266 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1267 tracked_objects::ScopedTracker
tracking_profile(
1268 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1269 "424386 SSLClientSocketOpenSSL::UpdateServerCert"));
1271 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1273 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1274 tracked_objects::ScopedTracker
tracking_profile1(
1275 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1276 "424386 SSLClientSocketOpenSSL::UpdateServerCert1"));
1277 server_cert_
= server_cert_chain_
->AsOSChain();
1279 if (server_cert_
.get()) {
1281 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
1282 base::Bind(&NetLogX509CertificateCallback
,
1283 base::Unretained(server_cert_
.get())));
1285 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1286 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1287 if (IsOCSPStaplingSupported()) {
1289 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
1291 tracked_objects::ScopedTracker
tracking_profile2(
1292 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1293 "424386 SSLClientSocketOpenSSL::UpdateServerCert2"));
1295 const uint8_t* ocsp_response_raw
;
1296 size_t ocsp_response_len
;
1297 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1299 CRYPT_DATA_BLOB ocsp_response_blob
;
1300 ocsp_response_blob
.cbData
= ocsp_response_len
;
1301 ocsp_response_blob
.pbData
= const_cast<BYTE
*>(ocsp_response_raw
);
1302 BOOL ok
= CertSetCertificateContextProperty(
1303 server_cert_
->os_cert_handle(),
1304 CERT_OCSP_RESPONSE_PROP_ID
,
1305 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
1306 &ocsp_response_blob
);
1308 VLOG(1) << "Failed to set OCSP response property: "
1318 void SSLClientSocketOpenSSL::VerifyCT() {
1319 if (!cert_transparency_verifier_
)
1322 const uint8_t* ocsp_response_raw
;
1323 size_t ocsp_response_len
;
1324 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1325 std::string ocsp_response
;
1326 if (ocsp_response_len
> 0) {
1327 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1331 const uint8_t* sct_list_raw
;
1332 size_t sct_list_len
;
1333 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1334 std::string sct_list
;
1335 if (sct_list_len
> 0)
1336 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1338 // Note that this is a completely synchronous operation: The CT Log Verifier
1339 // gets all the data it needs for SCT verification and does not do any
1340 // external communication.
1341 cert_transparency_verifier_
->Verify(
1342 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1343 &ct_verify_result_
, net_log_
);
1345 if (!policy_enforcer_
) {
1346 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1348 if (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
) {
1349 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1350 SSLConfigService::GetEVCertsWhitelist();
1351 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1352 server_cert_verify_result_
.verified_cert
.get(),
1353 ev_whitelist
.get(), ct_verify_result_
, net_log_
)) {
1354 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1355 VLOG(1) << "EV certificate for "
1356 << server_cert_verify_result_
.verified_cert
->subject()
1358 << " does not conform to CT policy, removing EV status.";
1359 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1365 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1366 int rv
= DoHandshakeLoop(result
);
1367 if (rv
!= ERR_IO_PENDING
) {
1368 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1369 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.SSL_Connection_Error", std::abs(rv
));
1370 DoConnectCallback(rv
);
1374 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1375 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1376 // In handshake phase.
1377 OnHandshakeIOComplete(result
);
1381 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1382 // handshake is in progress.
1383 int rv_read
= ERR_IO_PENDING
;
1384 int rv_write
= ERR_IO_PENDING
;
1387 if (user_read_buf_
.get())
1388 rv_read
= DoPayloadRead();
1389 if (user_write_buf_
.get())
1390 rv_write
= DoPayloadWrite();
1391 network_moved
= DoTransportIO();
1392 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1393 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1395 // Performing the Read callback may cause |this| to be deleted. If this
1396 // happens, the Write callback should not be invoked. Guard against this by
1397 // holding a WeakPtr to |this| and ensuring it's still valid.
1398 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1399 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1400 DoReadCallback(rv_read
);
1405 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1406 DoWriteCallback(rv_write
);
1409 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1410 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1411 // In handshake phase.
1412 OnHandshakeIOComplete(result
);
1416 // Network layer received some data, check if client requested to read
1418 if (!user_read_buf_
.get())
1421 int rv
= DoReadLoop();
1422 if (rv
!= ERR_IO_PENDING
)
1426 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1427 int rv
= last_io_result
;
1429 // Default to STATE_NONE for next state.
1430 // (This is a quirk carried over from the windows
1431 // implementation. It makes reading the logs a bit harder.)
1432 // State handlers can and often do call GotoState just
1433 // to stay in the current state.
1434 State state
= next_handshake_state_
;
1435 GotoState(STATE_NONE
);
1437 case STATE_HANDSHAKE
:
1440 case STATE_CHANNEL_ID_LOOKUP
:
1442 rv
= DoChannelIDLookup();
1444 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1445 rv
= DoChannelIDLookupComplete(rv
);
1447 case STATE_VERIFY_CERT
:
1449 rv
= DoVerifyCert(rv
);
1451 case STATE_VERIFY_CERT_COMPLETE
:
1452 rv
= DoVerifyCertComplete(rv
);
1456 rv
= ERR_UNEXPECTED
;
1457 NOTREACHED() << "unexpected state" << state
;
1461 bool network_moved
= DoTransportIO();
1462 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1463 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1464 // special case we keep looping even if rv is ERR_IO_PENDING because
1465 // the transport IO may allow DoHandshake to make progress.
1466 rv
= OK
; // This causes us to stay in the loop.
1468 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1473 int SSLClientSocketOpenSSL::DoReadLoop() {
1477 rv
= DoPayloadRead();
1478 network_moved
= DoTransportIO();
1479 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1484 int SSLClientSocketOpenSSL::DoWriteLoop() {
1488 rv
= DoPayloadWrite();
1489 network_moved
= DoTransportIO();
1490 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1495 int SSLClientSocketOpenSSL::DoPayloadRead() {
1496 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1499 if (pending_read_error_
!= kNoPendingReadResult
) {
1500 rv
= pending_read_error_
;
1501 pending_read_error_
= kNoPendingReadResult
;
1503 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1504 rv
, user_read_buf_
->data());
1507 NetLog::TYPE_SSL_READ_ERROR
,
1508 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1509 pending_read_error_info_
));
1511 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1512 pending_read_error_info_
= OpenSSLErrorInfo();
1516 int total_bytes_read
= 0;
1518 rv
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1519 user_read_buf_len_
- total_bytes_read
);
1521 total_bytes_read
+= rv
;
1522 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
1524 if (total_bytes_read
== user_read_buf_len_
) {
1525 rv
= total_bytes_read
;
1527 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1528 // immediately, while the OpenSSL errors are still available in
1529 // thread-local storage. However, the handled/remapped error code should
1530 // only be returned if no application data was already read; if it was, the
1531 // error code should be deferred until the next call of DoPayloadRead.
1533 // If no data was read, |*next_result| will point to the return value of
1534 // this function. If at least some data was read, |*next_result| will point
1535 // to |pending_read_error_|, to be returned in a future call to
1536 // DoPayloadRead() (e.g.: after the current data is handled).
1537 int *next_result
= &rv
;
1538 if (total_bytes_read
> 0) {
1539 pending_read_error_
= rv
;
1540 rv
= total_bytes_read
;
1541 next_result
= &pending_read_error_
;
1544 if (client_auth_cert_needed_
) {
1545 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1546 } else if (*next_result
< 0) {
1547 pending_read_ssl_error_
= SSL_get_error(ssl_
, *next_result
);
1548 *next_result
= MapOpenSSLErrorWithDetails(pending_read_ssl_error_
,
1550 &pending_read_error_info_
);
1552 // Many servers do not reliably send a close_notify alert when shutting
1553 // down a connection, and instead terminate the TCP connection. This is
1554 // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1555 // shutdown to a graceful EOF, instead of treating it as an error as it
1557 if (*next_result
== ERR_CONNECTION_CLOSED
)
1560 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
1561 // If at least some data was read from SSL_read(), do not treat
1562 // insufficient data as an error to return in the next call to
1563 // DoPayloadRead() - instead, let the call fall through to check
1564 // SSL_read() again. This is because DoTransportIO() may complete
1565 // in between the next call to DoPayloadRead(), and thus it is
1566 // important to check SSL_read() on subsequent invocations to see
1567 // if a complete record may now be read.
1568 *next_result
= kNoPendingReadResult
;
1574 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1575 user_read_buf_
->data());
1576 } else if (rv
!= ERR_IO_PENDING
) {
1578 NetLog::TYPE_SSL_READ_ERROR
,
1579 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1580 pending_read_error_info_
));
1581 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1582 pending_read_error_info_
= OpenSSLErrorInfo();
1587 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1588 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1589 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1591 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1592 user_write_buf_
->data());
1596 int ssl_error
= SSL_get_error(ssl_
, rv
);
1597 OpenSSLErrorInfo error_info
;
1598 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1601 if (net_error
!= ERR_IO_PENDING
) {
1603 NetLog::TYPE_SSL_WRITE_ERROR
,
1604 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1609 int SSLClientSocketOpenSSL::BufferSend(void) {
1610 if (transport_send_busy_
)
1611 return ERR_IO_PENDING
;
1613 size_t buffer_read_offset
;
1616 int status
= BIO_zero_copy_get_read_buf(transport_bio_
, &read_buf
,
1617 &buffer_read_offset
, &max_read
);
1618 DCHECK_EQ(status
, 1); // Should never fail.
1620 return 0; // Nothing pending in the OpenSSL write BIO.
1621 CHECK_EQ(read_buf
, reinterpret_cast<uint8_t*>(send_buffer_
->StartOfBuffer()));
1622 CHECK_LT(buffer_read_offset
, static_cast<size_t>(send_buffer_
->capacity()));
1623 send_buffer_
->set_offset(buffer_read_offset
);
1625 int rv
= transport_
->socket()->Write(
1626 send_buffer_
.get(), max_read
,
1627 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1628 base::Unretained(this)));
1629 if (rv
== ERR_IO_PENDING
) {
1630 transport_send_busy_
= true;
1632 TransportWriteComplete(rv
);
1637 int SSLClientSocketOpenSSL::BufferRecv(void) {
1638 if (transport_recv_busy_
)
1639 return ERR_IO_PENDING
;
1641 // Determine how much was requested from |transport_bio_| that was not
1642 // actually available.
1643 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1644 if (requested
== 0) {
1645 // This is not a perfect match of error codes, as no operation is
1646 // actually pending. However, returning 0 would be interpreted as
1647 // a possible sign of EOF, which is also an inappropriate match.
1648 return ERR_IO_PENDING
;
1651 // Known Issue: While only reading |requested| data is the more correct
1652 // implementation, it has the downside of resulting in frequent reads:
1653 // One read for the SSL record header (~5 bytes) and one read for the SSL
1654 // record body. Rather than issuing these reads to the underlying socket
1655 // (and constantly allocating new IOBuffers), a single Read() request to
1656 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1657 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1658 // traffic, this over-subscribed Read()ing will not cause issues.
1660 size_t buffer_write_offset
;
1663 int status
= BIO_zero_copy_get_write_buf(transport_bio_
, &write_buf
,
1664 &buffer_write_offset
, &max_write
);
1665 DCHECK_EQ(status
, 1); // Should never fail.
1667 return ERR_IO_PENDING
;
1670 reinterpret_cast<uint8_t*>(recv_buffer_
->StartOfBuffer()));
1671 CHECK_LT(buffer_write_offset
, static_cast<size_t>(recv_buffer_
->capacity()));
1673 recv_buffer_
->set_offset(buffer_write_offset
);
1674 int rv
= transport_
->socket()->Read(
1677 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1678 base::Unretained(this)));
1679 if (rv
== ERR_IO_PENDING
) {
1680 transport_recv_busy_
= true;
1682 rv
= TransportReadComplete(rv
);
1687 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1688 TransportWriteComplete(result
);
1689 OnSendComplete(result
);
1692 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1693 result
= TransportReadComplete(result
);
1694 OnRecvComplete(result
);
1697 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1698 DCHECK(ERR_IO_PENDING
!= result
);
1699 int bytes_written
= 0;
1701 // Record the error. Save it to be reported in a future read or write on
1702 // transport_bio_'s peer.
1703 transport_write_error_
= result
;
1705 bytes_written
= result
;
1707 DCHECK_GE(send_buffer_
->RemainingCapacity(), bytes_written
);
1708 int ret
= BIO_zero_copy_get_read_buf_done(transport_bio_
, bytes_written
);
1710 transport_send_busy_
= false;
1713 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1714 DCHECK(ERR_IO_PENDING
!= result
);
1715 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1716 // does not report success.
1718 result
= ERR_CONNECTION_CLOSED
;
1721 DVLOG(1) << "TransportReadComplete result " << result
;
1722 // Received an error. Save it to be reported in a future read on
1723 // transport_bio_'s peer.
1724 transport_read_error_
= result
;
1726 bytes_read
= result
;
1728 DCHECK_GE(recv_buffer_
->RemainingCapacity(), bytes_read
);
1729 int ret
= BIO_zero_copy_get_write_buf_done(transport_bio_
, bytes_read
);
1731 transport_recv_busy_
= false;
1735 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1736 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1737 tracked_objects::ScopedTracker
tracking_profile(
1738 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1739 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1741 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1742 DCHECK(ssl
== ssl_
);
1744 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1746 // Clear any currently configured certificates.
1747 SSL_certs_clear(ssl_
);
1750 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1751 LOG(WARNING
) << "Client auth is not supported";
1752 #else // !defined(OS_IOS)
1753 if (!ssl_config_
.send_client_cert
) {
1754 // First pass: we know that a client certificate is needed, but we do not
1755 // have one at hand.
1756 client_auth_cert_needed_
= true;
1757 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1758 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1759 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1760 unsigned char* str
= NULL
;
1761 int length
= i2d_X509_NAME(ca_name
, &str
);
1762 cert_authorities_
.push_back(std::string(
1763 reinterpret_cast<const char*>(str
),
1764 static_cast<size_t>(length
)));
1768 const unsigned char* client_cert_types
;
1769 size_t num_client_cert_types
=
1770 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1771 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1772 cert_key_types_
.push_back(
1773 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1776 return -1; // Suspends handshake.
1779 // Second pass: a client certificate should have been selected.
1780 if (ssl_config_
.client_cert
.get()) {
1781 ScopedX509 leaf_x509
=
1782 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1784 LOG(WARNING
) << "Failed to import certificate";
1785 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1789 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1790 ssl_config_
.client_cert
->GetIntermediateCertificates());
1792 LOG(WARNING
) << "Failed to import intermediate certificates";
1793 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1797 // TODO(davidben): With Linux client auth support, this should be
1798 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1799 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1800 // net/ client auth API lacking a private key handle.
1801 #if defined(USE_OPENSSL_CERTS)
1802 crypto::ScopedEVP_PKEY privkey
=
1803 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1804 ssl_config_
.client_cert
.get());
1805 #else // !defined(USE_OPENSSL_CERTS)
1806 crypto::ScopedEVP_PKEY privkey
=
1807 FetchClientCertPrivateKey(ssl_config_
.client_cert
.get());
1808 #endif // defined(USE_OPENSSL_CERTS)
1810 // Could not find the private key. Fail the handshake and surface an
1811 // appropriate error to the caller.
1812 LOG(WARNING
) << "Client cert found without private key";
1813 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1817 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1818 !SSL_use_PrivateKey(ssl_
, privkey
.get()) ||
1819 !SSL_set1_chain(ssl_
, chain
.get())) {
1820 LOG(WARNING
) << "Failed to set client certificate";
1824 int cert_count
= 1 + sk_X509_num(chain
.get());
1825 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1826 NetLog::IntegerCallback("cert_count", cert_count
));
1829 #endif // defined(OS_IOS)
1831 // Send no client certificate.
1832 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1833 NetLog::IntegerCallback("cert_count", 0));
1837 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1838 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1839 tracked_objects::ScopedTracker
tracking_profile(
1840 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1841 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1843 if (!completed_connect_
) {
1844 // If the first handshake hasn't completed then we accept any certificates
1845 // because we verify after the handshake.
1849 // Disallow the server certificate to change in a renegotiation.
1850 if (server_cert_chain_
->empty()) {
1851 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1854 base::StringPiece old_der
, new_der
;
1855 if (store_ctx
->cert
== NULL
||
1856 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1857 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1858 LOG(ERROR
) << "Failed to encode certificates";
1861 if (old_der
!= new_der
) {
1862 LOG(ERROR
) << "Server certificate changed between handshakes";
1869 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1870 // server supports NPN, selects a protocol from the list that the server
1871 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1872 // callback can assume that |in| is syntactically valid.
1873 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1874 unsigned char* outlen
,
1875 const unsigned char* in
,
1876 unsigned int inlen
) {
1877 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1878 tracked_objects::ScopedTracker
tracking_profile(
1879 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1880 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1882 if (ssl_config_
.next_protos
.empty()) {
1883 *out
= reinterpret_cast<uint8
*>(
1884 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1885 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1886 npn_status_
= kNextProtoUnsupported
;
1887 return SSL_TLSEXT_ERR_OK
;
1890 // Assume there's no overlap between our protocols and the server's list.
1891 npn_status_
= kNextProtoNoOverlap
;
1893 // For each protocol in server preference order, see if we support it.
1894 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1895 for (NextProto next_proto
: ssl_config_
.next_protos
) {
1896 const std::string proto
= NextProtoToString(next_proto
);
1897 if (in
[i
] == proto
.size() &&
1898 memcmp(&in
[i
+ 1], proto
.data(), in
[i
]) == 0) {
1899 // We found a match.
1900 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1902 npn_status_
= kNextProtoNegotiated
;
1906 if (npn_status_
== kNextProtoNegotiated
)
1910 // If we didn't find a protocol, we select the first one from our list.
1911 if (npn_status_
== kNextProtoNoOverlap
) {
1912 // NextProtoToString returns a pointer to a static string.
1913 const char* proto
= NextProtoToString(ssl_config_
.next_protos
[0]);
1914 *out
= reinterpret_cast<unsigned char*>(const_cast<char*>(proto
));
1915 *outlen
= strlen(proto
);
1918 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1919 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1920 set_negotiation_extension(kExtensionNPN
);
1921 return SSL_TLSEXT_ERR_OK
;
1924 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1927 const char *argp
, int argi
, long argl
,
1929 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1930 // If there is no more data in the buffer, report any pending errors that
1931 // were observed. Note that both the readbuf and the writebuf are checked
1932 // for errors, since the application may have encountered a socket error
1933 // while writing that would otherwise not be reported until the application
1934 // attempted to write again - which it may never do. See
1935 // https://crbug.com/249848.
1936 if (transport_read_error_
!= OK
) {
1937 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1940 if (transport_write_error_
!= OK
) {
1941 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1944 } else if (cmd
== BIO_CB_WRITE
) {
1945 // Because of the write buffer, this reports a failure from the previous
1946 // write payload. If the current payload fails to write, the error will be
1947 // reported in a future write or read to |bio|.
1948 if (transport_write_error_
!= OK
) {
1949 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1957 long SSLClientSocketOpenSSL::BIOCallback(
1960 const char *argp
, int argi
, long argl
,
1962 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1963 tracked_objects::ScopedTracker
tracking_profile(
1964 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1965 "424386 SSLClientSocketOpenSSL::BIOCallback"));
1967 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1968 BIO_get_callback_arg(bio
));
1970 return socket
->MaybeReplayTransportError(
1971 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1975 void SSLClientSocketOpenSSL::InfoCallback(const SSL
* ssl
,
1978 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1979 tracked_objects::ScopedTracker
tracking_profile(
1980 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1981 "424386 SSLClientSocketOpenSSL::InfoCallback"));
1983 if (type
== SSL_CB_HANDSHAKE_DONE
) {
1984 SSLClientSocketOpenSSL
* ssl_socket
=
1985 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl
);
1986 ssl_socket
->handshake_succeeded_
= true;
1987 ssl_socket
->CheckIfHandshakeFinished();
1991 // Determines if both the handshake and certificate verification have completed
1992 // successfully, and calls the handshake completion callback if that is the
1995 // CheckIfHandshakeFinished is called twice per connection: once after
1996 // MarkSSLSessionAsGood, when the certificate has been verified, and
1997 // once via an OpenSSL callback when the handshake has completed. On the
1998 // second call, when the certificate has been verified and the handshake
1999 // has completed, the connection's handshake completion callback is run.
2000 void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
2001 if (handshake_succeeded_
&& marked_session_as_good_
)
2002 OnHandshakeCompletion();
2005 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
2006 for (ct::SCTList::const_iterator iter
=
2007 ct_verify_result_
.verified_scts
.begin();
2008 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
2009 ssl_info
->signed_certificate_timestamps
.push_back(
2010 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
2012 for (ct::SCTList::const_iterator iter
=
2013 ct_verify_result_
.invalid_scts
.begin();
2014 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
2015 ssl_info
->signed_certificate_timestamps
.push_back(
2016 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
2018 for (ct::SCTList::const_iterator iter
=
2019 ct_verify_result_
.unknown_logs_scts
.begin();
2020 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
2021 ssl_info
->signed_certificate_timestamps
.push_back(
2022 SignedCertificateTimestampAndStatus(*iter
,
2023 ct::SCT_STATUS_LOG_UNKNOWN
));
2027 scoped_refptr
<X509Certificate
>
2028 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
2029 return server_cert_
;