Delete unmasked credit cards when clearing data.
[chromium-blink-merge.git] / net / socket / ssl_client_socket_openssl.cc
blobd8713f28f9e37e3fc48e0d94d38dba708b895380
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/scoped_openssl_types.h"
39 #include "net/ssl/ssl_cert_request_info.h"
40 #include "net/ssl/ssl_connection_status_flags.h"
41 #include "net/ssl/ssl_info.h"
43 #if defined(OS_WIN)
44 #include "base/win/windows_version.h"
45 #endif
47 #if defined(USE_OPENSSL_CERTS)
48 #include "net/ssl/openssl_client_key_store.h"
49 #else
50 #include "net/ssl/openssl_platform_key.h"
51 #endif
53 namespace net {
55 namespace {
57 // Enable this to see logging for state machine state transitions.
58 #if 0
59 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
60 " jump to state " << s; \
61 next_handshake_state_ = s; } while (0)
62 #else
63 #define GotoState(s) next_handshake_state_ = s
64 #endif
66 // This constant can be any non-negative/non-zero value (eg: it does not
67 // overlap with any value of the net::Error range, including net::OK).
68 const int kNoPendingReadResult = 1;
70 // If a client doesn't have a list of protocols that it supports, but
71 // the server supports NPN, choosing "http/1.1" is the best answer.
72 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
74 // Default size of the internal BoringSSL buffers.
75 const int KDefaultOpenSSLBufferSize = 17 * 1024;
77 void FreeX509Stack(STACK_OF(X509)* ptr) {
78 sk_X509_pop_free(ptr, X509_free);
81 using ScopedX509Stack = crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>;
83 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
84 // This method doesn't seem to have made it into the OpenSSL headers.
85 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
86 #endif
88 // Used for encoding the |connection_status| field of an SSLInfo object.
89 int EncodeSSLConnectionStatus(uint16 cipher_suite,
90 int compression,
91 int version) {
92 return cipher_suite |
93 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
94 SSL_CONNECTION_COMPRESSION_SHIFT) |
95 ((version & SSL_CONNECTION_VERSION_MASK) <<
96 SSL_CONNECTION_VERSION_SHIFT);
99 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
100 // this SSL connection.
101 int GetNetSSLVersion(SSL* ssl) {
102 switch (SSL_version(ssl)) {
103 case SSL2_VERSION:
104 return SSL_CONNECTION_VERSION_SSL2;
105 case SSL3_VERSION:
106 return SSL_CONNECTION_VERSION_SSL3;
107 case TLS1_VERSION:
108 return SSL_CONNECTION_VERSION_TLS1;
109 case TLS1_1_VERSION:
110 return SSL_CONNECTION_VERSION_TLS1_1;
111 case TLS1_2_VERSION:
112 return SSL_CONNECTION_VERSION_TLS1_2;
113 default:
114 return SSL_CONNECTION_VERSION_UNKNOWN;
118 ScopedX509 OSCertHandleToOpenSSL(
119 X509Certificate::OSCertHandle os_handle) {
120 #if defined(USE_OPENSSL_CERTS)
121 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
122 #else // !defined(USE_OPENSSL_CERTS)
123 std::string der_encoded;
124 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
125 return ScopedX509();
126 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
127 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
128 #endif // defined(USE_OPENSSL_CERTS)
131 ScopedX509Stack OSCertHandlesToOpenSSL(
132 const X509Certificate::OSCertHandles& os_handles) {
133 ScopedX509Stack stack(sk_X509_new_null());
134 for (size_t i = 0; i < os_handles.size(); i++) {
135 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
136 if (!x509)
137 return ScopedX509Stack();
138 sk_X509_push(stack.get(), x509.release());
140 return stack.Pass();
143 int LogErrorCallback(const char* str, size_t len, void* context) {
144 LOG(ERROR) << base::StringPiece(str, len);
145 return 1;
148 bool IsOCSPStaplingSupported() {
149 #if defined(OS_WIN)
150 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
151 // set on Windows XP without error. There is some overhead from the server
152 // sending the OCSP response if it supports the extension, for the subset of
153 // XP clients who will request it but be unable to use it, but this is an
154 // acceptable trade-off for simplicity of implementation.
155 return true;
156 #else
157 return false;
158 #endif
161 } // namespace
163 class SSLClientSocketOpenSSL::SSLContext {
164 public:
165 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
166 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
167 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
169 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
170 DCHECK(ssl);
171 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
172 SSL_get_ex_data(ssl, ssl_socket_data_index_));
173 DCHECK(socket);
174 return socket;
177 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
178 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
181 private:
182 friend struct DefaultSingletonTraits<SSLContext>;
184 SSLContext() {
185 crypto::EnsureOpenSSLInit();
186 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
187 DCHECK_NE(ssl_socket_data_index_, -1);
188 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
189 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
190 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
191 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
192 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
193 // This stops |SSL_shutdown| from generating the close_notify message, which
194 // is currently not sent on the network.
195 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
196 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
197 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
198 // It would be better if the callback were not a global setting,
199 // but that is an OpenSSL issue.
200 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
201 NULL);
202 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
204 scoped_ptr<base::Environment> env(base::Environment::Create());
205 std::string ssl_keylog_file;
206 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
207 !ssl_keylog_file.empty()) {
208 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
209 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
210 if (!bio) {
211 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
212 ERR_print_errors_cb(&LogErrorCallback, NULL);
213 } else {
214 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
219 static std::string GetSessionCacheKey(const SSL* ssl) {
220 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
221 DCHECK(socket);
222 return socket->GetSessionCacheKey();
225 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
227 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
228 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
229 DCHECK(socket);
230 return socket->ClientCertRequestCallback(ssl);
233 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
234 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
235 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
236 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
237 CHECK(socket);
239 return socket->CertVerifyCallback(store_ctx);
242 static int SelectNextProtoCallback(SSL* ssl,
243 unsigned char** out, unsigned char* outlen,
244 const unsigned char* in,
245 unsigned int inlen, void* arg) {
246 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
247 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
250 // This is the index used with SSL_get_ex_data to retrieve the owner
251 // SSLClientSocketOpenSSL object from an SSL instance.
252 int ssl_socket_data_index_;
254 ScopedSSL_CTX ssl_ctx_;
255 // |session_cache_| must be destroyed before |ssl_ctx_|.
256 SSLSessionCacheOpenSSL session_cache_;
259 // PeerCertificateChain is a helper object which extracts the certificate
260 // chain, as given by the server, from an OpenSSL socket and performs the needed
261 // resource management. The first element of the chain is the leaf certificate
262 // and the other elements are in the order given by the server.
263 class SSLClientSocketOpenSSL::PeerCertificateChain {
264 public:
265 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
266 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
267 ~PeerCertificateChain() {}
268 PeerCertificateChain& operator=(const PeerCertificateChain& other);
270 // Resets the PeerCertificateChain to the set of certificates in|chain|,
271 // which may be NULL, indicating to empty the store certificates.
272 // Note: If an error occurs, such as being unable to parse the certificates,
273 // this will behave as if Reset(NULL) was called.
274 void Reset(STACK_OF(X509)* chain);
276 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
277 scoped_refptr<X509Certificate> AsOSChain() const;
279 size_t size() const {
280 if (!openssl_chain_.get())
281 return 0;
282 return sk_X509_num(openssl_chain_.get());
285 bool empty() const {
286 return size() == 0;
289 X509* Get(size_t index) const {
290 DCHECK_LT(index, size());
291 return sk_X509_value(openssl_chain_.get(), index);
294 private:
295 ScopedX509Stack openssl_chain_;
298 SSLClientSocketOpenSSL::PeerCertificateChain&
299 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
300 const PeerCertificateChain& other) {
301 if (this == &other)
302 return *this;
304 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
305 return *this;
308 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
309 STACK_OF(X509)* chain) {
310 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
313 scoped_refptr<X509Certificate>
314 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
315 #if defined(USE_OPENSSL_CERTS)
316 // When OSCertHandle is typedef'ed to X509, this implementation does a short
317 // cut to avoid converting back and forth between DER and the X509 struct.
318 X509Certificate::OSCertHandles intermediates;
319 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
320 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
323 return make_scoped_refptr(X509Certificate::CreateFromHandle(
324 sk_X509_value(openssl_chain_.get(), 0), intermediates));
325 #else
326 // DER-encode the chain and convert to a platform certificate handle.
327 std::vector<base::StringPiece> der_chain;
328 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
329 X509* x = sk_X509_value(openssl_chain_.get(), i);
330 base::StringPiece der;
331 if (!x509_util::GetDER(x, &der))
332 return NULL;
333 der_chain.push_back(der);
336 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
337 #endif
340 // static
341 SSLSessionCacheOpenSSL::Config
342 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
343 &GetSessionCacheKey, // key_func
344 1024, // max_entries
345 256, // expiration_check_count
346 60 * 60, // timeout_seconds
349 // static
350 void SSLClientSocket::ClearSessionCache() {
351 SSLClientSocketOpenSSL::SSLContext* context =
352 SSLClientSocketOpenSSL::SSLContext::GetInstance();
353 context->session_cache()->Flush();
356 // static
357 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
358 return SSL_PROTOCOL_VERSION_TLS1_2;
361 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
362 scoped_ptr<ClientSocketHandle> transport_socket,
363 const HostPortPair& host_and_port,
364 const SSLConfig& ssl_config,
365 const SSLClientSocketContext& context)
366 : transport_send_busy_(false),
367 transport_recv_busy_(false),
368 pending_read_error_(kNoPendingReadResult),
369 pending_read_ssl_error_(SSL_ERROR_NONE),
370 transport_read_error_(OK),
371 transport_write_error_(OK),
372 server_cert_chain_(new PeerCertificateChain(NULL)),
373 completed_connect_(false),
374 was_ever_used_(false),
375 client_auth_cert_needed_(false),
376 cert_verifier_(context.cert_verifier),
377 cert_transparency_verifier_(context.cert_transparency_verifier),
378 channel_id_service_(context.channel_id_service),
379 ssl_(NULL),
380 transport_bio_(NULL),
381 transport_(transport_socket.Pass()),
382 host_and_port_(host_and_port),
383 ssl_config_(ssl_config),
384 ssl_session_cache_shard_(context.ssl_session_cache_shard),
385 trying_cached_session_(false),
386 next_handshake_state_(STATE_NONE),
387 npn_status_(kNextProtoUnsupported),
388 channel_id_xtn_negotiated_(false),
389 handshake_succeeded_(false),
390 marked_session_as_good_(false),
391 transport_security_state_(context.transport_security_state),
392 policy_enforcer_(context.cert_policy_enforcer),
393 net_log_(transport_->socket()->NetLog()),
394 weak_factory_(this) {
397 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
398 Disconnect();
401 std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
402 std::string result = host_and_port_.ToString();
403 result.append("/");
404 result.append(ssl_session_cache_shard_);
406 // Shard the session cache based on maximum protocol version. This causes
407 // fallback connections to use a separate session cache.
408 result.append("/");
409 switch (ssl_config_.version_max) {
410 case SSL_PROTOCOL_VERSION_SSL3:
411 result.append("ssl3");
412 break;
413 case SSL_PROTOCOL_VERSION_TLS1:
414 result.append("tls1");
415 break;
416 case SSL_PROTOCOL_VERSION_TLS1_1:
417 result.append("tls1.1");
418 break;
419 case SSL_PROTOCOL_VERSION_TLS1_2:
420 result.append("tls1.2");
421 break;
422 default:
423 NOTREACHED();
426 return result;
429 bool SSLClientSocketOpenSSL::InSessionCache() const {
430 SSLContext* context = SSLContext::GetInstance();
431 std::string cache_key = GetSessionCacheKey();
432 return context->session_cache()->SSLSessionIsInCache(cache_key);
435 void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
436 const base::Closure& callback) {
437 handshake_completion_callback_ = callback;
440 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
441 SSLCertRequestInfo* cert_request_info) {
442 cert_request_info->host_and_port = host_and_port_;
443 cert_request_info->cert_authorities = cert_authorities_;
444 cert_request_info->cert_key_types = cert_key_types_;
447 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
448 std::string* proto) {
449 *proto = npn_proto_;
450 return npn_status_;
453 ChannelIDService*
454 SSLClientSocketOpenSSL::GetChannelIDService() const {
455 return channel_id_service_;
458 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
459 const base::StringPiece& label,
460 bool has_context, const base::StringPiece& context,
461 unsigned char* out, unsigned int outlen) {
462 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
464 int rv = SSL_export_keying_material(
465 ssl_, out, outlen, label.data(), label.size(),
466 reinterpret_cast<const unsigned char*>(context.data()),
467 context.length(), context.length() > 0);
469 if (rv != 1) {
470 int ssl_error = SSL_get_error(ssl_, rv);
471 LOG(ERROR) << "Failed to export keying material;"
472 << " returned " << rv
473 << ", SSL error code " << ssl_error;
474 return MapOpenSSLError(ssl_error, err_tracer);
476 return OK;
479 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
480 NOTIMPLEMENTED();
481 return ERR_NOT_IMPLEMENTED;
484 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
485 // It is an error to create an SSLClientSocket whose context has no
486 // TransportSecurityState.
487 DCHECK(transport_security_state_);
489 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
491 // Set up new ssl object.
492 int rv = Init();
493 if (rv != OK) {
494 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
495 return rv;
498 // Set SSL to client mode. Handshake happens in the loop below.
499 SSL_set_connect_state(ssl_);
501 // Enable fastradio padding.
502 SSL_enable_fastradio_padding(ssl_,
503 ssl_config_.fastradio_padding_enabled &&
504 ssl_config_.fastradio_padding_eligible);
506 GotoState(STATE_HANDSHAKE);
507 rv = DoHandshakeLoop(OK);
508 if (rv == ERR_IO_PENDING) {
509 user_connect_callback_ = callback;
510 } else {
511 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
512 if (rv < OK)
513 OnHandshakeCompletion();
516 return rv > OK ? OK : rv;
519 void SSLClientSocketOpenSSL::Disconnect() {
520 // If a handshake was pending (Connect() had been called), notify interested
521 // parties that it's been aborted now. If the handshake had already
522 // completed, this is a no-op.
523 OnHandshakeCompletion();
524 if (ssl_) {
525 // Calling SSL_shutdown prevents the session from being marked as
526 // unresumable.
527 SSL_shutdown(ssl_);
528 SSL_free(ssl_);
529 ssl_ = NULL;
531 if (transport_bio_) {
532 BIO_free_all(transport_bio_);
533 transport_bio_ = NULL;
536 // Shut down anything that may call us back.
537 verifier_.reset();
538 transport_->socket()->Disconnect();
540 // Null all callbacks, delete all buffers.
541 transport_send_busy_ = false;
542 send_buffer_ = NULL;
543 transport_recv_busy_ = false;
544 recv_buffer_ = NULL;
546 user_connect_callback_.Reset();
547 user_read_callback_.Reset();
548 user_write_callback_.Reset();
549 user_read_buf_ = NULL;
550 user_read_buf_len_ = 0;
551 user_write_buf_ = NULL;
552 user_write_buf_len_ = 0;
554 pending_read_error_ = kNoPendingReadResult;
555 pending_read_ssl_error_ = SSL_ERROR_NONE;
556 pending_read_error_info_ = OpenSSLErrorInfo();
558 transport_read_error_ = OK;
559 transport_write_error_ = OK;
561 server_cert_verify_result_.Reset();
562 completed_connect_ = false;
564 cert_authorities_.clear();
565 cert_key_types_.clear();
566 client_auth_cert_needed_ = false;
568 start_cert_verification_time_ = base::TimeTicks();
570 npn_status_ = kNextProtoUnsupported;
571 npn_proto_.clear();
573 channel_id_xtn_negotiated_ = false;
574 channel_id_request_handle_.Cancel();
577 bool SSLClientSocketOpenSSL::IsConnected() const {
578 // If the handshake has not yet completed.
579 if (!completed_connect_)
580 return false;
581 // If an asynchronous operation is still pending.
582 if (user_read_buf_.get() || user_write_buf_.get())
583 return true;
585 return transport_->socket()->IsConnected();
588 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
589 // If the handshake has not yet completed.
590 if (!completed_connect_)
591 return false;
592 // If an asynchronous operation is still pending.
593 if (user_read_buf_.get() || user_write_buf_.get())
594 return false;
595 // If there is data waiting to be sent, or data read from the network that
596 // has not yet been consumed.
597 if (BIO_pending(transport_bio_) > 0 ||
598 BIO_wpending(transport_bio_) > 0) {
599 return false;
602 return transport_->socket()->IsConnectedAndIdle();
605 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
606 return transport_->socket()->GetPeerAddress(addressList);
609 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
610 return transport_->socket()->GetLocalAddress(addressList);
613 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
614 return net_log_;
617 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
618 if (transport_.get() && transport_->socket()) {
619 transport_->socket()->SetSubresourceSpeculation();
620 } else {
621 NOTREACHED();
625 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
626 if (transport_.get() && transport_->socket()) {
627 transport_->socket()->SetOmniboxSpeculation();
628 } else {
629 NOTREACHED();
633 bool SSLClientSocketOpenSSL::WasEverUsed() const {
634 return was_ever_used_;
637 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
638 if (transport_.get() && transport_->socket())
639 return transport_->socket()->UsingTCPFastOpen();
641 NOTREACHED();
642 return false;
645 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
646 ssl_info->Reset();
647 if (server_cert_chain_->empty())
648 return false;
650 ssl_info->cert = server_cert_verify_result_.verified_cert;
651 ssl_info->cert_status = server_cert_verify_result_.cert_status;
652 ssl_info->is_issued_by_known_root =
653 server_cert_verify_result_.is_issued_by_known_root;
654 ssl_info->public_key_hashes =
655 server_cert_verify_result_.public_key_hashes;
656 ssl_info->client_cert_sent =
657 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
658 ssl_info->channel_id_sent = WasChannelIDSent();
659 ssl_info->pinning_failure_log = pinning_failure_log_;
661 AddSCTInfoToSSLInfo(ssl_info);
663 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
664 CHECK(cipher);
665 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
667 ssl_info->connection_status = EncodeSSLConnectionStatus(
668 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
669 GetNetSSLVersion(ssl_));
671 if (!SSL_get_secure_renegotiation_support(ssl_))
672 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
674 if (ssl_config_.version_fallback)
675 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
677 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
678 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
680 DVLOG(3) << "Encoded connection status: cipher suite = "
681 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
682 << " version = "
683 << SSLConnectionStatusToVersion(ssl_info->connection_status);
684 return true;
687 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
688 int buf_len,
689 const CompletionCallback& callback) {
690 user_read_buf_ = buf;
691 user_read_buf_len_ = buf_len;
693 int rv = DoReadLoop();
695 if (rv == ERR_IO_PENDING) {
696 user_read_callback_ = callback;
697 } else {
698 if (rv > 0)
699 was_ever_used_ = true;
700 user_read_buf_ = NULL;
701 user_read_buf_len_ = 0;
702 if (rv <= 0) {
703 // Failure of a read attempt may indicate a failed false start
704 // connection.
705 OnHandshakeCompletion();
709 return rv;
712 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
713 int buf_len,
714 const CompletionCallback& callback) {
715 user_write_buf_ = buf;
716 user_write_buf_len_ = buf_len;
718 int rv = DoWriteLoop();
720 if (rv == ERR_IO_PENDING) {
721 user_write_callback_ = callback;
722 } else {
723 if (rv > 0)
724 was_ever_used_ = true;
725 user_write_buf_ = NULL;
726 user_write_buf_len_ = 0;
727 if (rv < 0) {
728 // Failure of a write attempt may indicate a failed false start
729 // connection.
730 OnHandshakeCompletion();
734 return rv;
737 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
738 return transport_->socket()->SetReceiveBufferSize(size);
741 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
742 return transport_->socket()->SetSendBufferSize(size);
745 int SSLClientSocketOpenSSL::Init() {
746 DCHECK(!ssl_);
747 DCHECK(!transport_bio_);
749 SSLContext* context = SSLContext::GetInstance();
750 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
752 ssl_ = SSL_new(context->ssl_ctx());
753 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
754 return ERR_UNEXPECTED;
756 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
757 return ERR_UNEXPECTED;
759 // Set an OpenSSL callback to monitor this SSL*'s connection.
760 SSL_set_info_callback(ssl_, &InfoCallback);
762 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
763 ssl_, GetSessionCacheKey());
765 send_buffer_ = new GrowableIOBuffer();
766 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
767 recv_buffer_ = new GrowableIOBuffer();
768 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
770 BIO* ssl_bio = NULL;
772 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
773 if (!BIO_new_bio_pair_external_buf(
774 &ssl_bio, send_buffer_->capacity(),
775 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
776 recv_buffer_->capacity(),
777 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
778 return ERR_UNEXPECTED;
779 DCHECK(ssl_bio);
780 DCHECK(transport_bio_);
782 // Install a callback on OpenSSL's end to plumb transport errors through.
783 BIO_set_callback(ssl_bio, BIOCallback);
784 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
786 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
788 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
789 // set everything we care about to an absolute value.
790 SslSetClearMask options;
791 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
792 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
793 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
794 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
795 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
796 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
797 bool tls1_1_enabled =
798 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
799 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
800 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
801 bool tls1_2_enabled =
802 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
803 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
804 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
806 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
808 // TODO(joth): Set this conditionally, see http://crbug.com/55410
809 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
811 SSL_set_options(ssl_, options.set_mask);
812 SSL_clear_options(ssl_, options.clear_mask);
814 // Same as above, this time for the SSL mode.
815 SslSetClearMask mode;
817 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
818 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
820 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START,
821 ssl_config_.false_start_enabled);
823 mode.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV, ssl_config_.version_fallback);
825 SSL_set_mode(ssl_, mode.set_mask);
826 SSL_clear_mode(ssl_, mode.clear_mask);
828 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
829 // textual name with SSL_set_cipher_list because there is no public API to
830 // directly remove a cipher by ID.
831 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
832 DCHECK(ciphers);
833 // See SSLConfig::disabled_cipher_suites for description of the suites
834 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
835 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
836 // as the handshake hash.
837 std::string command(
838 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
839 // Walk through all the installed ciphers, seeing if any need to be
840 // appended to the cipher removal |command|.
841 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
842 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
843 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
844 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
845 // implementation uses "effective" bits here but OpenSSL does not provide
846 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
847 // both of which are greater than 80 anyway.
848 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
849 if (!disable) {
850 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
851 ssl_config_.disabled_cipher_suites.end(), id) !=
852 ssl_config_.disabled_cipher_suites.end();
854 if (disable) {
855 const char* name = SSL_CIPHER_get_name(cipher);
856 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
857 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
858 command.append(":!");
859 command.append(name);
863 // Disable ECDSA cipher suites on platforms that do not support ECDSA
864 // signed certificates, as servers may use the presence of such
865 // ciphersuites as a hint to send an ECDSA certificate.
866 #if defined(OS_WIN)
867 if (base::win::GetVersion() < base::win::VERSION_VISTA)
868 command.append(":!ECDSA");
869 #endif
871 int rv = SSL_set_cipher_list(ssl_, command.c_str());
872 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
873 // This will almost certainly result in the socket failing to complete the
874 // handshake at which point the appropriate error is bubbled up to the client.
875 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
876 "returned " << rv;
878 // TLS channel ids.
879 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
880 SSL_enable_tls_channel_id(ssl_);
883 if (!ssl_config_.next_protos.empty()) {
884 // Get list of ciphers that are enabled.
885 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
886 DCHECK(enabled_ciphers);
887 std::vector<uint16> enabled_ciphers_vector;
888 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
889 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
890 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
891 enabled_ciphers_vector.push_back(id);
894 std::vector<uint8_t> wire_protos =
895 SerializeNextProtos(ssl_config_.next_protos,
896 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
897 IsTLSVersionAdequateForHTTP2(ssl_config_));
898 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
899 wire_protos.size());
902 if (ssl_config_.signed_cert_timestamps_enabled) {
903 SSL_enable_signed_cert_timestamps(ssl_);
904 SSL_enable_ocsp_stapling(ssl_);
907 if (IsOCSPStaplingSupported())
908 SSL_enable_ocsp_stapling(ssl_);
910 return OK;
913 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
914 // Since Run may result in Read being called, clear |user_read_callback_|
915 // up front.
916 if (rv > 0)
917 was_ever_used_ = true;
918 user_read_buf_ = NULL;
919 user_read_buf_len_ = 0;
920 if (rv <= 0) {
921 // Failure of a read attempt may indicate a failed false start
922 // connection.
923 OnHandshakeCompletion();
925 base::ResetAndReturn(&user_read_callback_).Run(rv);
928 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
929 // Since Run may result in Write being called, clear |user_write_callback_|
930 // up front.
931 if (rv > 0)
932 was_ever_used_ = true;
933 user_write_buf_ = NULL;
934 user_write_buf_len_ = 0;
935 if (rv < 0) {
936 // Failure of a write attempt may indicate a failed false start
937 // connection.
938 OnHandshakeCompletion();
940 base::ResetAndReturn(&user_write_callback_).Run(rv);
943 void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
944 if (!handshake_completion_callback_.is_null())
945 base::ResetAndReturn(&handshake_completion_callback_).Run();
948 bool SSLClientSocketOpenSSL::DoTransportIO() {
949 bool network_moved = false;
950 int rv;
951 // Read and write as much data as possible. The loop is necessary because
952 // Write() may return synchronously.
953 do {
954 rv = BufferSend();
955 if (rv != ERR_IO_PENDING && rv != 0)
956 network_moved = true;
957 } while (rv > 0);
958 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
959 network_moved = true;
960 return network_moved;
963 // TODO(vadimt): Remove including "base/threading/thread_local.h" and
964 // g_first_run_completed once crbug.com/424386 is fixed.
965 base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
966 LAZY_INSTANCE_INITIALIZER;
968 int SSLClientSocketOpenSSL::DoHandshake() {
969 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
970 int net_error = OK;
972 int rv;
974 // TODO(vadimt): Leave only 1 call to SSL_do_handshake once crbug.com/424386
975 // is fixed.
976 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
977 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
978 tracked_objects::ScopedTracker tracking_profile1(
979 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 DoHandshake_WithCert"));
981 rv = SSL_do_handshake(ssl_);
982 } else {
983 if (g_first_run_completed.Get().Get()) {
984 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
985 // fixed.
986 tracked_objects::ScopedTracker tracking_profile1(
987 FROM_HERE_WITH_EXPLICIT_FUNCTION(
988 "424386 DoHandshake_WithoutCert Not First"));
990 rv = SSL_do_handshake(ssl_);
991 } else {
992 g_first_run_completed.Get().Set(true);
994 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
995 // fixed.
996 tracked_objects::ScopedTracker tracking_profile1(
997 FROM_HERE_WITH_EXPLICIT_FUNCTION(
998 "424386 DoHandshake_WithoutCert First"));
1000 rv = SSL_do_handshake(ssl_);
1004 if (client_auth_cert_needed_) {
1005 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1006 tracked_objects::ScopedTracker tracking_profile2(
1007 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1008 "424386 SSLClientSocketOpenSSL::DoHandshake2"));
1010 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1011 // If the handshake already succeeded (because the server requests but
1012 // doesn't require a client cert), we need to invalidate the SSL session
1013 // so that we won't try to resume the non-client-authenticated session in
1014 // the next handshake. This will cause the server to ask for a client
1015 // cert again.
1016 if (rv == 1) {
1017 // Remove from session cache but don't clear this connection.
1018 SSL_SESSION* session = SSL_get_session(ssl_);
1019 if (session) {
1020 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
1021 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
1024 } else if (rv == 1) {
1025 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1026 tracked_objects::ScopedTracker tracking_profile3(
1027 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1028 "424386 SSLClientSocketOpenSSL::DoHandshake3"));
1030 if (trying_cached_session_ && logging::DEBUG_MODE) {
1031 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
1032 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
1035 if (ssl_config_.version_fallback &&
1036 ssl_config_.version_max < ssl_config_.version_fallback_min) {
1037 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
1040 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1041 if (npn_status_ == kNextProtoUnsupported) {
1042 const uint8_t* alpn_proto = NULL;
1043 unsigned alpn_len = 0;
1044 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
1045 if (alpn_len > 0) {
1046 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
1047 npn_status_ = kNextProtoNegotiated;
1048 set_negotiation_extension(kExtensionALPN);
1052 RecordChannelIDSupport(channel_id_service_,
1053 channel_id_xtn_negotiated_,
1054 ssl_config_.channel_id_enabled,
1055 crypto::ECPrivateKey::IsSupported());
1057 // Only record OCSP histograms if OCSP was requested.
1058 if (ssl_config_.signed_cert_timestamps_enabled ||
1059 IsOCSPStaplingSupported()) {
1060 const uint8_t* ocsp_response;
1061 size_t ocsp_response_len;
1062 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
1064 set_stapled_ocsp_response_received(ocsp_response_len != 0);
1065 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
1068 const uint8_t* sct_list;
1069 size_t sct_list_len;
1070 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
1071 set_signed_cert_timestamps_received(sct_list_len != 0);
1073 // Verify the certificate.
1074 UpdateServerCert();
1075 GotoState(STATE_VERIFY_CERT);
1076 } else {
1077 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1078 tracked_objects::ScopedTracker tracking_profile4(
1079 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1080 "424386 SSLClientSocketOpenSSL::DoHandshake4"));
1082 int ssl_error = SSL_get_error(ssl_, rv);
1084 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
1085 // The server supports channel ID. Stop to look one up before returning to
1086 // the handshake.
1087 channel_id_xtn_negotiated_ = true;
1088 GotoState(STATE_CHANNEL_ID_LOOKUP);
1089 return OK;
1092 OpenSSLErrorInfo error_info;
1093 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
1095 // If not done, stay in this state
1096 if (net_error == ERR_IO_PENDING) {
1097 GotoState(STATE_HANDSHAKE);
1098 } else {
1099 LOG(ERROR) << "handshake failed; returned " << rv
1100 << ", SSL error code " << ssl_error
1101 << ", net_error " << net_error;
1102 net_log_.AddEvent(
1103 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1104 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1107 return net_error;
1110 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1111 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED);
1112 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
1113 return channel_id_service_->GetOrCreateChannelID(
1114 host_and_port_.host(),
1115 &channel_id_private_key_,
1116 &channel_id_cert_,
1117 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1118 base::Unretained(this)),
1119 &channel_id_request_handle_);
1122 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1123 if (result < 0)
1124 return result;
1126 DCHECK_LT(0u, channel_id_private_key_.size());
1127 // Decode key.
1128 std::vector<uint8> encrypted_private_key_info;
1129 std::vector<uint8> subject_public_key_info;
1130 encrypted_private_key_info.assign(
1131 channel_id_private_key_.data(),
1132 channel_id_private_key_.data() + channel_id_private_key_.size());
1133 subject_public_key_info.assign(
1134 channel_id_cert_.data(),
1135 channel_id_cert_.data() + channel_id_cert_.size());
1136 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1137 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1138 ChannelIDService::kEPKIPassword,
1139 encrypted_private_key_info,
1140 subject_public_key_info));
1141 if (!ec_private_key) {
1142 LOG(ERROR) << "Failed to import Channel ID.";
1143 return ERR_CHANNEL_ID_IMPORT_FAILED;
1146 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1147 // type.
1148 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1149 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1150 if (!rv) {
1151 LOG(ERROR) << "Failed to set Channel ID.";
1152 int err = SSL_get_error(ssl_, rv);
1153 return MapOpenSSLError(err, err_tracer);
1156 // Return to the handshake.
1157 set_channel_id_sent(true);
1158 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
1159 GotoState(STATE_HANDSHAKE);
1160 return OK;
1163 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
1164 DCHECK(!server_cert_chain_->empty());
1165 DCHECK(start_cert_verification_time_.is_null());
1167 GotoState(STATE_VERIFY_CERT_COMPLETE);
1169 // If the certificate is bad and has been previously accepted, use
1170 // the previous status and bypass the error.
1171 base::StringPiece der_cert;
1172 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1173 NOTREACHED();
1174 return ERR_CERT_INVALID;
1176 CertStatus cert_status;
1177 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
1178 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1179 server_cert_verify_result_.Reset();
1180 server_cert_verify_result_.cert_status = cert_status;
1181 server_cert_verify_result_.verified_cert = server_cert_;
1182 return OK;
1185 // When running in a sandbox, it may not be possible to create an
1186 // X509Certificate*, as that may depend on OS functionality blocked
1187 // in the sandbox.
1188 if (!server_cert_.get()) {
1189 server_cert_verify_result_.Reset();
1190 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1191 return ERR_CERT_INVALID;
1194 start_cert_verification_time_ = base::TimeTicks::Now();
1196 int flags = 0;
1197 if (ssl_config_.rev_checking_enabled)
1198 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1199 if (ssl_config_.verify_ev_cert)
1200 flags |= CertVerifier::VERIFY_EV_CERT;
1201 if (ssl_config_.cert_io_enabled)
1202 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1203 if (ssl_config_.rev_checking_required_local_anchors)
1204 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1205 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1206 return verifier_->Verify(
1207 server_cert_.get(),
1208 host_and_port_.host(),
1209 flags,
1210 // TODO(davidben): Route the CRLSet through SSLConfig so
1211 // SSLClientSocket doesn't depend on SSLConfigService.
1212 SSLConfigService::GetCRLSet().get(),
1213 &server_cert_verify_result_,
1214 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1215 base::Unretained(this)),
1216 net_log_);
1219 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1220 verifier_.reset();
1222 if (!start_cert_verification_time_.is_null()) {
1223 base::TimeDelta verify_time =
1224 base::TimeTicks::Now() - start_cert_verification_time_;
1225 if (result == OK) {
1226 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1227 } else {
1228 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1232 if (result == OK) {
1233 if (SSL_session_reused(ssl_)) {
1234 // Record whether or not the server tried to resume a session for a
1235 // different version. See https://crbug.com/441456.
1236 UMA_HISTOGRAM_BOOLEAN(
1237 "Net.SSLSessionVersionMatch",
1238 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1242 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1243 if (transport_security_state_ &&
1244 (result == OK ||
1245 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1246 !transport_security_state_->CheckPublicKeyPins(
1247 host_and_port_.host(),
1248 server_cert_verify_result_.is_issued_by_known_root,
1249 server_cert_verify_result_.public_key_hashes,
1250 &pinning_failure_log_)) {
1251 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1254 if (result == OK) {
1255 // Only check Certificate Transparency if there were no other errors with
1256 // the connection.
1257 VerifyCT();
1259 // TODO(joth): Work out if we need to remember the intermediate CA certs
1260 // when the server sends them to us, and do so here.
1261 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
1262 marked_session_as_good_ = true;
1263 CheckIfHandshakeFinished();
1264 } else {
1265 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1266 << " (" << result << ")";
1269 completed_connect_ = true;
1271 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1272 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1273 return result;
1276 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1277 if (rv < OK)
1278 OnHandshakeCompletion();
1279 if (!user_connect_callback_.is_null()) {
1280 CompletionCallback c = user_connect_callback_;
1281 user_connect_callback_.Reset();
1282 c.Run(rv > OK ? OK : rv);
1286 void SSLClientSocketOpenSSL::UpdateServerCert() {
1287 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1288 tracked_objects::ScopedTracker tracking_profile(
1289 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1290 "424386 SSLClientSocketOpenSSL::UpdateServerCert"));
1292 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
1294 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1295 tracked_objects::ScopedTracker tracking_profile1(
1296 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1297 "424386 SSLClientSocketOpenSSL::UpdateServerCert1"));
1298 server_cert_ = server_cert_chain_->AsOSChain();
1300 if (server_cert_.get()) {
1301 net_log_.AddEvent(
1302 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1303 base::Bind(&NetLogX509CertificateCallback,
1304 base::Unretained(server_cert_.get())));
1306 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1307 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1308 if (IsOCSPStaplingSupported()) {
1309 #if defined(OS_WIN)
1310 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
1311 // fixed.
1312 tracked_objects::ScopedTracker tracking_profile2(
1313 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1314 "424386 SSLClientSocketOpenSSL::UpdateServerCert2"));
1316 const uint8_t* ocsp_response_raw;
1317 size_t ocsp_response_len;
1318 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1320 CRYPT_DATA_BLOB ocsp_response_blob;
1321 ocsp_response_blob.cbData = ocsp_response_len;
1322 ocsp_response_blob.pbData = const_cast<BYTE*>(ocsp_response_raw);
1323 BOOL ok = CertSetCertificateContextProperty(
1324 server_cert_->os_cert_handle(),
1325 CERT_OCSP_RESPONSE_PROP_ID,
1326 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1327 &ocsp_response_blob);
1328 if (!ok) {
1329 VLOG(1) << "Failed to set OCSP response property: "
1330 << GetLastError();
1332 #else
1333 NOTREACHED();
1334 #endif
1339 void SSLClientSocketOpenSSL::VerifyCT() {
1340 if (!cert_transparency_verifier_)
1341 return;
1343 const uint8_t* ocsp_response_raw;
1344 size_t ocsp_response_len;
1345 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1346 std::string ocsp_response;
1347 if (ocsp_response_len > 0) {
1348 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1349 ocsp_response_len);
1352 const uint8_t* sct_list_raw;
1353 size_t sct_list_len;
1354 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1355 std::string sct_list;
1356 if (sct_list_len > 0)
1357 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1359 // Note that this is a completely synchronous operation: The CT Log Verifier
1360 // gets all the data it needs for SCT verification and does not do any
1361 // external communication.
1362 cert_transparency_verifier_->Verify(
1363 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1364 &ct_verify_result_, net_log_);
1366 if (!policy_enforcer_) {
1367 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1368 } else {
1369 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1370 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1371 SSLConfigService::GetEVCertsWhitelist();
1372 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1373 server_cert_verify_result_.verified_cert.get(),
1374 ev_whitelist.get(), ct_verify_result_, net_log_)) {
1375 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1376 VLOG(1) << "EV certificate for "
1377 << server_cert_verify_result_.verified_cert->subject()
1378 .GetDisplayName()
1379 << " does not conform to CT policy, removing EV status.";
1380 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1386 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1387 int rv = DoHandshakeLoop(result);
1388 if (rv != ERR_IO_PENDING) {
1389 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1390 DoConnectCallback(rv);
1394 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1395 if (next_handshake_state_ == STATE_HANDSHAKE) {
1396 // In handshake phase.
1397 OnHandshakeIOComplete(result);
1398 return;
1401 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1402 // handshake is in progress.
1403 int rv_read = ERR_IO_PENDING;
1404 int rv_write = ERR_IO_PENDING;
1405 bool network_moved;
1406 do {
1407 if (user_read_buf_.get())
1408 rv_read = DoPayloadRead();
1409 if (user_write_buf_.get())
1410 rv_write = DoPayloadWrite();
1411 network_moved = DoTransportIO();
1412 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1413 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1415 // Performing the Read callback may cause |this| to be deleted. If this
1416 // happens, the Write callback should not be invoked. Guard against this by
1417 // holding a WeakPtr to |this| and ensuring it's still valid.
1418 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1419 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1420 DoReadCallback(rv_read);
1422 if (!guard.get())
1423 return;
1425 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1426 DoWriteCallback(rv_write);
1429 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1430 if (next_handshake_state_ == STATE_HANDSHAKE) {
1431 // In handshake phase.
1432 OnHandshakeIOComplete(result);
1433 return;
1436 // Network layer received some data, check if client requested to read
1437 // decrypted data.
1438 if (!user_read_buf_.get())
1439 return;
1441 int rv = DoReadLoop();
1442 if (rv != ERR_IO_PENDING)
1443 DoReadCallback(rv);
1446 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1447 int rv = last_io_result;
1448 do {
1449 // Default to STATE_NONE for next state.
1450 // (This is a quirk carried over from the windows
1451 // implementation. It makes reading the logs a bit harder.)
1452 // State handlers can and often do call GotoState just
1453 // to stay in the current state.
1454 State state = next_handshake_state_;
1455 GotoState(STATE_NONE);
1456 switch (state) {
1457 case STATE_HANDSHAKE:
1458 rv = DoHandshake();
1459 break;
1460 case STATE_CHANNEL_ID_LOOKUP:
1461 DCHECK_EQ(OK, rv);
1462 rv = DoChannelIDLookup();
1463 break;
1464 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1465 rv = DoChannelIDLookupComplete(rv);
1466 break;
1467 case STATE_VERIFY_CERT:
1468 DCHECK_EQ(OK, rv);
1469 rv = DoVerifyCert(rv);
1470 break;
1471 case STATE_VERIFY_CERT_COMPLETE:
1472 rv = DoVerifyCertComplete(rv);
1473 break;
1474 case STATE_NONE:
1475 default:
1476 rv = ERR_UNEXPECTED;
1477 NOTREACHED() << "unexpected state" << state;
1478 break;
1481 bool network_moved = DoTransportIO();
1482 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1483 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1484 // special case we keep looping even if rv is ERR_IO_PENDING because
1485 // the transport IO may allow DoHandshake to make progress.
1486 rv = OK; // This causes us to stay in the loop.
1488 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1490 return rv;
1493 int SSLClientSocketOpenSSL::DoReadLoop() {
1494 bool network_moved;
1495 int rv;
1496 do {
1497 rv = DoPayloadRead();
1498 network_moved = DoTransportIO();
1499 } while (rv == ERR_IO_PENDING && network_moved);
1501 return rv;
1504 int SSLClientSocketOpenSSL::DoWriteLoop() {
1505 bool network_moved;
1506 int rv;
1507 do {
1508 rv = DoPayloadWrite();
1509 network_moved = DoTransportIO();
1510 } while (rv == ERR_IO_PENDING && network_moved);
1512 return rv;
1515 int SSLClientSocketOpenSSL::DoPayloadRead() {
1516 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1518 int rv;
1519 if (pending_read_error_ != kNoPendingReadResult) {
1520 rv = pending_read_error_;
1521 pending_read_error_ = kNoPendingReadResult;
1522 if (rv == 0) {
1523 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1524 rv, user_read_buf_->data());
1525 } else {
1526 net_log_.AddEvent(
1527 NetLog::TYPE_SSL_READ_ERROR,
1528 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1529 pending_read_error_info_));
1531 pending_read_ssl_error_ = SSL_ERROR_NONE;
1532 pending_read_error_info_ = OpenSSLErrorInfo();
1533 return rv;
1536 int total_bytes_read = 0;
1537 do {
1538 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1539 user_read_buf_len_ - total_bytes_read);
1540 if (rv > 0)
1541 total_bytes_read += rv;
1542 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1544 if (total_bytes_read == user_read_buf_len_) {
1545 rv = total_bytes_read;
1546 } else {
1547 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1548 // immediately, while the OpenSSL errors are still available in
1549 // thread-local storage. However, the handled/remapped error code should
1550 // only be returned if no application data was already read; if it was, the
1551 // error code should be deferred until the next call of DoPayloadRead.
1553 // If no data was read, |*next_result| will point to the return value of
1554 // this function. If at least some data was read, |*next_result| will point
1555 // to |pending_read_error_|, to be returned in a future call to
1556 // DoPayloadRead() (e.g.: after the current data is handled).
1557 int *next_result = &rv;
1558 if (total_bytes_read > 0) {
1559 pending_read_error_ = rv;
1560 rv = total_bytes_read;
1561 next_result = &pending_read_error_;
1564 if (client_auth_cert_needed_) {
1565 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1566 } else if (*next_result < 0) {
1567 pending_read_ssl_error_ = SSL_get_error(ssl_, *next_result);
1568 *next_result = MapOpenSSLErrorWithDetails(pending_read_ssl_error_,
1569 err_tracer,
1570 &pending_read_error_info_);
1572 // Many servers do not reliably send a close_notify alert when shutting
1573 // down a connection, and instead terminate the TCP connection. This is
1574 // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1575 // shutdown to a graceful EOF, instead of treating it as an error as it
1576 // should be.
1577 if (*next_result == ERR_CONNECTION_CLOSED)
1578 *next_result = 0;
1580 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1581 // If at least some data was read from SSL_read(), do not treat
1582 // insufficient data as an error to return in the next call to
1583 // DoPayloadRead() - instead, let the call fall through to check
1584 // SSL_read() again. This is because DoTransportIO() may complete
1585 // in between the next call to DoPayloadRead(), and thus it is
1586 // important to check SSL_read() on subsequent invocations to see
1587 // if a complete record may now be read.
1588 *next_result = kNoPendingReadResult;
1593 if (rv >= 0) {
1594 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1595 user_read_buf_->data());
1596 } else if (rv != ERR_IO_PENDING) {
1597 net_log_.AddEvent(
1598 NetLog::TYPE_SSL_READ_ERROR,
1599 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1600 pending_read_error_info_));
1601 pending_read_ssl_error_ = SSL_ERROR_NONE;
1602 pending_read_error_info_ = OpenSSLErrorInfo();
1604 return rv;
1607 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1608 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1609 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1610 if (rv >= 0) {
1611 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1612 user_write_buf_->data());
1613 return rv;
1616 int ssl_error = SSL_get_error(ssl_, rv);
1617 OpenSSLErrorInfo error_info;
1618 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1619 &error_info);
1621 if (net_error != ERR_IO_PENDING) {
1622 net_log_.AddEvent(
1623 NetLog::TYPE_SSL_WRITE_ERROR,
1624 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1626 return net_error;
1629 int SSLClientSocketOpenSSL::BufferSend(void) {
1630 if (transport_send_busy_)
1631 return ERR_IO_PENDING;
1633 size_t buffer_read_offset;
1634 uint8_t* read_buf;
1635 size_t max_read;
1636 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1637 &buffer_read_offset, &max_read);
1638 DCHECK_EQ(status, 1); // Should never fail.
1639 if (!max_read)
1640 return 0; // Nothing pending in the OpenSSL write BIO.
1641 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1642 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1643 send_buffer_->set_offset(buffer_read_offset);
1645 int rv = transport_->socket()->Write(
1646 send_buffer_.get(), max_read,
1647 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1648 base::Unretained(this)));
1649 if (rv == ERR_IO_PENDING) {
1650 transport_send_busy_ = true;
1651 } else {
1652 TransportWriteComplete(rv);
1654 return rv;
1657 int SSLClientSocketOpenSSL::BufferRecv(void) {
1658 if (transport_recv_busy_)
1659 return ERR_IO_PENDING;
1661 // Determine how much was requested from |transport_bio_| that was not
1662 // actually available.
1663 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1664 if (requested == 0) {
1665 // This is not a perfect match of error codes, as no operation is
1666 // actually pending. However, returning 0 would be interpreted as
1667 // a possible sign of EOF, which is also an inappropriate match.
1668 return ERR_IO_PENDING;
1671 // Known Issue: While only reading |requested| data is the more correct
1672 // implementation, it has the downside of resulting in frequent reads:
1673 // One read for the SSL record header (~5 bytes) and one read for the SSL
1674 // record body. Rather than issuing these reads to the underlying socket
1675 // (and constantly allocating new IOBuffers), a single Read() request to
1676 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1677 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1678 // traffic, this over-subscribed Read()ing will not cause issues.
1680 size_t buffer_write_offset;
1681 uint8_t* write_buf;
1682 size_t max_write;
1683 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1684 &buffer_write_offset, &max_write);
1685 DCHECK_EQ(status, 1); // Should never fail.
1686 if (!max_write)
1687 return ERR_IO_PENDING;
1689 CHECK_EQ(write_buf,
1690 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1691 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1693 recv_buffer_->set_offset(buffer_write_offset);
1694 int rv = transport_->socket()->Read(
1695 recv_buffer_.get(),
1696 max_write,
1697 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1698 base::Unretained(this)));
1699 if (rv == ERR_IO_PENDING) {
1700 transport_recv_busy_ = true;
1701 } else {
1702 rv = TransportReadComplete(rv);
1704 return rv;
1707 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1708 TransportWriteComplete(result);
1709 OnSendComplete(result);
1712 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1713 result = TransportReadComplete(result);
1714 OnRecvComplete(result);
1717 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1718 DCHECK(ERR_IO_PENDING != result);
1719 int bytes_written = 0;
1720 if (result < 0) {
1721 // Record the error. Save it to be reported in a future read or write on
1722 // transport_bio_'s peer.
1723 transport_write_error_ = result;
1724 } else {
1725 bytes_written = result;
1727 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1728 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1729 DCHECK_EQ(1, ret);
1730 transport_send_busy_ = false;
1733 int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1734 DCHECK(ERR_IO_PENDING != result);
1735 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1736 // does not report success.
1737 if (result == 0)
1738 result = ERR_CONNECTION_CLOSED;
1739 int bytes_read = 0;
1740 if (result < 0) {
1741 DVLOG(1) << "TransportReadComplete result " << result;
1742 // Received an error. Save it to be reported in a future read on
1743 // transport_bio_'s peer.
1744 transport_read_error_ = result;
1745 } else {
1746 bytes_read = result;
1748 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1749 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1750 DCHECK_EQ(1, ret);
1751 transport_recv_busy_ = false;
1752 return result;
1755 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
1756 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1757 tracked_objects::ScopedTracker tracking_profile(
1758 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1759 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1761 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1762 DCHECK(ssl == ssl_);
1764 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1766 // Clear any currently configured certificates.
1767 SSL_certs_clear(ssl_);
1769 #if defined(OS_IOS)
1770 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1771 LOG(WARNING) << "Client auth is not supported";
1772 #else // !defined(OS_IOS)
1773 if (!ssl_config_.send_client_cert) {
1774 // First pass: we know that a client certificate is needed, but we do not
1775 // have one at hand.
1776 client_auth_cert_needed_ = true;
1777 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1778 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
1779 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1780 unsigned char* str = NULL;
1781 int length = i2d_X509_NAME(ca_name, &str);
1782 cert_authorities_.push_back(std::string(
1783 reinterpret_cast<const char*>(str),
1784 static_cast<size_t>(length)));
1785 OPENSSL_free(str);
1788 const unsigned char* client_cert_types;
1789 size_t num_client_cert_types =
1790 SSL_get0_certificate_types(ssl, &client_cert_types);
1791 for (size_t i = 0; i < num_client_cert_types; i++) {
1792 cert_key_types_.push_back(
1793 static_cast<SSLClientCertType>(client_cert_types[i]));
1796 return -1; // Suspends handshake.
1799 // Second pass: a client certificate should have been selected.
1800 if (ssl_config_.client_cert.get()) {
1801 ScopedX509 leaf_x509 =
1802 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1803 if (!leaf_x509) {
1804 LOG(WARNING) << "Failed to import certificate";
1805 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1806 return -1;
1809 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1810 ssl_config_.client_cert->GetIntermediateCertificates());
1811 if (!chain) {
1812 LOG(WARNING) << "Failed to import intermediate certificates";
1813 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1814 return -1;
1817 // TODO(davidben): With Linux client auth support, this should be
1818 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1819 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1820 // net/ client auth API lacking a private key handle.
1821 #if defined(USE_OPENSSL_CERTS)
1822 crypto::ScopedEVP_PKEY privkey =
1823 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1824 ssl_config_.client_cert.get());
1825 #else // !defined(USE_OPENSSL_CERTS)
1826 crypto::ScopedEVP_PKEY privkey =
1827 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1828 #endif // defined(USE_OPENSSL_CERTS)
1829 if (!privkey) {
1830 // Could not find the private key. Fail the handshake and surface an
1831 // appropriate error to the caller.
1832 LOG(WARNING) << "Client cert found without private key";
1833 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1834 return -1;
1837 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1838 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1839 !SSL_set1_chain(ssl_, chain.get())) {
1840 LOG(WARNING) << "Failed to set client certificate";
1841 return -1;
1844 int cert_count = 1 + sk_X509_num(chain.get());
1845 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1846 NetLog::IntegerCallback("cert_count", cert_count));
1847 return 1;
1849 #endif // defined(OS_IOS)
1851 // Send no client certificate.
1852 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1853 NetLog::IntegerCallback("cert_count", 0));
1854 return 1;
1857 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1858 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1859 tracked_objects::ScopedTracker tracking_profile(
1860 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1861 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1863 if (!completed_connect_) {
1864 // If the first handshake hasn't completed then we accept any certificates
1865 // because we verify after the handshake.
1866 return 1;
1869 // Disallow the server certificate to change in a renegotiation.
1870 if (server_cert_chain_->empty()) {
1871 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1872 return 0;
1874 base::StringPiece old_der, new_der;
1875 if (store_ctx->cert == NULL ||
1876 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1877 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1878 LOG(ERROR) << "Failed to encode certificates";
1879 return 0;
1881 if (old_der != new_der) {
1882 LOG(ERROR) << "Server certificate changed between handshakes";
1883 return 0;
1886 return 1;
1889 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1890 // server supports NPN, selects a protocol from the list that the server
1891 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1892 // callback can assume that |in| is syntactically valid.
1893 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1894 unsigned char* outlen,
1895 const unsigned char* in,
1896 unsigned int inlen) {
1897 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1898 tracked_objects::ScopedTracker tracking_profile(
1899 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1900 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1902 if (ssl_config_.next_protos.empty()) {
1903 *out = reinterpret_cast<uint8*>(
1904 const_cast<char*>(kDefaultSupportedNPNProtocol));
1905 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1906 npn_status_ = kNextProtoUnsupported;
1907 return SSL_TLSEXT_ERR_OK;
1910 // Assume there's no overlap between our protocols and the server's list.
1911 npn_status_ = kNextProtoNoOverlap;
1913 // For each protocol in server preference order, see if we support it.
1914 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1915 for (NextProto next_proto : ssl_config_.next_protos) {
1916 const std::string proto = NextProtoToString(next_proto);
1917 if (in[i] == proto.size() &&
1918 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
1919 // We found a match.
1920 *out = const_cast<unsigned char*>(in) + i + 1;
1921 *outlen = in[i];
1922 npn_status_ = kNextProtoNegotiated;
1923 break;
1926 if (npn_status_ == kNextProtoNegotiated)
1927 break;
1930 // If we didn't find a protocol, we select the first one from our list.
1931 if (npn_status_ == kNextProtoNoOverlap) {
1932 // NextProtoToString returns a pointer to a static string.
1933 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1934 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1935 *outlen = strlen(proto);
1938 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
1939 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
1940 set_negotiation_extension(kExtensionNPN);
1941 return SSL_TLSEXT_ERR_OK;
1944 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1945 BIO *bio,
1946 int cmd,
1947 const char *argp, int argi, long argl,
1948 long retvalue) {
1949 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1950 // If there is no more data in the buffer, report any pending errors that
1951 // were observed. Note that both the readbuf and the writebuf are checked
1952 // for errors, since the application may have encountered a socket error
1953 // while writing that would otherwise not be reported until the application
1954 // attempted to write again - which it may never do. See
1955 // https://crbug.com/249848.
1956 if (transport_read_error_ != OK) {
1957 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1958 return -1;
1960 if (transport_write_error_ != OK) {
1961 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1962 return -1;
1964 } else if (cmd == BIO_CB_WRITE) {
1965 // Because of the write buffer, this reports a failure from the previous
1966 // write payload. If the current payload fails to write, the error will be
1967 // reported in a future write or read to |bio|.
1968 if (transport_write_error_ != OK) {
1969 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1970 return -1;
1973 return retvalue;
1976 // static
1977 long SSLClientSocketOpenSSL::BIOCallback(
1978 BIO *bio,
1979 int cmd,
1980 const char *argp, int argi, long argl,
1981 long retvalue) {
1982 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1983 tracked_objects::ScopedTracker tracking_profile(
1984 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1985 "424386 SSLClientSocketOpenSSL::BIOCallback"));
1987 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1988 BIO_get_callback_arg(bio));
1989 CHECK(socket);
1990 return socket->MaybeReplayTransportError(
1991 bio, cmd, argp, argi, argl, retvalue);
1994 // static
1995 void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1996 int type,
1997 int /*val*/) {
1998 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1999 tracked_objects::ScopedTracker tracking_profile(
2000 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2001 "424386 SSLClientSocketOpenSSL::InfoCallback"));
2003 if (type == SSL_CB_HANDSHAKE_DONE) {
2004 SSLClientSocketOpenSSL* ssl_socket =
2005 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2006 ssl_socket->handshake_succeeded_ = true;
2007 ssl_socket->CheckIfHandshakeFinished();
2011 // Determines if both the handshake and certificate verification have completed
2012 // successfully, and calls the handshake completion callback if that is the
2013 // case.
2015 // CheckIfHandshakeFinished is called twice per connection: once after
2016 // MarkSSLSessionAsGood, when the certificate has been verified, and
2017 // once via an OpenSSL callback when the handshake has completed. On the
2018 // second call, when the certificate has been verified and the handshake
2019 // has completed, the connection's handshake completion callback is run.
2020 void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
2021 if (handshake_succeeded_ && marked_session_as_good_)
2022 OnHandshakeCompletion();
2025 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
2026 for (ct::SCTList::const_iterator iter =
2027 ct_verify_result_.verified_scts.begin();
2028 iter != ct_verify_result_.verified_scts.end(); ++iter) {
2029 ssl_info->signed_certificate_timestamps.push_back(
2030 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
2032 for (ct::SCTList::const_iterator iter =
2033 ct_verify_result_.invalid_scts.begin();
2034 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
2035 ssl_info->signed_certificate_timestamps.push_back(
2036 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
2038 for (ct::SCTList::const_iterator iter =
2039 ct_verify_result_.unknown_logs_scts.begin();
2040 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
2041 ssl_info->signed_certificate_timestamps.push_back(
2042 SignedCertificateTimestampAndStatus(*iter,
2043 ct::SCT_STATUS_LOG_UNKNOWN));
2047 scoped_refptr<X509Certificate>
2048 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
2049 return server_cert_;
2052 } // namespace net