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>
15 #include "base/bind.h"
16 #include "base/callback_helpers.h"
17 #include "base/environment.h"
18 #include "base/memory/singleton.h"
19 #include "base/metrics/histogram.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/strings/string_piece.h"
22 #include "base/synchronization/lock.h"
23 #include "crypto/ec_private_key.h"
24 #include "crypto/openssl_util.h"
25 #include "crypto/scoped_openssl_types.h"
26 #include "net/base/net_errors.h"
27 #include "net/cert/cert_policy_enforcer.h"
28 #include "net/cert/cert_verifier.h"
29 #include "net/cert/ct_ev_whitelist.h"
30 #include "net/cert/ct_verifier.h"
31 #include "net/cert/single_request_cert_verifier.h"
32 #include "net/cert/x509_certificate_net_log_param.h"
33 #include "net/cert/x509_util_openssl.h"
34 #include "net/http/transport_security_state.h"
35 #include "net/socket/ssl_session_cache_openssl.h"
36 #include "net/ssl/ssl_cert_request_info.h"
37 #include "net/ssl/ssl_connection_status_flags.h"
38 #include "net/ssl/ssl_info.h"
41 #include "base/win/windows_version.h"
44 #if defined(USE_OPENSSL_CERTS)
45 #include "net/ssl/openssl_client_key_store.h"
47 #include "net/ssl/openssl_platform_key.h"
54 // Enable this to see logging for state machine state transitions.
56 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
57 " jump to state " << s; \
58 next_handshake_state_ = s; } while (0)
60 #define GotoState(s) next_handshake_state_ = s
63 // This constant can be any non-negative/non-zero value (eg: it does not
64 // overlap with any value of the net::Error range, including net::OK).
65 const int kNoPendingReadResult
= 1;
67 // If a client doesn't have a list of protocols that it supports, but
68 // the server supports NPN, choosing "http/1.1" is the best answer.
69 const char kDefaultSupportedNPNProtocol
[] = "http/1.1";
71 void FreeX509Stack(STACK_OF(X509
)* ptr
) {
72 sk_X509_pop_free(ptr
, X509_free
);
75 typedef crypto::ScopedOpenSSL
<X509
, X509_free
>::Type ScopedX509
;
76 typedef crypto::ScopedOpenSSL
<STACK_OF(X509
), FreeX509Stack
>::Type
79 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
80 // This method doesn't seem to have made it into the OpenSSL headers.
81 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER
* cipher
) { return cipher
->id
; }
84 // Used for encoding the |connection_status| field of an SSLInfo object.
85 int EncodeSSLConnectionStatus(uint16 cipher_suite
,
89 ((compression
& SSL_CONNECTION_COMPRESSION_MASK
) <<
90 SSL_CONNECTION_COMPRESSION_SHIFT
) |
91 ((version
& SSL_CONNECTION_VERSION_MASK
) <<
92 SSL_CONNECTION_VERSION_SHIFT
);
95 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
96 // this SSL connection.
97 int GetNetSSLVersion(SSL
* ssl
) {
98 switch (SSL_version(ssl
)) {
100 return SSL_CONNECTION_VERSION_SSL2
;
102 return SSL_CONNECTION_VERSION_SSL3
;
104 return SSL_CONNECTION_VERSION_TLS1
;
106 return SSL_CONNECTION_VERSION_TLS1_1
;
108 return SSL_CONNECTION_VERSION_TLS1_2
;
110 return SSL_CONNECTION_VERSION_UNKNOWN
;
114 ScopedX509
OSCertHandleToOpenSSL(
115 X509Certificate::OSCertHandle os_handle
) {
116 #if defined(USE_OPENSSL_CERTS)
117 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle
));
118 #else // !defined(USE_OPENSSL_CERTS)
119 std::string der_encoded
;
120 if (!X509Certificate::GetDEREncoded(os_handle
, &der_encoded
))
122 const uint8_t* bytes
= reinterpret_cast<const uint8_t*>(der_encoded
.data());
123 return ScopedX509(d2i_X509(NULL
, &bytes
, der_encoded
.size()));
124 #endif // defined(USE_OPENSSL_CERTS)
127 ScopedX509Stack
OSCertHandlesToOpenSSL(
128 const X509Certificate::OSCertHandles
& os_handles
) {
129 ScopedX509Stack
stack(sk_X509_new_null());
130 for (size_t i
= 0; i
< os_handles
.size(); i
++) {
131 ScopedX509 x509
= OSCertHandleToOpenSSL(os_handles
[i
]);
133 return ScopedX509Stack();
134 sk_X509_push(stack
.get(), x509
.release());
139 int LogErrorCallback(const char* str
, size_t len
, void* context
) {
140 LOG(ERROR
) << base::StringPiece(str
, len
);
144 bool IsOCSPStaplingSupported() {
146 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
147 // set on Windows XP without error. There is some overhead from the server
148 // sending the OCSP response if it supports the extension, for the subset of
149 // XP clients who will request it but be unable to use it, but this is an
150 // acceptable trade-off for simplicity of implementation.
159 class SSLClientSocketOpenSSL::SSLContext
{
161 static SSLContext
* GetInstance() { return Singleton
<SSLContext
>::get(); }
162 SSL_CTX
* ssl_ctx() { return ssl_ctx_
.get(); }
163 SSLSessionCacheOpenSSL
* session_cache() { return &session_cache_
; }
165 SSLClientSocketOpenSSL
* GetClientSocketFromSSL(const SSL
* ssl
) {
167 SSLClientSocketOpenSSL
* socket
= static_cast<SSLClientSocketOpenSSL
*>(
168 SSL_get_ex_data(ssl
, ssl_socket_data_index_
));
173 bool SetClientSocketForSSL(SSL
* ssl
, SSLClientSocketOpenSSL
* socket
) {
174 return SSL_set_ex_data(ssl
, ssl_socket_data_index_
, socket
) != 0;
178 friend struct DefaultSingletonTraits
<SSLContext
>;
181 crypto::EnsureOpenSSLInit();
182 ssl_socket_data_index_
= SSL_get_ex_new_index(0, 0, 0, 0, 0);
183 DCHECK_NE(ssl_socket_data_index_
, -1);
184 ssl_ctx_
.reset(SSL_CTX_new(SSLv23_client_method()));
185 session_cache_
.Reset(ssl_ctx_
.get(), kDefaultSessionCacheConfig
);
186 SSL_CTX_set_cert_verify_callback(ssl_ctx_
.get(), CertVerifyCallback
, NULL
);
187 SSL_CTX_set_cert_cb(ssl_ctx_
.get(), ClientCertRequestCallback
, NULL
);
188 SSL_CTX_set_verify(ssl_ctx_
.get(), SSL_VERIFY_PEER
, NULL
);
189 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
190 // It would be better if the callback were not a global setting,
191 // but that is an OpenSSL issue.
192 SSL_CTX_set_next_proto_select_cb(ssl_ctx_
.get(), SelectNextProtoCallback
,
194 ssl_ctx_
->tlsext_channel_id_enabled_new
= 1;
196 scoped_ptr
<base::Environment
> env(base::Environment::Create());
197 std::string ssl_keylog_file
;
198 if (env
->GetVar("SSLKEYLOGFILE", &ssl_keylog_file
) &&
199 !ssl_keylog_file
.empty()) {
200 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
201 BIO
* bio
= BIO_new_file(ssl_keylog_file
.c_str(), "a");
203 LOG(ERROR
) << "Failed to open " << ssl_keylog_file
;
204 ERR_print_errors_cb(&LogErrorCallback
, NULL
);
206 SSL_CTX_set_keylog_bio(ssl_ctx_
.get(), bio
);
211 static std::string
GetSessionCacheKey(const SSL
* ssl
) {
212 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
214 return socket
->GetSessionCacheKey();
217 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig
;
219 static int ClientCertRequestCallback(SSL
* ssl
, void* arg
) {
220 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
222 return socket
->ClientCertRequestCallback(ssl
);
225 static int CertVerifyCallback(X509_STORE_CTX
*store_ctx
, void *arg
) {
226 SSL
* ssl
= reinterpret_cast<SSL
*>(X509_STORE_CTX_get_ex_data(
227 store_ctx
, SSL_get_ex_data_X509_STORE_CTX_idx()));
228 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
231 return socket
->CertVerifyCallback(store_ctx
);
234 static int SelectNextProtoCallback(SSL
* ssl
,
235 unsigned char** out
, unsigned char* outlen
,
236 const unsigned char* in
,
237 unsigned int inlen
, void* arg
) {
238 SSLClientSocketOpenSSL
* socket
= GetInstance()->GetClientSocketFromSSL(ssl
);
239 return socket
->SelectNextProtoCallback(out
, outlen
, in
, inlen
);
242 // This is the index used with SSL_get_ex_data to retrieve the owner
243 // SSLClientSocketOpenSSL object from an SSL instance.
244 int ssl_socket_data_index_
;
246 crypto::ScopedOpenSSL
<SSL_CTX
, SSL_CTX_free
>::Type ssl_ctx_
;
247 // |session_cache_| must be destroyed before |ssl_ctx_|.
248 SSLSessionCacheOpenSSL session_cache_
;
251 // PeerCertificateChain is a helper object which extracts the certificate
252 // chain, as given by the server, from an OpenSSL socket and performs the needed
253 // resource management. The first element of the chain is the leaf certificate
254 // and the other elements are in the order given by the server.
255 class SSLClientSocketOpenSSL::PeerCertificateChain
{
257 explicit PeerCertificateChain(STACK_OF(X509
)* chain
) { Reset(chain
); }
258 PeerCertificateChain(const PeerCertificateChain
& other
) { *this = other
; }
259 ~PeerCertificateChain() {}
260 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
262 // Resets the PeerCertificateChain to the set of certificates in|chain|,
263 // which may be NULL, indicating to empty the store certificates.
264 // Note: If an error occurs, such as being unable to parse the certificates,
265 // this will behave as if Reset(NULL) was called.
266 void Reset(STACK_OF(X509
)* chain
);
268 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
269 scoped_refptr
<X509Certificate
> AsOSChain() const;
271 size_t size() const {
272 if (!openssl_chain_
.get())
274 return sk_X509_num(openssl_chain_
.get());
281 X509
* Get(size_t index
) const {
282 DCHECK_LT(index
, size());
283 return sk_X509_value(openssl_chain_
.get(), index
);
287 ScopedX509Stack openssl_chain_
;
290 SSLClientSocketOpenSSL::PeerCertificateChain
&
291 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
292 const PeerCertificateChain
& other
) {
296 openssl_chain_
.reset(X509_chain_up_ref(other
.openssl_chain_
.get()));
300 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
301 STACK_OF(X509
)* chain
) {
302 openssl_chain_
.reset(chain
? X509_chain_up_ref(chain
) : NULL
);
305 scoped_refptr
<X509Certificate
>
306 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
307 #if defined(USE_OPENSSL_CERTS)
308 // When OSCertHandle is typedef'ed to X509, this implementation does a short
309 // cut to avoid converting back and forth between DER and the X509 struct.
310 X509Certificate::OSCertHandles intermediates
;
311 for (size_t i
= 1; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
312 intermediates
.push_back(sk_X509_value(openssl_chain_
.get(), i
));
315 return make_scoped_refptr(X509Certificate::CreateFromHandle(
316 sk_X509_value(openssl_chain_
.get(), 0), intermediates
));
318 // DER-encode the chain and convert to a platform certificate handle.
319 std::vector
<base::StringPiece
> der_chain
;
320 for (size_t i
= 0; i
< sk_X509_num(openssl_chain_
.get()); ++i
) {
321 X509
* x
= sk_X509_value(openssl_chain_
.get(), i
);
322 base::StringPiece der
;
323 if (!x509_util::GetDER(x
, &der
))
325 der_chain
.push_back(der
);
328 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain
));
333 SSLSessionCacheOpenSSL::Config
334 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig
= {
335 &GetSessionCacheKey
, // key_func
337 256, // expiration_check_count
338 60 * 60, // timeout_seconds
342 void SSLClientSocket::ClearSessionCache() {
343 SSLClientSocketOpenSSL::SSLContext
* context
=
344 SSLClientSocketOpenSSL::SSLContext::GetInstance();
345 context
->session_cache()->Flush();
349 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
350 return SSL_PROTOCOL_VERSION_TLS1_2
;
353 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
354 scoped_ptr
<ClientSocketHandle
> transport_socket
,
355 const HostPortPair
& host_and_port
,
356 const SSLConfig
& ssl_config
,
357 const SSLClientSocketContext
& context
)
358 : transport_send_busy_(false),
359 transport_recv_busy_(false),
360 pending_read_error_(kNoPendingReadResult
),
361 pending_read_ssl_error_(SSL_ERROR_NONE
),
362 transport_read_error_(OK
),
363 transport_write_error_(OK
),
364 server_cert_chain_(new PeerCertificateChain(NULL
)),
365 completed_connect_(false),
366 was_ever_used_(false),
367 client_auth_cert_needed_(false),
368 cert_verifier_(context
.cert_verifier
),
369 cert_transparency_verifier_(context
.cert_transparency_verifier
),
370 channel_id_service_(context
.channel_id_service
),
372 transport_bio_(NULL
),
373 transport_(transport_socket
.Pass()),
374 host_and_port_(host_and_port
),
375 ssl_config_(ssl_config
),
376 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
377 trying_cached_session_(false),
378 next_handshake_state_(STATE_NONE
),
379 npn_status_(kNextProtoUnsupported
),
380 channel_id_xtn_negotiated_(false),
381 handshake_succeeded_(false),
382 marked_session_as_good_(false),
383 transport_security_state_(context
.transport_security_state
),
384 policy_enforcer_(context
.cert_policy_enforcer
),
385 net_log_(transport_
->socket()->NetLog()),
386 weak_factory_(this) {
389 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
393 std::string
SSLClientSocketOpenSSL::GetSessionCacheKey() const {
394 std::string result
= host_and_port_
.ToString();
396 result
.append(ssl_session_cache_shard_
);
400 bool SSLClientSocketOpenSSL::InSessionCache() const {
401 SSLContext
* context
= SSLContext::GetInstance();
402 std::string cache_key
= GetSessionCacheKey();
403 return context
->session_cache()->SSLSessionIsInCache(cache_key
);
406 void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
407 const base::Closure
& callback
) {
408 handshake_completion_callback_
= callback
;
411 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
412 SSLCertRequestInfo
* cert_request_info
) {
413 cert_request_info
->host_and_port
= host_and_port_
;
414 cert_request_info
->cert_authorities
= cert_authorities_
;
415 cert_request_info
->cert_key_types
= cert_key_types_
;
418 SSLClientSocket::NextProtoStatus
SSLClientSocketOpenSSL::GetNextProto(
419 std::string
* proto
) {
425 SSLClientSocketOpenSSL::GetChannelIDService() const {
426 return channel_id_service_
;
429 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
430 const base::StringPiece
& label
,
431 bool has_context
, const base::StringPiece
& context
,
432 unsigned char* out
, unsigned int outlen
) {
433 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
435 int rv
= SSL_export_keying_material(
436 ssl_
, out
, outlen
, label
.data(), label
.size(),
437 reinterpret_cast<const unsigned char*>(context
.data()),
438 context
.length(), context
.length() > 0);
441 int ssl_error
= SSL_get_error(ssl_
, rv
);
442 LOG(ERROR
) << "Failed to export keying material;"
443 << " returned " << rv
444 << ", SSL error code " << ssl_error
;
445 return MapOpenSSLError(ssl_error
, err_tracer
);
450 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string
* out
) {
452 return ERR_NOT_IMPLEMENTED
;
455 int SSLClientSocketOpenSSL::Connect(const CompletionCallback
& callback
) {
456 // It is an error to create an SSLClientSocket whose context has no
457 // TransportSecurityState.
458 DCHECK(transport_security_state_
);
460 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
462 // Set up new ssl object.
465 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
469 // Set SSL to client mode. Handshake happens in the loop below.
470 SSL_set_connect_state(ssl_
);
472 GotoState(STATE_HANDSHAKE
);
473 rv
= DoHandshakeLoop(OK
);
474 if (rv
== ERR_IO_PENDING
) {
475 user_connect_callback_
= callback
;
477 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
479 OnHandshakeCompletion();
482 return rv
> OK
? OK
: rv
;
485 void SSLClientSocketOpenSSL::Disconnect() {
486 // If a handshake was pending (Connect() had been called), notify interested
487 // parties that it's been aborted now. If the handshake had already
488 // completed, this is a no-op.
489 OnHandshakeCompletion();
491 // Calling SSL_shutdown prevents the session from being marked as
497 if (transport_bio_
) {
498 BIO_free_all(transport_bio_
);
499 transport_bio_
= NULL
;
502 // Shut down anything that may call us back.
504 transport_
->socket()->Disconnect();
506 // Null all callbacks, delete all buffers.
507 transport_send_busy_
= false;
509 transport_recv_busy_
= false;
512 user_connect_callback_
.Reset();
513 user_read_callback_
.Reset();
514 user_write_callback_
.Reset();
515 user_read_buf_
= NULL
;
516 user_read_buf_len_
= 0;
517 user_write_buf_
= NULL
;
518 user_write_buf_len_
= 0;
520 pending_read_error_
= kNoPendingReadResult
;
521 pending_read_ssl_error_
= SSL_ERROR_NONE
;
522 pending_read_error_info_
= OpenSSLErrorInfo();
524 transport_read_error_
= OK
;
525 transport_write_error_
= OK
;
527 server_cert_verify_result_
.Reset();
528 completed_connect_
= false;
530 cert_authorities_
.clear();
531 cert_key_types_
.clear();
532 client_auth_cert_needed_
= false;
534 start_cert_verification_time_
= base::TimeTicks();
536 npn_status_
= kNextProtoUnsupported
;
539 channel_id_xtn_negotiated_
= false;
540 channel_id_request_handle_
.Cancel();
543 bool SSLClientSocketOpenSSL::IsConnected() const {
544 // If the handshake has not yet completed.
545 if (!completed_connect_
)
547 // If an asynchronous operation is still pending.
548 if (user_read_buf_
.get() || user_write_buf_
.get())
551 return transport_
->socket()->IsConnected();
554 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
555 // If the handshake has not yet completed.
556 if (!completed_connect_
)
558 // If an asynchronous operation is still pending.
559 if (user_read_buf_
.get() || user_write_buf_
.get())
561 // If there is data waiting to be sent, or data read from the network that
562 // has not yet been consumed.
563 if (BIO_pending(transport_bio_
) > 0 ||
564 BIO_wpending(transport_bio_
) > 0) {
568 return transport_
->socket()->IsConnectedAndIdle();
571 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint
* addressList
) const {
572 return transport_
->socket()->GetPeerAddress(addressList
);
575 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint
* addressList
) const {
576 return transport_
->socket()->GetLocalAddress(addressList
);
579 const BoundNetLog
& SSLClientSocketOpenSSL::NetLog() const {
583 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
584 if (transport_
.get() && transport_
->socket()) {
585 transport_
->socket()->SetSubresourceSpeculation();
591 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
592 if (transport_
.get() && transport_
->socket()) {
593 transport_
->socket()->SetOmniboxSpeculation();
599 bool SSLClientSocketOpenSSL::WasEverUsed() const {
600 return was_ever_used_
;
603 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
604 if (transport_
.get() && transport_
->socket())
605 return transport_
->socket()->UsingTCPFastOpen();
611 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo
* ssl_info
) {
613 if (server_cert_chain_
->empty())
616 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
617 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
618 ssl_info
->is_issued_by_known_root
=
619 server_cert_verify_result_
.is_issued_by_known_root
;
620 ssl_info
->public_key_hashes
=
621 server_cert_verify_result_
.public_key_hashes
;
622 ssl_info
->client_cert_sent
=
623 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
624 ssl_info
->channel_id_sent
= WasChannelIDSent();
625 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
627 AddSCTInfoToSSLInfo(ssl_info
);
629 const SSL_CIPHER
* cipher
= SSL_get_current_cipher(ssl_
);
631 ssl_info
->security_bits
= SSL_CIPHER_get_bits(cipher
, NULL
);
633 ssl_info
->connection_status
= EncodeSSLConnectionStatus(
634 static_cast<uint16
>(SSL_CIPHER_get_id(cipher
)), 0 /* no compression */,
635 GetNetSSLVersion(ssl_
));
637 if (!SSL_get_secure_renegotiation_support(ssl_
))
638 ssl_info
->connection_status
|= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
640 if (ssl_config_
.version_fallback
)
641 ssl_info
->connection_status
|= SSL_CONNECTION_VERSION_FALLBACK
;
643 ssl_info
->handshake_type
= SSL_session_reused(ssl_
) ?
644 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
646 DVLOG(3) << "Encoded connection status: cipher suite = "
647 << SSLConnectionStatusToCipherSuite(ssl_info
->connection_status
)
649 << SSLConnectionStatusToVersion(ssl_info
->connection_status
);
653 int SSLClientSocketOpenSSL::Read(IOBuffer
* buf
,
655 const CompletionCallback
& callback
) {
656 user_read_buf_
= buf
;
657 user_read_buf_len_
= buf_len
;
659 int rv
= DoReadLoop();
661 if (rv
== ERR_IO_PENDING
) {
662 user_read_callback_
= callback
;
665 was_ever_used_
= true;
666 user_read_buf_
= NULL
;
667 user_read_buf_len_
= 0;
669 // Failure of a read attempt may indicate a failed false start
671 OnHandshakeCompletion();
678 int SSLClientSocketOpenSSL::Write(IOBuffer
* buf
,
680 const CompletionCallback
& callback
) {
681 user_write_buf_
= buf
;
682 user_write_buf_len_
= buf_len
;
684 int rv
= DoWriteLoop();
686 if (rv
== ERR_IO_PENDING
) {
687 user_write_callback_
= callback
;
690 was_ever_used_
= true;
691 user_write_buf_
= NULL
;
692 user_write_buf_len_
= 0;
694 // Failure of a write attempt may indicate a failed false start
696 OnHandshakeCompletion();
703 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size
) {
704 return transport_
->socket()->SetReceiveBufferSize(size
);
707 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size
) {
708 return transport_
->socket()->SetSendBufferSize(size
);
711 int SSLClientSocketOpenSSL::Init() {
713 DCHECK(!transport_bio_
);
715 SSLContext
* context
= SSLContext::GetInstance();
716 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
718 ssl_
= SSL_new(context
->ssl_ctx());
719 if (!ssl_
|| !context
->SetClientSocketForSSL(ssl_
, this))
720 return ERR_UNEXPECTED
;
722 if (!SSL_set_tlsext_host_name(ssl_
, host_and_port_
.host().c_str()))
723 return ERR_UNEXPECTED
;
725 // Set an OpenSSL callback to monitor this SSL*'s connection.
726 SSL_set_info_callback(ssl_
, &InfoCallback
);
728 trying_cached_session_
= context
->session_cache()->SetSSLSessionWithKey(
729 ssl_
, GetSessionCacheKey());
732 // 0 => use default buffer sizes.
733 if (!BIO_new_bio_pair(&ssl_bio
, 0, &transport_bio_
, 0))
734 return ERR_UNEXPECTED
;
736 DCHECK(transport_bio_
);
738 // Install a callback on OpenSSL's end to plumb transport errors through.
739 BIO_set_callback(ssl_bio
, BIOCallback
);
740 BIO_set_callback_arg(ssl_bio
, reinterpret_cast<char*>(this));
742 SSL_set_bio(ssl_
, ssl_bio
, ssl_bio
);
744 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
745 // set everything we care about to an absolute value.
746 SslSetClearMask options
;
747 options
.ConfigureFlag(SSL_OP_NO_SSLv2
, true);
748 bool ssl3_enabled
= (ssl_config_
.version_min
== SSL_PROTOCOL_VERSION_SSL3
);
749 options
.ConfigureFlag(SSL_OP_NO_SSLv3
, !ssl3_enabled
);
750 bool tls1_enabled
= (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1
&&
751 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1
);
752 options
.ConfigureFlag(SSL_OP_NO_TLSv1
, !tls1_enabled
);
753 bool tls1_1_enabled
=
754 (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1_1
&&
755 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
);
756 options
.ConfigureFlag(SSL_OP_NO_TLSv1_1
, !tls1_1_enabled
);
757 bool tls1_2_enabled
=
758 (ssl_config_
.version_min
<= SSL_PROTOCOL_VERSION_TLS1_2
&&
759 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_2
);
760 options
.ConfigureFlag(SSL_OP_NO_TLSv1_2
, !tls1_2_enabled
);
762 options
.ConfigureFlag(SSL_OP_NO_COMPRESSION
, true);
764 // TODO(joth): Set this conditionally, see http://crbug.com/55410
765 options
.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT
, true);
767 SSL_set_options(ssl_
, options
.set_mask
);
768 SSL_clear_options(ssl_
, options
.clear_mask
);
770 // Same as above, this time for the SSL mode.
771 SslSetClearMask mode
;
773 mode
.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS
, true);
774 mode
.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING
, true);
776 mode
.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH
,
777 ssl_config_
.false_start_enabled
);
779 SSL_set_mode(ssl_
, mode
.set_mask
);
780 SSL_clear_mode(ssl_
, mode
.clear_mask
);
782 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
783 // textual name with SSL_set_cipher_list because there is no public API to
784 // directly remove a cipher by ID.
785 STACK_OF(SSL_CIPHER
)* ciphers
= SSL_get_ciphers(ssl_
);
787 // See SSLConfig::disabled_cipher_suites for description of the suites
788 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
789 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
790 // as the handshake hash.
791 std::string
command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
792 "!aECDH:!AESGCM+AES256");
793 // Walk through all the installed ciphers, seeing if any need to be
794 // appended to the cipher removal |command|.
795 for (size_t i
= 0; i
< sk_SSL_CIPHER_num(ciphers
); ++i
) {
796 const SSL_CIPHER
* cipher
= sk_SSL_CIPHER_value(ciphers
, i
);
797 const uint16 id
= static_cast<uint16
>(SSL_CIPHER_get_id(cipher
));
798 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
799 // implementation uses "effective" bits here but OpenSSL does not provide
800 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
801 // both of which are greater than 80 anyway.
802 bool disable
= SSL_CIPHER_get_bits(cipher
, NULL
) < 80;
804 disable
= std::find(ssl_config_
.disabled_cipher_suites
.begin(),
805 ssl_config_
.disabled_cipher_suites
.end(), id
) !=
806 ssl_config_
.disabled_cipher_suites
.end();
809 const char* name
= SSL_CIPHER_get_name(cipher
);
810 DVLOG(3) << "Found cipher to remove: '" << name
<< "', ID: " << id
811 << " strength: " << SSL_CIPHER_get_bits(cipher
, NULL
);
812 command
.append(":!");
813 command
.append(name
);
817 // Disable ECDSA cipher suites on platforms that do not support ECDSA
818 // signed certificates, as servers may use the presence of such
819 // ciphersuites as a hint to send an ECDSA certificate.
821 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
822 command
.append(":!ECDSA");
825 int rv
= SSL_set_cipher_list(ssl_
, command
.c_str());
826 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
827 // This will almost certainly result in the socket failing to complete the
828 // handshake at which point the appropriate error is bubbled up to the client.
829 LOG_IF(WARNING
, rv
!= 1) << "SSL_set_cipher_list('" << command
<< "') "
832 if (ssl_config_
.version_fallback
)
833 SSL_enable_fallback_scsv(ssl_
);
836 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
837 SSL_enable_tls_channel_id(ssl_
);
840 if (!ssl_config_
.next_protos
.empty()) {
841 std::vector
<uint8_t> wire_protos
=
842 SerializeNextProtos(ssl_config_
.next_protos
);
843 SSL_set_alpn_protos(ssl_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
847 if (ssl_config_
.signed_cert_timestamps_enabled
) {
848 SSL_enable_signed_cert_timestamps(ssl_
);
849 SSL_enable_ocsp_stapling(ssl_
);
852 if (IsOCSPStaplingSupported())
853 SSL_enable_ocsp_stapling(ssl_
);
858 void SSLClientSocketOpenSSL::DoReadCallback(int rv
) {
859 // Since Run may result in Read being called, clear |user_read_callback_|
862 was_ever_used_
= true;
863 user_read_buf_
= NULL
;
864 user_read_buf_len_
= 0;
866 // Failure of a read attempt may indicate a failed false start
868 OnHandshakeCompletion();
870 base::ResetAndReturn(&user_read_callback_
).Run(rv
);
873 void SSLClientSocketOpenSSL::DoWriteCallback(int rv
) {
874 // Since Run may result in Write being called, clear |user_write_callback_|
877 was_ever_used_
= true;
878 user_write_buf_
= NULL
;
879 user_write_buf_len_
= 0;
881 // Failure of a write attempt may indicate a failed false start
883 OnHandshakeCompletion();
885 base::ResetAndReturn(&user_write_callback_
).Run(rv
);
888 void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
889 if (!handshake_completion_callback_
.is_null())
890 base::ResetAndReturn(&handshake_completion_callback_
).Run();
893 bool SSLClientSocketOpenSSL::DoTransportIO() {
894 bool network_moved
= false;
896 // Read and write as much data as possible. The loop is necessary because
897 // Write() may return synchronously.
900 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
901 network_moved
= true;
903 if (transport_read_error_
== OK
&& BufferRecv() != ERR_IO_PENDING
)
904 network_moved
= true;
905 return network_moved
;
908 int SSLClientSocketOpenSSL::DoHandshake() {
909 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
910 tracked_objects::ScopedTracker
tracking_profile1(
911 FROM_HERE_WITH_EXPLICIT_FUNCTION(
912 "424386 SSLClientSocketOpenSSL::DoHandshake1"));
914 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
916 int rv
= SSL_do_handshake(ssl_
);
918 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
919 tracked_objects::ScopedTracker
tracking_profile2(
920 FROM_HERE_WITH_EXPLICIT_FUNCTION(
921 "424386 SSLClientSocketOpenSSL::DoHandshake2"));
923 if (client_auth_cert_needed_
) {
924 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
925 // If the handshake already succeeded (because the server requests but
926 // doesn't require a client cert), we need to invalidate the SSL session
927 // so that we won't try to resume the non-client-authenticated session in
928 // the next handshake. This will cause the server to ask for a client
931 // Remove from session cache but don't clear this connection.
932 SSL_SESSION
* session
= SSL_get_session(ssl_
);
934 int rv
= SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_
), session
);
935 LOG_IF(WARNING
, !rv
) << "Couldn't invalidate SSL session: " << session
;
938 } else if (rv
== 1) {
939 if (trying_cached_session_
&& logging::DEBUG_MODE
) {
940 DVLOG(2) << "Result of session reuse for " << host_and_port_
.ToString()
941 << " is: " << (SSL_session_reused(ssl_
) ? "Success" : "Fail");
944 if (ssl_config_
.version_fallback
&&
945 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
946 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
949 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
950 if (npn_status_
== kNextProtoUnsupported
) {
951 const uint8_t* alpn_proto
= NULL
;
952 unsigned alpn_len
= 0;
953 SSL_get0_alpn_selected(ssl_
, &alpn_proto
, &alpn_len
);
955 npn_proto_
.assign(reinterpret_cast<const char*>(alpn_proto
), alpn_len
);
956 npn_status_
= kNextProtoNegotiated
;
957 set_negotiation_extension(kExtensionALPN
);
961 RecordChannelIDSupport(channel_id_service_
,
962 channel_id_xtn_negotiated_
,
963 ssl_config_
.channel_id_enabled
,
964 crypto::ECPrivateKey::IsSupported());
966 // Only record OCSP histograms if OCSP was requested.
967 if (ssl_config_
.signed_cert_timestamps_enabled
||
968 IsOCSPStaplingSupported()) {
969 const uint8_t* ocsp_response
;
970 size_t ocsp_response_len
;
971 SSL_get0_ocsp_response(ssl_
, &ocsp_response
, &ocsp_response_len
);
973 set_stapled_ocsp_response_received(ocsp_response_len
!= 0);
974 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len
!= 0);
977 const uint8_t* sct_list
;
979 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list
, &sct_list_len
);
980 set_signed_cert_timestamps_received(sct_list_len
!= 0);
982 // Verify the certificate.
984 GotoState(STATE_VERIFY_CERT
);
986 int ssl_error
= SSL_get_error(ssl_
, rv
);
988 if (ssl_error
== SSL_ERROR_WANT_CHANNEL_ID_LOOKUP
) {
989 // The server supports channel ID. Stop to look one up before returning to
991 channel_id_xtn_negotiated_
= true;
992 GotoState(STATE_CHANNEL_ID_LOOKUP
);
996 OpenSSLErrorInfo error_info
;
997 net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
, &error_info
);
999 // If not done, stay in this state
1000 if (net_error
== ERR_IO_PENDING
) {
1001 GotoState(STATE_HANDSHAKE
);
1003 LOG(ERROR
) << "handshake failed; returned " << rv
1004 << ", SSL error code " << ssl_error
1005 << ", net_error " << net_error
;
1007 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1008 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1014 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1015 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE
);
1016 return channel_id_service_
->GetOrCreateChannelID(
1017 host_and_port_
.host(),
1018 &channel_id_private_key_
,
1020 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1021 base::Unretained(this)),
1022 &channel_id_request_handle_
);
1025 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result
) {
1029 DCHECK_LT(0u, channel_id_private_key_
.size());
1031 std::vector
<uint8
> encrypted_private_key_info
;
1032 std::vector
<uint8
> subject_public_key_info
;
1033 encrypted_private_key_info
.assign(
1034 channel_id_private_key_
.data(),
1035 channel_id_private_key_
.data() + channel_id_private_key_
.size());
1036 subject_public_key_info
.assign(
1037 channel_id_cert_
.data(),
1038 channel_id_cert_
.data() + channel_id_cert_
.size());
1039 scoped_ptr
<crypto::ECPrivateKey
> ec_private_key(
1040 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1041 ChannelIDService::kEPKIPassword
,
1042 encrypted_private_key_info
,
1043 subject_public_key_info
));
1044 if (!ec_private_key
) {
1045 LOG(ERROR
) << "Failed to import Channel ID.";
1046 return ERR_CHANNEL_ID_IMPORT_FAILED
;
1049 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1051 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1052 int rv
= SSL_set1_tls_channel_id(ssl_
, ec_private_key
->key());
1054 LOG(ERROR
) << "Failed to set Channel ID.";
1055 int err
= SSL_get_error(ssl_
, rv
);
1056 return MapOpenSSLError(err
, err_tracer
);
1059 // Return to the handshake.
1060 set_channel_id_sent(true);
1061 GotoState(STATE_HANDSHAKE
);
1065 int SSLClientSocketOpenSSL::DoVerifyCert(int result
) {
1066 DCHECK(!server_cert_chain_
->empty());
1067 DCHECK(start_cert_verification_time_
.is_null());
1069 GotoState(STATE_VERIFY_CERT_COMPLETE
);
1071 // If the certificate is bad and has been previously accepted, use
1072 // the previous status and bypass the error.
1073 base::StringPiece der_cert
;
1074 if (!x509_util::GetDER(server_cert_chain_
->Get(0), &der_cert
)) {
1076 return ERR_CERT_INVALID
;
1078 CertStatus cert_status
;
1079 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
1080 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
1081 server_cert_verify_result_
.Reset();
1082 server_cert_verify_result_
.cert_status
= cert_status
;
1083 server_cert_verify_result_
.verified_cert
= server_cert_
;
1087 // When running in a sandbox, it may not be possible to create an
1088 // X509Certificate*, as that may depend on OS functionality blocked
1090 if (!server_cert_
.get()) {
1091 server_cert_verify_result_
.Reset();
1092 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
1093 return ERR_CERT_INVALID
;
1096 start_cert_verification_time_
= base::TimeTicks::Now();
1099 if (ssl_config_
.rev_checking_enabled
)
1100 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
1101 if (ssl_config_
.verify_ev_cert
)
1102 flags
|= CertVerifier::VERIFY_EV_CERT
;
1103 if (ssl_config_
.cert_io_enabled
)
1104 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
1105 if (ssl_config_
.rev_checking_required_local_anchors
)
1106 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
1107 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
1108 return verifier_
->Verify(
1110 host_and_port_
.host(),
1112 // TODO(davidben): Route the CRLSet through SSLConfig so
1113 // SSLClientSocket doesn't depend on SSLConfigService.
1114 SSLConfigService::GetCRLSet().get(),
1115 &server_cert_verify_result_
,
1116 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete
,
1117 base::Unretained(this)),
1121 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result
) {
1124 if (!start_cert_verification_time_
.is_null()) {
1125 base::TimeDelta verify_time
=
1126 base::TimeTicks::Now() - start_cert_verification_time_
;
1128 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
1130 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
1135 RecordConnectionTypeMetrics(GetNetSSLVersion(ssl_
));
1137 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
1138 if (transport_security_state_
&&
1140 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
1141 !transport_security_state_
->CheckPublicKeyPins(
1142 host_and_port_
.host(),
1143 server_cert_verify_result_
.is_issued_by_known_root
,
1144 server_cert_verify_result_
.public_key_hashes
,
1145 &pinning_failure_log_
)) {
1146 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
1150 // Only check Certificate Transparency if there were no other errors with
1154 // TODO(joth): Work out if we need to remember the intermediate CA certs
1155 // when the server sends them to us, and do so here.
1156 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_
);
1157 marked_session_as_good_
= true;
1158 CheckIfHandshakeFinished();
1160 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result
)
1161 << " (" << result
<< ")";
1164 completed_connect_
= true;
1166 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1167 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1171 void SSLClientSocketOpenSSL::DoConnectCallback(int rv
) {
1173 OnHandshakeCompletion();
1174 if (!user_connect_callback_
.is_null()) {
1175 CompletionCallback c
= user_connect_callback_
;
1176 user_connect_callback_
.Reset();
1177 c
.Run(rv
> OK
? OK
: rv
);
1181 void SSLClientSocketOpenSSL::UpdateServerCert() {
1182 server_cert_chain_
->Reset(SSL_get_peer_cert_chain(ssl_
));
1183 server_cert_
= server_cert_chain_
->AsOSChain();
1185 if (server_cert_
.get()) {
1187 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
1188 base::Bind(&NetLogX509CertificateCallback
,
1189 base::Unretained(server_cert_
.get())));
1191 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1192 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1193 if (IsOCSPStaplingSupported()) {
1195 const uint8_t* ocsp_response_raw
;
1196 size_t ocsp_response_len
;
1197 SSL_get0_ocsp_response(ssl_
, &ocsp_response_raw
, &ocsp_response_len
);
1199 CRYPT_DATA_BLOB ocsp_response_blob
;
1200 ocsp_response_blob
.cbData
= ocsp_response_len
;
1201 ocsp_response_blob
.pbData
= const_cast<BYTE
*>(ocsp_response_raw
);
1202 BOOL ok
= CertSetCertificateContextProperty(
1203 server_cert_
->os_cert_handle(),
1204 CERT_OCSP_RESPONSE_PROP_ID
,
1205 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
1206 &ocsp_response_blob
);
1208 VLOG(1) << "Failed to set OCSP response property: "
1218 void SSLClientSocketOpenSSL::VerifyCT() {
1219 if (!cert_transparency_verifier_
)
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
);
1225 std::string ocsp_response
;
1226 if (ocsp_response_len
> 0) {
1227 ocsp_response
.assign(reinterpret_cast<const char*>(ocsp_response_raw
),
1231 const uint8_t* sct_list_raw
;
1232 size_t sct_list_len
;
1233 SSL_get0_signed_cert_timestamp_list(ssl_
, &sct_list_raw
, &sct_list_len
);
1234 std::string sct_list
;
1235 if (sct_list_len
> 0)
1236 sct_list
.assign(reinterpret_cast<const char*>(sct_list_raw
), sct_list_len
);
1238 // Note that this is a completely synchronous operation: The CT Log Verifier
1239 // gets all the data it needs for SCT verification and does not do any
1240 // external communication.
1241 cert_transparency_verifier_
->Verify(
1242 server_cert_verify_result_
.verified_cert
.get(), ocsp_response
, sct_list
,
1243 &ct_verify_result_
, net_log_
);
1245 if (!policy_enforcer_
) {
1246 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1248 if (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
) {
1249 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
1250 SSLConfigService::GetEVCertsWhitelist();
1251 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
1252 server_cert_verify_result_
.verified_cert
.get(),
1253 ev_whitelist
.get(), ct_verify_result_
)) {
1254 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1255 VLOG(1) << "EV certificate for "
1256 << server_cert_verify_result_
.verified_cert
->subject()
1258 << " does not conform to CT policy, removing EV status.";
1259 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
1265 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result
) {
1266 int rv
= DoHandshakeLoop(result
);
1267 if (rv
!= ERR_IO_PENDING
) {
1268 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
1269 DoConnectCallback(rv
);
1273 void SSLClientSocketOpenSSL::OnSendComplete(int result
) {
1274 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1275 // In handshake phase.
1276 OnHandshakeIOComplete(result
);
1280 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1281 // handshake is in progress.
1282 int rv_read
= ERR_IO_PENDING
;
1283 int rv_write
= ERR_IO_PENDING
;
1286 if (user_read_buf_
.get())
1287 rv_read
= DoPayloadRead();
1288 if (user_write_buf_
.get())
1289 rv_write
= DoPayloadWrite();
1290 network_moved
= DoTransportIO();
1291 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1292 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1294 // Performing the Read callback may cause |this| to be deleted. If this
1295 // happens, the Write callback should not be invoked. Guard against this by
1296 // holding a WeakPtr to |this| and ensuring it's still valid.
1297 base::WeakPtr
<SSLClientSocketOpenSSL
> guard(weak_factory_
.GetWeakPtr());
1298 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1299 DoReadCallback(rv_read
);
1304 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1305 DoWriteCallback(rv_write
);
1308 void SSLClientSocketOpenSSL::OnRecvComplete(int result
) {
1309 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1310 // In handshake phase.
1311 OnHandshakeIOComplete(result
);
1315 // Network layer received some data, check if client requested to read
1317 if (!user_read_buf_
.get())
1320 int rv
= DoReadLoop();
1321 if (rv
!= ERR_IO_PENDING
)
1325 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result
) {
1326 int rv
= last_io_result
;
1328 // Default to STATE_NONE for next state.
1329 // (This is a quirk carried over from the windows
1330 // implementation. It makes reading the logs a bit harder.)
1331 // State handlers can and often do call GotoState just
1332 // to stay in the current state.
1333 State state
= next_handshake_state_
;
1334 GotoState(STATE_NONE
);
1336 case STATE_HANDSHAKE
:
1339 case STATE_CHANNEL_ID_LOOKUP
:
1341 rv
= DoChannelIDLookup();
1343 case STATE_CHANNEL_ID_LOOKUP_COMPLETE
:
1344 rv
= DoChannelIDLookupComplete(rv
);
1346 case STATE_VERIFY_CERT
:
1348 rv
= DoVerifyCert(rv
);
1350 case STATE_VERIFY_CERT_COMPLETE
:
1351 rv
= DoVerifyCertComplete(rv
);
1355 rv
= ERR_UNEXPECTED
;
1356 NOTREACHED() << "unexpected state" << state
;
1360 bool network_moved
= DoTransportIO();
1361 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1362 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1363 // special case we keep looping even if rv is ERR_IO_PENDING because
1364 // the transport IO may allow DoHandshake to make progress.
1365 rv
= OK
; // This causes us to stay in the loop.
1367 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1372 int SSLClientSocketOpenSSL::DoReadLoop() {
1376 rv
= DoPayloadRead();
1377 network_moved
= DoTransportIO();
1378 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1383 int SSLClientSocketOpenSSL::DoWriteLoop() {
1387 rv
= DoPayloadWrite();
1388 network_moved
= DoTransportIO();
1389 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1394 int SSLClientSocketOpenSSL::DoPayloadRead() {
1395 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1398 if (pending_read_error_
!= kNoPendingReadResult
) {
1399 rv
= pending_read_error_
;
1400 pending_read_error_
= kNoPendingReadResult
;
1402 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
1403 rv
, user_read_buf_
->data());
1406 NetLog::TYPE_SSL_READ_ERROR
,
1407 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1408 pending_read_error_info_
));
1410 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1411 pending_read_error_info_
= OpenSSLErrorInfo();
1415 int total_bytes_read
= 0;
1417 rv
= SSL_read(ssl_
, user_read_buf_
->data() + total_bytes_read
,
1418 user_read_buf_len_
- total_bytes_read
);
1420 total_bytes_read
+= rv
;
1421 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
1423 if (total_bytes_read
== user_read_buf_len_
) {
1424 rv
= total_bytes_read
;
1426 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1427 // immediately, while the OpenSSL errors are still available in
1428 // thread-local storage. However, the handled/remapped error code should
1429 // only be returned if no application data was already read; if it was, the
1430 // error code should be deferred until the next call of DoPayloadRead.
1432 // If no data was read, |*next_result| will point to the return value of
1433 // this function. If at least some data was read, |*next_result| will point
1434 // to |pending_read_error_|, to be returned in a future call to
1435 // DoPayloadRead() (e.g.: after the current data is handled).
1436 int *next_result
= &rv
;
1437 if (total_bytes_read
> 0) {
1438 pending_read_error_
= rv
;
1439 rv
= total_bytes_read
;
1440 next_result
= &pending_read_error_
;
1443 if (client_auth_cert_needed_
) {
1444 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1445 } else if (*next_result
< 0) {
1446 pending_read_ssl_error_
= SSL_get_error(ssl_
, *next_result
);
1447 *next_result
= MapOpenSSLErrorWithDetails(pending_read_ssl_error_
,
1449 &pending_read_error_info_
);
1451 // Many servers do not reliably send a close_notify alert when shutting
1452 // down a connection, and instead terminate the TCP connection. This is
1453 // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1454 // shutdown to a graceful EOF, instead of treating it as an error as it
1456 if (*next_result
== ERR_CONNECTION_CLOSED
)
1459 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
1460 // If at least some data was read from SSL_read(), do not treat
1461 // insufficient data as an error to return in the next call to
1462 // DoPayloadRead() - instead, let the call fall through to check
1463 // SSL_read() again. This is because DoTransportIO() may complete
1464 // in between the next call to DoPayloadRead(), and thus it is
1465 // important to check SSL_read() on subsequent invocations to see
1466 // if a complete record may now be read.
1467 *next_result
= kNoPendingReadResult
;
1473 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1474 user_read_buf_
->data());
1475 } else if (rv
!= ERR_IO_PENDING
) {
1477 NetLog::TYPE_SSL_READ_ERROR
,
1478 CreateNetLogOpenSSLErrorCallback(rv
, pending_read_ssl_error_
,
1479 pending_read_error_info_
));
1480 pending_read_ssl_error_
= SSL_ERROR_NONE
;
1481 pending_read_error_info_
= OpenSSLErrorInfo();
1486 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1487 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
1488 int rv
= SSL_write(ssl_
, user_write_buf_
->data(), user_write_buf_len_
);
1490 net_log_
.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1491 user_write_buf_
->data());
1495 int ssl_error
= SSL_get_error(ssl_
, rv
);
1496 OpenSSLErrorInfo error_info
;
1497 int net_error
= MapOpenSSLErrorWithDetails(ssl_error
, err_tracer
,
1500 if (net_error
!= ERR_IO_PENDING
) {
1502 NetLog::TYPE_SSL_WRITE_ERROR
,
1503 CreateNetLogOpenSSLErrorCallback(net_error
, ssl_error
, error_info
));
1508 int SSLClientSocketOpenSSL::BufferSend(void) {
1509 if (transport_send_busy_
)
1510 return ERR_IO_PENDING
;
1512 if (!send_buffer_
.get()) {
1513 // Get a fresh send buffer out of the send BIO.
1514 size_t max_read
= BIO_pending(transport_bio_
);
1516 return 0; // Nothing pending in the OpenSSL write BIO.
1517 send_buffer_
= new DrainableIOBuffer(new IOBuffer(max_read
), max_read
);
1518 int read_bytes
= BIO_read(transport_bio_
, send_buffer_
->data(), max_read
);
1519 DCHECK_GT(read_bytes
, 0);
1520 CHECK_EQ(static_cast<int>(max_read
), read_bytes
);
1523 int rv
= transport_
->socket()->Write(
1525 send_buffer_
->BytesRemaining(),
1526 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete
,
1527 base::Unretained(this)));
1528 if (rv
== ERR_IO_PENDING
) {
1529 transport_send_busy_
= true;
1531 TransportWriteComplete(rv
);
1536 int SSLClientSocketOpenSSL::BufferRecv(void) {
1537 if (transport_recv_busy_
)
1538 return ERR_IO_PENDING
;
1540 // Determine how much was requested from |transport_bio_| that was not
1541 // actually available.
1542 size_t requested
= BIO_ctrl_get_read_request(transport_bio_
);
1543 if (requested
== 0) {
1544 // This is not a perfect match of error codes, as no operation is
1545 // actually pending. However, returning 0 would be interpreted as
1546 // a possible sign of EOF, which is also an inappropriate match.
1547 return ERR_IO_PENDING
;
1550 // Known Issue: While only reading |requested| data is the more correct
1551 // implementation, it has the downside of resulting in frequent reads:
1552 // One read for the SSL record header (~5 bytes) and one read for the SSL
1553 // record body. Rather than issuing these reads to the underlying socket
1554 // (and constantly allocating new IOBuffers), a single Read() request to
1555 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1556 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1557 // traffic, this over-subscribed Read()ing will not cause issues.
1558 size_t max_write
= BIO_ctrl_get_write_guarantee(transport_bio_
);
1560 return ERR_IO_PENDING
;
1562 recv_buffer_
= new IOBuffer(max_write
);
1563 int rv
= transport_
->socket()->Read(
1566 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete
,
1567 base::Unretained(this)));
1568 if (rv
== ERR_IO_PENDING
) {
1569 transport_recv_busy_
= true;
1571 rv
= TransportReadComplete(rv
);
1576 void SSLClientSocketOpenSSL::BufferSendComplete(int result
) {
1577 transport_send_busy_
= false;
1578 TransportWriteComplete(result
);
1579 OnSendComplete(result
);
1582 void SSLClientSocketOpenSSL::BufferRecvComplete(int result
) {
1583 result
= TransportReadComplete(result
);
1584 OnRecvComplete(result
);
1587 void SSLClientSocketOpenSSL::TransportWriteComplete(int result
) {
1588 DCHECK(ERR_IO_PENDING
!= result
);
1590 // Record the error. Save it to be reported in a future read or write on
1591 // transport_bio_'s peer.
1592 transport_write_error_
= result
;
1593 send_buffer_
= NULL
;
1595 DCHECK(send_buffer_
.get());
1596 send_buffer_
->DidConsume(result
);
1597 DCHECK_GE(send_buffer_
->BytesRemaining(), 0);
1598 if (send_buffer_
->BytesRemaining() <= 0)
1599 send_buffer_
= NULL
;
1603 int SSLClientSocketOpenSSL::TransportReadComplete(int result
) {
1604 DCHECK(ERR_IO_PENDING
!= result
);
1605 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1606 // does not report success.
1608 result
= ERR_CONNECTION_CLOSED
;
1610 DVLOG(1) << "TransportReadComplete result " << result
;
1611 // Received an error. Save it to be reported in a future read on
1612 // transport_bio_'s peer.
1613 transport_read_error_
= result
;
1615 DCHECK(recv_buffer_
.get());
1616 int ret
= BIO_write(transport_bio_
, recv_buffer_
->data(), result
);
1617 // A write into a memory BIO should always succeed.
1618 DCHECK_EQ(result
, ret
);
1620 recv_buffer_
= NULL
;
1621 transport_recv_busy_
= false;
1625 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL
* ssl
) {
1626 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1627 tracked_objects::ScopedTracker
tracking_profile(
1628 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1629 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1631 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1632 DCHECK(ssl
== ssl_
);
1634 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
);
1636 // Clear any currently configured certificates.
1637 SSL_certs_clear(ssl_
);
1640 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1641 LOG(WARNING
) << "Client auth is not supported";
1642 #else // !defined(OS_IOS)
1643 if (!ssl_config_
.send_client_cert
) {
1644 // First pass: we know that a client certificate is needed, but we do not
1645 // have one at hand.
1646 client_auth_cert_needed_
= true;
1647 STACK_OF(X509_NAME
) *authorities
= SSL_get_client_CA_list(ssl
);
1648 for (size_t i
= 0; i
< sk_X509_NAME_num(authorities
); i
++) {
1649 X509_NAME
*ca_name
= (X509_NAME
*)sk_X509_NAME_value(authorities
, i
);
1650 unsigned char* str
= NULL
;
1651 int length
= i2d_X509_NAME(ca_name
, &str
);
1652 cert_authorities_
.push_back(std::string(
1653 reinterpret_cast<const char*>(str
),
1654 static_cast<size_t>(length
)));
1658 const unsigned char* client_cert_types
;
1659 size_t num_client_cert_types
=
1660 SSL_get0_certificate_types(ssl
, &client_cert_types
);
1661 for (size_t i
= 0; i
< num_client_cert_types
; i
++) {
1662 cert_key_types_
.push_back(
1663 static_cast<SSLClientCertType
>(client_cert_types
[i
]));
1666 return -1; // Suspends handshake.
1669 // Second pass: a client certificate should have been selected.
1670 if (ssl_config_
.client_cert
.get()) {
1671 ScopedX509 leaf_x509
=
1672 OSCertHandleToOpenSSL(ssl_config_
.client_cert
->os_cert_handle());
1674 LOG(WARNING
) << "Failed to import certificate";
1675 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1679 ScopedX509Stack chain
= OSCertHandlesToOpenSSL(
1680 ssl_config_
.client_cert
->GetIntermediateCertificates());
1682 LOG(WARNING
) << "Failed to import intermediate certificates";
1683 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT
);
1687 // TODO(davidben): With Linux client auth support, this should be
1688 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1689 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1690 // net/ client auth API lacking a private key handle.
1691 #if defined(USE_OPENSSL_CERTS)
1692 crypto::ScopedEVP_PKEY privkey
=
1693 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1694 ssl_config_
.client_cert
.get());
1695 #else // !defined(USE_OPENSSL_CERTS)
1696 crypto::ScopedEVP_PKEY privkey
=
1697 FetchClientCertPrivateKey(ssl_config_
.client_cert
.get());
1698 #endif // defined(USE_OPENSSL_CERTS)
1700 // Could not find the private key. Fail the handshake and surface an
1701 // appropriate error to the caller.
1702 LOG(WARNING
) << "Client cert found without private key";
1703 OpenSSLPutNetError(FROM_HERE
, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
);
1707 if (!SSL_use_certificate(ssl_
, leaf_x509
.get()) ||
1708 !SSL_use_PrivateKey(ssl_
, privkey
.get()) ||
1709 !SSL_set1_chain(ssl_
, chain
.get())) {
1710 LOG(WARNING
) << "Failed to set client certificate";
1714 int cert_count
= 1 + sk_X509_num(chain
.get());
1715 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1716 NetLog::IntegerCallback("cert_count", cert_count
));
1719 #endif // defined(OS_IOS)
1721 // Send no client certificate.
1722 net_log_
.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
1723 NetLog::IntegerCallback("cert_count", 0));
1727 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX
* store_ctx
) {
1728 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1729 tracked_objects::ScopedTracker
tracking_profile(
1730 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1731 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1733 if (!completed_connect_
) {
1734 // If the first handshake hasn't completed then we accept any certificates
1735 // because we verify after the handshake.
1739 // Disallow the server certificate to change in a renegotiation.
1740 if (server_cert_chain_
->empty()) {
1741 LOG(ERROR
) << "Received invalid certificate chain between handshakes";
1744 base::StringPiece old_der
, new_der
;
1745 if (store_ctx
->cert
== NULL
||
1746 !x509_util::GetDER(server_cert_chain_
->Get(0), &old_der
) ||
1747 !x509_util::GetDER(store_ctx
->cert
, &new_der
)) {
1748 LOG(ERROR
) << "Failed to encode certificates";
1751 if (old_der
!= new_der
) {
1752 LOG(ERROR
) << "Server certificate changed between handshakes";
1759 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1760 // server supports NPN, selects a protocol from the list that the server
1761 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1762 // callback can assume that |in| is syntactically valid.
1763 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out
,
1764 unsigned char* outlen
,
1765 const unsigned char* in
,
1766 unsigned int inlen
) {
1767 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1768 tracked_objects::ScopedTracker
tracking_profile(
1769 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1770 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1772 if (ssl_config_
.next_protos
.empty()) {
1773 *out
= reinterpret_cast<uint8
*>(
1774 const_cast<char*>(kDefaultSupportedNPNProtocol
));
1775 *outlen
= arraysize(kDefaultSupportedNPNProtocol
) - 1;
1776 npn_status_
= kNextProtoUnsupported
;
1777 return SSL_TLSEXT_ERR_OK
;
1780 // Assume there's no overlap between our protocols and the server's list.
1781 npn_status_
= kNextProtoNoOverlap
;
1783 // For each protocol in server preference order, see if we support it.
1784 for (unsigned int i
= 0; i
< inlen
; i
+= in
[i
] + 1) {
1785 for (std::vector
<std::string
>::const_iterator
1786 j
= ssl_config_
.next_protos
.begin();
1787 j
!= ssl_config_
.next_protos
.end(); ++j
) {
1788 if (in
[i
] == j
->size() &&
1789 memcmp(&in
[i
+ 1], j
->data(), in
[i
]) == 0) {
1790 // We found a match.
1791 *out
= const_cast<unsigned char*>(in
) + i
+ 1;
1793 npn_status_
= kNextProtoNegotiated
;
1797 if (npn_status_
== kNextProtoNegotiated
)
1801 // If we didn't find a protocol, we select the first one from our list.
1802 if (npn_status_
== kNextProtoNoOverlap
) {
1803 *out
= reinterpret_cast<uint8
*>(const_cast<char*>(
1804 ssl_config_
.next_protos
[0].data()));
1805 *outlen
= ssl_config_
.next_protos
[0].size();
1808 npn_proto_
.assign(reinterpret_cast<const char*>(*out
), *outlen
);
1809 DVLOG(2) << "next protocol: '" << npn_proto_
<< "' status: " << npn_status_
;
1810 set_negotiation_extension(kExtensionNPN
);
1811 return SSL_TLSEXT_ERR_OK
;
1814 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1817 const char *argp
, int argi
, long argl
,
1819 if (cmd
== (BIO_CB_READ
|BIO_CB_RETURN
) && retvalue
<= 0) {
1820 // If there is no more data in the buffer, report any pending errors that
1821 // were observed. Note that both the readbuf and the writebuf are checked
1822 // for errors, since the application may have encountered a socket error
1823 // while writing that would otherwise not be reported until the application
1824 // attempted to write again - which it may never do. See
1825 // https://crbug.com/249848.
1826 if (transport_read_error_
!= OK
) {
1827 OpenSSLPutNetError(FROM_HERE
, transport_read_error_
);
1830 if (transport_write_error_
!= OK
) {
1831 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1834 } else if (cmd
== BIO_CB_WRITE
) {
1835 // Because of the write buffer, this reports a failure from the previous
1836 // write payload. If the current payload fails to write, the error will be
1837 // reported in a future write or read to |bio|.
1838 if (transport_write_error_
!= OK
) {
1839 OpenSSLPutNetError(FROM_HERE
, transport_write_error_
);
1847 long SSLClientSocketOpenSSL::BIOCallback(
1850 const char *argp
, int argi
, long argl
,
1852 SSLClientSocketOpenSSL
* socket
= reinterpret_cast<SSLClientSocketOpenSSL
*>(
1853 BIO_get_callback_arg(bio
));
1855 return socket
->MaybeReplayTransportError(
1856 bio
, cmd
, argp
, argi
, argl
, retvalue
);
1860 void SSLClientSocketOpenSSL::InfoCallback(const SSL
* ssl
,
1863 if (type
== SSL_CB_HANDSHAKE_DONE
) {
1864 SSLClientSocketOpenSSL
* ssl_socket
=
1865 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl
);
1866 ssl_socket
->handshake_succeeded_
= true;
1867 ssl_socket
->CheckIfHandshakeFinished();
1871 // Determines if both the handshake and certificate verification have completed
1872 // successfully, and calls the handshake completion callback if that is the
1875 // CheckIfHandshakeFinished is called twice per connection: once after
1876 // MarkSSLSessionAsGood, when the certificate has been verified, and
1877 // once via an OpenSSL callback when the handshake has completed. On the
1878 // second call, when the certificate has been verified and the handshake
1879 // has completed, the connection's handshake completion callback is run.
1880 void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1881 if (handshake_succeeded_
&& marked_session_as_good_
)
1882 OnHandshakeCompletion();
1885 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
1886 for (ct::SCTList::const_iterator iter
=
1887 ct_verify_result_
.verified_scts
.begin();
1888 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
1889 ssl_info
->signed_certificate_timestamps
.push_back(
1890 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
1892 for (ct::SCTList::const_iterator iter
=
1893 ct_verify_result_
.invalid_scts
.begin();
1894 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
1895 ssl_info
->signed_certificate_timestamps
.push_back(
1896 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
1898 for (ct::SCTList::const_iterator iter
=
1899 ct_verify_result_
.unknown_logs_scts
.begin();
1900 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
1901 ssl_info
->signed_certificate_timestamps
.push_back(
1902 SignedCertificateTimestampAndStatus(*iter
,
1903 ct::SCT_STATUS_LOG_UNKNOWN
));
1907 scoped_refptr
<X509Certificate
>
1908 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1909 return server_cert_
;