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 // This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived
      6 // from AuthCertificateCallback() in
      7 // mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp.
      8 
      9 /* ***** BEGIN LICENSE BLOCK *****
     10  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
     11  *
     12  * The contents of this file are subject to the Mozilla Public License Version
     13  * 1.1 (the "License"); you may not use this file except in compliance with
     14  * the License. You may obtain a copy of the License at
     15  * http://www.mozilla.org/MPL/
     16  *
     17  * Software distributed under the License is distributed on an "AS IS" basis,
     18  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
     19  * for the specific language governing rights and limitations under the
     20  * License.
     21  *
     22  * The Original Code is the Netscape security libraries.
     23  *
     24  * The Initial Developer of the Original Code is
     25  * Netscape Communications Corporation.
     26  * Portions created by the Initial Developer are Copyright (C) 2000
     27  * the Initial Developer. All Rights Reserved.
     28  *
     29  * Contributor(s):
     30  *   Ian McGreer <mcgreer (at) netscape.com>
     31  *   Javier Delgadillo <javi (at) netscape.com>
     32  *   Kai Engert <kengert (at) redhat.com>
     33  *
     34  * Alternatively, the contents of this file may be used under the terms of
     35  * either the GNU General Public License Version 2 or later (the "GPL"), or
     36  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
     37  * in which case the provisions of the GPL or the LGPL are applicable instead
     38  * of those above. If you wish to allow use of your version of this file only
     39  * under the terms of either the GPL or the LGPL, and not to allow others to
     40  * use your version of this file under the terms of the MPL, indicate your
     41  * decision by deleting the provisions above and replace them with the notice
     42  * and other provisions required by the GPL or the LGPL. If you do not delete
     43  * the provisions above, a recipient may use your version of this file under
     44  * the terms of any one of the MPL, the GPL or the LGPL.
     45  *
     46  * ***** END LICENSE BLOCK ***** */
     47 
     48 #include "net/socket/ssl_client_socket_nss.h"
     49 
     50 #include <certdb.h>
     51 #include <hasht.h>
     52 #include <keyhi.h>
     53 #include <nspr.h>
     54 #include <nss.h>
     55 #include <ocsp.h>
     56 #include <pk11pub.h>
     57 #include <secerr.h>
     58 #include <sechash.h>
     59 #include <ssl.h>
     60 #include <sslerr.h>
     61 #include <sslproto.h>
     62 
     63 #include <algorithm>
     64 #include <limits>
     65 #include <map>
     66 
     67 #include "base/bind.h"
     68 #include "base/bind_helpers.h"
     69 #include "base/callback_helpers.h"
     70 #include "base/compiler_specific.h"
     71 #include "base/logging.h"
     72 #include "base/memory/singleton.h"
     73 #include "base/metrics/histogram.h"
     74 #include "base/single_thread_task_runner.h"
     75 #include "base/stl_util.h"
     76 #include "base/strings/string_number_conversions.h"
     77 #include "base/strings/string_util.h"
     78 #include "base/strings/stringprintf.h"
     79 #include "base/thread_task_runner_handle.h"
     80 #include "base/threading/thread_restrictions.h"
     81 #include "base/values.h"
     82 #include "crypto/ec_private_key.h"
     83 #include "crypto/nss_util.h"
     84 #include "crypto/nss_util_internal.h"
     85 #include "crypto/rsa_private_key.h"
     86 #include "crypto/scoped_nss_types.h"
     87 #include "net/base/address_list.h"
     88 #include "net/base/connection_type_histograms.h"
     89 #include "net/base/dns_util.h"
     90 #include "net/base/io_buffer.h"
     91 #include "net/base/net_errors.h"
     92 #include "net/base/net_log.h"
     93 #include "net/cert/asn1_util.h"
     94 #include "net/cert/cert_status_flags.h"
     95 #include "net/cert/cert_verifier.h"
     96 #include "net/cert/ct_objects_extractor.h"
     97 #include "net/cert/ct_verifier.h"
     98 #include "net/cert/ct_verify_result.h"
     99 #include "net/cert/scoped_nss_types.h"
    100 #include "net/cert/sct_status_flags.h"
    101 #include "net/cert/single_request_cert_verifier.h"
    102 #include "net/cert/x509_certificate_net_log_param.h"
    103 #include "net/cert/x509_util.h"
    104 #include "net/http/transport_security_state.h"
    105 #include "net/ocsp/nss_ocsp.h"
    106 #include "net/socket/client_socket_handle.h"
    107 #include "net/socket/nss_ssl_util.h"
    108 #include "net/socket/ssl_error_params.h"
    109 #include "net/ssl/ssl_cert_request_info.h"
    110 #include "net/ssl/ssl_connection_status_flags.h"
    111 #include "net/ssl/ssl_info.h"
    112 
    113 #if defined(OS_WIN)
    114 #include <windows.h>
    115 #include <wincrypt.h>
    116 
    117 #include "base/win/windows_version.h"
    118 #elif defined(OS_MACOSX)
    119 #include <Security/SecBase.h>
    120 #include <Security/SecCertificate.h>
    121 #include <Security/SecIdentity.h>
    122 
    123 #include "base/mac/mac_logging.h"
    124 #include "base/synchronization/lock.h"
    125 #include "crypto/mac_security_services_lock.h"
    126 #elif defined(USE_NSS)
    127 #include <dlfcn.h>
    128 #endif
    129 
    130 namespace net {
    131 
    132 // State machines are easier to debug if you log state transitions.
    133 // Enable these if you want to see what's going on.
    134 #if 1
    135 #define EnterFunction(x)
    136 #define LeaveFunction(x)
    137 #define GotoState(s) next_handshake_state_ = s
    138 #else
    139 #define EnterFunction(x)\
    140     VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
    141             << "; next_handshake_state " << next_handshake_state_
    142 #define LeaveFunction(x)\
    143     VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
    144             << "; next_handshake_state " << next_handshake_state_
    145 #define GotoState(s)\
    146     do {\
    147       VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
    148       next_handshake_state_ = s;\
    149     } while (0)
    150 #endif
    151 
    152 namespace {
    153 
    154 // SSL plaintext fragments are shorter than 16KB. Although the record layer
    155 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
    156 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
    157 // entire SSL record.
    158 const int kRecvBufferSize = 17 * 1024;
    159 const int kSendBufferSize = 17 * 1024;
    160 
    161 // Used by SSLClientSocketNSS::Core to indicate there is no read result
    162 // obtained by a previous operation waiting to be returned to the caller.
    163 // This constant can be any non-negative/non-zero value (eg: it does not
    164 // overlap with any value of the net::Error range, including net::OK).
    165 const int kNoPendingReadResult = 1;
    166 
    167 #if defined(OS_WIN)
    168 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
    169 // set on Windows XP without error. There is some overhead from the server
    170 // sending the OCSP response if it supports the extension, for the subset of
    171 // XP clients who will request it but be unable to use it, but this is an
    172 // acceptable trade-off for simplicity of implementation.
    173 bool IsOCSPStaplingSupported() {
    174   return true;
    175 }
    176 #elif defined(USE_NSS)
    177 typedef SECStatus
    178 (*CacheOCSPResponseFromSideChannelFunction)(
    179     CERTCertDBHandle *handle, CERTCertificate *cert, PRTime time,
    180     SECItem *encodedResponse, void *pwArg);
    181 
    182 // On Linux, we dynamically link against the system version of libnss3.so. In
    183 // order to continue working on systems without up-to-date versions of NSS we
    184 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
    185 
    186 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
    187 // runtime symbol resolution that we need.
    188 class RuntimeLibNSSFunctionPointers {
    189  public:
    190   CacheOCSPResponseFromSideChannelFunction
    191   GetCacheOCSPResponseFromSideChannelFunction() {
    192     return cache_ocsp_response_from_side_channel_;
    193   }
    194 
    195   static RuntimeLibNSSFunctionPointers* GetInstance() {
    196     return Singleton<RuntimeLibNSSFunctionPointers>::get();
    197   }
    198 
    199  private:
    200   friend struct DefaultSingletonTraits<RuntimeLibNSSFunctionPointers>;
    201 
    202   RuntimeLibNSSFunctionPointers() {
    203     cache_ocsp_response_from_side_channel_ =
    204         (CacheOCSPResponseFromSideChannelFunction)
    205         dlsym(RTLD_DEFAULT, "CERT_CacheOCSPResponseFromSideChannel");
    206   }
    207 
    208   CacheOCSPResponseFromSideChannelFunction
    209       cache_ocsp_response_from_side_channel_;
    210 };
    211 
    212 CacheOCSPResponseFromSideChannelFunction
    213 GetCacheOCSPResponseFromSideChannelFunction() {
    214   return RuntimeLibNSSFunctionPointers::GetInstance()
    215     ->GetCacheOCSPResponseFromSideChannelFunction();
    216 }
    217 
    218 bool IsOCSPStaplingSupported() {
    219   return GetCacheOCSPResponseFromSideChannelFunction() != NULL;
    220 }
    221 #else
    222 // TODO(agl): Figure out if we can plumb the OCSP response into Mac's system
    223 // certificate validation functions.
    224 bool IsOCSPStaplingSupported() {
    225   return false;
    226 }
    227 #endif
    228 
    229 #if defined(OS_WIN)
    230 
    231 // This callback is intended to be used with CertFindChainInStore. In addition
    232 // to filtering by extended/enhanced key usage, we do not show expired
    233 // certificates and require digital signature usage in the key usage
    234 // extension.
    235 //
    236 // This matches our behavior on Mac OS X and that of NSS. It also matches the
    237 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
    238 // http://blogs.msdn.com/b/askie/archive/2009/06/09/my-expired-client-certificates-no-longer-display-when-connecting-to-my-web-server-using-ie8.aspx
    239 BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
    240                                    void* find_arg) {
    241   VLOG(1) << "Calling ClientCertFindCallback from _nss";
    242   // Verify the certificate's KU is good.
    243   BYTE key_usage;
    244   if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
    245                               &key_usage, 1)) {
    246     if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
    247       return FALSE;
    248   } else {
    249     DWORD err = GetLastError();
    250     // If |err| is non-zero, it's an actual error. Otherwise the extension
    251     // just isn't present, and we treat it as if everything was allowed.
    252     if (err) {
    253       DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
    254       return FALSE;
    255     }
    256   }
    257 
    258   // Verify the current time is within the certificate's validity period.
    259   if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
    260     return FALSE;
    261 
    262   // Verify private key metadata is associated with this certificate.
    263   DWORD size = 0;
    264   if (!CertGetCertificateContextProperty(
    265           cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
    266     return FALSE;
    267   }
    268 
    269   return TRUE;
    270 }
    271 
    272 #endif
    273 
    274 void DestroyCertificates(CERTCertificate** certs, size_t len) {
    275   for (size_t i = 0; i < len; i++)
    276     CERT_DestroyCertificate(certs[i]);
    277 }
    278 
    279 // Helper functions to make it possible to log events from within the
    280 // SSLClientSocketNSS::Core.
    281 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
    282                  NetLog::EventType event_type) {
    283   if (!net_log)
    284     return;
    285   net_log->AddEvent(event_type);
    286 }
    287 
    288 // Helper function to make it possible to log events from within the
    289 // SSLClientSocketNSS::Core.
    290 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
    291                              NetLog::EventType event_type,
    292                              const NetLog::ParametersCallback& callback) {
    293   if (!net_log)
    294     return;
    295   net_log->AddEvent(event_type, callback);
    296 }
    297 
    298 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
    299 // from within the SSLClientSocketNSS::Core.
    300 // AddByteTransferEvent expects to receive a const char*, which within the
    301 // Core is backed by an IOBuffer. If the "const char*" is bound via
    302 // base::Bind and posted to another thread, and the IOBuffer that backs that
    303 // pointer then goes out of scope on the origin thread, this would result in
    304 // an invalid read of a stale pointer.
    305 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
    306 // to the owning IOBuffer can be bound to the Callback. This ensures that the
    307 // IOBuffer will stay alive long enough to cross threads if needed.
    308 void LogByteTransferEvent(
    309     const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
    310     int len, IOBuffer* buffer) {
    311   if (!net_log)
    312     return;
    313   net_log->AddByteTransferEvent(event_type, len, buffer->data());
    314 }
    315 
    316 // PeerCertificateChain is a helper object which extracts the certificate
    317 // chain, as given by the server, from an NSS socket and performs the needed
    318 // resource management. The first element of the chain is the leaf certificate
    319 // and the other elements are in the order given by the server.
    320 class PeerCertificateChain {
    321  public:
    322   PeerCertificateChain() {}
    323   PeerCertificateChain(const PeerCertificateChain& other);
    324   ~PeerCertificateChain();
    325   PeerCertificateChain& operator=(const PeerCertificateChain& other);
    326 
    327   // Resets the current chain, freeing any resources, and updates the current
    328   // chain to be a copy of the chain stored in |nss_fd|.
    329   // If |nss_fd| is NULL, then the current certificate chain will be freed.
    330   void Reset(PRFileDesc* nss_fd);
    331 
    332   // Returns the current certificate chain as a vector of DER-encoded
    333   // base::StringPieces. The returned vector remains valid until Reset is
    334   // called.
    335   std::vector<base::StringPiece> AsStringPieceVector() const;
    336 
    337   bool empty() const { return certs_.empty(); }
    338   size_t size() const { return certs_.size(); }
    339 
    340   CERTCertificate* operator[](size_t index) const {
    341     DCHECK_LT(index, certs_.size());
    342     return certs_[index];
    343   }
    344 
    345  private:
    346   std::vector<CERTCertificate*> certs_;
    347 };
    348 
    349 PeerCertificateChain::PeerCertificateChain(
    350     const PeerCertificateChain& other) {
    351   *this = other;
    352 }
    353 
    354 PeerCertificateChain::~PeerCertificateChain() {
    355   Reset(NULL);
    356 }
    357 
    358 PeerCertificateChain& PeerCertificateChain::operator=(
    359     const PeerCertificateChain& other) {
    360   if (this == &other)
    361     return *this;
    362 
    363   Reset(NULL);
    364   certs_.reserve(other.certs_.size());
    365   for (size_t i = 0; i < other.certs_.size(); ++i)
    366     certs_.push_back(CERT_DupCertificate(other.certs_[i]));
    367 
    368   return *this;
    369 }
    370 
    371 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
    372   for (size_t i = 0; i < certs_.size(); ++i)
    373     CERT_DestroyCertificate(certs_[i]);
    374   certs_.clear();
    375 
    376   if (nss_fd == NULL)
    377     return;
    378 
    379   CERTCertList* list = SSL_PeerCertificateChain(nss_fd);
    380   // The handshake on |nss_fd| may not have completed.
    381   if (list == NULL)
    382     return;
    383 
    384   for (CERTCertListNode* node = CERT_LIST_HEAD(list);
    385        !CERT_LIST_END(node, list); node = CERT_LIST_NEXT(node)) {
    386     certs_.push_back(CERT_DupCertificate(node->cert));
    387   }
    388   CERT_DestroyCertList(list);
    389 }
    390 
    391 std::vector<base::StringPiece>
    392 PeerCertificateChain::AsStringPieceVector() const {
    393   std::vector<base::StringPiece> v(certs_.size());
    394   for (unsigned i = 0; i < certs_.size(); i++) {
    395     v[i] = base::StringPiece(
    396         reinterpret_cast<const char*>(certs_[i]->derCert.data),
    397         certs_[i]->derCert.len);
    398   }
    399 
    400   return v;
    401 }
    402 
    403 // HandshakeState is a helper struct used to pass handshake state between
    404 // the NSS task runner and the network task runner.
    405 //
    406 // It contains members that may be read or written on the NSS task runner,
    407 // but which also need to be read from the network task runner. The NSS task
    408 // runner will notify the network task runner whenever this state changes, so
    409 // that the network task runner can safely make a copy, which avoids the need
    410 // for locking.
    411 struct HandshakeState {
    412   HandshakeState() { Reset(); }
    413 
    414   void Reset() {
    415     next_proto_status = SSLClientSocket::kNextProtoUnsupported;
    416     next_proto.clear();
    417     server_protos.clear();
    418     channel_id_sent = false;
    419     server_cert_chain.Reset(NULL);
    420     server_cert = NULL;
    421     sct_list_from_tls_extension.clear();
    422     stapled_ocsp_response.clear();
    423     resumed_handshake = false;
    424     ssl_connection_status = 0;
    425   }
    426 
    427   // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
    428   // negotiated protocol stored in |next_proto|.
    429   SSLClientSocket::NextProtoStatus next_proto_status;
    430   std::string next_proto;
    431   // If the server supports NPN, the protocols supported by the server.
    432   std::string server_protos;
    433 
    434   // True if a channel ID was sent.
    435   bool channel_id_sent;
    436 
    437   // List of DER-encoded X.509 DistinguishedName of certificate authorities
    438   // allowed by the server.
    439   std::vector<std::string> cert_authorities;
    440 
    441   // Set when the handshake fully completes.
    442   //
    443   // The server certificate is first received from NSS as an NSS certificate
    444   // chain (|server_cert_chain|) and then converted into a platform-specific
    445   // X509Certificate object (|server_cert|). It's possible for some
    446   // certificates to be successfully parsed by NSS, and not by the platform
    447   // libraries (i.e.: when running within a sandbox, different parsing
    448   // algorithms, etc), so it's not safe to assume that |server_cert| will
    449   // always be non-NULL.
    450   PeerCertificateChain server_cert_chain;
    451   scoped_refptr<X509Certificate> server_cert;
    452   // SignedCertificateTimestampList received via TLS extension (RFC 6962).
    453   std::string sct_list_from_tls_extension;
    454   // Stapled OCSP response received.
    455   std::string stapled_ocsp_response;
    456 
    457   // True if the current handshake was the result of TLS session resumption.
    458   bool resumed_handshake;
    459 
    460   // The negotiated security parameters (TLS version, cipher, extensions) of
    461   // the SSL connection.
    462   int ssl_connection_status;
    463 };
    464 
    465 // Client-side error mapping functions.
    466 
    467 // Map NSS error code to network error code.
    468 int MapNSSClientError(PRErrorCode err) {
    469   switch (err) {
    470     case SSL_ERROR_BAD_CERT_ALERT:
    471     case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
    472     case SSL_ERROR_REVOKED_CERT_ALERT:
    473     case SSL_ERROR_EXPIRED_CERT_ALERT:
    474     case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
    475     case SSL_ERROR_UNKNOWN_CA_ALERT:
    476     case SSL_ERROR_ACCESS_DENIED_ALERT:
    477       return ERR_BAD_SSL_CLIENT_AUTH_CERT;
    478     default:
    479       return MapNSSError(err);
    480   }
    481 }
    482 
    483 // Map NSS error code from the first SSL handshake to network error code.
    484 int MapNSSClientHandshakeError(PRErrorCode err) {
    485   switch (err) {
    486     // If the server closed on us, it is a protocol error.
    487     // Some TLS-intolerant servers do this when we request TLS.
    488     case PR_END_OF_FILE_ERROR:
    489       return ERR_SSL_PROTOCOL_ERROR;
    490     default:
    491       return MapNSSClientError(err);
    492   }
    493 }
    494 
    495 }  // namespace
    496 
    497 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
    498 // able to marshal data between NSS functions and an underlying transport
    499 // socket.
    500 //
    501 // All public functions are meant to be called from the network task runner,
    502 // and any callbacks supplied will be invoked there as well, provided that
    503 // Detach() has not been called yet.
    504 //
    505 /////////////////////////////////////////////////////////////////////////////
    506 //
    507 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
    508 //
    509 // Because NSS may block on either hardware or user input during operations
    510 // such as signing, creating certificates, or locating private keys, the Core
    511 // handles all of the interactions with the underlying NSS SSL socket, so
    512 // that these blocking calls can be executed on a dedicated task runner.
    513 //
    514 // Note that the network task runner and the NSS task runner may be executing
    515 // on the same thread. If that happens, then it's more performant to try to
    516 // complete as much work as possible synchronously, even if it might block,
    517 // rather than continually PostTask-ing to the same thread.
    518 //
    519 // Because NSS functions should only be called on the NSS task runner, while
    520 // I/O resources should only be accessed on the network task runner, most
    521 // public functions are implemented via three methods, each with different
    522 // task runner affinities.
    523 //
    524 // In the single-threaded mode (where the network and NSS task runners run on
    525 // the same thread), these are all attempted synchronously, while in the
    526 // multi-threaded mode, message passing is used.
    527 //
    528 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
    529 //    DoHandshake)
    530 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
    531 //    (BufferRecv, BufferSend)
    532 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
    533 //    DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete)
    534 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
    535 //    data from the network task runner back to NSS (BufferRecvComplete,
    536 //    BufferSendComplete, OnHandshakeIOComplete)
    537 //
    538 /////////////////////////////////////////////////////////////////////////////
    539 // Single-threaded example
    540 //
    541 // |--------------------------Network Task Runner--------------------------|
    542 //  SSLClientSocketNSS              Core               (Transport Socket)
    543 //       Read()
    544 //         |-------------------------V
    545 //                                 Read()
    546 //                                   |
    547 //                            DoPayloadRead()
    548 //                                   |
    549 //                               BufferRecv()
    550 //                                   |
    551 //                              DoBufferRecv()
    552 //                                   |-------------------------V
    553 //                                                           Read()
    554 //                                   V-------------------------|
    555 //                          BufferRecvComplete()
    556 //                                   |
    557 //                           PostOrRunCallback()
    558 //         V-------------------------|
    559 //    (Read Callback)
    560 //
    561 /////////////////////////////////////////////////////////////////////////////
    562 // Multi-threaded example:
    563 //
    564 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
    565 //  SSLClientSocketNSS          Core            Socket         Core
    566 //       Read()
    567 //         |---------------------V
    568 //                             Read()
    569 //                               |-------------------------------V
    570 //                                                             Read()
    571 //                                                               |
    572 //                                                         DoPayloadRead()
    573 //                                                               |
    574 //                                                          BufferRecv
    575 //                               V-------------------------------|
    576 //                          DoBufferRecv
    577 //                               |----------------V
    578 //                                              Read()
    579 //                               V----------------|
    580 //                        BufferRecvComplete()
    581 //                               |-------------------------------V
    582 //                                                      BufferRecvComplete()
    583 //                                                               |
    584 //                                                       PostOrRunCallback()
    585 //                               V-------------------------------|
    586 //                        PostOrRunCallback()
    587 //         V---------------------|
    588 //    (Read Callback)
    589 //
    590 /////////////////////////////////////////////////////////////////////////////
    591 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
    592  public:
    593   // Creates a new Core.
    594   //
    595   // Any calls to NSS are executed on the |nss_task_runner|, while any calls
    596   // that need to operate on the underlying transport, net log, or server
    597   // bound certificate fetching will happen on the |network_task_runner|, so
    598   // that their lifetimes match that of the owning SSLClientSocketNSS.
    599   //
    600   // The caller retains ownership of |transport|, |net_log|, and
    601   // |server_bound_cert_service|, and they will not be accessed once Detach()
    602   // has been called.
    603   Core(base::SequencedTaskRunner* network_task_runner,
    604        base::SequencedTaskRunner* nss_task_runner,
    605        ClientSocketHandle* transport,
    606        const HostPortPair& host_and_port,
    607        const SSLConfig& ssl_config,
    608        BoundNetLog* net_log,
    609        ServerBoundCertService* server_bound_cert_service);
    610 
    611   // Called on the network task runner.
    612   // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
    613   // underlying memio implementation, to the Core. Returns true if the Core
    614   // was successfully registered with the socket.
    615   bool Init(PRFileDesc* socket, memio_Private* buffers);
    616 
    617   // Called on the network task runner.
    618   // Sets the predicted certificate chain that the peer will send, for use
    619   // with the TLS CachedInfo extension. If called, it must not be called
    620   // before Init() or after Connect().
    621   void SetPredictedCertificates(
    622       const std::vector<std::string>& predicted_certificates);
    623 
    624   // Called on the network task runner.
    625   //
    626   // Attempts to perform an SSL handshake. If the handshake cannot be
    627   // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
    628   // the network task runner once the handshake has completed. Otherwise,
    629   // returns OK on success or a network error code on failure.
    630   int Connect(const CompletionCallback& callback);
    631 
    632   // Called on the network task runner.
    633   // Signals that the resources owned by the network task runner are going
    634   // away. No further callbacks will be invoked on the network task runner.
    635   // May be called at any time.
    636   void Detach();
    637 
    638   // Called on the network task runner.
    639   // Returns the current state of the underlying SSL socket. May be called at
    640   // any time.
    641   const HandshakeState& state() const { return network_handshake_state_; }
    642 
    643   // Called on the network task runner.
    644   // Read() and Write() mirror the net::Socket functions of the same name.
    645   // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
    646   // task runner at a later point, unless the caller calls Detach().
    647   int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
    648   int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
    649 
    650   // Called on the network task runner.
    651   bool IsConnected();
    652   bool HasPendingAsyncOperation();
    653   bool HasUnhandledReceivedData();
    654 
    655   // Called on the network task runner.
    656   // Causes the associated SSL/TLS session ID to be added to NSS's session
    657   // cache, but only if the connection has not been False Started.
    658   //
    659   // This should only be called after the server's certificate has been
    660   // verified, and may not be called within an NSS callback.
    661   void CacheSessionIfNecessary();
    662 
    663  private:
    664   friend class base::RefCountedThreadSafe<Core>;
    665   ~Core();
    666 
    667   enum State {
    668     STATE_NONE,
    669     STATE_HANDSHAKE,
    670     STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
    671   };
    672 
    673   bool OnNSSTaskRunner() const;
    674   bool OnNetworkTaskRunner() const;
    675 
    676   ////////////////////////////////////////////////////////////////////////////
    677   // Methods that are ONLY called on the NSS task runner:
    678   ////////////////////////////////////////////////////////////////////////////
    679 
    680   // Called by NSS during full handshakes to allow the application to
    681   // verify the certificate. Instead of verifying the certificate in the midst
    682   // of the handshake, SECSuccess is always returned and the peer's certificate
    683   // is verified afterwards.
    684   // This behaviour is an artifact of the original SSLClientSocketWin
    685   // implementation, which could not verify the peer's certificate until after
    686   // the handshake had completed, as well as bugs in NSS that prevent
    687   // SSL_RestartHandshakeAfterCertReq from working.
    688   static SECStatus OwnAuthCertHandler(void* arg,
    689                                       PRFileDesc* socket,
    690                                       PRBool checksig,
    691                                       PRBool is_server);
    692 
    693   // Callbacks called by NSS when the peer requests client certificate
    694   // authentication.
    695   // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
    696   // the arguments.
    697 #if defined(NSS_PLATFORM_CLIENT_AUTH)
    698   // When NSS has been integrated with awareness of the underlying system
    699   // cryptographic libraries, this callback allows the caller to supply a
    700   // native platform certificate and key for use by NSS. At most, one of
    701   // either (result_certs, result_private_key) or (result_nss_certificate,
    702   // result_nss_private_key) should be set.
    703   // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
    704   static SECStatus PlatformClientAuthHandler(
    705       void* arg,
    706       PRFileDesc* socket,
    707       CERTDistNames* ca_names,
    708       CERTCertList** result_certs,
    709       void** result_private_key,
    710       CERTCertificate** result_nss_certificate,
    711       SECKEYPrivateKey** result_nss_private_key);
    712 #else
    713   static SECStatus ClientAuthHandler(void* arg,
    714                                      PRFileDesc* socket,
    715                                      CERTDistNames* ca_names,
    716                                      CERTCertificate** result_certificate,
    717                                      SECKEYPrivateKey** result_private_key);
    718 #endif
    719 
    720   // Called by NSS to determine if we can False Start.
    721   // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
    722   static SECStatus CanFalseStartCallback(PRFileDesc* socket,
    723                                          void* arg,
    724                                          PRBool* can_false_start);
    725 
    726   // Called by NSS once the handshake has completed.
    727   // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
    728   static void HandshakeCallback(PRFileDesc* socket, void* arg);
    729 
    730   // Called once the handshake has succeeded.
    731   void HandshakeSucceeded();
    732 
    733   // Handles an NSS error generated while handshaking or performing IO.
    734   // Returns a network error code mapped from the original NSS error.
    735   int HandleNSSError(PRErrorCode error, bool handshake_error);
    736 
    737   int DoHandshakeLoop(int last_io_result);
    738   int DoReadLoop(int result);
    739   int DoWriteLoop(int result);
    740 
    741   int DoHandshake();
    742   int DoGetDBCertComplete(int result);
    743 
    744   int DoPayloadRead();
    745   int DoPayloadWrite();
    746 
    747   bool DoTransportIO();
    748   int BufferRecv();
    749   int BufferSend();
    750 
    751   void OnRecvComplete(int result);
    752   void OnSendComplete(int result);
    753 
    754   void DoConnectCallback(int result);
    755   void DoReadCallback(int result);
    756   void DoWriteCallback(int result);
    757 
    758   // Client channel ID handler.
    759   static SECStatus ClientChannelIDHandler(
    760       void* arg,
    761       PRFileDesc* socket,
    762       SECKEYPublicKey **out_public_key,
    763       SECKEYPrivateKey **out_private_key);
    764 
    765   // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
    766   // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
    767   // and an error code otherwise.
    768   // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
    769   // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
    770   // takes ownership of the |*cert| and |*key|.
    771   int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
    772 
    773   // Updates the NSS and platform specific certificates.
    774   void UpdateServerCert();
    775   // Update the nss_handshake_state_ with the SignedCertificateTimestampList
    776   // received in the handshake via a TLS extension.
    777   void UpdateSignedCertTimestamps();
    778   // Update the OCSP response cache with the stapled response received in the
    779   // handshake, and update nss_handshake_state_ with
    780   // the SignedCertificateTimestampList received in the stapled OCSP response.
    781   void UpdateStapledOCSPResponse();
    782   // Updates the nss_handshake_state_ with the negotiated security parameters.
    783   void UpdateConnectionStatus();
    784   // Record histograms for channel id support during full handshakes - resumed
    785   // handshakes are ignored.
    786   void RecordChannelIDSupportOnNSSTaskRunner();
    787   // UpdateNextProto gets any application-layer protocol that may have been
    788   // negotiated by the TLS connection.
    789   void UpdateNextProto();
    790 
    791   ////////////////////////////////////////////////////////////////////////////
    792   // Methods that are ONLY called on the network task runner:
    793   ////////////////////////////////////////////////////////////////////////////
    794   int DoBufferRecv(IOBuffer* buffer, int len);
    795   int DoBufferSend(IOBuffer* buffer, int len);
    796   int DoGetDomainBoundCert(const std::string& host);
    797 
    798   void OnGetDomainBoundCertComplete(int result);
    799   void OnHandshakeStateUpdated(const HandshakeState& state);
    800   void OnNSSBufferUpdated(int amount_in_read_buffer);
    801   void DidNSSRead(int result);
    802   void DidNSSWrite(int result);
    803   void RecordChannelIDSupportOnNetworkTaskRunner(
    804       bool negotiated_channel_id,
    805       bool channel_id_enabled,
    806       bool supports_ecc) const;
    807 
    808   ////////////////////////////////////////////////////////////////////////////
    809   // Methods that are called on both the network task runner and the NSS
    810   // task runner.
    811   ////////////////////////////////////////////////////////////////////////////
    812   void OnHandshakeIOComplete(int result);
    813   void BufferRecvComplete(IOBuffer* buffer, int result);
    814   void BufferSendComplete(int result);
    815 
    816   // PostOrRunCallback is a helper function to ensure that |callback| is
    817   // invoked on the network task runner, but only if Detach() has not yet
    818   // been called.
    819   void PostOrRunCallback(const tracked_objects::Location& location,
    820                          const base::Closure& callback);
    821 
    822   // Uses PostOrRunCallback and |weak_net_log_| to try and log a
    823   // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
    824   void AddCertProvidedEvent(int cert_count);
    825 
    826   // Sets the handshake state |channel_id_sent| flag and logs the
    827   // SSL_CHANNEL_ID_PROVIDED event.
    828   void SetChannelIDProvided();
    829 
    830   ////////////////////////////////////////////////////////////////////////////
    831   // Members that are ONLY accessed on the network task runner:
    832   ////////////////////////////////////////////////////////////////////////////
    833 
    834   // True if the owning SSLClientSocketNSS has called Detach(). No further
    835   // callbacks will be invoked nor access to members owned by the network
    836   // task runner.
    837   bool detached_;
    838 
    839   // The underlying transport to use for network IO.
    840   ClientSocketHandle* transport_;
    841   base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
    842 
    843   // The current handshake state. Mirrors |nss_handshake_state_|.
    844   HandshakeState network_handshake_state_;
    845 
    846   // The service for retrieving Channel ID keys.  May be NULL.
    847   ServerBoundCertService* server_bound_cert_service_;
    848   ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_;
    849 
    850   // The information about NSS task runner.
    851   int unhandled_buffer_size_;
    852   bool nss_waiting_read_;
    853   bool nss_waiting_write_;
    854   bool nss_is_closed_;
    855 
    856   ////////////////////////////////////////////////////////////////////////////
    857   // Members that are ONLY accessed on the NSS task runner:
    858   ////////////////////////////////////////////////////////////////////////////
    859   HostPortPair host_and_port_;
    860   SSLConfig ssl_config_;
    861 
    862   // NSS SSL socket.
    863   PRFileDesc* nss_fd_;
    864 
    865   // Buffers for the network end of the SSL state machine
    866   memio_Private* nss_bufs_;
    867 
    868   // Used by DoPayloadRead() when attempting to fill the caller's buffer with
    869   // as much data as possible, without blocking.
    870   // If DoPayloadRead() encounters an error after having read some data, stores
    871   // the results to return on the *next* call to DoPayloadRead(). A value of
    872   // kNoPendingReadResult indicates there is no pending result, otherwise 0
    873   // indicates EOF and < 0 indicates an error.
    874   int pending_read_result_;
    875   // Contains the previously observed NSS error. Only valid when
    876   // pending_read_result_ != kNoPendingReadResult.
    877   PRErrorCode pending_read_nss_error_;
    878 
    879   // The certificate chain, in DER form, that is expected to be received from
    880   // the server.
    881   std::vector<std::string> predicted_certs_;
    882 
    883   State next_handshake_state_;
    884 
    885   // True if channel ID extension was negotiated.
    886   bool channel_id_xtn_negotiated_;
    887   // True if the handshake state machine was interrupted for channel ID.
    888   bool channel_id_needed_;
    889   // True if the handshake state machine was interrupted for client auth.
    890   bool client_auth_cert_needed_;
    891   // True if NSS has False Started.
    892   bool false_started_;
    893   // True if NSS has called HandshakeCallback.
    894   bool handshake_callback_called_;
    895 
    896   HandshakeState nss_handshake_state_;
    897 
    898   bool transport_recv_busy_;
    899   bool transport_recv_eof_;
    900   bool transport_send_busy_;
    901 
    902   // Used by Read function.
    903   scoped_refptr<IOBuffer> user_read_buf_;
    904   int user_read_buf_len_;
    905 
    906   // Used by Write function.
    907   scoped_refptr<IOBuffer> user_write_buf_;
    908   int user_write_buf_len_;
    909 
    910   CompletionCallback user_connect_callback_;
    911   CompletionCallback user_read_callback_;
    912   CompletionCallback user_write_callback_;
    913 
    914   ////////////////////////////////////////////////////////////////////////////
    915   // Members that are accessed on both the network task runner and the NSS
    916   // task runner.
    917   ////////////////////////////////////////////////////////////////////////////
    918   scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
    919   scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
    920 
    921   // Dereferenced only on the network task runner, but bound to tasks destined
    922   // for the network task runner from the NSS task runner.
    923   base::WeakPtr<BoundNetLog> weak_net_log_;
    924 
    925   // Written on the network task runner by the |server_bound_cert_service_|,
    926   // prior to invoking OnHandshakeIOComplete.
    927   // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
    928   // on the NSS task runner.
    929   std::string domain_bound_private_key_;
    930   std::string domain_bound_cert_;
    931 
    932   DISALLOW_COPY_AND_ASSIGN(Core);
    933 };
    934 
    935 SSLClientSocketNSS::Core::Core(
    936     base::SequencedTaskRunner* network_task_runner,
    937     base::SequencedTaskRunner* nss_task_runner,
    938     ClientSocketHandle* transport,
    939     const HostPortPair& host_and_port,
    940     const SSLConfig& ssl_config,
    941     BoundNetLog* net_log,
    942     ServerBoundCertService* server_bound_cert_service)
    943     : detached_(false),
    944       transport_(transport),
    945       weak_net_log_factory_(net_log),
    946       server_bound_cert_service_(server_bound_cert_service),
    947       unhandled_buffer_size_(0),
    948       nss_waiting_read_(false),
    949       nss_waiting_write_(false),
    950       nss_is_closed_(false),
    951       host_and_port_(host_and_port),
    952       ssl_config_(ssl_config),
    953       nss_fd_(NULL),
    954       nss_bufs_(NULL),
    955       pending_read_result_(kNoPendingReadResult),
    956       pending_read_nss_error_(0),
    957       next_handshake_state_(STATE_NONE),
    958       channel_id_xtn_negotiated_(false),
    959       channel_id_needed_(false),
    960       client_auth_cert_needed_(false),
    961       false_started_(false),
    962       handshake_callback_called_(false),
    963       transport_recv_busy_(false),
    964       transport_recv_eof_(false),
    965       transport_send_busy_(false),
    966       user_read_buf_len_(0),
    967       user_write_buf_len_(0),
    968       network_task_runner_(network_task_runner),
    969       nss_task_runner_(nss_task_runner),
    970       weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
    971 }
    972 
    973 SSLClientSocketNSS::Core::~Core() {
    974   // TODO(wtc): Send SSL close_notify alert.
    975   if (nss_fd_ != NULL) {
    976     PR_Close(nss_fd_);
    977     nss_fd_ = NULL;
    978   }
    979 }
    980 
    981 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
    982                                     memio_Private* buffers) {
    983   DCHECK(OnNetworkTaskRunner());
    984   DCHECK(!nss_fd_);
    985   DCHECK(!nss_bufs_);
    986 
    987   nss_fd_ = socket;
    988   nss_bufs_ = buffers;
    989 
    990   SECStatus rv = SECSuccess;
    991 
    992   if (!ssl_config_.next_protos.empty()) {
    993     size_t wire_length = 0;
    994     for (std::vector<std::string>::const_iterator
    995          i = ssl_config_.next_protos.begin();
    996          i != ssl_config_.next_protos.end(); ++i) {
    997       if (i->size() > 255) {
    998         LOG(WARNING) << "Ignoring overlong NPN/ALPN protocol: " << *i;
    999         continue;
   1000       }
   1001       wire_length += i->size();
   1002       wire_length++;
   1003     }
   1004     scoped_ptr<uint8[]> wire_protos(new uint8[wire_length]);
   1005     uint8* dst = wire_protos.get();
   1006     for (std::vector<std::string>::const_iterator
   1007          i = ssl_config_.next_protos.begin();
   1008          i != ssl_config_.next_protos.end(); i++) {
   1009       if (i->size() > 255)
   1010         continue;
   1011       *dst++ = i->size();
   1012       memcpy(dst, i->data(), i->size());
   1013       dst += i->size();
   1014     }
   1015     DCHECK_EQ(dst, wire_protos.get() + wire_length);
   1016     rv = SSL_SetNextProtoNego(nss_fd_, wire_protos.get(), wire_length);
   1017     if (rv != SECSuccess)
   1018       LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoCallback", "");
   1019   }
   1020 
   1021   rv = SSL_AuthCertificateHook(
   1022       nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
   1023   if (rv != SECSuccess) {
   1024     LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
   1025     return false;
   1026   }
   1027 
   1028 #if defined(NSS_PLATFORM_CLIENT_AUTH)
   1029   rv = SSL_GetPlatformClientAuthDataHook(
   1030       nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler,
   1031       this);
   1032 #else
   1033   rv = SSL_GetClientAuthDataHook(
   1034       nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
   1035 #endif
   1036   if (rv != SECSuccess) {
   1037     LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
   1038     return false;
   1039   }
   1040 
   1041   if (IsChannelIDEnabled(ssl_config_, server_bound_cert_service_)) {
   1042     rv = SSL_SetClientChannelIDCallback(
   1043         nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
   1044     if (rv != SECSuccess) {
   1045       LogFailedNSSFunction(
   1046           *weak_net_log_, "SSL_SetClientChannelIDCallback", "");
   1047     }
   1048   }
   1049 
   1050   rv = SSL_SetCanFalseStartCallback(
   1051       nss_fd_, SSLClientSocketNSS::Core::CanFalseStartCallback, this);
   1052   if (rv != SECSuccess) {
   1053     LogFailedNSSFunction(*weak_net_log_, "SSL_SetCanFalseStartCallback", "");
   1054     return false;
   1055   }
   1056 
   1057   rv = SSL_HandshakeCallback(
   1058       nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
   1059   if (rv != SECSuccess) {
   1060     LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
   1061     return false;
   1062   }
   1063 
   1064   return true;
   1065 }
   1066 
   1067 void SSLClientSocketNSS::Core::SetPredictedCertificates(
   1068     const std::vector<std::string>& predicted_certs) {
   1069   if (predicted_certs.empty())
   1070     return;
   1071 
   1072   if (!OnNSSTaskRunner()) {
   1073     DCHECK(!detached_);
   1074     nss_task_runner_->PostTask(
   1075         FROM_HERE,
   1076         base::Bind(&Core::SetPredictedCertificates, this, predicted_certs));
   1077     return;
   1078   }
   1079 
   1080   DCHECK(nss_fd_);
   1081 
   1082   predicted_certs_ = predicted_certs;
   1083 
   1084   scoped_ptr<CERTCertificate*[]> certs(
   1085       new CERTCertificate*[predicted_certs.size()]);
   1086 
   1087   for (size_t i = 0; i < predicted_certs.size(); i++) {
   1088     SECItem derCert;
   1089     derCert.data = const_cast<uint8*>(reinterpret_cast<const uint8*>(
   1090         predicted_certs[i].data()));
   1091     derCert.len = predicted_certs[i].size();
   1092     certs[i] = CERT_NewTempCertificate(
   1093         CERT_GetDefaultCertDB(), &derCert, NULL /* no nickname given */,
   1094         PR_FALSE /* not permanent */, PR_TRUE /* copy DER data */);
   1095     if (!certs[i]) {
   1096       DestroyCertificates(&certs[0], i);
   1097       NOTREACHED();
   1098       return;
   1099     }
   1100   }
   1101 
   1102   SECStatus rv;
   1103 #ifdef SSL_ENABLE_CACHED_INFO
   1104   rv = SSL_SetPredictedPeerCertificates(nss_fd_, certs.get(),
   1105                                         predicted_certs.size());
   1106   DCHECK_EQ(SECSuccess, rv);
   1107 #else
   1108   rv = SECFailure;  // Not implemented.
   1109 #endif
   1110   DestroyCertificates(&certs[0], predicted_certs.size());
   1111 
   1112   if (rv != SECSuccess) {
   1113     LOG(WARNING) << "SetPredictedCertificates failed: "
   1114                  << host_and_port_.ToString();
   1115   }
   1116 }
   1117 
   1118 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
   1119   if (!OnNSSTaskRunner()) {
   1120     DCHECK(!detached_);
   1121     bool posted = nss_task_runner_->PostTask(
   1122         FROM_HERE,
   1123         base::Bind(IgnoreResult(&Core::Connect), this, callback));
   1124     return posted ? ERR_IO_PENDING : ERR_ABORTED;
   1125   }
   1126 
   1127   DCHECK(OnNSSTaskRunner());
   1128   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1129   DCHECK(user_read_callback_.is_null());
   1130   DCHECK(user_write_callback_.is_null());
   1131   DCHECK(user_connect_callback_.is_null());
   1132   DCHECK(!user_read_buf_.get());
   1133   DCHECK(!user_write_buf_.get());
   1134 
   1135   next_handshake_state_ = STATE_HANDSHAKE;
   1136   int rv = DoHandshakeLoop(OK);
   1137   if (rv == ERR_IO_PENDING) {
   1138     user_connect_callback_ = callback;
   1139   } else if (rv > OK) {
   1140     rv = OK;
   1141   }
   1142   if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
   1143     PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
   1144     return ERR_IO_PENDING;
   1145   }
   1146 
   1147   return rv;
   1148 }
   1149 
   1150 void SSLClientSocketNSS::Core::Detach() {
   1151   DCHECK(OnNetworkTaskRunner());
   1152 
   1153   detached_ = true;
   1154   transport_ = NULL;
   1155   weak_net_log_factory_.InvalidateWeakPtrs();
   1156 
   1157   network_handshake_state_.Reset();
   1158 
   1159   domain_bound_cert_request_handle_.Cancel();
   1160 }
   1161 
   1162 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
   1163                                    const CompletionCallback& callback) {
   1164   if (!OnNSSTaskRunner()) {
   1165     DCHECK(OnNetworkTaskRunner());
   1166     DCHECK(!detached_);
   1167     DCHECK(transport_);
   1168     DCHECK(!nss_waiting_read_);
   1169 
   1170     nss_waiting_read_ = true;
   1171     bool posted = nss_task_runner_->PostTask(
   1172         FROM_HERE,
   1173         base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
   1174                    buf_len, callback));
   1175     if (!posted) {
   1176       nss_is_closed_ = true;
   1177       nss_waiting_read_ = false;
   1178     }
   1179     return posted ? ERR_IO_PENDING : ERR_ABORTED;
   1180   }
   1181 
   1182   DCHECK(OnNSSTaskRunner());
   1183   DCHECK(false_started_ || handshake_callback_called_);
   1184   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1185   DCHECK(user_read_callback_.is_null());
   1186   DCHECK(user_connect_callback_.is_null());
   1187   DCHECK(!user_read_buf_.get());
   1188   DCHECK(nss_bufs_);
   1189 
   1190   user_read_buf_ = buf;
   1191   user_read_buf_len_ = buf_len;
   1192 
   1193   int rv = DoReadLoop(OK);
   1194   if (rv == ERR_IO_PENDING) {
   1195     if (OnNetworkTaskRunner())
   1196       nss_waiting_read_ = true;
   1197     user_read_callback_ = callback;
   1198   } else {
   1199     user_read_buf_ = NULL;
   1200     user_read_buf_len_ = 0;
   1201 
   1202     if (!OnNetworkTaskRunner()) {
   1203       PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
   1204       PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
   1205       return ERR_IO_PENDING;
   1206     } else {
   1207       DCHECK(!nss_waiting_read_);
   1208       if (rv <= 0)
   1209         nss_is_closed_ = true;
   1210     }
   1211   }
   1212 
   1213   return rv;
   1214 }
   1215 
   1216 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
   1217                                     const CompletionCallback& callback) {
   1218   if (!OnNSSTaskRunner()) {
   1219     DCHECK(OnNetworkTaskRunner());
   1220     DCHECK(!detached_);
   1221     DCHECK(transport_);
   1222     DCHECK(!nss_waiting_write_);
   1223 
   1224     nss_waiting_write_ = true;
   1225     bool posted = nss_task_runner_->PostTask(
   1226         FROM_HERE,
   1227         base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
   1228                    buf_len, callback));
   1229     if (!posted) {
   1230       nss_is_closed_ = true;
   1231       nss_waiting_write_ = false;
   1232     }
   1233     return posted ? ERR_IO_PENDING : ERR_ABORTED;
   1234   }
   1235 
   1236   DCHECK(OnNSSTaskRunner());
   1237   DCHECK(false_started_ || handshake_callback_called_);
   1238   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1239   DCHECK(user_write_callback_.is_null());
   1240   DCHECK(user_connect_callback_.is_null());
   1241   DCHECK(!user_write_buf_.get());
   1242   DCHECK(nss_bufs_);
   1243 
   1244   user_write_buf_ = buf;
   1245   user_write_buf_len_ = buf_len;
   1246 
   1247   int rv = DoWriteLoop(OK);
   1248   if (rv == ERR_IO_PENDING) {
   1249     if (OnNetworkTaskRunner())
   1250       nss_waiting_write_ = true;
   1251     user_write_callback_ = callback;
   1252   } else {
   1253     user_write_buf_ = NULL;
   1254     user_write_buf_len_ = 0;
   1255 
   1256     if (!OnNetworkTaskRunner()) {
   1257       PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
   1258       PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
   1259       return ERR_IO_PENDING;
   1260     } else {
   1261       DCHECK(!nss_waiting_write_);
   1262       if (rv < 0)
   1263         nss_is_closed_ = true;
   1264     }
   1265   }
   1266 
   1267   return rv;
   1268 }
   1269 
   1270 bool SSLClientSocketNSS::Core::IsConnected() {
   1271   DCHECK(OnNetworkTaskRunner());
   1272   return !nss_is_closed_;
   1273 }
   1274 
   1275 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() {
   1276   DCHECK(OnNetworkTaskRunner());
   1277   return nss_waiting_read_ || nss_waiting_write_;
   1278 }
   1279 
   1280 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() {
   1281   DCHECK(OnNetworkTaskRunner());
   1282   return unhandled_buffer_size_ != 0;
   1283 }
   1284 
   1285 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
   1286   // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
   1287   // nss_fd_. However, it happens on the network task runner in order to match
   1288   // the buggy behavior of ExportKeyingMaterial.
   1289   //
   1290   // Once http://crbug.com/330360 is fixed, this should be moved to an
   1291   // implementation that exclusively does this work on the NSS TaskRunner. This
   1292   // is "safe" because it is only called during the certificate verification
   1293   // state machine of the main socket, which is safe because no underlying
   1294   // transport IO will be occuring in that state, and NSS will not be blocking
   1295   // on any PKCS#11 related locks that might block the Network TaskRunner.
   1296   DCHECK(OnNetworkTaskRunner());
   1297 
   1298   // Only cache the session if the connection was not False Started, because
   1299   // sessions should only be cached *after* the peer's Finished message is
   1300   // processed.
   1301   // In the case of False Start, the session will be cached once the
   1302   // HandshakeCallback is called, which signals the receipt and processing of
   1303   // the Finished message, and which will happen during a call to
   1304   // PR_Read/PR_Write.
   1305   if (!false_started_)
   1306     SSL_CacheSession(nss_fd_);
   1307 }
   1308 
   1309 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
   1310   return nss_task_runner_->RunsTasksOnCurrentThread();
   1311 }
   1312 
   1313 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
   1314   return network_task_runner_->RunsTasksOnCurrentThread();
   1315 }
   1316 
   1317 // static
   1318 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
   1319     void* arg,
   1320     PRFileDesc* socket,
   1321     PRBool checksig,
   1322     PRBool is_server) {
   1323   Core* core = reinterpret_cast<Core*>(arg);
   1324   if (core->handshake_callback_called_) {
   1325     // Disallow the server certificate to change in a renegotiation.
   1326     CERTCertificate* old_cert = core->nss_handshake_state_.server_cert_chain[0];
   1327     ScopedCERTCertificate new_cert(SSL_PeerCertificate(socket));
   1328     if (new_cert->derCert.len != old_cert->derCert.len ||
   1329         memcmp(new_cert->derCert.data, old_cert->derCert.data,
   1330                new_cert->derCert.len) != 0) {
   1331       // NSS doesn't have an error code that indicates the server certificate
   1332       // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
   1333       // for this purpose.
   1334       PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE);
   1335       return SECFailure;
   1336     }
   1337   }
   1338 
   1339   // Tell NSS to not verify the certificate.
   1340   return SECSuccess;
   1341 }
   1342 
   1343 #if defined(NSS_PLATFORM_CLIENT_AUTH)
   1344 // static
   1345 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler(
   1346     void* arg,
   1347     PRFileDesc* socket,
   1348     CERTDistNames* ca_names,
   1349     CERTCertList** result_certs,
   1350     void** result_private_key,
   1351     CERTCertificate** result_nss_certificate,
   1352     SECKEYPrivateKey** result_nss_private_key) {
   1353   Core* core = reinterpret_cast<Core*>(arg);
   1354   DCHECK(core->OnNSSTaskRunner());
   1355 
   1356   core->PostOrRunCallback(
   1357       FROM_HERE,
   1358       base::Bind(&AddLogEvent, core->weak_net_log_,
   1359                  NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
   1360 
   1361   core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
   1362 #if defined(OS_WIN)
   1363   if (core->ssl_config_.send_client_cert) {
   1364     if (core->ssl_config_.client_cert) {
   1365       PCCERT_CONTEXT cert_context =
   1366           core->ssl_config_.client_cert->os_cert_handle();
   1367 
   1368       HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
   1369       DWORD key_spec = 0;
   1370       BOOL must_free = FALSE;
   1371       DWORD flags = 0;
   1372       if (base::win::GetVersion() >= base::win::VERSION_VISTA)
   1373         flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
   1374 
   1375       BOOL acquired_key = CryptAcquireCertificatePrivateKey(
   1376           cert_context, flags, NULL, &crypt_prov, &key_spec, &must_free);
   1377 
   1378       if (acquired_key) {
   1379         // Should never get a cached handle back - ownership must always be
   1380         // transferred.
   1381         CHECK_EQ(must_free, TRUE);
   1382 
   1383         SECItem der_cert;
   1384         der_cert.type = siDERCertBuffer;
   1385         der_cert.data = cert_context->pbCertEncoded;
   1386         der_cert.len  = cert_context->cbCertEncoded;
   1387 
   1388         // TODO(rsleevi): Error checking for NSS allocation errors.
   1389         CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB();
   1390         CERTCertificate* user_cert = CERT_NewTempCertificate(
   1391             db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
   1392         if (!user_cert) {
   1393           // Importing the certificate can fail for reasons including a serial
   1394           // number collision. See crbug.com/97355.
   1395           core->AddCertProvidedEvent(0);
   1396           return SECFailure;
   1397         }
   1398         CERTCertList* cert_chain = CERT_NewCertList();
   1399         CERT_AddCertToListTail(cert_chain, user_cert);
   1400 
   1401         // Add the intermediates.
   1402         X509Certificate::OSCertHandles intermediates =
   1403             core->ssl_config_.client_cert->GetIntermediateCertificates();
   1404         for (X509Certificate::OSCertHandles::const_iterator it =
   1405             intermediates.begin(); it != intermediates.end(); ++it) {
   1406           der_cert.data = (*it)->pbCertEncoded;
   1407           der_cert.len = (*it)->cbCertEncoded;
   1408 
   1409           CERTCertificate* intermediate = CERT_NewTempCertificate(
   1410               db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
   1411           if (!intermediate) {
   1412             CERT_DestroyCertList(cert_chain);
   1413             core->AddCertProvidedEvent(0);
   1414             return SECFailure;
   1415           }
   1416           CERT_AddCertToListTail(cert_chain, intermediate);
   1417         }
   1418         PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>(
   1419             PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT)));
   1420         key_context->cbSize = sizeof(*key_context);
   1421         // NSS will free this context when no longer in use.
   1422         key_context->hCryptProv = crypt_prov;
   1423         key_context->dwKeySpec = key_spec;
   1424         *result_private_key = key_context;
   1425         *result_certs = cert_chain;
   1426 
   1427         int cert_count = 1 + intermediates.size();
   1428         core->AddCertProvidedEvent(cert_count);
   1429         return SECSuccess;
   1430       }
   1431       LOG(WARNING) << "Client cert found without private key";
   1432     }
   1433 
   1434     // Send no client certificate.
   1435     core->AddCertProvidedEvent(0);
   1436     return SECFailure;
   1437   }
   1438 
   1439   core->nss_handshake_state_.cert_authorities.clear();
   1440 
   1441   std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
   1442   for (int i = 0; i < ca_names->nnames; ++i) {
   1443     issuer_list[i].cbData = ca_names->names[i].len;
   1444     issuer_list[i].pbData = ca_names->names[i].data;
   1445     core->nss_handshake_state_.cert_authorities.push_back(std::string(
   1446         reinterpret_cast<const char*>(ca_names->names[i].data),
   1447         static_cast<size_t>(ca_names->names[i].len)));
   1448   }
   1449 
   1450   // Update the network task runner's view of the handshake state now that
   1451   // server certificate request has been recorded.
   1452   core->PostOrRunCallback(
   1453       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
   1454                             core->nss_handshake_state_));
   1455 
   1456   // Tell NSS to suspend the client authentication.  We will then abort the
   1457   // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
   1458   return SECWouldBlock;
   1459 #elif defined(OS_MACOSX)
   1460   if (core->ssl_config_.send_client_cert) {
   1461     if (core->ssl_config_.client_cert.get()) {
   1462       OSStatus os_error = noErr;
   1463       SecIdentityRef identity = NULL;
   1464       SecKeyRef private_key = NULL;
   1465       X509Certificate::OSCertHandles chain;
   1466       {
   1467         base::AutoLock lock(crypto::GetMacSecurityServicesLock());
   1468         os_error = SecIdentityCreateWithCertificate(
   1469             NULL, core->ssl_config_.client_cert->os_cert_handle(), &identity);
   1470       }
   1471       if (os_error == noErr) {
   1472         os_error = SecIdentityCopyPrivateKey(identity, &private_key);
   1473         CFRelease(identity);
   1474       }
   1475 
   1476       if (os_error == noErr) {
   1477         // TODO(rsleevi): Error checking for NSS allocation errors.
   1478         *result_certs = CERT_NewCertList();
   1479         *result_private_key = private_key;
   1480 
   1481         chain.push_back(core->ssl_config_.client_cert->os_cert_handle());
   1482         const X509Certificate::OSCertHandles& intermediates =
   1483             core->ssl_config_.client_cert->GetIntermediateCertificates();
   1484         if (!intermediates.empty())
   1485           chain.insert(chain.end(), intermediates.begin(), intermediates.end());
   1486 
   1487         for (size_t i = 0, chain_count = chain.size(); i < chain_count; ++i) {
   1488           CSSM_DATA cert_data;
   1489           SecCertificateRef cert_ref = chain[i];
   1490           os_error = SecCertificateGetData(cert_ref, &cert_data);
   1491           if (os_error != noErr)
   1492             break;
   1493 
   1494           SECItem der_cert;
   1495           der_cert.type = siDERCertBuffer;
   1496           der_cert.data = cert_data.Data;
   1497           der_cert.len = cert_data.Length;
   1498           CERTCertificate* nss_cert = CERT_NewTempCertificate(
   1499               CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
   1500           if (!nss_cert) {
   1501             // In the event of an NSS error, make up an OS error and reuse
   1502             // the error handling below.
   1503             os_error = errSecCreateChainFailed;
   1504             break;
   1505           }
   1506           CERT_AddCertToListTail(*result_certs, nss_cert);
   1507         }
   1508       }
   1509 
   1510       if (os_error == noErr) {
   1511         core->AddCertProvidedEvent(chain.size());
   1512         return SECSuccess;
   1513       }
   1514 
   1515       OSSTATUS_LOG(WARNING, os_error)
   1516           << "Client cert found, but could not be used";
   1517       if (*result_certs) {
   1518         CERT_DestroyCertList(*result_certs);
   1519         *result_certs = NULL;
   1520       }
   1521       if (*result_private_key)
   1522         *result_private_key = NULL;
   1523       if (private_key)
   1524         CFRelease(private_key);
   1525     }
   1526 
   1527     // Send no client certificate.
   1528     core->AddCertProvidedEvent(0);
   1529     return SECFailure;
   1530   }
   1531 
   1532   core->nss_handshake_state_.cert_authorities.clear();
   1533 
   1534   // Retrieve the cert issuers accepted by the server.
   1535   std::vector<CertPrincipal> valid_issuers;
   1536   int n = ca_names->nnames;
   1537   for (int i = 0; i < n; i++) {
   1538     core->nss_handshake_state_.cert_authorities.push_back(std::string(
   1539         reinterpret_cast<const char*>(ca_names->names[i].data),
   1540         static_cast<size_t>(ca_names->names[i].len)));
   1541   }
   1542 
   1543   // Update the network task runner's view of the handshake state now that
   1544   // server certificate request has been recorded.
   1545   core->PostOrRunCallback(
   1546       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
   1547                             core->nss_handshake_state_));
   1548 
   1549   // Tell NSS to suspend the client authentication.  We will then abort the
   1550   // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
   1551   return SECWouldBlock;
   1552 #else
   1553   return SECFailure;
   1554 #endif
   1555 }
   1556 
   1557 #elif defined(OS_IOS)
   1558 
   1559 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
   1560     void* arg,
   1561     PRFileDesc* socket,
   1562     CERTDistNames* ca_names,
   1563     CERTCertificate** result_certificate,
   1564     SECKEYPrivateKey** result_private_key) {
   1565   Core* core = reinterpret_cast<Core*>(arg);
   1566   DCHECK(core->OnNSSTaskRunner());
   1567 
   1568   core->PostOrRunCallback(
   1569       FROM_HERE,
   1570       base::Bind(&AddLogEvent, core->weak_net_log_,
   1571                  NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
   1572 
   1573   // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
   1574   LOG(WARNING) << "Client auth is not supported";
   1575 
   1576   // Never send a certificate.
   1577   core->AddCertProvidedEvent(0);
   1578   return SECFailure;
   1579 }
   1580 
   1581 #else  // NSS_PLATFORM_CLIENT_AUTH
   1582 
   1583 // static
   1584 // Based on Mozilla's NSS_GetClientAuthData.
   1585 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
   1586     void* arg,
   1587     PRFileDesc* socket,
   1588     CERTDistNames* ca_names,
   1589     CERTCertificate** result_certificate,
   1590     SECKEYPrivateKey** result_private_key) {
   1591   Core* core = reinterpret_cast<Core*>(arg);
   1592   DCHECK(core->OnNSSTaskRunner());
   1593 
   1594   core->PostOrRunCallback(
   1595       FROM_HERE,
   1596       base::Bind(&AddLogEvent, core->weak_net_log_,
   1597                  NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
   1598 
   1599   // Regular client certificate requested.
   1600   core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
   1601   void* wincx  = SSL_RevealPinArg(socket);
   1602 
   1603   if (core->ssl_config_.send_client_cert) {
   1604     // Second pass: a client certificate should have been selected.
   1605     if (core->ssl_config_.client_cert.get()) {
   1606       CERTCertificate* cert =
   1607           CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
   1608       SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
   1609       if (privkey) {
   1610         // TODO(jsorianopastor): We should wait for server certificate
   1611         // verification before sending our credentials.  See
   1612         // http://crbug.com/13934.
   1613         *result_certificate = cert;
   1614         *result_private_key = privkey;
   1615         // A cert_count of -1 means the number of certificates is unknown.
   1616         // NSS will construct the certificate chain.
   1617         core->AddCertProvidedEvent(-1);
   1618 
   1619         return SECSuccess;
   1620       }
   1621       LOG(WARNING) << "Client cert found without private key";
   1622     }
   1623     // Send no client certificate.
   1624     core->AddCertProvidedEvent(0);
   1625     return SECFailure;
   1626   }
   1627 
   1628   // First pass: client certificate is needed.
   1629   core->nss_handshake_state_.cert_authorities.clear();
   1630 
   1631   // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
   1632   // the server and save them in |cert_authorities|.
   1633   for (int i = 0; i < ca_names->nnames; i++) {
   1634     core->nss_handshake_state_.cert_authorities.push_back(std::string(
   1635         reinterpret_cast<const char*>(ca_names->names[i].data),
   1636         static_cast<size_t>(ca_names->names[i].len)));
   1637   }
   1638 
   1639   // Update the network task runner's view of the handshake state now that
   1640   // server certificate request has been recorded.
   1641   core->PostOrRunCallback(
   1642       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
   1643                             core->nss_handshake_state_));
   1644 
   1645   // Tell NSS to suspend the client authentication.  We will then abort the
   1646   // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
   1647   return SECWouldBlock;
   1648 }
   1649 #endif  // NSS_PLATFORM_CLIENT_AUTH
   1650 
   1651 // static
   1652 SECStatus SSLClientSocketNSS::Core::CanFalseStartCallback(
   1653     PRFileDesc* socket,
   1654     void* arg,
   1655     PRBool* can_false_start) {
   1656   // If the server doesn't support NPN or ALPN, then we don't do False
   1657   // Start with it.
   1658   PRBool negotiated_extension;
   1659   SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
   1660                                                   ssl_app_layer_protocol_xtn,
   1661                                                   &negotiated_extension);
   1662   if (rv != SECSuccess || !negotiated_extension) {
   1663     rv = SSL_HandshakeNegotiatedExtension(socket,
   1664                                           ssl_next_proto_nego_xtn,
   1665                                           &negotiated_extension);
   1666   }
   1667   if (rv != SECSuccess || !negotiated_extension) {
   1668     *can_false_start = PR_FALSE;
   1669     return SECSuccess;
   1670   }
   1671 
   1672   return SSL_RecommendedCanFalseStart(socket, can_false_start);
   1673 }
   1674 
   1675 // static
   1676 void SSLClientSocketNSS::Core::HandshakeCallback(
   1677     PRFileDesc* socket,
   1678     void* arg) {
   1679   Core* core = reinterpret_cast<Core*>(arg);
   1680   DCHECK(core->OnNSSTaskRunner());
   1681 
   1682   core->handshake_callback_called_ = true;
   1683   if (core->false_started_) {
   1684     core->false_started_ = false;
   1685     // If the connection was False Started, then at the time of this callback,
   1686     // the peer's certificate will have been verified or the caller will have
   1687     // accepted the error.
   1688     // This is guaranteed when using False Start because this callback will
   1689     // not be invoked until processing the peer's Finished message, which
   1690     // will only happen in a PR_Read/PR_Write call, which can only happen
   1691     // after the peer's certificate is verified.
   1692     SSL_CacheSessionUnlocked(socket);
   1693 
   1694     // Additionally, when False Starting, DoHandshake() will have already
   1695     // called HandshakeSucceeded(), so return now.
   1696     return;
   1697   }
   1698   core->HandshakeSucceeded();
   1699 }
   1700 
   1701 void SSLClientSocketNSS::Core::HandshakeSucceeded() {
   1702   DCHECK(OnNSSTaskRunner());
   1703 
   1704   PRBool last_handshake_resumed;
   1705   SECStatus rv = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed);
   1706   if (rv == SECSuccess && last_handshake_resumed) {
   1707     nss_handshake_state_.resumed_handshake = true;
   1708   } else {
   1709     nss_handshake_state_.resumed_handshake = false;
   1710   }
   1711 
   1712   RecordChannelIDSupportOnNSSTaskRunner();
   1713   UpdateServerCert();
   1714   UpdateSignedCertTimestamps();
   1715   UpdateStapledOCSPResponse();
   1716   UpdateConnectionStatus();
   1717   UpdateNextProto();
   1718 
   1719   // Update the network task runners view of the handshake state whenever
   1720   // a handshake has completed.
   1721   PostOrRunCallback(
   1722       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
   1723                             nss_handshake_state_));
   1724 }
   1725 
   1726 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error,
   1727                                              bool handshake_error) {
   1728   DCHECK(OnNSSTaskRunner());
   1729 
   1730   int net_error = handshake_error ? MapNSSClientHandshakeError(nss_error) :
   1731                                     MapNSSClientError(nss_error);
   1732 
   1733 #if defined(OS_WIN)
   1734   // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
   1735   // os_cert_handle() as an optimization. However, if the certificate
   1736   // private key is stored on a smart card, and the smart card is removed,
   1737   // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
   1738   // preventing client certificate authentication. Because the
   1739   // X509Certificate may outlive the individual SSLClientSocketNSS, due to
   1740   // caching in X509Certificate, this failure ends up preventing client
   1741   // certificate authentication with the same certificate for all future
   1742   // attempts, even after the smart card has been re-inserted. By setting
   1743   // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
   1744   // typically be freed. This allows a new HCRYPTPROV to be obtained from
   1745   // the certificate on the next attempt, which should succeed if the smart
   1746   // card has been re-inserted, or will typically prompt the user to
   1747   // re-insert the smart card if not.
   1748   if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY ||
   1749        net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) &&
   1750       ssl_config_.send_client_cert && ssl_config_.client_cert) {
   1751     CertSetCertificateContextProperty(
   1752         ssl_config_.client_cert->os_cert_handle(),
   1753         CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL);
   1754   }
   1755 #endif
   1756 
   1757   return net_error;
   1758 }
   1759 
   1760 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
   1761   DCHECK(OnNSSTaskRunner());
   1762 
   1763   int rv = last_io_result;
   1764   do {
   1765     // Default to STATE_NONE for next state.
   1766     State state = next_handshake_state_;
   1767     GotoState(STATE_NONE);
   1768 
   1769     switch (state) {
   1770       case STATE_HANDSHAKE:
   1771         rv = DoHandshake();
   1772         break;
   1773       case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
   1774         rv = DoGetDBCertComplete(rv);
   1775         break;
   1776       case STATE_NONE:
   1777       default:
   1778         rv = ERR_UNEXPECTED;
   1779         LOG(DFATAL) << "unexpected state " << state;
   1780         break;
   1781     }
   1782 
   1783     // Do the actual network I/O
   1784     bool network_moved = DoTransportIO();
   1785     if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
   1786       // In general we exit the loop if rv is ERR_IO_PENDING.  In this
   1787       // special case we keep looping even if rv is ERR_IO_PENDING because
   1788       // the transport IO may allow DoHandshake to make progress.
   1789       DCHECK(rv == OK || rv == ERR_IO_PENDING);
   1790       rv = OK;  // This causes us to stay in the loop.
   1791     }
   1792   } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
   1793   return rv;
   1794 }
   1795 
   1796 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
   1797   DCHECK(OnNSSTaskRunner());
   1798   DCHECK(false_started_ || handshake_callback_called_);
   1799   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1800 
   1801   if (result < 0)
   1802     return result;
   1803 
   1804   if (!nss_bufs_) {
   1805     LOG(DFATAL) << "!nss_bufs_";
   1806     int rv = ERR_UNEXPECTED;
   1807     PostOrRunCallback(
   1808         FROM_HERE,
   1809         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1810                    NetLog::TYPE_SSL_READ_ERROR,
   1811                    CreateNetLogSSLErrorCallback(rv, 0)));
   1812     return rv;
   1813   }
   1814 
   1815   bool network_moved;
   1816   int rv;
   1817   do {
   1818     rv = DoPayloadRead();
   1819     network_moved = DoTransportIO();
   1820   } while (rv == ERR_IO_PENDING && network_moved);
   1821 
   1822   return rv;
   1823 }
   1824 
   1825 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
   1826   DCHECK(OnNSSTaskRunner());
   1827   DCHECK(false_started_ || handshake_callback_called_);
   1828   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   1829 
   1830   if (result < 0)
   1831     return result;
   1832 
   1833   if (!nss_bufs_) {
   1834     LOG(DFATAL) << "!nss_bufs_";
   1835     int rv = ERR_UNEXPECTED;
   1836     PostOrRunCallback(
   1837         FROM_HERE,
   1838         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1839                    NetLog::TYPE_SSL_READ_ERROR,
   1840                    CreateNetLogSSLErrorCallback(rv, 0)));
   1841     return rv;
   1842   }
   1843 
   1844   bool network_moved;
   1845   int rv;
   1846   do {
   1847     rv = DoPayloadWrite();
   1848     network_moved = DoTransportIO();
   1849   } while (rv == ERR_IO_PENDING && network_moved);
   1850 
   1851   LeaveFunction(rv);
   1852   return rv;
   1853 }
   1854 
   1855 int SSLClientSocketNSS::Core::DoHandshake() {
   1856   DCHECK(OnNSSTaskRunner());
   1857 
   1858   int net_error = net::OK;
   1859   SECStatus rv = SSL_ForceHandshake(nss_fd_);
   1860 
   1861   // Note: this function may be called multiple times during the handshake, so
   1862   // even though channel id and client auth are separate else cases, they can
   1863   // both be used during a single SSL handshake.
   1864   if (channel_id_needed_) {
   1865     GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
   1866     net_error = ERR_IO_PENDING;
   1867   } else if (client_auth_cert_needed_) {
   1868     net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
   1869     PostOrRunCallback(
   1870         FROM_HERE,
   1871         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1872                    NetLog::TYPE_SSL_HANDSHAKE_ERROR,
   1873                    CreateNetLogSSLErrorCallback(net_error, 0)));
   1874 
   1875     // If the handshake already succeeded (because the server requests but
   1876     // doesn't require a client cert), we need to invalidate the SSL session
   1877     // so that we won't try to resume the non-client-authenticated session in
   1878     // the next handshake.  This will cause the server to ask for a client
   1879     // cert again.
   1880     if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess)
   1881       LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError();
   1882   } else if (rv == SECSuccess) {
   1883     if (!handshake_callback_called_) {
   1884       false_started_ = true;
   1885       HandshakeSucceeded();
   1886     }
   1887   } else {
   1888     PRErrorCode prerr = PR_GetError();
   1889     net_error = HandleNSSError(prerr, true);
   1890 
   1891     // Some network devices that inspect application-layer packets seem to
   1892     // inject TCP reset packets to break the connections when they see
   1893     // TLS 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
   1894     //
   1895     // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
   1896     // 1.2. We don't lose much in this fallback because the explicit IV for CBC
   1897     // mode in TLS 1.1 is approximated by record splitting in TLS 1.0. The
   1898     // fallback will be more painful for TLS 1.2 when we have GCM support.
   1899     //
   1900     // ERR_CONNECTION_RESET is a common network error, so we don't want it
   1901     // to trigger a version fallback in general, especially the TLS 1.0 ->
   1902     // SSL 3.0 fallback, which would drop TLS extensions.
   1903     if (prerr == PR_CONNECT_RESET_ERROR &&
   1904         ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1) {
   1905       net_error = ERR_SSL_PROTOCOL_ERROR;
   1906     }
   1907 
   1908     // If not done, stay in this state
   1909     if (net_error == ERR_IO_PENDING) {
   1910       GotoState(STATE_HANDSHAKE);
   1911     } else {
   1912       PostOrRunCallback(
   1913           FROM_HERE,
   1914           base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1915                      NetLog::TYPE_SSL_HANDSHAKE_ERROR,
   1916                      CreateNetLogSSLErrorCallback(net_error, prerr)));
   1917     }
   1918   }
   1919 
   1920   return net_error;
   1921 }
   1922 
   1923 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
   1924   SECStatus rv;
   1925   PostOrRunCallback(
   1926       FROM_HERE,
   1927       base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
   1928                  NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
   1929 
   1930   channel_id_needed_ = false;
   1931 
   1932   if (result != OK)
   1933     return result;
   1934 
   1935   SECKEYPublicKey* public_key;
   1936   SECKEYPrivateKey* private_key;
   1937   int error = ImportChannelIDKeys(&public_key, &private_key);
   1938   if (error != OK)
   1939     return error;
   1940 
   1941   rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
   1942   if (rv != SECSuccess)
   1943     return MapNSSError(PORT_GetError());
   1944 
   1945   SetChannelIDProvided();
   1946   GotoState(STATE_HANDSHAKE);
   1947   return OK;
   1948 }
   1949 
   1950 int SSLClientSocketNSS::Core::DoPayloadRead() {
   1951   DCHECK(OnNSSTaskRunner());
   1952   DCHECK(user_read_buf_.get());
   1953   DCHECK_GT(user_read_buf_len_, 0);
   1954 
   1955   int rv;
   1956   // If a previous greedy read resulted in an error that was not consumed (eg:
   1957   // due to the caller having read some data successfully), then return that
   1958   // pending error now.
   1959   if (pending_read_result_ != kNoPendingReadResult) {
   1960     rv = pending_read_result_;
   1961     PRErrorCode prerr = pending_read_nss_error_;
   1962     pending_read_result_ = kNoPendingReadResult;
   1963     pending_read_nss_error_ = 0;
   1964 
   1965     if (rv == 0) {
   1966       PostOrRunCallback(
   1967           FROM_HERE,
   1968           base::Bind(&LogByteTransferEvent, weak_net_log_,
   1969                      NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
   1970                      scoped_refptr<IOBuffer>(user_read_buf_)));
   1971     } else {
   1972       PostOrRunCallback(
   1973           FROM_HERE,
   1974           base::Bind(&AddLogEventWithCallback, weak_net_log_,
   1975                      NetLog::TYPE_SSL_READ_ERROR,
   1976                      CreateNetLogSSLErrorCallback(rv, prerr)));
   1977     }
   1978     return rv;
   1979   }
   1980 
   1981   // Perform a greedy read, attempting to read as much as the caller has
   1982   // requested. In the current NSS implementation, PR_Read will return
   1983   // exactly one SSL application data record's worth of data per invocation.
   1984   // The record size is dictated by the server, and may be noticeably smaller
   1985   // than the caller's buffer. This may be as little as a single byte, if the
   1986   // server is performing 1/n-1 record splitting.
   1987   //
   1988   // However, this greedy read may result in renegotiations/re-handshakes
   1989   // happening or may lead to some data being read, followed by an EOF (such as
   1990   // a TLS close-notify). If at least some data was read, then that result
   1991   // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
   1992   // data was read, it's safe to return the error or EOF immediately.
   1993   int total_bytes_read = 0;
   1994   do {
   1995     rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
   1996                  user_read_buf_len_ - total_bytes_read);
   1997     if (rv > 0)
   1998       total_bytes_read += rv;
   1999   } while (total_bytes_read < user_read_buf_len_ && rv > 0);
   2000   int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2001   PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
   2002                                           amount_in_read_buffer));
   2003 
   2004   if (total_bytes_read == user_read_buf_len_) {
   2005     // The caller's entire request was satisfied without error. No further
   2006     // processing needed.
   2007     rv = total_bytes_read;
   2008   } else {
   2009     // Otherwise, an error occurred (rv <= 0). The error needs to be handled
   2010     // immediately, while the NSPR/NSS errors are still available in
   2011     // thread-local storage. However, the handled/remapped error code should
   2012     // only be returned if no application data was already read; if it was, the
   2013     // error code should be deferred until the next call of DoPayloadRead.
   2014     //
   2015     // If no data was read, |*next_result| will point to the return value of
   2016     // this function. If at least some data was read, |*next_result| will point
   2017     // to |pending_read_error_|, to be returned in a future call to
   2018     // DoPayloadRead() (e.g.: after the current data is handled).
   2019     int* next_result = &rv;
   2020     if (total_bytes_read > 0) {
   2021       pending_read_result_ = rv;
   2022       rv = total_bytes_read;
   2023       next_result = &pending_read_result_;
   2024     }
   2025 
   2026     if (client_auth_cert_needed_) {
   2027       *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
   2028       pending_read_nss_error_ = 0;
   2029     } else if (*next_result < 0) {
   2030       // If *next_result == 0, then that indicates EOF, and no special error
   2031       // handling is needed.
   2032       pending_read_nss_error_ = PR_GetError();
   2033       *next_result = HandleNSSError(pending_read_nss_error_, false);
   2034       if (rv > 0 && *next_result == ERR_IO_PENDING) {
   2035         // If at least some data was read from PR_Read(), do not treat
   2036         // insufficient data as an error to return in the next call to
   2037         // DoPayloadRead() - instead, let the call fall through to check
   2038         // PR_Read() again. This is because DoTransportIO() may complete
   2039         // in between the next call to DoPayloadRead(), and thus it is
   2040         // important to check PR_Read() on subsequent invocations to see
   2041         // if a complete record may now be read.
   2042         pending_read_nss_error_ = 0;
   2043         pending_read_result_ = kNoPendingReadResult;
   2044       }
   2045     }
   2046   }
   2047 
   2048   DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
   2049 
   2050   if (rv >= 0) {
   2051     PostOrRunCallback(
   2052         FROM_HERE,
   2053         base::Bind(&LogByteTransferEvent, weak_net_log_,
   2054                    NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
   2055                    scoped_refptr<IOBuffer>(user_read_buf_)));
   2056   } else if (rv != ERR_IO_PENDING) {
   2057     PostOrRunCallback(
   2058         FROM_HERE,
   2059         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   2060                    NetLog::TYPE_SSL_READ_ERROR,
   2061                    CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
   2062     pending_read_nss_error_ = 0;
   2063   }
   2064   return rv;
   2065 }
   2066 
   2067 int SSLClientSocketNSS::Core::DoPayloadWrite() {
   2068   DCHECK(OnNSSTaskRunner());
   2069 
   2070   DCHECK(user_write_buf_.get());
   2071 
   2072   int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2073   int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
   2074   int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2075   // PR_Write could potentially consume the unhandled data in the memio read
   2076   // buffer if a renegotiation is in progress. If the buffer is consumed,
   2077   // notify the latest buffer size to NetworkRunner.
   2078   if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
   2079     PostOrRunCallback(
   2080         FROM_HERE,
   2081         base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
   2082   }
   2083   if (rv >= 0) {
   2084     PostOrRunCallback(
   2085         FROM_HERE,
   2086         base::Bind(&LogByteTransferEvent, weak_net_log_,
   2087                    NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
   2088                    scoped_refptr<IOBuffer>(user_write_buf_)));
   2089     return rv;
   2090   }
   2091   PRErrorCode prerr = PR_GetError();
   2092   if (prerr == PR_WOULD_BLOCK_ERROR)
   2093     return ERR_IO_PENDING;
   2094 
   2095   rv = HandleNSSError(prerr, false);
   2096   PostOrRunCallback(
   2097       FROM_HERE,
   2098       base::Bind(&AddLogEventWithCallback, weak_net_log_,
   2099                  NetLog::TYPE_SSL_WRITE_ERROR,
   2100                  CreateNetLogSSLErrorCallback(rv, prerr)));
   2101   return rv;
   2102 }
   2103 
   2104 // Do as much network I/O as possible between the buffer and the
   2105 // transport socket. Return true if some I/O performed, false
   2106 // otherwise (error or ERR_IO_PENDING).
   2107 bool SSLClientSocketNSS::Core::DoTransportIO() {
   2108   DCHECK(OnNSSTaskRunner());
   2109 
   2110   bool network_moved = false;
   2111   if (nss_bufs_ != NULL) {
   2112     int rv;
   2113     // Read and write as much data as we can. The loop is neccessary
   2114     // because Write() may return synchronously.
   2115     do {
   2116       rv = BufferSend();
   2117       if (rv != ERR_IO_PENDING && rv != 0)
   2118         network_moved = true;
   2119     } while (rv > 0);
   2120     if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
   2121       network_moved = true;
   2122   }
   2123   return network_moved;
   2124 }
   2125 
   2126 int SSLClientSocketNSS::Core::BufferRecv() {
   2127   DCHECK(OnNSSTaskRunner());
   2128 
   2129   if (transport_recv_busy_)
   2130     return ERR_IO_PENDING;
   2131 
   2132   // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
   2133   // determine how much data NSS wants to read. If NSS was not blocked,
   2134   // this will return 0.
   2135   int requested = memio_GetReadRequest(nss_bufs_);
   2136   if (requested == 0) {
   2137     // This is not a perfect match of error codes, as no operation is
   2138     // actually pending. However, returning 0 would be interpreted as a
   2139     // possible sign of EOF, which is also an inappropriate match.
   2140     return ERR_IO_PENDING;
   2141   }
   2142 
   2143   char* buf;
   2144   int nb = memio_GetReadParams(nss_bufs_, &buf);
   2145   int rv;
   2146   if (!nb) {
   2147     // buffer too full to read into, so no I/O possible at moment
   2148     rv = ERR_IO_PENDING;
   2149   } else {
   2150     scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
   2151     if (OnNetworkTaskRunner()) {
   2152       rv = DoBufferRecv(read_buffer.get(), nb);
   2153     } else {
   2154       bool posted = network_task_runner_->PostTask(
   2155           FROM_HERE,
   2156           base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
   2157                      nb));
   2158       rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
   2159     }
   2160 
   2161     if (rv == ERR_IO_PENDING) {
   2162       transport_recv_busy_ = true;
   2163     } else {
   2164       if (rv > 0) {
   2165         memcpy(buf, read_buffer->data(), rv);
   2166       } else if (rv == 0) {
   2167         transport_recv_eof_ = true;
   2168       }
   2169       memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
   2170     }
   2171   }
   2172   return rv;
   2173 }
   2174 
   2175 // Return 0 if nss_bufs_ was empty,
   2176 // > 0 for bytes transferred immediately,
   2177 // < 0 for error (or the non-error ERR_IO_PENDING).
   2178 int SSLClientSocketNSS::Core::BufferSend() {
   2179   DCHECK(OnNSSTaskRunner());
   2180 
   2181   if (transport_send_busy_)
   2182     return ERR_IO_PENDING;
   2183 
   2184   const char* buf1;
   2185   const char* buf2;
   2186   unsigned int len1, len2;
   2187   memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2);
   2188   const unsigned int len = len1 + len2;
   2189 
   2190   int rv = 0;
   2191   if (len) {
   2192     scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
   2193     memcpy(send_buffer->data(), buf1, len1);
   2194     memcpy(send_buffer->data() + len1, buf2, len2);
   2195 
   2196     if (OnNetworkTaskRunner()) {
   2197       rv = DoBufferSend(send_buffer.get(), len);
   2198     } else {
   2199       bool posted = network_task_runner_->PostTask(
   2200           FROM_HERE,
   2201           base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
   2202                      len));
   2203       rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
   2204     }
   2205 
   2206     if (rv == ERR_IO_PENDING) {
   2207       transport_send_busy_ = true;
   2208     } else {
   2209       memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
   2210     }
   2211   }
   2212 
   2213   return rv;
   2214 }
   2215 
   2216 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
   2217   DCHECK(OnNSSTaskRunner());
   2218 
   2219   if (next_handshake_state_ == STATE_HANDSHAKE) {
   2220     OnHandshakeIOComplete(result);
   2221     return;
   2222   }
   2223 
   2224   // Network layer received some data, check if client requested to read
   2225   // decrypted data.
   2226   if (!user_read_buf_.get())
   2227     return;
   2228 
   2229   int rv = DoReadLoop(result);
   2230   if (rv != ERR_IO_PENDING)
   2231     DoReadCallback(rv);
   2232 }
   2233 
   2234 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
   2235   DCHECK(OnNSSTaskRunner());
   2236 
   2237   if (next_handshake_state_ == STATE_HANDSHAKE) {
   2238     OnHandshakeIOComplete(result);
   2239     return;
   2240   }
   2241 
   2242   // OnSendComplete may need to call DoPayloadRead while the renegotiation
   2243   // handshake is in progress.
   2244   int rv_read = ERR_IO_PENDING;
   2245   int rv_write = ERR_IO_PENDING;
   2246   bool network_moved;
   2247   do {
   2248     if (user_read_buf_.get())
   2249       rv_read = DoPayloadRead();
   2250     if (user_write_buf_.get())
   2251       rv_write = DoPayloadWrite();
   2252     network_moved = DoTransportIO();
   2253   } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
   2254            (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
   2255 
   2256   // If the parent SSLClientSocketNSS is deleted during the processing of the
   2257   // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
   2258   // will be detached (and possibly deleted). Guard against deletion by taking
   2259   // an extra reference, then check if the Core was detached before invoking the
   2260   // next callback.
   2261   scoped_refptr<Core> guard(this);
   2262   if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
   2263     DoReadCallback(rv_read);
   2264 
   2265   if (OnNetworkTaskRunner() && detached_)
   2266     return;
   2267 
   2268   if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
   2269     DoWriteCallback(rv_write);
   2270 }
   2271 
   2272 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
   2273 // handshake. This requires network IO, which in turn calls
   2274 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
   2275 // winds its way through the state machine and ends up being passed to the
   2276 // callback. For Read() and Write(), that's what we want. But for Connect(),
   2277 // the caller expects OK (i.e. 0) for success.
   2278 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
   2279   DCHECK(OnNSSTaskRunner());
   2280   DCHECK_NE(rv, ERR_IO_PENDING);
   2281   DCHECK(!user_connect_callback_.is_null());
   2282 
   2283   base::Closure c = base::Bind(
   2284       base::ResetAndReturn(&user_connect_callback_),
   2285       rv > OK ? OK : rv);
   2286   PostOrRunCallback(FROM_HERE, c);
   2287 }
   2288 
   2289 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
   2290   DCHECK(OnNSSTaskRunner());
   2291   DCHECK_NE(ERR_IO_PENDING, rv);
   2292   DCHECK(!user_read_callback_.is_null());
   2293 
   2294   user_read_buf_ = NULL;
   2295   user_read_buf_len_ = 0;
   2296   int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2297   // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
   2298   // the network task runner.
   2299   PostOrRunCallback(
   2300       FROM_HERE,
   2301       base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
   2302   PostOrRunCallback(
   2303       FROM_HERE,
   2304       base::Bind(&Core::DidNSSRead, this, rv));
   2305   PostOrRunCallback(
   2306       FROM_HERE,
   2307       base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
   2308 }
   2309 
   2310 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
   2311   DCHECK(OnNSSTaskRunner());
   2312   DCHECK_NE(ERR_IO_PENDING, rv);
   2313   DCHECK(!user_write_callback_.is_null());
   2314 
   2315   // Since Run may result in Write being called, clear |user_write_callback_|
   2316   // up front.
   2317   user_write_buf_ = NULL;
   2318   user_write_buf_len_ = 0;
   2319   // Update buffer status because DoWriteLoop called DoTransportIO which may
   2320   // perform read operations.
   2321   int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
   2322   // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
   2323   // the network task runner.
   2324   PostOrRunCallback(
   2325       FROM_HERE,
   2326       base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
   2327   PostOrRunCallback(
   2328       FROM_HERE,
   2329       base::Bind(&Core::DidNSSWrite, this, rv));
   2330   PostOrRunCallback(
   2331       FROM_HERE,
   2332       base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
   2333 }
   2334 
   2335 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
   2336     void* arg,
   2337     PRFileDesc* socket,
   2338     SECKEYPublicKey **out_public_key,
   2339     SECKEYPrivateKey **out_private_key) {
   2340   Core* core = reinterpret_cast<Core*>(arg);
   2341   DCHECK(core->OnNSSTaskRunner());
   2342 
   2343   core->PostOrRunCallback(
   2344       FROM_HERE,
   2345       base::Bind(&AddLogEvent, core->weak_net_log_,
   2346                  NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
   2347 
   2348   // We have negotiated the TLS channel ID extension.
   2349   core->channel_id_xtn_negotiated_ = true;
   2350   std::string host = core->host_and_port_.host();
   2351   int error = ERR_UNEXPECTED;
   2352   if (core->OnNetworkTaskRunner()) {
   2353     error = core->DoGetDomainBoundCert(host);
   2354   } else {
   2355     bool posted = core->network_task_runner_->PostTask(
   2356         FROM_HERE,
   2357         base::Bind(
   2358             IgnoreResult(&Core::DoGetDomainBoundCert),
   2359             core, host));
   2360     error = posted ? ERR_IO_PENDING : ERR_ABORTED;
   2361   }
   2362 
   2363   if (error == ERR_IO_PENDING) {
   2364     // Asynchronous case.
   2365     core->channel_id_needed_ = true;
   2366     return SECWouldBlock;
   2367   }
   2368 
   2369   core->PostOrRunCallback(
   2370       FROM_HERE,
   2371       base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
   2372                  NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
   2373   SECStatus rv = SECSuccess;
   2374   if (error == OK) {
   2375     // Synchronous success.
   2376     int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
   2377     if (result == OK)
   2378       core->SetChannelIDProvided();
   2379     else
   2380       rv = SECFailure;
   2381   } else {
   2382     rv = SECFailure;
   2383   }
   2384 
   2385   return rv;
   2386 }
   2387 
   2388 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
   2389                                                   SECKEYPrivateKey** key) {
   2390   // Set the certificate.
   2391   SECItem cert_item;
   2392   cert_item.data = (unsigned char*) domain_bound_cert_.data();
   2393   cert_item.len = domain_bound_cert_.size();
   2394   ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
   2395                                                      &cert_item,
   2396                                                      NULL,
   2397                                                      PR_FALSE,
   2398                                                      PR_TRUE));
   2399   if (cert == NULL)
   2400     return MapNSSError(PORT_GetError());
   2401 
   2402   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
   2403   // Set the private key.
   2404   if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
   2405           slot.get(),
   2406           ServerBoundCertService::kEPKIPassword,
   2407           reinterpret_cast<const unsigned char*>(
   2408               domain_bound_private_key_.data()),
   2409           domain_bound_private_key_.size(),
   2410           &cert->subjectPublicKeyInfo,
   2411           false,
   2412           false,
   2413           key,
   2414           public_key)) {
   2415     int error = MapNSSError(PORT_GetError());
   2416     return error;
   2417   }
   2418 
   2419   return OK;
   2420 }
   2421 
   2422 void SSLClientSocketNSS::Core::UpdateServerCert() {
   2423   nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
   2424   nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
   2425       nss_handshake_state_.server_cert_chain.AsStringPieceVector());
   2426   if (nss_handshake_state_.server_cert.get()) {
   2427     // Since this will be called asynchronously on another thread, it needs to
   2428     // own a reference to the certificate.
   2429     NetLog::ParametersCallback net_log_callback =
   2430         base::Bind(&NetLogX509CertificateCallback,
   2431                    nss_handshake_state_.server_cert);
   2432     PostOrRunCallback(
   2433         FROM_HERE,
   2434         base::Bind(&AddLogEventWithCallback, weak_net_log_,
   2435                    NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
   2436                    net_log_callback));
   2437   }
   2438 }
   2439 
   2440 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
   2441   const SECItem* signed_cert_timestamps =
   2442       SSL_PeerSignedCertTimestamps(nss_fd_);
   2443 
   2444   if (!signed_cert_timestamps || !signed_cert_timestamps->len)
   2445     return;
   2446 
   2447   nss_handshake_state_.sct_list_from_tls_extension = std::string(
   2448       reinterpret_cast<char*>(signed_cert_timestamps->data),
   2449       signed_cert_timestamps->len);
   2450 }
   2451 
   2452 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
   2453   const SECItemArray* ocsp_responses =
   2454       SSL_PeerStapledOCSPResponses(nss_fd_);
   2455   if (!ocsp_responses || !ocsp_responses->len)
   2456     return;
   2457 
   2458   nss_handshake_state_.stapled_ocsp_response = std::string(
   2459       reinterpret_cast<char*>(ocsp_responses->items[0].data),
   2460       ocsp_responses->items[0].len);
   2461 
   2462   // TODO(agl): figure out how to plumb an OCSP response into the Mac
   2463   // system library and update IsOCSPStaplingSupported for Mac.
   2464   if (IsOCSPStaplingSupported()) {
   2465   #if defined(OS_WIN)
   2466     if (nss_handshake_state_.server_cert) {
   2467       CRYPT_DATA_BLOB ocsp_response_blob;
   2468       ocsp_response_blob.cbData = ocsp_responses->items[0].len;
   2469       ocsp_response_blob.pbData = ocsp_responses->items[0].data;
   2470       BOOL ok = CertSetCertificateContextProperty(
   2471           nss_handshake_state_.server_cert->os_cert_handle(),
   2472           CERT_OCSP_RESPONSE_PROP_ID,
   2473           CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
   2474           &ocsp_response_blob);
   2475       if (!ok) {
   2476         VLOG(1) << "Failed to set OCSP response property: "
   2477                 << GetLastError();
   2478       }
   2479     }
   2480   #elif defined(USE_NSS)
   2481     CacheOCSPResponseFromSideChannelFunction cache_ocsp_response =
   2482         GetCacheOCSPResponseFromSideChannelFunction();
   2483 
   2484     cache_ocsp_response(
   2485         CERT_GetDefaultCertDB(),
   2486         nss_handshake_state_.server_cert_chain[0], PR_Now(),
   2487         &ocsp_responses->items[0], NULL);
   2488   #endif
   2489   }  // IsOCSPStaplingSupported()
   2490 }
   2491 
   2492 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
   2493   SSLChannelInfo channel_info;
   2494   SECStatus ok = SSL_GetChannelInfo(nss_fd_,
   2495                                     &channel_info, sizeof(channel_info));
   2496   if (ok == SECSuccess &&
   2497       channel_info.length == sizeof(channel_info) &&
   2498       channel_info.cipherSuite) {
   2499     nss_handshake_state_.ssl_connection_status |=
   2500         (static_cast<int>(channel_info.cipherSuite) &
   2501          SSL_CONNECTION_CIPHERSUITE_MASK) <<
   2502         SSL_CONNECTION_CIPHERSUITE_SHIFT;
   2503 
   2504     nss_handshake_state_.ssl_connection_status |=
   2505         (static_cast<int>(channel_info.compressionMethod) &
   2506          SSL_CONNECTION_COMPRESSION_MASK) <<
   2507         SSL_CONNECTION_COMPRESSION_SHIFT;
   2508 
   2509     // NSS 3.14.x doesn't have a version macro for TLS 1.2 (because NSS didn't
   2510     // support it yet), so use 0x0303 directly.
   2511     int version = SSL_CONNECTION_VERSION_UNKNOWN;
   2512     if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) {
   2513       // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
   2514       // version 2.
   2515       version = SSL_CONNECTION_VERSION_SSL2;
   2516     } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
   2517       version = SSL_CONNECTION_VERSION_SSL3;
   2518     } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_1_TLS) {
   2519       version = SSL_CONNECTION_VERSION_TLS1;
   2520     } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
   2521       version = SSL_CONNECTION_VERSION_TLS1_1;
   2522     } else if (channel_info.protocolVersion == 0x0303) {
   2523       version = SSL_CONNECTION_VERSION_TLS1_2;
   2524     }
   2525     nss_handshake_state_.ssl_connection_status |=
   2526         (version & SSL_CONNECTION_VERSION_MASK) <<
   2527         SSL_CONNECTION_VERSION_SHIFT;
   2528   }
   2529 
   2530   PRBool peer_supports_renego_ext;
   2531   ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
   2532                                         &peer_supports_renego_ext);
   2533   if (ok == SECSuccess) {
   2534     if (!peer_supports_renego_ext) {
   2535       nss_handshake_state_.ssl_connection_status |=
   2536           SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
   2537       // Log an informational message if the server does not support secure
   2538       // renegotiation (RFC 5746).
   2539       VLOG(1) << "The server " << host_and_port_.ToString()
   2540               << " does not support the TLS renegotiation_info extension.";
   2541     }
   2542     UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
   2543                               peer_supports_renego_ext, 2);
   2544 
   2545     // We would like to eliminate fallback to SSLv3 for non-buggy servers
   2546     // because of security concerns. For example, Google offers forward
   2547     // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
   2548     // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
   2549     // secrecy.
   2550     //
   2551     // Yngve from Opera has suggested using the renegotiation extension as an
   2552     // indicator that SSLv3 fallback was mistaken:
   2553     // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
   2554     //
   2555     // As a first step, measure how often clients perform version fallback
   2556     // while the server advertises support secure renegotiation.
   2557     if (ssl_config_.version_fallback &&
   2558         channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
   2559       UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
   2560                             peer_supports_renego_ext == PR_TRUE);
   2561     }
   2562   }
   2563 
   2564   if (ssl_config_.version_fallback) {
   2565     nss_handshake_state_.ssl_connection_status |=
   2566         SSL_CONNECTION_VERSION_FALLBACK;
   2567   }
   2568 }
   2569 
   2570 void SSLClientSocketNSS::Core::UpdateNextProto() {
   2571   uint8 buf[256];
   2572   SSLNextProtoState state;
   2573   unsigned buf_len;
   2574 
   2575   SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
   2576   if (rv != SECSuccess)
   2577     return;
   2578 
   2579   nss_handshake_state_.next_proto =
   2580       std::string(reinterpret_cast<char*>(buf), buf_len);
   2581   switch (state) {
   2582     case SSL_NEXT_PROTO_NEGOTIATED:
   2583     case SSL_NEXT_PROTO_SELECTED:
   2584       nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
   2585       break;
   2586     case SSL_NEXT_PROTO_NO_OVERLAP:
   2587       nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
   2588       break;
   2589     case SSL_NEXT_PROTO_NO_SUPPORT:
   2590       nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
   2591       break;
   2592     default:
   2593       NOTREACHED();
   2594       break;
   2595   }
   2596 }
   2597 
   2598 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
   2599   DCHECK(OnNSSTaskRunner());
   2600   if (nss_handshake_state_.resumed_handshake)
   2601     return;
   2602 
   2603   // Copy the NSS task runner-only state to the network task runner and
   2604   // log histograms from there, since the histograms also need access to the
   2605   // network task runner state.
   2606   PostOrRunCallback(
   2607       FROM_HERE,
   2608       base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
   2609                  this,
   2610                  channel_id_xtn_negotiated_,
   2611                  ssl_config_.channel_id_enabled,
   2612                  crypto::ECPrivateKey::IsSupported()));
   2613 }
   2614 
   2615 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
   2616     bool negotiated_channel_id,
   2617     bool channel_id_enabled,
   2618     bool supports_ecc) const {
   2619   DCHECK(OnNetworkTaskRunner());
   2620 
   2621   RecordChannelIDSupport(server_bound_cert_service_,
   2622                          negotiated_channel_id,
   2623                          channel_id_enabled,
   2624                          supports_ecc);
   2625 }
   2626 
   2627 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
   2628   DCHECK(OnNetworkTaskRunner());
   2629   DCHECK_GT(len, 0);
   2630 
   2631   if (detached_)
   2632     return ERR_ABORTED;
   2633 
   2634   int rv = transport_->socket()->Read(
   2635       read_buffer, len,
   2636       base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
   2637                  scoped_refptr<IOBuffer>(read_buffer)));
   2638 
   2639   if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
   2640     nss_task_runner_->PostTask(
   2641         FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
   2642                               scoped_refptr<IOBuffer>(read_buffer), rv));
   2643     return rv;
   2644   }
   2645 
   2646   return rv;
   2647 }
   2648 
   2649 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
   2650   DCHECK(OnNetworkTaskRunner());
   2651   DCHECK_GT(len, 0);
   2652 
   2653   if (detached_)
   2654     return ERR_ABORTED;
   2655 
   2656   int rv = transport_->socket()->Write(
   2657       send_buffer, len,
   2658       base::Bind(&Core::BufferSendComplete,
   2659                  base::Unretained(this)));
   2660 
   2661   if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
   2662     nss_task_runner_->PostTask(
   2663         FROM_HERE,
   2664         base::Bind(&Core::BufferSendComplete, this, rv));
   2665     return rv;
   2666   }
   2667 
   2668   return rv;
   2669 }
   2670 
   2671 int SSLClientSocketNSS::Core::DoGetDomainBoundCert(const std::string& host) {
   2672   DCHECK(OnNetworkTaskRunner());
   2673 
   2674   if (detached_)
   2675     return ERR_FAILED;
   2676 
   2677   weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
   2678 
   2679   int rv = server_bound_cert_service_->GetOrCreateDomainBoundCert(
   2680       host,
   2681       &domain_bound_private_key_,
   2682       &domain_bound_cert_,
   2683       base::Bind(&Core::OnGetDomainBoundCertComplete, base::Unretained(this)),
   2684       &domain_bound_cert_request_handle_);
   2685 
   2686   if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
   2687     nss_task_runner_->PostTask(
   2688         FROM_HERE,
   2689         base::Bind(&Core::OnHandshakeIOComplete, this, rv));
   2690     return ERR_IO_PENDING;
   2691   }
   2692 
   2693   return rv;
   2694 }
   2695 
   2696 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
   2697     const HandshakeState& state) {
   2698   DCHECK(OnNetworkTaskRunner());
   2699   network_handshake_state_ = state;
   2700 }
   2701 
   2702 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
   2703   DCHECK(OnNetworkTaskRunner());
   2704   unhandled_buffer_size_ = amount_in_read_buffer;
   2705 }
   2706 
   2707 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
   2708   DCHECK(OnNetworkTaskRunner());
   2709   DCHECK(nss_waiting_read_);
   2710   nss_waiting_read_ = false;
   2711   if (result <= 0)
   2712     nss_is_closed_ = true;
   2713 }
   2714 
   2715 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
   2716   DCHECK(OnNetworkTaskRunner());
   2717   DCHECK(nss_waiting_write_);
   2718   nss_waiting_write_ = false;
   2719   if (result < 0)
   2720     nss_is_closed_ = true;
   2721 }
   2722 
   2723 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
   2724   if (!OnNSSTaskRunner()) {
   2725     if (detached_)
   2726       return;
   2727 
   2728     nss_task_runner_->PostTask(
   2729         FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
   2730     return;
   2731   }
   2732 
   2733   DCHECK(OnNSSTaskRunner());
   2734 
   2735   memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
   2736   transport_send_busy_ = false;
   2737   OnSendComplete(result);
   2738 }
   2739 
   2740 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
   2741   if (!OnNSSTaskRunner()) {
   2742     if (detached_)
   2743       return;
   2744 
   2745     nss_task_runner_->PostTask(
   2746         FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
   2747     return;
   2748   }
   2749 
   2750   DCHECK(OnNSSTaskRunner());
   2751 
   2752   int rv = DoHandshakeLoop(result);
   2753   if (rv != ERR_IO_PENDING)
   2754     DoConnectCallback(rv);
   2755 }
   2756 
   2757 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result) {
   2758   DVLOG(1) << __FUNCTION__ << " " << result;
   2759   DCHECK(OnNetworkTaskRunner());
   2760 
   2761   OnHandshakeIOComplete(result);
   2762 }
   2763 
   2764 void SSLClientSocketNSS::Core::BufferRecvComplete(
   2765     IOBuffer* read_buffer,
   2766     int result) {
   2767   DCHECK(read_buffer);
   2768 
   2769   if (!OnNSSTaskRunner()) {
   2770     if (detached_)
   2771       return;
   2772 
   2773     nss_task_runner_->PostTask(
   2774         FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
   2775                               scoped_refptr<IOBuffer>(read_buffer), result));
   2776     return;
   2777   }
   2778 
   2779   DCHECK(OnNSSTaskRunner());
   2780 
   2781   if (result > 0) {
   2782     char* buf;
   2783     int nb = memio_GetReadParams(nss_bufs_, &buf);
   2784     CHECK_GE(nb, result);
   2785     memcpy(buf, read_buffer->data(), result);
   2786   } else if (result == 0) {
   2787     transport_recv_eof_ = true;
   2788   }
   2789 
   2790   memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
   2791   transport_recv_busy_ = false;
   2792   OnRecvComplete(result);
   2793 }
   2794 
   2795 void SSLClientSocketNSS::Core::PostOrRunCallback(
   2796     const tracked_objects::Location& location,
   2797     const base::Closure& task) {
   2798   if (!OnNetworkTaskRunner()) {
   2799     network_task_runner_->PostTask(
   2800         FROM_HERE,
   2801         base::Bind(&Core::PostOrRunCallback, this, location, task));
   2802     return;
   2803   }
   2804 
   2805   if (detached_ || task.is_null())
   2806     return;
   2807   task.Run();
   2808 }
   2809 
   2810 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
   2811   PostOrRunCallback(
   2812       FROM_HERE,
   2813       base::Bind(&AddLogEventWithCallback, weak_net_log_,
   2814                  NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
   2815                  NetLog::IntegerCallback("cert_count", cert_count)));
   2816 }
   2817 
   2818 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
   2819   PostOrRunCallback(
   2820       FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
   2821                             NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
   2822   nss_handshake_state_.channel_id_sent = true;
   2823   // Update the network task runner's view of the handshake state now that
   2824   // channel id has been sent.
   2825   PostOrRunCallback(
   2826       FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
   2827                             nss_handshake_state_));
   2828 }
   2829 
   2830 SSLClientSocketNSS::SSLClientSocketNSS(
   2831     base::SequencedTaskRunner* nss_task_runner,
   2832     scoped_ptr<ClientSocketHandle> transport_socket,
   2833     const HostPortPair& host_and_port,
   2834     const SSLConfig& ssl_config,
   2835     const SSLClientSocketContext& context)
   2836     : nss_task_runner_(nss_task_runner),
   2837       transport_(transport_socket.Pass()),
   2838       host_and_port_(host_and_port),
   2839       ssl_config_(ssl_config),
   2840       cert_verifier_(context.cert_verifier),
   2841       cert_transparency_verifier_(context.cert_transparency_verifier),
   2842       server_bound_cert_service_(context.server_bound_cert_service),
   2843       ssl_session_cache_shard_(context.ssl_session_cache_shard),
   2844       completed_handshake_(false),
   2845       next_handshake_state_(STATE_NONE),
   2846       nss_fd_(NULL),
   2847       net_log_(transport_->socket()->NetLog()),
   2848       transport_security_state_(context.transport_security_state),
   2849       valid_thread_id_(base::kInvalidThreadId) {
   2850   EnterFunction("");
   2851   InitCore();
   2852   LeaveFunction("");
   2853 }
   2854 
   2855 SSLClientSocketNSS::~SSLClientSocketNSS() {
   2856   EnterFunction("");
   2857   Disconnect();
   2858   LeaveFunction("");
   2859 }
   2860 
   2861 // static
   2862 void SSLClientSocket::ClearSessionCache() {
   2863   // SSL_ClearSessionCache can't be called before NSS is initialized.  Don't
   2864   // bother initializing NSS just to clear an empty SSL session cache.
   2865   if (!NSS_IsInitialized())
   2866     return;
   2867 
   2868   SSL_ClearSessionCache();
   2869 }
   2870 
   2871 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
   2872   EnterFunction("");
   2873   ssl_info->Reset();
   2874   if (core_->state().server_cert_chain.empty() ||
   2875       !core_->state().server_cert_chain[0]) {
   2876     return false;
   2877   }
   2878 
   2879   ssl_info->cert_status = server_cert_verify_result_.cert_status;
   2880   ssl_info->cert = server_cert_verify_result_.verified_cert;
   2881 
   2882   AddSCTInfoToSSLInfo(ssl_info);
   2883 
   2884   ssl_info->connection_status =
   2885       core_->state().ssl_connection_status;
   2886   ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
   2887   for (HashValueVector::const_iterator i = side_pinned_public_keys_.begin();
   2888        i != side_pinned_public_keys_.end(); ++i) {
   2889     ssl_info->public_key_hashes.push_back(*i);
   2890   }
   2891   ssl_info->is_issued_by_known_root =
   2892       server_cert_verify_result_.is_issued_by_known_root;
   2893   ssl_info->client_cert_sent =
   2894       ssl_config_.send_client_cert && ssl_config_.client_cert.get();
   2895   ssl_info->channel_id_sent = WasChannelIDSent();
   2896 
   2897   PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
   2898       core_->state().ssl_connection_status);
   2899   SSLCipherSuiteInfo cipher_info;
   2900   SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
   2901                                         &cipher_info, sizeof(cipher_info));
   2902   if (ok == SECSuccess) {
   2903     ssl_info->security_bits = cipher_info.effectiveKeyBits;
   2904   } else {
   2905     ssl_info->security_bits = -1;
   2906     LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
   2907                 << " for cipherSuite " << cipher_suite;
   2908   }
   2909 
   2910   ssl_info->handshake_type = core_->state().resumed_handshake ?
   2911       SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
   2912 
   2913   LeaveFunction("");
   2914   return true;
   2915 }
   2916 
   2917 void SSLClientSocketNSS::GetSSLCertRequestInfo(
   2918     SSLCertRequestInfo* cert_request_info) {
   2919   EnterFunction("");
   2920   // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair
   2921   cert_request_info->host_and_port = host_and_port_.ToString();
   2922   cert_request_info->cert_authorities = core_->state().cert_authorities;
   2923   LeaveFunction("");
   2924 }
   2925 
   2926 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
   2927                                              bool has_context,
   2928                                              const base::StringPiece& context,
   2929                                              unsigned char* out,
   2930                                              unsigned int outlen) {
   2931   if (!IsConnected())
   2932     return ERR_SOCKET_NOT_CONNECTED;
   2933 
   2934   // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
   2935   // the midst of a handshake.
   2936   SECStatus result = SSL_ExportKeyingMaterial(
   2937       nss_fd_, label.data(), label.size(), has_context,
   2938       reinterpret_cast<const unsigned char*>(context.data()),
   2939       context.length(), out, outlen);
   2940   if (result != SECSuccess) {
   2941     LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
   2942     return MapNSSError(PORT_GetError());
   2943   }
   2944   return OK;
   2945 }
   2946 
   2947 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
   2948   if (!IsConnected())
   2949     return ERR_SOCKET_NOT_CONNECTED;
   2950   unsigned char buf[64];
   2951   unsigned int len;
   2952   SECStatus result = SSL_GetChannelBinding(nss_fd_,
   2953                                            SSL_CHANNEL_BINDING_TLS_UNIQUE,
   2954                                            buf, &len, arraysize(buf));
   2955   if (result != SECSuccess) {
   2956     LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
   2957     return MapNSSError(PORT_GetError());
   2958   }
   2959   out->assign(reinterpret_cast<char*>(buf), len);
   2960   return OK;
   2961 }
   2962 
   2963 SSLClientSocket::NextProtoStatus
   2964 SSLClientSocketNSS::GetNextProto(std::string* proto,
   2965                                  std::string* server_protos) {
   2966   *proto = core_->state().next_proto;
   2967   *server_protos = core_->state().server_protos;
   2968   return core_->state().next_proto_status;
   2969 }
   2970 
   2971 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
   2972   EnterFunction("");
   2973   DCHECK(transport_.get());
   2974   // It is an error to create an SSLClientSocket whose context has no
   2975   // TransportSecurityState.
   2976   DCHECK(transport_security_state_);
   2977   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   2978   DCHECK(user_connect_callback_.is_null());
   2979   DCHECK(!callback.is_null());
   2980 
   2981   EnsureThreadIdAssigned();
   2982 
   2983   net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
   2984 
   2985   int rv = Init();
   2986   if (rv != OK) {
   2987     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   2988     return rv;
   2989   }
   2990 
   2991   rv = InitializeSSLOptions();
   2992   if (rv != OK) {
   2993     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   2994     return rv;
   2995   }
   2996 
   2997   rv = InitializeSSLPeerName();
   2998   if (rv != OK) {
   2999     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   3000     return rv;
   3001   }
   3002 
   3003   GotoState(STATE_HANDSHAKE);
   3004 
   3005   rv = DoHandshakeLoop(OK);
   3006   if (rv == ERR_IO_PENDING) {
   3007     user_connect_callback_ = callback;
   3008   } else {
   3009     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   3010   }
   3011 
   3012   LeaveFunction("");
   3013   return rv > OK ? OK : rv;
   3014 }
   3015 
   3016 void SSLClientSocketNSS::Disconnect() {
   3017   EnterFunction("");
   3018 
   3019   CHECK(CalledOnValidThread());
   3020 
   3021   // Shut down anything that may call us back.
   3022   core_->Detach();
   3023   verifier_.reset();
   3024   transport_->socket()->Disconnect();
   3025 
   3026   // Reset object state.
   3027   user_connect_callback_.Reset();
   3028   server_cert_verify_result_.Reset();
   3029   completed_handshake_   = false;
   3030   start_cert_verification_time_ = base::TimeTicks();
   3031   InitCore();
   3032 
   3033   LeaveFunction("");
   3034 }
   3035 
   3036 bool SSLClientSocketNSS::IsConnected() const {
   3037   EnterFunction("");
   3038   bool ret = completed_handshake_ &&
   3039              (core_->HasPendingAsyncOperation() ||
   3040               (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
   3041               transport_->socket()->IsConnected());
   3042   LeaveFunction("");
   3043   return ret;
   3044 }
   3045 
   3046 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
   3047   EnterFunction("");
   3048   bool ret = completed_handshake_ &&
   3049              !core_->HasPendingAsyncOperation() &&
   3050              !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
   3051              transport_->socket()->IsConnectedAndIdle();
   3052   LeaveFunction("");
   3053   return ret;
   3054 }
   3055 
   3056 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
   3057   return transport_->socket()->GetPeerAddress(address);
   3058 }
   3059 
   3060 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
   3061   return transport_->socket()->GetLocalAddress(address);
   3062 }
   3063 
   3064 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
   3065   return net_log_;
   3066 }
   3067 
   3068 void SSLClientSocketNSS::SetSubresourceSpeculation() {
   3069   if (transport_.get() && transport_->socket()) {
   3070     transport_->socket()->SetSubresourceSpeculation();
   3071   } else {
   3072     NOTREACHED();
   3073   }
   3074 }
   3075 
   3076 void SSLClientSocketNSS::SetOmniboxSpeculation() {
   3077   if (transport_.get() && transport_->socket()) {
   3078     transport_->socket()->SetOmniboxSpeculation();
   3079   } else {
   3080     NOTREACHED();
   3081   }
   3082 }
   3083 
   3084 bool SSLClientSocketNSS::WasEverUsed() const {
   3085   if (transport_.get() && transport_->socket()) {
   3086     return transport_->socket()->WasEverUsed();
   3087   }
   3088   NOTREACHED();
   3089   return false;
   3090 }
   3091 
   3092 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
   3093   if (transport_.get() && transport_->socket()) {
   3094     return transport_->socket()->UsingTCPFastOpen();
   3095   }
   3096   NOTREACHED();
   3097   return false;
   3098 }
   3099 
   3100 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
   3101                              const CompletionCallback& callback) {
   3102   DCHECK(core_.get());
   3103   DCHECK(!callback.is_null());
   3104 
   3105   EnterFunction(buf_len);
   3106   int rv = core_->Read(buf, buf_len, callback);
   3107   LeaveFunction(rv);
   3108 
   3109   return rv;
   3110 }
   3111 
   3112 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
   3113                               const CompletionCallback& callback) {
   3114   DCHECK(core_.get());
   3115   DCHECK(!callback.is_null());
   3116 
   3117   EnterFunction(buf_len);
   3118   int rv = core_->Write(buf, buf_len, callback);
   3119   LeaveFunction(rv);
   3120 
   3121   return rv;
   3122 }
   3123 
   3124 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
   3125   return transport_->socket()->SetReceiveBufferSize(size);
   3126 }
   3127 
   3128 bool SSLClientSocketNSS::SetSendBufferSize(int32 size) {
   3129   return transport_->socket()->SetSendBufferSize(size);
   3130 }
   3131 
   3132 int SSLClientSocketNSS::Init() {
   3133   EnterFunction("");
   3134   // Initialize the NSS SSL library in a threadsafe way.  This also
   3135   // initializes the NSS base library.
   3136   EnsureNSSSSLInit();
   3137   if (!NSS_IsInitialized())
   3138     return ERR_UNEXPECTED;
   3139 #if defined(USE_NSS) || defined(OS_IOS)
   3140   if (ssl_config_.cert_io_enabled) {
   3141     // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
   3142     // loop by MessageLoopForIO::current().
   3143     // X509Certificate::Verify() runs on a worker thread of CertVerifier.
   3144     EnsureNSSHttpIOInit();
   3145   }
   3146 #endif
   3147 
   3148   LeaveFunction("");
   3149   return OK;
   3150 }
   3151 
   3152 void SSLClientSocketNSS::InitCore() {
   3153   core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
   3154                    nss_task_runner_.get(),
   3155                    transport_.get(),
   3156                    host_and_port_,
   3157                    ssl_config_,
   3158                    &net_log_,
   3159                    server_bound_cert_service_);
   3160 }
   3161 
   3162 int SSLClientSocketNSS::InitializeSSLOptions() {
   3163   // Transport connected, now hook it up to nss
   3164   nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
   3165   if (nss_fd_ == NULL) {
   3166     return ERR_OUT_OF_MEMORY;  // TODO(port): map NSPR error code.
   3167   }
   3168 
   3169   // Grab pointer to buffers
   3170   memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
   3171 
   3172   /* Create SSL state machine */
   3173   /* Push SSL onto our fake I/O socket */
   3174   if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_) == NULL) {
   3175     LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
   3176     PR_Close(nss_fd_);
   3177     nss_fd_ = NULL;
   3178     return ERR_OUT_OF_MEMORY;  // TODO(port): map NSPR/NSS error code.
   3179   }
   3180   // TODO(port): set more ssl options!  Check errors!
   3181 
   3182   int rv;
   3183 
   3184   rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
   3185   if (rv != SECSuccess) {
   3186     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
   3187     return ERR_UNEXPECTED;
   3188   }
   3189 
   3190   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
   3191   if (rv != SECSuccess) {
   3192     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
   3193     return ERR_UNEXPECTED;
   3194   }
   3195 
   3196   // Don't do V2 compatible hellos because they don't support TLS extensions.
   3197   rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
   3198   if (rv != SECSuccess) {
   3199     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
   3200     return ERR_UNEXPECTED;
   3201   }
   3202 
   3203   SSLVersionRange version_range;
   3204   version_range.min = ssl_config_.version_min;
   3205   version_range.max = ssl_config_.version_max;
   3206   rv = SSL_VersionRangeSet(nss_fd_, &version_range);
   3207   if (rv != SECSuccess) {
   3208     LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
   3209     return ERR_NO_SSL_VERSIONS_ENABLED;
   3210   }
   3211 
   3212   if (ssl_config_.version_fallback) {
   3213     rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALLBACK_SCSV, PR_TRUE);
   3214     if (rv != SECSuccess) {
   3215       LogFailedNSSFunction(
   3216           net_log_, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
   3217     }
   3218   }
   3219 
   3220   for (std::vector<uint16>::const_iterator it =
   3221            ssl_config_.disabled_cipher_suites.begin();
   3222        it != ssl_config_.disabled_cipher_suites.end(); ++it) {
   3223     // This will fail if the specified cipher is not implemented by NSS, but
   3224     // the failure is harmless.
   3225     SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
   3226   }
   3227 
   3228   // Support RFC 5077
   3229   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
   3230   if (rv != SECSuccess) {
   3231     LogFailedNSSFunction(
   3232         net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
   3233   }
   3234 
   3235   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
   3236                      ssl_config_.false_start_enabled);
   3237   if (rv != SECSuccess)
   3238     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
   3239 
   3240   // We allow servers to request renegotiation. Since we're a client,
   3241   // prohibiting this is rather a waste of time. Only servers are in a
   3242   // position to prevent renegotiation attacks.
   3243   // http://extendedsubset.com/?p=8
   3244 
   3245   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
   3246                      SSL_RENEGOTIATE_TRANSITIONAL);
   3247   if (rv != SECSuccess) {
   3248     LogFailedNSSFunction(
   3249         net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
   3250   }
   3251 
   3252   rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
   3253   if (rv != SECSuccess)
   3254     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
   3255 
   3256 // Added in NSS 3.15
   3257 #ifdef SSL_ENABLE_OCSP_STAPLING
   3258   // Request OCSP stapling even on platforms that don't support it, in
   3259   // order to extract Certificate Transparency information.
   3260   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING,
   3261                      (IsOCSPStaplingSupported() ||
   3262                       ssl_config_.signed_cert_timestamps_enabled));
   3263   if (rv != SECSuccess) {
   3264     LogFailedNSSFunction(net_log_, "SSL_OptionSet",
   3265                          "SSL_ENABLE_OCSP_STAPLING");
   3266   }
   3267 #endif
   3268 
   3269   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
   3270                      ssl_config_.signed_cert_timestamps_enabled);
   3271   if (rv != SECSuccess) {
   3272     LogFailedNSSFunction(net_log_, "SSL_OptionSet",
   3273                          "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
   3274   }
   3275 
   3276 // Chromium patch to libssl
   3277 #ifdef SSL_ENABLE_CACHED_INFO
   3278   rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_CACHED_INFO,
   3279                      ssl_config_.cached_info_enabled);
   3280   if (rv != SECSuccess)
   3281     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO");
   3282 #endif
   3283 
   3284   rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
   3285   if (rv != SECSuccess) {
   3286     LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
   3287     return ERR_UNEXPECTED;
   3288   }
   3289 
   3290   if (!core_->Init(nss_fd_, nss_bufs))
   3291     return ERR_UNEXPECTED;
   3292 
   3293   // Tell SSL the hostname we're trying to connect to.
   3294   SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
   3295 
   3296   // Tell SSL we're a client; needed if not letting NSPR do socket I/O
   3297   SSL_ResetHandshake(nss_fd_, PR_FALSE);
   3298 
   3299   return OK;
   3300 }
   3301 
   3302 int SSLClientSocketNSS::InitializeSSLPeerName() {
   3303   // Tell NSS who we're connected to
   3304   IPEndPoint peer_address;
   3305   int err = transport_->socket()->GetPeerAddress(&peer_address);
   3306   if (err != OK)
   3307     return err;
   3308 
   3309   SockaddrStorage storage;
   3310   if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
   3311     return ERR_UNEXPECTED;
   3312 
   3313   PRNetAddr peername;
   3314   memset(&peername, 0, sizeof(peername));
   3315   DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
   3316   size_t len = std::min(static_cast<size_t>(storage.addr_len),
   3317                         sizeof(peername));
   3318   memcpy(&peername, storage.addr, len);
   3319 
   3320   // Adjust the address family field for BSD, whose sockaddr
   3321   // structure has a one-byte length and one-byte address family
   3322   // field at the beginning.  PRNetAddr has a two-byte address
   3323   // family field at the beginning.
   3324   peername.raw.family = storage.addr->sa_family;
   3325 
   3326   memio_SetPeerName(nss_fd_, &peername);
   3327 
   3328   // Set the peer ID for session reuse.  This is necessary when we create an
   3329   // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
   3330   // rather than the destination server's address in that case.
   3331   std::string peer_id = host_and_port_.ToString();
   3332   // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
   3333   // This will cause session cache misses between sockets with different values
   3334   // of ssl_session_cache_shard_ and this is used to partition the session cache
   3335   // for incognito mode.
   3336   if (!ssl_session_cache_shard_.empty()) {
   3337     peer_id += "/" + ssl_session_cache_shard_;
   3338   }
   3339   SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
   3340   if (rv != SECSuccess)
   3341     LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
   3342 
   3343   return OK;
   3344 }
   3345 
   3346 void SSLClientSocketNSS::DoConnectCallback(int rv) {
   3347   EnterFunction(rv);
   3348   DCHECK_NE(ERR_IO_PENDING, rv);
   3349   DCHECK(!user_connect_callback_.is_null());
   3350 
   3351   base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
   3352   LeaveFunction("");
   3353 }
   3354 
   3355 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
   3356   EnterFunction(result);
   3357   int rv = DoHandshakeLoop(result);
   3358   if (rv != ERR_IO_PENDING) {
   3359     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
   3360     DoConnectCallback(rv);
   3361   }
   3362   LeaveFunction("");
   3363 }
   3364 
   3365 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
   3366   EnterFunction(last_io_result);
   3367   int rv = last_io_result;
   3368   do {
   3369     // Default to STATE_NONE for next state.
   3370     // (This is a quirk carried over from the windows
   3371     // implementation.  It makes reading the logs a bit harder.)
   3372     // State handlers can and often do call GotoState just
   3373     // to stay in the current state.
   3374     State state = next_handshake_state_;
   3375     GotoState(STATE_NONE);
   3376     switch (state) {
   3377       case STATE_HANDSHAKE:
   3378         rv = DoHandshake();
   3379         break;
   3380       case STATE_HANDSHAKE_COMPLETE:
   3381         rv = DoHandshakeComplete(rv);
   3382         break;
   3383       case STATE_VERIFY_CERT:
   3384         DCHECK(rv == OK);
   3385         rv = DoVerifyCert(rv);
   3386         break;
   3387       case STATE_VERIFY_CERT_COMPLETE:
   3388         rv = DoVerifyCertComplete(rv);
   3389         break;
   3390       case STATE_NONE:
   3391       default:
   3392         rv = ERR_UNEXPECTED;
   3393         LOG(DFATAL) << "unexpected state " << state;
   3394         break;
   3395     }
   3396   } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
   3397   LeaveFunction("");
   3398   return rv;
   3399 }
   3400 
   3401 int SSLClientSocketNSS::DoHandshake() {
   3402   EnterFunction("");
   3403   int rv = core_->Connect(
   3404       base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
   3405                  base::Unretained(this)));
   3406   GotoState(STATE_HANDSHAKE_COMPLETE);
   3407 
   3408   LeaveFunction(rv);
   3409   return rv;
   3410 }
   3411 
   3412 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
   3413   EnterFunction(result);
   3414 
   3415   if (result == OK) {
   3416     // SSL handshake is completed. Let's verify the certificate.
   3417     GotoState(STATE_VERIFY_CERT);
   3418     // Done!
   3419   }
   3420   set_channel_id_sent(core_->state().channel_id_sent);
   3421   set_signed_cert_timestamps_received(
   3422       !core_->state().sct_list_from_tls_extension.empty());
   3423   set_stapled_ocsp_response_received(
   3424       !core_->state().stapled_ocsp_response.empty());
   3425 
   3426   LeaveFunction(result);
   3427   return result;
   3428 }
   3429 
   3430 int SSLClientSocketNSS::DoVerifyCert(int result) {
   3431   DCHECK(!core_->state().server_cert_chain.empty());
   3432   DCHECK(core_->state().server_cert_chain[0]);
   3433 
   3434   GotoState(STATE_VERIFY_CERT_COMPLETE);
   3435 
   3436   // If the certificate is expected to be bad we can use the expectation as
   3437   // the cert status.
   3438   base::StringPiece der_cert(
   3439       reinterpret_cast<char*>(
   3440           core_->state().server_cert_chain[0]->derCert.data),
   3441       core_->state().server_cert_chain[0]->derCert.len);
   3442   CertStatus cert_status;
   3443   if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
   3444     DCHECK(start_cert_verification_time_.is_null());
   3445     VLOG(1) << "Received an expected bad cert with status: " << cert_status;
   3446     server_cert_verify_result_.Reset();
   3447     server_cert_verify_result_.cert_status = cert_status;
   3448     server_cert_verify_result_.verified_cert = core_->state().server_cert;
   3449     return OK;
   3450   }
   3451 
   3452   // We may have failed to create X509Certificate object if we are
   3453   // running inside sandbox.
   3454   if (!core_->state().server_cert.get()) {
   3455     server_cert_verify_result_.Reset();
   3456     server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
   3457     return ERR_CERT_INVALID;
   3458   }
   3459 
   3460   start_cert_verification_time_ = base::TimeTicks::Now();
   3461 
   3462   int flags = 0;
   3463   if (ssl_config_.rev_checking_enabled)
   3464     flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
   3465   if (ssl_config_.verify_ev_cert)
   3466     flags |= CertVerifier::VERIFY_EV_CERT;
   3467   if (ssl_config_.cert_io_enabled)
   3468     flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
   3469   if (ssl_config_.rev_checking_required_local_anchors)
   3470     flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
   3471   verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
   3472   return verifier_->Verify(
   3473       core_->state().server_cert.get(),
   3474       host_and_port_.host(),
   3475       flags,
   3476       SSLConfigService::GetCRLSet().get(),
   3477       &server_cert_verify_result_,
   3478       base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
   3479                  base::Unretained(this)),
   3480       net_log_);
   3481 }
   3482 
   3483 // Derived from AuthCertificateCallback() in
   3484 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
   3485 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
   3486   verifier_.reset();
   3487 
   3488   if (!start_cert_verification_time_.is_null()) {
   3489     base::TimeDelta verify_time =
   3490         base::TimeTicks::Now() - start_cert_verification_time_;
   3491     if (result == OK)
   3492         UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
   3493     else
   3494         UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
   3495   }
   3496 
   3497   // We used to remember the intermediate CA certs in the NSS database
   3498   // persistently.  However, NSS opens a connection to the SQLite database
   3499   // during NSS initialization and doesn't close the connection until NSS
   3500   // shuts down.  If the file system where the database resides is gone,
   3501   // the database connection goes bad.  What's worse, the connection won't
   3502   // recover when the file system comes back.  Until this NSS or SQLite bug
   3503   // is fixed, we need to  avoid using the NSS database for non-essential
   3504   // purposes.  See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
   3505   // http://crbug.com/15630 for more info.
   3506 
   3507   // TODO(hclam): Skip logging if server cert was expected to be bad because
   3508   // |server_cert_verify_result_| doesn't contain all the information about
   3509   // the cert.
   3510   if (result == OK)
   3511     LogConnectionTypeMetrics();
   3512 
   3513 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) && !defined(OS_IOS)
   3514   // Take care of any mandates for public key pinning.
   3515   //
   3516   // Pinning is only enabled for official builds to make sure that others don't
   3517   // end up with pins that cannot be easily updated.
   3518   //
   3519   // TODO(agl): We might have an issue here where a request for foo.example.com
   3520   // merges into a SPDY connection to www.example.com, and gets a different
   3521   // certificate.
   3522 
   3523   // Perform pin validation if, and only if, all these conditions obtain:
   3524   //
   3525   // * a TransportSecurityState object is available;
   3526   // * the server's certificate chain is valid (or suffers from only a minor
   3527   //   error);
   3528   // * the server's certificate chain chains up to a known root (i.e. not a
   3529   //   user-installed trust anchor); and
   3530   // * the build is recent (very old builds should fail open so that users
   3531   //   have some chance to recover).
   3532   //
   3533   const CertStatus cert_status = server_cert_verify_result_.cert_status;
   3534   if (transport_security_state_ &&
   3535       (result == OK ||
   3536        (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
   3537       server_cert_verify_result_.is_issued_by_known_root &&
   3538       TransportSecurityState::IsBuildTimely()) {
   3539     bool sni_available =
   3540         ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1 ||
   3541         ssl_config_.version_fallback;
   3542     const std::string& host = host_and_port_.host();
   3543 
   3544     TransportSecurityState::DomainState domain_state;
   3545     if (transport_security_state_->GetDomainState(host, sni_available,
   3546                                                   &domain_state) &&
   3547         domain_state.HasPublicKeyPins()) {
   3548       if (!domain_state.CheckPublicKeyPins(
   3549               server_cert_verify_result_.public_key_hashes)) {
   3550         result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
   3551         UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
   3552         TransportSecurityState::ReportUMAOnPinFailure(host);
   3553       } else {
   3554         UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
   3555       }
   3556     }
   3557   }
   3558 #endif
   3559 
   3560   if (result == OK) {
   3561     // Only check Certificate Transparency if there were no other errors with
   3562     // the connection.
   3563     VerifyCT();
   3564 
   3565     // Only cache the session if the certificate verified successfully.
   3566     core_->CacheSessionIfNecessary();
   3567   }
   3568 
   3569   completed_handshake_ = true;
   3570 
   3571   // Exit DoHandshakeLoop and return the result to the caller to Connect.
   3572   DCHECK_EQ(STATE_NONE, next_handshake_state_);
   3573   return result;
   3574 }
   3575 
   3576 void SSLClientSocketNSS::VerifyCT() {
   3577   if (!cert_transparency_verifier_)
   3578     return;
   3579 
   3580   // Note that this is a completely synchronous operation: The CT Log Verifier
   3581   // gets all the data it needs for SCT verification and does not do any
   3582   // external communication.
   3583   int result = cert_transparency_verifier_->Verify(
   3584       server_cert_verify_result_.verified_cert,
   3585       core_->state().stapled_ocsp_response,
   3586       core_->state().sct_list_from_tls_extension,
   3587       &ct_verify_result_,
   3588       net_log_);
   3589   // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
   3590   // from the state after verification is complete, to conserve memory.
   3591 
   3592   VLOG(1) << "CT Verification complete: result " << result
   3593           << " Invalid scts: " << ct_verify_result_.invalid_scts.size()
   3594           << " Verified scts: " << ct_verify_result_.verified_scts.size()
   3595           << " scts from unknown logs: "
   3596           << ct_verify_result_.unknown_logs_scts.size();
   3597 }
   3598 
   3599 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
   3600   UpdateConnectionTypeHistograms(CONNECTION_SSL);
   3601   int ssl_version = SSLConnectionStatusToVersion(
   3602       core_->state().ssl_connection_status);
   3603   switch (ssl_version) {
   3604     case SSL_CONNECTION_VERSION_SSL2:
   3605       UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2);
   3606       break;
   3607     case SSL_CONNECTION_VERSION_SSL3:
   3608       UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3);
   3609       break;
   3610     case SSL_CONNECTION_VERSION_TLS1:
   3611       UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1);
   3612       break;
   3613     case SSL_CONNECTION_VERSION_TLS1_1:
   3614       UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1);
   3615       break;
   3616     case SSL_CONNECTION_VERSION_TLS1_2:
   3617       UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2);
   3618       break;
   3619   };
   3620 }
   3621 
   3622 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
   3623   base::AutoLock auto_lock(lock_);
   3624   if (valid_thread_id_ != base::kInvalidThreadId)
   3625     return;
   3626   valid_thread_id_ = base::PlatformThread::CurrentId();
   3627 }
   3628 
   3629 bool SSLClientSocketNSS::CalledOnValidThread() const {
   3630   EnsureThreadIdAssigned();
   3631   base::AutoLock auto_lock(lock_);
   3632   return valid_thread_id_ == base::PlatformThread::CurrentId();
   3633 }
   3634 
   3635 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
   3636   for (ct::SCTList::const_iterator iter =
   3637        ct_verify_result_.verified_scts.begin();
   3638        iter != ct_verify_result_.verified_scts.end(); ++iter) {
   3639     ssl_info->signed_certificate_timestamps.push_back(
   3640         SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
   3641   }
   3642   for (ct::SCTList::const_iterator iter =
   3643        ct_verify_result_.invalid_scts.begin();
   3644        iter != ct_verify_result_.invalid_scts.end(); ++iter) {
   3645     ssl_info->signed_certificate_timestamps.push_back(
   3646         SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
   3647   }
   3648   for (ct::SCTList::const_iterator iter =
   3649        ct_verify_result_.unknown_logs_scts.begin();
   3650        iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
   3651     ssl_info->signed_certificate_timestamps.push_back(
   3652         SignedCertificateTimestampAndStatus(*iter,
   3653                                             ct::SCT_STATUS_LOG_UNKNOWN));
   3654   }
   3655 }
   3656 
   3657 ServerBoundCertService* SSLClientSocketNSS::GetServerBoundCertService() const {
   3658   return server_bound_cert_service_;
   3659 }
   3660 
   3661 }  // namespace net
   3662