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