Adding Baseframework of the ResourceManager (all hooks and observers)
[chromium-blink-merge.git] / net / socket / ssl_client_socket_openssl.cc
blob8b5e25a84ae5eaa7dd829eaa3b7e942eb0cd5fde
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_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 void FreeX509Stack(STACK_OF(X509)* ptr) {
61 sk_X509_pop_free(ptr, X509_free);
64 typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
65 typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
66 ScopedX509Stack;
68 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
69 // This method doesn't seem to have made it into the OpenSSL headers.
70 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
71 #endif
73 // Used for encoding the |connection_status| field of an SSLInfo object.
74 int EncodeSSLConnectionStatus(int cipher_suite,
75 int compression,
76 int version) {
77 return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
78 SSL_CONNECTION_CIPHERSUITE_SHIFT) |
79 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
80 SSL_CONNECTION_COMPRESSION_SHIFT) |
81 ((version & SSL_CONNECTION_VERSION_MASK) <<
82 SSL_CONNECTION_VERSION_SHIFT);
85 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
86 // this SSL connection.
87 int GetNetSSLVersion(SSL* ssl) {
88 switch (SSL_version(ssl)) {
89 case SSL2_VERSION:
90 return SSL_CONNECTION_VERSION_SSL2;
91 case SSL3_VERSION:
92 return SSL_CONNECTION_VERSION_SSL3;
93 case TLS1_VERSION:
94 return SSL_CONNECTION_VERSION_TLS1;
95 case 0x0302:
96 return SSL_CONNECTION_VERSION_TLS1_1;
97 case 0x0303:
98 return SSL_CONNECTION_VERSION_TLS1_2;
99 default:
100 return SSL_CONNECTION_VERSION_UNKNOWN;
104 ScopedX509 OSCertHandleToOpenSSL(
105 X509Certificate::OSCertHandle os_handle) {
106 #if defined(USE_OPENSSL_CERTS)
107 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
108 #else // !defined(USE_OPENSSL_CERTS)
109 std::string der_encoded;
110 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
111 return ScopedX509();
112 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
113 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
114 #endif // defined(USE_OPENSSL_CERTS)
117 ScopedX509Stack OSCertHandlesToOpenSSL(
118 const X509Certificate::OSCertHandles& os_handles) {
119 ScopedX509Stack stack(sk_X509_new_null());
120 for (size_t i = 0; i < os_handles.size(); i++) {
121 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
122 if (!x509)
123 return ScopedX509Stack();
124 sk_X509_push(stack.get(), x509.release());
126 return stack.Pass();
129 } // namespace
131 class SSLClientSocketOpenSSL::SSLContext {
132 public:
133 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
134 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
135 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
137 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
138 DCHECK(ssl);
139 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
140 SSL_get_ex_data(ssl, ssl_socket_data_index_));
141 DCHECK(socket);
142 return socket;
145 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
146 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
149 private:
150 friend struct DefaultSingletonTraits<SSLContext>;
152 SSLContext() {
153 crypto::EnsureOpenSSLInit();
154 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
155 DCHECK_NE(ssl_socket_data_index_, -1);
156 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
157 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
158 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
159 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
160 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
161 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
162 // It would be better if the callback were not a global setting,
163 // but that is an OpenSSL issue.
164 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
165 NULL);
166 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
169 static std::string GetSessionCacheKey(const SSL* ssl) {
170 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
171 DCHECK(socket);
172 return socket->GetSessionCacheKey();
175 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
177 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
178 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
179 DCHECK(socket);
180 return socket->ClientCertRequestCallback(ssl);
183 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
184 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
185 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
186 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
187 CHECK(socket);
189 return socket->CertVerifyCallback(store_ctx);
192 static int SelectNextProtoCallback(SSL* ssl,
193 unsigned char** out, unsigned char* outlen,
194 const unsigned char* in,
195 unsigned int inlen, void* arg) {
196 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
197 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
200 // This is the index used with SSL_get_ex_data to retrieve the owner
201 // SSLClientSocketOpenSSL object from an SSL instance.
202 int ssl_socket_data_index_;
204 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
205 // |session_cache_| must be destroyed before |ssl_ctx_|.
206 SSLSessionCacheOpenSSL session_cache_;
209 // PeerCertificateChain is a helper object which extracts the certificate
210 // chain, as given by the server, from an OpenSSL socket and performs the needed
211 // resource management. The first element of the chain is the leaf certificate
212 // and the other elements are in the order given by the server.
213 class SSLClientSocketOpenSSL::PeerCertificateChain {
214 public:
215 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
216 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
217 ~PeerCertificateChain() {}
218 PeerCertificateChain& operator=(const PeerCertificateChain& other);
220 // Resets the PeerCertificateChain to the set of certificates in|chain|,
221 // which may be NULL, indicating to empty the store certificates.
222 // Note: If an error occurs, such as being unable to parse the certificates,
223 // this will behave as if Reset(NULL) was called.
224 void Reset(STACK_OF(X509)* chain);
226 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
227 const scoped_refptr<X509Certificate>& AsOSChain() const { return os_chain_; }
229 size_t size() const {
230 if (!openssl_chain_.get())
231 return 0;
232 return sk_X509_num(openssl_chain_.get());
235 X509* operator[](size_t index) const {
236 DCHECK_LT(index, size());
237 return sk_X509_value(openssl_chain_.get(), index);
240 bool IsValid() { return os_chain_.get() && openssl_chain_.get(); }
242 private:
243 ScopedX509Stack openssl_chain_;
245 scoped_refptr<X509Certificate> os_chain_;
248 SSLClientSocketOpenSSL::PeerCertificateChain&
249 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
250 const PeerCertificateChain& other) {
251 if (this == &other)
252 return *this;
254 // os_chain_ is reference counted by scoped_refptr;
255 os_chain_ = other.os_chain_;
257 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
259 return *this;
262 #if defined(USE_OPENSSL_CERTS)
263 // When OSCertHandle is typedef'ed to X509, this implementation does a short cut
264 // to avoid converting back and forth between der and X509 struct.
265 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
266 STACK_OF(X509)* chain) {
267 openssl_chain_.reset(NULL);
268 os_chain_ = NULL;
270 if (!chain)
271 return;
273 X509Certificate::OSCertHandles intermediates;
274 for (size_t i = 1; i < sk_X509_num(chain); ++i)
275 intermediates.push_back(sk_X509_value(chain, i));
277 os_chain_ =
278 X509Certificate::CreateFromHandle(sk_X509_value(chain, 0), intermediates);
280 openssl_chain_.reset(X509_chain_up_ref(chain));
282 #else // !defined(USE_OPENSSL_CERTS)
283 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
284 STACK_OF(X509)* chain) {
285 openssl_chain_.reset(NULL);
286 os_chain_ = NULL;
288 if (!chain)
289 return;
291 openssl_chain_.reset(X509_chain_up_ref(chain));
293 std::vector<base::StringPiece> der_chain;
294 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
295 X509* x = sk_X509_value(openssl_chain_.get(), i);
297 unsigned char* cert_data = NULL;
298 int cert_data_length = i2d_X509(x, &cert_data);
299 if (cert_data_length && cert_data)
300 der_chain.push_back(base::StringPiece(reinterpret_cast<char*>(cert_data),
301 cert_data_length));
304 os_chain_ = X509Certificate::CreateFromDERCertChain(der_chain);
306 for (size_t i = 0; i < der_chain.size(); ++i) {
307 OPENSSL_free(const_cast<char*>(der_chain[i].data()));
310 if (der_chain.size() !=
311 static_cast<size_t>(sk_X509_num(openssl_chain_.get()))) {
312 openssl_chain_.reset(NULL);
313 os_chain_ = NULL;
316 #endif // defined(USE_OPENSSL_CERTS)
318 // static
319 SSLSessionCacheOpenSSL::Config
320 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
321 &GetSessionCacheKey, // key_func
322 1024, // max_entries
323 256, // expiration_check_count
324 60 * 60, // timeout_seconds
327 // static
328 void SSLClientSocket::ClearSessionCache() {
329 SSLClientSocketOpenSSL::SSLContext* context =
330 SSLClientSocketOpenSSL::SSLContext::GetInstance();
331 context->session_cache()->Flush();
334 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
335 scoped_ptr<ClientSocketHandle> transport_socket,
336 const HostPortPair& host_and_port,
337 const SSLConfig& ssl_config,
338 const SSLClientSocketContext& context)
339 : transport_send_busy_(false),
340 transport_recv_busy_(false),
341 weak_factory_(this),
342 pending_read_error_(kNoPendingReadResult),
343 transport_read_error_(OK),
344 transport_write_error_(OK),
345 server_cert_chain_(new PeerCertificateChain(NULL)),
346 completed_connect_(false),
347 was_ever_used_(false),
348 client_auth_cert_needed_(false),
349 cert_verifier_(context.cert_verifier),
350 channel_id_service_(context.channel_id_service),
351 ssl_(NULL),
352 transport_bio_(NULL),
353 transport_(transport_socket.Pass()),
354 host_and_port_(host_and_port),
355 ssl_config_(ssl_config),
356 ssl_session_cache_shard_(context.ssl_session_cache_shard),
357 trying_cached_session_(false),
358 next_handshake_state_(STATE_NONE),
359 npn_status_(kNextProtoUnsupported),
360 channel_id_xtn_negotiated_(false),
361 handshake_succeeded_(false),
362 marked_session_as_good_(false),
363 transport_security_state_(context.transport_security_state),
364 net_log_(transport_->socket()->NetLog()) {
367 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
368 Disconnect();
371 std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
372 std::string result = host_and_port_.ToString();
373 result.append("/");
374 result.append(ssl_session_cache_shard_);
375 return result;
378 bool SSLClientSocketOpenSSL::InSessionCache() const {
379 SSLContext* context = SSLContext::GetInstance();
380 std::string cache_key = GetSessionCacheKey();
381 return context->session_cache()->SSLSessionIsInCache(cache_key);
384 void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
385 const base::Closure& callback) {
386 handshake_completion_callback_ = callback;
389 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
390 SSLCertRequestInfo* cert_request_info) {
391 cert_request_info->host_and_port = host_and_port_;
392 cert_request_info->cert_authorities = cert_authorities_;
393 cert_request_info->cert_key_types = cert_key_types_;
396 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
397 std::string* proto) {
398 *proto = npn_proto_;
399 return npn_status_;
402 ChannelIDService*
403 SSLClientSocketOpenSSL::GetChannelIDService() const {
404 return channel_id_service_;
407 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
408 const base::StringPiece& label,
409 bool has_context, const base::StringPiece& context,
410 unsigned char* out, unsigned int outlen) {
411 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
413 int rv = SSL_export_keying_material(
414 ssl_, out, outlen, label.data(), label.size(),
415 reinterpret_cast<const unsigned char*>(context.data()),
416 context.length(), context.length() > 0);
418 if (rv != 1) {
419 int ssl_error = SSL_get_error(ssl_, rv);
420 LOG(ERROR) << "Failed to export keying material;"
421 << " returned " << rv
422 << ", SSL error code " << ssl_error;
423 return MapOpenSSLError(ssl_error, err_tracer);
425 return OK;
428 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
429 NOTIMPLEMENTED();
430 return ERR_NOT_IMPLEMENTED;
433 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
434 // It is an error to create an SSLClientSocket whose context has no
435 // TransportSecurityState.
436 DCHECK(transport_security_state_);
438 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
440 // Set up new ssl object.
441 int rv = Init();
442 if (rv != OK) {
443 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
444 return rv;
447 // Set SSL to client mode. Handshake happens in the loop below.
448 SSL_set_connect_state(ssl_);
450 GotoState(STATE_HANDSHAKE);
451 rv = DoHandshakeLoop(OK);
452 if (rv == ERR_IO_PENDING) {
453 user_connect_callback_ = callback;
454 } else {
455 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
456 if (rv < OK)
457 OnHandshakeCompletion();
460 return rv > OK ? OK : rv;
463 void SSLClientSocketOpenSSL::Disconnect() {
464 // If a handshake was pending (Connect() had been called), notify interested
465 // parties that it's been aborted now. If the handshake had already
466 // completed, this is a no-op.
467 OnHandshakeCompletion();
468 if (ssl_) {
469 // Calling SSL_shutdown prevents the session from being marked as
470 // unresumable.
471 SSL_shutdown(ssl_);
472 SSL_free(ssl_);
473 ssl_ = NULL;
475 if (transport_bio_) {
476 BIO_free_all(transport_bio_);
477 transport_bio_ = NULL;
480 // Shut down anything that may call us back.
481 verifier_.reset();
482 transport_->socket()->Disconnect();
484 // Null all callbacks, delete all buffers.
485 transport_send_busy_ = false;
486 send_buffer_ = NULL;
487 transport_recv_busy_ = false;
488 recv_buffer_ = NULL;
490 user_connect_callback_.Reset();
491 user_read_callback_.Reset();
492 user_write_callback_.Reset();
493 user_read_buf_ = NULL;
494 user_read_buf_len_ = 0;
495 user_write_buf_ = NULL;
496 user_write_buf_len_ = 0;
498 pending_read_error_ = kNoPendingReadResult;
499 transport_read_error_ = OK;
500 transport_write_error_ = OK;
502 server_cert_verify_result_.Reset();
503 completed_connect_ = false;
505 cert_authorities_.clear();
506 cert_key_types_.clear();
507 client_auth_cert_needed_ = false;
509 start_cert_verification_time_ = base::TimeTicks();
511 npn_status_ = kNextProtoUnsupported;
512 npn_proto_.clear();
514 channel_id_xtn_negotiated_ = false;
515 channel_id_request_handle_.Cancel();
518 bool SSLClientSocketOpenSSL::IsConnected() const {
519 // If the handshake has not yet completed.
520 if (!completed_connect_)
521 return false;
522 // If an asynchronous operation is still pending.
523 if (user_read_buf_.get() || user_write_buf_.get())
524 return true;
526 return transport_->socket()->IsConnected();
529 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
530 // If the handshake has not yet completed.
531 if (!completed_connect_)
532 return false;
533 // If an asynchronous operation is still pending.
534 if (user_read_buf_.get() || user_write_buf_.get())
535 return false;
536 // If there is data waiting to be sent, or data read from the network that
537 // has not yet been consumed.
538 if (BIO_pending(transport_bio_) > 0 ||
539 BIO_wpending(transport_bio_) > 0) {
540 return false;
543 return transport_->socket()->IsConnectedAndIdle();
546 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
547 return transport_->socket()->GetPeerAddress(addressList);
550 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
551 return transport_->socket()->GetLocalAddress(addressList);
554 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
555 return net_log_;
558 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
559 if (transport_.get() && transport_->socket()) {
560 transport_->socket()->SetSubresourceSpeculation();
561 } else {
562 NOTREACHED();
566 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
567 if (transport_.get() && transport_->socket()) {
568 transport_->socket()->SetOmniboxSpeculation();
569 } else {
570 NOTREACHED();
574 bool SSLClientSocketOpenSSL::WasEverUsed() const {
575 return was_ever_used_;
578 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
579 if (transport_.get() && transport_->socket())
580 return transport_->socket()->UsingTCPFastOpen();
582 NOTREACHED();
583 return false;
586 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
587 ssl_info->Reset();
588 if (!server_cert_.get())
589 return false;
591 ssl_info->cert = server_cert_verify_result_.verified_cert;
592 ssl_info->cert_status = server_cert_verify_result_.cert_status;
593 ssl_info->is_issued_by_known_root =
594 server_cert_verify_result_.is_issued_by_known_root;
595 ssl_info->public_key_hashes =
596 server_cert_verify_result_.public_key_hashes;
597 ssl_info->client_cert_sent =
598 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
599 ssl_info->channel_id_sent = WasChannelIDSent();
600 ssl_info->pinning_failure_log = pinning_failure_log_;
602 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
603 CHECK(cipher);
604 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
606 ssl_info->connection_status = EncodeSSLConnectionStatus(
607 SSL_CIPHER_get_id(cipher), 0 /* no compression */,
608 GetNetSSLVersion(ssl_));
610 if (!SSL_get_secure_renegotiation_support(ssl_))
611 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
613 if (ssl_config_.version_fallback)
614 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
616 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
617 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
619 DVLOG(3) << "Encoded connection status: cipher suite = "
620 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
621 << " version = "
622 << SSLConnectionStatusToVersion(ssl_info->connection_status);
623 return true;
626 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
627 int buf_len,
628 const CompletionCallback& callback) {
629 user_read_buf_ = buf;
630 user_read_buf_len_ = buf_len;
632 int rv = DoReadLoop(OK);
634 if (rv == ERR_IO_PENDING) {
635 user_read_callback_ = callback;
636 } else {
637 if (rv > 0)
638 was_ever_used_ = true;
639 user_read_buf_ = NULL;
640 user_read_buf_len_ = 0;
641 if (rv <= 0) {
642 // Failure of a read attempt may indicate a failed false start
643 // connection.
644 OnHandshakeCompletion();
648 return rv;
651 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
652 int buf_len,
653 const CompletionCallback& callback) {
654 user_write_buf_ = buf;
655 user_write_buf_len_ = buf_len;
657 int rv = DoWriteLoop(OK);
659 if (rv == ERR_IO_PENDING) {
660 user_write_callback_ = callback;
661 } else {
662 if (rv > 0)
663 was_ever_used_ = true;
664 user_write_buf_ = NULL;
665 user_write_buf_len_ = 0;
666 if (rv < 0) {
667 // Failure of a write attempt may indicate a failed false start
668 // connection.
669 OnHandshakeCompletion();
673 return rv;
676 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
677 return transport_->socket()->SetReceiveBufferSize(size);
680 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
681 return transport_->socket()->SetSendBufferSize(size);
684 int SSLClientSocketOpenSSL::Init() {
685 DCHECK(!ssl_);
686 DCHECK(!transport_bio_);
688 SSLContext* context = SSLContext::GetInstance();
689 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
691 ssl_ = SSL_new(context->ssl_ctx());
692 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
693 return ERR_UNEXPECTED;
695 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
696 return ERR_UNEXPECTED;
698 // Set an OpenSSL callback to monitor this SSL*'s connection.
699 SSL_set_info_callback(ssl_, &InfoCallback);
701 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
702 ssl_, GetSessionCacheKey());
704 BIO* ssl_bio = NULL;
705 // 0 => use default buffer sizes.
706 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
707 return ERR_UNEXPECTED;
708 DCHECK(ssl_bio);
709 DCHECK(transport_bio_);
711 // Install a callback on OpenSSL's end to plumb transport errors through.
712 BIO_set_callback(ssl_bio, BIOCallback);
713 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
715 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
717 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
718 // set everything we care about to an absolute value.
719 SslSetClearMask options;
720 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
721 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
722 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
723 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
724 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
725 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
726 bool tls1_1_enabled =
727 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
728 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
729 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
730 bool tls1_2_enabled =
731 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
732 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
733 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
735 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
737 // TODO(joth): Set this conditionally, see http://crbug.com/55410
738 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
740 SSL_set_options(ssl_, options.set_mask);
741 SSL_clear_options(ssl_, options.clear_mask);
743 // Same as above, this time for the SSL mode.
744 SslSetClearMask mode;
746 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
747 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
749 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
750 ssl_config_.false_start_enabled);
752 SSL_set_mode(ssl_, mode.set_mask);
753 SSL_clear_mode(ssl_, mode.clear_mask);
755 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
756 // textual name with SSL_set_cipher_list because there is no public API to
757 // directly remove a cipher by ID.
758 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
759 DCHECK(ciphers);
760 // See SSLConfig::disabled_cipher_suites for description of the suites
761 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
762 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
763 // as the handshake hash.
764 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
765 "!aECDH:!AESGCM+AES256");
766 // Walk through all the installed ciphers, seeing if any need to be
767 // appended to the cipher removal |command|.
768 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
769 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
770 const uint16 id = SSL_CIPHER_get_id(cipher);
771 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
772 // implementation uses "effective" bits here but OpenSSL does not provide
773 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
774 // both of which are greater than 80 anyway.
775 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
776 if (!disable) {
777 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
778 ssl_config_.disabled_cipher_suites.end(), id) !=
779 ssl_config_.disabled_cipher_suites.end();
781 if (disable) {
782 const char* name = SSL_CIPHER_get_name(cipher);
783 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
784 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
785 command.append(":!");
786 command.append(name);
789 int rv = SSL_set_cipher_list(ssl_, command.c_str());
790 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
791 // This will almost certainly result in the socket failing to complete the
792 // handshake at which point the appropriate error is bubbled up to the client.
793 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
794 "returned " << rv;
796 if (ssl_config_.version_fallback)
797 SSL_enable_fallback_scsv(ssl_);
799 // TLS channel ids.
800 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
801 SSL_enable_tls_channel_id(ssl_);
804 if (!ssl_config_.next_protos.empty()) {
805 std::vector<uint8_t> wire_protos =
806 SerializeNextProtos(ssl_config_.next_protos);
807 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
808 wire_protos.size());
811 return OK;
814 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
815 // Since Run may result in Read being called, clear |user_read_callback_|
816 // up front.
817 if (rv > 0)
818 was_ever_used_ = true;
819 user_read_buf_ = NULL;
820 user_read_buf_len_ = 0;
821 if (rv <= 0) {
822 // Failure of a read attempt may indicate a failed false start
823 // connection.
824 OnHandshakeCompletion();
826 base::ResetAndReturn(&user_read_callback_).Run(rv);
829 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
830 // Since Run may result in Write being called, clear |user_write_callback_|
831 // up front.
832 if (rv > 0)
833 was_ever_used_ = true;
834 user_write_buf_ = NULL;
835 user_write_buf_len_ = 0;
836 if (rv < 0) {
837 // Failure of a write attempt may indicate a failed false start
838 // connection.
839 OnHandshakeCompletion();
841 base::ResetAndReturn(&user_write_callback_).Run(rv);
844 void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
845 if (!handshake_completion_callback_.is_null())
846 base::ResetAndReturn(&handshake_completion_callback_).Run();
849 bool SSLClientSocketOpenSSL::DoTransportIO() {
850 bool network_moved = false;
851 int rv;
852 // Read and write as much data as possible. The loop is necessary because
853 // Write() may return synchronously.
854 do {
855 rv = BufferSend();
856 if (rv != ERR_IO_PENDING && rv != 0)
857 network_moved = true;
858 } while (rv > 0);
859 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
860 network_moved = true;
861 return network_moved;
864 int SSLClientSocketOpenSSL::DoHandshake() {
865 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
866 int net_error = OK;
867 int rv = SSL_do_handshake(ssl_);
869 if (client_auth_cert_needed_) {
870 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
871 // If the handshake already succeeded (because the server requests but
872 // doesn't require a client cert), we need to invalidate the SSL session
873 // so that we won't try to resume the non-client-authenticated session in
874 // the next handshake. This will cause the server to ask for a client
875 // cert again.
876 if (rv == 1) {
877 // Remove from session cache but don't clear this connection.
878 SSL_SESSION* session = SSL_get_session(ssl_);
879 if (session) {
880 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
881 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
884 } else if (rv == 1) {
885 if (trying_cached_session_ && logging::DEBUG_MODE) {
886 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
887 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
890 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
891 if (npn_status_ == kNextProtoUnsupported) {
892 const uint8_t* alpn_proto = NULL;
893 unsigned alpn_len = 0;
894 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
895 if (alpn_len > 0) {
896 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
897 npn_status_ = kNextProtoNegotiated;
901 RecordChannelIDSupport(channel_id_service_,
902 channel_id_xtn_negotiated_,
903 ssl_config_.channel_id_enabled,
904 crypto::ECPrivateKey::IsSupported());
906 // Verify the certificate.
907 const bool got_cert = !!UpdateServerCert();
908 DCHECK(got_cert);
909 net_log_.AddEvent(
910 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
911 base::Bind(&NetLogX509CertificateCallback,
912 base::Unretained(server_cert_.get())));
913 GotoState(STATE_VERIFY_CERT);
914 } else {
915 int ssl_error = SSL_get_error(ssl_, rv);
917 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
918 // The server supports channel ID. Stop to look one up before returning to
919 // the handshake.
920 channel_id_xtn_negotiated_ = true;
921 GotoState(STATE_CHANNEL_ID_LOOKUP);
922 return OK;
925 OpenSSLErrorInfo error_info;
926 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
928 // If not done, stay in this state
929 if (net_error == ERR_IO_PENDING) {
930 GotoState(STATE_HANDSHAKE);
931 } else {
932 LOG(ERROR) << "handshake failed; returned " << rv
933 << ", SSL error code " << ssl_error
934 << ", net_error " << net_error;
935 net_log_.AddEvent(
936 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
937 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
940 return net_error;
943 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
944 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
945 return channel_id_service_->GetOrCreateChannelID(
946 host_and_port_.host(),
947 &channel_id_private_key_,
948 &channel_id_cert_,
949 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
950 base::Unretained(this)),
951 &channel_id_request_handle_);
954 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
955 if (result < 0)
956 return result;
958 DCHECK_LT(0u, channel_id_private_key_.size());
959 // Decode key.
960 std::vector<uint8> encrypted_private_key_info;
961 std::vector<uint8> subject_public_key_info;
962 encrypted_private_key_info.assign(
963 channel_id_private_key_.data(),
964 channel_id_private_key_.data() + channel_id_private_key_.size());
965 subject_public_key_info.assign(
966 channel_id_cert_.data(),
967 channel_id_cert_.data() + channel_id_cert_.size());
968 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
969 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
970 ChannelIDService::kEPKIPassword,
971 encrypted_private_key_info,
972 subject_public_key_info));
973 if (!ec_private_key) {
974 LOG(ERROR) << "Failed to import Channel ID.";
975 return ERR_CHANNEL_ID_IMPORT_FAILED;
978 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
979 // type.
980 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
981 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
982 if (!rv) {
983 LOG(ERROR) << "Failed to set Channel ID.";
984 int err = SSL_get_error(ssl_, rv);
985 return MapOpenSSLError(err, err_tracer);
988 // Return to the handshake.
989 set_channel_id_sent(true);
990 GotoState(STATE_HANDSHAKE);
991 return OK;
994 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
995 DCHECK(server_cert_.get());
996 DCHECK(start_cert_verification_time_.is_null());
997 GotoState(STATE_VERIFY_CERT_COMPLETE);
999 CertStatus cert_status;
1000 if (ssl_config_.IsAllowedBadCert(server_cert_.get(), &cert_status)) {
1001 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1002 server_cert_verify_result_.Reset();
1003 server_cert_verify_result_.cert_status = cert_status;
1004 server_cert_verify_result_.verified_cert = server_cert_;
1005 return OK;
1008 start_cert_verification_time_ = base::TimeTicks::Now();
1010 int flags = 0;
1011 if (ssl_config_.rev_checking_enabled)
1012 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1013 if (ssl_config_.verify_ev_cert)
1014 flags |= CertVerifier::VERIFY_EV_CERT;
1015 if (ssl_config_.cert_io_enabled)
1016 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1017 if (ssl_config_.rev_checking_required_local_anchors)
1018 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1019 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1020 return verifier_->Verify(
1021 server_cert_.get(),
1022 host_and_port_.host(),
1023 flags,
1024 // TODO(davidben): Route the CRLSet through SSLConfig so
1025 // SSLClientSocket doesn't depend on SSLConfigService.
1026 SSLConfigService::GetCRLSet().get(),
1027 &server_cert_verify_result_,
1028 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1029 base::Unretained(this)),
1030 net_log_);
1033 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1034 verifier_.reset();
1036 if (!start_cert_verification_time_.is_null()) {
1037 base::TimeDelta verify_time =
1038 base::TimeTicks::Now() - start_cert_verification_time_;
1039 if (result == OK) {
1040 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1041 } else {
1042 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1046 bool sni_available = ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1 ||
1047 ssl_config_.version_fallback;
1048 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1049 if (transport_security_state_ &&
1050 (result == OK ||
1051 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1052 !transport_security_state_->CheckPublicKeyPins(
1053 host_and_port_.host(),
1054 sni_available,
1055 server_cert_verify_result_.is_issued_by_known_root,
1056 server_cert_verify_result_.public_key_hashes,
1057 &pinning_failure_log_)) {
1058 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1061 if (result == OK) {
1062 // TODO(joth): Work out if we need to remember the intermediate CA certs
1063 // when the server sends them to us, and do so here.
1064 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
1065 marked_session_as_good_ = true;
1066 CheckIfHandshakeFinished();
1067 } else {
1068 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1069 << " (" << result << ")";
1072 completed_connect_ = true;
1074 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1075 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1076 return result;
1079 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1080 if (rv < OK)
1081 OnHandshakeCompletion();
1082 if (!user_connect_callback_.is_null()) {
1083 CompletionCallback c = user_connect_callback_;
1084 user_connect_callback_.Reset();
1085 c.Run(rv > OK ? OK : rv);
1089 X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
1090 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
1091 server_cert_ = server_cert_chain_->AsOSChain();
1093 if (!server_cert_chain_->IsValid())
1094 DVLOG(1) << "UpdateServerCert received invalid certificate chain from peer";
1096 return server_cert_.get();
1099 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1100 int rv = DoHandshakeLoop(result);
1101 if (rv != ERR_IO_PENDING) {
1102 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1103 DoConnectCallback(rv);
1107 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1108 if (next_handshake_state_ == STATE_HANDSHAKE) {
1109 // In handshake phase.
1110 OnHandshakeIOComplete(result);
1111 return;
1114 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1115 // handshake is in progress.
1116 int rv_read = ERR_IO_PENDING;
1117 int rv_write = ERR_IO_PENDING;
1118 bool network_moved;
1119 do {
1120 if (user_read_buf_.get())
1121 rv_read = DoPayloadRead();
1122 if (user_write_buf_.get())
1123 rv_write = DoPayloadWrite();
1124 network_moved = DoTransportIO();
1125 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1126 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1128 // Performing the Read callback may cause |this| to be deleted. If this
1129 // happens, the Write callback should not be invoked. Guard against this by
1130 // holding a WeakPtr to |this| and ensuring it's still valid.
1131 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1132 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1133 DoReadCallback(rv_read);
1135 if (!guard.get())
1136 return;
1138 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1139 DoWriteCallback(rv_write);
1142 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1143 if (next_handshake_state_ == STATE_HANDSHAKE) {
1144 // In handshake phase.
1145 OnHandshakeIOComplete(result);
1146 return;
1149 // Network layer received some data, check if client requested to read
1150 // decrypted data.
1151 if (!user_read_buf_.get())
1152 return;
1154 int rv = DoReadLoop(result);
1155 if (rv != ERR_IO_PENDING)
1156 DoReadCallback(rv);
1159 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1160 int rv = last_io_result;
1161 do {
1162 // Default to STATE_NONE for next state.
1163 // (This is a quirk carried over from the windows
1164 // implementation. It makes reading the logs a bit harder.)
1165 // State handlers can and often do call GotoState just
1166 // to stay in the current state.
1167 State state = next_handshake_state_;
1168 GotoState(STATE_NONE);
1169 switch (state) {
1170 case STATE_HANDSHAKE:
1171 rv = DoHandshake();
1172 break;
1173 case STATE_CHANNEL_ID_LOOKUP:
1174 DCHECK_EQ(OK, rv);
1175 rv = DoChannelIDLookup();
1176 break;
1177 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1178 rv = DoChannelIDLookupComplete(rv);
1179 break;
1180 case STATE_VERIFY_CERT:
1181 DCHECK_EQ(OK, rv);
1182 rv = DoVerifyCert(rv);
1183 break;
1184 case STATE_VERIFY_CERT_COMPLETE:
1185 rv = DoVerifyCertComplete(rv);
1186 break;
1187 case STATE_NONE:
1188 default:
1189 rv = ERR_UNEXPECTED;
1190 NOTREACHED() << "unexpected state" << state;
1191 break;
1194 bool network_moved = DoTransportIO();
1195 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1196 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1197 // special case we keep looping even if rv is ERR_IO_PENDING because
1198 // the transport IO may allow DoHandshake to make progress.
1199 rv = OK; // This causes us to stay in the loop.
1201 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1203 return rv;
1206 int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1207 if (result < 0)
1208 return result;
1210 bool network_moved;
1211 int rv;
1212 do {
1213 rv = DoPayloadRead();
1214 network_moved = DoTransportIO();
1215 } while (rv == ERR_IO_PENDING && network_moved);
1217 return rv;
1220 int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1221 if (result < 0)
1222 return result;
1224 bool network_moved;
1225 int rv;
1226 do {
1227 rv = DoPayloadWrite();
1228 network_moved = DoTransportIO();
1229 } while (rv == ERR_IO_PENDING && network_moved);
1231 return rv;
1234 int SSLClientSocketOpenSSL::DoPayloadRead() {
1235 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1237 int rv;
1238 if (pending_read_error_ != kNoPendingReadResult) {
1239 rv = pending_read_error_;
1240 pending_read_error_ = kNoPendingReadResult;
1241 if (rv == 0) {
1242 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1243 rv, user_read_buf_->data());
1245 return rv;
1248 int total_bytes_read = 0;
1249 do {
1250 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1251 user_read_buf_len_ - total_bytes_read);
1252 if (rv > 0)
1253 total_bytes_read += rv;
1254 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1256 if (total_bytes_read == user_read_buf_len_) {
1257 rv = total_bytes_read;
1258 } else {
1259 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1260 // immediately, while the OpenSSL errors are still available in
1261 // thread-local storage. However, the handled/remapped error code should
1262 // only be returned if no application data was already read; if it was, the
1263 // error code should be deferred until the next call of DoPayloadRead.
1265 // If no data was read, |*next_result| will point to the return value of
1266 // this function. If at least some data was read, |*next_result| will point
1267 // to |pending_read_error_|, to be returned in a future call to
1268 // DoPayloadRead() (e.g.: after the current data is handled).
1269 int *next_result = &rv;
1270 if (total_bytes_read > 0) {
1271 pending_read_error_ = rv;
1272 rv = total_bytes_read;
1273 next_result = &pending_read_error_;
1276 if (client_auth_cert_needed_) {
1277 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1278 } else if (*next_result < 0) {
1279 int err = SSL_get_error(ssl_, *next_result);
1280 *next_result = MapOpenSSLError(err, err_tracer);
1281 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1282 // If at least some data was read from SSL_read(), do not treat
1283 // insufficient data as an error to return in the next call to
1284 // DoPayloadRead() - instead, let the call fall through to check
1285 // SSL_read() again. This is because DoTransportIO() may complete
1286 // in between the next call to DoPayloadRead(), and thus it is
1287 // important to check SSL_read() on subsequent invocations to see
1288 // if a complete record may now be read.
1289 *next_result = kNoPendingReadResult;
1294 if (rv >= 0) {
1295 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1296 user_read_buf_->data());
1298 return rv;
1301 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1302 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1303 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1304 if (rv >= 0) {
1305 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1306 user_write_buf_->data());
1307 return rv;
1310 int err = SSL_get_error(ssl_, rv);
1311 return MapOpenSSLError(err, err_tracer);
1314 int SSLClientSocketOpenSSL::BufferSend(void) {
1315 if (transport_send_busy_)
1316 return ERR_IO_PENDING;
1318 if (!send_buffer_.get()) {
1319 // Get a fresh send buffer out of the send BIO.
1320 size_t max_read = BIO_pending(transport_bio_);
1321 if (!max_read)
1322 return 0; // Nothing pending in the OpenSSL write BIO.
1323 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1324 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1325 DCHECK_GT(read_bytes, 0);
1326 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1329 int rv = transport_->socket()->Write(
1330 send_buffer_.get(),
1331 send_buffer_->BytesRemaining(),
1332 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1333 base::Unretained(this)));
1334 if (rv == ERR_IO_PENDING) {
1335 transport_send_busy_ = true;
1336 } else {
1337 TransportWriteComplete(rv);
1339 return rv;
1342 int SSLClientSocketOpenSSL::BufferRecv(void) {
1343 if (transport_recv_busy_)
1344 return ERR_IO_PENDING;
1346 // Determine how much was requested from |transport_bio_| that was not
1347 // actually available.
1348 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1349 if (requested == 0) {
1350 // This is not a perfect match of error codes, as no operation is
1351 // actually pending. However, returning 0 would be interpreted as
1352 // a possible sign of EOF, which is also an inappropriate match.
1353 return ERR_IO_PENDING;
1356 // Known Issue: While only reading |requested| data is the more correct
1357 // implementation, it has the downside of resulting in frequent reads:
1358 // One read for the SSL record header (~5 bytes) and one read for the SSL
1359 // record body. Rather than issuing these reads to the underlying socket
1360 // (and constantly allocating new IOBuffers), a single Read() request to
1361 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1362 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1363 // traffic, this over-subscribed Read()ing will not cause issues.
1364 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1365 if (!max_write)
1366 return ERR_IO_PENDING;
1368 recv_buffer_ = new IOBuffer(max_write);
1369 int rv = transport_->socket()->Read(
1370 recv_buffer_.get(),
1371 max_write,
1372 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1373 base::Unretained(this)));
1374 if (rv == ERR_IO_PENDING) {
1375 transport_recv_busy_ = true;
1376 } else {
1377 rv = TransportReadComplete(rv);
1379 return rv;
1382 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1383 transport_send_busy_ = false;
1384 TransportWriteComplete(result);
1385 OnSendComplete(result);
1388 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1389 result = TransportReadComplete(result);
1390 OnRecvComplete(result);
1393 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1394 DCHECK(ERR_IO_PENDING != result);
1395 if (result < 0) {
1396 // Record the error. Save it to be reported in a future read or write on
1397 // transport_bio_'s peer.
1398 transport_write_error_ = result;
1399 send_buffer_ = NULL;
1400 } else {
1401 DCHECK(send_buffer_.get());
1402 send_buffer_->DidConsume(result);
1403 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1404 if (send_buffer_->BytesRemaining() <= 0)
1405 send_buffer_ = NULL;
1409 int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1410 DCHECK(ERR_IO_PENDING != result);
1411 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1412 // does not report success.
1413 if (result == 0)
1414 result = ERR_CONNECTION_CLOSED;
1415 if (result < 0) {
1416 DVLOG(1) << "TransportReadComplete result " << result;
1417 // Received an error. Save it to be reported in a future read on
1418 // transport_bio_'s peer.
1419 transport_read_error_ = result;
1420 } else {
1421 DCHECK(recv_buffer_.get());
1422 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1423 // A write into a memory BIO should always succeed.
1424 DCHECK_EQ(result, ret);
1426 recv_buffer_ = NULL;
1427 transport_recv_busy_ = false;
1428 return result;
1431 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
1432 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1433 DCHECK(ssl == ssl_);
1435 // Clear any currently configured certificates.
1436 SSL_certs_clear(ssl_);
1438 #if defined(OS_IOS)
1439 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1440 LOG(WARNING) << "Client auth is not supported";
1441 #else // !defined(OS_IOS)
1442 if (!ssl_config_.send_client_cert) {
1443 // First pass: we know that a client certificate is needed, but we do not
1444 // have one at hand.
1445 client_auth_cert_needed_ = true;
1446 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1447 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
1448 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1449 unsigned char* str = NULL;
1450 int length = i2d_X509_NAME(ca_name, &str);
1451 cert_authorities_.push_back(std::string(
1452 reinterpret_cast<const char*>(str),
1453 static_cast<size_t>(length)));
1454 OPENSSL_free(str);
1457 const unsigned char* client_cert_types;
1458 size_t num_client_cert_types =
1459 SSL_get0_certificate_types(ssl, &client_cert_types);
1460 for (size_t i = 0; i < num_client_cert_types; i++) {
1461 cert_key_types_.push_back(
1462 static_cast<SSLClientCertType>(client_cert_types[i]));
1465 return -1; // Suspends handshake.
1468 // Second pass: a client certificate should have been selected.
1469 if (ssl_config_.client_cert.get()) {
1470 ScopedX509 leaf_x509 =
1471 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1472 if (!leaf_x509) {
1473 LOG(WARNING) << "Failed to import certificate";
1474 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1475 return -1;
1478 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1479 ssl_config_.client_cert->GetIntermediateCertificates());
1480 if (!chain) {
1481 LOG(WARNING) << "Failed to import intermediate certificates";
1482 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1483 return -1;
1486 // TODO(davidben): With Linux client auth support, this should be
1487 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1488 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1489 // net/ client auth API lacking a private key handle.
1490 #if defined(USE_OPENSSL_CERTS)
1491 crypto::ScopedEVP_PKEY privkey =
1492 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1493 ssl_config_.client_cert.get());
1494 #else // !defined(USE_OPENSSL_CERTS)
1495 crypto::ScopedEVP_PKEY privkey =
1496 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1497 #endif // defined(USE_OPENSSL_CERTS)
1498 if (!privkey) {
1499 // Could not find the private key. Fail the handshake and surface an
1500 // appropriate error to the caller.
1501 LOG(WARNING) << "Client cert found without private key";
1502 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1503 return -1;
1506 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1507 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1508 !SSL_set1_chain(ssl_, chain.get())) {
1509 LOG(WARNING) << "Failed to set client certificate";
1510 return -1;
1512 return 1;
1514 #endif // defined(OS_IOS)
1516 // Send no client certificate.
1517 return 1;
1520 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1521 if (!completed_connect_) {
1522 // If the first handshake hasn't completed then we accept any certificates
1523 // because we verify after the handshake.
1524 return 1;
1527 CHECK(server_cert_.get());
1529 PeerCertificateChain chain(store_ctx->untrusted);
1530 if (chain.IsValid() && server_cert_->Equals(chain.AsOSChain()))
1531 return 1;
1533 if (!chain.IsValid())
1534 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1535 else
1536 LOG(ERROR) << "Server certificate changed between handshakes";
1537 return 0;
1540 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1541 // server supports NPN, selects a protocol from the list that the server
1542 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1543 // callback can assume that |in| is syntactically valid.
1544 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1545 unsigned char* outlen,
1546 const unsigned char* in,
1547 unsigned int inlen) {
1548 if (ssl_config_.next_protos.empty()) {
1549 *out = reinterpret_cast<uint8*>(
1550 const_cast<char*>(kDefaultSupportedNPNProtocol));
1551 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1552 npn_status_ = kNextProtoUnsupported;
1553 return SSL_TLSEXT_ERR_OK;
1556 // Assume there's no overlap between our protocols and the server's list.
1557 npn_status_ = kNextProtoNoOverlap;
1559 // For each protocol in server preference order, see if we support it.
1560 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1561 for (std::vector<std::string>::const_iterator
1562 j = ssl_config_.next_protos.begin();
1563 j != ssl_config_.next_protos.end(); ++j) {
1564 if (in[i] == j->size() &&
1565 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
1566 // We found a match.
1567 *out = const_cast<unsigned char*>(in) + i + 1;
1568 *outlen = in[i];
1569 npn_status_ = kNextProtoNegotiated;
1570 break;
1573 if (npn_status_ == kNextProtoNegotiated)
1574 break;
1577 // If we didn't find a protocol, we select the first one from our list.
1578 if (npn_status_ == kNextProtoNoOverlap) {
1579 *out = reinterpret_cast<uint8*>(const_cast<char*>(
1580 ssl_config_.next_protos[0].data()));
1581 *outlen = ssl_config_.next_protos[0].size();
1584 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
1585 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
1586 return SSL_TLSEXT_ERR_OK;
1589 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1590 BIO *bio,
1591 int cmd,
1592 const char *argp, int argi, long argl,
1593 long retvalue) {
1594 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1595 // If there is no more data in the buffer, report any pending errors that
1596 // were observed. Note that both the readbuf and the writebuf are checked
1597 // for errors, since the application may have encountered a socket error
1598 // while writing that would otherwise not be reported until the application
1599 // attempted to write again - which it may never do. See
1600 // https://crbug.com/249848.
1601 if (transport_read_error_ != OK) {
1602 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1603 return -1;
1605 if (transport_write_error_ != OK) {
1606 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1607 return -1;
1609 } else if (cmd == BIO_CB_WRITE) {
1610 // Because of the write buffer, this reports a failure from the previous
1611 // write payload. If the current payload fails to write, the error will be
1612 // reported in a future write or read to |bio|.
1613 if (transport_write_error_ != OK) {
1614 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1615 return -1;
1618 return retvalue;
1621 // static
1622 long SSLClientSocketOpenSSL::BIOCallback(
1623 BIO *bio,
1624 int cmd,
1625 const char *argp, int argi, long argl,
1626 long retvalue) {
1627 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1628 BIO_get_callback_arg(bio));
1629 CHECK(socket);
1630 return socket->MaybeReplayTransportError(
1631 bio, cmd, argp, argi, argl, retvalue);
1634 // static
1635 void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1636 int type,
1637 int /*val*/) {
1638 if (type == SSL_CB_HANDSHAKE_DONE) {
1639 SSLClientSocketOpenSSL* ssl_socket =
1640 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1641 ssl_socket->handshake_succeeded_ = true;
1642 ssl_socket->CheckIfHandshakeFinished();
1646 // Determines if both the handshake and certificate verification have completed
1647 // successfully, and calls the handshake completion callback if that is the
1648 // case.
1650 // CheckIfHandshakeFinished is called twice per connection: once after
1651 // MarkSSLSessionAsGood, when the certificate has been verified, and
1652 // once via an OpenSSL callback when the handshake has completed. On the
1653 // second call, when the certificate has been verified and the handshake
1654 // has completed, the connection's handshake completion callback is run.
1655 void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1656 if (handshake_succeeded_ && marked_session_as_good_)
1657 OnHandshakeCompletion();
1660 scoped_refptr<X509Certificate>
1661 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1662 return server_cert_;
1665 } // namespace net