Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / net / socket / ssl_client_socket_openssl.cc
blob721b69c02e2a36846d55cc8966b5c5e5c3c7e8f7
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/lazy_instance.h"
21 #include "base/memory/singleton.h"
22 #include "base/metrics/histogram_macros.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/stl_util.h"
25 #include "base/strings/string_piece.h"
26 #include "base/synchronization/lock.h"
27 #include "base/threading/sequenced_worker_pool.h"
28 #include "base/threading/thread_local.h"
29 #include "base/values.h"
30 #include "crypto/ec_private_key.h"
31 #include "crypto/openssl_util.h"
32 #include "crypto/scoped_openssl_types.h"
33 #include "net/base/ip_address_number.h"
34 #include "net/base/net_errors.h"
35 #include "net/cert/cert_policy_enforcer.h"
36 #include "net/cert/cert_verifier.h"
37 #include "net/cert/ct_ev_whitelist.h"
38 #include "net/cert/ct_verifier.h"
39 #include "net/cert/x509_certificate_net_log_param.h"
40 #include "net/cert/x509_util_openssl.h"
41 #include "net/http/transport_security_state.h"
42 #include "net/ssl/scoped_openssl_types.h"
43 #include "net/ssl/ssl_cert_request_info.h"
44 #include "net/ssl/ssl_client_session_cache_openssl.h"
45 #include "net/ssl/ssl_connection_status_flags.h"
46 #include "net/ssl/ssl_failure_state.h"
47 #include "net/ssl/ssl_info.h"
48 #include "net/ssl/ssl_private_key.h"
50 #if defined(OS_WIN)
51 #include "base/win/windows_version.h"
52 #endif
54 #if defined(USE_OPENSSL_CERTS)
55 #include "net/ssl/openssl_client_key_store.h"
56 #else
57 #include "net/ssl/ssl_platform_key.h"
58 #endif
60 namespace net {
62 namespace {
64 // Enable this to see logging for state machine state transitions.
65 #if 0
66 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
67 " jump to state " << s; \
68 next_handshake_state_ = s; } while (0)
69 #else
70 #define GotoState(s) next_handshake_state_ = s
71 #endif
73 // This constant can be any non-negative/non-zero value (eg: it does not
74 // overlap with any value of the net::Error range, including net::OK).
75 const int kNoPendingResult = 1;
77 // If a client doesn't have a list of protocols that it supports, but
78 // the server supports NPN, choosing "http/1.1" is the best answer.
79 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
81 // Default size of the internal BoringSSL buffers.
82 const int KDefaultOpenSSLBufferSize = 17 * 1024;
84 void FreeX509Stack(STACK_OF(X509)* ptr) {
85 sk_X509_pop_free(ptr, X509_free);
88 using ScopedX509Stack = crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>;
90 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
91 // This method doesn't seem to have made it into the OpenSSL headers.
92 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
93 #endif
95 // Used for encoding the |connection_status| field of an SSLInfo object.
96 int EncodeSSLConnectionStatus(uint16 cipher_suite,
97 int compression,
98 int version) {
99 return cipher_suite |
100 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
101 SSL_CONNECTION_COMPRESSION_SHIFT) |
102 ((version & SSL_CONNECTION_VERSION_MASK) <<
103 SSL_CONNECTION_VERSION_SHIFT);
106 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
107 // this SSL connection.
108 int GetNetSSLVersion(SSL* ssl) {
109 switch (SSL_version(ssl)) {
110 case TLS1_VERSION:
111 return SSL_CONNECTION_VERSION_TLS1;
112 case TLS1_1_VERSION:
113 return SSL_CONNECTION_VERSION_TLS1_1;
114 case TLS1_2_VERSION:
115 return SSL_CONNECTION_VERSION_TLS1_2;
116 default:
117 NOTREACHED();
118 return SSL_CONNECTION_VERSION_UNKNOWN;
122 ScopedX509 OSCertHandleToOpenSSL(
123 X509Certificate::OSCertHandle os_handle) {
124 #if defined(USE_OPENSSL_CERTS)
125 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
126 #else // !defined(USE_OPENSSL_CERTS)
127 std::string der_encoded;
128 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
129 return ScopedX509();
130 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
131 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
132 #endif // defined(USE_OPENSSL_CERTS)
135 ScopedX509Stack OSCertHandlesToOpenSSL(
136 const X509Certificate::OSCertHandles& os_handles) {
137 ScopedX509Stack stack(sk_X509_new_null());
138 for (size_t i = 0; i < os_handles.size(); i++) {
139 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
140 if (!x509)
141 return ScopedX509Stack();
142 sk_X509_push(stack.get(), x509.release());
144 return stack.Pass();
147 int LogErrorCallback(const char* str, size_t len, void* context) {
148 LOG(ERROR) << base::StringPiece(str, len);
149 return 1;
152 bool EVP_MDToPrivateKeyHash(const EVP_MD* md, SSLPrivateKey::Hash* hash) {
153 switch (EVP_MD_type(md)) {
154 case NID_md5_sha1:
155 *hash = SSLPrivateKey::Hash::MD5_SHA1;
156 return true;
157 case NID_sha1:
158 *hash = SSLPrivateKey::Hash::SHA1;
159 return true;
160 case NID_sha256:
161 *hash = SSLPrivateKey::Hash::SHA256;
162 return true;
163 case NID_sha384:
164 *hash = SSLPrivateKey::Hash::SHA384;
165 return true;
166 case NID_sha512:
167 *hash = SSLPrivateKey::Hash::SHA512;
168 return true;
169 default:
170 return false;
174 #if !defined(USE_OPENSSL_CERTS)
175 class PlatformKeyTaskRunner {
176 public:
177 PlatformKeyTaskRunner() {
178 // Serialize all the private key operations on a single background
179 // thread to avoid problems with buggy smartcards.
180 worker_pool_ = new base::SequencedWorkerPool(1, "Platform Key Thread");
181 task_runner_ = worker_pool_->GetSequencedTaskRunnerWithShutdownBehavior(
182 worker_pool_->GetSequenceToken(),
183 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN);
186 scoped_refptr<base::SequencedTaskRunner> task_runner() {
187 return task_runner_;
190 private:
191 scoped_refptr<base::SequencedWorkerPool> worker_pool_;
192 scoped_refptr<base::SequencedTaskRunner> task_runner_;
194 DISALLOW_COPY_AND_ASSIGN(PlatformKeyTaskRunner);
197 base::LazyInstance<PlatformKeyTaskRunner>::Leaky g_platform_key_task_runner =
198 LAZY_INSTANCE_INITIALIZER;
199 #endif // !USE_OPENSSL_CERTS
201 } // namespace
203 class SSLClientSocketOpenSSL::SSLContext {
204 public:
205 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
206 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
207 SSLClientSessionCacheOpenSSL* session_cache() { return &session_cache_; }
209 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
210 DCHECK(ssl);
211 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
212 SSL_get_ex_data(ssl, ssl_socket_data_index_));
213 DCHECK(socket);
214 return socket;
217 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
218 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
221 static const SSL_PRIVATE_KEY_METHOD kPrivateKeyMethod;
223 private:
224 friend struct DefaultSingletonTraits<SSLContext>;
226 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
227 crypto::EnsureOpenSSLInit();
228 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
229 DCHECK_NE(ssl_socket_data_index_, -1);
230 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
231 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
232 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
233 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
234 // This stops |SSL_shutdown| from generating the close_notify message, which
235 // is currently not sent on the network.
236 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
237 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
238 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
239 // It would be better if the callback were not a global setting,
240 // but that is an OpenSSL issue.
241 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
242 NULL);
244 // Disable the internal session cache. Session caching is handled
245 // externally (i.e. by SSLClientSessionCacheOpenSSL).
246 SSL_CTX_set_session_cache_mode(
247 ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
248 SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallback);
250 scoped_ptr<base::Environment> env(base::Environment::Create());
251 std::string ssl_keylog_file;
252 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
253 !ssl_keylog_file.empty()) {
254 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
255 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
256 if (!bio) {
257 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
258 ERR_print_errors_cb(&LogErrorCallback, NULL);
259 } else {
260 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
265 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
266 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
267 DCHECK(socket);
268 return socket->ClientCertRequestCallback(ssl);
271 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
272 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
273 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
274 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
275 CHECK(socket);
277 return socket->CertVerifyCallback(store_ctx);
280 static int SelectNextProtoCallback(SSL* ssl,
281 unsigned char** out, unsigned char* outlen,
282 const unsigned char* in,
283 unsigned int inlen, void* arg) {
284 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
285 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
288 static int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
289 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
290 return socket->NewSessionCallback(session);
293 static int PrivateKeyTypeCallback(SSL* ssl) {
294 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
295 return socket->PrivateKeyTypeCallback();
298 static int PrivateKeySupportsDigestCallback(SSL* ssl, const EVP_MD* md) {
299 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
300 return socket->PrivateKeySupportsDigestCallback(md);
303 static size_t PrivateKeyMaxSignatureLenCallback(SSL* ssl) {
304 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
305 return socket->PrivateKeyMaxSignatureLenCallback();
308 static ssl_private_key_result_t PrivateKeySignCallback(SSL* ssl,
309 uint8_t* out,
310 size_t* out_len,
311 size_t max_out,
312 const EVP_MD* md,
313 const uint8_t* in,
314 size_t in_len) {
315 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
316 return socket->PrivateKeySignCallback(out, out_len, max_out, md, in,
317 in_len);
320 static ssl_private_key_result_t PrivateKeySignCompleteCallback(
321 SSL* ssl,
322 uint8_t* out,
323 size_t* out_len,
324 size_t max_out) {
325 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
326 return socket->PrivateKeySignCompleteCallback(out, out_len, max_out);
329 // This is the index used with SSL_get_ex_data to retrieve the owner
330 // SSLClientSocketOpenSSL object from an SSL instance.
331 int ssl_socket_data_index_;
333 ScopedSSL_CTX ssl_ctx_;
335 // TODO(davidben): Use a separate cache per URLRequestContext.
336 // https://crbug.com/458365
338 // TODO(davidben): Sessions should be invalidated on fatal
339 // alerts. https://crbug.com/466352
340 SSLClientSessionCacheOpenSSL session_cache_;
343 const SSL_PRIVATE_KEY_METHOD
344 SSLClientSocketOpenSSL::SSLContext::kPrivateKeyMethod = {
345 &SSLClientSocketOpenSSL::SSLContext::PrivateKeyTypeCallback,
346 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySupportsDigestCallback,
347 &SSLClientSocketOpenSSL::SSLContext::PrivateKeyMaxSignatureLenCallback,
348 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySignCallback,
349 &SSLClientSocketOpenSSL::SSLContext::PrivateKeySignCompleteCallback,
352 // PeerCertificateChain is a helper object which extracts the certificate
353 // chain, as given by the server, from an OpenSSL socket and performs the needed
354 // resource management. The first element of the chain is the leaf certificate
355 // and the other elements are in the order given by the server.
356 class SSLClientSocketOpenSSL::PeerCertificateChain {
357 public:
358 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
359 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
360 ~PeerCertificateChain() {}
361 PeerCertificateChain& operator=(const PeerCertificateChain& other);
363 // Resets the PeerCertificateChain to the set of certificates in|chain|,
364 // which may be NULL, indicating to empty the store certificates.
365 // Note: If an error occurs, such as being unable to parse the certificates,
366 // this will behave as if Reset(NULL) was called.
367 void Reset(STACK_OF(X509)* chain);
369 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
370 scoped_refptr<X509Certificate> AsOSChain() const;
372 size_t size() const {
373 if (!openssl_chain_.get())
374 return 0;
375 return sk_X509_num(openssl_chain_.get());
378 bool empty() const {
379 return size() == 0;
382 X509* Get(size_t index) const {
383 DCHECK_LT(index, size());
384 return sk_X509_value(openssl_chain_.get(), index);
387 private:
388 ScopedX509Stack openssl_chain_;
391 SSLClientSocketOpenSSL::PeerCertificateChain&
392 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
393 const PeerCertificateChain& other) {
394 if (this == &other)
395 return *this;
397 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
398 return *this;
401 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
402 STACK_OF(X509)* chain) {
403 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
406 scoped_refptr<X509Certificate>
407 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
408 #if defined(USE_OPENSSL_CERTS)
409 // When OSCertHandle is typedef'ed to X509, this implementation does a short
410 // cut to avoid converting back and forth between DER and the X509 struct.
411 X509Certificate::OSCertHandles intermediates;
412 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
413 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
416 return make_scoped_refptr(X509Certificate::CreateFromHandle(
417 sk_X509_value(openssl_chain_.get(), 0), intermediates));
418 #else
419 // DER-encode the chain and convert to a platform certificate handle.
420 std::vector<base::StringPiece> der_chain;
421 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
422 X509* x = sk_X509_value(openssl_chain_.get(), i);
423 base::StringPiece der;
424 if (!x509_util::GetDER(x, &der))
425 return NULL;
426 der_chain.push_back(der);
429 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
430 #endif
433 // static
434 void SSLClientSocket::ClearSessionCache() {
435 SSLClientSocketOpenSSL::SSLContext* context =
436 SSLClientSocketOpenSSL::SSLContext::GetInstance();
437 context->session_cache()->Flush();
440 // static
441 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
442 return SSL_PROTOCOL_VERSION_TLS1_2;
445 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
446 scoped_ptr<ClientSocketHandle> transport_socket,
447 const HostPortPair& host_and_port,
448 const SSLConfig& ssl_config,
449 const SSLClientSocketContext& context)
450 : transport_send_busy_(false),
451 transport_recv_busy_(false),
452 pending_read_error_(kNoPendingResult),
453 pending_read_ssl_error_(SSL_ERROR_NONE),
454 transport_read_error_(OK),
455 transport_write_error_(OK),
456 server_cert_chain_(new PeerCertificateChain(NULL)),
457 completed_connect_(false),
458 was_ever_used_(false),
459 cert_verifier_(context.cert_verifier),
460 cert_transparency_verifier_(context.cert_transparency_verifier),
461 channel_id_service_(context.channel_id_service),
462 ssl_(NULL),
463 transport_bio_(NULL),
464 transport_(transport_socket.Pass()),
465 host_and_port_(host_and_port),
466 ssl_config_(ssl_config),
467 ssl_session_cache_shard_(context.ssl_session_cache_shard),
468 next_handshake_state_(STATE_NONE),
469 disconnected_(false),
470 npn_status_(kNextProtoUnsupported),
471 channel_id_sent_(false),
472 session_pending_(false),
473 certificate_verified_(false),
474 ssl_failure_state_(SSL_FAILURE_NONE),
475 signature_result_(kNoPendingResult),
476 transport_security_state_(context.transport_security_state),
477 policy_enforcer_(context.cert_policy_enforcer),
478 net_log_(transport_->socket()->NetLog()),
479 weak_factory_(this) {
480 DCHECK(cert_verifier_);
483 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
484 Disconnect();
487 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
488 SSLCertRequestInfo* cert_request_info) {
489 cert_request_info->host_and_port = host_and_port_;
490 cert_request_info->cert_authorities = cert_authorities_;
491 cert_request_info->cert_key_types = cert_key_types_;
494 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
495 std::string* proto) const {
496 *proto = npn_proto_;
497 return npn_status_;
500 ChannelIDService*
501 SSLClientSocketOpenSSL::GetChannelIDService() const {
502 return channel_id_service_;
505 SSLFailureState SSLClientSocketOpenSSL::GetSSLFailureState() const {
506 return ssl_failure_state_;
509 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
510 const base::StringPiece& label,
511 bool has_context, const base::StringPiece& context,
512 unsigned char* out, unsigned int outlen) {
513 if (!IsConnected())
514 return ERR_SOCKET_NOT_CONNECTED;
516 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
518 int rv = SSL_export_keying_material(
519 ssl_, out, outlen, label.data(), label.size(),
520 reinterpret_cast<const unsigned char*>(context.data()), context.length(),
521 has_context ? 1 : 0);
523 if (rv != 1) {
524 int ssl_error = SSL_get_error(ssl_, rv);
525 LOG(ERROR) << "Failed to export keying material;"
526 << " returned " << rv
527 << ", SSL error code " << ssl_error;
528 return MapOpenSSLError(ssl_error, err_tracer);
530 return OK;
533 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
534 NOTIMPLEMENTED();
535 return ERR_NOT_IMPLEMENTED;
538 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
539 // It is an error to create an SSLClientSocket whose context has no
540 // TransportSecurityState.
541 DCHECK(transport_security_state_);
543 // Although StreamSocket does allow calling Connect() after Disconnect(),
544 // this has never worked for layered sockets. CHECK to detect any consumers
545 // reconnecting an SSL socket.
547 // TODO(davidben,mmenke): Remove this API feature. See
548 // https://crbug.com/499289.
549 CHECK(!disconnected_);
551 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
553 // Set up new ssl object.
554 int rv = Init();
555 if (rv != OK) {
556 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
557 return rv;
560 // Set SSL to client mode. Handshake happens in the loop below.
561 SSL_set_connect_state(ssl_);
563 GotoState(STATE_HANDSHAKE);
564 rv = DoHandshakeLoop(OK);
565 if (rv == ERR_IO_PENDING) {
566 user_connect_callback_ = callback;
567 } else {
568 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
571 return rv > OK ? OK : rv;
574 void SSLClientSocketOpenSSL::Disconnect() {
575 if (ssl_) {
576 // Calling SSL_shutdown prevents the session from being marked as
577 // unresumable.
578 SSL_shutdown(ssl_);
579 SSL_free(ssl_);
580 ssl_ = NULL;
582 if (transport_bio_) {
583 BIO_free_all(transport_bio_);
584 transport_bio_ = NULL;
587 disconnected_ = true;
589 // Shut down anything that may call us back.
590 cert_verifier_request_.reset();
591 transport_->socket()->Disconnect();
593 // Null all callbacks, delete all buffers.
594 transport_send_busy_ = false;
595 send_buffer_ = NULL;
596 transport_recv_busy_ = false;
597 recv_buffer_ = NULL;
599 user_connect_callback_.Reset();
600 user_read_callback_.Reset();
601 user_write_callback_.Reset();
602 user_read_buf_ = NULL;
603 user_read_buf_len_ = 0;
604 user_write_buf_ = NULL;
605 user_write_buf_len_ = 0;
607 pending_read_error_ = kNoPendingResult;
608 pending_read_ssl_error_ = SSL_ERROR_NONE;
609 pending_read_error_info_ = OpenSSLErrorInfo();
611 transport_read_error_ = OK;
612 transport_write_error_ = OK;
614 server_cert_verify_result_.Reset();
615 completed_connect_ = false;
617 cert_authorities_.clear();
618 cert_key_types_.clear();
620 start_cert_verification_time_ = base::TimeTicks();
622 npn_status_ = kNextProtoUnsupported;
623 npn_proto_.clear();
625 channel_id_sent_ = false;
626 session_pending_ = false;
627 certificate_verified_ = false;
628 channel_id_request_.Cancel();
629 ssl_failure_state_ = SSL_FAILURE_NONE;
631 private_key_.reset();
632 signature_result_ = kNoPendingResult;
633 signature_.clear();
636 bool SSLClientSocketOpenSSL::IsConnected() const {
637 // If the handshake has not yet completed.
638 if (!completed_connect_)
639 return false;
640 // If an asynchronous operation is still pending.
641 if (user_read_buf_.get() || user_write_buf_.get())
642 return true;
644 return transport_->socket()->IsConnected();
647 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
648 // If the handshake has not yet completed.
649 if (!completed_connect_)
650 return false;
651 // If an asynchronous operation is still pending.
652 if (user_read_buf_.get() || user_write_buf_.get())
653 return false;
655 // If there is data read from the network that has not yet been consumed, do
656 // not treat the connection as idle.
658 // Note that this does not check |BIO_pending|, whether there is ciphertext
659 // that has not yet been flushed to the network. |Write| returns early, so
660 // this can cause race conditions which cause a socket to not be treated
661 // reusable when it should be. See https://crbug.com/466147.
662 if (BIO_wpending(transport_bio_) > 0)
663 return false;
665 return transport_->socket()->IsConnectedAndIdle();
668 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
669 return transport_->socket()->GetPeerAddress(addressList);
672 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
673 return transport_->socket()->GetLocalAddress(addressList);
676 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
677 return net_log_;
680 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
681 if (transport_.get() && transport_->socket()) {
682 transport_->socket()->SetSubresourceSpeculation();
683 } else {
684 NOTREACHED();
688 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
689 if (transport_.get() && transport_->socket()) {
690 transport_->socket()->SetOmniboxSpeculation();
691 } else {
692 NOTREACHED();
696 bool SSLClientSocketOpenSSL::WasEverUsed() const {
697 return was_ever_used_;
700 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
701 if (transport_.get() && transport_->socket())
702 return transport_->socket()->UsingTCPFastOpen();
704 NOTREACHED();
705 return false;
708 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
709 ssl_info->Reset();
710 if (server_cert_chain_->empty())
711 return false;
713 ssl_info->cert = server_cert_verify_result_.verified_cert;
714 ssl_info->unverified_cert = server_cert_;
715 ssl_info->cert_status = server_cert_verify_result_.cert_status;
716 ssl_info->is_issued_by_known_root =
717 server_cert_verify_result_.is_issued_by_known_root;
718 ssl_info->public_key_hashes =
719 server_cert_verify_result_.public_key_hashes;
720 ssl_info->client_cert_sent =
721 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
722 ssl_info->channel_id_sent = channel_id_sent_;
723 ssl_info->pinning_failure_log = pinning_failure_log_;
725 AddSCTInfoToSSLInfo(ssl_info);
727 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
728 CHECK(cipher);
729 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
731 ssl_info->connection_status = EncodeSSLConnectionStatus(
732 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
733 GetNetSSLVersion(ssl_));
735 if (!SSL_get_secure_renegotiation_support(ssl_))
736 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
738 if (ssl_config_.version_fallback)
739 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
741 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
742 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
744 DVLOG(3) << "Encoded connection status: cipher suite = "
745 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
746 << " version = "
747 << SSLConnectionStatusToVersion(ssl_info->connection_status);
748 return true;
751 void SSLClientSocketOpenSSL::GetConnectionAttempts(
752 ConnectionAttempts* out) const {
753 out->clear();
756 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
757 int buf_len,
758 const CompletionCallback& callback) {
759 user_read_buf_ = buf;
760 user_read_buf_len_ = buf_len;
762 int rv = DoReadLoop();
764 if (rv == ERR_IO_PENDING) {
765 user_read_callback_ = callback;
766 } else {
767 if (rv > 0)
768 was_ever_used_ = true;
769 user_read_buf_ = NULL;
770 user_read_buf_len_ = 0;
773 return rv;
776 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
777 int buf_len,
778 const CompletionCallback& callback) {
779 user_write_buf_ = buf;
780 user_write_buf_len_ = buf_len;
782 int rv = DoWriteLoop();
784 if (rv == ERR_IO_PENDING) {
785 user_write_callback_ = callback;
786 } else {
787 if (rv > 0)
788 was_ever_used_ = true;
789 user_write_buf_ = NULL;
790 user_write_buf_len_ = 0;
793 return rv;
796 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
797 return transport_->socket()->SetReceiveBufferSize(size);
800 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
801 return transport_->socket()->SetSendBufferSize(size);
804 int SSLClientSocketOpenSSL::Init() {
805 DCHECK(!ssl_);
806 DCHECK(!transport_bio_);
808 SSLContext* context = SSLContext::GetInstance();
809 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
811 ssl_ = SSL_new(context->ssl_ctx());
812 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
813 return ERR_UNEXPECTED;
815 // SNI should only contain valid DNS hostnames, not IP addresses (see RFC
816 // 6066, Section 3).
818 // TODO(rsleevi): Should this code allow hostnames that violate the LDH rule?
819 // See https://crbug.com/496472 and https://crbug.com/496468 for discussion.
820 IPAddressNumber unused;
821 if (!ParseIPLiteralToNumber(host_and_port_.host(), &unused) &&
822 !SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str())) {
823 return ERR_UNEXPECTED;
826 SSL_SESSION* session = context->session_cache()->Lookup(GetSessionCacheKey());
827 if (session != nullptr)
828 SSL_set_session(ssl_, session);
830 send_buffer_ = new GrowableIOBuffer();
831 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
832 recv_buffer_ = new GrowableIOBuffer();
833 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
835 BIO* ssl_bio = NULL;
837 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
838 if (!BIO_new_bio_pair_external_buf(
839 &ssl_bio, send_buffer_->capacity(),
840 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
841 recv_buffer_->capacity(),
842 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
843 return ERR_UNEXPECTED;
844 DCHECK(ssl_bio);
845 DCHECK(transport_bio_);
847 // Install a callback on OpenSSL's end to plumb transport errors through.
848 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
849 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
851 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
853 DCHECK_LT(SSL3_VERSION, ssl_config_.version_min);
854 DCHECK_LT(SSL3_VERSION, ssl_config_.version_max);
855 SSL_set_min_version(ssl_, ssl_config_.version_min);
856 SSL_set_max_version(ssl_, ssl_config_.version_max);
858 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
859 // set everything we care about to an absolute value.
860 SslSetClearMask options;
861 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
863 // TODO(joth): Set this conditionally, see http://crbug.com/55410
864 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
866 SSL_set_options(ssl_, options.set_mask);
867 SSL_clear_options(ssl_, options.clear_mask);
869 // Same as above, this time for the SSL mode.
870 SslSetClearMask mode;
872 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
873 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
875 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START,
876 ssl_config_.false_start_enabled);
878 mode.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV, ssl_config_.version_fallback);
880 SSL_set_mode(ssl_, mode.set_mask);
881 SSL_clear_mode(ssl_, mode.clear_mask);
883 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
884 // textual name with SSL_set_cipher_list because there is no public API to
885 // directly remove a cipher by ID.
886 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
887 DCHECK(ciphers);
888 // See SSLConfig::disabled_cipher_suites for description of the suites
889 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
890 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
891 // as the handshake hash.
892 std::string command("DEFAULT:!SHA256:!SHA384:!AESGCM+AES256:!aPSK");
893 // Walk through all the installed ciphers, seeing if any need to be
894 // appended to the cipher removal |command|.
895 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
896 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
897 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
898 bool disable = false;
899 if (ssl_config_.require_ecdhe) {
900 base::StringPiece kx_name(SSL_CIPHER_get_kx_name(cipher));
901 disable = kx_name != "ECDHE_RSA" && kx_name != "ECDHE_ECDSA";
903 if (!disable) {
904 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
905 ssl_config_.disabled_cipher_suites.end(), id) !=
906 ssl_config_.disabled_cipher_suites.end();
908 if (disable) {
909 const char* name = SSL_CIPHER_get_name(cipher);
910 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
911 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
912 command.append(":!");
913 command.append(name);
917 if (!ssl_config_.enable_deprecated_cipher_suites)
918 command.append(":!RC4");
920 // Disable ECDSA cipher suites on platforms that do not support ECDSA
921 // signed certificates, as servers may use the presence of such
922 // ciphersuites as a hint to send an ECDSA certificate.
923 #if defined(OS_WIN)
924 if (base::win::GetVersion() < base::win::VERSION_VISTA)
925 command.append(":!ECDSA");
926 #endif
928 int rv = SSL_set_cipher_list(ssl_, command.c_str());
929 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
930 // This will almost certainly result in the socket failing to complete the
931 // handshake at which point the appropriate error is bubbled up to the client.
932 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
933 "returned " << rv;
935 // TLS channel ids.
936 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
937 SSL_enable_tls_channel_id(ssl_);
940 if (!ssl_config_.next_protos.empty()) {
941 // Get list of ciphers that are enabled.
942 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
943 DCHECK(enabled_ciphers);
944 std::vector<uint16> enabled_ciphers_vector;
945 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
946 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
947 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
948 enabled_ciphers_vector.push_back(id);
951 std::vector<uint8_t> wire_protos =
952 SerializeNextProtos(ssl_config_.next_protos,
953 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
954 IsTLSVersionAdequateForHTTP2(ssl_config_));
955 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
956 wire_protos.size());
959 if (ssl_config_.signed_cert_timestamps_enabled) {
960 SSL_enable_signed_cert_timestamps(ssl_);
961 SSL_enable_ocsp_stapling(ssl_);
964 if (cert_verifier_->SupportsOCSPStapling())
965 SSL_enable_ocsp_stapling(ssl_);
967 // By default, renegotiations are rejected. After the initial handshake
968 // completes, some application protocols may re-enable it.
969 SSL_set_reject_peer_renegotiations(ssl_, 1);
971 return OK;
974 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
975 // Since Run may result in Read being called, clear |user_read_callback_|
976 // up front.
977 if (rv > 0)
978 was_ever_used_ = true;
979 user_read_buf_ = NULL;
980 user_read_buf_len_ = 0;
981 base::ResetAndReturn(&user_read_callback_).Run(rv);
984 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
985 // Since Run may result in Write being called, clear |user_write_callback_|
986 // up front.
987 if (rv > 0)
988 was_ever_used_ = true;
989 user_write_buf_ = NULL;
990 user_write_buf_len_ = 0;
991 base::ResetAndReturn(&user_write_callback_).Run(rv);
994 bool SSLClientSocketOpenSSL::DoTransportIO() {
995 bool network_moved = false;
996 int rv;
997 // Read and write as much data as possible. The loop is necessary because
998 // Write() may return synchronously.
999 do {
1000 rv = BufferSend();
1001 if (rv != ERR_IO_PENDING && rv != 0)
1002 network_moved = true;
1003 } while (rv > 0);
1004 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
1005 network_moved = true;
1006 return network_moved;
1009 // TODO(cbentzel): Remove including "base/threading/thread_local.h" and
1010 // g_first_run_completed once crbug.com/424386 is fixed.
1011 base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
1012 LAZY_INSTANCE_INITIALIZER;
1014 int SSLClientSocketOpenSSL::DoHandshake() {
1015 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1017 int rv;
1019 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
1020 // is fixed.
1021 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
1022 rv = SSL_do_handshake(ssl_);
1023 } else {
1024 if (g_first_run_completed.Get().Get()) {
1025 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
1026 // fixed.
1027 tracked_objects::ScopedTracker tracking_profile(
1028 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
1030 rv = SSL_do_handshake(ssl_);
1031 } else {
1032 g_first_run_completed.Get().Set(true);
1033 rv = SSL_do_handshake(ssl_);
1037 int net_error = OK;
1038 if (rv <= 0) {
1039 int ssl_error = SSL_get_error(ssl_, rv);
1040 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
1041 // The server supports channel ID. Stop to look one up before returning to
1042 // the handshake.
1043 GotoState(STATE_CHANNEL_ID_LOOKUP);
1044 return OK;
1046 if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP &&
1047 !ssl_config_.send_client_cert) {
1048 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1050 if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1051 DCHECK(private_key_);
1052 DCHECK_NE(kNoPendingResult, signature_result_);
1053 GotoState(STATE_HANDSHAKE);
1054 return ERR_IO_PENDING;
1057 OpenSSLErrorInfo error_info;
1058 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
1059 if (net_error == ERR_IO_PENDING) {
1060 // If not done, stay in this state
1061 GotoState(STATE_HANDSHAKE);
1062 return ERR_IO_PENDING;
1065 LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
1066 << ssl_error << ", net_error " << net_error;
1067 net_log_.AddEvent(
1068 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1069 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1071 // Classify the handshake failure. This is used to determine causes of the
1072 // TLS version fallback.
1074 // |cipher| is the current outgoing cipher suite, so it is non-null iff
1075 // ChangeCipherSpec was sent.
1076 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
1077 if (SSL_get_state(ssl_) == SSL3_ST_CR_SRVR_HELLO_A) {
1078 ssl_failure_state_ = SSL_FAILURE_CLIENT_HELLO;
1079 } else if (cipher && (SSL_CIPHER_get_id(cipher) ==
1080 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 ||
1081 SSL_CIPHER_get_id(cipher) ==
1082 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256)) {
1083 ssl_failure_state_ = SSL_FAILURE_BUGGY_GCM;
1084 } else if (cipher && ssl_config_.send_client_cert) {
1085 ssl_failure_state_ = SSL_FAILURE_CLIENT_AUTH;
1086 } else if (ERR_GET_LIB(error_info.error_code) == ERR_LIB_SSL &&
1087 ERR_GET_REASON(error_info.error_code) ==
1088 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED) {
1089 ssl_failure_state_ = SSL_FAILURE_SESSION_MISMATCH;
1090 } else if (cipher && npn_status_ != kNextProtoUnsupported) {
1091 ssl_failure_state_ = SSL_FAILURE_NEXT_PROTO;
1092 } else {
1093 ssl_failure_state_ = SSL_FAILURE_UNKNOWN;
1097 GotoState(STATE_HANDSHAKE_COMPLETE);
1098 return net_error;
1101 int SSLClientSocketOpenSSL::DoHandshakeComplete(int result) {
1102 if (result < 0)
1103 return result;
1105 if (ssl_config_.version_fallback &&
1106 ssl_config_.version_max < ssl_config_.version_fallback_min) {
1107 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
1110 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1111 if (npn_status_ == kNextProtoUnsupported) {
1112 const uint8_t* alpn_proto = NULL;
1113 unsigned alpn_len = 0;
1114 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
1115 if (alpn_len > 0) {
1116 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
1117 npn_status_ = kNextProtoNegotiated;
1118 set_negotiation_extension(kExtensionALPN);
1122 RecordNegotiationExtension();
1123 RecordChannelIDSupport(channel_id_service_, channel_id_sent_,
1124 ssl_config_.channel_id_enabled,
1125 crypto::ECPrivateKey::IsSupported());
1127 // Only record OCSP histograms if OCSP was requested.
1128 if (ssl_config_.signed_cert_timestamps_enabled ||
1129 cert_verifier_->SupportsOCSPStapling()) {
1130 const uint8_t* ocsp_response;
1131 size_t ocsp_response_len;
1132 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
1134 set_stapled_ocsp_response_received(ocsp_response_len != 0);
1135 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
1138 const uint8_t* sct_list;
1139 size_t sct_list_len;
1140 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
1141 set_signed_cert_timestamps_received(sct_list_len != 0);
1143 if (IsRenegotiationAllowed())
1144 SSL_set_reject_peer_renegotiations(ssl_, 0);
1146 // Verify the certificate.
1147 UpdateServerCert();
1148 GotoState(STATE_VERIFY_CERT);
1149 return OK;
1152 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1153 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED);
1154 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
1155 return channel_id_service_->GetOrCreateChannelID(
1156 host_and_port_.host(), &channel_id_key_,
1157 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1158 base::Unretained(this)),
1159 &channel_id_request_);
1162 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1163 if (result < 0)
1164 return result;
1166 if (!channel_id_key_) {
1167 LOG(ERROR) << "Failed to import Channel ID.";
1168 return ERR_CHANNEL_ID_IMPORT_FAILED;
1171 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1172 // type.
1173 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1174 int rv = SSL_set1_tls_channel_id(ssl_, channel_id_key_->key());
1175 if (!rv) {
1176 LOG(ERROR) << "Failed to set Channel ID.";
1177 int err = SSL_get_error(ssl_, rv);
1178 return MapOpenSSLError(err, err_tracer);
1181 // Return to the handshake.
1182 channel_id_sent_ = true;
1183 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
1184 GotoState(STATE_HANDSHAKE);
1185 return OK;
1188 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
1189 DCHECK(!server_cert_chain_->empty());
1190 DCHECK(start_cert_verification_time_.is_null());
1192 GotoState(STATE_VERIFY_CERT_COMPLETE);
1194 // OpenSSL decoded the certificate, but the platform certificate
1195 // implementation could not. This is treated as a fatal SSL-level protocol
1196 // error rather than a certificate error. See https://crbug.com/91341.
1197 if (!server_cert_.get())
1198 return ERR_SSL_SERVER_CERT_BAD_FORMAT;
1200 // If the certificate is bad and has been previously accepted, use
1201 // the previous status and bypass the error.
1202 base::StringPiece der_cert;
1203 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1204 NOTREACHED();
1205 return ERR_CERT_INVALID;
1207 CertStatus cert_status;
1208 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
1209 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1210 server_cert_verify_result_.Reset();
1211 server_cert_verify_result_.cert_status = cert_status;
1212 server_cert_verify_result_.verified_cert = server_cert_;
1213 return OK;
1216 std::string ocsp_response;
1217 if (cert_verifier_->SupportsOCSPStapling()) {
1218 const uint8_t* ocsp_response_raw;
1219 size_t ocsp_response_len;
1220 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1221 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1222 ocsp_response_len);
1225 start_cert_verification_time_ = base::TimeTicks::Now();
1227 return cert_verifier_->Verify(
1228 server_cert_.get(), host_and_port_.host(), ocsp_response,
1229 ssl_config_.GetCertVerifyFlags(),
1230 // TODO(davidben): Route the CRLSet through SSLConfig so
1231 // SSLClientSocket doesn't depend on SSLConfigService.
1232 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
1233 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1234 base::Unretained(this)),
1235 &cert_verifier_request_, net_log_);
1238 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1239 cert_verifier_request_.reset();
1241 if (!start_cert_verification_time_.is_null()) {
1242 base::TimeDelta verify_time =
1243 base::TimeTicks::Now() - start_cert_verification_time_;
1244 if (result == OK) {
1245 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1246 } else {
1247 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1251 if (result == OK) {
1252 if (SSL_session_reused(ssl_)) {
1253 // Record whether or not the server tried to resume a session for a
1254 // different version. See https://crbug.com/441456.
1255 UMA_HISTOGRAM_BOOLEAN(
1256 "Net.SSLSessionVersionMatch",
1257 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1261 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1262 if (transport_security_state_ &&
1263 (result == OK ||
1264 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1265 !transport_security_state_->CheckPublicKeyPins(
1266 host_and_port_, server_cert_verify_result_.is_issued_by_known_root,
1267 server_cert_verify_result_.public_key_hashes, server_cert_.get(),
1268 server_cert_verify_result_.verified_cert.get(),
1269 TransportSecurityState::ENABLE_PIN_REPORTS, &pinning_failure_log_)) {
1270 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1273 if (result == OK) {
1274 // Only check Certificate Transparency if there were no other errors with
1275 // the connection.
1276 VerifyCT();
1278 DCHECK(!certificate_verified_);
1279 certificate_verified_ = true;
1280 MaybeCacheSession();
1281 } else {
1282 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1283 << " (" << result << ")";
1286 completed_connect_ = true;
1287 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1288 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1289 return result;
1292 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1293 if (!user_connect_callback_.is_null()) {
1294 CompletionCallback c = user_connect_callback_;
1295 user_connect_callback_.Reset();
1296 c.Run(rv > OK ? OK : rv);
1300 void SSLClientSocketOpenSSL::UpdateServerCert() {
1301 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
1302 server_cert_ = server_cert_chain_->AsOSChain();
1303 if (server_cert_.get()) {
1304 net_log_.AddEvent(
1305 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1306 base::Bind(&NetLogX509CertificateCallback,
1307 base::Unretained(server_cert_.get())));
1311 void SSLClientSocketOpenSSL::VerifyCT() {
1312 if (!cert_transparency_verifier_)
1313 return;
1315 const uint8_t* ocsp_response_raw;
1316 size_t ocsp_response_len;
1317 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1318 std::string ocsp_response;
1319 if (ocsp_response_len > 0) {
1320 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1321 ocsp_response_len);
1324 const uint8_t* sct_list_raw;
1325 size_t sct_list_len;
1326 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1327 std::string sct_list;
1328 if (sct_list_len > 0)
1329 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1331 // Note that this is a completely synchronous operation: The CT Log Verifier
1332 // gets all the data it needs for SCT verification and does not do any
1333 // external communication.
1334 cert_transparency_verifier_->Verify(
1335 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1336 &ct_verify_result_, net_log_);
1338 if (policy_enforcer_ &&
1339 (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV)) {
1340 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1341 SSLConfigService::GetEVCertsWhitelist();
1342 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1343 server_cert_verify_result_.verified_cert.get(), ev_whitelist.get(),
1344 ct_verify_result_, net_log_)) {
1345 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1346 VLOG(1) << "EV certificate for "
1347 << server_cert_verify_result_.verified_cert->subject()
1348 .GetDisplayName()
1349 << " does not conform to CT policy, removing EV status.";
1350 server_cert_verify_result_.cert_status |=
1351 CERT_STATUS_CT_COMPLIANCE_FAILED;
1352 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1357 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1358 int rv = DoHandshakeLoop(result);
1359 if (rv != ERR_IO_PENDING) {
1360 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1361 DoConnectCallback(rv);
1365 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1366 if (next_handshake_state_ == STATE_HANDSHAKE) {
1367 // In handshake phase.
1368 OnHandshakeIOComplete(result);
1369 return;
1372 // During a renegotiation, a Read call may also be blocked on a transport
1373 // write, so retry both operations.
1374 PumpReadWriteEvents();
1377 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1378 if (next_handshake_state_ == STATE_HANDSHAKE) {
1379 // In handshake phase.
1380 OnHandshakeIOComplete(result);
1381 return;
1384 // Network layer received some data, check if client requested to read
1385 // decrypted data.
1386 if (!user_read_buf_.get())
1387 return;
1389 int rv = DoReadLoop();
1390 if (rv != ERR_IO_PENDING)
1391 DoReadCallback(rv);
1394 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1395 int rv = last_io_result;
1396 do {
1397 // Default to STATE_NONE for next state.
1398 // (This is a quirk carried over from the windows
1399 // implementation. It makes reading the logs a bit harder.)
1400 // State handlers can and often do call GotoState just
1401 // to stay in the current state.
1402 State state = next_handshake_state_;
1403 GotoState(STATE_NONE);
1404 switch (state) {
1405 case STATE_HANDSHAKE:
1406 rv = DoHandshake();
1407 break;
1408 case STATE_HANDSHAKE_COMPLETE:
1409 rv = DoHandshakeComplete(rv);
1410 break;
1411 case STATE_CHANNEL_ID_LOOKUP:
1412 DCHECK_EQ(OK, rv);
1413 rv = DoChannelIDLookup();
1414 break;
1415 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1416 rv = DoChannelIDLookupComplete(rv);
1417 break;
1418 case STATE_VERIFY_CERT:
1419 DCHECK_EQ(OK, rv);
1420 rv = DoVerifyCert(rv);
1421 break;
1422 case STATE_VERIFY_CERT_COMPLETE:
1423 rv = DoVerifyCertComplete(rv);
1424 break;
1425 case STATE_NONE:
1426 default:
1427 rv = ERR_UNEXPECTED;
1428 NOTREACHED() << "unexpected state" << state;
1429 break;
1432 bool network_moved = DoTransportIO();
1433 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1434 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1435 // special case we keep looping even if rv is ERR_IO_PENDING because
1436 // the transport IO may allow DoHandshake to make progress.
1437 rv = OK; // This causes us to stay in the loop.
1439 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1440 return rv;
1443 int SSLClientSocketOpenSSL::DoReadLoop() {
1444 bool network_moved;
1445 int rv;
1446 do {
1447 rv = DoPayloadRead();
1448 network_moved = DoTransportIO();
1449 } while (rv == ERR_IO_PENDING && network_moved);
1451 return rv;
1454 int SSLClientSocketOpenSSL::DoWriteLoop() {
1455 bool network_moved;
1456 int rv;
1457 do {
1458 rv = DoPayloadWrite();
1459 network_moved = DoTransportIO();
1460 } while (rv == ERR_IO_PENDING && network_moved);
1462 return rv;
1465 int SSLClientSocketOpenSSL::DoPayloadRead() {
1466 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1468 DCHECK_LT(0, user_read_buf_len_);
1469 DCHECK(user_read_buf_.get());
1471 int rv;
1472 if (pending_read_error_ != kNoPendingResult) {
1473 rv = pending_read_error_;
1474 pending_read_error_ = kNoPendingResult;
1475 if (rv == 0) {
1476 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1477 rv, user_read_buf_->data());
1478 } else {
1479 net_log_.AddEvent(
1480 NetLog::TYPE_SSL_READ_ERROR,
1481 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1482 pending_read_error_info_));
1484 pending_read_ssl_error_ = SSL_ERROR_NONE;
1485 pending_read_error_info_ = OpenSSLErrorInfo();
1486 return rv;
1489 int total_bytes_read = 0;
1490 int ssl_ret;
1491 do {
1492 ssl_ret = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1493 user_read_buf_len_ - total_bytes_read);
1494 if (ssl_ret > 0)
1495 total_bytes_read += ssl_ret;
1496 } while (total_bytes_read < user_read_buf_len_ && ssl_ret > 0);
1498 // Although only the final SSL_read call may have failed, the failure needs to
1499 // processed immediately, while the information still available in OpenSSL's
1500 // error queue.
1501 if (ssl_ret <= 0) {
1502 // A zero return from SSL_read may mean any of:
1503 // - The underlying BIO_read returned 0.
1504 // - The peer sent a close_notify.
1505 // - Any arbitrary error. https://crbug.com/466303
1507 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1508 // error, so it does not occur. The second and third are distinguished by
1509 // SSL_ERROR_ZERO_RETURN.
1510 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1511 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1512 pending_read_error_ = 0;
1513 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP &&
1514 !ssl_config_.send_client_cert) {
1515 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1516 } else if (pending_read_ssl_error_ ==
1517 SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1518 DCHECK(private_key_);
1519 DCHECK_NE(kNoPendingResult, signature_result_);
1520 pending_read_error_ = ERR_IO_PENDING;
1521 } else {
1522 pending_read_error_ = MapOpenSSLErrorWithDetails(
1523 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
1526 // Many servers do not reliably send a close_notify alert when shutting down
1527 // a connection, and instead terminate the TCP connection. This is reported
1528 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1529 // graceful EOF, instead of treating it as an error as it should be.
1530 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1531 pending_read_error_ = 0;
1534 if (total_bytes_read > 0) {
1535 // Return any bytes read to the caller. The error will be deferred to the
1536 // next call of DoPayloadRead.
1537 rv = total_bytes_read;
1539 // Do not treat insufficient data as an error to return in the next call to
1540 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1541 // again. This is because DoTransportIO() may complete in between the next
1542 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1543 // subsequent invocations to see if a complete record may now be read.
1544 if (pending_read_error_ == ERR_IO_PENDING)
1545 pending_read_error_ = kNoPendingResult;
1546 } else {
1547 // No bytes were returned. Return the pending read error immediately.
1548 DCHECK_NE(kNoPendingResult, pending_read_error_);
1549 rv = pending_read_error_;
1550 pending_read_error_ = kNoPendingResult;
1553 if (rv >= 0) {
1554 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1555 user_read_buf_->data());
1556 } else if (rv != ERR_IO_PENDING) {
1557 net_log_.AddEvent(
1558 NetLog::TYPE_SSL_READ_ERROR,
1559 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1560 pending_read_error_info_));
1561 pending_read_ssl_error_ = SSL_ERROR_NONE;
1562 pending_read_error_info_ = OpenSSLErrorInfo();
1564 return rv;
1567 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1568 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1569 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1571 if (rv >= 0) {
1572 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1573 user_write_buf_->data());
1574 return rv;
1577 int ssl_error = SSL_get_error(ssl_, rv);
1578 if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION)
1579 return ERR_IO_PENDING;
1580 OpenSSLErrorInfo error_info;
1581 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1582 &error_info);
1584 if (net_error != ERR_IO_PENDING) {
1585 net_log_.AddEvent(
1586 NetLog::TYPE_SSL_WRITE_ERROR,
1587 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1589 return net_error;
1592 void SSLClientSocketOpenSSL::PumpReadWriteEvents() {
1593 int rv_read = ERR_IO_PENDING;
1594 int rv_write = ERR_IO_PENDING;
1595 bool network_moved;
1596 do {
1597 if (user_read_buf_.get())
1598 rv_read = DoPayloadRead();
1599 if (user_write_buf_.get())
1600 rv_write = DoPayloadWrite();
1601 network_moved = DoTransportIO();
1602 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1603 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1605 // Performing the Read callback may cause |this| to be deleted. If this
1606 // happens, the Write callback should not be invoked. Guard against this by
1607 // holding a WeakPtr to |this| and ensuring it's still valid.
1608 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1609 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1610 DoReadCallback(rv_read);
1612 if (!guard.get())
1613 return;
1615 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1616 DoWriteCallback(rv_write);
1619 int SSLClientSocketOpenSSL::BufferSend(void) {
1620 if (transport_send_busy_)
1621 return ERR_IO_PENDING;
1623 size_t buffer_read_offset;
1624 uint8_t* read_buf;
1625 size_t max_read;
1626 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1627 &buffer_read_offset, &max_read);
1628 DCHECK_EQ(status, 1); // Should never fail.
1629 if (!max_read)
1630 return 0; // Nothing pending in the OpenSSL write BIO.
1631 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1632 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1633 send_buffer_->set_offset(buffer_read_offset);
1635 int rv = transport_->socket()->Write(
1636 send_buffer_.get(), max_read,
1637 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1638 base::Unretained(this)));
1639 if (rv == ERR_IO_PENDING) {
1640 transport_send_busy_ = true;
1641 } else {
1642 TransportWriteComplete(rv);
1644 return rv;
1647 int SSLClientSocketOpenSSL::BufferRecv(void) {
1648 if (transport_recv_busy_)
1649 return ERR_IO_PENDING;
1651 // Determine how much was requested from |transport_bio_| that was not
1652 // actually available.
1653 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1654 if (requested == 0) {
1655 // This is not a perfect match of error codes, as no operation is
1656 // actually pending. However, returning 0 would be interpreted as
1657 // a possible sign of EOF, which is also an inappropriate match.
1658 return ERR_IO_PENDING;
1661 // Known Issue: While only reading |requested| data is the more correct
1662 // implementation, it has the downside of resulting in frequent reads:
1663 // One read for the SSL record header (~5 bytes) and one read for the SSL
1664 // record body. Rather than issuing these reads to the underlying socket
1665 // (and constantly allocating new IOBuffers), a single Read() request to
1666 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1667 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1668 // traffic, this over-subscribed Read()ing will not cause issues.
1670 size_t buffer_write_offset;
1671 uint8_t* write_buf;
1672 size_t max_write;
1673 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1674 &buffer_write_offset, &max_write);
1675 DCHECK_EQ(status, 1); // Should never fail.
1676 if (!max_write)
1677 return ERR_IO_PENDING;
1679 CHECK_EQ(write_buf,
1680 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1681 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1683 recv_buffer_->set_offset(buffer_write_offset);
1684 int rv = transport_->socket()->Read(
1685 recv_buffer_.get(),
1686 max_write,
1687 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1688 base::Unretained(this)));
1689 if (rv == ERR_IO_PENDING) {
1690 transport_recv_busy_ = true;
1691 } else {
1692 rv = TransportReadComplete(rv);
1694 return rv;
1697 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1698 TransportWriteComplete(result);
1699 OnSendComplete(result);
1702 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1703 result = TransportReadComplete(result);
1704 OnRecvComplete(result);
1707 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1708 DCHECK(ERR_IO_PENDING != result);
1709 int bytes_written = 0;
1710 if (result < 0) {
1711 // Record the error. Save it to be reported in a future read or write on
1712 // transport_bio_'s peer.
1713 transport_write_error_ = result;
1714 } else {
1715 bytes_written = result;
1717 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1718 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1719 DCHECK_EQ(1, ret);
1720 transport_send_busy_ = false;
1723 int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1724 DCHECK(ERR_IO_PENDING != result);
1725 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1726 // does not report success.
1727 if (result == 0)
1728 result = ERR_CONNECTION_CLOSED;
1729 int bytes_read = 0;
1730 if (result < 0) {
1731 DVLOG(1) << "TransportReadComplete result " << result;
1732 // Received an error. Save it to be reported in a future read on
1733 // transport_bio_'s peer.
1734 transport_read_error_ = result;
1735 } else {
1736 bytes_read = result;
1738 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1739 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1740 DCHECK_EQ(1, ret);
1741 transport_recv_busy_ = false;
1742 return result;
1745 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
1746 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1747 DCHECK(ssl == ssl_);
1749 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1751 // Clear any currently configured certificates.
1752 SSL_certs_clear(ssl_);
1754 #if defined(OS_IOS)
1755 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1756 LOG(WARNING) << "Client auth is not supported";
1757 #else // !defined(OS_IOS)
1758 if (!ssl_config_.send_client_cert) {
1759 // First pass: we know that a client certificate is needed, but we do not
1760 // have one at hand.
1761 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1762 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
1763 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1764 unsigned char* str = NULL;
1765 int length = i2d_X509_NAME(ca_name, &str);
1766 cert_authorities_.push_back(std::string(
1767 reinterpret_cast<const char*>(str),
1768 static_cast<size_t>(length)));
1769 OPENSSL_free(str);
1772 const unsigned char* client_cert_types;
1773 size_t num_client_cert_types =
1774 SSL_get0_certificate_types(ssl, &client_cert_types);
1775 for (size_t i = 0; i < num_client_cert_types; i++) {
1776 cert_key_types_.push_back(
1777 static_cast<SSLClientCertType>(client_cert_types[i]));
1780 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1781 return -1;
1784 // Second pass: a client certificate should have been selected.
1785 if (ssl_config_.client_cert.get()) {
1786 ScopedX509 leaf_x509 =
1787 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1788 if (!leaf_x509) {
1789 LOG(WARNING) << "Failed to import certificate";
1790 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1791 return -1;
1794 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1795 ssl_config_.client_cert->GetIntermediateCertificates());
1796 if (!chain) {
1797 LOG(WARNING) << "Failed to import intermediate certificates";
1798 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1799 return -1;
1802 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1803 !SSL_set1_chain(ssl_, chain.get())) {
1804 LOG(WARNING) << "Failed to set client certificate";
1805 return -1;
1808 #if defined(USE_OPENSSL_CERTS)
1809 // TODO(davidben): Move Android to the SSLPrivateKey codepath and disable
1810 // client auth on NaCl altogether.
1811 crypto::ScopedEVP_PKEY privkey =
1812 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1813 ssl_config_.client_cert.get());
1814 if (!privkey) {
1815 // Could not find the private key. Fail the handshake and surface an
1816 // appropriate error to the caller.
1817 LOG(WARNING) << "Client cert found without private key";
1818 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1819 return -1;
1821 if (!SSL_use_PrivateKey(ssl_, privkey.get())) {
1822 LOG(WARNING) << "Failed to set private key";
1823 return -1;
1825 #else // !USE_OPENSSL_CERTS
1826 // TODO(davidben): Lift this call up to the embedder so we can actually test
1827 // this code. https://crbug.com/394131
1828 private_key_ = FetchClientCertPrivateKey(
1829 ssl_config_.client_cert.get(),
1830 g_platform_key_task_runner.Get().task_runner());
1831 if (!private_key_) {
1832 // Could not find the private key. Fail the handshake and surface an
1833 // appropriate error to the caller.
1834 LOG(WARNING) << "Client cert found without private key";
1835 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1836 return -1;
1839 SSL_set_private_key_method(ssl_, &SSLContext::kPrivateKeyMethod);
1840 #endif // USE_OPENSSL_CERTS
1842 int cert_count = 1 + sk_X509_num(chain.get());
1843 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1844 NetLog::IntegerCallback("cert_count", cert_count));
1845 return 1;
1847 #endif // defined(OS_IOS)
1849 // Send no client certificate.
1850 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1851 NetLog::IntegerCallback("cert_count", 0));
1852 return 1;
1855 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1856 if (!completed_connect_) {
1857 // If the first handshake hasn't completed then we accept any certificates
1858 // because we verify after the handshake.
1859 return 1;
1862 // Disallow the server certificate to change in a renegotiation.
1863 if (server_cert_chain_->empty()) {
1864 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1865 return 0;
1867 base::StringPiece old_der, new_der;
1868 if (store_ctx->cert == NULL ||
1869 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1870 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1871 LOG(ERROR) << "Failed to encode certificates";
1872 return 0;
1874 if (old_der != new_der) {
1875 LOG(ERROR) << "Server certificate changed between handshakes";
1876 return 0;
1879 return 1;
1882 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1883 // server supports NPN, selects a protocol from the list that the server
1884 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1885 // callback can assume that |in| is syntactically valid.
1886 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1887 unsigned char* outlen,
1888 const unsigned char* in,
1889 unsigned int inlen) {
1890 if (ssl_config_.next_protos.empty()) {
1891 *out = reinterpret_cast<uint8*>(
1892 const_cast<char*>(kDefaultSupportedNPNProtocol));
1893 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1894 npn_status_ = kNextProtoUnsupported;
1895 return SSL_TLSEXT_ERR_OK;
1898 // Assume there's no overlap between our protocols and the server's list.
1899 npn_status_ = kNextProtoNoOverlap;
1901 // For each protocol in server preference order, see if we support it.
1902 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1903 for (NextProto next_proto : ssl_config_.next_protos) {
1904 const std::string proto = NextProtoToString(next_proto);
1905 if (in[i] == proto.size() &&
1906 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
1907 // We found a match.
1908 *out = const_cast<unsigned char*>(in) + i + 1;
1909 *outlen = in[i];
1910 npn_status_ = kNextProtoNegotiated;
1911 break;
1914 if (npn_status_ == kNextProtoNegotiated)
1915 break;
1918 // If we didn't find a protocol, we select the first one from our list.
1919 if (npn_status_ == kNextProtoNoOverlap) {
1920 // NextProtoToString returns a pointer to a static string.
1921 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1922 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1923 *outlen = strlen(proto);
1926 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
1927 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
1928 set_negotiation_extension(kExtensionNPN);
1929 return SSL_TLSEXT_ERR_OK;
1932 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1933 BIO *bio,
1934 int cmd,
1935 const char *argp, int argi, long argl,
1936 long retvalue) {
1937 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1938 // If there is no more data in the buffer, report any pending errors that
1939 // were observed. Note that both the readbuf and the writebuf are checked
1940 // for errors, since the application may have encountered a socket error
1941 // while writing that would otherwise not be reported until the application
1942 // attempted to write again - which it may never do. See
1943 // https://crbug.com/249848.
1944 if (transport_read_error_ != OK) {
1945 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1946 return -1;
1948 if (transport_write_error_ != OK) {
1949 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1950 return -1;
1952 } else if (cmd == BIO_CB_WRITE) {
1953 // Because of the write buffer, this reports a failure from the previous
1954 // write payload. If the current payload fails to write, the error will be
1955 // reported in a future write or read to |bio|.
1956 if (transport_write_error_ != OK) {
1957 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1958 return -1;
1961 return retvalue;
1964 // static
1965 long SSLClientSocketOpenSSL::BIOCallback(
1966 BIO *bio,
1967 int cmd,
1968 const char *argp, int argi, long argl,
1969 long retvalue) {
1970 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1971 BIO_get_callback_arg(bio));
1972 CHECK(socket);
1973 return socket->MaybeReplayTransportError(
1974 bio, cmd, argp, argi, argl, retvalue);
1977 void SSLClientSocketOpenSSL::MaybeCacheSession() {
1978 // Only cache the session once both a new session has been established and the
1979 // certificate has been verified. Due to False Start, these events may happen
1980 // in either order.
1981 if (!session_pending_ || !certificate_verified_)
1982 return;
1984 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1985 SSL_get_session(ssl_));
1986 session_pending_ = false;
1989 int SSLClientSocketOpenSSL::NewSessionCallback(SSL_SESSION* session) {
1990 DCHECK_EQ(session, SSL_get_session(ssl_));
1992 // Only sessions from the initial handshake get cached. Note this callback may
1993 // be signaled on abbreviated handshakes if the ticket was renewed.
1994 session_pending_ = true;
1995 MaybeCacheSession();
1997 // OpenSSL passes a reference to |session|, but the session cache does not
1998 // take this reference, so release it.
1999 SSL_SESSION_free(session);
2000 return 1;
2003 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
2004 for (ct::SCTList::const_iterator iter =
2005 ct_verify_result_.verified_scts.begin();
2006 iter != ct_verify_result_.verified_scts.end(); ++iter) {
2007 ssl_info->signed_certificate_timestamps.push_back(
2008 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
2010 for (ct::SCTList::const_iterator iter =
2011 ct_verify_result_.invalid_scts.begin();
2012 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
2013 ssl_info->signed_certificate_timestamps.push_back(
2014 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
2016 for (ct::SCTList::const_iterator iter =
2017 ct_verify_result_.unknown_logs_scts.begin();
2018 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
2019 ssl_info->signed_certificate_timestamps.push_back(
2020 SignedCertificateTimestampAndStatus(*iter,
2021 ct::SCT_STATUS_LOG_UNKNOWN));
2025 std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
2026 std::string result = host_and_port_.ToString();
2027 result.append("/");
2028 result.append(ssl_session_cache_shard_);
2030 // Shard the session cache based on maximum protocol version. This causes
2031 // fallback connections to use a separate session cache.
2032 result.append("/");
2033 switch (ssl_config_.version_max) {
2034 case SSL_PROTOCOL_VERSION_TLS1:
2035 result.append("tls1");
2036 break;
2037 case SSL_PROTOCOL_VERSION_TLS1_1:
2038 result.append("tls1.1");
2039 break;
2040 case SSL_PROTOCOL_VERSION_TLS1_2:
2041 result.append("tls1.2");
2042 break;
2043 default:
2044 NOTREACHED();
2047 result.append("/");
2048 if (ssl_config_.enable_deprecated_cipher_suites)
2049 result.append("deprecated");
2051 return result;
2054 bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
2055 if (npn_status_ == kNextProtoUnsupported)
2056 return ssl_config_.renego_allowed_default;
2058 NextProto next_proto = NextProtoFromString(npn_proto_);
2059 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
2060 if (next_proto == allowed)
2061 return true;
2063 return false;
2066 int SSLClientSocketOpenSSL::PrivateKeyTypeCallback() {
2067 switch (private_key_->GetType()) {
2068 case SSLPrivateKey::Type::RSA:
2069 return EVP_PKEY_RSA;
2070 case SSLPrivateKey::Type::ECDSA:
2071 return EVP_PKEY_EC;
2073 NOTREACHED();
2074 return EVP_PKEY_NONE;
2077 int SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback(const EVP_MD* md) {
2078 SSLPrivateKey::Hash hash;
2079 return EVP_MDToPrivateKeyHash(md, &hash) && private_key_->SupportsHash(hash);
2082 size_t SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback() {
2083 return private_key_->GetMaxSignatureLengthInBytes();
2086 ssl_private_key_result_t SSLClientSocketOpenSSL::PrivateKeySignCallback(
2087 uint8_t* out,
2088 size_t* out_len,
2089 size_t max_out,
2090 const EVP_MD* md,
2091 const uint8_t* in,
2092 size_t in_len) {
2093 DCHECK_EQ(kNoPendingResult, signature_result_);
2094 DCHECK(signature_.empty());
2095 DCHECK(private_key_);
2097 net_log_.BeginEvent(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION);
2099 SSLPrivateKey::Hash hash;
2100 if (!EVP_MDToPrivateKeyHash(md, &hash)) {
2101 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
2102 return ssl_private_key_failure;
2105 signature_result_ = ERR_IO_PENDING;
2106 private_key_->SignDigest(
2107 hash, base::StringPiece(reinterpret_cast<const char*>(in), in_len),
2108 base::Bind(&SSLClientSocketOpenSSL::OnPrivateKeySignComplete,
2109 weak_factory_.GetWeakPtr()));
2110 return ssl_private_key_retry;
2113 ssl_private_key_result_t SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback(
2114 uint8_t* out,
2115 size_t* out_len,
2116 size_t max_out) {
2117 DCHECK_NE(kNoPendingResult, signature_result_);
2118 DCHECK(private_key_);
2120 if (signature_result_ == ERR_IO_PENDING)
2121 return ssl_private_key_retry;
2122 if (signature_result_ != OK) {
2123 OpenSSLPutNetError(FROM_HERE, signature_result_);
2124 return ssl_private_key_failure;
2126 if (signature_.size() > max_out) {
2127 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
2128 return ssl_private_key_failure;
2130 memcpy(out, vector_as_array(&signature_), signature_.size());
2131 *out_len = signature_.size();
2132 signature_.clear();
2133 return ssl_private_key_success;
2136 void SSLClientSocketOpenSSL::OnPrivateKeySignComplete(
2137 Error error,
2138 const std::vector<uint8_t>& signature) {
2139 DCHECK_EQ(ERR_IO_PENDING, signature_result_);
2140 DCHECK(signature_.empty());
2141 DCHECK(private_key_);
2143 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION,
2144 error);
2146 signature_result_ = error;
2147 if (signature_result_ == OK)
2148 signature_ = signature;
2150 if (next_handshake_state_ == STATE_HANDSHAKE) {
2151 OnHandshakeIOComplete(signature_result_);
2152 return;
2155 // During a renegotiation, either Read or Write calls may be blocked on an
2156 // asynchronous private key operation.
2157 PumpReadWriteEvents();
2160 } // namespace net