QUIC - enable persisting of QUICServerInfo (server config) to disk
[chromium-blink-merge.git] / net / socket / ssl_client_socket_openssl.cc
blob7192d850e6a99d5efee473ffd727ca65912d5223
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/socket/ssl_error_params.h"
27 #include "net/socket/ssl_session_cache_openssl.h"
28 #include "net/ssl/openssl_ssl_util.h"
29 #include "net/ssl/ssl_cert_request_info.h"
30 #include "net/ssl/ssl_connection_status_flags.h"
31 #include "net/ssl/ssl_info.h"
33 #if defined(USE_OPENSSL_CERTS)
34 #include "net/ssl/openssl_client_key_store.h"
35 #else
36 #include "net/ssl/openssl_platform_key.h"
37 #endif
39 namespace net {
41 namespace {
43 // Enable this to see logging for state machine state transitions.
44 #if 0
45 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
46 " jump to state " << s; \
47 next_handshake_state_ = s; } while (0)
48 #else
49 #define GotoState(s) next_handshake_state_ = s
50 #endif
52 // This constant can be any non-negative/non-zero value (eg: it does not
53 // overlap with any value of the net::Error range, including net::OK).
54 const int kNoPendingReadResult = 1;
56 // If a client doesn't have a list of protocols that it supports, but
57 // the server supports NPN, choosing "http/1.1" is the best answer.
58 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
60 typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
62 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
63 // This method doesn't seem to have made it into the OpenSSL headers.
64 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
65 #endif
67 // Used for encoding the |connection_status| field of an SSLInfo object.
68 int EncodeSSLConnectionStatus(int cipher_suite,
69 int compression,
70 int version) {
71 return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
72 SSL_CONNECTION_CIPHERSUITE_SHIFT) |
73 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
74 SSL_CONNECTION_COMPRESSION_SHIFT) |
75 ((version & SSL_CONNECTION_VERSION_MASK) <<
76 SSL_CONNECTION_VERSION_SHIFT);
79 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
80 // this SSL connection.
81 int GetNetSSLVersion(SSL* ssl) {
82 switch (SSL_version(ssl)) {
83 case SSL2_VERSION:
84 return SSL_CONNECTION_VERSION_SSL2;
85 case SSL3_VERSION:
86 return SSL_CONNECTION_VERSION_SSL3;
87 case TLS1_VERSION:
88 return SSL_CONNECTION_VERSION_TLS1;
89 case 0x0302:
90 return SSL_CONNECTION_VERSION_TLS1_1;
91 case 0x0303:
92 return SSL_CONNECTION_VERSION_TLS1_2;
93 default:
94 return SSL_CONNECTION_VERSION_UNKNOWN;
98 // Compute a unique key string for the SSL session cache. |socket| is an
99 // input socket object. Return a string.
100 std::string GetSocketSessionCacheKey(const SSLClientSocketOpenSSL& socket) {
101 std::string result = socket.host_and_port().ToString();
102 result.append("/");
103 result.append(socket.ssl_session_cache_shard());
104 return result;
107 void FreeX509Stack(STACK_OF(X509) * ptr) {
108 sk_X509_pop_free(ptr, X509_free);
111 ScopedX509 OSCertHandleToOpenSSL(
112 X509Certificate::OSCertHandle os_handle) {
113 #if defined(USE_OPENSSL_CERTS)
114 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
115 #else // !defined(USE_OPENSSL_CERTS)
116 std::string der_encoded;
117 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
118 return ScopedX509();
119 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
120 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
121 #endif // defined(USE_OPENSSL_CERTS)
124 } // namespace
126 class SSLClientSocketOpenSSL::SSLContext {
127 public:
128 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
129 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
130 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
132 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
133 DCHECK(ssl);
134 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
135 SSL_get_ex_data(ssl, ssl_socket_data_index_));
136 DCHECK(socket);
137 return socket;
140 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
141 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
144 private:
145 friend struct DefaultSingletonTraits<SSLContext>;
147 SSLContext() {
148 crypto::EnsureOpenSSLInit();
149 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
150 DCHECK_NE(ssl_socket_data_index_, -1);
151 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
152 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
153 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
154 SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
155 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
156 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
157 // It would be better if the callback were not a global setting,
158 // but that is an OpenSSL issue.
159 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
160 NULL);
161 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
164 static std::string GetSessionCacheKey(const SSL* ssl) {
165 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
166 DCHECK(socket);
167 return GetSocketSessionCacheKey(*socket);
170 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
172 static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
173 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
174 CHECK(socket);
175 return socket->ClientCertRequestCallback(ssl, x509, pkey);
178 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
179 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
180 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
181 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
182 CHECK(socket);
184 return socket->CertVerifyCallback(store_ctx);
187 static int SelectNextProtoCallback(SSL* ssl,
188 unsigned char** out, unsigned char* outlen,
189 const unsigned char* in,
190 unsigned int inlen, void* arg) {
191 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
192 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
195 // This is the index used with SSL_get_ex_data to retrieve the owner
196 // SSLClientSocketOpenSSL object from an SSL instance.
197 int ssl_socket_data_index_;
199 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
200 // |session_cache_| must be destroyed before |ssl_ctx_|.
201 SSLSessionCacheOpenSSL session_cache_;
204 // PeerCertificateChain is a helper object which extracts the certificate
205 // chain, as given by the server, from an OpenSSL socket and performs the needed
206 // resource management. The first element of the chain is the leaf certificate
207 // and the other elements are in the order given by the server.
208 class SSLClientSocketOpenSSL::PeerCertificateChain {
209 public:
210 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
211 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
212 ~PeerCertificateChain() {}
213 PeerCertificateChain& operator=(const PeerCertificateChain& other);
215 // Resets the PeerCertificateChain to the set of certificates in|chain|,
216 // which may be NULL, indicating to empty the store certificates.
217 // Note: If an error occurs, such as being unable to parse the certificates,
218 // this will behave as if Reset(NULL) was called.
219 void Reset(STACK_OF(X509)* chain);
221 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
222 const scoped_refptr<X509Certificate>& AsOSChain() const { return os_chain_; }
224 size_t size() const {
225 if (!openssl_chain_.get())
226 return 0;
227 return sk_X509_num(openssl_chain_.get());
230 X509* operator[](size_t index) const {
231 DCHECK_LT(index, size());
232 return sk_X509_value(openssl_chain_.get(), index);
235 bool IsValid() { return os_chain_.get() && openssl_chain_.get(); }
237 private:
238 typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
239 ScopedX509Stack;
241 ScopedX509Stack openssl_chain_;
243 scoped_refptr<X509Certificate> os_chain_;
246 SSLClientSocketOpenSSL::PeerCertificateChain&
247 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
248 const PeerCertificateChain& other) {
249 if (this == &other)
250 return *this;
252 // os_chain_ is reference counted by scoped_refptr;
253 os_chain_ = other.os_chain_;
255 // Must increase the reference count manually for sk_X509_dup
256 openssl_chain_.reset(sk_X509_dup(other.openssl_chain_.get()));
257 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
258 X509* x = sk_X509_value(openssl_chain_.get(), i);
259 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
261 return *this;
264 #if defined(USE_OPENSSL_CERTS)
265 // When OSCertHandle is typedef'ed to X509, this implementation does a short cut
266 // to avoid converting back and forth between der and X509 struct.
267 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
268 STACK_OF(X509)* chain) {
269 openssl_chain_.reset(NULL);
270 os_chain_ = NULL;
272 if (!chain)
273 return;
275 X509Certificate::OSCertHandles intermediates;
276 for (size_t i = 1; i < sk_X509_num(chain); ++i)
277 intermediates.push_back(sk_X509_value(chain, i));
279 os_chain_ =
280 X509Certificate::CreateFromHandle(sk_X509_value(chain, 0), intermediates);
282 // sk_X509_dup does not increase reference count on the certs in the stack.
283 openssl_chain_.reset(sk_X509_dup(chain));
285 std::vector<base::StringPiece> der_chain;
286 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
287 X509* x = sk_X509_value(openssl_chain_.get(), i);
288 // Increase the reference count for the certs in openssl_chain_.
289 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
292 #else // !defined(USE_OPENSSL_CERTS)
293 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
294 STACK_OF(X509)* chain) {
295 openssl_chain_.reset(NULL);
296 os_chain_ = NULL;
298 if (!chain)
299 return;
301 // sk_X509_dup does not increase reference count on the certs in the stack.
302 openssl_chain_.reset(sk_X509_dup(chain));
304 std::vector<base::StringPiece> der_chain;
305 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
306 X509* x = sk_X509_value(openssl_chain_.get(), i);
308 // Increase the reference count for the certs in openssl_chain_.
309 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
311 unsigned char* cert_data = NULL;
312 int cert_data_length = i2d_X509(x, &cert_data);
313 if (cert_data_length && cert_data)
314 der_chain.push_back(base::StringPiece(reinterpret_cast<char*>(cert_data),
315 cert_data_length));
318 os_chain_ = X509Certificate::CreateFromDERCertChain(der_chain);
320 for (size_t i = 0; i < der_chain.size(); ++i) {
321 OPENSSL_free(const_cast<char*>(der_chain[i].data()));
324 if (der_chain.size() !=
325 static_cast<size_t>(sk_X509_num(openssl_chain_.get()))) {
326 openssl_chain_.reset(NULL);
327 os_chain_ = NULL;
330 #endif // defined(USE_OPENSSL_CERTS)
332 // static
333 SSLSessionCacheOpenSSL::Config
334 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
335 &GetSessionCacheKey, // key_func
336 1024, // max_entries
337 256, // expiration_check_count
338 60 * 60, // timeout_seconds
341 // static
342 void SSLClientSocket::ClearSessionCache() {
343 SSLClientSocketOpenSSL::SSLContext* context =
344 SSLClientSocketOpenSSL::SSLContext::GetInstance();
345 context->session_cache()->Flush();
348 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
349 scoped_ptr<ClientSocketHandle> transport_socket,
350 const HostPortPair& host_and_port,
351 const SSLConfig& ssl_config,
352 const SSLClientSocketContext& context)
353 : transport_send_busy_(false),
354 transport_recv_busy_(false),
355 weak_factory_(this),
356 pending_read_error_(kNoPendingReadResult),
357 transport_read_error_(OK),
358 transport_write_error_(OK),
359 server_cert_chain_(new PeerCertificateChain(NULL)),
360 completed_handshake_(false),
361 was_ever_used_(false),
362 client_auth_cert_needed_(false),
363 cert_verifier_(context.cert_verifier),
364 channel_id_service_(context.channel_id_service),
365 ssl_(NULL),
366 transport_bio_(NULL),
367 transport_(transport_socket.Pass()),
368 host_and_port_(host_and_port),
369 ssl_config_(ssl_config),
370 ssl_session_cache_shard_(context.ssl_session_cache_shard),
371 trying_cached_session_(false),
372 next_handshake_state_(STATE_NONE),
373 npn_status_(kNextProtoUnsupported),
374 channel_id_xtn_negotiated_(false),
375 net_log_(transport_->socket()->NetLog()) {}
377 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
378 Disconnect();
381 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
382 SSLCertRequestInfo* cert_request_info) {
383 cert_request_info->host_and_port = host_and_port_;
384 cert_request_info->cert_authorities = cert_authorities_;
385 cert_request_info->cert_key_types = cert_key_types_;
388 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
389 std::string* proto) {
390 *proto = npn_proto_;
391 return npn_status_;
394 ChannelIDService*
395 SSLClientSocketOpenSSL::GetChannelIDService() const {
396 return channel_id_service_;
399 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
400 const base::StringPiece& label,
401 bool has_context, const base::StringPiece& context,
402 unsigned char* out, unsigned int outlen) {
403 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
405 int rv = SSL_export_keying_material(
406 ssl_, out, outlen, label.data(), label.size(),
407 reinterpret_cast<const unsigned char*>(context.data()),
408 context.length(), context.length() > 0);
410 if (rv != 1) {
411 int ssl_error = SSL_get_error(ssl_, rv);
412 LOG(ERROR) << "Failed to export keying material;"
413 << " returned " << rv
414 << ", SSL error code " << ssl_error;
415 return MapOpenSSLError(ssl_error, err_tracer);
417 return OK;
420 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
421 NOTIMPLEMENTED();
422 return ERR_NOT_IMPLEMENTED;
425 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
426 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
428 // Set up new ssl object.
429 int rv = Init();
430 if (rv != OK) {
431 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
432 return rv;
435 // Set SSL to client mode. Handshake happens in the loop below.
436 SSL_set_connect_state(ssl_);
438 GotoState(STATE_HANDSHAKE);
439 rv = DoHandshakeLoop(OK);
440 if (rv == ERR_IO_PENDING) {
441 user_connect_callback_ = callback;
442 } else {
443 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
446 return rv > OK ? OK : rv;
449 void SSLClientSocketOpenSSL::Disconnect() {
450 if (ssl_) {
451 // Calling SSL_shutdown prevents the session from being marked as
452 // unresumable.
453 SSL_shutdown(ssl_);
454 SSL_free(ssl_);
455 ssl_ = NULL;
457 if (transport_bio_) {
458 BIO_free_all(transport_bio_);
459 transport_bio_ = NULL;
462 // Shut down anything that may call us back.
463 verifier_.reset();
464 transport_->socket()->Disconnect();
466 // Null all callbacks, delete all buffers.
467 transport_send_busy_ = false;
468 send_buffer_ = NULL;
469 transport_recv_busy_ = false;
470 recv_buffer_ = NULL;
472 user_connect_callback_.Reset();
473 user_read_callback_.Reset();
474 user_write_callback_.Reset();
475 user_read_buf_ = NULL;
476 user_read_buf_len_ = 0;
477 user_write_buf_ = NULL;
478 user_write_buf_len_ = 0;
480 pending_read_error_ = kNoPendingReadResult;
481 transport_read_error_ = OK;
482 transport_write_error_ = OK;
484 server_cert_verify_result_.Reset();
485 completed_handshake_ = false;
487 cert_authorities_.clear();
488 cert_key_types_.clear();
489 client_auth_cert_needed_ = false;
491 npn_status_ = kNextProtoUnsupported;
492 npn_proto_.clear();
494 channel_id_xtn_negotiated_ = false;
495 channel_id_request_handle_.Cancel();
498 bool SSLClientSocketOpenSSL::IsConnected() const {
499 // If the handshake has not yet completed.
500 if (!completed_handshake_)
501 return false;
502 // If an asynchronous operation is still pending.
503 if (user_read_buf_.get() || user_write_buf_.get())
504 return true;
506 return transport_->socket()->IsConnected();
509 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
510 // If the handshake has not yet completed.
511 if (!completed_handshake_)
512 return false;
513 // If an asynchronous operation is still pending.
514 if (user_read_buf_.get() || user_write_buf_.get())
515 return false;
516 // If there is data waiting to be sent, or data read from the network that
517 // has not yet been consumed.
518 if (BIO_pending(transport_bio_) > 0 ||
519 BIO_wpending(transport_bio_) > 0) {
520 return false;
523 return transport_->socket()->IsConnectedAndIdle();
526 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
527 return transport_->socket()->GetPeerAddress(addressList);
530 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
531 return transport_->socket()->GetLocalAddress(addressList);
534 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
535 return net_log_;
538 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
539 if (transport_.get() && transport_->socket()) {
540 transport_->socket()->SetSubresourceSpeculation();
541 } else {
542 NOTREACHED();
546 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
547 if (transport_.get() && transport_->socket()) {
548 transport_->socket()->SetOmniboxSpeculation();
549 } else {
550 NOTREACHED();
554 bool SSLClientSocketOpenSSL::WasEverUsed() const {
555 return was_ever_used_;
558 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
559 if (transport_.get() && transport_->socket())
560 return transport_->socket()->UsingTCPFastOpen();
562 NOTREACHED();
563 return false;
566 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
567 ssl_info->Reset();
568 if (!server_cert_.get())
569 return false;
571 ssl_info->cert = server_cert_verify_result_.verified_cert;
572 ssl_info->cert_status = server_cert_verify_result_.cert_status;
573 ssl_info->is_issued_by_known_root =
574 server_cert_verify_result_.is_issued_by_known_root;
575 ssl_info->public_key_hashes =
576 server_cert_verify_result_.public_key_hashes;
577 ssl_info->client_cert_sent =
578 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
579 ssl_info->channel_id_sent = WasChannelIDSent();
581 RecordChannelIDSupport(channel_id_service_,
582 channel_id_xtn_negotiated_,
583 ssl_config_.channel_id_enabled,
584 crypto::ECPrivateKey::IsSupported());
586 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
587 CHECK(cipher);
588 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
590 ssl_info->connection_status = EncodeSSLConnectionStatus(
591 SSL_CIPHER_get_id(cipher), 0 /* no compression */,
592 GetNetSSLVersion(ssl_));
594 bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
595 if (!peer_supports_renego_ext)
596 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
597 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
598 implicit_cast<int>(peer_supports_renego_ext), 2);
600 if (ssl_config_.version_fallback)
601 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
603 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
604 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
606 DVLOG(3) << "Encoded connection status: cipher suite = "
607 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
608 << " version = "
609 << SSLConnectionStatusToVersion(ssl_info->connection_status);
610 return true;
613 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
614 int buf_len,
615 const CompletionCallback& callback) {
616 user_read_buf_ = buf;
617 user_read_buf_len_ = buf_len;
619 int rv = DoReadLoop(OK);
621 if (rv == ERR_IO_PENDING) {
622 user_read_callback_ = callback;
623 } else {
624 if (rv > 0)
625 was_ever_used_ = true;
626 user_read_buf_ = NULL;
627 user_read_buf_len_ = 0;
630 return rv;
633 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
634 int buf_len,
635 const CompletionCallback& callback) {
636 user_write_buf_ = buf;
637 user_write_buf_len_ = buf_len;
639 int rv = DoWriteLoop(OK);
641 if (rv == ERR_IO_PENDING) {
642 user_write_callback_ = callback;
643 } else {
644 if (rv > 0)
645 was_ever_used_ = true;
646 user_write_buf_ = NULL;
647 user_write_buf_len_ = 0;
650 return rv;
653 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
654 return transport_->socket()->SetReceiveBufferSize(size);
657 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
658 return transport_->socket()->SetSendBufferSize(size);
661 int SSLClientSocketOpenSSL::Init() {
662 DCHECK(!ssl_);
663 DCHECK(!transport_bio_);
665 SSLContext* context = SSLContext::GetInstance();
666 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
668 ssl_ = SSL_new(context->ssl_ctx());
669 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
670 return ERR_UNEXPECTED;
672 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
673 return ERR_UNEXPECTED;
675 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
676 ssl_, GetSocketSessionCacheKey(*this));
678 BIO* ssl_bio = NULL;
679 // 0 => use default buffer sizes.
680 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
681 return ERR_UNEXPECTED;
682 DCHECK(ssl_bio);
683 DCHECK(transport_bio_);
685 // Install a callback on OpenSSL's end to plumb transport errors through.
686 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
687 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
689 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
691 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
692 // set everything we care about to an absolute value.
693 SslSetClearMask options;
694 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
695 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
696 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
697 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
698 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
699 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
700 bool tls1_1_enabled =
701 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
702 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
703 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
704 bool tls1_2_enabled =
705 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
706 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
707 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
709 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
711 // TODO(joth): Set this conditionally, see http://crbug.com/55410
712 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
714 SSL_set_options(ssl_, options.set_mask);
715 SSL_clear_options(ssl_, options.clear_mask);
717 // Same as above, this time for the SSL mode.
718 SslSetClearMask mode;
720 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
722 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
723 ssl_config_.false_start_enabled);
725 SSL_set_mode(ssl_, mode.set_mask);
726 SSL_clear_mode(ssl_, mode.clear_mask);
728 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
729 // textual name with SSL_set_cipher_list because there is no public API to
730 // directly remove a cipher by ID.
731 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
732 DCHECK(ciphers);
733 // See SSLConfig::disabled_cipher_suites for description of the suites
734 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
735 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
736 // as the handshake hash.
737 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
738 "!aECDH:!AESGCM+AES256");
739 // Walk through all the installed ciphers, seeing if any need to be
740 // appended to the cipher removal |command|.
741 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
742 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
743 const uint16 id = SSL_CIPHER_get_id(cipher);
744 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
745 // implementation uses "effective" bits here but OpenSSL does not provide
746 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
747 // both of which are greater than 80 anyway.
748 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
749 if (!disable) {
750 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
751 ssl_config_.disabled_cipher_suites.end(), id) !=
752 ssl_config_.disabled_cipher_suites.end();
754 if (disable) {
755 const char* name = SSL_CIPHER_get_name(cipher);
756 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
757 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
758 command.append(":!");
759 command.append(name);
762 int rv = SSL_set_cipher_list(ssl_, command.c_str());
763 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
764 // This will almost certainly result in the socket failing to complete the
765 // handshake at which point the appropriate error is bubbled up to the client.
766 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
767 "returned " << rv;
769 if (ssl_config_.version_fallback)
770 SSL_enable_fallback_scsv(ssl_);
772 // TLS channel ids.
773 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
774 SSL_enable_tls_channel_id(ssl_);
777 if (!ssl_config_.next_protos.empty()) {
778 std::vector<uint8_t> wire_protos =
779 SerializeNextProtos(ssl_config_.next_protos);
780 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
781 wire_protos.size());
784 return OK;
787 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
788 // Since Run may result in Read being called, clear |user_read_callback_|
789 // up front.
790 if (rv > 0)
791 was_ever_used_ = true;
792 user_read_buf_ = NULL;
793 user_read_buf_len_ = 0;
794 base::ResetAndReturn(&user_read_callback_).Run(rv);
797 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
798 // Since Run may result in Write being called, clear |user_write_callback_|
799 // up front.
800 if (rv > 0)
801 was_ever_used_ = true;
802 user_write_buf_ = NULL;
803 user_write_buf_len_ = 0;
804 base::ResetAndReturn(&user_write_callback_).Run(rv);
807 bool SSLClientSocketOpenSSL::DoTransportIO() {
808 bool network_moved = false;
809 int rv;
810 // Read and write as much data as possible. The loop is necessary because
811 // Write() may return synchronously.
812 do {
813 rv = BufferSend();
814 if (rv != ERR_IO_PENDING && rv != 0)
815 network_moved = true;
816 } while (rv > 0);
817 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
818 network_moved = true;
819 return network_moved;
822 int SSLClientSocketOpenSSL::DoHandshake() {
823 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
824 int net_error = OK;
825 int rv = SSL_do_handshake(ssl_);
827 if (client_auth_cert_needed_) {
828 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
829 // If the handshake already succeeded (because the server requests but
830 // doesn't require a client cert), we need to invalidate the SSL session
831 // so that we won't try to resume the non-client-authenticated session in
832 // the next handshake. This will cause the server to ask for a client
833 // cert again.
834 if (rv == 1) {
835 // Remove from session cache but don't clear this connection.
836 SSL_SESSION* session = SSL_get_session(ssl_);
837 if (session) {
838 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
839 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
842 } else if (rv == 1) {
843 if (trying_cached_session_ && logging::DEBUG_MODE) {
844 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
845 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
848 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
849 if (npn_status_ == kNextProtoUnsupported) {
850 const uint8_t* alpn_proto = NULL;
851 unsigned alpn_len = 0;
852 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
853 if (alpn_len > 0) {
854 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
855 npn_status_ = kNextProtoNegotiated;
859 // Verify the certificate.
860 const bool got_cert = !!UpdateServerCert();
861 DCHECK(got_cert);
862 net_log_.AddEvent(
863 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
864 base::Bind(&NetLogX509CertificateCallback,
865 base::Unretained(server_cert_.get())));
866 GotoState(STATE_VERIFY_CERT);
867 } else {
868 int ssl_error = SSL_get_error(ssl_, rv);
870 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
871 // The server supports channel ID. Stop to look one up before returning to
872 // the handshake.
873 channel_id_xtn_negotiated_ = true;
874 GotoState(STATE_CHANNEL_ID_LOOKUP);
875 return OK;
878 net_error = MapOpenSSLError(ssl_error, err_tracer);
880 // If not done, stay in this state
881 if (net_error == ERR_IO_PENDING) {
882 GotoState(STATE_HANDSHAKE);
883 } else {
884 LOG(ERROR) << "handshake failed; returned " << rv
885 << ", SSL error code " << ssl_error
886 << ", net_error " << net_error;
887 net_log_.AddEvent(
888 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
889 CreateNetLogSSLErrorCallback(net_error, ssl_error));
892 return net_error;
895 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
896 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
897 return channel_id_service_->GetOrCreateChannelID(
898 host_and_port_.host(),
899 &channel_id_private_key_,
900 &channel_id_cert_,
901 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
902 base::Unretained(this)),
903 &channel_id_request_handle_);
906 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
907 if (result < 0)
908 return result;
910 DCHECK_LT(0u, channel_id_private_key_.size());
911 // Decode key.
912 std::vector<uint8> encrypted_private_key_info;
913 std::vector<uint8> subject_public_key_info;
914 encrypted_private_key_info.assign(
915 channel_id_private_key_.data(),
916 channel_id_private_key_.data() + channel_id_private_key_.size());
917 subject_public_key_info.assign(
918 channel_id_cert_.data(),
919 channel_id_cert_.data() + channel_id_cert_.size());
920 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
921 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
922 ChannelIDService::kEPKIPassword,
923 encrypted_private_key_info,
924 subject_public_key_info));
925 if (!ec_private_key) {
926 LOG(ERROR) << "Failed to import Channel ID.";
927 return ERR_CHANNEL_ID_IMPORT_FAILED;
930 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
931 // type.
932 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
933 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
934 if (!rv) {
935 LOG(ERROR) << "Failed to set Channel ID.";
936 int err = SSL_get_error(ssl_, rv);
937 return MapOpenSSLError(err, err_tracer);
940 // Return to the handshake.
941 set_channel_id_sent(true);
942 GotoState(STATE_HANDSHAKE);
943 return OK;
946 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
947 DCHECK(server_cert_.get());
948 GotoState(STATE_VERIFY_CERT_COMPLETE);
950 CertStatus cert_status;
951 if (ssl_config_.IsAllowedBadCert(server_cert_.get(), &cert_status)) {
952 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
953 server_cert_verify_result_.Reset();
954 server_cert_verify_result_.cert_status = cert_status;
955 server_cert_verify_result_.verified_cert = server_cert_;
956 return OK;
959 int flags = 0;
960 if (ssl_config_.rev_checking_enabled)
961 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
962 if (ssl_config_.verify_ev_cert)
963 flags |= CertVerifier::VERIFY_EV_CERT;
964 if (ssl_config_.cert_io_enabled)
965 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
966 if (ssl_config_.rev_checking_required_local_anchors)
967 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
968 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
969 return verifier_->Verify(
970 server_cert_.get(),
971 host_and_port_.host(),
972 flags,
973 NULL /* no CRL set */,
974 &server_cert_verify_result_,
975 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
976 base::Unretained(this)),
977 net_log_);
980 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
981 verifier_.reset();
983 if (result == OK) {
984 // TODO(joth): Work out if we need to remember the intermediate CA certs
985 // when the server sends them to us, and do so here.
986 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
987 } else {
988 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
989 << " (" << result << ")";
992 completed_handshake_ = true;
993 // Exit DoHandshakeLoop and return the result to the caller to Connect.
994 DCHECK_EQ(STATE_NONE, next_handshake_state_);
995 return result;
998 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
999 if (!user_connect_callback_.is_null()) {
1000 CompletionCallback c = user_connect_callback_;
1001 user_connect_callback_.Reset();
1002 c.Run(rv > OK ? OK : rv);
1006 X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
1007 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
1008 server_cert_ = server_cert_chain_->AsOSChain();
1010 if (!server_cert_chain_->IsValid())
1011 DVLOG(1) << "UpdateServerCert received invalid certificate chain from peer";
1013 return server_cert_.get();
1016 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1017 int rv = DoHandshakeLoop(result);
1018 if (rv != ERR_IO_PENDING) {
1019 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1020 DoConnectCallback(rv);
1024 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1025 if (next_handshake_state_ == STATE_HANDSHAKE) {
1026 // In handshake phase.
1027 OnHandshakeIOComplete(result);
1028 return;
1031 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1032 // handshake is in progress.
1033 int rv_read = ERR_IO_PENDING;
1034 int rv_write = ERR_IO_PENDING;
1035 bool network_moved;
1036 do {
1037 if (user_read_buf_.get())
1038 rv_read = DoPayloadRead();
1039 if (user_write_buf_.get())
1040 rv_write = DoPayloadWrite();
1041 network_moved = DoTransportIO();
1042 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1043 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1045 // Performing the Read callback may cause |this| to be deleted. If this
1046 // happens, the Write callback should not be invoked. Guard against this by
1047 // holding a WeakPtr to |this| and ensuring it's still valid.
1048 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1049 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1050 DoReadCallback(rv_read);
1052 if (!guard.get())
1053 return;
1055 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1056 DoWriteCallback(rv_write);
1059 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1060 if (next_handshake_state_ == STATE_HANDSHAKE) {
1061 // In handshake phase.
1062 OnHandshakeIOComplete(result);
1063 return;
1066 // Network layer received some data, check if client requested to read
1067 // decrypted data.
1068 if (!user_read_buf_.get())
1069 return;
1071 int rv = DoReadLoop(result);
1072 if (rv != ERR_IO_PENDING)
1073 DoReadCallback(rv);
1076 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1077 int rv = last_io_result;
1078 do {
1079 // Default to STATE_NONE for next state.
1080 // (This is a quirk carried over from the windows
1081 // implementation. It makes reading the logs a bit harder.)
1082 // State handlers can and often do call GotoState just
1083 // to stay in the current state.
1084 State state = next_handshake_state_;
1085 GotoState(STATE_NONE);
1086 switch (state) {
1087 case STATE_HANDSHAKE:
1088 rv = DoHandshake();
1089 break;
1090 case STATE_CHANNEL_ID_LOOKUP:
1091 DCHECK_EQ(OK, rv);
1092 rv = DoChannelIDLookup();
1093 break;
1094 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1095 rv = DoChannelIDLookupComplete(rv);
1096 break;
1097 case STATE_VERIFY_CERT:
1098 DCHECK_EQ(OK, rv);
1099 rv = DoVerifyCert(rv);
1100 break;
1101 case STATE_VERIFY_CERT_COMPLETE:
1102 rv = DoVerifyCertComplete(rv);
1103 break;
1104 case STATE_NONE:
1105 default:
1106 rv = ERR_UNEXPECTED;
1107 NOTREACHED() << "unexpected state" << state;
1108 break;
1111 bool network_moved = DoTransportIO();
1112 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1113 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1114 // special case we keep looping even if rv is ERR_IO_PENDING because
1115 // the transport IO may allow DoHandshake to make progress.
1116 rv = OK; // This causes us to stay in the loop.
1118 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1119 return rv;
1122 int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1123 if (result < 0)
1124 return result;
1126 bool network_moved;
1127 int rv;
1128 do {
1129 rv = DoPayloadRead();
1130 network_moved = DoTransportIO();
1131 } while (rv == ERR_IO_PENDING && network_moved);
1133 return rv;
1136 int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1137 if (result < 0)
1138 return result;
1140 bool network_moved;
1141 int rv;
1142 do {
1143 rv = DoPayloadWrite();
1144 network_moved = DoTransportIO();
1145 } while (rv == ERR_IO_PENDING && network_moved);
1147 return rv;
1150 int SSLClientSocketOpenSSL::DoPayloadRead() {
1151 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1153 int rv;
1154 if (pending_read_error_ != kNoPendingReadResult) {
1155 rv = pending_read_error_;
1156 pending_read_error_ = kNoPendingReadResult;
1157 if (rv == 0) {
1158 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1159 rv, user_read_buf_->data());
1161 return rv;
1164 int total_bytes_read = 0;
1165 do {
1166 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1167 user_read_buf_len_ - total_bytes_read);
1168 if (rv > 0)
1169 total_bytes_read += rv;
1170 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1172 if (total_bytes_read == user_read_buf_len_) {
1173 rv = total_bytes_read;
1174 } else {
1175 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1176 // immediately, while the OpenSSL errors are still available in
1177 // thread-local storage. However, the handled/remapped error code should
1178 // only be returned if no application data was already read; if it was, the
1179 // error code should be deferred until the next call of DoPayloadRead.
1181 // If no data was read, |*next_result| will point to the return value of
1182 // this function. If at least some data was read, |*next_result| will point
1183 // to |pending_read_error_|, to be returned in a future call to
1184 // DoPayloadRead() (e.g.: after the current data is handled).
1185 int *next_result = &rv;
1186 if (total_bytes_read > 0) {
1187 pending_read_error_ = rv;
1188 rv = total_bytes_read;
1189 next_result = &pending_read_error_;
1192 if (client_auth_cert_needed_) {
1193 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1194 } else if (*next_result < 0) {
1195 int err = SSL_get_error(ssl_, *next_result);
1196 *next_result = MapOpenSSLError(err, err_tracer);
1197 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1198 // If at least some data was read from SSL_read(), do not treat
1199 // insufficient data as an error to return in the next call to
1200 // DoPayloadRead() - instead, let the call fall through to check
1201 // SSL_read() again. This is because DoTransportIO() may complete
1202 // in between the next call to DoPayloadRead(), and thus it is
1203 // important to check SSL_read() on subsequent invocations to see
1204 // if a complete record may now be read.
1205 *next_result = kNoPendingReadResult;
1210 if (rv >= 0) {
1211 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1212 user_read_buf_->data());
1214 return rv;
1217 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1218 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1219 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1221 if (rv >= 0) {
1222 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1223 user_write_buf_->data());
1224 return rv;
1227 int err = SSL_get_error(ssl_, rv);
1228 return MapOpenSSLError(err, err_tracer);
1231 int SSLClientSocketOpenSSL::BufferSend(void) {
1232 if (transport_send_busy_)
1233 return ERR_IO_PENDING;
1235 if (!send_buffer_.get()) {
1236 // Get a fresh send buffer out of the send BIO.
1237 size_t max_read = BIO_pending(transport_bio_);
1238 if (!max_read)
1239 return 0; // Nothing pending in the OpenSSL write BIO.
1240 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1241 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1242 DCHECK_GT(read_bytes, 0);
1243 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1246 int rv = transport_->socket()->Write(
1247 send_buffer_.get(),
1248 send_buffer_->BytesRemaining(),
1249 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1250 base::Unretained(this)));
1251 if (rv == ERR_IO_PENDING) {
1252 transport_send_busy_ = true;
1253 } else {
1254 TransportWriteComplete(rv);
1256 return rv;
1259 int SSLClientSocketOpenSSL::BufferRecv(void) {
1260 if (transport_recv_busy_)
1261 return ERR_IO_PENDING;
1263 // Determine how much was requested from |transport_bio_| that was not
1264 // actually available.
1265 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1266 if (requested == 0) {
1267 // This is not a perfect match of error codes, as no operation is
1268 // actually pending. However, returning 0 would be interpreted as
1269 // a possible sign of EOF, which is also an inappropriate match.
1270 return ERR_IO_PENDING;
1273 // Known Issue: While only reading |requested| data is the more correct
1274 // implementation, it has the downside of resulting in frequent reads:
1275 // One read for the SSL record header (~5 bytes) and one read for the SSL
1276 // record body. Rather than issuing these reads to the underlying socket
1277 // (and constantly allocating new IOBuffers), a single Read() request to
1278 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1279 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1280 // traffic, this over-subscribed Read()ing will not cause issues.
1281 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1282 if (!max_write)
1283 return ERR_IO_PENDING;
1285 recv_buffer_ = new IOBuffer(max_write);
1286 int rv = transport_->socket()->Read(
1287 recv_buffer_.get(),
1288 max_write,
1289 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1290 base::Unretained(this)));
1291 if (rv == ERR_IO_PENDING) {
1292 transport_recv_busy_ = true;
1293 } else {
1294 rv = TransportReadComplete(rv);
1296 return rv;
1299 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1300 transport_send_busy_ = false;
1301 TransportWriteComplete(result);
1302 OnSendComplete(result);
1305 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1306 result = TransportReadComplete(result);
1307 OnRecvComplete(result);
1310 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1311 DCHECK(ERR_IO_PENDING != result);
1312 if (result < 0) {
1313 // Record the error. Save it to be reported in a future read or write on
1314 // transport_bio_'s peer.
1315 transport_write_error_ = result;
1316 send_buffer_ = NULL;
1317 } else {
1318 DCHECK(send_buffer_.get());
1319 send_buffer_->DidConsume(result);
1320 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1321 if (send_buffer_->BytesRemaining() <= 0)
1322 send_buffer_ = NULL;
1326 int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1327 DCHECK(ERR_IO_PENDING != result);
1328 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1329 // does not report success.
1330 if (result == 0)
1331 result = ERR_CONNECTION_CLOSED;
1332 if (result < 0) {
1333 DVLOG(1) << "TransportReadComplete result " << result;
1334 // Received an error. Save it to be reported in a future read on
1335 // transport_bio_'s peer.
1336 transport_read_error_ = result;
1337 } else {
1338 DCHECK(recv_buffer_.get());
1339 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1340 // A write into a memory BIO should always succeed.
1341 DCHECK_EQ(result, ret);
1343 recv_buffer_ = NULL;
1344 transport_recv_busy_ = false;
1345 return result;
1348 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
1349 X509** x509,
1350 EVP_PKEY** pkey) {
1351 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1352 DCHECK(ssl == ssl_);
1353 DCHECK(*x509 == NULL);
1354 DCHECK(*pkey == NULL);
1356 #if defined(OS_IOS)
1357 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1358 LOG(WARNING) << "Client auth is not supported";
1359 #else // !defined(OS_IOS)
1360 if (!ssl_config_.send_client_cert) {
1361 // First pass: we know that a client certificate is needed, but we do not
1362 // have one at hand.
1363 client_auth_cert_needed_ = true;
1364 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1365 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
1366 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1367 unsigned char* str = NULL;
1368 int length = i2d_X509_NAME(ca_name, &str);
1369 cert_authorities_.push_back(std::string(
1370 reinterpret_cast<const char*>(str),
1371 static_cast<size_t>(length)));
1372 OPENSSL_free(str);
1375 const unsigned char* client_cert_types;
1376 size_t num_client_cert_types =
1377 SSL_get0_certificate_types(ssl, &client_cert_types);
1378 for (size_t i = 0; i < num_client_cert_types; i++) {
1379 cert_key_types_.push_back(
1380 static_cast<SSLClientCertType>(client_cert_types[i]));
1383 return -1; // Suspends handshake.
1386 // Second pass: a client certificate should have been selected.
1387 if (ssl_config_.client_cert.get()) {
1388 // TODO(davidben): Configure OpenSSL to also send the intermediates.
1389 ScopedX509 leaf_x509 =
1390 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1391 if (!leaf_x509) {
1392 LOG(WARNING) << "Failed to import certificate";
1393 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1394 return -1;
1397 // TODO(davidben): With Linux client auth support, this should be
1398 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1399 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1400 // net/ client auth API lacking a private key handle.
1401 #if defined(USE_OPENSSL_CERTS)
1402 crypto::ScopedEVP_PKEY privkey =
1403 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1404 ssl_config_.client_cert.get());
1405 #else // !defined(USE_OPENSSL_CERTS)
1406 crypto::ScopedEVP_PKEY privkey =
1407 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1408 #endif // defined(USE_OPENSSL_CERTS)
1409 if (!privkey) {
1410 // Could not find the private key. Fail the handshake and surface an
1411 // appropriate error to the caller.
1412 LOG(WARNING) << "Client cert found without private key";
1413 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1414 return -1;
1417 // TODO(joth): (copied from NSS) We should wait for server certificate
1418 // verification before sending our credentials. See http://crbug.com/13934
1419 *x509 = leaf_x509.release();
1420 *pkey = privkey.release();
1421 return 1;
1423 #endif // defined(OS_IOS)
1425 // Send no client certificate.
1426 return 0;
1429 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1430 if (!completed_handshake_) {
1431 // If the first handshake hasn't completed then we accept any certificates
1432 // because we verify after the handshake.
1433 return 1;
1436 CHECK(server_cert_.get());
1438 PeerCertificateChain chain(store_ctx->untrusted);
1439 if (chain.IsValid() && server_cert_->Equals(chain.AsOSChain()))
1440 return 1;
1442 if (!chain.IsValid())
1443 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1444 else
1445 LOG(ERROR) << "Server certificate changed between handshakes";
1446 return 0;
1449 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1450 // server supports NPN, selects a protocol from the list that the server
1451 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1452 // callback can assume that |in| is syntactically valid.
1453 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1454 unsigned char* outlen,
1455 const unsigned char* in,
1456 unsigned int inlen) {
1457 if (ssl_config_.next_protos.empty()) {
1458 *out = reinterpret_cast<uint8*>(
1459 const_cast<char*>(kDefaultSupportedNPNProtocol));
1460 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1461 npn_status_ = kNextProtoUnsupported;
1462 return SSL_TLSEXT_ERR_OK;
1465 // Assume there's no overlap between our protocols and the server's list.
1466 npn_status_ = kNextProtoNoOverlap;
1468 // For each protocol in server preference order, see if we support it.
1469 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1470 for (std::vector<std::string>::const_iterator
1471 j = ssl_config_.next_protos.begin();
1472 j != ssl_config_.next_protos.end(); ++j) {
1473 if (in[i] == j->size() &&
1474 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
1475 // We found a match.
1476 *out = const_cast<unsigned char*>(in) + i + 1;
1477 *outlen = in[i];
1478 npn_status_ = kNextProtoNegotiated;
1479 break;
1482 if (npn_status_ == kNextProtoNegotiated)
1483 break;
1486 // If we didn't find a protocol, we select the first one from our list.
1487 if (npn_status_ == kNextProtoNoOverlap) {
1488 *out = reinterpret_cast<uint8*>(const_cast<char*>(
1489 ssl_config_.next_protos[0].data()));
1490 *outlen = ssl_config_.next_protos[0].size();
1493 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
1494 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
1495 return SSL_TLSEXT_ERR_OK;
1498 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1499 BIO *bio,
1500 int cmd,
1501 const char *argp, int argi, long argl,
1502 long retvalue) {
1503 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1504 // If there is no more data in the buffer, report any pending errors that
1505 // were observed. Note that both the readbuf and the writebuf are checked
1506 // for errors, since the application may have encountered a socket error
1507 // while writing that would otherwise not be reported until the application
1508 // attempted to write again - which it may never do. See
1509 // https://crbug.com/249848.
1510 if (transport_read_error_ != OK) {
1511 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1512 return -1;
1514 if (transport_write_error_ != OK) {
1515 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1516 return -1;
1518 } else if (cmd == BIO_CB_WRITE) {
1519 // Because of the write buffer, this reports a failure from the previous
1520 // write payload. If the current payload fails to write, the error will be
1521 // reported in a future write or read to |bio|.
1522 if (transport_write_error_ != OK) {
1523 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1524 return -1;
1527 return retvalue;
1530 // static
1531 long SSLClientSocketOpenSSL::BIOCallback(
1532 BIO *bio,
1533 int cmd,
1534 const char *argp, int argi, long argl,
1535 long retvalue) {
1536 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1537 BIO_get_callback_arg(bio));
1538 CHECK(socket);
1539 return socket->MaybeReplayTransportError(
1540 bio, cmd, argp, argi, argl, retvalue);
1543 scoped_refptr<X509Certificate>
1544 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1545 return server_cert_;
1548 } // namespace net