Material throbber: use in tabstrip
[chromium-blink-merge.git] / net / socket / ssl_client_socket_openssl.cc
blob9338bcf96c45cf9734247215a45bcea3f1c26a4c
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"
10 #include <errno.h>
11 #include <openssl/bio.h>
12 #include <openssl/err.h>
13 #include <openssl/mem.h>
14 #include <openssl/ssl.h>
15 #include <string.h>
17 #include "base/bind.h"
18 #include "base/callback_helpers.h"
19 #include "base/environment.h"
20 #include "base/memory/singleton.h"
21 #include "base/metrics/histogram.h"
22 #include "base/profiler/scoped_tracker.h"
23 #include "base/strings/string_piece.h"
24 #include "base/synchronization/lock.h"
25 #include "base/threading/thread_local.h"
26 #include "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/ssl/scoped_openssl_types.h"
39 #include "net/ssl/ssl_cert_request_info.h"
40 #include "net/ssl/ssl_client_session_cache_openssl.h"
41 #include "net/ssl/ssl_connection_status_flags.h"
42 #include "net/ssl/ssl_info.h"
44 #if defined(OS_WIN)
45 #include "base/win/windows_version.h"
46 #endif
48 #if defined(USE_OPENSSL_CERTS)
49 #include "net/ssl/openssl_client_key_store.h"
50 #else
51 #include "net/ssl/openssl_platform_key.h"
52 #endif
54 namespace net {
56 namespace {
58 // Enable this to see logging for state machine state transitions.
59 #if 0
60 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
61 " jump to state " << s; \
62 next_handshake_state_ = s; } while (0)
63 #else
64 #define GotoState(s) next_handshake_state_ = s
65 #endif
67 // This constant can be any non-negative/non-zero value (eg: it does not
68 // overlap with any value of the net::Error range, including net::OK).
69 const int kNoPendingReadResult = 1;
71 // If a client doesn't have a list of protocols that it supports, but
72 // the server supports NPN, choosing "http/1.1" is the best answer.
73 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
75 // Default size of the internal BoringSSL buffers.
76 const int KDefaultOpenSSLBufferSize = 17 * 1024;
78 void FreeX509Stack(STACK_OF(X509)* ptr) {
79 sk_X509_pop_free(ptr, X509_free);
82 using ScopedX509Stack = crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>;
84 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
85 // This method doesn't seem to have made it into the OpenSSL headers.
86 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
87 #endif
89 // Used for encoding the |connection_status| field of an SSLInfo object.
90 int EncodeSSLConnectionStatus(uint16 cipher_suite,
91 int compression,
92 int version) {
93 return cipher_suite |
94 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
95 SSL_CONNECTION_COMPRESSION_SHIFT) |
96 ((version & SSL_CONNECTION_VERSION_MASK) <<
97 SSL_CONNECTION_VERSION_SHIFT);
100 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
101 // this SSL connection.
102 int GetNetSSLVersion(SSL* ssl) {
103 switch (SSL_version(ssl)) {
104 case SSL2_VERSION:
105 return SSL_CONNECTION_VERSION_SSL2;
106 case SSL3_VERSION:
107 return SSL_CONNECTION_VERSION_SSL3;
108 case TLS1_VERSION:
109 return SSL_CONNECTION_VERSION_TLS1;
110 case TLS1_1_VERSION:
111 return SSL_CONNECTION_VERSION_TLS1_1;
112 case TLS1_2_VERSION:
113 return SSL_CONNECTION_VERSION_TLS1_2;
114 default:
115 return SSL_CONNECTION_VERSION_UNKNOWN;
119 ScopedX509 OSCertHandleToOpenSSL(
120 X509Certificate::OSCertHandle os_handle) {
121 #if defined(USE_OPENSSL_CERTS)
122 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
123 #else // !defined(USE_OPENSSL_CERTS)
124 std::string der_encoded;
125 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
126 return ScopedX509();
127 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
128 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
129 #endif // defined(USE_OPENSSL_CERTS)
132 ScopedX509Stack OSCertHandlesToOpenSSL(
133 const X509Certificate::OSCertHandles& os_handles) {
134 ScopedX509Stack stack(sk_X509_new_null());
135 for (size_t i = 0; i < os_handles.size(); i++) {
136 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
137 if (!x509)
138 return ScopedX509Stack();
139 sk_X509_push(stack.get(), x509.release());
141 return stack.Pass();
144 int LogErrorCallback(const char* str, size_t len, void* context) {
145 LOG(ERROR) << base::StringPiece(str, len);
146 return 1;
149 } // namespace
151 class SSLClientSocketOpenSSL::SSLContext {
152 public:
153 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
154 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
155 SSLClientSessionCacheOpenSSL* session_cache() { return &session_cache_; }
157 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
158 DCHECK(ssl);
159 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
160 SSL_get_ex_data(ssl, ssl_socket_data_index_));
161 DCHECK(socket);
162 return socket;
165 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
166 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
169 private:
170 friend struct DefaultSingletonTraits<SSLContext>;
172 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
173 crypto::EnsureOpenSSLInit();
174 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
175 DCHECK_NE(ssl_socket_data_index_, -1);
176 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
177 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
178 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
179 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
180 // This stops |SSL_shutdown| from generating the close_notify message, which
181 // is currently not sent on the network.
182 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
183 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
184 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
185 // It would be better if the callback were not a global setting,
186 // but that is an OpenSSL issue.
187 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
188 NULL);
189 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
190 SSL_CTX_set_info_callback(ssl_ctx_.get(), InfoCallback);
192 // Disable the internal session cache. Session caching is handled
193 // externally (i.e. by SSLClientSessionCacheOpenSSL).
194 SSL_CTX_set_session_cache_mode(
195 ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
197 scoped_ptr<base::Environment> env(base::Environment::Create());
198 std::string ssl_keylog_file;
199 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
200 !ssl_keylog_file.empty()) {
201 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
202 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
203 if (!bio) {
204 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
205 ERR_print_errors_cb(&LogErrorCallback, NULL);
206 } else {
207 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
212 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
213 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
214 DCHECK(socket);
215 return socket->ClientCertRequestCallback(ssl);
218 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
219 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
220 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
221 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
222 CHECK(socket);
224 return socket->CertVerifyCallback(store_ctx);
227 static int SelectNextProtoCallback(SSL* ssl,
228 unsigned char** out, unsigned char* outlen,
229 const unsigned char* in,
230 unsigned int inlen, void* arg) {
231 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
232 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
235 static void InfoCallback(const SSL* ssl, int type, int val) {
236 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
237 socket->InfoCallback(type, val);
240 // This is the index used with SSL_get_ex_data to retrieve the owner
241 // SSLClientSocketOpenSSL object from an SSL instance.
242 int ssl_socket_data_index_;
244 ScopedSSL_CTX ssl_ctx_;
246 // TODO(davidben): Use a separate cache per URLRequestContext.
247 // https://crbug.com/458365
249 // TODO(davidben): Sessions should be invalidated on fatal
250 // alerts. https://crbug.com/466352
251 SSLClientSessionCacheOpenSSL session_cache_;
254 // PeerCertificateChain is a helper object which extracts the certificate
255 // chain, as given by the server, from an OpenSSL socket and performs the needed
256 // resource management. The first element of the chain is the leaf certificate
257 // and the other elements are in the order given by the server.
258 class SSLClientSocketOpenSSL::PeerCertificateChain {
259 public:
260 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
261 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
262 ~PeerCertificateChain() {}
263 PeerCertificateChain& operator=(const PeerCertificateChain& other);
265 // Resets the PeerCertificateChain to the set of certificates in|chain|,
266 // which may be NULL, indicating to empty the store certificates.
267 // Note: If an error occurs, such as being unable to parse the certificates,
268 // this will behave as if Reset(NULL) was called.
269 void Reset(STACK_OF(X509)* chain);
271 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
272 scoped_refptr<X509Certificate> AsOSChain() const;
274 size_t size() const {
275 if (!openssl_chain_.get())
276 return 0;
277 return sk_X509_num(openssl_chain_.get());
280 bool empty() const {
281 return size() == 0;
284 X509* Get(size_t index) const {
285 DCHECK_LT(index, size());
286 return sk_X509_value(openssl_chain_.get(), index);
289 private:
290 ScopedX509Stack openssl_chain_;
293 SSLClientSocketOpenSSL::PeerCertificateChain&
294 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
295 const PeerCertificateChain& other) {
296 if (this == &other)
297 return *this;
299 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
300 return *this;
303 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
304 STACK_OF(X509)* chain) {
305 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
308 scoped_refptr<X509Certificate>
309 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
310 #if defined(USE_OPENSSL_CERTS)
311 // When OSCertHandle is typedef'ed to X509, this implementation does a short
312 // cut to avoid converting back and forth between DER and the X509 struct.
313 X509Certificate::OSCertHandles intermediates;
314 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
315 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
318 return make_scoped_refptr(X509Certificate::CreateFromHandle(
319 sk_X509_value(openssl_chain_.get(), 0), intermediates));
320 #else
321 // DER-encode the chain and convert to a platform certificate handle.
322 std::vector<base::StringPiece> der_chain;
323 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
324 X509* x = sk_X509_value(openssl_chain_.get(), i);
325 base::StringPiece der;
326 if (!x509_util::GetDER(x, &der))
327 return NULL;
328 der_chain.push_back(der);
331 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
332 #endif
335 // static
336 void SSLClientSocket::ClearSessionCache() {
337 SSLClientSocketOpenSSL::SSLContext* context =
338 SSLClientSocketOpenSSL::SSLContext::GetInstance();
339 context->session_cache()->Flush();
342 // static
343 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
344 return SSL_PROTOCOL_VERSION_TLS1_2;
347 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
348 scoped_ptr<ClientSocketHandle> transport_socket,
349 const HostPortPair& host_and_port,
350 const SSLConfig& ssl_config,
351 const SSLClientSocketContext& context)
352 : transport_send_busy_(false),
353 transport_recv_busy_(false),
354 pending_read_error_(kNoPendingReadResult),
355 pending_read_ssl_error_(SSL_ERROR_NONE),
356 transport_read_error_(OK),
357 transport_write_error_(OK),
358 server_cert_chain_(new PeerCertificateChain(NULL)),
359 completed_connect_(false),
360 was_ever_used_(false),
361 client_auth_cert_needed_(false),
362 cert_verifier_(context.cert_verifier),
363 cert_transparency_verifier_(context.cert_transparency_verifier),
364 channel_id_service_(context.channel_id_service),
365 ssl_(NULL),
366 transport_bio_(NULL),
367 transport_(transport_socket.Pass()),
368 host_and_port_(host_and_port),
369 ssl_config_(ssl_config),
370 ssl_session_cache_shard_(context.ssl_session_cache_shard),
371 next_handshake_state_(STATE_NONE),
372 npn_status_(kNextProtoUnsupported),
373 channel_id_sent_(false),
374 handshake_completed_(false),
375 certificate_verified_(false),
376 transport_security_state_(context.transport_security_state),
377 policy_enforcer_(context.cert_policy_enforcer),
378 net_log_(transport_->socket()->NetLog()),
379 weak_factory_(this) {
380 DCHECK(cert_verifier_);
383 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
384 Disconnect();
387 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
388 SSLCertRequestInfo* cert_request_info) {
389 cert_request_info->host_and_port = host_and_port_;
390 cert_request_info->cert_authorities = cert_authorities_;
391 cert_request_info->cert_key_types = cert_key_types_;
394 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
395 std::string* proto) const {
396 *proto = npn_proto_;
397 return npn_status_;
400 ChannelIDService*
401 SSLClientSocketOpenSSL::GetChannelIDService() const {
402 return channel_id_service_;
405 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
406 const base::StringPiece& label,
407 bool has_context, const base::StringPiece& context,
408 unsigned char* out, unsigned int outlen) {
409 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
411 int rv = SSL_export_keying_material(
412 ssl_, out, outlen, label.data(), label.size(),
413 reinterpret_cast<const unsigned char*>(context.data()), context.length(),
414 has_context ? 1 : 0);
416 if (rv != 1) {
417 int ssl_error = SSL_get_error(ssl_, rv);
418 LOG(ERROR) << "Failed to export keying material;"
419 << " returned " << rv
420 << ", SSL error code " << ssl_error;
421 return MapOpenSSLError(ssl_error, err_tracer);
423 return OK;
426 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
427 NOTIMPLEMENTED();
428 return ERR_NOT_IMPLEMENTED;
431 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
432 // It is an error to create an SSLClientSocket whose context has no
433 // TransportSecurityState.
434 DCHECK(transport_security_state_);
436 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
438 // Set up new ssl object.
439 int rv = Init();
440 if (rv != OK) {
441 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
442 return rv;
445 // Set SSL to client mode. Handshake happens in the loop below.
446 SSL_set_connect_state(ssl_);
448 GotoState(STATE_HANDSHAKE);
449 rv = DoHandshakeLoop(OK);
450 if (rv == ERR_IO_PENDING) {
451 user_connect_callback_ = callback;
452 } else {
453 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
456 return rv > OK ? OK : rv;
459 void SSLClientSocketOpenSSL::Disconnect() {
460 if (ssl_) {
461 // Calling SSL_shutdown prevents the session from being marked as
462 // unresumable.
463 SSL_shutdown(ssl_);
464 SSL_free(ssl_);
465 ssl_ = NULL;
467 if (transport_bio_) {
468 BIO_free_all(transport_bio_);
469 transport_bio_ = NULL;
472 // Shut down anything that may call us back.
473 verifier_.reset();
474 transport_->socket()->Disconnect();
476 // Null all callbacks, delete all buffers.
477 transport_send_busy_ = false;
478 send_buffer_ = NULL;
479 transport_recv_busy_ = false;
480 recv_buffer_ = NULL;
482 user_connect_callback_.Reset();
483 user_read_callback_.Reset();
484 user_write_callback_.Reset();
485 user_read_buf_ = NULL;
486 user_read_buf_len_ = 0;
487 user_write_buf_ = NULL;
488 user_write_buf_len_ = 0;
490 pending_read_error_ = kNoPendingReadResult;
491 pending_read_ssl_error_ = SSL_ERROR_NONE;
492 pending_read_error_info_ = OpenSSLErrorInfo();
494 transport_read_error_ = OK;
495 transport_write_error_ = OK;
497 server_cert_verify_result_.Reset();
498 completed_connect_ = false;
500 cert_authorities_.clear();
501 cert_key_types_.clear();
502 client_auth_cert_needed_ = false;
504 start_cert_verification_time_ = base::TimeTicks();
506 npn_status_ = kNextProtoUnsupported;
507 npn_proto_.clear();
509 channel_id_sent_ = false;
510 channel_id_request_handle_.Cancel();
513 bool SSLClientSocketOpenSSL::IsConnected() const {
514 // If the handshake has not yet completed.
515 if (!completed_connect_)
516 return false;
517 // If an asynchronous operation is still pending.
518 if (user_read_buf_.get() || user_write_buf_.get())
519 return true;
521 return transport_->socket()->IsConnected();
524 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
525 // If the handshake has not yet completed.
526 if (!completed_connect_)
527 return false;
528 // If an asynchronous operation is still pending.
529 if (user_read_buf_.get() || user_write_buf_.get())
530 return false;
532 // If there is data read from the network that has not yet been consumed, do
533 // not treat the connection as idle.
535 // Note that this does not check |BIO_pending|, whether there is ciphertext
536 // that has not yet been flushed to the network. |Write| returns early, so
537 // this can cause race conditions which cause a socket to not be treated
538 // reusable when it should be. See https://crbug.com/466147.
539 if (BIO_wpending(transport_bio_) > 0)
540 return false;
542 return transport_->socket()->IsConnectedAndIdle();
545 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
546 return transport_->socket()->GetPeerAddress(addressList);
549 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
550 return transport_->socket()->GetLocalAddress(addressList);
553 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
554 return net_log_;
557 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
558 if (transport_.get() && transport_->socket()) {
559 transport_->socket()->SetSubresourceSpeculation();
560 } else {
561 NOTREACHED();
565 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
566 if (transport_.get() && transport_->socket()) {
567 transport_->socket()->SetOmniboxSpeculation();
568 } else {
569 NOTREACHED();
573 bool SSLClientSocketOpenSSL::WasEverUsed() const {
574 return was_ever_used_;
577 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
578 if (transport_.get() && transport_->socket())
579 return transport_->socket()->UsingTCPFastOpen();
581 NOTREACHED();
582 return false;
585 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
586 ssl_info->Reset();
587 if (server_cert_chain_->empty())
588 return false;
590 ssl_info->cert = server_cert_verify_result_.verified_cert;
591 ssl_info->cert_status = server_cert_verify_result_.cert_status;
592 ssl_info->is_issued_by_known_root =
593 server_cert_verify_result_.is_issued_by_known_root;
594 ssl_info->public_key_hashes =
595 server_cert_verify_result_.public_key_hashes;
596 ssl_info->client_cert_sent =
597 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
598 ssl_info->channel_id_sent = channel_id_sent_;
599 ssl_info->pinning_failure_log = pinning_failure_log_;
601 AddSCTInfoToSSLInfo(ssl_info);
603 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
604 CHECK(cipher);
605 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
607 ssl_info->connection_status = EncodeSSLConnectionStatus(
608 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
609 GetNetSSLVersion(ssl_));
611 if (!SSL_get_secure_renegotiation_support(ssl_))
612 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
614 if (ssl_config_.version_fallback)
615 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
617 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
618 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
620 DVLOG(3) << "Encoded connection status: cipher suite = "
621 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
622 << " version = "
623 << SSLConnectionStatusToVersion(ssl_info->connection_status);
624 return true;
627 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
628 int buf_len,
629 const CompletionCallback& callback) {
630 user_read_buf_ = buf;
631 user_read_buf_len_ = buf_len;
633 int rv = DoReadLoop();
635 if (rv == ERR_IO_PENDING) {
636 user_read_callback_ = callback;
637 } else {
638 if (rv > 0)
639 was_ever_used_ = true;
640 user_read_buf_ = NULL;
641 user_read_buf_len_ = 0;
644 return rv;
647 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
648 int buf_len,
649 const CompletionCallback& callback) {
650 user_write_buf_ = buf;
651 user_write_buf_len_ = buf_len;
653 int rv = DoWriteLoop();
655 if (rv == ERR_IO_PENDING) {
656 user_write_callback_ = callback;
657 } else {
658 if (rv > 0)
659 was_ever_used_ = true;
660 user_write_buf_ = NULL;
661 user_write_buf_len_ = 0;
664 return rv;
667 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
668 return transport_->socket()->SetReceiveBufferSize(size);
671 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
672 return transport_->socket()->SetSendBufferSize(size);
675 int SSLClientSocketOpenSSL::Init() {
676 DCHECK(!ssl_);
677 DCHECK(!transport_bio_);
679 SSLContext* context = SSLContext::GetInstance();
680 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
682 ssl_ = SSL_new(context->ssl_ctx());
683 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
684 return ERR_UNEXPECTED;
686 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
687 return ERR_UNEXPECTED;
689 SSL_SESSION* session = context->session_cache()->Lookup(GetSessionCacheKey());
690 if (session != nullptr)
691 SSL_set_session(ssl_, session);
693 send_buffer_ = new GrowableIOBuffer();
694 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
695 recv_buffer_ = new GrowableIOBuffer();
696 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
698 BIO* ssl_bio = NULL;
700 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
701 if (!BIO_new_bio_pair_external_buf(
702 &ssl_bio, send_buffer_->capacity(),
703 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
704 recv_buffer_->capacity(),
705 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
706 return ERR_UNEXPECTED;
707 DCHECK(ssl_bio);
708 DCHECK(transport_bio_);
710 // Install a callback on OpenSSL's end to plumb transport errors through.
711 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
712 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
714 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
716 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
717 // set everything we care about to an absolute value.
718 SslSetClearMask options;
719 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
720 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
721 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
722 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
723 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
724 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
725 bool tls1_1_enabled =
726 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
727 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
728 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
729 bool tls1_2_enabled =
730 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
731 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
732 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
734 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
736 // TODO(joth): Set this conditionally, see http://crbug.com/55410
737 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
739 SSL_set_options(ssl_, options.set_mask);
740 SSL_clear_options(ssl_, options.clear_mask);
742 // Same as above, this time for the SSL mode.
743 SslSetClearMask mode;
745 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
746 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
748 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START,
749 ssl_config_.false_start_enabled);
751 mode.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV, ssl_config_.version_fallback);
753 SSL_set_mode(ssl_, mode.set_mask);
754 SSL_clear_mode(ssl_, mode.clear_mask);
756 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
757 // textual name with SSL_set_cipher_list because there is no public API to
758 // directly remove a cipher by ID.
759 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
760 DCHECK(ciphers);
761 // See SSLConfig::disabled_cipher_suites for description of the suites
762 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
763 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
764 // as the handshake hash.
765 std::string command(
766 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
767 // Walk through all the installed ciphers, seeing if any need to be
768 // appended to the cipher removal |command|.
769 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
770 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
771 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
772 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
773 // implementation uses "effective" bits here but OpenSSL does not provide
774 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
775 // both of which are greater than 80 anyway.
776 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
777 if (!disable) {
778 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
779 ssl_config_.disabled_cipher_suites.end(), id) !=
780 ssl_config_.disabled_cipher_suites.end();
782 if (disable) {
783 const char* name = SSL_CIPHER_get_name(cipher);
784 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
785 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
786 command.append(":!");
787 command.append(name);
791 if (!ssl_config_.enable_deprecated_cipher_suites)
792 command.append(":!RC4");
794 // Disable ECDSA cipher suites on platforms that do not support ECDSA
795 // signed certificates, as servers may use the presence of such
796 // ciphersuites as a hint to send an ECDSA certificate.
797 #if defined(OS_WIN)
798 if (base::win::GetVersion() < base::win::VERSION_VISTA)
799 command.append(":!ECDSA");
800 #endif
802 int rv = SSL_set_cipher_list(ssl_, command.c_str());
803 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
804 // This will almost certainly result in the socket failing to complete the
805 // handshake at which point the appropriate error is bubbled up to the client.
806 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
807 "returned " << rv;
809 // TLS channel ids.
810 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
811 SSL_enable_tls_channel_id(ssl_);
814 if (!ssl_config_.next_protos.empty()) {
815 // Get list of ciphers that are enabled.
816 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
817 DCHECK(enabled_ciphers);
818 std::vector<uint16> enabled_ciphers_vector;
819 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
820 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
821 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
822 enabled_ciphers_vector.push_back(id);
825 std::vector<uint8_t> wire_protos =
826 SerializeNextProtos(ssl_config_.next_protos,
827 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
828 IsTLSVersionAdequateForHTTP2(ssl_config_));
829 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
830 wire_protos.size());
833 if (ssl_config_.signed_cert_timestamps_enabled) {
834 SSL_enable_signed_cert_timestamps(ssl_);
835 SSL_enable_ocsp_stapling(ssl_);
838 if (cert_verifier_->SupportsOCSPStapling())
839 SSL_enable_ocsp_stapling(ssl_);
841 // Enable fastradio padding.
842 SSL_enable_fastradio_padding(ssl_,
843 ssl_config_.fastradio_padding_enabled &&
844 ssl_config_.fastradio_padding_eligible);
846 return OK;
849 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
850 // Since Run may result in Read being called, clear |user_read_callback_|
851 // up front.
852 if (rv > 0)
853 was_ever_used_ = true;
854 user_read_buf_ = NULL;
855 user_read_buf_len_ = 0;
856 base::ResetAndReturn(&user_read_callback_).Run(rv);
859 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
860 // Since Run may result in Write being called, clear |user_write_callback_|
861 // up front.
862 if (rv > 0)
863 was_ever_used_ = true;
864 user_write_buf_ = NULL;
865 user_write_buf_len_ = 0;
866 base::ResetAndReturn(&user_write_callback_).Run(rv);
869 bool SSLClientSocketOpenSSL::DoTransportIO() {
870 bool network_moved = false;
871 int rv;
872 // Read and write as much data as possible. The loop is necessary because
873 // Write() may return synchronously.
874 do {
875 rv = BufferSend();
876 if (rv != ERR_IO_PENDING && rv != 0)
877 network_moved = true;
878 } while (rv > 0);
879 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
880 network_moved = true;
881 return network_moved;
884 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
885 // g_first_run_completed once crbug.com/424386 is fixed.
886 base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
887 LAZY_INSTANCE_INITIALIZER;
889 int SSLClientSocketOpenSSL::DoHandshake() {
890 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
891 int net_error = OK;
893 int rv;
895 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
896 // is fixed.
897 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
898 rv = SSL_do_handshake(ssl_);
899 } else {
900 if (g_first_run_completed.Get().Get()) {
901 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
902 // fixed.
903 tracked_objects::ScopedTracker tracking_profile(
904 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
906 rv = SSL_do_handshake(ssl_);
907 } else {
908 g_first_run_completed.Get().Set(true);
909 rv = SSL_do_handshake(ssl_);
913 if (rv == 1) {
914 if (ssl_config_.version_fallback &&
915 ssl_config_.version_max < ssl_config_.version_fallback_min) {
916 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
919 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
920 if (npn_status_ == kNextProtoUnsupported) {
921 const uint8_t* alpn_proto = NULL;
922 unsigned alpn_len = 0;
923 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
924 if (alpn_len > 0) {
925 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
926 npn_status_ = kNextProtoNegotiated;
927 set_negotiation_extension(kExtensionALPN);
931 RecordNegotiationExtension();
932 RecordChannelIDSupport(channel_id_service_, channel_id_sent_,
933 ssl_config_.channel_id_enabled,
934 crypto::ECPrivateKey::IsSupported());
936 // Only record OCSP histograms if OCSP was requested.
937 if (ssl_config_.signed_cert_timestamps_enabled ||
938 cert_verifier_->SupportsOCSPStapling()) {
939 const uint8_t* ocsp_response;
940 size_t ocsp_response_len;
941 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
943 set_stapled_ocsp_response_received(ocsp_response_len != 0);
944 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
947 const uint8_t* sct_list;
948 size_t sct_list_len;
949 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
950 set_signed_cert_timestamps_received(sct_list_len != 0);
952 // Verify the certificate.
953 UpdateServerCert();
954 GotoState(STATE_VERIFY_CERT);
955 } else {
956 if (client_auth_cert_needed_)
957 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
959 int ssl_error = SSL_get_error(ssl_, rv);
961 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
962 // The server supports channel ID. Stop to look one up before returning to
963 // the handshake.
964 GotoState(STATE_CHANNEL_ID_LOOKUP);
965 return OK;
968 OpenSSLErrorInfo error_info;
969 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
971 // If not done, stay in this state
972 if (net_error == ERR_IO_PENDING) {
973 GotoState(STATE_HANDSHAKE);
974 } else {
975 LOG(ERROR) << "handshake failed; returned " << rv
976 << ", SSL error code " << ssl_error
977 << ", net_error " << net_error;
978 net_log_.AddEvent(
979 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
980 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
983 return net_error;
986 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
987 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED);
988 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
989 return channel_id_service_->GetOrCreateChannelID(
990 host_and_port_.host(),
991 &channel_id_private_key_,
992 &channel_id_cert_,
993 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
994 base::Unretained(this)),
995 &channel_id_request_handle_);
998 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
999 if (result < 0)
1000 return result;
1002 DCHECK_LT(0u, channel_id_private_key_.size());
1003 // Decode key.
1004 std::vector<uint8> encrypted_private_key_info;
1005 std::vector<uint8> subject_public_key_info;
1006 encrypted_private_key_info.assign(
1007 channel_id_private_key_.data(),
1008 channel_id_private_key_.data() + channel_id_private_key_.size());
1009 subject_public_key_info.assign(
1010 channel_id_cert_.data(),
1011 channel_id_cert_.data() + channel_id_cert_.size());
1012 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1013 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1014 ChannelIDService::kEPKIPassword,
1015 encrypted_private_key_info,
1016 subject_public_key_info));
1017 if (!ec_private_key) {
1018 LOG(ERROR) << "Failed to import Channel ID.";
1019 return ERR_CHANNEL_ID_IMPORT_FAILED;
1022 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1023 // type.
1024 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1025 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1026 if (!rv) {
1027 LOG(ERROR) << "Failed to set Channel ID.";
1028 int err = SSL_get_error(ssl_, rv);
1029 return MapOpenSSLError(err, err_tracer);
1032 // Return to the handshake.
1033 channel_id_sent_ = true;
1034 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
1035 GotoState(STATE_HANDSHAKE);
1036 return OK;
1039 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
1040 DCHECK(!server_cert_chain_->empty());
1041 DCHECK(start_cert_verification_time_.is_null());
1043 GotoState(STATE_VERIFY_CERT_COMPLETE);
1045 // If the certificate is bad and has been previously accepted, use
1046 // the previous status and bypass the error.
1047 base::StringPiece der_cert;
1048 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1049 NOTREACHED();
1050 return ERR_CERT_INVALID;
1052 CertStatus cert_status;
1053 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
1054 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1055 server_cert_verify_result_.Reset();
1056 server_cert_verify_result_.cert_status = cert_status;
1057 server_cert_verify_result_.verified_cert = server_cert_;
1058 return OK;
1061 // When running in a sandbox, it may not be possible to create an
1062 // X509Certificate*, as that may depend on OS functionality blocked
1063 // in the sandbox.
1064 if (!server_cert_.get()) {
1065 server_cert_verify_result_.Reset();
1066 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1067 return ERR_CERT_INVALID;
1070 std::string ocsp_response;
1071 if (cert_verifier_->SupportsOCSPStapling()) {
1072 const uint8_t* ocsp_response_raw;
1073 size_t ocsp_response_len;
1074 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1075 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1076 ocsp_response_len);
1079 start_cert_verification_time_ = base::TimeTicks::Now();
1081 int flags = 0;
1082 if (ssl_config_.rev_checking_enabled)
1083 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1084 if (ssl_config_.verify_ev_cert)
1085 flags |= CertVerifier::VERIFY_EV_CERT;
1086 if (ssl_config_.cert_io_enabled)
1087 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1088 if (ssl_config_.rev_checking_required_local_anchors)
1089 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1090 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1091 return verifier_->Verify(
1092 server_cert_.get(), host_and_port_.host(), ocsp_response, flags,
1093 // TODO(davidben): Route the CRLSet through SSLConfig so
1094 // SSLClientSocket doesn't depend on SSLConfigService.
1095 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
1096 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1097 base::Unretained(this)),
1098 net_log_);
1101 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1102 verifier_.reset();
1104 if (!start_cert_verification_time_.is_null()) {
1105 base::TimeDelta verify_time =
1106 base::TimeTicks::Now() - start_cert_verification_time_;
1107 if (result == OK) {
1108 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1109 } else {
1110 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1114 if (result == OK) {
1115 if (SSL_session_reused(ssl_)) {
1116 // Record whether or not the server tried to resume a session for a
1117 // different version. See https://crbug.com/441456.
1118 UMA_HISTOGRAM_BOOLEAN(
1119 "Net.SSLSessionVersionMatch",
1120 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1124 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1125 if (transport_security_state_ &&
1126 (result == OK ||
1127 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1128 !transport_security_state_->CheckPublicKeyPins(
1129 host_and_port_.host(),
1130 server_cert_verify_result_.is_issued_by_known_root,
1131 server_cert_verify_result_.public_key_hashes,
1132 &pinning_failure_log_)) {
1133 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1136 if (result == OK) {
1137 // Only check Certificate Transparency if there were no other errors with
1138 // the connection.
1139 VerifyCT();
1141 DCHECK(!certificate_verified_);
1142 certificate_verified_ = true;
1143 MaybeCacheSession();
1144 } else {
1145 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1146 << " (" << result << ")";
1149 completed_connect_ = true;
1150 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1151 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1152 return result;
1155 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1156 if (!user_connect_callback_.is_null()) {
1157 CompletionCallback c = user_connect_callback_;
1158 user_connect_callback_.Reset();
1159 c.Run(rv > OK ? OK : rv);
1163 void SSLClientSocketOpenSSL::UpdateServerCert() {
1164 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
1165 server_cert_ = server_cert_chain_->AsOSChain();
1166 if (server_cert_.get()) {
1167 net_log_.AddEvent(
1168 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1169 base::Bind(&NetLogX509CertificateCallback,
1170 base::Unretained(server_cert_.get())));
1174 void SSLClientSocketOpenSSL::VerifyCT() {
1175 if (!cert_transparency_verifier_)
1176 return;
1178 const uint8_t* ocsp_response_raw;
1179 size_t ocsp_response_len;
1180 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1181 std::string ocsp_response;
1182 if (ocsp_response_len > 0) {
1183 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1184 ocsp_response_len);
1187 const uint8_t* sct_list_raw;
1188 size_t sct_list_len;
1189 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1190 std::string sct_list;
1191 if (sct_list_len > 0)
1192 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1194 // Note that this is a completely synchronous operation: The CT Log Verifier
1195 // gets all the data it needs for SCT verification and does not do any
1196 // external communication.
1197 cert_transparency_verifier_->Verify(
1198 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1199 &ct_verify_result_, net_log_);
1201 if (!policy_enforcer_) {
1202 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1203 } else {
1204 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1205 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1206 SSLConfigService::GetEVCertsWhitelist();
1207 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1208 server_cert_verify_result_.verified_cert.get(),
1209 ev_whitelist.get(), ct_verify_result_, net_log_)) {
1210 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1211 VLOG(1) << "EV certificate for "
1212 << server_cert_verify_result_.verified_cert->subject()
1213 .GetDisplayName()
1214 << " does not conform to CT policy, removing EV status.";
1215 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1221 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1222 int rv = DoHandshakeLoop(result);
1223 if (rv != ERR_IO_PENDING) {
1224 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1225 DoConnectCallback(rv);
1229 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1230 if (next_handshake_state_ == STATE_HANDSHAKE) {
1231 // In handshake phase.
1232 OnHandshakeIOComplete(result);
1233 return;
1236 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1237 // handshake is in progress.
1238 int rv_read = ERR_IO_PENDING;
1239 int rv_write = ERR_IO_PENDING;
1240 bool network_moved;
1241 do {
1242 if (user_read_buf_.get())
1243 rv_read = DoPayloadRead();
1244 if (user_write_buf_.get())
1245 rv_write = DoPayloadWrite();
1246 network_moved = DoTransportIO();
1247 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1248 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1250 // Performing the Read callback may cause |this| to be deleted. If this
1251 // happens, the Write callback should not be invoked. Guard against this by
1252 // holding a WeakPtr to |this| and ensuring it's still valid.
1253 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1254 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1255 DoReadCallback(rv_read);
1257 if (!guard.get())
1258 return;
1260 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1261 DoWriteCallback(rv_write);
1264 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1265 if (next_handshake_state_ == STATE_HANDSHAKE) {
1266 // In handshake phase.
1267 OnHandshakeIOComplete(result);
1268 return;
1271 // Network layer received some data, check if client requested to read
1272 // decrypted data.
1273 if (!user_read_buf_.get())
1274 return;
1276 int rv = DoReadLoop();
1277 if (rv != ERR_IO_PENDING)
1278 DoReadCallback(rv);
1281 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1282 int rv = last_io_result;
1283 do {
1284 // Default to STATE_NONE for next state.
1285 // (This is a quirk carried over from the windows
1286 // implementation. It makes reading the logs a bit harder.)
1287 // State handlers can and often do call GotoState just
1288 // to stay in the current state.
1289 State state = next_handshake_state_;
1290 GotoState(STATE_NONE);
1291 switch (state) {
1292 case STATE_HANDSHAKE:
1293 rv = DoHandshake();
1294 break;
1295 case STATE_CHANNEL_ID_LOOKUP:
1296 DCHECK_EQ(OK, rv);
1297 rv = DoChannelIDLookup();
1298 break;
1299 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1300 rv = DoChannelIDLookupComplete(rv);
1301 break;
1302 case STATE_VERIFY_CERT:
1303 DCHECK_EQ(OK, rv);
1304 rv = DoVerifyCert(rv);
1305 break;
1306 case STATE_VERIFY_CERT_COMPLETE:
1307 rv = DoVerifyCertComplete(rv);
1308 break;
1309 case STATE_NONE:
1310 default:
1311 rv = ERR_UNEXPECTED;
1312 NOTREACHED() << "unexpected state" << state;
1313 break;
1316 bool network_moved = DoTransportIO();
1317 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1318 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1319 // special case we keep looping even if rv is ERR_IO_PENDING because
1320 // the transport IO may allow DoHandshake to make progress.
1321 rv = OK; // This causes us to stay in the loop.
1323 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1324 return rv;
1327 int SSLClientSocketOpenSSL::DoReadLoop() {
1328 bool network_moved;
1329 int rv;
1330 do {
1331 rv = DoPayloadRead();
1332 network_moved = DoTransportIO();
1333 } while (rv == ERR_IO_PENDING && network_moved);
1335 return rv;
1338 int SSLClientSocketOpenSSL::DoWriteLoop() {
1339 bool network_moved;
1340 int rv;
1341 do {
1342 rv = DoPayloadWrite();
1343 network_moved = DoTransportIO();
1344 } while (rv == ERR_IO_PENDING && network_moved);
1346 return rv;
1349 int SSLClientSocketOpenSSL::DoPayloadRead() {
1350 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1352 DCHECK_LT(0, user_read_buf_len_);
1353 DCHECK(user_read_buf_.get());
1355 int rv;
1356 if (pending_read_error_ != kNoPendingReadResult) {
1357 rv = pending_read_error_;
1358 pending_read_error_ = kNoPendingReadResult;
1359 if (rv == 0) {
1360 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1361 rv, user_read_buf_->data());
1362 } else {
1363 net_log_.AddEvent(
1364 NetLog::TYPE_SSL_READ_ERROR,
1365 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1366 pending_read_error_info_));
1368 pending_read_ssl_error_ = SSL_ERROR_NONE;
1369 pending_read_error_info_ = OpenSSLErrorInfo();
1370 return rv;
1373 int total_bytes_read = 0;
1374 int ssl_ret;
1375 do {
1376 ssl_ret = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1377 user_read_buf_len_ - total_bytes_read);
1378 if (ssl_ret > 0)
1379 total_bytes_read += ssl_ret;
1380 } while (total_bytes_read < user_read_buf_len_ && ssl_ret > 0);
1382 // Although only the final SSL_read call may have failed, the failure needs to
1383 // processed immediately, while the information still available in OpenSSL's
1384 // error queue.
1385 if (client_auth_cert_needed_) {
1386 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1387 } else if (ssl_ret <= 0) {
1388 // A zero return from SSL_read may mean any of:
1389 // - The underlying BIO_read returned 0.
1390 // - The peer sent a close_notify.
1391 // - Any arbitrary error. https://crbug.com/466303
1393 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1394 // error, so it does not occur. The second and third are distinguished by
1395 // SSL_ERROR_ZERO_RETURN.
1396 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1397 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1398 pending_read_error_ = 0;
1399 } else {
1400 pending_read_error_ = MapOpenSSLErrorWithDetails(
1401 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
1404 // Many servers do not reliably send a close_notify alert when shutting down
1405 // a connection, and instead terminate the TCP connection. This is reported
1406 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1407 // graceful EOF, instead of treating it as an error as it should be.
1408 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1409 pending_read_error_ = 0;
1412 if (total_bytes_read > 0) {
1413 // Return any bytes read to the caller. The error will be deferred to the
1414 // next call of DoPayloadRead.
1415 rv = total_bytes_read;
1417 // Do not treat insufficient data as an error to return in the next call to
1418 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1419 // again. This is because DoTransportIO() may complete in between the next
1420 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1421 // subsequent invocations to see if a complete record may now be read.
1422 if (pending_read_error_ == ERR_IO_PENDING)
1423 pending_read_error_ = kNoPendingReadResult;
1424 } else {
1425 // No bytes were returned. Return the pending read error immediately.
1426 DCHECK_NE(kNoPendingReadResult, pending_read_error_);
1427 rv = pending_read_error_;
1428 pending_read_error_ = kNoPendingReadResult;
1431 if (rv >= 0) {
1432 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1433 user_read_buf_->data());
1434 } else if (rv != ERR_IO_PENDING) {
1435 net_log_.AddEvent(
1436 NetLog::TYPE_SSL_READ_ERROR,
1437 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1438 pending_read_error_info_));
1439 pending_read_ssl_error_ = SSL_ERROR_NONE;
1440 pending_read_error_info_ = OpenSSLErrorInfo();
1442 return rv;
1445 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1446 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1447 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1449 if (rv >= 0) {
1450 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1451 user_write_buf_->data());
1452 return rv;
1455 int ssl_error = SSL_get_error(ssl_, rv);
1456 OpenSSLErrorInfo error_info;
1457 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1458 &error_info);
1460 if (net_error != ERR_IO_PENDING) {
1461 net_log_.AddEvent(
1462 NetLog::TYPE_SSL_WRITE_ERROR,
1463 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1465 return net_error;
1468 int SSLClientSocketOpenSSL::BufferSend(void) {
1469 if (transport_send_busy_)
1470 return ERR_IO_PENDING;
1472 size_t buffer_read_offset;
1473 uint8_t* read_buf;
1474 size_t max_read;
1475 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1476 &buffer_read_offset, &max_read);
1477 DCHECK_EQ(status, 1); // Should never fail.
1478 if (!max_read)
1479 return 0; // Nothing pending in the OpenSSL write BIO.
1480 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1481 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1482 send_buffer_->set_offset(buffer_read_offset);
1484 int rv = transport_->socket()->Write(
1485 send_buffer_.get(), max_read,
1486 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1487 base::Unretained(this)));
1488 if (rv == ERR_IO_PENDING) {
1489 transport_send_busy_ = true;
1490 } else {
1491 TransportWriteComplete(rv);
1493 return rv;
1496 int SSLClientSocketOpenSSL::BufferRecv(void) {
1497 if (transport_recv_busy_)
1498 return ERR_IO_PENDING;
1500 // Determine how much was requested from |transport_bio_| that was not
1501 // actually available.
1502 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1503 if (requested == 0) {
1504 // This is not a perfect match of error codes, as no operation is
1505 // actually pending. However, returning 0 would be interpreted as
1506 // a possible sign of EOF, which is also an inappropriate match.
1507 return ERR_IO_PENDING;
1510 // Known Issue: While only reading |requested| data is the more correct
1511 // implementation, it has the downside of resulting in frequent reads:
1512 // One read for the SSL record header (~5 bytes) and one read for the SSL
1513 // record body. Rather than issuing these reads to the underlying socket
1514 // (and constantly allocating new IOBuffers), a single Read() request to
1515 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1516 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1517 // traffic, this over-subscribed Read()ing will not cause issues.
1519 size_t buffer_write_offset;
1520 uint8_t* write_buf;
1521 size_t max_write;
1522 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1523 &buffer_write_offset, &max_write);
1524 DCHECK_EQ(status, 1); // Should never fail.
1525 if (!max_write)
1526 return ERR_IO_PENDING;
1528 CHECK_EQ(write_buf,
1529 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1530 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1532 recv_buffer_->set_offset(buffer_write_offset);
1533 int rv = transport_->socket()->Read(
1534 recv_buffer_.get(),
1535 max_write,
1536 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1537 base::Unretained(this)));
1538 if (rv == ERR_IO_PENDING) {
1539 transport_recv_busy_ = true;
1540 } else {
1541 rv = TransportReadComplete(rv);
1543 return rv;
1546 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1547 TransportWriteComplete(result);
1548 OnSendComplete(result);
1551 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1552 result = TransportReadComplete(result);
1553 OnRecvComplete(result);
1556 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1557 DCHECK(ERR_IO_PENDING != result);
1558 int bytes_written = 0;
1559 if (result < 0) {
1560 // Record the error. Save it to be reported in a future read or write on
1561 // transport_bio_'s peer.
1562 transport_write_error_ = result;
1563 } else {
1564 bytes_written = result;
1566 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1567 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1568 DCHECK_EQ(1, ret);
1569 transport_send_busy_ = false;
1572 int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1573 DCHECK(ERR_IO_PENDING != result);
1574 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1575 // does not report success.
1576 if (result == 0)
1577 result = ERR_CONNECTION_CLOSED;
1578 int bytes_read = 0;
1579 if (result < 0) {
1580 DVLOG(1) << "TransportReadComplete result " << result;
1581 // Received an error. Save it to be reported in a future read on
1582 // transport_bio_'s peer.
1583 transport_read_error_ = result;
1584 } else {
1585 bytes_read = result;
1587 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1588 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1589 DCHECK_EQ(1, ret);
1590 transport_recv_busy_ = false;
1591 return result;
1594 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
1595 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1596 DCHECK(ssl == ssl_);
1598 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1600 // Clear any currently configured certificates.
1601 SSL_certs_clear(ssl_);
1603 #if defined(OS_IOS)
1604 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1605 LOG(WARNING) << "Client auth is not supported";
1606 #else // !defined(OS_IOS)
1607 if (!ssl_config_.send_client_cert) {
1608 // First pass: we know that a client certificate is needed, but we do not
1609 // have one at hand.
1610 client_auth_cert_needed_ = true;
1611 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1612 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
1613 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1614 unsigned char* str = NULL;
1615 int length = i2d_X509_NAME(ca_name, &str);
1616 cert_authorities_.push_back(std::string(
1617 reinterpret_cast<const char*>(str),
1618 static_cast<size_t>(length)));
1619 OPENSSL_free(str);
1622 const unsigned char* client_cert_types;
1623 size_t num_client_cert_types =
1624 SSL_get0_certificate_types(ssl, &client_cert_types);
1625 for (size_t i = 0; i < num_client_cert_types; i++) {
1626 cert_key_types_.push_back(
1627 static_cast<SSLClientCertType>(client_cert_types[i]));
1630 return -1; // Suspends handshake.
1633 // Second pass: a client certificate should have been selected.
1634 if (ssl_config_.client_cert.get()) {
1635 ScopedX509 leaf_x509 =
1636 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1637 if (!leaf_x509) {
1638 LOG(WARNING) << "Failed to import certificate";
1639 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1640 return -1;
1643 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1644 ssl_config_.client_cert->GetIntermediateCertificates());
1645 if (!chain) {
1646 LOG(WARNING) << "Failed to import intermediate certificates";
1647 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1648 return -1;
1651 // TODO(davidben): With Linux client auth support, this should be
1652 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1653 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1654 // net/ client auth API lacking a private key handle.
1655 #if defined(USE_OPENSSL_CERTS)
1656 crypto::ScopedEVP_PKEY privkey =
1657 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1658 ssl_config_.client_cert.get());
1659 #else // !defined(USE_OPENSSL_CERTS)
1660 crypto::ScopedEVP_PKEY privkey =
1661 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1662 #endif // defined(USE_OPENSSL_CERTS)
1663 if (!privkey) {
1664 // Could not find the private key. Fail the handshake and surface an
1665 // appropriate error to the caller.
1666 LOG(WARNING) << "Client cert found without private key";
1667 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1668 return -1;
1671 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1672 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1673 !SSL_set1_chain(ssl_, chain.get())) {
1674 LOG(WARNING) << "Failed to set client certificate";
1675 return -1;
1678 int cert_count = 1 + sk_X509_num(chain.get());
1679 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1680 NetLog::IntegerCallback("cert_count", cert_count));
1681 return 1;
1683 #endif // defined(OS_IOS)
1685 // Send no client certificate.
1686 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1687 NetLog::IntegerCallback("cert_count", 0));
1688 return 1;
1691 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1692 if (!completed_connect_) {
1693 // If the first handshake hasn't completed then we accept any certificates
1694 // because we verify after the handshake.
1695 return 1;
1698 // Disallow the server certificate to change in a renegotiation.
1699 if (server_cert_chain_->empty()) {
1700 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1701 return 0;
1703 base::StringPiece old_der, new_der;
1704 if (store_ctx->cert == NULL ||
1705 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1706 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1707 LOG(ERROR) << "Failed to encode certificates";
1708 return 0;
1710 if (old_der != new_der) {
1711 LOG(ERROR) << "Server certificate changed between handshakes";
1712 return 0;
1715 return 1;
1718 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1719 // server supports NPN, selects a protocol from the list that the server
1720 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1721 // callback can assume that |in| is syntactically valid.
1722 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1723 unsigned char* outlen,
1724 const unsigned char* in,
1725 unsigned int inlen) {
1726 if (ssl_config_.next_protos.empty()) {
1727 *out = reinterpret_cast<uint8*>(
1728 const_cast<char*>(kDefaultSupportedNPNProtocol));
1729 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1730 npn_status_ = kNextProtoUnsupported;
1731 return SSL_TLSEXT_ERR_OK;
1734 // Assume there's no overlap between our protocols and the server's list.
1735 npn_status_ = kNextProtoNoOverlap;
1737 // For each protocol in server preference order, see if we support it.
1738 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1739 for (NextProto next_proto : ssl_config_.next_protos) {
1740 const std::string proto = NextProtoToString(next_proto);
1741 if (in[i] == proto.size() &&
1742 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
1743 // We found a match.
1744 *out = const_cast<unsigned char*>(in) + i + 1;
1745 *outlen = in[i];
1746 npn_status_ = kNextProtoNegotiated;
1747 break;
1750 if (npn_status_ == kNextProtoNegotiated)
1751 break;
1754 // If we didn't find a protocol, we select the first one from our list.
1755 if (npn_status_ == kNextProtoNoOverlap) {
1756 // NextProtoToString returns a pointer to a static string.
1757 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1758 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1759 *outlen = strlen(proto);
1762 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
1763 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
1764 set_negotiation_extension(kExtensionNPN);
1765 return SSL_TLSEXT_ERR_OK;
1768 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1769 BIO *bio,
1770 int cmd,
1771 const char *argp, int argi, long argl,
1772 long retvalue) {
1773 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1774 // If there is no more data in the buffer, report any pending errors that
1775 // were observed. Note that both the readbuf and the writebuf are checked
1776 // for errors, since the application may have encountered a socket error
1777 // while writing that would otherwise not be reported until the application
1778 // attempted to write again - which it may never do. See
1779 // https://crbug.com/249848.
1780 if (transport_read_error_ != OK) {
1781 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1782 return -1;
1784 if (transport_write_error_ != OK) {
1785 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1786 return -1;
1788 } else if (cmd == BIO_CB_WRITE) {
1789 // Because of the write buffer, this reports a failure from the previous
1790 // write payload. If the current payload fails to write, the error will be
1791 // reported in a future write or read to |bio|.
1792 if (transport_write_error_ != OK) {
1793 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1794 return -1;
1797 return retvalue;
1800 // static
1801 long SSLClientSocketOpenSSL::BIOCallback(
1802 BIO *bio,
1803 int cmd,
1804 const char *argp, int argi, long argl,
1805 long retvalue) {
1806 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1807 BIO_get_callback_arg(bio));
1808 CHECK(socket);
1809 return socket->MaybeReplayTransportError(
1810 bio, cmd, argp, argi, argl, retvalue);
1813 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1814 // Only cache the session once both the handshake has completed and the
1815 // certificate has been verified.
1816 if (!handshake_completed_ || !certificate_verified_ ||
1817 SSL_session_reused(ssl_)) {
1818 return;
1821 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1822 SSL_get_session(ssl_));
1825 void SSLClientSocketOpenSSL::InfoCallback(int type, int val) {
1826 // Note that SSL_CB_HANDSHAKE_DONE may be signaled multiple times if the
1827 // socket renegotiates.
1828 if (type != SSL_CB_HANDSHAKE_DONE || handshake_completed_)
1829 return;
1831 handshake_completed_ = true;
1832 MaybeCacheSession();
1835 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1836 for (ct::SCTList::const_iterator iter =
1837 ct_verify_result_.verified_scts.begin();
1838 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1839 ssl_info->signed_certificate_timestamps.push_back(
1840 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1842 for (ct::SCTList::const_iterator iter =
1843 ct_verify_result_.invalid_scts.begin();
1844 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1845 ssl_info->signed_certificate_timestamps.push_back(
1846 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1848 for (ct::SCTList::const_iterator iter =
1849 ct_verify_result_.unknown_logs_scts.begin();
1850 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1851 ssl_info->signed_certificate_timestamps.push_back(
1852 SignedCertificateTimestampAndStatus(*iter,
1853 ct::SCT_STATUS_LOG_UNKNOWN));
1857 std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1858 std::string result = host_and_port_.ToString();
1859 result.append("/");
1860 result.append(ssl_session_cache_shard_);
1862 // Shard the session cache based on maximum protocol version. This causes
1863 // fallback connections to use a separate session cache.
1864 result.append("/");
1865 switch (ssl_config_.version_max) {
1866 case SSL_PROTOCOL_VERSION_SSL3:
1867 result.append("ssl3");
1868 break;
1869 case SSL_PROTOCOL_VERSION_TLS1:
1870 result.append("tls1");
1871 break;
1872 case SSL_PROTOCOL_VERSION_TLS1_1:
1873 result.append("tls1.1");
1874 break;
1875 case SSL_PROTOCOL_VERSION_TLS1_2:
1876 result.append("tls1.2");
1877 break;
1878 default:
1879 NOTREACHED();
1882 result.append("/");
1883 if (ssl_config_.enable_deprecated_cipher_suites)
1884 result.append("deprecated");
1886 return result;
1889 scoped_refptr<X509Certificate>
1890 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1891 return server_cert_;
1894 } // namespace net