Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / net / socket / ssl_client_socket_openssl.cc
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.
4
5 // OpenSSL binding for SSLClientSocket. The class layout and general principle
6 // of operation is derived from SSLClientSocketNSS.
7
8 #include "net/socket/ssl_client_socket_openssl.h"
9
10 #include <errno.h>
11 #include <openssl/bio.h>
12 #include <openssl/err.h>
13 #include <openssl/ssl.h>
14
15 #include "base/bind.h"
16 #include "base/callback_helpers.h"
17 #include "base/environment.h"
18 #include "base/memory/singleton.h"
19 #include "base/metrics/histogram.h"
20 #include "base/strings/string_piece.h"
21 #include "base/synchronization/lock.h"
22 #include "crypto/ec_private_key.h"
23 #include "crypto/openssl_util.h"
24 #include "crypto/scoped_openssl_types.h"
25 #include "net/base/net_errors.h"
26 #include "net/cert/cert_verifier.h"
27 #include "net/cert/ct_ev_whitelist.h"
28 #include "net/cert/ct_verifier.h"
29 #include "net/cert/single_request_cert_verifier.h"
30 #include "net/cert/x509_certificate_net_log_param.h"
31 #include "net/cert/x509_util_openssl.h"
32 #include "net/http/transport_security_state.h"
33 #include "net/socket/ssl_session_cache_openssl.h"
34 #include "net/ssl/ssl_cert_request_info.h"
35 #include "net/ssl/ssl_connection_status_flags.h"
36 #include "net/ssl/ssl_info.h"
37
38 #if defined(OS_WIN)
39 #include "base/win/windows_version.h"
40 #endif
41
42 #if defined(USE_OPENSSL_CERTS)
43 #include "net/ssl/openssl_client_key_store.h"
44 #else
45 #include "net/ssl/openssl_platform_key.h"
46 #endif
47
48 namespace net {
49
50 namespace {
51
52 // Enable this to see logging for state machine state transitions.
53 #if 0
54 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
55                            " jump to state " << s; \
56                            next_handshake_state_ = s; } while (0)
57 #else
58 #define GotoState(s) next_handshake_state_ = s
59 #endif
60
61 // This constant can be any non-negative/non-zero value (eg: it does not
62 // overlap with any value of the net::Error range, including net::OK).
63 const int kNoPendingReadResult = 1;
64
65 // If a client doesn't have a list of protocols that it supports, but
66 // the server supports NPN, choosing "http/1.1" is the best answer.
67 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
68
69 void FreeX509Stack(STACK_OF(X509)* ptr) {
70   sk_X509_pop_free(ptr, X509_free);
71 }
72
73 typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
74 typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
75     ScopedX509Stack;
76
77 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
78 // This method doesn't seem to have made it into the OpenSSL headers.
79 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
80 #endif
81
82 // Used for encoding the |connection_status| field of an SSLInfo object.
83 int EncodeSSLConnectionStatus(int cipher_suite,
84                               int compression,
85                               int version) {
86   return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
87           SSL_CONNECTION_CIPHERSUITE_SHIFT) |
88          ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
89           SSL_CONNECTION_COMPRESSION_SHIFT) |
90          ((version & SSL_CONNECTION_VERSION_MASK) <<
91           SSL_CONNECTION_VERSION_SHIFT);
92 }
93
94 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
95 // this SSL connection.
96 int GetNetSSLVersion(SSL* ssl) {
97   switch (SSL_version(ssl)) {
98     case SSL2_VERSION:
99       return SSL_CONNECTION_VERSION_SSL2;
100     case SSL3_VERSION:
101       return SSL_CONNECTION_VERSION_SSL3;
102     case TLS1_VERSION:
103       return SSL_CONNECTION_VERSION_TLS1;
104     case TLS1_1_VERSION:
105       return SSL_CONNECTION_VERSION_TLS1_1;
106     case TLS1_2_VERSION:
107       return SSL_CONNECTION_VERSION_TLS1_2;
108     default:
109       return SSL_CONNECTION_VERSION_UNKNOWN;
110   }
111 }
112
113 ScopedX509 OSCertHandleToOpenSSL(
114     X509Certificate::OSCertHandle os_handle) {
115 #if defined(USE_OPENSSL_CERTS)
116   return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
117 #else  // !defined(USE_OPENSSL_CERTS)
118   std::string der_encoded;
119   if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
120     return ScopedX509();
121   const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
122   return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
123 #endif  // defined(USE_OPENSSL_CERTS)
124 }
125
126 ScopedX509Stack OSCertHandlesToOpenSSL(
127     const X509Certificate::OSCertHandles& os_handles) {
128   ScopedX509Stack stack(sk_X509_new_null());
129   for (size_t i = 0; i < os_handles.size(); i++) {
130     ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
131     if (!x509)
132       return ScopedX509Stack();
133     sk_X509_push(stack.get(), x509.release());
134   }
135   return stack.Pass();
136 }
137
138 int LogErrorCallback(const char* str, size_t len, void* context) {
139   LOG(ERROR) << base::StringPiece(str, len);
140   return 1;
141 }
142
143 }  // namespace
144
145 class SSLClientSocketOpenSSL::SSLContext {
146  public:
147   static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
148   SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
149   SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
150
151   SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
152     DCHECK(ssl);
153     SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
154         SSL_get_ex_data(ssl, ssl_socket_data_index_));
155     DCHECK(socket);
156     return socket;
157   }
158
159   bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
160     return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
161   }
162
163  private:
164   friend struct DefaultSingletonTraits<SSLContext>;
165
166   SSLContext() {
167     crypto::EnsureOpenSSLInit();
168     ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
169     DCHECK_NE(ssl_socket_data_index_, -1);
170     ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
171     session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
172     SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
173     SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
174     SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
175     // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
176     // It would be better if the callback were not a global setting,
177     // but that is an OpenSSL issue.
178     SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
179                                      NULL);
180     ssl_ctx_->tlsext_channel_id_enabled_new = 1;
181
182     scoped_ptr<base::Environment> env(base::Environment::Create());
183     std::string ssl_keylog_file;
184     if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
185         !ssl_keylog_file.empty()) {
186       crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
187       BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
188       if (!bio) {
189         LOG(ERROR) << "Failed to open " << ssl_keylog_file;
190         ERR_print_errors_cb(&LogErrorCallback, NULL);
191       } else {
192         SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
193       }
194     }
195   }
196
197   static std::string GetSessionCacheKey(const SSL* ssl) {
198     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
199     DCHECK(socket);
200     return socket->GetSessionCacheKey();
201   }
202
203   static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
204
205   static int ClientCertRequestCallback(SSL* ssl, void* arg) {
206     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
207     DCHECK(socket);
208     return socket->ClientCertRequestCallback(ssl);
209   }
210
211   static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
212     SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
213         store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
214     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
215     CHECK(socket);
216
217     return socket->CertVerifyCallback(store_ctx);
218   }
219
220   static int SelectNextProtoCallback(SSL* ssl,
221                                      unsigned char** out, unsigned char* outlen,
222                                      const unsigned char* in,
223                                      unsigned int inlen, void* arg) {
224     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
225     return socket->SelectNextProtoCallback(out, outlen, in, inlen);
226   }
227
228   // This is the index used with SSL_get_ex_data to retrieve the owner
229   // SSLClientSocketOpenSSL object from an SSL instance.
230   int ssl_socket_data_index_;
231
232   crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
233   // |session_cache_| must be destroyed before |ssl_ctx_|.
234   SSLSessionCacheOpenSSL session_cache_;
235 };
236
237 // PeerCertificateChain is a helper object which extracts the certificate
238 // chain, as given by the server, from an OpenSSL socket and performs the needed
239 // resource management. The first element of the chain is the leaf certificate
240 // and the other elements are in the order given by the server.
241 class SSLClientSocketOpenSSL::PeerCertificateChain {
242  public:
243   explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
244   PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
245   ~PeerCertificateChain() {}
246   PeerCertificateChain& operator=(const PeerCertificateChain& other);
247
248   // Resets the PeerCertificateChain to the set of certificates in|chain|,
249   // which may be NULL, indicating to empty the store certificates.
250   // Note: If an error occurs, such as being unable to parse the certificates,
251   // this will behave as if Reset(NULL) was called.
252   void Reset(STACK_OF(X509)* chain);
253
254   // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
255   scoped_refptr<X509Certificate> AsOSChain() const;
256
257   size_t size() const {
258     if (!openssl_chain_.get())
259       return 0;
260     return sk_X509_num(openssl_chain_.get());
261   }
262
263   bool empty() const {
264     return size() == 0;
265   }
266
267   X509* Get(size_t index) const {
268     DCHECK_LT(index, size());
269     return sk_X509_value(openssl_chain_.get(), index);
270   }
271
272  private:
273   ScopedX509Stack openssl_chain_;
274 };
275
276 SSLClientSocketOpenSSL::PeerCertificateChain&
277 SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
278     const PeerCertificateChain& other) {
279   if (this == &other)
280     return *this;
281
282   openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
283   return *this;
284 }
285
286 void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
287     STACK_OF(X509)* chain) {
288   openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
289 }
290
291 scoped_refptr<X509Certificate>
292 SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
293 #if defined(USE_OPENSSL_CERTS)
294   // When OSCertHandle is typedef'ed to X509, this implementation does a short
295   // cut to avoid converting back and forth between DER and the X509 struct.
296   X509Certificate::OSCertHandles intermediates;
297   for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
298     intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
299   }
300
301   return make_scoped_refptr(X509Certificate::CreateFromHandle(
302       sk_X509_value(openssl_chain_.get(), 0), intermediates));
303 #else
304   // DER-encode the chain and convert to a platform certificate handle.
305   std::vector<base::StringPiece> der_chain;
306   for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
307     X509* x = sk_X509_value(openssl_chain_.get(), i);
308     base::StringPiece der;
309     if (!x509_util::GetDER(x, &der))
310       return NULL;
311     der_chain.push_back(der);
312   }
313
314   return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
315 #endif
316 }
317
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
325 };
326
327 // static
328 void SSLClientSocket::ClearSessionCache() {
329   SSLClientSocketOpenSSL::SSLContext* context =
330       SSLClientSocketOpenSSL::SSLContext::GetInstance();
331   context->session_cache()->Flush();
332 }
333
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       pending_read_error_(kNoPendingReadResult),
342       pending_read_ssl_error_(SSL_ERROR_NONE),
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       cert_transparency_verifier_(context.cert_transparency_verifier),
351       channel_id_service_(context.channel_id_service),
352       ssl_(NULL),
353       transport_bio_(NULL),
354       transport_(transport_socket.Pass()),
355       host_and_port_(host_and_port),
356       ssl_config_(ssl_config),
357       ssl_session_cache_shard_(context.ssl_session_cache_shard),
358       trying_cached_session_(false),
359       next_handshake_state_(STATE_NONE),
360       npn_status_(kNextProtoUnsupported),
361       channel_id_xtn_negotiated_(false),
362       handshake_succeeded_(false),
363       marked_session_as_good_(false),
364       transport_security_state_(context.transport_security_state),
365       net_log_(transport_->socket()->NetLog()),
366       weak_factory_(this) {
367 }
368
369 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
370   Disconnect();
371 }
372
373 std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
374   std::string result = host_and_port_.ToString();
375   result.append("/");
376   result.append(ssl_session_cache_shard_);
377   return result;
378 }
379
380 bool SSLClientSocketOpenSSL::InSessionCache() const {
381   SSLContext* context = SSLContext::GetInstance();
382   std::string cache_key = GetSessionCacheKey();
383   return context->session_cache()->SSLSessionIsInCache(cache_key);
384 }
385
386 void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
387     const base::Closure& callback) {
388   handshake_completion_callback_ = callback;
389 }
390
391 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
392     SSLCertRequestInfo* cert_request_info) {
393   cert_request_info->host_and_port = host_and_port_;
394   cert_request_info->cert_authorities = cert_authorities_;
395   cert_request_info->cert_key_types = cert_key_types_;
396 }
397
398 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
399     std::string* proto) {
400   *proto = npn_proto_;
401   return npn_status_;
402 }
403
404 ChannelIDService*
405 SSLClientSocketOpenSSL::GetChannelIDService() const {
406   return channel_id_service_;
407 }
408
409 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
410     const base::StringPiece& label,
411     bool has_context, const base::StringPiece& context,
412     unsigned char* out, unsigned int outlen) {
413   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
414
415   int rv = SSL_export_keying_material(
416       ssl_, out, outlen, label.data(), label.size(),
417       reinterpret_cast<const unsigned char*>(context.data()),
418       context.length(), context.length() > 0);
419
420   if (rv != 1) {
421     int ssl_error = SSL_get_error(ssl_, rv);
422     LOG(ERROR) << "Failed to export keying material;"
423                << " returned " << rv
424                << ", SSL error code " << ssl_error;
425     return MapOpenSSLError(ssl_error, err_tracer);
426   }
427   return OK;
428 }
429
430 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
431   NOTIMPLEMENTED();
432   return ERR_NOT_IMPLEMENTED;
433 }
434
435 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
436   // It is an error to create an SSLClientSocket whose context has no
437   // TransportSecurityState.
438   DCHECK(transport_security_state_);
439
440   net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
441
442   // Set up new ssl object.
443   int rv = Init();
444   if (rv != OK) {
445     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
446     return rv;
447   }
448
449   // Set SSL to client mode. Handshake happens in the loop below.
450   SSL_set_connect_state(ssl_);
451
452   GotoState(STATE_HANDSHAKE);
453   rv = DoHandshakeLoop(OK);
454   if (rv == ERR_IO_PENDING) {
455     user_connect_callback_ = callback;
456   } else {
457     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
458     if (rv < OK)
459       OnHandshakeCompletion();
460   }
461
462   return rv > OK ? OK : rv;
463 }
464
465 void SSLClientSocketOpenSSL::Disconnect() {
466   // If a handshake was pending (Connect() had been called), notify interested
467   // parties that it's been aborted now. If the handshake had already
468   // completed, this is a no-op.
469   OnHandshakeCompletion();
470   if (ssl_) {
471     // Calling SSL_shutdown prevents the session from being marked as
472     // unresumable.
473     SSL_shutdown(ssl_);
474     SSL_free(ssl_);
475     ssl_ = NULL;
476   }
477   if (transport_bio_) {
478     BIO_free_all(transport_bio_);
479     transport_bio_ = NULL;
480   }
481
482   // Shut down anything that may call us back.
483   verifier_.reset();
484   transport_->socket()->Disconnect();
485
486   // Null all callbacks, delete all buffers.
487   transport_send_busy_ = false;
488   send_buffer_ = NULL;
489   transport_recv_busy_ = false;
490   recv_buffer_ = NULL;
491
492   user_connect_callback_.Reset();
493   user_read_callback_.Reset();
494   user_write_callback_.Reset();
495   user_read_buf_         = NULL;
496   user_read_buf_len_     = 0;
497   user_write_buf_        = NULL;
498   user_write_buf_len_    = 0;
499
500   pending_read_error_ = kNoPendingReadResult;
501   pending_read_ssl_error_ = SSL_ERROR_NONE;
502   pending_read_error_info_ = OpenSSLErrorInfo();
503
504   transport_read_error_ = OK;
505   transport_write_error_ = OK;
506
507   server_cert_verify_result_.Reset();
508   completed_connect_ = false;
509
510   cert_authorities_.clear();
511   cert_key_types_.clear();
512   client_auth_cert_needed_ = false;
513
514   start_cert_verification_time_ = base::TimeTicks();
515
516   npn_status_ = kNextProtoUnsupported;
517   npn_proto_.clear();
518
519   channel_id_xtn_negotiated_ = false;
520   channel_id_request_handle_.Cancel();
521 }
522
523 bool SSLClientSocketOpenSSL::IsConnected() const {
524   // If the handshake has not yet completed.
525   if (!completed_connect_)
526     return false;
527   // If an asynchronous operation is still pending.
528   if (user_read_buf_.get() || user_write_buf_.get())
529     return true;
530
531   return transport_->socket()->IsConnected();
532 }
533
534 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
535   // If the handshake has not yet completed.
536   if (!completed_connect_)
537     return false;
538   // If an asynchronous operation is still pending.
539   if (user_read_buf_.get() || user_write_buf_.get())
540     return false;
541   // If there is data waiting to be sent, or data read from the network that
542   // has not yet been consumed.
543   if (BIO_pending(transport_bio_) > 0 ||
544       BIO_wpending(transport_bio_) > 0) {
545     return false;
546   }
547
548   return transport_->socket()->IsConnectedAndIdle();
549 }
550
551 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
552   return transport_->socket()->GetPeerAddress(addressList);
553 }
554
555 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
556   return transport_->socket()->GetLocalAddress(addressList);
557 }
558
559 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
560   return net_log_;
561 }
562
563 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
564   if (transport_.get() && transport_->socket()) {
565     transport_->socket()->SetSubresourceSpeculation();
566   } else {
567     NOTREACHED();
568   }
569 }
570
571 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
572   if (transport_.get() && transport_->socket()) {
573     transport_->socket()->SetOmniboxSpeculation();
574   } else {
575     NOTREACHED();
576   }
577 }
578
579 bool SSLClientSocketOpenSSL::WasEverUsed() const {
580   return was_ever_used_;
581 }
582
583 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
584   if (transport_.get() && transport_->socket())
585     return transport_->socket()->UsingTCPFastOpen();
586
587   NOTREACHED();
588   return false;
589 }
590
591 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
592   ssl_info->Reset();
593   if (server_cert_chain_->empty())
594     return false;
595
596   ssl_info->cert = server_cert_verify_result_.verified_cert;
597   ssl_info->cert_status = server_cert_verify_result_.cert_status;
598   ssl_info->is_issued_by_known_root =
599       server_cert_verify_result_.is_issued_by_known_root;
600   ssl_info->public_key_hashes =
601     server_cert_verify_result_.public_key_hashes;
602   ssl_info->client_cert_sent =
603       ssl_config_.send_client_cert && ssl_config_.client_cert.get();
604   ssl_info->channel_id_sent = WasChannelIDSent();
605   ssl_info->pinning_failure_log = pinning_failure_log_;
606
607   AddSCTInfoToSSLInfo(ssl_info);
608
609   const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
610   CHECK(cipher);
611   ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
612
613   ssl_info->connection_status = EncodeSSLConnectionStatus(
614       SSL_CIPHER_get_id(cipher), 0 /* no compression */,
615       GetNetSSLVersion(ssl_));
616
617   if (!SSL_get_secure_renegotiation_support(ssl_))
618     ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
619
620   if (ssl_config_.version_fallback)
621     ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
622
623   ssl_info->handshake_type = SSL_session_reused(ssl_) ?
624       SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
625
626   DVLOG(3) << "Encoded connection status: cipher suite = "
627       << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
628       << " version = "
629       << SSLConnectionStatusToVersion(ssl_info->connection_status);
630   return true;
631 }
632
633 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
634                                  int buf_len,
635                                  const CompletionCallback& callback) {
636   user_read_buf_ = buf;
637   user_read_buf_len_ = buf_len;
638
639   int rv = DoReadLoop();
640
641   if (rv == ERR_IO_PENDING) {
642     user_read_callback_ = callback;
643   } else {
644     if (rv > 0)
645       was_ever_used_ = true;
646     user_read_buf_ = NULL;
647     user_read_buf_len_ = 0;
648     if (rv <= 0) {
649       // Failure of a read attempt may indicate a failed false start
650       // connection.
651       OnHandshakeCompletion();
652     }
653   }
654
655   return rv;
656 }
657
658 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
659                                   int buf_len,
660                                   const CompletionCallback& callback) {
661   user_write_buf_ = buf;
662   user_write_buf_len_ = buf_len;
663
664   int rv = DoWriteLoop();
665
666   if (rv == ERR_IO_PENDING) {
667     user_write_callback_ = callback;
668   } else {
669     if (rv > 0)
670       was_ever_used_ = true;
671     user_write_buf_ = NULL;
672     user_write_buf_len_ = 0;
673     if (rv < 0) {
674       // Failure of a write attempt may indicate a failed false start
675       // connection.
676       OnHandshakeCompletion();
677     }
678   }
679
680   return rv;
681 }
682
683 int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
684   return transport_->socket()->SetReceiveBufferSize(size);
685 }
686
687 int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
688   return transport_->socket()->SetSendBufferSize(size);
689 }
690
691 int SSLClientSocketOpenSSL::Init() {
692   DCHECK(!ssl_);
693   DCHECK(!transport_bio_);
694
695   SSLContext* context = SSLContext::GetInstance();
696   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
697
698   ssl_ = SSL_new(context->ssl_ctx());
699   if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
700     return ERR_UNEXPECTED;
701
702   if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
703     return ERR_UNEXPECTED;
704
705   // Set an OpenSSL callback to monitor this SSL*'s connection.
706   SSL_set_info_callback(ssl_, &InfoCallback);
707
708   trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
709       ssl_, GetSessionCacheKey());
710
711   BIO* ssl_bio = NULL;
712   // 0 => use default buffer sizes.
713   if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
714     return ERR_UNEXPECTED;
715   DCHECK(ssl_bio);
716   DCHECK(transport_bio_);
717
718   // Install a callback on OpenSSL's end to plumb transport errors through.
719   BIO_set_callback(ssl_bio, BIOCallback);
720   BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
721
722   SSL_set_bio(ssl_, ssl_bio, ssl_bio);
723
724   // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
725   // set everything we care about to an absolute value.
726   SslSetClearMask options;
727   options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
728   bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
729   options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
730   bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
731                        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
732   options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
733   bool tls1_1_enabled =
734       (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
735        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
736   options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
737   bool tls1_2_enabled =
738       (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
739        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
740   options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
741
742   options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
743
744   // TODO(joth): Set this conditionally, see http://crbug.com/55410
745   options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
746
747   SSL_set_options(ssl_, options.set_mask);
748   SSL_clear_options(ssl_, options.clear_mask);
749
750   // Same as above, this time for the SSL mode.
751   SslSetClearMask mode;
752
753   mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
754   mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
755
756   mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
757                      ssl_config_.false_start_enabled);
758
759   SSL_set_mode(ssl_, mode.set_mask);
760   SSL_clear_mode(ssl_, mode.clear_mask);
761
762   // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
763   // textual name with SSL_set_cipher_list because there is no public API to
764   // directly remove a cipher by ID.
765   STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
766   DCHECK(ciphers);
767   // See SSLConfig::disabled_cipher_suites for description of the suites
768   // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
769   // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
770   // as the handshake hash.
771   std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
772                       "!aECDH:!AESGCM+AES256");
773   // Walk through all the installed ciphers, seeing if any need to be
774   // appended to the cipher removal |command|.
775   for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
776     const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
777     const uint16 id = SSL_CIPHER_get_id(cipher);
778     // Remove any ciphers with a strength of less than 80 bits. Note the NSS
779     // implementation uses "effective" bits here but OpenSSL does not provide
780     // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
781     // both of which are greater than 80 anyway.
782     bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
783     if (!disable) {
784       disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
785                           ssl_config_.disabled_cipher_suites.end(), id) !=
786                     ssl_config_.disabled_cipher_suites.end();
787     }
788     if (disable) {
789        const char* name = SSL_CIPHER_get_name(cipher);
790        DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
791                 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
792        command.append(":!");
793        command.append(name);
794      }
795   }
796
797   // Disable ECDSA cipher suites on platforms that do not support ECDSA
798   // signed certificates, as servers may use the presence of such
799   // ciphersuites as a hint to send an ECDSA certificate.
800 #if defined(OS_WIN)
801   if (base::win::GetVersion() < base::win::VERSION_VISTA)
802     command.append(":!ECDSA");
803 #endif
804
805   int rv = SSL_set_cipher_list(ssl_, command.c_str());
806   // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
807   // This will almost certainly result in the socket failing to complete the
808   // handshake at which point the appropriate error is bubbled up to the client.
809   LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
810                               "returned " << rv;
811
812   if (ssl_config_.version_fallback)
813     SSL_enable_fallback_scsv(ssl_);
814
815   // TLS channel ids.
816   if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
817     SSL_enable_tls_channel_id(ssl_);
818   }
819
820   if (!ssl_config_.next_protos.empty()) {
821     std::vector<uint8_t> wire_protos =
822         SerializeNextProtos(ssl_config_.next_protos);
823     SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
824                         wire_protos.size());
825   }
826
827   if (ssl_config_.signed_cert_timestamps_enabled) {
828     SSL_enable_signed_cert_timestamps(ssl_);
829     SSL_enable_ocsp_stapling(ssl_);
830   }
831
832   // TODO(davidben): Enable OCSP stapling on platforms which support it and pass
833   // into the certificate verifier. https://crbug.com/398677
834
835   return OK;
836 }
837
838 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
839   // Since Run may result in Read being called, clear |user_read_callback_|
840   // up front.
841   if (rv > 0)
842     was_ever_used_ = true;
843   user_read_buf_ = NULL;
844   user_read_buf_len_ = 0;
845   if (rv <= 0) {
846     // Failure of a read attempt may indicate a failed false start
847     // connection.
848     OnHandshakeCompletion();
849   }
850   base::ResetAndReturn(&user_read_callback_).Run(rv);
851 }
852
853 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
854   // Since Run may result in Write being called, clear |user_write_callback_|
855   // up front.
856   if (rv > 0)
857     was_ever_used_ = true;
858   user_write_buf_ = NULL;
859   user_write_buf_len_ = 0;
860   if (rv < 0) {
861     // Failure of a write attempt may indicate a failed false start
862     // connection.
863     OnHandshakeCompletion();
864   }
865   base::ResetAndReturn(&user_write_callback_).Run(rv);
866 }
867
868 void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
869   if (!handshake_completion_callback_.is_null())
870     base::ResetAndReturn(&handshake_completion_callback_).Run();
871 }
872
873 bool SSLClientSocketOpenSSL::DoTransportIO() {
874   bool network_moved = false;
875   int rv;
876   // Read and write as much data as possible. The loop is necessary because
877   // Write() may return synchronously.
878   do {
879     rv = BufferSend();
880     if (rv != ERR_IO_PENDING && rv != 0)
881       network_moved = true;
882   } while (rv > 0);
883   if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
884     network_moved = true;
885   return network_moved;
886 }
887
888 int SSLClientSocketOpenSSL::DoHandshake() {
889   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
890   int net_error = OK;
891   int rv = SSL_do_handshake(ssl_);
892
893   if (client_auth_cert_needed_) {
894     net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
895     // If the handshake already succeeded (because the server requests but
896     // doesn't require a client cert), we need to invalidate the SSL session
897     // so that we won't try to resume the non-client-authenticated session in
898     // the next handshake.  This will cause the server to ask for a client
899     // cert again.
900     if (rv == 1) {
901       // Remove from session cache but don't clear this connection.
902       SSL_SESSION* session = SSL_get_session(ssl_);
903       if (session) {
904         int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
905         LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
906       }
907     }
908   } else if (rv == 1) {
909     if (trying_cached_session_ && logging::DEBUG_MODE) {
910       DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
911                << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
912     }
913
914     if (ssl_config_.version_fallback &&
915         ssl_config_.version_max < ssl_config_.version_fallback_min) {
916       return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
917     }
918
919     // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
920     if (npn_status_ == kNextProtoUnsupported) {
921       const uint8_t* alpn_proto = NULL;
922       unsigned alpn_len = 0;
923       SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
924       if (alpn_len > 0) {
925         npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
926         npn_status_ = kNextProtoNegotiated;
927         set_negotiation_extension(kExtensionALPN);
928       }
929     }
930
931     RecordChannelIDSupport(channel_id_service_,
932                            channel_id_xtn_negotiated_,
933                            ssl_config_.channel_id_enabled,
934                            crypto::ECPrivateKey::IsSupported());
935
936     uint8_t* ocsp_response;
937     size_t ocsp_response_len;
938     SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
939     set_stapled_ocsp_response_received(ocsp_response_len != 0);
940
941     uint8_t* sct_list;
942     size_t sct_list_len;
943     SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
944     set_signed_cert_timestamps_received(sct_list_len != 0);
945
946     // Verify the certificate.
947     UpdateServerCert();
948     GotoState(STATE_VERIFY_CERT);
949   } else {
950     int ssl_error = SSL_get_error(ssl_, rv);
951
952     if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
953       // The server supports channel ID. Stop to look one up before returning to
954       // the handshake.
955       channel_id_xtn_negotiated_ = true;
956       GotoState(STATE_CHANNEL_ID_LOOKUP);
957       return OK;
958     }
959
960     OpenSSLErrorInfo error_info;
961     net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
962
963     // If not done, stay in this state
964     if (net_error == ERR_IO_PENDING) {
965       GotoState(STATE_HANDSHAKE);
966     } else {
967       LOG(ERROR) << "handshake failed; returned " << rv
968                  << ", SSL error code " << ssl_error
969                  << ", net_error " << net_error;
970       net_log_.AddEvent(
971           NetLog::TYPE_SSL_HANDSHAKE_ERROR,
972           CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
973     }
974   }
975   return net_error;
976 }
977
978 int SSLClientSocketOpenSSL::DoChannelIDLookup() {
979   GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
980   return channel_id_service_->GetOrCreateChannelID(
981       host_and_port_.host(),
982       &channel_id_private_key_,
983       &channel_id_cert_,
984       base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
985                  base::Unretained(this)),
986       &channel_id_request_handle_);
987 }
988
989 int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
990   if (result < 0)
991     return result;
992
993   DCHECK_LT(0u, channel_id_private_key_.size());
994   // Decode key.
995   std::vector<uint8> encrypted_private_key_info;
996   std::vector<uint8> subject_public_key_info;
997   encrypted_private_key_info.assign(
998       channel_id_private_key_.data(),
999       channel_id_private_key_.data() + channel_id_private_key_.size());
1000   subject_public_key_info.assign(
1001       channel_id_cert_.data(),
1002       channel_id_cert_.data() + channel_id_cert_.size());
1003   scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1004       crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
1005           ChannelIDService::kEPKIPassword,
1006           encrypted_private_key_info,
1007           subject_public_key_info));
1008   if (!ec_private_key) {
1009     LOG(ERROR) << "Failed to import Channel ID.";
1010     return ERR_CHANNEL_ID_IMPORT_FAILED;
1011   }
1012
1013   // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1014   // type.
1015   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1016   int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1017   if (!rv) {
1018     LOG(ERROR) << "Failed to set Channel ID.";
1019     int err = SSL_get_error(ssl_, rv);
1020     return MapOpenSSLError(err, err_tracer);
1021   }
1022
1023   // Return to the handshake.
1024   set_channel_id_sent(true);
1025   GotoState(STATE_HANDSHAKE);
1026   return OK;
1027 }
1028
1029 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
1030   DCHECK(!server_cert_chain_->empty());
1031   DCHECK(start_cert_verification_time_.is_null());
1032
1033   GotoState(STATE_VERIFY_CERT_COMPLETE);
1034
1035   // If the certificate is bad and has been previously accepted, use
1036   // the previous status and bypass the error.
1037   base::StringPiece der_cert;
1038   if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1039     NOTREACHED();
1040     return ERR_CERT_INVALID;
1041   }
1042   CertStatus cert_status;
1043   if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
1044     VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1045     server_cert_verify_result_.Reset();
1046     server_cert_verify_result_.cert_status = cert_status;
1047     server_cert_verify_result_.verified_cert = server_cert_;
1048     return OK;
1049   }
1050
1051   // When running in a sandbox, it may not be possible to create an
1052   // X509Certificate*, as that may depend on OS functionality blocked
1053   // in the sandbox.
1054   if (!server_cert_.get()) {
1055     server_cert_verify_result_.Reset();
1056     server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1057     return ERR_CERT_INVALID;
1058   }
1059
1060   start_cert_verification_time_ = base::TimeTicks::Now();
1061
1062   int flags = 0;
1063   if (ssl_config_.rev_checking_enabled)
1064     flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1065   if (ssl_config_.verify_ev_cert)
1066     flags |= CertVerifier::VERIFY_EV_CERT;
1067   if (ssl_config_.cert_io_enabled)
1068     flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1069   if (ssl_config_.rev_checking_required_local_anchors)
1070     flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1071   verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1072   return verifier_->Verify(
1073       server_cert_.get(),
1074       host_and_port_.host(),
1075       flags,
1076       // TODO(davidben): Route the CRLSet through SSLConfig so
1077       // SSLClientSocket doesn't depend on SSLConfigService.
1078       SSLConfigService::GetCRLSet().get(),
1079       &server_cert_verify_result_,
1080       base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1081                  base::Unretained(this)),
1082       net_log_);
1083 }
1084
1085 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1086   verifier_.reset();
1087
1088   if (!start_cert_verification_time_.is_null()) {
1089     base::TimeDelta verify_time =
1090         base::TimeTicks::Now() - start_cert_verification_time_;
1091     if (result == OK) {
1092       UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1093     } else {
1094       UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1095     }
1096   }
1097
1098   if (result == OK)
1099     RecordConnectionTypeMetrics(GetNetSSLVersion(ssl_));
1100
1101   const CertStatus cert_status = server_cert_verify_result_.cert_status;
1102   if (transport_security_state_ &&
1103       (result == OK ||
1104        (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1105       !transport_security_state_->CheckPublicKeyPins(
1106           host_and_port_.host(),
1107           server_cert_verify_result_.is_issued_by_known_root,
1108           server_cert_verify_result_.public_key_hashes,
1109           &pinning_failure_log_)) {
1110     result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1111   }
1112
1113   scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1114       SSLConfigService::GetEVCertsWhitelist();
1115   if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1116     if (ev_whitelist.get() && ev_whitelist->IsValid()) {
1117       const SHA256HashValue fingerprint(
1118           X509Certificate::CalculateFingerprint256(
1119               server_cert_verify_result_.verified_cert->os_cert_handle()));
1120
1121       UMA_HISTOGRAM_BOOLEAN(
1122           "Net.SSL_EVCertificateInWhitelist",
1123           ev_whitelist->ContainsCertificateHash(
1124               std::string(reinterpret_cast<const char*>(fingerprint.data), 8)));
1125     }
1126   }
1127
1128   if (result == OK) {
1129     // Only check Certificate Transparency if there were no other errors with
1130     // the connection.
1131     VerifyCT();
1132
1133     // TODO(joth): Work out if we need to remember the intermediate CA certs
1134     // when the server sends them to us, and do so here.
1135     SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
1136     marked_session_as_good_ = true;
1137     CheckIfHandshakeFinished();
1138   } else {
1139     DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1140              << " (" << result << ")";
1141   }
1142
1143   completed_connect_ = true;
1144
1145   // Exit DoHandshakeLoop and return the result to the caller to Connect.
1146   DCHECK_EQ(STATE_NONE, next_handshake_state_);
1147   return result;
1148 }
1149
1150 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1151   if (rv < OK)
1152     OnHandshakeCompletion();
1153   if (!user_connect_callback_.is_null()) {
1154     CompletionCallback c = user_connect_callback_;
1155     user_connect_callback_.Reset();
1156     c.Run(rv > OK ? OK : rv);
1157   }
1158 }
1159
1160 void SSLClientSocketOpenSSL::UpdateServerCert() {
1161   server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
1162   server_cert_ = server_cert_chain_->AsOSChain();
1163
1164   if (server_cert_.get()) {
1165     net_log_.AddEvent(
1166         NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1167         base::Bind(&NetLogX509CertificateCallback,
1168                    base::Unretained(server_cert_.get())));
1169   }
1170 }
1171
1172 void SSLClientSocketOpenSSL::VerifyCT() {
1173   if (!cert_transparency_verifier_)
1174     return;
1175
1176   uint8_t* ocsp_response_raw;
1177   size_t ocsp_response_len;
1178   SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1179   std::string ocsp_response;
1180   if (ocsp_response_len > 0) {
1181     ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1182                          ocsp_response_len);
1183   }
1184
1185   uint8_t* sct_list_raw;
1186   size_t sct_list_len;
1187   SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1188   std::string sct_list;
1189   if (sct_list_len > 0)
1190     sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1191
1192   // Note that this is a completely synchronous operation: The CT Log Verifier
1193   // gets all the data it needs for SCT verification and does not do any
1194   // external communication.
1195   int result = cert_transparency_verifier_->Verify(
1196       server_cert_verify_result_.verified_cert.get(),
1197       ocsp_response, sct_list, &ct_verify_result_, net_log_);
1198
1199   VLOG(1) << "CT Verification complete: result " << result
1200           << " Invalid scts: " << ct_verify_result_.invalid_scts.size()
1201           << " Verified scts: " << ct_verify_result_.verified_scts.size()
1202           << " scts from unknown logs: "
1203           << ct_verify_result_.unknown_logs_scts.size();
1204 }
1205
1206 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1207   int rv = DoHandshakeLoop(result);
1208   if (rv != ERR_IO_PENDING) {
1209     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1210     DoConnectCallback(rv);
1211   }
1212 }
1213
1214 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1215   if (next_handshake_state_ == STATE_HANDSHAKE) {
1216     // In handshake phase.
1217     OnHandshakeIOComplete(result);
1218     return;
1219   }
1220
1221   // OnSendComplete may need to call DoPayloadRead while the renegotiation
1222   // handshake is in progress.
1223   int rv_read = ERR_IO_PENDING;
1224   int rv_write = ERR_IO_PENDING;
1225   bool network_moved;
1226   do {
1227     if (user_read_buf_.get())
1228       rv_read = DoPayloadRead();
1229     if (user_write_buf_.get())
1230       rv_write = DoPayloadWrite();
1231     network_moved = DoTransportIO();
1232   } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1233            (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1234
1235   // Performing the Read callback may cause |this| to be deleted. If this
1236   // happens, the Write callback should not be invoked. Guard against this by
1237   // holding a WeakPtr to |this| and ensuring it's still valid.
1238   base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1239   if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1240     DoReadCallback(rv_read);
1241
1242   if (!guard.get())
1243     return;
1244
1245   if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1246     DoWriteCallback(rv_write);
1247 }
1248
1249 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1250   if (next_handshake_state_ == STATE_HANDSHAKE) {
1251     // In handshake phase.
1252     OnHandshakeIOComplete(result);
1253     return;
1254   }
1255
1256   // Network layer received some data, check if client requested to read
1257   // decrypted data.
1258   if (!user_read_buf_.get())
1259     return;
1260
1261   int rv = DoReadLoop();
1262   if (rv != ERR_IO_PENDING)
1263     DoReadCallback(rv);
1264 }
1265
1266 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1267   int rv = last_io_result;
1268   do {
1269     // Default to STATE_NONE for next state.
1270     // (This is a quirk carried over from the windows
1271     // implementation.  It makes reading the logs a bit harder.)
1272     // State handlers can and often do call GotoState just
1273     // to stay in the current state.
1274     State state = next_handshake_state_;
1275     GotoState(STATE_NONE);
1276     switch (state) {
1277       case STATE_HANDSHAKE:
1278         rv = DoHandshake();
1279         break;
1280       case STATE_CHANNEL_ID_LOOKUP:
1281         DCHECK_EQ(OK, rv);
1282         rv = DoChannelIDLookup();
1283        break;
1284       case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1285         rv = DoChannelIDLookupComplete(rv);
1286         break;
1287       case STATE_VERIFY_CERT:
1288         DCHECK_EQ(OK, rv);
1289         rv = DoVerifyCert(rv);
1290        break;
1291       case STATE_VERIFY_CERT_COMPLETE:
1292         rv = DoVerifyCertComplete(rv);
1293         break;
1294       case STATE_NONE:
1295       default:
1296         rv = ERR_UNEXPECTED;
1297         NOTREACHED() << "unexpected state" << state;
1298         break;
1299     }
1300
1301     bool network_moved = DoTransportIO();
1302     if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1303       // In general we exit the loop if rv is ERR_IO_PENDING.  In this
1304       // special case we keep looping even if rv is ERR_IO_PENDING because
1305       // the transport IO may allow DoHandshake to make progress.
1306       rv = OK;  // This causes us to stay in the loop.
1307     }
1308   } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1309
1310   return rv;
1311 }
1312
1313 int SSLClientSocketOpenSSL::DoReadLoop() {
1314   bool network_moved;
1315   int rv;
1316   do {
1317     rv = DoPayloadRead();
1318     network_moved = DoTransportIO();
1319   } while (rv == ERR_IO_PENDING && network_moved);
1320
1321   return rv;
1322 }
1323
1324 int SSLClientSocketOpenSSL::DoWriteLoop() {
1325   bool network_moved;
1326   int rv;
1327   do {
1328     rv = DoPayloadWrite();
1329     network_moved = DoTransportIO();
1330   } while (rv == ERR_IO_PENDING && network_moved);
1331
1332   return rv;
1333 }
1334
1335 int SSLClientSocketOpenSSL::DoPayloadRead() {
1336   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1337
1338   int rv;
1339   if (pending_read_error_ != kNoPendingReadResult) {
1340     rv = pending_read_error_;
1341     pending_read_error_ = kNoPendingReadResult;
1342     if (rv == 0) {
1343       net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1344                                     rv, user_read_buf_->data());
1345     } else {
1346       net_log_.AddEvent(
1347           NetLog::TYPE_SSL_READ_ERROR,
1348           CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1349                                            pending_read_error_info_));
1350     }
1351     pending_read_ssl_error_ = SSL_ERROR_NONE;
1352     pending_read_error_info_ = OpenSSLErrorInfo();
1353     return rv;
1354   }
1355
1356   int total_bytes_read = 0;
1357   do {
1358     rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1359                   user_read_buf_len_ - total_bytes_read);
1360     if (rv > 0)
1361       total_bytes_read += rv;
1362   } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1363
1364   if (total_bytes_read == user_read_buf_len_) {
1365     rv = total_bytes_read;
1366   } else {
1367     // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1368     // immediately, while the OpenSSL errors are still available in
1369     // thread-local storage. However, the handled/remapped error code should
1370     // only be returned if no application data was already read; if it was, the
1371     // error code should be deferred until the next call of DoPayloadRead.
1372     //
1373     // If no data was read, |*next_result| will point to the return value of
1374     // this function. If at least some data was read, |*next_result| will point
1375     // to |pending_read_error_|, to be returned in a future call to
1376     // DoPayloadRead() (e.g.: after the current data is handled).
1377     int *next_result = &rv;
1378     if (total_bytes_read > 0) {
1379       pending_read_error_ = rv;
1380       rv = total_bytes_read;
1381       next_result = &pending_read_error_;
1382     }
1383
1384     if (client_auth_cert_needed_) {
1385       *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1386     } else if (*next_result < 0) {
1387       pending_read_ssl_error_ = SSL_get_error(ssl_, *next_result);
1388       *next_result = MapOpenSSLErrorWithDetails(pending_read_ssl_error_,
1389                                                 err_tracer,
1390                                                 &pending_read_error_info_);
1391
1392       // Many servers do not reliably send a close_notify alert when shutting
1393       // down a connection, and instead terminate the TCP connection. This is
1394       // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1395       // shutdown to a graceful EOF, instead of treating it as an error as it
1396       // should be.
1397       if (*next_result == ERR_CONNECTION_CLOSED)
1398         *next_result = 0;
1399
1400       if (rv > 0 && *next_result == ERR_IO_PENDING) {
1401           // If at least some data was read from SSL_read(), do not treat
1402           // insufficient data as an error to return in the next call to
1403           // DoPayloadRead() - instead, let the call fall through to check
1404           // SSL_read() again. This is because DoTransportIO() may complete
1405           // in between the next call to DoPayloadRead(), and thus it is
1406           // important to check SSL_read() on subsequent invocations to see
1407           // if a complete record may now be read.
1408         *next_result = kNoPendingReadResult;
1409       }
1410     }
1411   }
1412
1413   if (rv >= 0) {
1414     net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1415                                   user_read_buf_->data());
1416   } else if (rv != ERR_IO_PENDING) {
1417     net_log_.AddEvent(
1418         NetLog::TYPE_SSL_READ_ERROR,
1419         CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1420                                          pending_read_error_info_));
1421     pending_read_ssl_error_ = SSL_ERROR_NONE;
1422     pending_read_error_info_ = OpenSSLErrorInfo();
1423   }
1424   return rv;
1425 }
1426
1427 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1428   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1429   int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1430   if (rv >= 0) {
1431     net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1432                                   user_write_buf_->data());
1433     return rv;
1434   }
1435
1436   int ssl_error = SSL_get_error(ssl_, rv);
1437   OpenSSLErrorInfo error_info;
1438   int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1439                                              &error_info);
1440
1441   if (net_error != ERR_IO_PENDING) {
1442     net_log_.AddEvent(
1443         NetLog::TYPE_SSL_WRITE_ERROR,
1444         CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1445   }
1446   return net_error;
1447 }
1448
1449 int SSLClientSocketOpenSSL::BufferSend(void) {
1450   if (transport_send_busy_)
1451     return ERR_IO_PENDING;
1452
1453   if (!send_buffer_.get()) {
1454     // Get a fresh send buffer out of the send BIO.
1455     size_t max_read = BIO_pending(transport_bio_);
1456     if (!max_read)
1457       return 0;  // Nothing pending in the OpenSSL write BIO.
1458     send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1459     int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1460     DCHECK_GT(read_bytes, 0);
1461     CHECK_EQ(static_cast<int>(max_read), read_bytes);
1462   }
1463
1464   int rv = transport_->socket()->Write(
1465       send_buffer_.get(),
1466       send_buffer_->BytesRemaining(),
1467       base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1468                  base::Unretained(this)));
1469   if (rv == ERR_IO_PENDING) {
1470     transport_send_busy_ = true;
1471   } else {
1472     TransportWriteComplete(rv);
1473   }
1474   return rv;
1475 }
1476
1477 int SSLClientSocketOpenSSL::BufferRecv(void) {
1478   if (transport_recv_busy_)
1479     return ERR_IO_PENDING;
1480
1481   // Determine how much was requested from |transport_bio_| that was not
1482   // actually available.
1483   size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1484   if (requested == 0) {
1485     // This is not a perfect match of error codes, as no operation is
1486     // actually pending. However, returning 0 would be interpreted as
1487     // a possible sign of EOF, which is also an inappropriate match.
1488     return ERR_IO_PENDING;
1489   }
1490
1491   // Known Issue: While only reading |requested| data is the more correct
1492   // implementation, it has the downside of resulting in frequent reads:
1493   // One read for the SSL record header (~5 bytes) and one read for the SSL
1494   // record body. Rather than issuing these reads to the underlying socket
1495   // (and constantly allocating new IOBuffers), a single Read() request to
1496   // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1497   // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1498   // traffic, this over-subscribed Read()ing will not cause issues.
1499   size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1500   if (!max_write)
1501     return ERR_IO_PENDING;
1502
1503   recv_buffer_ = new IOBuffer(max_write);
1504   int rv = transport_->socket()->Read(
1505       recv_buffer_.get(),
1506       max_write,
1507       base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1508                  base::Unretained(this)));
1509   if (rv == ERR_IO_PENDING) {
1510     transport_recv_busy_ = true;
1511   } else {
1512     rv = TransportReadComplete(rv);
1513   }
1514   return rv;
1515 }
1516
1517 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1518   transport_send_busy_ = false;
1519   TransportWriteComplete(result);
1520   OnSendComplete(result);
1521 }
1522
1523 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1524   result = TransportReadComplete(result);
1525   OnRecvComplete(result);
1526 }
1527
1528 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1529   DCHECK(ERR_IO_PENDING != result);
1530   if (result < 0) {
1531     // Record the error. Save it to be reported in a future read or write on
1532     // transport_bio_'s peer.
1533     transport_write_error_ = result;
1534     send_buffer_ = NULL;
1535   } else {
1536     DCHECK(send_buffer_.get());
1537     send_buffer_->DidConsume(result);
1538     DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1539     if (send_buffer_->BytesRemaining() <= 0)
1540       send_buffer_ = NULL;
1541   }
1542 }
1543
1544 int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1545   DCHECK(ERR_IO_PENDING != result);
1546   // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1547   // does not report success.
1548   if (result == 0)
1549     result = ERR_CONNECTION_CLOSED;
1550   if (result < 0) {
1551     DVLOG(1) << "TransportReadComplete result " << result;
1552     // Received an error. Save it to be reported in a future read on
1553     // transport_bio_'s peer.
1554     transport_read_error_ = result;
1555   } else {
1556     DCHECK(recv_buffer_.get());
1557     int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1558     // A write into a memory BIO should always succeed.
1559     DCHECK_EQ(result, ret);
1560   }
1561   recv_buffer_ = NULL;
1562   transport_recv_busy_ = false;
1563   return result;
1564 }
1565
1566 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
1567   DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1568   DCHECK(ssl == ssl_);
1569
1570   // Clear any currently configured certificates.
1571   SSL_certs_clear(ssl_);
1572
1573 #if defined(OS_IOS)
1574   // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1575   LOG(WARNING) << "Client auth is not supported";
1576 #else  // !defined(OS_IOS)
1577   if (!ssl_config_.send_client_cert) {
1578     // First pass: we know that a client certificate is needed, but we do not
1579     // have one at hand.
1580     client_auth_cert_needed_ = true;
1581     STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1582     for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
1583       X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1584       unsigned char* str = NULL;
1585       int length = i2d_X509_NAME(ca_name, &str);
1586       cert_authorities_.push_back(std::string(
1587           reinterpret_cast<const char*>(str),
1588           static_cast<size_t>(length)));
1589       OPENSSL_free(str);
1590     }
1591
1592     const unsigned char* client_cert_types;
1593     size_t num_client_cert_types =
1594         SSL_get0_certificate_types(ssl, &client_cert_types);
1595     for (size_t i = 0; i < num_client_cert_types; i++) {
1596       cert_key_types_.push_back(
1597           static_cast<SSLClientCertType>(client_cert_types[i]));
1598     }
1599
1600     return -1;  // Suspends handshake.
1601   }
1602
1603   // Second pass: a client certificate should have been selected.
1604   if (ssl_config_.client_cert.get()) {
1605     ScopedX509 leaf_x509 =
1606         OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1607     if (!leaf_x509) {
1608       LOG(WARNING) << "Failed to import certificate";
1609       OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1610       return -1;
1611     }
1612
1613     ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1614         ssl_config_.client_cert->GetIntermediateCertificates());
1615     if (!chain) {
1616       LOG(WARNING) << "Failed to import intermediate certificates";
1617       OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1618       return -1;
1619     }
1620
1621     // TODO(davidben): With Linux client auth support, this should be
1622     // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1623     // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1624     // net/ client auth API lacking a private key handle.
1625 #if defined(USE_OPENSSL_CERTS)
1626     crypto::ScopedEVP_PKEY privkey =
1627         OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1628             ssl_config_.client_cert.get());
1629 #else  // !defined(USE_OPENSSL_CERTS)
1630     crypto::ScopedEVP_PKEY privkey =
1631         FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1632 #endif  // defined(USE_OPENSSL_CERTS)
1633     if (!privkey) {
1634       // Could not find the private key. Fail the handshake and surface an
1635       // appropriate error to the caller.
1636       LOG(WARNING) << "Client cert found without private key";
1637       OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1638       return -1;
1639     }
1640
1641     if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1642         !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1643         !SSL_set1_chain(ssl_, chain.get())) {
1644       LOG(WARNING) << "Failed to set client certificate";
1645       return -1;
1646     }
1647     return 1;
1648   }
1649 #endif  // defined(OS_IOS)
1650
1651   // Send no client certificate.
1652   return 1;
1653 }
1654
1655 int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1656   if (!completed_connect_) {
1657     // If the first handshake hasn't completed then we accept any certificates
1658     // because we verify after the handshake.
1659     return 1;
1660   }
1661
1662   // Disallow the server certificate to change in a renegotiation.
1663   if (server_cert_chain_->empty()) {
1664     LOG(ERROR) << "Received invalid certificate chain between handshakes";
1665     return 0;
1666   }
1667   base::StringPiece old_der, new_der;
1668   if (store_ctx->cert == NULL ||
1669       !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1670       !x509_util::GetDER(store_ctx->cert, &new_der)) {
1671     LOG(ERROR) << "Failed to encode certificates";
1672     return 0;
1673   }
1674   if (old_der != new_der) {
1675     LOG(ERROR) << "Server certificate changed between handshakes";
1676     return 0;
1677   }
1678
1679   return 1;
1680 }
1681
1682 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1683 // server supports NPN, selects a protocol from the list that the server
1684 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1685 // callback can assume that |in| is syntactically valid.
1686 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1687                                                     unsigned char* outlen,
1688                                                     const unsigned char* in,
1689                                                     unsigned int inlen) {
1690   if (ssl_config_.next_protos.empty()) {
1691     *out = reinterpret_cast<uint8*>(
1692         const_cast<char*>(kDefaultSupportedNPNProtocol));
1693     *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1694     npn_status_ = kNextProtoUnsupported;
1695     return SSL_TLSEXT_ERR_OK;
1696   }
1697
1698   // Assume there's no overlap between our protocols and the server's list.
1699   npn_status_ = kNextProtoNoOverlap;
1700
1701   // For each protocol in server preference order, see if we support it.
1702   for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1703     for (std::vector<std::string>::const_iterator
1704              j = ssl_config_.next_protos.begin();
1705          j != ssl_config_.next_protos.end(); ++j) {
1706       if (in[i] == j->size() &&
1707           memcmp(&in[i + 1], j->data(), in[i]) == 0) {
1708         // We found a match.
1709         *out = const_cast<unsigned char*>(in) + i + 1;
1710         *outlen = in[i];
1711         npn_status_ = kNextProtoNegotiated;
1712         break;
1713       }
1714     }
1715     if (npn_status_ == kNextProtoNegotiated)
1716       break;
1717   }
1718
1719   // If we didn't find a protocol, we select the first one from our list.
1720   if (npn_status_ == kNextProtoNoOverlap) {
1721     *out = reinterpret_cast<uint8*>(const_cast<char*>(
1722         ssl_config_.next_protos[0].data()));
1723     *outlen = ssl_config_.next_protos[0].size();
1724   }
1725
1726   npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
1727   DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
1728   set_negotiation_extension(kExtensionNPN);
1729   return SSL_TLSEXT_ERR_OK;
1730 }
1731
1732 long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1733     BIO *bio,
1734     int cmd,
1735     const char *argp, int argi, long argl,
1736     long retvalue) {
1737   if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1738     // If there is no more data in the buffer, report any pending errors that
1739     // were observed. Note that both the readbuf and the writebuf are checked
1740     // for errors, since the application may have encountered a socket error
1741     // while writing that would otherwise not be reported until the application
1742     // attempted to write again - which it may never do. See
1743     // https://crbug.com/249848.
1744     if (transport_read_error_ != OK) {
1745       OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1746       return -1;
1747     }
1748     if (transport_write_error_ != OK) {
1749       OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1750       return -1;
1751     }
1752   } else if (cmd == BIO_CB_WRITE) {
1753     // Because of the write buffer, this reports a failure from the previous
1754     // write payload. If the current payload fails to write, the error will be
1755     // reported in a future write or read to |bio|.
1756     if (transport_write_error_ != OK) {
1757       OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1758       return -1;
1759     }
1760   }
1761   return retvalue;
1762 }
1763
1764 // static
1765 long SSLClientSocketOpenSSL::BIOCallback(
1766     BIO *bio,
1767     int cmd,
1768     const char *argp, int argi, long argl,
1769     long retvalue) {
1770   SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1771       BIO_get_callback_arg(bio));
1772   CHECK(socket);
1773   return socket->MaybeReplayTransportError(
1774       bio, cmd, argp, argi, argl, retvalue);
1775 }
1776
1777 // static
1778 void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1779                                           int type,
1780                                           int /*val*/) {
1781   if (type == SSL_CB_HANDSHAKE_DONE) {
1782     SSLClientSocketOpenSSL* ssl_socket =
1783         SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1784     ssl_socket->handshake_succeeded_ = true;
1785     ssl_socket->CheckIfHandshakeFinished();
1786   }
1787 }
1788
1789 // Determines if both the handshake and certificate verification have completed
1790 // successfully, and calls the handshake completion callback if that is the
1791 // case.
1792 //
1793 // CheckIfHandshakeFinished is called twice per connection: once after
1794 // MarkSSLSessionAsGood, when the certificate has been verified, and
1795 // once via an OpenSSL callback when the handshake has completed. On the
1796 // second call, when the certificate has been verified and the handshake
1797 // has completed, the connection's handshake completion callback is run.
1798 void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1799   if (handshake_succeeded_ && marked_session_as_good_)
1800     OnHandshakeCompletion();
1801 }
1802
1803 void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1804   for (ct::SCTList::const_iterator iter =
1805        ct_verify_result_.verified_scts.begin();
1806        iter != ct_verify_result_.verified_scts.end(); ++iter) {
1807     ssl_info->signed_certificate_timestamps.push_back(
1808         SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1809   }
1810   for (ct::SCTList::const_iterator iter =
1811        ct_verify_result_.invalid_scts.begin();
1812        iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1813     ssl_info->signed_certificate_timestamps.push_back(
1814         SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1815   }
1816   for (ct::SCTList::const_iterator iter =
1817        ct_verify_result_.unknown_logs_scts.begin();
1818        iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1819     ssl_info->signed_certificate_timestamps.push_back(
1820         SignedCertificateTimestampAndStatus(*iter,
1821                                             ct::SCT_STATUS_LOG_UNKNOWN));
1822   }
1823 }
1824
1825 scoped_refptr<X509Certificate>
1826 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1827   return server_cert_;
1828 }
1829
1830 }  // namespace net