Fix variable shadowing warnings in UDPSocketWin on VS2015
[chromium-blink-merge.git] / net / socket / ssl_client_socket_openssl.cc
blob504b702dc6614734df3894fb004168d4f6dad581
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/ssl.h>
14 #include <string.h>
16 #include "base/bind.h"
17 #include "base/callback_helpers.h"
18 #include "base/environment.h"
19 #include "base/memory/singleton.h"
20 #include "base/metrics/histogram.h"
21 #include "base/profiler/scoped_tracker.h"
22 #include "base/strings/string_piece.h"
23 #include "base/synchronization/lock.h"
24 #include "base/threading/thread_local.h"
25 #include "crypto/ec_private_key.h"
26 #include "crypto/openssl_util.h"
27 #include "crypto/scoped_openssl_types.h"
28 #include "net/base/net_errors.h"
29 #include "net/cert/cert_policy_enforcer.h"
30 #include "net/cert/cert_verifier.h"
31 #include "net/cert/ct_ev_whitelist.h"
32 #include "net/cert/ct_verifier.h"
33 #include "net/cert/single_request_cert_verifier.h"
34 #include "net/cert/x509_certificate_net_log_param.h"
35 #include "net/cert/x509_util_openssl.h"
36 #include "net/http/transport_security_state.h"
37 #include "net/socket/ssl_session_cache_openssl.h"
38 #include "net/ssl/ssl_cert_request_info.h"
39 #include "net/ssl/ssl_connection_status_flags.h"
40 #include "net/ssl/ssl_info.h"
42 #if defined(OS_WIN)
43 #include "base/win/windows_version.h"
44 #endif
46 #if defined(USE_OPENSSL_CERTS)
47 #include "net/ssl/openssl_client_key_store.h"
48 #else
49 #include "net/ssl/openssl_platform_key.h"
50 #endif
52 namespace net {
54 namespace {
56 // Enable this to see logging for state machine state transitions.
57 #if 0
58 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
59 " jump to state " << s; \
60 next_handshake_state_ = s; } while (0)
61 #else
62 #define GotoState(s) next_handshake_state_ = s
63 #endif
65 // This constant can be any non-negative/non-zero value (eg: it does not
66 // overlap with any value of the net::Error range, including net::OK).
67 const int kNoPendingReadResult = 1;
69 // If a client doesn't have a list of protocols that it supports, but
70 // the server supports NPN, choosing "http/1.1" is the best answer.
71 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
73 // Default size of the internal BoringSSL buffers.
74 const int KDefaultOpenSSLBufferSize = 17 * 1024;
76 void FreeX509Stack(STACK_OF(X509)* ptr) {
77 sk_X509_pop_free(ptr, X509_free);
80 typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
81 typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
82 ScopedX509Stack;
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 bool IsOCSPStaplingSupported() {
150 #if defined(OS_WIN)
151 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
152 // set on Windows XP without error. There is some overhead from the server
153 // sending the OCSP response if it supports the extension, for the subset of
154 // XP clients who will request it but be unable to use it, but this is an
155 // acceptable trade-off for simplicity of implementation.
156 return true;
157 #else
158 return false;
159 #endif
162 } // namespace
164 class SSLClientSocketOpenSSL::SSLContext {
165 public:
166 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
167 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
168 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
170 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
171 DCHECK(ssl);
172 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
173 SSL_get_ex_data(ssl, ssl_socket_data_index_));
174 DCHECK(socket);
175 return socket;
178 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
179 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
182 private:
183 friend struct DefaultSingletonTraits<SSLContext>;
185 SSLContext() {
186 crypto::EnsureOpenSSLInit();
187 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
188 DCHECK_NE(ssl_socket_data_index_, -1);
189 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
190 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
191 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
192 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
193 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
194 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
195 // It would be better if the callback were not a global setting,
196 // but that is an OpenSSL issue.
197 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
198 NULL);
199 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
201 scoped_ptr<base::Environment> env(base::Environment::Create());
202 std::string ssl_keylog_file;
203 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
204 !ssl_keylog_file.empty()) {
205 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
206 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
207 if (!bio) {
208 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
209 ERR_print_errors_cb(&LogErrorCallback, NULL);
210 } else {
211 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
216 static std::string GetSessionCacheKey(const SSL* ssl) {
217 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
218 DCHECK(socket);
219 return socket->GetSessionCacheKey();
222 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
224 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
225 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
226 DCHECK(socket);
227 return socket->ClientCertRequestCallback(ssl);
230 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
231 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
232 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
233 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
234 CHECK(socket);
236 return socket->CertVerifyCallback(store_ctx);
239 static int SelectNextProtoCallback(SSL* ssl,
240 unsigned char** out, unsigned char* outlen,
241 const unsigned char* in,
242 unsigned int inlen, void* arg) {
243 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
244 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
247 // This is the index used with SSL_get_ex_data to retrieve the owner
248 // SSLClientSocketOpenSSL object from an SSL instance.
249 int ssl_socket_data_index_;
251 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
252 // |session_cache_| must be destroyed before |ssl_ctx_|.
253 SSLSessionCacheOpenSSL session_cache_;
256 // PeerCertificateChain is a helper object which extracts the certificate
257 // chain, as given by the server, from an OpenSSL socket and performs the needed
258 // resource management. The first element of the chain is the leaf certificate
259 // and the other elements are in the order given by the server.
260 class SSLClientSocketOpenSSL::PeerCertificateChain {
261 public:
262 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
263 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
264 ~PeerCertificateChain() {}
265 PeerCertificateChain& operator=(const PeerCertificateChain& other);
267 // Resets the PeerCertificateChain to the set of certificates in|chain|,
268 // which may be NULL, indicating to empty the store certificates.
269 // Note: If an error occurs, such as being unable to parse the certificates,
270 // this will behave as if Reset(NULL) was called.
271 void Reset(STACK_OF(X509)* chain);
273 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
274 scoped_refptr<X509Certificate> AsOSChain() const;
276 size_t size() const {
277 if (!openssl_chain_.get())
278 return 0;
279 return sk_X509_num(openssl_chain_.get());
282 bool empty() const {
283 return size() == 0;
286 X509* Get(size_t index) const {
287 DCHECK_LT(index, size());
288 return sk_X509_value(openssl_chain_.get(), index);
291 private:
292 ScopedX509Stack openssl_chain_;
295 SSLClientSocketOpenSSL::PeerCertificateChain&
296 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
297 const PeerCertificateChain& other) {
298 if (this == &other)
299 return *this;
301 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
302 return *this;
305 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
306 STACK_OF(X509)* chain) {
307 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
310 scoped_refptr<X509Certificate>
311 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
312 #if defined(USE_OPENSSL_CERTS)
313 // When OSCertHandle is typedef'ed to X509, this implementation does a short
314 // cut to avoid converting back and forth between DER and the X509 struct.
315 X509Certificate::OSCertHandles intermediates;
316 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
317 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
320 return make_scoped_refptr(X509Certificate::CreateFromHandle(
321 sk_X509_value(openssl_chain_.get(), 0), intermediates));
322 #else
323 // DER-encode the chain and convert to a platform certificate handle.
324 std::vector<base::StringPiece> der_chain;
325 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
326 X509* x = sk_X509_value(openssl_chain_.get(), i);
327 base::StringPiece der;
328 if (!x509_util::GetDER(x, &der))
329 return NULL;
330 der_chain.push_back(der);
333 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
334 #endif
337 // static
338 SSLSessionCacheOpenSSL::Config
339 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
340 &GetSessionCacheKey, // key_func
341 1024, // max_entries
342 256, // expiration_check_count
343 60 * 60, // timeout_seconds
346 // static
347 void SSLClientSocket::ClearSessionCache() {
348 SSLClientSocketOpenSSL::SSLContext* context =
349 SSLClientSocketOpenSSL::SSLContext::GetInstance();
350 context->session_cache()->Flush();
353 // static
354 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
355 return SSL_PROTOCOL_VERSION_TLS1_2;
358 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
359 scoped_ptr<ClientSocketHandle> transport_socket,
360 const HostPortPair& host_and_port,
361 const SSLConfig& ssl_config,
362 const SSLClientSocketContext& context)
363 : transport_send_busy_(false),
364 transport_recv_busy_(false),
365 pending_read_error_(kNoPendingReadResult),
366 pending_read_ssl_error_(SSL_ERROR_NONE),
367 transport_read_error_(OK),
368 transport_write_error_(OK),
369 server_cert_chain_(new PeerCertificateChain(NULL)),
370 completed_connect_(false),
371 was_ever_used_(false),
372 client_auth_cert_needed_(false),
373 cert_verifier_(context.cert_verifier),
374 cert_transparency_verifier_(context.cert_transparency_verifier),
375 channel_id_service_(context.channel_id_service),
376 ssl_(NULL),
377 transport_bio_(NULL),
378 transport_(transport_socket.Pass()),
379 host_and_port_(host_and_port),
380 ssl_config_(ssl_config),
381 ssl_session_cache_shard_(context.ssl_session_cache_shard),
382 trying_cached_session_(false),
383 next_handshake_state_(STATE_NONE),
384 npn_status_(kNextProtoUnsupported),
385 channel_id_xtn_negotiated_(false),
386 handshake_succeeded_(false),
387 marked_session_as_good_(false),
388 transport_security_state_(context.transport_security_state),
389 policy_enforcer_(context.cert_policy_enforcer),
390 net_log_(transport_->socket()->NetLog()),
391 weak_factory_(this) {
394 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
395 Disconnect();
398 std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
399 std::string result = host_and_port_.ToString();
400 result.append("/");
401 result.append(ssl_session_cache_shard_);
402 return result;
405 bool SSLClientSocketOpenSSL::InSessionCache() const {
406 SSLContext* context = SSLContext::GetInstance();
407 std::string cache_key = GetSessionCacheKey();
408 return context->session_cache()->SSLSessionIsInCache(cache_key);
411 void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
412 const base::Closure& callback) {
413 handshake_completion_callback_ = callback;
416 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
417 SSLCertRequestInfo* cert_request_info) {
418 cert_request_info->host_and_port = host_and_port_;
419 cert_request_info->cert_authorities = cert_authorities_;
420 cert_request_info->cert_key_types = cert_key_types_;
423 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
424 std::string* proto) {
425 *proto = npn_proto_;
426 return npn_status_;
429 ChannelIDService*
430 SSLClientSocketOpenSSL::GetChannelIDService() const {
431 return channel_id_service_;
434 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
435 const base::StringPiece& label,
436 bool has_context, const base::StringPiece& context,
437 unsigned char* out, unsigned int outlen) {
438 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
440 int rv = SSL_export_keying_material(
441 ssl_, out, outlen, label.data(), label.size(),
442 reinterpret_cast<const unsigned char*>(context.data()),
443 context.length(), context.length() > 0);
445 if (rv != 1) {
446 int ssl_error = SSL_get_error(ssl_, rv);
447 LOG(ERROR) << "Failed to export keying material;"
448 << " returned " << rv
449 << ", SSL error code " << ssl_error;
450 return MapOpenSSLError(ssl_error, err_tracer);
452 return OK;
455 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
456 NOTIMPLEMENTED();
457 return ERR_NOT_IMPLEMENTED;
460 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
461 // It is an error to create an SSLClientSocket whose context has no
462 // TransportSecurityState.
463 DCHECK(transport_security_state_);
465 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
467 // Set up new ssl object.
468 int rv = Init();
469 if (rv != OK) {
470 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
471 return rv;
474 // Set SSL to client mode. Handshake happens in the loop below.
475 SSL_set_connect_state(ssl_);
477 GotoState(STATE_HANDSHAKE);
478 rv = DoHandshakeLoop(OK);
479 if (rv == ERR_IO_PENDING) {
480 user_connect_callback_ = callback;
481 } else {
482 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
483 if (rv < OK)
484 OnHandshakeCompletion();
487 return rv > OK ? OK : rv;
490 void SSLClientSocketOpenSSL::Disconnect() {
491 // If a handshake was pending (Connect() had been called), notify interested
492 // parties that it's been aborted now. If the handshake had already
493 // completed, this is a no-op.
494 OnHandshakeCompletion();
495 if (ssl_) {
496 // Calling SSL_shutdown prevents the session from being marked as
497 // unresumable.
498 SSL_shutdown(ssl_);
499 SSL_free(ssl_);
500 ssl_ = NULL;
502 if (transport_bio_) {
503 BIO_free_all(transport_bio_);
504 transport_bio_ = NULL;
507 // Shut down anything that may call us back.
508 verifier_.reset();
509 transport_->socket()->Disconnect();
511 // Null all callbacks, delete all buffers.
512 transport_send_busy_ = false;
513 send_buffer_ = NULL;
514 transport_recv_busy_ = false;
515 recv_buffer_ = NULL;
517 user_connect_callback_.Reset();
518 user_read_callback_.Reset();
519 user_write_callback_.Reset();
520 user_read_buf_ = NULL;
521 user_read_buf_len_ = 0;
522 user_write_buf_ = NULL;
523 user_write_buf_len_ = 0;
525 pending_read_error_ = kNoPendingReadResult;
526 pending_read_ssl_error_ = SSL_ERROR_NONE;
527 pending_read_error_info_ = OpenSSLErrorInfo();
529 transport_read_error_ = OK;
530 transport_write_error_ = OK;
532 server_cert_verify_result_.Reset();
533 completed_connect_ = false;
535 cert_authorities_.clear();
536 cert_key_types_.clear();
537 client_auth_cert_needed_ = false;
539 start_cert_verification_time_ = base::TimeTicks();
541 npn_status_ = kNextProtoUnsupported;
542 npn_proto_.clear();
544 channel_id_xtn_negotiated_ = false;
545 channel_id_request_handle_.Cancel();
548 bool SSLClientSocketOpenSSL::IsConnected() const {
549 // If the handshake has not yet completed.
550 if (!completed_connect_)
551 return false;
552 // If an asynchronous operation is still pending.
553 if (user_read_buf_.get() || user_write_buf_.get())
554 return true;
556 return transport_->socket()->IsConnected();
559 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
560 // If the handshake has not yet completed.
561 if (!completed_connect_)
562 return false;
563 // If an asynchronous operation is still pending.
564 if (user_read_buf_.get() || user_write_buf_.get())
565 return false;
566 // If there is data waiting to be sent, or data read from the network that
567 // has not yet been consumed.
568 if (BIO_pending(transport_bio_) > 0 ||
569 BIO_wpending(transport_bio_) > 0) {
570 return false;
573 return transport_->socket()->IsConnectedAndIdle();
576 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
577 return transport_->socket()->GetPeerAddress(addressList);
580 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
581 return transport_->socket()->GetLocalAddress(addressList);
584 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
585 return net_log_;
588 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
589 if (transport_.get() && transport_->socket()) {
590 transport_->socket()->SetSubresourceSpeculation();
591 } else {
592 NOTREACHED();
596 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
597 if (transport_.get() && transport_->socket()) {
598 transport_->socket()->SetOmniboxSpeculation();
599 } else {
600 NOTREACHED();
604 bool SSLClientSocketOpenSSL::WasEverUsed() const {
605 return was_ever_used_;
608 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
609 if (transport_.get() && transport_->socket())
610 return transport_->socket()->UsingTCPFastOpen();
612 NOTREACHED();
613 return false;
616 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
617 ssl_info->Reset();
618 if (server_cert_chain_->empty())
619 return false;
621 ssl_info->cert = server_cert_verify_result_.verified_cert;
622 ssl_info->cert_status = server_cert_verify_result_.cert_status;
623 ssl_info->is_issued_by_known_root =
624 server_cert_verify_result_.is_issued_by_known_root;
625 ssl_info->public_key_hashes =
626 server_cert_verify_result_.public_key_hashes;
627 ssl_info->client_cert_sent =
628 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
629 ssl_info->channel_id_sent = WasChannelIDSent();
630 ssl_info->pinning_failure_log = pinning_failure_log_;
632 AddSCTInfoToSSLInfo(ssl_info);
634 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
635 CHECK(cipher);
636 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
638 ssl_info->connection_status = EncodeSSLConnectionStatus(
639 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
640 GetNetSSLVersion(ssl_));
642 if (!SSL_get_secure_renegotiation_support(ssl_))
643 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
645 if (ssl_config_.version_fallback)
646 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
648 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
649 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
651 DVLOG(3) << "Encoded connection status: cipher suite = "
652 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
653 << " version = "
654 << SSLConnectionStatusToVersion(ssl_info->connection_status);
655 return true;
658 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
659 int buf_len,
660 const CompletionCallback& callback) {
661 user_read_buf_ = buf;
662 user_read_buf_len_ = buf_len;
664 int rv = DoReadLoop();
666 if (rv == ERR_IO_PENDING) {
667 user_read_callback_ = callback;
668 } else {
669 if (rv > 0)
670 was_ever_used_ = true;
671 user_read_buf_ = NULL;
672 user_read_buf_len_ = 0;
673 if (rv <= 0) {
674 // Failure of a read attempt may indicate a failed false start
675 // connection.
676 OnHandshakeCompletion();
680 return rv;
683 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
684 int buf_len,
685 const CompletionCallback& callback) {
686 user_write_buf_ = buf;
687 user_write_buf_len_ = buf_len;
689 int rv = DoWriteLoop();
691 if (rv == ERR_IO_PENDING) {
692 user_write_callback_ = callback;
693 } else {
694 if (rv > 0)
695 was_ever_used_ = true;
696 user_write_buf_ = NULL;
697 user_write_buf_len_ = 0;
698 if (rv < 0) {
699 // Failure of a write attempt may indicate a failed false start
700 // connection.
701 OnHandshakeCompletion();
705 return rv;
708 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
709 return transport_->socket()->SetReceiveBufferSize(size);
712 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
713 return transport_->socket()->SetSendBufferSize(size);
716 int SSLClientSocketOpenSSL::Init() {
717 DCHECK(!ssl_);
718 DCHECK(!transport_bio_);
720 SSLContext* context = SSLContext::GetInstance();
721 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
723 ssl_ = SSL_new(context->ssl_ctx());
724 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
725 return ERR_UNEXPECTED;
727 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
728 return ERR_UNEXPECTED;
730 // Set an OpenSSL callback to monitor this SSL*'s connection.
731 SSL_set_info_callback(ssl_, &InfoCallback);
733 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
734 ssl_, GetSessionCacheKey());
736 send_buffer_ = new GrowableIOBuffer();
737 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
738 recv_buffer_ = new GrowableIOBuffer();
739 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
741 BIO* ssl_bio = NULL;
743 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
744 if (!BIO_new_bio_pair_external_buf(
745 &ssl_bio, send_buffer_->capacity(),
746 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
747 recv_buffer_->capacity(),
748 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
749 return ERR_UNEXPECTED;
750 DCHECK(ssl_bio);
751 DCHECK(transport_bio_);
753 // Install a callback on OpenSSL's end to plumb transport errors through.
754 BIO_set_callback(ssl_bio, BIOCallback);
755 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
757 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
759 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
760 // set everything we care about to an absolute value.
761 SslSetClearMask options;
762 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
763 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
764 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
765 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
766 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
767 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
768 bool tls1_1_enabled =
769 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
770 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
771 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
772 bool tls1_2_enabled =
773 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
774 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
775 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
777 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
779 // TODO(joth): Set this conditionally, see http://crbug.com/55410
780 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
782 SSL_set_options(ssl_, options.set_mask);
783 SSL_clear_options(ssl_, options.clear_mask);
785 // Same as above, this time for the SSL mode.
786 SslSetClearMask mode;
788 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
789 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
791 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
792 ssl_config_.false_start_enabled);
794 SSL_set_mode(ssl_, mode.set_mask);
795 SSL_clear_mode(ssl_, mode.clear_mask);
797 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
798 // textual name with SSL_set_cipher_list because there is no public API to
799 // directly remove a cipher by ID.
800 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
801 DCHECK(ciphers);
802 // See SSLConfig::disabled_cipher_suites for description of the suites
803 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
804 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
805 // as the handshake hash.
806 std::string command(
807 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
808 // Walk through all the installed ciphers, seeing if any need to be
809 // appended to the cipher removal |command|.
810 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
811 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
812 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
813 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
814 // implementation uses "effective" bits here but OpenSSL does not provide
815 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
816 // both of which are greater than 80 anyway.
817 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
818 if (!disable) {
819 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
820 ssl_config_.disabled_cipher_suites.end(), id) !=
821 ssl_config_.disabled_cipher_suites.end();
823 if (disable) {
824 const char* name = SSL_CIPHER_get_name(cipher);
825 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
826 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
827 command.append(":!");
828 command.append(name);
832 // Disable ECDSA cipher suites on platforms that do not support ECDSA
833 // signed certificates, as servers may use the presence of such
834 // ciphersuites as a hint to send an ECDSA certificate.
835 #if defined(OS_WIN)
836 if (base::win::GetVersion() < base::win::VERSION_VISTA)
837 command.append(":!ECDSA");
838 #endif
840 int rv = SSL_set_cipher_list(ssl_, command.c_str());
841 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
842 // This will almost certainly result in the socket failing to complete the
843 // handshake at which point the appropriate error is bubbled up to the client.
844 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
845 "returned " << rv;
847 if (ssl_config_.version_fallback)
848 SSL_enable_fallback_scsv(ssl_);
850 // TLS channel ids.
851 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
852 SSL_enable_tls_channel_id(ssl_);
855 if (!ssl_config_.next_protos.empty()) {
856 // Get list of ciphers that are enabled.
857 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
858 DCHECK(enabled_ciphers);
859 std::vector<uint16> enabled_ciphers_vector;
860 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
861 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
862 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
863 enabled_ciphers_vector.push_back(id);
866 std::vector<uint8_t> wire_protos =
867 SerializeNextProtos(ssl_config_.next_protos,
868 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
869 IsTLSVersionAdequateForHTTP2(ssl_config_));
870 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
871 wire_protos.size());
874 if (ssl_config_.signed_cert_timestamps_enabled) {
875 SSL_enable_signed_cert_timestamps(ssl_);
876 SSL_enable_ocsp_stapling(ssl_);
879 if (IsOCSPStaplingSupported())
880 SSL_enable_ocsp_stapling(ssl_);
882 return OK;
885 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
886 // Since Run may result in Read being called, clear |user_read_callback_|
887 // up front.
888 if (rv > 0)
889 was_ever_used_ = true;
890 user_read_buf_ = NULL;
891 user_read_buf_len_ = 0;
892 if (rv <= 0) {
893 // Failure of a read attempt may indicate a failed false start
894 // connection.
895 OnHandshakeCompletion();
897 base::ResetAndReturn(&user_read_callback_).Run(rv);
900 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
901 // Since Run may result in Write being called, clear |user_write_callback_|
902 // up front.
903 if (rv > 0)
904 was_ever_used_ = true;
905 user_write_buf_ = NULL;
906 user_write_buf_len_ = 0;
907 if (rv < 0) {
908 // Failure of a write attempt may indicate a failed false start
909 // connection.
910 OnHandshakeCompletion();
912 base::ResetAndReturn(&user_write_callback_).Run(rv);
915 void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
916 if (!handshake_completion_callback_.is_null())
917 base::ResetAndReturn(&handshake_completion_callback_).Run();
920 bool SSLClientSocketOpenSSL::DoTransportIO() {
921 bool network_moved = false;
922 int rv;
923 // Read and write as much data as possible. The loop is necessary because
924 // Write() may return synchronously.
925 do {
926 rv = BufferSend();
927 if (rv != ERR_IO_PENDING && rv != 0)
928 network_moved = true;
929 } while (rv > 0);
930 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
931 network_moved = true;
932 return network_moved;
935 // TODO(vadimt): Remove including "base/threading/thread_local.h" and
936 // g_first_run_completed once crbug.com/424386 is fixed.
937 base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
938 LAZY_INSTANCE_INITIALIZER;
940 int SSLClientSocketOpenSSL::DoHandshake() {
941 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
942 int net_error = OK;
944 int rv;
946 // TODO(vadimt): Leave only 1 call to SSL_do_handshake once crbug.com/424386
947 // is fixed.
948 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
949 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
950 tracked_objects::ScopedTracker tracking_profile1(
951 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 DoHandshake_WithCert"));
953 rv = SSL_do_handshake(ssl_);
954 } else {
955 if (g_first_run_completed.Get().Get()) {
956 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
957 // fixed.
958 tracked_objects::ScopedTracker tracking_profile1(
959 FROM_HERE_WITH_EXPLICIT_FUNCTION(
960 "424386 DoHandshake_WithoutCert Not First"));
962 rv = SSL_do_handshake(ssl_);
963 } else {
964 g_first_run_completed.Get().Set(true);
966 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
967 // fixed.
968 tracked_objects::ScopedTracker tracking_profile1(
969 FROM_HERE_WITH_EXPLICIT_FUNCTION(
970 "424386 DoHandshake_WithoutCert First"));
972 rv = SSL_do_handshake(ssl_);
976 if (client_auth_cert_needed_) {
977 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
978 tracked_objects::ScopedTracker tracking_profile2(
979 FROM_HERE_WITH_EXPLICIT_FUNCTION(
980 "424386 SSLClientSocketOpenSSL::DoHandshake2"));
982 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
983 // If the handshake already succeeded (because the server requests but
984 // doesn't require a client cert), we need to invalidate the SSL session
985 // so that we won't try to resume the non-client-authenticated session in
986 // the next handshake. This will cause the server to ask for a client
987 // cert again.
988 if (rv == 1) {
989 // Remove from session cache but don't clear this connection.
990 SSL_SESSION* session = SSL_get_session(ssl_);
991 if (session) {
992 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
993 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
996 } else if (rv == 1) {
997 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
998 tracked_objects::ScopedTracker tracking_profile3(
999 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1000 "424386 SSLClientSocketOpenSSL::DoHandshake3"));
1002 if (trying_cached_session_ && logging::DEBUG_MODE) {
1003 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
1004 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
1007 if (ssl_config_.version_fallback &&
1008 ssl_config_.version_max < ssl_config_.version_fallback_min) {
1009 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
1012 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1013 if (npn_status_ == kNextProtoUnsupported) {
1014 const uint8_t* alpn_proto = NULL;
1015 unsigned alpn_len = 0;
1016 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
1017 if (alpn_len > 0) {
1018 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
1019 npn_status_ = kNextProtoNegotiated;
1020 set_negotiation_extension(kExtensionALPN);
1024 RecordChannelIDSupport(channel_id_service_,
1025 channel_id_xtn_negotiated_,
1026 ssl_config_.channel_id_enabled,
1027 crypto::ECPrivateKey::IsSupported());
1029 // Only record OCSP histograms if OCSP was requested.
1030 if (ssl_config_.signed_cert_timestamps_enabled ||
1031 IsOCSPStaplingSupported()) {
1032 const uint8_t* ocsp_response;
1033 size_t ocsp_response_len;
1034 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
1036 set_stapled_ocsp_response_received(ocsp_response_len != 0);
1037 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
1040 const uint8_t* sct_list;
1041 size_t sct_list_len;
1042 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
1043 set_signed_cert_timestamps_received(sct_list_len != 0);
1045 // Verify the certificate.
1046 UpdateServerCert();
1047 GotoState(STATE_VERIFY_CERT);
1048 } else {
1049 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1050 tracked_objects::ScopedTracker tracking_profile4(
1051 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1052 "424386 SSLClientSocketOpenSSL::DoHandshake4"));
1054 int ssl_error = SSL_get_error(ssl_, rv);
1056 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
1057 // The server supports channel ID. Stop to look one up before returning to
1058 // the handshake.
1059 channel_id_xtn_negotiated_ = true;
1060 GotoState(STATE_CHANNEL_ID_LOOKUP);
1061 return OK;
1064 OpenSSLErrorInfo error_info;
1065 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
1067 // If not done, stay in this state
1068 if (net_error == ERR_IO_PENDING) {
1069 GotoState(STATE_HANDSHAKE);
1070 } else {
1071 LOG(ERROR) << "handshake failed; returned " << rv
1072 << ", SSL error code " << ssl_error
1073 << ", net_error " << net_error;
1074 net_log_.AddEvent(
1075 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1076 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1079 return net_error;
1082 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1083 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
1084 return channel_id_service_->GetOrCreateChannelID(
1085 host_and_port_.host(),
1086 &channel_id_private_key_,
1087 &channel_id_cert_,
1088 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1089 base::Unretained(this)),
1090 &channel_id_request_handle_);
1093 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1094 if (result < 0)
1095 return result;
1097 DCHECK_LT(0u, channel_id_private_key_.size());
1098 // Decode key.
1099 std::vector<uint8> encrypted_private_key_info;
1100 std::vector<uint8> subject_public_key_info;
1101 encrypted_private_key_info.assign(
1102 channel_id_private_key_.data(),
1103 channel_id_private_key_.data() + channel_id_private_key_.size());
1104 subject_public_key_info.assign(
1105 channel_id_cert_.data(),
1106 channel_id_cert_.data() + channel_id_cert_.size());
1107 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1108 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1109 ChannelIDService::kEPKIPassword,
1110 encrypted_private_key_info,
1111 subject_public_key_info));
1112 if (!ec_private_key) {
1113 LOG(ERROR) << "Failed to import Channel ID.";
1114 return ERR_CHANNEL_ID_IMPORT_FAILED;
1117 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1118 // type.
1119 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1120 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1121 if (!rv) {
1122 LOG(ERROR) << "Failed to set Channel ID.";
1123 int err = SSL_get_error(ssl_, rv);
1124 return MapOpenSSLError(err, err_tracer);
1127 // Return to the handshake.
1128 set_channel_id_sent(true);
1129 GotoState(STATE_HANDSHAKE);
1130 return OK;
1133 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
1134 DCHECK(!server_cert_chain_->empty());
1135 DCHECK(start_cert_verification_time_.is_null());
1137 GotoState(STATE_VERIFY_CERT_COMPLETE);
1139 // If the certificate is bad and has been previously accepted, use
1140 // the previous status and bypass the error.
1141 base::StringPiece der_cert;
1142 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1143 NOTREACHED();
1144 return ERR_CERT_INVALID;
1146 CertStatus cert_status;
1147 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
1148 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1149 server_cert_verify_result_.Reset();
1150 server_cert_verify_result_.cert_status = cert_status;
1151 server_cert_verify_result_.verified_cert = server_cert_;
1152 return OK;
1155 // When running in a sandbox, it may not be possible to create an
1156 // X509Certificate*, as that may depend on OS functionality blocked
1157 // in the sandbox.
1158 if (!server_cert_.get()) {
1159 server_cert_verify_result_.Reset();
1160 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1161 return ERR_CERT_INVALID;
1164 start_cert_verification_time_ = base::TimeTicks::Now();
1166 int flags = 0;
1167 if (ssl_config_.rev_checking_enabled)
1168 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1169 if (ssl_config_.verify_ev_cert)
1170 flags |= CertVerifier::VERIFY_EV_CERT;
1171 if (ssl_config_.cert_io_enabled)
1172 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1173 if (ssl_config_.rev_checking_required_local_anchors)
1174 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1175 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1176 return verifier_->Verify(
1177 server_cert_.get(),
1178 host_and_port_.host(),
1179 flags,
1180 // TODO(davidben): Route the CRLSet through SSLConfig so
1181 // SSLClientSocket doesn't depend on SSLConfigService.
1182 SSLConfigService::GetCRLSet().get(),
1183 &server_cert_verify_result_,
1184 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1185 base::Unretained(this)),
1186 net_log_);
1189 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1190 verifier_.reset();
1192 if (!start_cert_verification_time_.is_null()) {
1193 base::TimeDelta verify_time =
1194 base::TimeTicks::Now() - start_cert_verification_time_;
1195 if (result == OK) {
1196 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1197 } else {
1198 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1202 if (result == OK) {
1203 RecordConnectionTypeMetrics(GetNetSSLVersion(ssl_));
1205 if (SSL_session_reused(ssl_)) {
1206 // Record whether or not the server tried to resume a session for a
1207 // different version. See https://crbug.com/441456.
1208 UMA_HISTOGRAM_BOOLEAN(
1209 "Net.SSLSessionVersionMatch",
1210 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1214 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1215 if (transport_security_state_ &&
1216 (result == OK ||
1217 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1218 !transport_security_state_->CheckPublicKeyPins(
1219 host_and_port_.host(),
1220 server_cert_verify_result_.is_issued_by_known_root,
1221 server_cert_verify_result_.public_key_hashes,
1222 &pinning_failure_log_)) {
1223 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1226 if (result == OK) {
1227 // Only check Certificate Transparency if there were no other errors with
1228 // the connection.
1229 VerifyCT();
1231 // TODO(joth): Work out if we need to remember the intermediate CA certs
1232 // when the server sends them to us, and do so here.
1233 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
1234 marked_session_as_good_ = true;
1235 CheckIfHandshakeFinished();
1236 } else {
1237 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1238 << " (" << result << ")";
1241 completed_connect_ = true;
1243 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1244 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1245 return result;
1248 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1249 if (rv < OK)
1250 OnHandshakeCompletion();
1251 if (!user_connect_callback_.is_null()) {
1252 CompletionCallback c = user_connect_callback_;
1253 user_connect_callback_.Reset();
1254 c.Run(rv > OK ? OK : rv);
1258 void SSLClientSocketOpenSSL::UpdateServerCert() {
1259 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1260 tracked_objects::ScopedTracker tracking_profile(
1261 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1262 "424386 SSLClientSocketOpenSSL::UpdateServerCert"));
1264 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
1266 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1267 tracked_objects::ScopedTracker tracking_profile1(
1268 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1269 "424386 SSLClientSocketOpenSSL::UpdateServerCert1"));
1270 server_cert_ = server_cert_chain_->AsOSChain();
1272 if (server_cert_.get()) {
1273 net_log_.AddEvent(
1274 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1275 base::Bind(&NetLogX509CertificateCallback,
1276 base::Unretained(server_cert_.get())));
1278 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1279 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1280 if (IsOCSPStaplingSupported()) {
1281 #if defined(OS_WIN)
1282 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
1283 // fixed.
1284 tracked_objects::ScopedTracker tracking_profile2(
1285 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1286 "424386 SSLClientSocketOpenSSL::UpdateServerCert2"));
1288 const uint8_t* ocsp_response_raw;
1289 size_t ocsp_response_len;
1290 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1292 CRYPT_DATA_BLOB ocsp_response_blob;
1293 ocsp_response_blob.cbData = ocsp_response_len;
1294 ocsp_response_blob.pbData = const_cast<BYTE*>(ocsp_response_raw);
1295 BOOL ok = CertSetCertificateContextProperty(
1296 server_cert_->os_cert_handle(),
1297 CERT_OCSP_RESPONSE_PROP_ID,
1298 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1299 &ocsp_response_blob);
1300 if (!ok) {
1301 VLOG(1) << "Failed to set OCSP response property: "
1302 << GetLastError();
1304 #else
1305 NOTREACHED();
1306 #endif
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 } else {
1341 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1342 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1343 SSLConfigService::GetEVCertsWhitelist();
1344 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1345 server_cert_verify_result_.verified_cert.get(),
1346 ev_whitelist.get(), ct_verify_result_, net_log_)) {
1347 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1348 VLOG(1) << "EV certificate for "
1349 << server_cert_verify_result_.verified_cert->subject()
1350 .GetDisplayName()
1351 << " does not conform to CT policy, removing EV status.";
1352 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1358 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1359 int rv = DoHandshakeLoop(result);
1360 if (rv != ERR_IO_PENDING) {
1361 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1362 DoConnectCallback(rv);
1366 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1367 if (next_handshake_state_ == STATE_HANDSHAKE) {
1368 // In handshake phase.
1369 OnHandshakeIOComplete(result);
1370 return;
1373 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1374 // handshake is in progress.
1375 int rv_read = ERR_IO_PENDING;
1376 int rv_write = ERR_IO_PENDING;
1377 bool network_moved;
1378 do {
1379 if (user_read_buf_.get())
1380 rv_read = DoPayloadRead();
1381 if (user_write_buf_.get())
1382 rv_write = DoPayloadWrite();
1383 network_moved = DoTransportIO();
1384 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1385 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1387 // Performing the Read callback may cause |this| to be deleted. If this
1388 // happens, the Write callback should not be invoked. Guard against this by
1389 // holding a WeakPtr to |this| and ensuring it's still valid.
1390 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1391 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1392 DoReadCallback(rv_read);
1394 if (!guard.get())
1395 return;
1397 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1398 DoWriteCallback(rv_write);
1401 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1402 if (next_handshake_state_ == STATE_HANDSHAKE) {
1403 // In handshake phase.
1404 OnHandshakeIOComplete(result);
1405 return;
1408 // Network layer received some data, check if client requested to read
1409 // decrypted data.
1410 if (!user_read_buf_.get())
1411 return;
1413 int rv = DoReadLoop();
1414 if (rv != ERR_IO_PENDING)
1415 DoReadCallback(rv);
1418 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1419 int rv = last_io_result;
1420 do {
1421 // Default to STATE_NONE for next state.
1422 // (This is a quirk carried over from the windows
1423 // implementation. It makes reading the logs a bit harder.)
1424 // State handlers can and often do call GotoState just
1425 // to stay in the current state.
1426 State state = next_handshake_state_;
1427 GotoState(STATE_NONE);
1428 switch (state) {
1429 case STATE_HANDSHAKE:
1430 rv = DoHandshake();
1431 break;
1432 case STATE_CHANNEL_ID_LOOKUP:
1433 DCHECK_EQ(OK, rv);
1434 rv = DoChannelIDLookup();
1435 break;
1436 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1437 rv = DoChannelIDLookupComplete(rv);
1438 break;
1439 case STATE_VERIFY_CERT:
1440 DCHECK_EQ(OK, rv);
1441 rv = DoVerifyCert(rv);
1442 break;
1443 case STATE_VERIFY_CERT_COMPLETE:
1444 rv = DoVerifyCertComplete(rv);
1445 break;
1446 case STATE_NONE:
1447 default:
1448 rv = ERR_UNEXPECTED;
1449 NOTREACHED() << "unexpected state" << state;
1450 break;
1453 bool network_moved = DoTransportIO();
1454 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1455 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1456 // special case we keep looping even if rv is ERR_IO_PENDING because
1457 // the transport IO may allow DoHandshake to make progress.
1458 rv = OK; // This causes us to stay in the loop.
1460 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1462 return rv;
1465 int SSLClientSocketOpenSSL::DoReadLoop() {
1466 bool network_moved;
1467 int rv;
1468 do {
1469 rv = DoPayloadRead();
1470 network_moved = DoTransportIO();
1471 } while (rv == ERR_IO_PENDING && network_moved);
1473 return rv;
1476 int SSLClientSocketOpenSSL::DoWriteLoop() {
1477 bool network_moved;
1478 int rv;
1479 do {
1480 rv = DoPayloadWrite();
1481 network_moved = DoTransportIO();
1482 } while (rv == ERR_IO_PENDING && network_moved);
1484 return rv;
1487 int SSLClientSocketOpenSSL::DoPayloadRead() {
1488 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1490 int rv;
1491 if (pending_read_error_ != kNoPendingReadResult) {
1492 rv = pending_read_error_;
1493 pending_read_error_ = kNoPendingReadResult;
1494 if (rv == 0) {
1495 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1496 rv, user_read_buf_->data());
1497 } else {
1498 net_log_.AddEvent(
1499 NetLog::TYPE_SSL_READ_ERROR,
1500 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1501 pending_read_error_info_));
1503 pending_read_ssl_error_ = SSL_ERROR_NONE;
1504 pending_read_error_info_ = OpenSSLErrorInfo();
1505 return rv;
1508 int total_bytes_read = 0;
1509 do {
1510 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1511 user_read_buf_len_ - total_bytes_read);
1512 if (rv > 0)
1513 total_bytes_read += rv;
1514 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1516 if (total_bytes_read == user_read_buf_len_) {
1517 rv = total_bytes_read;
1518 } else {
1519 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1520 // immediately, while the OpenSSL errors are still available in
1521 // thread-local storage. However, the handled/remapped error code should
1522 // only be returned if no application data was already read; if it was, the
1523 // error code should be deferred until the next call of DoPayloadRead.
1525 // If no data was read, |*next_result| will point to the return value of
1526 // this function. If at least some data was read, |*next_result| will point
1527 // to |pending_read_error_|, to be returned in a future call to
1528 // DoPayloadRead() (e.g.: after the current data is handled).
1529 int *next_result = &rv;
1530 if (total_bytes_read > 0) {
1531 pending_read_error_ = rv;
1532 rv = total_bytes_read;
1533 next_result = &pending_read_error_;
1536 if (client_auth_cert_needed_) {
1537 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1538 } else if (*next_result < 0) {
1539 pending_read_ssl_error_ = SSL_get_error(ssl_, *next_result);
1540 *next_result = MapOpenSSLErrorWithDetails(pending_read_ssl_error_,
1541 err_tracer,
1542 &pending_read_error_info_);
1544 // Many servers do not reliably send a close_notify alert when shutting
1545 // down a connection, and instead terminate the TCP connection. This is
1546 // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1547 // shutdown to a graceful EOF, instead of treating it as an error as it
1548 // should be.
1549 if (*next_result == ERR_CONNECTION_CLOSED)
1550 *next_result = 0;
1552 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1553 // If at least some data was read from SSL_read(), do not treat
1554 // insufficient data as an error to return in the next call to
1555 // DoPayloadRead() - instead, let the call fall through to check
1556 // SSL_read() again. This is because DoTransportIO() may complete
1557 // in between the next call to DoPayloadRead(), and thus it is
1558 // important to check SSL_read() on subsequent invocations to see
1559 // if a complete record may now be read.
1560 *next_result = kNoPendingReadResult;
1565 if (rv >= 0) {
1566 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1567 user_read_buf_->data());
1568 } else if (rv != ERR_IO_PENDING) {
1569 net_log_.AddEvent(
1570 NetLog::TYPE_SSL_READ_ERROR,
1571 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1572 pending_read_error_info_));
1573 pending_read_ssl_error_ = SSL_ERROR_NONE;
1574 pending_read_error_info_ = OpenSSLErrorInfo();
1576 return rv;
1579 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1580 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1581 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1582 if (rv >= 0) {
1583 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1584 user_write_buf_->data());
1585 return rv;
1588 int ssl_error = SSL_get_error(ssl_, rv);
1589 OpenSSLErrorInfo error_info;
1590 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1591 &error_info);
1593 if (net_error != ERR_IO_PENDING) {
1594 net_log_.AddEvent(
1595 NetLog::TYPE_SSL_WRITE_ERROR,
1596 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1598 return net_error;
1601 int SSLClientSocketOpenSSL::BufferSend(void) {
1602 if (transport_send_busy_)
1603 return ERR_IO_PENDING;
1605 size_t buffer_read_offset;
1606 uint8_t* read_buf;
1607 size_t max_read;
1608 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1609 &buffer_read_offset, &max_read);
1610 DCHECK_EQ(status, 1); // Should never fail.
1611 if (!max_read)
1612 return 0; // Nothing pending in the OpenSSL write BIO.
1613 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1614 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1615 send_buffer_->set_offset(buffer_read_offset);
1617 int rv = transport_->socket()->Write(
1618 send_buffer_.get(), max_read,
1619 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1620 base::Unretained(this)));
1621 if (rv == ERR_IO_PENDING) {
1622 transport_send_busy_ = true;
1623 } else {
1624 TransportWriteComplete(rv);
1626 return rv;
1629 int SSLClientSocketOpenSSL::BufferRecv(void) {
1630 if (transport_recv_busy_)
1631 return ERR_IO_PENDING;
1633 // Determine how much was requested from |transport_bio_| that was not
1634 // actually available.
1635 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1636 if (requested == 0) {
1637 // This is not a perfect match of error codes, as no operation is
1638 // actually pending. However, returning 0 would be interpreted as
1639 // a possible sign of EOF, which is also an inappropriate match.
1640 return ERR_IO_PENDING;
1643 // Known Issue: While only reading |requested| data is the more correct
1644 // implementation, it has the downside of resulting in frequent reads:
1645 // One read for the SSL record header (~5 bytes) and one read for the SSL
1646 // record body. Rather than issuing these reads to the underlying socket
1647 // (and constantly allocating new IOBuffers), a single Read() request to
1648 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1649 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1650 // traffic, this over-subscribed Read()ing will not cause issues.
1652 size_t buffer_write_offset;
1653 uint8_t* write_buf;
1654 size_t max_write;
1655 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1656 &buffer_write_offset, &max_write);
1657 DCHECK_EQ(status, 1); // Should never fail.
1658 if (!max_write)
1659 return ERR_IO_PENDING;
1661 CHECK_EQ(write_buf,
1662 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1663 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1665 recv_buffer_->set_offset(buffer_write_offset);
1666 int rv = transport_->socket()->Read(
1667 recv_buffer_.get(),
1668 max_write,
1669 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1670 base::Unretained(this)));
1671 if (rv == ERR_IO_PENDING) {
1672 transport_recv_busy_ = true;
1673 } else {
1674 rv = TransportReadComplete(rv);
1676 return rv;
1679 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1680 TransportWriteComplete(result);
1681 OnSendComplete(result);
1684 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1685 result = TransportReadComplete(result);
1686 OnRecvComplete(result);
1689 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1690 DCHECK(ERR_IO_PENDING != result);
1691 int bytes_written = 0;
1692 if (result < 0) {
1693 // Record the error. Save it to be reported in a future read or write on
1694 // transport_bio_'s peer.
1695 transport_write_error_ = result;
1696 } else {
1697 bytes_written = result;
1699 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1700 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1701 DCHECK_EQ(1, ret);
1702 transport_send_busy_ = false;
1705 int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1706 DCHECK(ERR_IO_PENDING != result);
1707 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1708 // does not report success.
1709 if (result == 0)
1710 result = ERR_CONNECTION_CLOSED;
1711 int bytes_read = 0;
1712 if (result < 0) {
1713 DVLOG(1) << "TransportReadComplete result " << result;
1714 // Received an error. Save it to be reported in a future read on
1715 // transport_bio_'s peer.
1716 transport_read_error_ = result;
1717 } else {
1718 bytes_read = result;
1720 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1721 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1722 DCHECK_EQ(1, ret);
1723 transport_recv_busy_ = false;
1724 return result;
1727 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
1728 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1729 tracked_objects::ScopedTracker tracking_profile(
1730 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1731 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1733 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1734 DCHECK(ssl == ssl_);
1736 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1738 // Clear any currently configured certificates.
1739 SSL_certs_clear(ssl_);
1741 #if defined(OS_IOS)
1742 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1743 LOG(WARNING) << "Client auth is not supported";
1744 #else // !defined(OS_IOS)
1745 if (!ssl_config_.send_client_cert) {
1746 // First pass: we know that a client certificate is needed, but we do not
1747 // have one at hand.
1748 client_auth_cert_needed_ = true;
1749 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1750 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
1751 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1752 unsigned char* str = NULL;
1753 int length = i2d_X509_NAME(ca_name, &str);
1754 cert_authorities_.push_back(std::string(
1755 reinterpret_cast<const char*>(str),
1756 static_cast<size_t>(length)));
1757 OPENSSL_free(str);
1760 const unsigned char* client_cert_types;
1761 size_t num_client_cert_types =
1762 SSL_get0_certificate_types(ssl, &client_cert_types);
1763 for (size_t i = 0; i < num_client_cert_types; i++) {
1764 cert_key_types_.push_back(
1765 static_cast<SSLClientCertType>(client_cert_types[i]));
1768 return -1; // Suspends handshake.
1771 // Second pass: a client certificate should have been selected.
1772 if (ssl_config_.client_cert.get()) {
1773 ScopedX509 leaf_x509 =
1774 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1775 if (!leaf_x509) {
1776 LOG(WARNING) << "Failed to import certificate";
1777 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1778 return -1;
1781 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1782 ssl_config_.client_cert->GetIntermediateCertificates());
1783 if (!chain) {
1784 LOG(WARNING) << "Failed to import intermediate certificates";
1785 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1786 return -1;
1789 // TODO(davidben): With Linux client auth support, this should be
1790 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1791 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1792 // net/ client auth API lacking a private key handle.
1793 #if defined(USE_OPENSSL_CERTS)
1794 crypto::ScopedEVP_PKEY privkey =
1795 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1796 ssl_config_.client_cert.get());
1797 #else // !defined(USE_OPENSSL_CERTS)
1798 crypto::ScopedEVP_PKEY privkey =
1799 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1800 #endif // defined(USE_OPENSSL_CERTS)
1801 if (!privkey) {
1802 // Could not find the private key. Fail the handshake and surface an
1803 // appropriate error to the caller.
1804 LOG(WARNING) << "Client cert found without private key";
1805 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1806 return -1;
1809 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1810 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1811 !SSL_set1_chain(ssl_, chain.get())) {
1812 LOG(WARNING) << "Failed to set client certificate";
1813 return -1;
1816 int cert_count = 1 + sk_X509_num(chain.get());
1817 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1818 NetLog::IntegerCallback("cert_count", cert_count));
1819 return 1;
1821 #endif // defined(OS_IOS)
1823 // Send no client certificate.
1824 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1825 NetLog::IntegerCallback("cert_count", 0));
1826 return 1;
1829 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1830 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1831 tracked_objects::ScopedTracker tracking_profile(
1832 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1833 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1835 if (!completed_connect_) {
1836 // If the first handshake hasn't completed then we accept any certificates
1837 // because we verify after the handshake.
1838 return 1;
1841 // Disallow the server certificate to change in a renegotiation.
1842 if (server_cert_chain_->empty()) {
1843 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1844 return 0;
1846 base::StringPiece old_der, new_der;
1847 if (store_ctx->cert == NULL ||
1848 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1849 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1850 LOG(ERROR) << "Failed to encode certificates";
1851 return 0;
1853 if (old_der != new_der) {
1854 LOG(ERROR) << "Server certificate changed between handshakes";
1855 return 0;
1858 return 1;
1861 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1862 // server supports NPN, selects a protocol from the list that the server
1863 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1864 // callback can assume that |in| is syntactically valid.
1865 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1866 unsigned char* outlen,
1867 const unsigned char* in,
1868 unsigned int inlen) {
1869 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1870 tracked_objects::ScopedTracker tracking_profile(
1871 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1872 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1874 if (ssl_config_.next_protos.empty()) {
1875 *out = reinterpret_cast<uint8*>(
1876 const_cast<char*>(kDefaultSupportedNPNProtocol));
1877 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1878 npn_status_ = kNextProtoUnsupported;
1879 return SSL_TLSEXT_ERR_OK;
1882 // Assume there's no overlap between our protocols and the server's list.
1883 npn_status_ = kNextProtoNoOverlap;
1885 // For each protocol in server preference order, see if we support it.
1886 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1887 for (NextProto next_proto : ssl_config_.next_protos) {
1888 const std::string proto = NextProtoToString(next_proto);
1889 if (in[i] == proto.size() &&
1890 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
1891 // We found a match.
1892 *out = const_cast<unsigned char*>(in) + i + 1;
1893 *outlen = in[i];
1894 npn_status_ = kNextProtoNegotiated;
1895 break;
1898 if (npn_status_ == kNextProtoNegotiated)
1899 break;
1902 // If we didn't find a protocol, we select the first one from our list.
1903 if (npn_status_ == kNextProtoNoOverlap) {
1904 // NextProtoToString returns a pointer to a static string.
1905 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1906 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1907 *outlen = strlen(proto);
1910 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
1911 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
1912 set_negotiation_extension(kExtensionNPN);
1913 return SSL_TLSEXT_ERR_OK;
1916 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1917 BIO *bio,
1918 int cmd,
1919 const char *argp, int argi, long argl,
1920 long retvalue) {
1921 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1922 // If there is no more data in the buffer, report any pending errors that
1923 // were observed. Note that both the readbuf and the writebuf are checked
1924 // for errors, since the application may have encountered a socket error
1925 // while writing that would otherwise not be reported until the application
1926 // attempted to write again - which it may never do. See
1927 // https://crbug.com/249848.
1928 if (transport_read_error_ != OK) {
1929 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1930 return -1;
1932 if (transport_write_error_ != OK) {
1933 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1934 return -1;
1936 } else if (cmd == BIO_CB_WRITE) {
1937 // Because of the write buffer, this reports a failure from the previous
1938 // write payload. If the current payload fails to write, the error will be
1939 // reported in a future write or read to |bio|.
1940 if (transport_write_error_ != OK) {
1941 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1942 return -1;
1945 return retvalue;
1948 // static
1949 long SSLClientSocketOpenSSL::BIOCallback(
1950 BIO *bio,
1951 int cmd,
1952 const char *argp, int argi, long argl,
1953 long retvalue) {
1954 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1955 tracked_objects::ScopedTracker tracking_profile(
1956 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1957 "424386 SSLClientSocketOpenSSL::BIOCallback"));
1959 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1960 BIO_get_callback_arg(bio));
1961 CHECK(socket);
1962 return socket->MaybeReplayTransportError(
1963 bio, cmd, argp, argi, argl, retvalue);
1966 // static
1967 void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1968 int type,
1969 int /*val*/) {
1970 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1971 tracked_objects::ScopedTracker tracking_profile(
1972 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1973 "424386 SSLClientSocketOpenSSL::InfoCallback"));
1975 if (type == SSL_CB_HANDSHAKE_DONE) {
1976 SSLClientSocketOpenSSL* ssl_socket =
1977 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1978 ssl_socket->handshake_succeeded_ = true;
1979 ssl_socket->CheckIfHandshakeFinished();
1983 // Determines if both the handshake and certificate verification have completed
1984 // successfully, and calls the handshake completion callback if that is the
1985 // case.
1987 // CheckIfHandshakeFinished is called twice per connection: once after
1988 // MarkSSLSessionAsGood, when the certificate has been verified, and
1989 // once via an OpenSSL callback when the handshake has completed. On the
1990 // second call, when the certificate has been verified and the handshake
1991 // has completed, the connection's handshake completion callback is run.
1992 void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1993 if (handshake_succeeded_ && marked_session_as_good_)
1994 OnHandshakeCompletion();
1997 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1998 for (ct::SCTList::const_iterator iter =
1999 ct_verify_result_.verified_scts.begin();
2000 iter != ct_verify_result_.verified_scts.end(); ++iter) {
2001 ssl_info->signed_certificate_timestamps.push_back(
2002 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
2004 for (ct::SCTList::const_iterator iter =
2005 ct_verify_result_.invalid_scts.begin();
2006 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
2007 ssl_info->signed_certificate_timestamps.push_back(
2008 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
2010 for (ct::SCTList::const_iterator iter =
2011 ct_verify_result_.unknown_logs_scts.begin();
2012 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
2013 ssl_info->signed_certificate_timestamps.push_back(
2014 SignedCertificateTimestampAndStatus(*iter,
2015 ct::SCT_STATUS_LOG_UNKNOWN));
2019 scoped_refptr<X509Certificate>
2020 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
2021 return server_cert_;
2024 } // namespace net