Add UMA reporting to CdmPromise.
[chromium-blink-merge.git] / net / socket / ssl_client_socket_openssl.cc
blob89cb40592952b387939d39c8ea21938f96c2bd2f
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/err.h>
12 #include <openssl/ssl.h>
14 #include "base/bind.h"
15 #include "base/callback_helpers.h"
16 #include "base/memory/singleton.h"
17 #include "base/metrics/histogram.h"
18 #include "base/synchronization/lock.h"
19 #include "crypto/ec_private_key.h"
20 #include "crypto/openssl_util.h"
21 #include "crypto/scoped_openssl_types.h"
22 #include "net/base/net_errors.h"
23 #include "net/cert/cert_verifier.h"
24 #include "net/cert/single_request_cert_verifier.h"
25 #include "net/cert/x509_certificate_net_log_param.h"
26 #include "net/http/transport_security_state.h"
27 #include "net/socket/ssl_error_params.h"
28 #include "net/socket/ssl_session_cache_openssl.h"
29 #include "net/ssl/openssl_ssl_util.h"
30 #include "net/ssl/ssl_cert_request_info.h"
31 #include "net/ssl/ssl_connection_status_flags.h"
32 #include "net/ssl/ssl_info.h"
34 #if defined(USE_OPENSSL_CERTS)
35 #include "net/ssl/openssl_client_key_store.h"
36 #else
37 #include "net/ssl/openssl_platform_key.h"
38 #endif
40 namespace net {
42 namespace {
44 // Enable this to see logging for state machine state transitions.
45 #if 0
46 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
47 " jump to state " << s; \
48 next_handshake_state_ = s; } while (0)
49 #else
50 #define GotoState(s) next_handshake_state_ = s
51 #endif
53 // This constant can be any non-negative/non-zero value (eg: it does not
54 // overlap with any value of the net::Error range, including net::OK).
55 const int kNoPendingReadResult = 1;
57 // If a client doesn't have a list of protocols that it supports, but
58 // the server supports NPN, choosing "http/1.1" is the best answer.
59 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
61 typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
63 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
64 // This method doesn't seem to have made it into the OpenSSL headers.
65 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
66 #endif
68 // Used for encoding the |connection_status| field of an SSLInfo object.
69 int EncodeSSLConnectionStatus(int cipher_suite,
70 int compression,
71 int version) {
72 return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
73 SSL_CONNECTION_CIPHERSUITE_SHIFT) |
74 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
75 SSL_CONNECTION_COMPRESSION_SHIFT) |
76 ((version & SSL_CONNECTION_VERSION_MASK) <<
77 SSL_CONNECTION_VERSION_SHIFT);
80 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
81 // this SSL connection.
82 int GetNetSSLVersion(SSL* ssl) {
83 switch (SSL_version(ssl)) {
84 case SSL2_VERSION:
85 return SSL_CONNECTION_VERSION_SSL2;
86 case SSL3_VERSION:
87 return SSL_CONNECTION_VERSION_SSL3;
88 case TLS1_VERSION:
89 return SSL_CONNECTION_VERSION_TLS1;
90 case 0x0302:
91 return SSL_CONNECTION_VERSION_TLS1_1;
92 case 0x0303:
93 return SSL_CONNECTION_VERSION_TLS1_2;
94 default:
95 return SSL_CONNECTION_VERSION_UNKNOWN;
99 void FreeX509Stack(STACK_OF(X509) * ptr) {
100 sk_X509_pop_free(ptr, X509_free);
103 ScopedX509 OSCertHandleToOpenSSL(
104 X509Certificate::OSCertHandle os_handle) {
105 #if defined(USE_OPENSSL_CERTS)
106 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
107 #else // !defined(USE_OPENSSL_CERTS)
108 std::string der_encoded;
109 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
110 return ScopedX509();
111 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
112 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
113 #endif // defined(USE_OPENSSL_CERTS)
116 } // namespace
118 class SSLClientSocketOpenSSL::SSLContext {
119 public:
120 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
121 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
122 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
124 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
125 DCHECK(ssl);
126 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
127 SSL_get_ex_data(ssl, ssl_socket_data_index_));
128 DCHECK(socket);
129 return socket;
132 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
133 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
136 private:
137 friend struct DefaultSingletonTraits<SSLContext>;
139 SSLContext() {
140 crypto::EnsureOpenSSLInit();
141 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
142 DCHECK_NE(ssl_socket_data_index_, -1);
143 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
144 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
145 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
146 SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
147 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
148 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
149 // It would be better if the callback were not a global setting,
150 // but that is an OpenSSL issue.
151 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
152 NULL);
153 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
156 static std::string GetSessionCacheKey(const SSL* ssl) {
157 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
158 DCHECK(socket);
159 return socket->GetSessionCacheKey();
162 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
164 static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
165 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
166 CHECK(socket);
167 return socket->ClientCertRequestCallback(ssl, x509, pkey);
170 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
171 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
172 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
173 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
174 CHECK(socket);
176 return socket->CertVerifyCallback(store_ctx);
179 static int SelectNextProtoCallback(SSL* ssl,
180 unsigned char** out, unsigned char* outlen,
181 const unsigned char* in,
182 unsigned int inlen, void* arg) {
183 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
184 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
187 // This is the index used with SSL_get_ex_data to retrieve the owner
188 // SSLClientSocketOpenSSL object from an SSL instance.
189 int ssl_socket_data_index_;
191 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
192 // |session_cache_| must be destroyed before |ssl_ctx_|.
193 SSLSessionCacheOpenSSL session_cache_;
196 // PeerCertificateChain is a helper object which extracts the certificate
197 // chain, as given by the server, from an OpenSSL socket and performs the needed
198 // resource management. The first element of the chain is the leaf certificate
199 // and the other elements are in the order given by the server.
200 class SSLClientSocketOpenSSL::PeerCertificateChain {
201 public:
202 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
203 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
204 ~PeerCertificateChain() {}
205 PeerCertificateChain& operator=(const PeerCertificateChain& other);
207 // Resets the PeerCertificateChain to the set of certificates in|chain|,
208 // which may be NULL, indicating to empty the store certificates.
209 // Note: If an error occurs, such as being unable to parse the certificates,
210 // this will behave as if Reset(NULL) was called.
211 void Reset(STACK_OF(X509)* chain);
213 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
214 const scoped_refptr<X509Certificate>& AsOSChain() const { return os_chain_; }
216 size_t size() const {
217 if (!openssl_chain_.get())
218 return 0;
219 return sk_X509_num(openssl_chain_.get());
222 X509* operator[](size_t index) const {
223 DCHECK_LT(index, size());
224 return sk_X509_value(openssl_chain_.get(), index);
227 bool IsValid() { return os_chain_.get() && openssl_chain_.get(); }
229 private:
230 typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
231 ScopedX509Stack;
233 ScopedX509Stack openssl_chain_;
235 scoped_refptr<X509Certificate> os_chain_;
238 SSLClientSocketOpenSSL::PeerCertificateChain&
239 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
240 const PeerCertificateChain& other) {
241 if (this == &other)
242 return *this;
244 // os_chain_ is reference counted by scoped_refptr;
245 os_chain_ = other.os_chain_;
247 // Must increase the reference count manually for sk_X509_dup
248 openssl_chain_.reset(sk_X509_dup(other.openssl_chain_.get()));
249 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
250 X509* x = sk_X509_value(openssl_chain_.get(), i);
251 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
253 return *this;
256 #if defined(USE_OPENSSL_CERTS)
257 // When OSCertHandle is typedef'ed to X509, this implementation does a short cut
258 // to avoid converting back and forth between der and X509 struct.
259 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
260 STACK_OF(X509)* chain) {
261 openssl_chain_.reset(NULL);
262 os_chain_ = NULL;
264 if (!chain)
265 return;
267 X509Certificate::OSCertHandles intermediates;
268 for (size_t i = 1; i < sk_X509_num(chain); ++i)
269 intermediates.push_back(sk_X509_value(chain, i));
271 os_chain_ =
272 X509Certificate::CreateFromHandle(sk_X509_value(chain, 0), intermediates);
274 // sk_X509_dup does not increase reference count on the certs in the stack.
275 openssl_chain_.reset(sk_X509_dup(chain));
277 std::vector<base::StringPiece> der_chain;
278 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
279 X509* x = sk_X509_value(openssl_chain_.get(), i);
280 // Increase the reference count for the certs in openssl_chain_.
281 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
284 #else // !defined(USE_OPENSSL_CERTS)
285 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
286 STACK_OF(X509)* chain) {
287 openssl_chain_.reset(NULL);
288 os_chain_ = NULL;
290 if (!chain)
291 return;
293 // sk_X509_dup does not increase reference count on the certs in the stack.
294 openssl_chain_.reset(sk_X509_dup(chain));
296 std::vector<base::StringPiece> der_chain;
297 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
298 X509* x = sk_X509_value(openssl_chain_.get(), i);
300 // Increase the reference count for the certs in openssl_chain_.
301 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
303 unsigned char* cert_data = NULL;
304 int cert_data_length = i2d_X509(x, &cert_data);
305 if (cert_data_length && cert_data)
306 der_chain.push_back(base::StringPiece(reinterpret_cast<char*>(cert_data),
307 cert_data_length));
310 os_chain_ = X509Certificate::CreateFromDERCertChain(der_chain);
312 for (size_t i = 0; i < der_chain.size(); ++i) {
313 OPENSSL_free(const_cast<char*>(der_chain[i].data()));
316 if (der_chain.size() !=
317 static_cast<size_t>(sk_X509_num(openssl_chain_.get()))) {
318 openssl_chain_.reset(NULL);
319 os_chain_ = NULL;
322 #endif // defined(USE_OPENSSL_CERTS)
324 // static
325 SSLSessionCacheOpenSSL::Config
326 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
327 &GetSessionCacheKey, // key_func
328 1024, // max_entries
329 256, // expiration_check_count
330 60 * 60, // timeout_seconds
333 // static
334 void SSLClientSocket::ClearSessionCache() {
335 SSLClientSocketOpenSSL::SSLContext* context =
336 SSLClientSocketOpenSSL::SSLContext::GetInstance();
337 context->session_cache()->Flush();
340 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
341 scoped_ptr<ClientSocketHandle> transport_socket,
342 const HostPortPair& host_and_port,
343 const SSLConfig& ssl_config,
344 const SSLClientSocketContext& context)
345 : transport_send_busy_(false),
346 transport_recv_busy_(false),
347 weak_factory_(this),
348 pending_read_error_(kNoPendingReadResult),
349 transport_read_error_(OK),
350 transport_write_error_(OK),
351 server_cert_chain_(new PeerCertificateChain(NULL)),
352 completed_connect_(false),
353 was_ever_used_(false),
354 client_auth_cert_needed_(false),
355 cert_verifier_(context.cert_verifier),
356 channel_id_service_(context.channel_id_service),
357 ssl_(NULL),
358 transport_bio_(NULL),
359 transport_(transport_socket.Pass()),
360 host_and_port_(host_and_port),
361 ssl_config_(ssl_config),
362 ssl_session_cache_shard_(context.ssl_session_cache_shard),
363 trying_cached_session_(false),
364 next_handshake_state_(STATE_NONE),
365 npn_status_(kNextProtoUnsupported),
366 channel_id_xtn_negotiated_(false),
367 handshake_succeeded_(false),
368 marked_session_as_good_(false),
369 transport_security_state_(context.transport_security_state),
370 net_log_(transport_->socket()->NetLog()) {
373 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
374 Disconnect();
377 bool SSLClientSocketOpenSSL::InSessionCache() const {
378 SSLContext* context = SSLContext::GetInstance();
379 std::string cache_key = GetSessionCacheKey();
380 return context->session_cache()->SSLSessionIsInCache(cache_key);
383 void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
384 const base::Closure& callback) {
385 handshake_completion_callback_ = callback;
388 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
389 SSLCertRequestInfo* cert_request_info) {
390 cert_request_info->host_and_port = host_and_port_;
391 cert_request_info->cert_authorities = cert_authorities_;
392 cert_request_info->cert_key_types = cert_key_types_;
395 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
396 std::string* proto) {
397 *proto = npn_proto_;
398 return npn_status_;
401 ChannelIDService*
402 SSLClientSocketOpenSSL::GetChannelIDService() const {
403 return channel_id_service_;
406 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
407 const base::StringPiece& label,
408 bool has_context, const base::StringPiece& context,
409 unsigned char* out, unsigned int outlen) {
410 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
412 int rv = SSL_export_keying_material(
413 ssl_, out, outlen, label.data(), label.size(),
414 reinterpret_cast<const unsigned char*>(context.data()),
415 context.length(), context.length() > 0);
417 if (rv != 1) {
418 int ssl_error = SSL_get_error(ssl_, rv);
419 LOG(ERROR) << "Failed to export keying material;"
420 << " returned " << rv
421 << ", SSL error code " << ssl_error;
422 return MapOpenSSLError(ssl_error, err_tracer);
424 return OK;
427 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
428 NOTIMPLEMENTED();
429 return ERR_NOT_IMPLEMENTED;
432 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
433 // It is an error to create an SSLClientSocket whose context has no
434 // TransportSecurityState.
435 DCHECK(transport_security_state_);
437 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
439 // Set up new ssl object.
440 int rv = Init();
441 if (rv != OK) {
442 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
443 return rv;
446 // Set SSL to client mode. Handshake happens in the loop below.
447 SSL_set_connect_state(ssl_);
449 GotoState(STATE_HANDSHAKE);
450 rv = DoHandshakeLoop(OK);
451 if (rv == ERR_IO_PENDING) {
452 user_connect_callback_ = callback;
453 } else {
454 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
455 if (rv < OK)
456 OnHandshakeCompletion();
459 return rv > OK ? OK : rv;
462 void SSLClientSocketOpenSSL::Disconnect() {
463 // If a handshake was pending (Connect() had been called), notify interested
464 // parties that it's been aborted now. If the handshake had already
465 // completed, this is a no-op.
466 OnHandshakeCompletion();
467 if (ssl_) {
468 // Calling SSL_shutdown prevents the session from being marked as
469 // unresumable.
470 SSL_shutdown(ssl_);
471 SSL_free(ssl_);
472 ssl_ = NULL;
474 if (transport_bio_) {
475 BIO_free_all(transport_bio_);
476 transport_bio_ = NULL;
479 // Shut down anything that may call us back.
480 verifier_.reset();
481 transport_->socket()->Disconnect();
483 // Null all callbacks, delete all buffers.
484 transport_send_busy_ = false;
485 send_buffer_ = NULL;
486 transport_recv_busy_ = false;
487 recv_buffer_ = NULL;
489 user_connect_callback_.Reset();
490 user_read_callback_.Reset();
491 user_write_callback_.Reset();
492 user_read_buf_ = NULL;
493 user_read_buf_len_ = 0;
494 user_write_buf_ = NULL;
495 user_write_buf_len_ = 0;
497 pending_read_error_ = kNoPendingReadResult;
498 transport_read_error_ = OK;
499 transport_write_error_ = OK;
501 server_cert_verify_result_.Reset();
502 completed_connect_ = false;
504 cert_authorities_.clear();
505 cert_key_types_.clear();
506 client_auth_cert_needed_ = false;
508 npn_status_ = kNextProtoUnsupported;
509 npn_proto_.clear();
511 channel_id_xtn_negotiated_ = false;
512 channel_id_request_handle_.Cancel();
515 bool SSLClientSocketOpenSSL::IsConnected() const {
516 // If the handshake has not yet completed.
517 if (!completed_connect_)
518 return false;
519 // If an asynchronous operation is still pending.
520 if (user_read_buf_.get() || user_write_buf_.get())
521 return true;
523 return transport_->socket()->IsConnected();
526 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
527 // If the handshake has not yet completed.
528 if (!completed_connect_)
529 return false;
530 // If an asynchronous operation is still pending.
531 if (user_read_buf_.get() || user_write_buf_.get())
532 return false;
533 // If there is data waiting to be sent, or data read from the network that
534 // has not yet been consumed.
535 if (BIO_pending(transport_bio_) > 0 ||
536 BIO_wpending(transport_bio_) > 0) {
537 return false;
540 return transport_->socket()->IsConnectedAndIdle();
543 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
544 return transport_->socket()->GetPeerAddress(addressList);
547 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
548 return transport_->socket()->GetLocalAddress(addressList);
551 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
552 return net_log_;
555 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
556 if (transport_.get() && transport_->socket()) {
557 transport_->socket()->SetSubresourceSpeculation();
558 } else {
559 NOTREACHED();
563 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
564 if (transport_.get() && transport_->socket()) {
565 transport_->socket()->SetOmniboxSpeculation();
566 } else {
567 NOTREACHED();
571 bool SSLClientSocketOpenSSL::WasEverUsed() const {
572 return was_ever_used_;
575 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
576 if (transport_.get() && transport_->socket())
577 return transport_->socket()->UsingTCPFastOpen();
579 NOTREACHED();
580 return false;
583 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
584 ssl_info->Reset();
585 if (!server_cert_.get())
586 return false;
588 ssl_info->cert = server_cert_verify_result_.verified_cert;
589 ssl_info->cert_status = server_cert_verify_result_.cert_status;
590 ssl_info->is_issued_by_known_root =
591 server_cert_verify_result_.is_issued_by_known_root;
592 ssl_info->public_key_hashes =
593 server_cert_verify_result_.public_key_hashes;
594 ssl_info->client_cert_sent =
595 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
596 ssl_info->channel_id_sent = WasChannelIDSent();
597 ssl_info->pinning_failure_log = pinning_failure_log_;
599 RecordChannelIDSupport(channel_id_service_,
600 channel_id_xtn_negotiated_,
601 ssl_config_.channel_id_enabled,
602 crypto::ECPrivateKey::IsSupported());
604 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
605 CHECK(cipher);
606 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
608 ssl_info->connection_status = EncodeSSLConnectionStatus(
609 SSL_CIPHER_get_id(cipher), 0 /* no compression */,
610 GetNetSSLVersion(ssl_));
612 bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
613 if (!peer_supports_renego_ext)
614 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
615 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
616 implicit_cast<int>(peer_supports_renego_ext), 2);
618 if (ssl_config_.version_fallback)
619 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
621 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
622 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
624 DVLOG(3) << "Encoded connection status: cipher suite = "
625 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
626 << " version = "
627 << SSLConnectionStatusToVersion(ssl_info->connection_status);
628 return true;
631 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
632 int buf_len,
633 const CompletionCallback& callback) {
634 user_read_buf_ = buf;
635 user_read_buf_len_ = buf_len;
637 int rv = DoReadLoop(OK);
639 if (rv == ERR_IO_PENDING) {
640 user_read_callback_ = callback;
641 } else {
642 if (rv > 0)
643 was_ever_used_ = true;
644 user_read_buf_ = NULL;
645 user_read_buf_len_ = 0;
646 if (rv <= 0) {
647 // Failure of a read attempt may indicate a failed false start
648 // connection.
649 OnHandshakeCompletion();
653 return rv;
656 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
657 int buf_len,
658 const CompletionCallback& callback) {
659 user_write_buf_ = buf;
660 user_write_buf_len_ = buf_len;
662 int rv = DoWriteLoop(OK);
664 if (rv == ERR_IO_PENDING) {
665 user_write_callback_ = callback;
666 } else {
667 if (rv > 0)
668 was_ever_used_ = true;
669 user_write_buf_ = NULL;
670 user_write_buf_len_ = 0;
671 if (rv < 0) {
672 // Failure of a write attempt may indicate a failed false start
673 // connection.
674 OnHandshakeCompletion();
678 return rv;
681 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
682 return transport_->socket()->SetReceiveBufferSize(size);
685 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
686 return transport_->socket()->SetSendBufferSize(size);
689 int SSLClientSocketOpenSSL::Init() {
690 DCHECK(!ssl_);
691 DCHECK(!transport_bio_);
693 SSLContext* context = SSLContext::GetInstance();
694 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
696 ssl_ = SSL_new(context->ssl_ctx());
697 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
698 return ERR_UNEXPECTED;
700 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
701 return ERR_UNEXPECTED;
703 // Set an OpenSSL callback to monitor this SSL*'s connection.
704 SSL_set_info_callback(ssl_, &InfoCallback);
706 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
707 ssl_, GetSessionCacheKey());
709 BIO* ssl_bio = NULL;
710 // 0 => use default buffer sizes.
711 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
712 return ERR_UNEXPECTED;
713 DCHECK(ssl_bio);
714 DCHECK(transport_bio_);
716 // Install a callback on OpenSSL's end to plumb transport errors through.
717 BIO_set_callback(ssl_bio, BIOCallback);
718 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
720 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
722 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
723 // set everything we care about to an absolute value.
724 SslSetClearMask options;
725 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
726 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
727 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
728 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
729 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
730 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
731 bool tls1_1_enabled =
732 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
733 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
734 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
735 bool tls1_2_enabled =
736 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
737 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
738 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
740 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
742 // TODO(joth): Set this conditionally, see http://crbug.com/55410
743 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
745 SSL_set_options(ssl_, options.set_mask);
746 SSL_clear_options(ssl_, options.clear_mask);
748 // Same as above, this time for the SSL mode.
749 SslSetClearMask mode;
751 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
753 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
754 ssl_config_.false_start_enabled);
756 SSL_set_mode(ssl_, mode.set_mask);
757 SSL_clear_mode(ssl_, mode.clear_mask);
759 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
760 // textual name with SSL_set_cipher_list because there is no public API to
761 // directly remove a cipher by ID.
762 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
763 DCHECK(ciphers);
764 // See SSLConfig::disabled_cipher_suites for description of the suites
765 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
766 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
767 // as the handshake hash.
768 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
769 "!aECDH:!AESGCM+AES256");
770 // Walk through all the installed ciphers, seeing if any need to be
771 // appended to the cipher removal |command|.
772 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
773 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
774 const uint16 id = SSL_CIPHER_get_id(cipher);
775 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
776 // implementation uses "effective" bits here but OpenSSL does not provide
777 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
778 // both of which are greater than 80 anyway.
779 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
780 if (!disable) {
781 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
782 ssl_config_.disabled_cipher_suites.end(), id) !=
783 ssl_config_.disabled_cipher_suites.end();
785 if (disable) {
786 const char* name = SSL_CIPHER_get_name(cipher);
787 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
788 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
789 command.append(":!");
790 command.append(name);
793 int rv = SSL_set_cipher_list(ssl_, command.c_str());
794 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
795 // This will almost certainly result in the socket failing to complete the
796 // handshake at which point the appropriate error is bubbled up to the client.
797 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
798 "returned " << rv;
800 if (ssl_config_.version_fallback)
801 SSL_enable_fallback_scsv(ssl_);
803 // TLS channel ids.
804 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
805 SSL_enable_tls_channel_id(ssl_);
808 if (!ssl_config_.next_protos.empty()) {
809 std::vector<uint8_t> wire_protos =
810 SerializeNextProtos(ssl_config_.next_protos);
811 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
812 wire_protos.size());
815 return OK;
818 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
819 // Since Run may result in Read being called, clear |user_read_callback_|
820 // up front.
821 if (rv > 0)
822 was_ever_used_ = true;
823 user_read_buf_ = NULL;
824 user_read_buf_len_ = 0;
825 if (rv <= 0) {
826 // Failure of a read attempt may indicate a failed false start
827 // connection.
828 OnHandshakeCompletion();
830 base::ResetAndReturn(&user_read_callback_).Run(rv);
833 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
834 // Since Run may result in Write being called, clear |user_write_callback_|
835 // up front.
836 if (rv > 0)
837 was_ever_used_ = true;
838 user_write_buf_ = NULL;
839 user_write_buf_len_ = 0;
840 if (rv < 0) {
841 // Failure of a write attempt may indicate a failed false start
842 // connection.
843 OnHandshakeCompletion();
845 base::ResetAndReturn(&user_write_callback_).Run(rv);
848 std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
849 return CreateSessionCacheKey(host_and_port_, ssl_session_cache_shard_);
852 void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
853 if (!handshake_completion_callback_.is_null())
854 base::ResetAndReturn(&handshake_completion_callback_).Run();
857 bool SSLClientSocketOpenSSL::DoTransportIO() {
858 bool network_moved = false;
859 int rv;
860 // Read and write as much data as possible. The loop is necessary because
861 // Write() may return synchronously.
862 do {
863 rv = BufferSend();
864 if (rv != ERR_IO_PENDING && rv != 0)
865 network_moved = true;
866 } while (rv > 0);
867 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
868 network_moved = true;
869 return network_moved;
872 int SSLClientSocketOpenSSL::DoHandshake() {
873 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
874 int net_error = OK;
875 int rv = SSL_do_handshake(ssl_);
877 if (client_auth_cert_needed_) {
878 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
879 // If the handshake already succeeded (because the server requests but
880 // doesn't require a client cert), we need to invalidate the SSL session
881 // so that we won't try to resume the non-client-authenticated session in
882 // the next handshake. This will cause the server to ask for a client
883 // cert again.
884 if (rv == 1) {
885 // Remove from session cache but don't clear this connection.
886 SSL_SESSION* session = SSL_get_session(ssl_);
887 if (session) {
888 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
889 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
892 } else if (rv == 1) {
893 if (trying_cached_session_ && logging::DEBUG_MODE) {
894 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
895 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
898 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
899 if (npn_status_ == kNextProtoUnsupported) {
900 const uint8_t* alpn_proto = NULL;
901 unsigned alpn_len = 0;
902 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
903 if (alpn_len > 0) {
904 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
905 npn_status_ = kNextProtoNegotiated;
909 // Verify the certificate.
910 const bool got_cert = !!UpdateServerCert();
911 DCHECK(got_cert);
912 net_log_.AddEvent(
913 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
914 base::Bind(&NetLogX509CertificateCallback,
915 base::Unretained(server_cert_.get())));
916 GotoState(STATE_VERIFY_CERT);
917 } else {
918 int ssl_error = SSL_get_error(ssl_, rv);
920 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
921 // The server supports channel ID. Stop to look one up before returning to
922 // the handshake.
923 channel_id_xtn_negotiated_ = true;
924 GotoState(STATE_CHANNEL_ID_LOOKUP);
925 return OK;
928 net_error = MapOpenSSLError(ssl_error, err_tracer);
930 // If not done, stay in this state
931 if (net_error == ERR_IO_PENDING) {
932 GotoState(STATE_HANDSHAKE);
933 } else {
934 LOG(ERROR) << "handshake failed; returned " << rv
935 << ", SSL error code " << ssl_error
936 << ", net_error " << net_error;
937 net_log_.AddEvent(
938 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
939 CreateNetLogSSLErrorCallback(net_error, ssl_error));
942 return net_error;
945 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
946 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
947 return channel_id_service_->GetOrCreateChannelID(
948 host_and_port_.host(),
949 &channel_id_private_key_,
950 &channel_id_cert_,
951 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
952 base::Unretained(this)),
953 &channel_id_request_handle_);
956 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
957 if (result < 0)
958 return result;
960 DCHECK_LT(0u, channel_id_private_key_.size());
961 // Decode key.
962 std::vector<uint8> encrypted_private_key_info;
963 std::vector<uint8> subject_public_key_info;
964 encrypted_private_key_info.assign(
965 channel_id_private_key_.data(),
966 channel_id_private_key_.data() + channel_id_private_key_.size());
967 subject_public_key_info.assign(
968 channel_id_cert_.data(),
969 channel_id_cert_.data() + channel_id_cert_.size());
970 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
971 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
972 ChannelIDService::kEPKIPassword,
973 encrypted_private_key_info,
974 subject_public_key_info));
975 if (!ec_private_key) {
976 LOG(ERROR) << "Failed to import Channel ID.";
977 return ERR_CHANNEL_ID_IMPORT_FAILED;
980 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
981 // type.
982 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
983 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
984 if (!rv) {
985 LOG(ERROR) << "Failed to set Channel ID.";
986 int err = SSL_get_error(ssl_, rv);
987 return MapOpenSSLError(err, err_tracer);
990 // Return to the handshake.
991 set_channel_id_sent(true);
992 GotoState(STATE_HANDSHAKE);
993 return OK;
996 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
997 DCHECK(server_cert_.get());
998 GotoState(STATE_VERIFY_CERT_COMPLETE);
1000 CertStatus cert_status;
1001 if (ssl_config_.IsAllowedBadCert(server_cert_.get(), &cert_status)) {
1002 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1003 server_cert_verify_result_.Reset();
1004 server_cert_verify_result_.cert_status = cert_status;
1005 server_cert_verify_result_.verified_cert = server_cert_;
1006 return OK;
1009 int flags = 0;
1010 if (ssl_config_.rev_checking_enabled)
1011 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1012 if (ssl_config_.verify_ev_cert)
1013 flags |= CertVerifier::VERIFY_EV_CERT;
1014 if (ssl_config_.cert_io_enabled)
1015 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1016 if (ssl_config_.rev_checking_required_local_anchors)
1017 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1018 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1019 return verifier_->Verify(
1020 server_cert_.get(),
1021 host_and_port_.host(),
1022 flags,
1023 NULL /* no CRL set */,
1024 &server_cert_verify_result_,
1025 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1026 base::Unretained(this)),
1027 net_log_);
1030 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1031 verifier_.reset();
1033 bool sni_available = ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1 ||
1034 ssl_config_.version_fallback;
1035 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1036 if (transport_security_state_ &&
1037 (result == OK ||
1038 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1039 !transport_security_state_->CheckPublicKeyPins(
1040 host_and_port_.host(),
1041 sni_available,
1042 server_cert_verify_result_.is_issued_by_known_root,
1043 server_cert_verify_result_.public_key_hashes,
1044 &pinning_failure_log_)) {
1045 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1048 if (result == OK) {
1049 // TODO(joth): Work out if we need to remember the intermediate CA certs
1050 // when the server sends them to us, and do so here.
1051 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
1052 marked_session_as_good_ = true;
1053 CheckIfHandshakeFinished();
1054 } else {
1055 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1056 << " (" << result << ")";
1059 completed_connect_ = true;
1061 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1062 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1063 return result;
1066 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1067 if (rv < OK)
1068 OnHandshakeCompletion();
1069 if (!user_connect_callback_.is_null()) {
1070 CompletionCallback c = user_connect_callback_;
1071 user_connect_callback_.Reset();
1072 c.Run(rv > OK ? OK : rv);
1076 X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
1077 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
1078 server_cert_ = server_cert_chain_->AsOSChain();
1080 if (!server_cert_chain_->IsValid())
1081 DVLOG(1) << "UpdateServerCert received invalid certificate chain from peer";
1083 return server_cert_.get();
1086 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1087 int rv = DoHandshakeLoop(result);
1088 if (rv != ERR_IO_PENDING) {
1089 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1090 DoConnectCallback(rv);
1094 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1095 if (next_handshake_state_ == STATE_HANDSHAKE) {
1096 // In handshake phase.
1097 OnHandshakeIOComplete(result);
1098 return;
1101 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1102 // handshake is in progress.
1103 int rv_read = ERR_IO_PENDING;
1104 int rv_write = ERR_IO_PENDING;
1105 bool network_moved;
1106 do {
1107 if (user_read_buf_.get())
1108 rv_read = DoPayloadRead();
1109 if (user_write_buf_.get())
1110 rv_write = DoPayloadWrite();
1111 network_moved = DoTransportIO();
1112 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1113 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1115 // Performing the Read callback may cause |this| to be deleted. If this
1116 // happens, the Write callback should not be invoked. Guard against this by
1117 // holding a WeakPtr to |this| and ensuring it's still valid.
1118 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1119 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1120 DoReadCallback(rv_read);
1122 if (!guard.get())
1123 return;
1125 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1126 DoWriteCallback(rv_write);
1129 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1130 if (next_handshake_state_ == STATE_HANDSHAKE) {
1131 // In handshake phase.
1132 OnHandshakeIOComplete(result);
1133 return;
1136 // Network layer received some data, check if client requested to read
1137 // decrypted data.
1138 if (!user_read_buf_.get())
1139 return;
1141 int rv = DoReadLoop(result);
1142 if (rv != ERR_IO_PENDING)
1143 DoReadCallback(rv);
1146 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1147 int rv = last_io_result;
1148 do {
1149 // Default to STATE_NONE for next state.
1150 // (This is a quirk carried over from the windows
1151 // implementation. It makes reading the logs a bit harder.)
1152 // State handlers can and often do call GotoState just
1153 // to stay in the current state.
1154 State state = next_handshake_state_;
1155 GotoState(STATE_NONE);
1156 switch (state) {
1157 case STATE_HANDSHAKE:
1158 rv = DoHandshake();
1159 break;
1160 case STATE_CHANNEL_ID_LOOKUP:
1161 DCHECK_EQ(OK, rv);
1162 rv = DoChannelIDLookup();
1163 break;
1164 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1165 rv = DoChannelIDLookupComplete(rv);
1166 break;
1167 case STATE_VERIFY_CERT:
1168 DCHECK_EQ(OK, rv);
1169 rv = DoVerifyCert(rv);
1170 break;
1171 case STATE_VERIFY_CERT_COMPLETE:
1172 rv = DoVerifyCertComplete(rv);
1173 break;
1174 case STATE_NONE:
1175 default:
1176 rv = ERR_UNEXPECTED;
1177 NOTREACHED() << "unexpected state" << state;
1178 break;
1181 bool network_moved = DoTransportIO();
1182 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1183 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1184 // special case we keep looping even if rv is ERR_IO_PENDING because
1185 // the transport IO may allow DoHandshake to make progress.
1186 rv = OK; // This causes us to stay in the loop.
1188 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1190 return rv;
1193 int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1194 if (result < 0)
1195 return result;
1197 bool network_moved;
1198 int rv;
1199 do {
1200 rv = DoPayloadRead();
1201 network_moved = DoTransportIO();
1202 } while (rv == ERR_IO_PENDING && network_moved);
1204 return rv;
1207 int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1208 if (result < 0)
1209 return result;
1211 bool network_moved;
1212 int rv;
1213 do {
1214 rv = DoPayloadWrite();
1215 network_moved = DoTransportIO();
1216 } while (rv == ERR_IO_PENDING && network_moved);
1218 return rv;
1221 int SSLClientSocketOpenSSL::DoPayloadRead() {
1222 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1224 int rv;
1225 if (pending_read_error_ != kNoPendingReadResult) {
1226 rv = pending_read_error_;
1227 pending_read_error_ = kNoPendingReadResult;
1228 if (rv == 0) {
1229 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1230 rv, user_read_buf_->data());
1232 return rv;
1235 int total_bytes_read = 0;
1236 do {
1237 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1238 user_read_buf_len_ - total_bytes_read);
1239 if (rv > 0)
1240 total_bytes_read += rv;
1241 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1243 if (total_bytes_read == user_read_buf_len_) {
1244 rv = total_bytes_read;
1245 } else {
1246 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1247 // immediately, while the OpenSSL errors are still available in
1248 // thread-local storage. However, the handled/remapped error code should
1249 // only be returned if no application data was already read; if it was, the
1250 // error code should be deferred until the next call of DoPayloadRead.
1252 // If no data was read, |*next_result| will point to the return value of
1253 // this function. If at least some data was read, |*next_result| will point
1254 // to |pending_read_error_|, to be returned in a future call to
1255 // DoPayloadRead() (e.g.: after the current data is handled).
1256 int *next_result = &rv;
1257 if (total_bytes_read > 0) {
1258 pending_read_error_ = rv;
1259 rv = total_bytes_read;
1260 next_result = &pending_read_error_;
1263 if (client_auth_cert_needed_) {
1264 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1265 } else if (*next_result < 0) {
1266 int err = SSL_get_error(ssl_, *next_result);
1267 *next_result = MapOpenSSLError(err, err_tracer);
1268 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1269 // If at least some data was read from SSL_read(), do not treat
1270 // insufficient data as an error to return in the next call to
1271 // DoPayloadRead() - instead, let the call fall through to check
1272 // SSL_read() again. This is because DoTransportIO() may complete
1273 // in between the next call to DoPayloadRead(), and thus it is
1274 // important to check SSL_read() on subsequent invocations to see
1275 // if a complete record may now be read.
1276 *next_result = kNoPendingReadResult;
1281 if (rv >= 0) {
1282 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1283 user_read_buf_->data());
1285 return rv;
1288 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1289 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1290 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1291 if (rv >= 0) {
1292 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1293 user_write_buf_->data());
1294 return rv;
1297 int err = SSL_get_error(ssl_, rv);
1298 return MapOpenSSLError(err, err_tracer);
1301 int SSLClientSocketOpenSSL::BufferSend(void) {
1302 if (transport_send_busy_)
1303 return ERR_IO_PENDING;
1305 if (!send_buffer_.get()) {
1306 // Get a fresh send buffer out of the send BIO.
1307 size_t max_read = BIO_pending(transport_bio_);
1308 if (!max_read)
1309 return 0; // Nothing pending in the OpenSSL write BIO.
1310 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1311 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1312 DCHECK_GT(read_bytes, 0);
1313 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1316 int rv = transport_->socket()->Write(
1317 send_buffer_.get(),
1318 send_buffer_->BytesRemaining(),
1319 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1320 base::Unretained(this)));
1321 if (rv == ERR_IO_PENDING) {
1322 transport_send_busy_ = true;
1323 } else {
1324 TransportWriteComplete(rv);
1326 return rv;
1329 int SSLClientSocketOpenSSL::BufferRecv(void) {
1330 if (transport_recv_busy_)
1331 return ERR_IO_PENDING;
1333 // Determine how much was requested from |transport_bio_| that was not
1334 // actually available.
1335 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1336 if (requested == 0) {
1337 // This is not a perfect match of error codes, as no operation is
1338 // actually pending. However, returning 0 would be interpreted as
1339 // a possible sign of EOF, which is also an inappropriate match.
1340 return ERR_IO_PENDING;
1343 // Known Issue: While only reading |requested| data is the more correct
1344 // implementation, it has the downside of resulting in frequent reads:
1345 // One read for the SSL record header (~5 bytes) and one read for the SSL
1346 // record body. Rather than issuing these reads to the underlying socket
1347 // (and constantly allocating new IOBuffers), a single Read() request to
1348 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1349 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1350 // traffic, this over-subscribed Read()ing will not cause issues.
1351 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1352 if (!max_write)
1353 return ERR_IO_PENDING;
1355 recv_buffer_ = new IOBuffer(max_write);
1356 int rv = transport_->socket()->Read(
1357 recv_buffer_.get(),
1358 max_write,
1359 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1360 base::Unretained(this)));
1361 if (rv == ERR_IO_PENDING) {
1362 transport_recv_busy_ = true;
1363 } else {
1364 rv = TransportReadComplete(rv);
1366 return rv;
1369 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1370 transport_send_busy_ = false;
1371 TransportWriteComplete(result);
1372 OnSendComplete(result);
1375 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1376 result = TransportReadComplete(result);
1377 OnRecvComplete(result);
1380 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1381 DCHECK(ERR_IO_PENDING != result);
1382 if (result < 0) {
1383 // Record the error. Save it to be reported in a future read or write on
1384 // transport_bio_'s peer.
1385 transport_write_error_ = result;
1386 send_buffer_ = NULL;
1387 } else {
1388 DCHECK(send_buffer_.get());
1389 send_buffer_->DidConsume(result);
1390 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1391 if (send_buffer_->BytesRemaining() <= 0)
1392 send_buffer_ = NULL;
1396 int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1397 DCHECK(ERR_IO_PENDING != result);
1398 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1399 // does not report success.
1400 if (result == 0)
1401 result = ERR_CONNECTION_CLOSED;
1402 if (result < 0) {
1403 DVLOG(1) << "TransportReadComplete result " << result;
1404 // Received an error. Save it to be reported in a future read on
1405 // transport_bio_'s peer.
1406 transport_read_error_ = result;
1407 } else {
1408 DCHECK(recv_buffer_.get());
1409 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1410 // A write into a memory BIO should always succeed.
1411 DCHECK_EQ(result, ret);
1413 recv_buffer_ = NULL;
1414 transport_recv_busy_ = false;
1415 return result;
1418 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
1419 X509** x509,
1420 EVP_PKEY** pkey) {
1421 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1422 DCHECK(ssl == ssl_);
1423 DCHECK(*x509 == NULL);
1424 DCHECK(*pkey == NULL);
1426 #if defined(OS_IOS)
1427 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1428 LOG(WARNING) << "Client auth is not supported";
1429 #else // !defined(OS_IOS)
1430 if (!ssl_config_.send_client_cert) {
1431 // First pass: we know that a client certificate is needed, but we do not
1432 // have one at hand.
1433 client_auth_cert_needed_ = true;
1434 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1435 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
1436 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1437 unsigned char* str = NULL;
1438 int length = i2d_X509_NAME(ca_name, &str);
1439 cert_authorities_.push_back(std::string(
1440 reinterpret_cast<const char*>(str),
1441 static_cast<size_t>(length)));
1442 OPENSSL_free(str);
1445 const unsigned char* client_cert_types;
1446 size_t num_client_cert_types =
1447 SSL_get0_certificate_types(ssl, &client_cert_types);
1448 for (size_t i = 0; i < num_client_cert_types; i++) {
1449 cert_key_types_.push_back(
1450 static_cast<SSLClientCertType>(client_cert_types[i]));
1453 return -1; // Suspends handshake.
1456 // Second pass: a client certificate should have been selected.
1457 if (ssl_config_.client_cert.get()) {
1458 // TODO(davidben): Configure OpenSSL to also send the intermediates.
1459 ScopedX509 leaf_x509 =
1460 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1461 if (!leaf_x509) {
1462 LOG(WARNING) << "Failed to import certificate";
1463 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1464 return -1;
1467 // TODO(davidben): With Linux client auth support, this should be
1468 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1469 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1470 // net/ client auth API lacking a private key handle.
1471 #if defined(USE_OPENSSL_CERTS)
1472 crypto::ScopedEVP_PKEY privkey =
1473 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1474 ssl_config_.client_cert.get());
1475 #else // !defined(USE_OPENSSL_CERTS)
1476 crypto::ScopedEVP_PKEY privkey =
1477 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1478 #endif // defined(USE_OPENSSL_CERTS)
1479 if (!privkey) {
1480 // Could not find the private key. Fail the handshake and surface an
1481 // appropriate error to the caller.
1482 LOG(WARNING) << "Client cert found without private key";
1483 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1484 return -1;
1487 // TODO(joth): (copied from NSS) We should wait for server certificate
1488 // verification before sending our credentials. See http://crbug.com/13934
1489 *x509 = leaf_x509.release();
1490 *pkey = privkey.release();
1491 return 1;
1493 #endif // defined(OS_IOS)
1495 // Send no client certificate.
1496 return 0;
1499 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1500 if (!completed_connect_) {
1501 // If the first handshake hasn't completed then we accept any certificates
1502 // because we verify after the handshake.
1503 return 1;
1506 CHECK(server_cert_.get());
1508 PeerCertificateChain chain(store_ctx->untrusted);
1509 if (chain.IsValid() && server_cert_->Equals(chain.AsOSChain()))
1510 return 1;
1512 if (!chain.IsValid())
1513 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1514 else
1515 LOG(ERROR) << "Server certificate changed between handshakes";
1516 return 0;
1519 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1520 // server supports NPN, selects a protocol from the list that the server
1521 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1522 // callback can assume that |in| is syntactically valid.
1523 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1524 unsigned char* outlen,
1525 const unsigned char* in,
1526 unsigned int inlen) {
1527 if (ssl_config_.next_protos.empty()) {
1528 *out = reinterpret_cast<uint8*>(
1529 const_cast<char*>(kDefaultSupportedNPNProtocol));
1530 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1531 npn_status_ = kNextProtoUnsupported;
1532 return SSL_TLSEXT_ERR_OK;
1535 // Assume there's no overlap between our protocols and the server's list.
1536 npn_status_ = kNextProtoNoOverlap;
1538 // For each protocol in server preference order, see if we support it.
1539 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1540 for (std::vector<std::string>::const_iterator
1541 j = ssl_config_.next_protos.begin();
1542 j != ssl_config_.next_protos.end(); ++j) {
1543 if (in[i] == j->size() &&
1544 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
1545 // We found a match.
1546 *out = const_cast<unsigned char*>(in) + i + 1;
1547 *outlen = in[i];
1548 npn_status_ = kNextProtoNegotiated;
1549 break;
1552 if (npn_status_ == kNextProtoNegotiated)
1553 break;
1556 // If we didn't find a protocol, we select the first one from our list.
1557 if (npn_status_ == kNextProtoNoOverlap) {
1558 *out = reinterpret_cast<uint8*>(const_cast<char*>(
1559 ssl_config_.next_protos[0].data()));
1560 *outlen = ssl_config_.next_protos[0].size();
1563 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
1564 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
1565 return SSL_TLSEXT_ERR_OK;
1568 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1569 BIO *bio,
1570 int cmd,
1571 const char *argp, int argi, long argl,
1572 long retvalue) {
1573 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1574 // If there is no more data in the buffer, report any pending errors that
1575 // were observed. Note that both the readbuf and the writebuf are checked
1576 // for errors, since the application may have encountered a socket error
1577 // while writing that would otherwise not be reported until the application
1578 // attempted to write again - which it may never do. See
1579 // https://crbug.com/249848.
1580 if (transport_read_error_ != OK) {
1581 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1582 return -1;
1584 if (transport_write_error_ != OK) {
1585 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1586 return -1;
1588 } else if (cmd == BIO_CB_WRITE) {
1589 // Because of the write buffer, this reports a failure from the previous
1590 // write payload. If the current payload fails to write, the error will be
1591 // reported in a future write or read to |bio|.
1592 if (transport_write_error_ != OK) {
1593 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1594 return -1;
1597 return retvalue;
1600 // static
1601 long SSLClientSocketOpenSSL::BIOCallback(
1602 BIO *bio,
1603 int cmd,
1604 const char *argp, int argi, long argl,
1605 long retvalue) {
1606 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1607 BIO_get_callback_arg(bio));
1608 CHECK(socket);
1609 return socket->MaybeReplayTransportError(
1610 bio, cmd, argp, argi, argl, retvalue);
1613 // static
1614 void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1615 int type,
1616 int /*val*/) {
1617 if (type == SSL_CB_HANDSHAKE_DONE) {
1618 SSLClientSocketOpenSSL* ssl_socket =
1619 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1620 ssl_socket->handshake_succeeded_ = true;
1621 ssl_socket->CheckIfHandshakeFinished();
1625 // Determines if both the handshake and certificate verification have completed
1626 // successfully, and calls the handshake completion callback if that is the
1627 // case.
1629 // CheckIfHandshakeFinished is called twice per connection: once after
1630 // MarkSSLSessionAsGood, when the certificate has been verified, and
1631 // once via an OpenSSL callback when the handshake has completed. On the
1632 // second call, when the certificate has been verified and the handshake
1633 // has completed, the connection's handshake completion callback is run.
1634 void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1635 if (handshake_succeeded_ && marked_session_as_good_)
1636 OnHandshakeCompletion();
1639 scoped_refptr<X509Certificate>
1640 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1641 return server_cert_;
1644 } // namespace net