Mark two tests in ImeTest.java as flaky
[chromium-blink-merge.git] / net / socket / ssl_client_socket_nss.cc
blob161184b10fff3d8206b7b79353d2d916b92c57f7
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived
6 // from AuthCertificateCallback() in
7 // mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp.
9 /* ***** BEGIN LICENSE BLOCK *****
10 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
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/
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.
22 * The Original Code is the Netscape security libraries.
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.
29 * Contributor(s):
30 * Ian McGreer <mcgreer@netscape.com>
31 * Javier Delgadillo <javi@netscape.com>
32 * Kai Engert <kengert@redhat.com>
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.
46 * ***** END LICENSE BLOCK ***** */
48 #include "net/socket/ssl_client_socket_nss.h"
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>
63 #include <algorithm>
64 #include <limits>
65 #include <map>
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/profiler/scoped_tracker.h"
75 #include "base/single_thread_task_runner.h"
76 #include "base/stl_util.h"
77 #include "base/strings/string_number_conversions.h"
78 #include "base/strings/string_util.h"
79 #include "base/strings/stringprintf.h"
80 #include "base/thread_task_runner_handle.h"
81 #include "base/threading/thread_restrictions.h"
82 #include "base/values.h"
83 #include "crypto/ec_private_key.h"
84 #include "crypto/nss_util.h"
85 #include "crypto/nss_util_internal.h"
86 #include "crypto/rsa_private_key.h"
87 #include "crypto/scoped_nss_types.h"
88 #include "net/base/address_list.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_policy_enforcer.h"
95 #include "net/cert/cert_status_flags.h"
96 #include "net/cert/cert_verifier.h"
97 #include "net/cert/ct_ev_whitelist.h"
98 #include "net/cert/ct_verifier.h"
99 #include "net/cert/ct_verify_result.h"
100 #include "net/cert/scoped_nss_types.h"
101 #include "net/cert/sct_status_flags.h"
102 #include "net/cert/single_request_cert_verifier.h"
103 #include "net/cert/x509_certificate_net_log_param.h"
104 #include "net/cert/x509_util.h"
105 #include "net/http/transport_security_state.h"
106 #include "net/ocsp/nss_ocsp.h"
107 #include "net/socket/client_socket_handle.h"
108 #include "net/socket/nss_ssl_util.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"
113 #if defined(OS_WIN)
114 #include <windows.h>
115 #include <wincrypt.h>
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>
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
130 namespace net {
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
152 #if !defined(CKM_AES_GCM)
153 #define CKM_AES_GCM 0x00001087
154 #endif
156 #if !defined(CKM_NSS_CHACHA20_POLY1305)
157 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
158 #endif
160 namespace {
162 // SSL plaintext fragments are shorter than 16KB. Although the record layer
163 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
164 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
165 // entire SSL record.
166 const int kRecvBufferSize = 17 * 1024;
167 const int kSendBufferSize = 17 * 1024;
169 // Used by SSLClientSocketNSS::Core to indicate there is no read result
170 // obtained by a previous operation waiting to be returned to the caller.
171 // This constant can be any non-negative/non-zero value (eg: it does not
172 // overlap with any value of the net::Error range, including net::OK).
173 const int kNoPendingReadResult = 1;
175 #if defined(OS_WIN)
176 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
177 // set on Windows XP without error. There is some overhead from the server
178 // sending the OCSP response if it supports the extension, for the subset of
179 // XP clients who will request it but be unable to use it, but this is an
180 // acceptable trade-off for simplicity of implementation.
181 bool IsOCSPStaplingSupported() {
182 return true;
184 #elif defined(USE_NSS)
185 typedef SECStatus
186 (*CacheOCSPResponseFromSideChannelFunction)(
187 CERTCertDBHandle *handle, CERTCertificate *cert, PRTime time,
188 SECItem *encodedResponse, void *pwArg);
190 // On Linux, we dynamically link against the system version of libnss3.so. In
191 // order to continue working on systems without up-to-date versions of NSS we
192 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
194 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
195 // runtime symbol resolution that we need.
196 class RuntimeLibNSSFunctionPointers {
197 public:
198 CacheOCSPResponseFromSideChannelFunction
199 GetCacheOCSPResponseFromSideChannelFunction() {
200 return cache_ocsp_response_from_side_channel_;
203 static RuntimeLibNSSFunctionPointers* GetInstance() {
204 return Singleton<RuntimeLibNSSFunctionPointers>::get();
207 private:
208 friend struct DefaultSingletonTraits<RuntimeLibNSSFunctionPointers>;
210 RuntimeLibNSSFunctionPointers() {
211 cache_ocsp_response_from_side_channel_ =
212 (CacheOCSPResponseFromSideChannelFunction)
213 dlsym(RTLD_DEFAULT, "CERT_CacheOCSPResponseFromSideChannel");
216 CacheOCSPResponseFromSideChannelFunction
217 cache_ocsp_response_from_side_channel_;
220 CacheOCSPResponseFromSideChannelFunction
221 GetCacheOCSPResponseFromSideChannelFunction() {
222 return RuntimeLibNSSFunctionPointers::GetInstance()
223 ->GetCacheOCSPResponseFromSideChannelFunction();
226 bool IsOCSPStaplingSupported() {
227 return GetCacheOCSPResponseFromSideChannelFunction() != NULL;
229 #else
230 bool IsOCSPStaplingSupported() {
231 return false;
233 #endif
235 #if defined(OS_WIN)
237 // This callback is intended to be used with CertFindChainInStore. In addition
238 // to filtering by extended/enhanced key usage, we do not show expired
239 // certificates and require digital signature usage in the key usage
240 // extension.
242 // This matches our behavior on Mac OS X and that of NSS. It also matches the
243 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
244 // 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
245 BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
246 void* find_arg) {
247 VLOG(1) << "Calling ClientCertFindCallback from _nss";
248 // Verify the certificate's KU is good.
249 BYTE key_usage;
250 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
251 &key_usage, 1)) {
252 if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
253 return FALSE;
254 } else {
255 DWORD err = GetLastError();
256 // If |err| is non-zero, it's an actual error. Otherwise the extension
257 // just isn't present, and we treat it as if everything was allowed.
258 if (err) {
259 DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
260 return FALSE;
264 // Verify the current time is within the certificate's validity period.
265 if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
266 return FALSE;
268 // Verify private key metadata is associated with this certificate.
269 DWORD size = 0;
270 if (!CertGetCertificateContextProperty(
271 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
272 return FALSE;
275 return TRUE;
278 #endif
280 // Helper functions to make it possible to log events from within the
281 // SSLClientSocketNSS::Core.
282 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
283 NetLog::EventType event_type) {
284 if (!net_log)
285 return;
286 net_log->AddEvent(event_type);
289 // Helper function to make it possible to log events from within the
290 // SSLClientSocketNSS::Core.
291 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
292 NetLog::EventType event_type,
293 const NetLog::ParametersCallback& callback) {
294 if (!net_log)
295 return;
296 net_log->AddEvent(event_type, callback);
299 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
300 // from within the SSLClientSocketNSS::Core.
301 // AddByteTransferEvent expects to receive a const char*, which within the
302 // Core is backed by an IOBuffer. If the "const char*" is bound via
303 // base::Bind and posted to another thread, and the IOBuffer that backs that
304 // pointer then goes out of scope on the origin thread, this would result in
305 // an invalid read of a stale pointer.
306 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
307 // to the owning IOBuffer can be bound to the Callback. This ensures that the
308 // IOBuffer will stay alive long enough to cross threads if needed.
309 void LogByteTransferEvent(
310 const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
311 int len, IOBuffer* buffer) {
312 if (!net_log)
313 return;
314 net_log->AddByteTransferEvent(event_type, len, buffer->data());
317 // PeerCertificateChain is a helper object which extracts the certificate
318 // chain, as given by the server, from an NSS socket and performs the needed
319 // resource management. The first element of the chain is the leaf certificate
320 // and the other elements are in the order given by the server.
321 class PeerCertificateChain {
322 public:
323 PeerCertificateChain() {}
324 PeerCertificateChain(const PeerCertificateChain& other);
325 ~PeerCertificateChain();
326 PeerCertificateChain& operator=(const PeerCertificateChain& other);
328 // Resets the current chain, freeing any resources, and updates the current
329 // chain to be a copy of the chain stored in |nss_fd|.
330 // If |nss_fd| is NULL, then the current certificate chain will be freed.
331 void Reset(PRFileDesc* nss_fd);
333 // Returns the current certificate chain as a vector of DER-encoded
334 // base::StringPieces. The returned vector remains valid until Reset is
335 // called.
336 std::vector<base::StringPiece> AsStringPieceVector() const;
338 bool empty() const { return certs_.empty(); }
340 CERTCertificate* operator[](size_t index) const {
341 DCHECK_LT(index, certs_.size());
342 return certs_[index];
345 private:
346 std::vector<CERTCertificate*> certs_;
349 PeerCertificateChain::PeerCertificateChain(
350 const PeerCertificateChain& other) {
351 *this = other;
354 PeerCertificateChain::~PeerCertificateChain() {
355 Reset(NULL);
358 PeerCertificateChain& PeerCertificateChain::operator=(
359 const PeerCertificateChain& other) {
360 if (this == &other)
361 return *this;
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]));
368 return *this;
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();
376 if (nss_fd == NULL)
377 return;
379 CERTCertList* list = SSL_PeerCertificateChain(nss_fd);
380 // The handshake on |nss_fd| may not have completed.
381 if (list == NULL)
382 return;
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));
388 CERT_DestroyCertList(list);
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);
400 return v;
403 // HandshakeState is a helper struct used to pass handshake state between
404 // the NSS task runner and the network task runner.
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(); }
414 void Reset() {
415 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
416 next_proto.clear();
417 negotiation_extension_ = SSLClientSocket::kExtensionUnknown;
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;
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;
432 // TLS extension used for protocol negotiation.
433 SSLClientSocket::SSLNegotiationExtension negotiation_extension_;
435 // True if a channel ID was sent.
436 bool channel_id_sent;
438 // List of DER-encoded X.509 DistinguishedName of certificate authorities
439 // allowed by the server.
440 std::vector<std::string> cert_authorities;
442 // Set when the handshake fully completes.
444 // The server certificate is first received from NSS as an NSS certificate
445 // chain (|server_cert_chain|) and then converted into a platform-specific
446 // X509Certificate object (|server_cert|). It's possible for some
447 // certificates to be successfully parsed by NSS, and not by the platform
448 // libraries (i.e.: when running within a sandbox, different parsing
449 // algorithms, etc), so it's not safe to assume that |server_cert| will
450 // always be non-NULL.
451 PeerCertificateChain server_cert_chain;
452 scoped_refptr<X509Certificate> server_cert;
453 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
454 std::string sct_list_from_tls_extension;
455 // Stapled OCSP response received.
456 std::string stapled_ocsp_response;
458 // True if the current handshake was the result of TLS session resumption.
459 bool resumed_handshake;
461 // The negotiated security parameters (TLS version, cipher, extensions) of
462 // the SSL connection.
463 int ssl_connection_status;
466 // Client-side error mapping functions.
468 // Map NSS error code to network error code.
469 int MapNSSClientError(PRErrorCode err) {
470 switch (err) {
471 case SSL_ERROR_BAD_CERT_ALERT:
472 case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
473 case SSL_ERROR_REVOKED_CERT_ALERT:
474 case SSL_ERROR_EXPIRED_CERT_ALERT:
475 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
476 case SSL_ERROR_UNKNOWN_CA_ALERT:
477 case SSL_ERROR_ACCESS_DENIED_ALERT:
478 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
479 default:
480 return MapNSSError(err);
484 } // namespace
486 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
487 // able to marshal data between NSS functions and an underlying transport
488 // socket.
490 // All public functions are meant to be called from the network task runner,
491 // and any callbacks supplied will be invoked there as well, provided that
492 // Detach() has not been called yet.
494 /////////////////////////////////////////////////////////////////////////////
496 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
498 // Because NSS may block on either hardware or user input during operations
499 // such as signing, creating certificates, or locating private keys, the Core
500 // handles all of the interactions with the underlying NSS SSL socket, so
501 // that these blocking calls can be executed on a dedicated task runner.
503 // Note that the network task runner and the NSS task runner may be executing
504 // on the same thread. If that happens, then it's more performant to try to
505 // complete as much work as possible synchronously, even if it might block,
506 // rather than continually PostTask-ing to the same thread.
508 // Because NSS functions should only be called on the NSS task runner, while
509 // I/O resources should only be accessed on the network task runner, most
510 // public functions are implemented via three methods, each with different
511 // task runner affinities.
513 // In the single-threaded mode (where the network and NSS task runners run on
514 // the same thread), these are all attempted synchronously, while in the
515 // multi-threaded mode, message passing is used.
517 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
518 // DoHandshake)
519 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
520 // (BufferRecv, BufferSend)
521 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
522 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
523 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
524 // data from the network task runner back to NSS (BufferRecvComplete,
525 // BufferSendComplete, OnHandshakeIOComplete)
527 /////////////////////////////////////////////////////////////////////////////
528 // Single-threaded example
530 // |--------------------------Network Task Runner--------------------------|
531 // SSLClientSocketNSS Core (Transport Socket)
532 // Read()
533 // |-------------------------V
534 // Read()
535 // |
536 // DoPayloadRead()
537 // |
538 // BufferRecv()
539 // |
540 // DoBufferRecv()
541 // |-------------------------V
542 // Read()
543 // V-------------------------|
544 // BufferRecvComplete()
545 // |
546 // PostOrRunCallback()
547 // V-------------------------|
548 // (Read Callback)
550 /////////////////////////////////////////////////////////////////////////////
551 // Multi-threaded example:
553 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
554 // SSLClientSocketNSS Core Socket Core
555 // Read()
556 // |---------------------V
557 // Read()
558 // |-------------------------------V
559 // Read()
560 // |
561 // DoPayloadRead()
562 // |
563 // BufferRecv
564 // V-------------------------------|
565 // DoBufferRecv
566 // |----------------V
567 // Read()
568 // V----------------|
569 // BufferRecvComplete()
570 // |-------------------------------V
571 // BufferRecvComplete()
572 // |
573 // PostOrRunCallback()
574 // V-------------------------------|
575 // PostOrRunCallback()
576 // V---------------------|
577 // (Read Callback)
579 /////////////////////////////////////////////////////////////////////////////
580 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
581 public:
582 // Creates a new Core.
584 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
585 // that need to operate on the underlying transport, net log, or server
586 // bound certificate fetching will happen on the |network_task_runner|, so
587 // that their lifetimes match that of the owning SSLClientSocketNSS.
589 // The caller retains ownership of |transport|, |net_log|, and
590 // |channel_id_service|, and they will not be accessed once Detach()
591 // has been called.
592 Core(base::SequencedTaskRunner* network_task_runner,
593 base::SequencedTaskRunner* nss_task_runner,
594 ClientSocketHandle* transport,
595 const HostPortPair& host_and_port,
596 const SSLConfig& ssl_config,
597 BoundNetLog* net_log,
598 ChannelIDService* channel_id_service);
600 // Called on the network task runner.
601 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
602 // underlying memio implementation, to the Core. Returns true if the Core
603 // was successfully registered with the socket.
604 bool Init(PRFileDesc* socket, memio_Private* buffers);
606 // Called on the network task runner.
608 // Attempts to perform an SSL handshake. If the handshake cannot be
609 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
610 // the network task runner once the handshake has completed. Otherwise,
611 // returns OK on success or a network error code on failure.
612 int Connect(const CompletionCallback& callback);
614 // Called on the network task runner.
615 // Signals that the resources owned by the network task runner are going
616 // away. No further callbacks will be invoked on the network task runner.
617 // May be called at any time.
618 void Detach();
620 // Called on the network task runner.
621 // Returns the current state of the underlying SSL socket. May be called at
622 // any time.
623 const HandshakeState& state() const { return network_handshake_state_; }
625 // Called on the network task runner.
626 // Read() and Write() mirror the net::Socket functions of the same name.
627 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
628 // task runner at a later point, unless the caller calls Detach().
629 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
630 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
632 // Called on the network task runner.
633 bool IsConnected() const;
634 bool HasPendingAsyncOperation() const;
635 bool HasUnhandledReceivedData() const;
636 bool WasEverUsed() const;
638 // Called on the network task runner.
639 // Causes the associated SSL/TLS session ID to be added to NSS's session
640 // cache, but only if the connection has not been False Started.
642 // This should only be called after the server's certificate has been
643 // verified, and may not be called within an NSS callback.
644 void CacheSessionIfNecessary();
646 private:
647 friend class base::RefCountedThreadSafe<Core>;
648 ~Core();
650 enum State {
651 STATE_NONE,
652 STATE_HANDSHAKE,
653 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
656 bool OnNSSTaskRunner() const;
657 bool OnNetworkTaskRunner() const;
659 ////////////////////////////////////////////////////////////////////////////
660 // Methods that are ONLY called on the NSS task runner:
661 ////////////////////////////////////////////////////////////////////////////
663 // Called by NSS during full handshakes to allow the application to
664 // verify the certificate. Instead of verifying the certificate in the midst
665 // of the handshake, SECSuccess is always returned and the peer's certificate
666 // is verified afterwards.
667 // This behaviour is an artifact of the original SSLClientSocketWin
668 // implementation, which could not verify the peer's certificate until after
669 // the handshake had completed, as well as bugs in NSS that prevent
670 // SSL_RestartHandshakeAfterCertReq from working.
671 static SECStatus OwnAuthCertHandler(void* arg,
672 PRFileDesc* socket,
673 PRBool checksig,
674 PRBool is_server);
676 // Callbacks called by NSS when the peer requests client certificate
677 // authentication.
678 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
679 // the arguments.
680 #if defined(NSS_PLATFORM_CLIENT_AUTH)
681 // When NSS has been integrated with awareness of the underlying system
682 // cryptographic libraries, this callback allows the caller to supply a
683 // native platform certificate and key for use by NSS. At most, one of
684 // either (result_certs, result_private_key) or (result_nss_certificate,
685 // result_nss_private_key) should be set.
686 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
687 static SECStatus PlatformClientAuthHandler(
688 void* arg,
689 PRFileDesc* socket,
690 CERTDistNames* ca_names,
691 CERTCertList** result_certs,
692 void** result_private_key,
693 CERTCertificate** result_nss_certificate,
694 SECKEYPrivateKey** result_nss_private_key);
695 #else
696 static SECStatus ClientAuthHandler(void* arg,
697 PRFileDesc* socket,
698 CERTDistNames* ca_names,
699 CERTCertificate** result_certificate,
700 SECKEYPrivateKey** result_private_key);
701 #endif
703 // Called by NSS to determine if we can False Start.
704 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
705 static SECStatus CanFalseStartCallback(PRFileDesc* socket,
706 void* arg,
707 PRBool* can_false_start);
709 // Called by NSS once the handshake has completed.
710 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
711 static void HandshakeCallback(PRFileDesc* socket, void* arg);
713 // Called once the handshake has succeeded.
714 void HandshakeSucceeded();
716 // Handles an NSS error generated while handshaking or performing IO.
717 // Returns a network error code mapped from the original NSS error.
718 int HandleNSSError(PRErrorCode error);
720 int DoHandshakeLoop(int last_io_result);
721 int DoReadLoop(int result);
722 int DoWriteLoop(int result);
724 int DoHandshake();
725 int DoGetDBCertComplete(int result);
727 int DoPayloadRead();
728 int DoPayloadWrite();
730 bool DoTransportIO();
731 int BufferRecv();
732 int BufferSend();
734 void OnRecvComplete(int result);
735 void OnSendComplete(int result);
737 void DoConnectCallback(int result);
738 void DoReadCallback(int result);
739 void DoWriteCallback(int result);
741 // Client channel ID handler.
742 static SECStatus ClientChannelIDHandler(
743 void* arg,
744 PRFileDesc* socket,
745 SECKEYPublicKey **out_public_key,
746 SECKEYPrivateKey **out_private_key);
748 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
749 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
750 // and an error code otherwise.
751 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
752 // set by a call to ChannelIDService->GetChannelID. The caller
753 // takes ownership of the |*cert| and |*key|.
754 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
756 // Updates the NSS and platform specific certificates.
757 void UpdateServerCert();
758 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
759 // received in the handshake via a TLS extension.
760 void UpdateSignedCertTimestamps();
761 // Update the OCSP response cache with the stapled response received in the
762 // handshake, and update nss_handshake_state_ with
763 // the SignedCertificateTimestampList received in the stapled OCSP response.
764 void UpdateStapledOCSPResponse();
765 // Updates the nss_handshake_state_ with the negotiated security parameters.
766 void UpdateConnectionStatus();
767 // Record histograms for channel id support during full handshakes - resumed
768 // handshakes are ignored.
769 void RecordChannelIDSupportOnNSSTaskRunner();
770 // UpdateNextProto gets any application-layer protocol that may have been
771 // negotiated by the TLS connection.
772 void UpdateNextProto();
773 // Record TLS extension used for protocol negotiation (NPN or ALPN).
774 void UpdateExtensionUsed();
776 ////////////////////////////////////////////////////////////////////////////
777 // Methods that are ONLY called on the network task runner:
778 ////////////////////////////////////////////////////////////////////////////
779 int DoBufferRecv(IOBuffer* buffer, int len);
780 int DoBufferSend(IOBuffer* buffer, int len);
781 int DoGetChannelID(const std::string& host);
783 void OnGetChannelIDComplete(int result);
784 void OnHandshakeStateUpdated(const HandshakeState& state);
785 void OnNSSBufferUpdated(int amount_in_read_buffer);
786 void DidNSSRead(int result);
787 void DidNSSWrite(int result);
788 void RecordChannelIDSupportOnNetworkTaskRunner(
789 bool negotiated_channel_id,
790 bool channel_id_enabled,
791 bool supports_ecc) const;
793 ////////////////////////////////////////////////////////////////////////////
794 // Methods that are called on both the network task runner and the NSS
795 // task runner.
796 ////////////////////////////////////////////////////////////////////////////
797 void OnHandshakeIOComplete(int result);
798 void BufferRecvComplete(IOBuffer* buffer, int result);
799 void BufferSendComplete(int result);
801 // PostOrRunCallback is a helper function to ensure that |callback| is
802 // invoked on the network task runner, but only if Detach() has not yet
803 // been called.
804 void PostOrRunCallback(const tracked_objects::Location& location,
805 const base::Closure& callback);
807 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
808 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
809 void AddCertProvidedEvent(int cert_count);
811 // Sets the handshake state |channel_id_sent| flag and logs the
812 // SSL_CHANNEL_ID_PROVIDED event.
813 void SetChannelIDProvided();
815 ////////////////////////////////////////////////////////////////////////////
816 // Members that are ONLY accessed on the network task runner:
817 ////////////////////////////////////////////////////////////////////////////
819 // True if the owning SSLClientSocketNSS has called Detach(). No further
820 // callbacks will be invoked nor access to members owned by the network
821 // task runner.
822 bool detached_;
824 // The underlying transport to use for network IO.
825 ClientSocketHandle* transport_;
826 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
828 // The current handshake state. Mirrors |nss_handshake_state_|.
829 HandshakeState network_handshake_state_;
831 // The service for retrieving Channel ID keys. May be NULL.
832 ChannelIDService* channel_id_service_;
833 ChannelIDService::RequestHandle domain_bound_cert_request_handle_;
835 // The information about NSS task runner.
836 int unhandled_buffer_size_;
837 bool nss_waiting_read_;
838 bool nss_waiting_write_;
839 bool nss_is_closed_;
841 // Set when Read() or Write() successfully reads or writes data to or from the
842 // network.
843 bool was_ever_used_;
845 ////////////////////////////////////////////////////////////////////////////
846 // Members that are ONLY accessed on the NSS task runner:
847 ////////////////////////////////////////////////////////////////////////////
848 HostPortPair host_and_port_;
849 SSLConfig ssl_config_;
851 // NSS SSL socket.
852 PRFileDesc* nss_fd_;
854 // Buffers for the network end of the SSL state machine
855 memio_Private* nss_bufs_;
857 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
858 // as much data as possible, without blocking.
859 // If DoPayloadRead() encounters an error after having read some data, stores
860 // the results to return on the *next* call to DoPayloadRead(). A value of
861 // kNoPendingReadResult indicates there is no pending result, otherwise 0
862 // indicates EOF and < 0 indicates an error.
863 int pending_read_result_;
864 // Contains the previously observed NSS error. Only valid when
865 // pending_read_result_ != kNoPendingReadResult.
866 PRErrorCode pending_read_nss_error_;
868 // The certificate chain, in DER form, that is expected to be received from
869 // the server.
870 std::vector<std::string> predicted_certs_;
872 State next_handshake_state_;
874 // True if channel ID extension was negotiated.
875 bool channel_id_xtn_negotiated_;
876 // True if the handshake state machine was interrupted for channel ID.
877 bool channel_id_needed_;
878 // True if the handshake state machine was interrupted for client auth.
879 bool client_auth_cert_needed_;
880 // True if NSS has False Started.
881 bool false_started_;
882 // True if NSS has called HandshakeCallback.
883 bool handshake_callback_called_;
885 HandshakeState nss_handshake_state_;
887 bool transport_recv_busy_;
888 bool transport_recv_eof_;
889 bool transport_send_busy_;
891 // Used by Read function.
892 scoped_refptr<IOBuffer> user_read_buf_;
893 int user_read_buf_len_;
895 // Used by Write function.
896 scoped_refptr<IOBuffer> user_write_buf_;
897 int user_write_buf_len_;
899 CompletionCallback user_connect_callback_;
900 CompletionCallback user_read_callback_;
901 CompletionCallback user_write_callback_;
903 ////////////////////////////////////////////////////////////////////////////
904 // Members that are accessed on both the network task runner and the NSS
905 // task runner.
906 ////////////////////////////////////////////////////////////////////////////
907 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
908 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
910 // Dereferenced only on the network task runner, but bound to tasks destined
911 // for the network task runner from the NSS task runner.
912 base::WeakPtr<BoundNetLog> weak_net_log_;
914 // Written on the network task runner by the |channel_id_service_|,
915 // prior to invoking OnHandshakeIOComplete.
916 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
917 // on the NSS task runner.
918 std::string domain_bound_private_key_;
919 std::string domain_bound_cert_;
921 DISALLOW_COPY_AND_ASSIGN(Core);
924 SSLClientSocketNSS::Core::Core(
925 base::SequencedTaskRunner* network_task_runner,
926 base::SequencedTaskRunner* nss_task_runner,
927 ClientSocketHandle* transport,
928 const HostPortPair& host_and_port,
929 const SSLConfig& ssl_config,
930 BoundNetLog* net_log,
931 ChannelIDService* channel_id_service)
932 : detached_(false),
933 transport_(transport),
934 weak_net_log_factory_(net_log),
935 channel_id_service_(channel_id_service),
936 unhandled_buffer_size_(0),
937 nss_waiting_read_(false),
938 nss_waiting_write_(false),
939 nss_is_closed_(false),
940 was_ever_used_(false),
941 host_and_port_(host_and_port),
942 ssl_config_(ssl_config),
943 nss_fd_(NULL),
944 nss_bufs_(NULL),
945 pending_read_result_(kNoPendingReadResult),
946 pending_read_nss_error_(0),
947 next_handshake_state_(STATE_NONE),
948 channel_id_xtn_negotiated_(false),
949 channel_id_needed_(false),
950 client_auth_cert_needed_(false),
951 false_started_(false),
952 handshake_callback_called_(false),
953 transport_recv_busy_(false),
954 transport_recv_eof_(false),
955 transport_send_busy_(false),
956 user_read_buf_len_(0),
957 user_write_buf_len_(0),
958 network_task_runner_(network_task_runner),
959 nss_task_runner_(nss_task_runner),
960 weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
963 SSLClientSocketNSS::Core::~Core() {
964 // TODO(wtc): Send SSL close_notify alert.
965 if (nss_fd_ != NULL) {
966 PR_Close(nss_fd_);
967 nss_fd_ = NULL;
969 nss_bufs_ = NULL;
972 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
973 memio_Private* buffers) {
974 DCHECK(OnNetworkTaskRunner());
975 DCHECK(!nss_fd_);
976 DCHECK(!nss_bufs_);
978 nss_fd_ = socket;
979 nss_bufs_ = buffers;
981 SECStatus rv = SECSuccess;
983 if (!ssl_config_.next_protos.empty()) {
984 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
985 const bool adequate_encryption =
986 PK11_TokenExists(CKM_AES_GCM) ||
987 PK11_TokenExists(CKM_NSS_CHACHA20_POLY1305);
988 const bool adequate_key_agreement = PK11_TokenExists(CKM_DH_PKCS_DERIVE) ||
989 PK11_TokenExists(CKM_ECDH1_DERIVE);
990 std::vector<uint8_t> wire_protos =
991 SerializeNextProtos(ssl_config_.next_protos,
992 adequate_encryption && adequate_key_agreement &&
993 IsTLSVersionAdequateForHTTP2(ssl_config_));
994 rv = SSL_SetNextProtoNego(
995 nss_fd_, wire_protos.empty() ? NULL : &wire_protos[0],
996 wire_protos.size());
997 if (rv != SECSuccess)
998 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoNego", "");
999 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_ALPN, PR_TRUE);
1000 if (rv != SECSuccess)
1001 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_ALPN");
1002 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_NPN, PR_TRUE);
1003 if (rv != SECSuccess)
1004 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_NPN");
1007 rv = SSL_AuthCertificateHook(
1008 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
1009 if (rv != SECSuccess) {
1010 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
1011 return false;
1014 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1015 rv = SSL_GetPlatformClientAuthDataHook(
1016 nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler,
1017 this);
1018 #else
1019 rv = SSL_GetClientAuthDataHook(
1020 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
1021 #endif
1022 if (rv != SECSuccess) {
1023 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
1024 return false;
1027 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
1028 rv = SSL_SetClientChannelIDCallback(
1029 nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
1030 if (rv != SECSuccess) {
1031 LogFailedNSSFunction(
1032 *weak_net_log_, "SSL_SetClientChannelIDCallback", "");
1036 rv = SSL_SetCanFalseStartCallback(
1037 nss_fd_, SSLClientSocketNSS::Core::CanFalseStartCallback, this);
1038 if (rv != SECSuccess) {
1039 LogFailedNSSFunction(*weak_net_log_, "SSL_SetCanFalseStartCallback", "");
1040 return false;
1043 rv = SSL_HandshakeCallback(
1044 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
1045 if (rv != SECSuccess) {
1046 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
1047 return false;
1050 return true;
1053 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
1054 if (!OnNSSTaskRunner()) {
1055 DCHECK(!detached_);
1056 bool posted = nss_task_runner_->PostTask(
1057 FROM_HERE,
1058 base::Bind(IgnoreResult(&Core::Connect), this, callback));
1059 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1062 DCHECK(OnNSSTaskRunner());
1063 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1064 DCHECK(user_read_callback_.is_null());
1065 DCHECK(user_write_callback_.is_null());
1066 DCHECK(user_connect_callback_.is_null());
1067 DCHECK(!user_read_buf_.get());
1068 DCHECK(!user_write_buf_.get());
1070 next_handshake_state_ = STATE_HANDSHAKE;
1071 int rv = DoHandshakeLoop(OK);
1072 if (rv == ERR_IO_PENDING) {
1073 user_connect_callback_ = callback;
1074 } else if (rv > OK) {
1075 rv = OK;
1077 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
1078 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1079 return ERR_IO_PENDING;
1082 return rv;
1085 void SSLClientSocketNSS::Core::Detach() {
1086 DCHECK(OnNetworkTaskRunner());
1088 detached_ = true;
1089 transport_ = NULL;
1090 weak_net_log_factory_.InvalidateWeakPtrs();
1092 network_handshake_state_.Reset();
1094 domain_bound_cert_request_handle_.Cancel();
1097 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
1098 const CompletionCallback& callback) {
1099 if (!OnNSSTaskRunner()) {
1100 DCHECK(OnNetworkTaskRunner());
1101 DCHECK(!detached_);
1102 DCHECK(transport_);
1103 DCHECK(!nss_waiting_read_);
1105 nss_waiting_read_ = true;
1106 bool posted = nss_task_runner_->PostTask(
1107 FROM_HERE,
1108 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
1109 buf_len, callback));
1110 if (!posted) {
1111 nss_is_closed_ = true;
1112 nss_waiting_read_ = false;
1114 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1117 DCHECK(OnNSSTaskRunner());
1118 DCHECK(false_started_ || handshake_callback_called_);
1119 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1120 DCHECK(user_read_callback_.is_null());
1121 DCHECK(user_connect_callback_.is_null());
1122 DCHECK(!user_read_buf_.get());
1123 DCHECK(nss_bufs_);
1125 user_read_buf_ = buf;
1126 user_read_buf_len_ = buf_len;
1128 int rv = DoReadLoop(OK);
1129 if (rv == ERR_IO_PENDING) {
1130 if (OnNetworkTaskRunner())
1131 nss_waiting_read_ = true;
1132 user_read_callback_ = callback;
1133 } else {
1134 user_read_buf_ = NULL;
1135 user_read_buf_len_ = 0;
1137 if (!OnNetworkTaskRunner()) {
1138 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
1139 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1140 return ERR_IO_PENDING;
1141 } else {
1142 DCHECK(!nss_waiting_read_);
1143 if (rv <= 0) {
1144 nss_is_closed_ = true;
1145 } else {
1146 was_ever_used_ = true;
1151 return rv;
1154 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1155 const CompletionCallback& callback) {
1156 if (!OnNSSTaskRunner()) {
1157 DCHECK(OnNetworkTaskRunner());
1158 DCHECK(!detached_);
1159 DCHECK(transport_);
1160 DCHECK(!nss_waiting_write_);
1162 nss_waiting_write_ = true;
1163 bool posted = nss_task_runner_->PostTask(
1164 FROM_HERE,
1165 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
1166 buf_len, callback));
1167 if (!posted) {
1168 nss_is_closed_ = true;
1169 nss_waiting_write_ = false;
1171 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1174 DCHECK(OnNSSTaskRunner());
1175 DCHECK(false_started_ || handshake_callback_called_);
1176 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1177 DCHECK(user_write_callback_.is_null());
1178 DCHECK(user_connect_callback_.is_null());
1179 DCHECK(!user_write_buf_.get());
1180 DCHECK(nss_bufs_);
1182 user_write_buf_ = buf;
1183 user_write_buf_len_ = buf_len;
1185 int rv = DoWriteLoop(OK);
1186 if (rv == ERR_IO_PENDING) {
1187 if (OnNetworkTaskRunner())
1188 nss_waiting_write_ = true;
1189 user_write_callback_ = callback;
1190 } else {
1191 user_write_buf_ = NULL;
1192 user_write_buf_len_ = 0;
1194 if (!OnNetworkTaskRunner()) {
1195 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
1196 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1197 return ERR_IO_PENDING;
1198 } else {
1199 DCHECK(!nss_waiting_write_);
1200 if (rv < 0) {
1201 nss_is_closed_ = true;
1202 } else if (rv > 0) {
1203 was_ever_used_ = true;
1208 return rv;
1211 bool SSLClientSocketNSS::Core::IsConnected() const {
1212 DCHECK(OnNetworkTaskRunner());
1213 return !nss_is_closed_;
1216 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1217 DCHECK(OnNetworkTaskRunner());
1218 return nss_waiting_read_ || nss_waiting_write_;
1221 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1222 DCHECK(OnNetworkTaskRunner());
1223 return unhandled_buffer_size_ != 0;
1226 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1227 DCHECK(OnNetworkTaskRunner());
1228 return was_ever_used_;
1231 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1232 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1233 // nss_fd_. However, it happens on the network task runner in order to match
1234 // the buggy behavior of ExportKeyingMaterial.
1236 // Once http://crbug.com/330360 is fixed, this should be moved to an
1237 // implementation that exclusively does this work on the NSS TaskRunner. This
1238 // is "safe" because it is only called during the certificate verification
1239 // state machine of the main socket, which is safe because no underlying
1240 // transport IO will be occuring in that state, and NSS will not be blocking
1241 // on any PKCS#11 related locks that might block the Network TaskRunner.
1242 DCHECK(OnNetworkTaskRunner());
1244 // Only cache the session if the connection was not False Started, because
1245 // sessions should only be cached *after* the peer's Finished message is
1246 // processed.
1247 // In the case of False Start, the session will be cached once the
1248 // HandshakeCallback is called, which signals the receipt and processing of
1249 // the Finished message, and which will happen during a call to
1250 // PR_Read/PR_Write.
1251 if (!false_started_)
1252 SSL_CacheSession(nss_fd_);
1255 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1256 return nss_task_runner_->RunsTasksOnCurrentThread();
1259 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1260 return network_task_runner_->RunsTasksOnCurrentThread();
1263 // static
1264 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1265 void* arg,
1266 PRFileDesc* socket,
1267 PRBool checksig,
1268 PRBool is_server) {
1269 Core* core = reinterpret_cast<Core*>(arg);
1270 if (core->handshake_callback_called_) {
1271 // Disallow the server certificate to change in a renegotiation.
1272 CERTCertificate* old_cert = core->nss_handshake_state_.server_cert_chain[0];
1273 ScopedCERTCertificate new_cert(SSL_PeerCertificate(socket));
1274 if (new_cert->derCert.len != old_cert->derCert.len ||
1275 memcmp(new_cert->derCert.data, old_cert->derCert.data,
1276 new_cert->derCert.len) != 0) {
1277 // NSS doesn't have an error code that indicates the server certificate
1278 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1279 // for this purpose.
1280 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE);
1281 return SECFailure;
1285 // Tell NSS to not verify the certificate.
1286 return SECSuccess;
1289 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1290 // static
1291 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1292 void* arg,
1293 PRFileDesc* socket,
1294 CERTDistNames* ca_names,
1295 CERTCertList** result_certs,
1296 void** result_private_key,
1297 CERTCertificate** result_nss_certificate,
1298 SECKEYPrivateKey** result_nss_private_key) {
1299 Core* core = reinterpret_cast<Core*>(arg);
1300 DCHECK(core->OnNSSTaskRunner());
1302 core->PostOrRunCallback(
1303 FROM_HERE,
1304 base::Bind(&AddLogEvent, core->weak_net_log_,
1305 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1307 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1308 #if defined(OS_WIN)
1309 if (core->ssl_config_.send_client_cert) {
1310 if (core->ssl_config_.client_cert.get()) {
1311 PCCERT_CONTEXT cert_context =
1312 core->ssl_config_.client_cert->os_cert_handle();
1314 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
1315 DWORD key_spec = 0;
1316 BOOL must_free = FALSE;
1317 DWORD flags = 0;
1318 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
1319 flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
1321 BOOL acquired_key = CryptAcquireCertificatePrivateKey(
1322 cert_context, flags, NULL, &crypt_prov, &key_spec, &must_free);
1324 if (acquired_key) {
1325 // Should never get a cached handle back - ownership must always be
1326 // transferred.
1327 CHECK_EQ(must_free, TRUE);
1329 SECItem der_cert;
1330 der_cert.type = siDERCertBuffer;
1331 der_cert.data = cert_context->pbCertEncoded;
1332 der_cert.len = cert_context->cbCertEncoded;
1334 // TODO(rsleevi): Error checking for NSS allocation errors.
1335 CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB();
1336 CERTCertificate* user_cert = CERT_NewTempCertificate(
1337 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1338 if (!user_cert) {
1339 // Importing the certificate can fail for reasons including a serial
1340 // number collision. See crbug.com/97355.
1341 core->AddCertProvidedEvent(0);
1342 return SECFailure;
1344 CERTCertList* cert_chain = CERT_NewCertList();
1345 CERT_AddCertToListTail(cert_chain, user_cert);
1347 // Add the intermediates.
1348 X509Certificate::OSCertHandles intermediates =
1349 core->ssl_config_.client_cert->GetIntermediateCertificates();
1350 for (X509Certificate::OSCertHandles::const_iterator it =
1351 intermediates.begin(); it != intermediates.end(); ++it) {
1352 der_cert.data = (*it)->pbCertEncoded;
1353 der_cert.len = (*it)->cbCertEncoded;
1355 CERTCertificate* intermediate = CERT_NewTempCertificate(
1356 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1357 if (!intermediate) {
1358 CERT_DestroyCertList(cert_chain);
1359 core->AddCertProvidedEvent(0);
1360 return SECFailure;
1362 CERT_AddCertToListTail(cert_chain, intermediate);
1364 PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>(
1365 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT)));
1366 key_context->cbSize = sizeof(*key_context);
1367 // NSS will free this context when no longer in use.
1368 key_context->hCryptProv = crypt_prov;
1369 key_context->dwKeySpec = key_spec;
1370 *result_private_key = key_context;
1371 *result_certs = cert_chain;
1373 int cert_count = 1 + intermediates.size();
1374 core->AddCertProvidedEvent(cert_count);
1375 return SECSuccess;
1377 LOG(WARNING) << "Client cert found without private key";
1380 // Send no client certificate.
1381 core->AddCertProvidedEvent(0);
1382 return SECFailure;
1385 core->nss_handshake_state_.cert_authorities.clear();
1387 std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
1388 for (int i = 0; i < ca_names->nnames; ++i) {
1389 issuer_list[i].cbData = ca_names->names[i].len;
1390 issuer_list[i].pbData = ca_names->names[i].data;
1391 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1392 reinterpret_cast<const char*>(ca_names->names[i].data),
1393 static_cast<size_t>(ca_names->names[i].len)));
1396 // Update the network task runner's view of the handshake state now that
1397 // server certificate request has been recorded.
1398 core->PostOrRunCallback(
1399 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1400 core->nss_handshake_state_));
1402 // Tell NSS to suspend the client authentication. We will then abort the
1403 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1404 return SECWouldBlock;
1405 #elif defined(OS_MACOSX)
1406 if (core->ssl_config_.send_client_cert) {
1407 if (core->ssl_config_.client_cert.get()) {
1408 OSStatus os_error = noErr;
1409 SecIdentityRef identity = NULL;
1410 SecKeyRef private_key = NULL;
1411 X509Certificate::OSCertHandles chain;
1413 base::AutoLock lock(crypto::GetMacSecurityServicesLock());
1414 os_error = SecIdentityCreateWithCertificate(
1415 NULL, core->ssl_config_.client_cert->os_cert_handle(), &identity);
1417 if (os_error == noErr) {
1418 os_error = SecIdentityCopyPrivateKey(identity, &private_key);
1419 CFRelease(identity);
1422 if (os_error == noErr) {
1423 // TODO(rsleevi): Error checking for NSS allocation errors.
1424 *result_certs = CERT_NewCertList();
1425 *result_private_key = private_key;
1427 chain.push_back(core->ssl_config_.client_cert->os_cert_handle());
1428 const X509Certificate::OSCertHandles& intermediates =
1429 core->ssl_config_.client_cert->GetIntermediateCertificates();
1430 if (!intermediates.empty())
1431 chain.insert(chain.end(), intermediates.begin(), intermediates.end());
1433 for (size_t i = 0, chain_count = chain.size(); i < chain_count; ++i) {
1434 CSSM_DATA cert_data;
1435 SecCertificateRef cert_ref = chain[i];
1436 os_error = SecCertificateGetData(cert_ref, &cert_data);
1437 if (os_error != noErr)
1438 break;
1440 SECItem der_cert;
1441 der_cert.type = siDERCertBuffer;
1442 der_cert.data = cert_data.Data;
1443 der_cert.len = cert_data.Length;
1444 CERTCertificate* nss_cert = CERT_NewTempCertificate(
1445 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
1446 if (!nss_cert) {
1447 // In the event of an NSS error, make up an OS error and reuse
1448 // the error handling below.
1449 os_error = errSecCreateChainFailed;
1450 break;
1452 CERT_AddCertToListTail(*result_certs, nss_cert);
1456 if (os_error == noErr) {
1457 core->AddCertProvidedEvent(chain.size());
1458 return SECSuccess;
1461 OSSTATUS_LOG(WARNING, os_error)
1462 << "Client cert found, but could not be used";
1463 if (*result_certs) {
1464 CERT_DestroyCertList(*result_certs);
1465 *result_certs = NULL;
1467 if (*result_private_key)
1468 *result_private_key = NULL;
1469 if (private_key)
1470 CFRelease(private_key);
1473 // Send no client certificate.
1474 core->AddCertProvidedEvent(0);
1475 return SECFailure;
1478 core->nss_handshake_state_.cert_authorities.clear();
1480 // Retrieve the cert issuers accepted by the server.
1481 std::vector<CertPrincipal> valid_issuers;
1482 int n = ca_names->nnames;
1483 for (int i = 0; i < n; i++) {
1484 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1485 reinterpret_cast<const char*>(ca_names->names[i].data),
1486 static_cast<size_t>(ca_names->names[i].len)));
1489 // Update the network task runner's view of the handshake state now that
1490 // server certificate request has been recorded.
1491 core->PostOrRunCallback(
1492 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1493 core->nss_handshake_state_));
1495 // Tell NSS to suspend the client authentication. We will then abort the
1496 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1497 return SECWouldBlock;
1498 #else
1499 return SECFailure;
1500 #endif
1503 #elif defined(OS_IOS)
1505 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1506 void* arg,
1507 PRFileDesc* socket,
1508 CERTDistNames* ca_names,
1509 CERTCertificate** result_certificate,
1510 SECKEYPrivateKey** result_private_key) {
1511 Core* core = reinterpret_cast<Core*>(arg);
1512 DCHECK(core->OnNSSTaskRunner());
1514 core->PostOrRunCallback(
1515 FROM_HERE,
1516 base::Bind(&AddLogEvent, core->weak_net_log_,
1517 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1519 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1520 LOG(WARNING) << "Client auth is not supported";
1522 // Never send a certificate.
1523 core->AddCertProvidedEvent(0);
1524 return SECFailure;
1527 #else // NSS_PLATFORM_CLIENT_AUTH
1529 // static
1530 // Based on Mozilla's NSS_GetClientAuthData.
1531 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1532 void* arg,
1533 PRFileDesc* socket,
1534 CERTDistNames* ca_names,
1535 CERTCertificate** result_certificate,
1536 SECKEYPrivateKey** result_private_key) {
1537 Core* core = reinterpret_cast<Core*>(arg);
1538 DCHECK(core->OnNSSTaskRunner());
1540 core->PostOrRunCallback(
1541 FROM_HERE,
1542 base::Bind(&AddLogEvent, core->weak_net_log_,
1543 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1545 // Regular client certificate requested.
1546 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1547 void* wincx = SSL_RevealPinArg(socket);
1549 if (core->ssl_config_.send_client_cert) {
1550 // Second pass: a client certificate should have been selected.
1551 if (core->ssl_config_.client_cert.get()) {
1552 CERTCertificate* cert =
1553 CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
1554 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1555 if (privkey) {
1556 // TODO(jsorianopastor): We should wait for server certificate
1557 // verification before sending our credentials. See
1558 // http://crbug.com/13934.
1559 *result_certificate = cert;
1560 *result_private_key = privkey;
1561 // A cert_count of -1 means the number of certificates is unknown.
1562 // NSS will construct the certificate chain.
1563 core->AddCertProvidedEvent(-1);
1565 return SECSuccess;
1567 LOG(WARNING) << "Client cert found without private key";
1569 // Send no client certificate.
1570 core->AddCertProvidedEvent(0);
1571 return SECFailure;
1574 // First pass: client certificate is needed.
1575 core->nss_handshake_state_.cert_authorities.clear();
1577 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1578 // the server and save them in |cert_authorities|.
1579 for (int i = 0; i < ca_names->nnames; i++) {
1580 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1581 reinterpret_cast<const char*>(ca_names->names[i].data),
1582 static_cast<size_t>(ca_names->names[i].len)));
1585 // Update the network task runner's view of the handshake state now that
1586 // server certificate request has been recorded.
1587 core->PostOrRunCallback(
1588 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1589 core->nss_handshake_state_));
1591 // Tell NSS to suspend the client authentication. We will then abort the
1592 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1593 return SECWouldBlock;
1595 #endif // NSS_PLATFORM_CLIENT_AUTH
1597 // static
1598 SECStatus SSLClientSocketNSS::Core::CanFalseStartCallback(
1599 PRFileDesc* socket,
1600 void* arg,
1601 PRBool* can_false_start) {
1602 // If the server doesn't support NPN or ALPN, then we don't do False
1603 // Start with it.
1604 PRBool negotiated_extension;
1605 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1606 ssl_app_layer_protocol_xtn,
1607 &negotiated_extension);
1608 if (rv != SECSuccess || !negotiated_extension) {
1609 rv = SSL_HandshakeNegotiatedExtension(socket,
1610 ssl_next_proto_nego_xtn,
1611 &negotiated_extension);
1613 if (rv != SECSuccess || !negotiated_extension) {
1614 *can_false_start = PR_FALSE;
1615 return SECSuccess;
1618 return SSL_RecommendedCanFalseStart(socket, can_false_start);
1621 // static
1622 void SSLClientSocketNSS::Core::HandshakeCallback(
1623 PRFileDesc* socket,
1624 void* arg) {
1625 Core* core = reinterpret_cast<Core*>(arg);
1626 DCHECK(core->OnNSSTaskRunner());
1628 core->handshake_callback_called_ = true;
1629 if (core->false_started_) {
1630 core->false_started_ = false;
1631 // If the connection was False Started, then at the time of this callback,
1632 // the peer's certificate will have been verified or the caller will have
1633 // accepted the error.
1634 // This is guaranteed when using False Start because this callback will
1635 // not be invoked until processing the peer's Finished message, which
1636 // will only happen in a PR_Read/PR_Write call, which can only happen
1637 // after the peer's certificate is verified.
1638 SSL_CacheSessionUnlocked(socket);
1640 // Additionally, when False Starting, DoHandshake() will have already
1641 // called HandshakeSucceeded(), so return now.
1642 return;
1644 core->HandshakeSucceeded();
1647 void SSLClientSocketNSS::Core::HandshakeSucceeded() {
1648 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1649 tracked_objects::ScopedTracker tracking_profile(
1650 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1651 "424386 SSLClientSocketNSS::Core::HandshakeSucceeded"));
1653 DCHECK(OnNSSTaskRunner());
1655 PRBool last_handshake_resumed;
1656 SECStatus rv = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed);
1657 if (rv == SECSuccess && last_handshake_resumed) {
1658 nss_handshake_state_.resumed_handshake = true;
1659 } else {
1660 nss_handshake_state_.resumed_handshake = false;
1663 RecordChannelIDSupportOnNSSTaskRunner();
1664 UpdateServerCert();
1665 UpdateSignedCertTimestamps();
1666 UpdateStapledOCSPResponse();
1667 UpdateConnectionStatus();
1668 UpdateNextProto();
1669 UpdateExtensionUsed();
1671 // Update the network task runners view of the handshake state whenever
1672 // a handshake has completed.
1673 PostOrRunCallback(
1674 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
1675 nss_handshake_state_));
1678 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error) {
1679 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1680 tracked_objects::ScopedTracker tracking_profile(
1681 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1682 "424386 SSLClientSocketNSS::Core::HandleNSSError"));
1684 DCHECK(OnNSSTaskRunner());
1686 int net_error = MapNSSClientError(nss_error);
1688 #if defined(OS_WIN)
1689 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1690 // os_cert_handle() as an optimization. However, if the certificate
1691 // private key is stored on a smart card, and the smart card is removed,
1692 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1693 // preventing client certificate authentication. Because the
1694 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1695 // caching in X509Certificate, this failure ends up preventing client
1696 // certificate authentication with the same certificate for all future
1697 // attempts, even after the smart card has been re-inserted. By setting
1698 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1699 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1700 // the certificate on the next attempt, which should succeed if the smart
1701 // card has been re-inserted, or will typically prompt the user to
1702 // re-insert the smart card if not.
1703 if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY ||
1704 net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) &&
1705 ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
1706 CertSetCertificateContextProperty(
1707 ssl_config_.client_cert->os_cert_handle(),
1708 CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL);
1710 #endif
1712 return net_error;
1715 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1716 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1717 tracked_objects::ScopedTracker tracking_profile(
1718 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1719 "424386 SSLClientSocketNSS::Core::DoHandshakeLoop"));
1721 DCHECK(OnNSSTaskRunner());
1723 int rv = last_io_result;
1724 do {
1725 // Default to STATE_NONE for next state.
1726 State state = next_handshake_state_;
1727 GotoState(STATE_NONE);
1729 switch (state) {
1730 case STATE_HANDSHAKE:
1731 rv = DoHandshake();
1732 break;
1733 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1734 rv = DoGetDBCertComplete(rv);
1735 break;
1736 case STATE_NONE:
1737 default:
1738 rv = ERR_UNEXPECTED;
1739 LOG(DFATAL) << "unexpected state " << state;
1740 break;
1743 // Do the actual network I/O
1744 bool network_moved = DoTransportIO();
1745 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1746 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1747 // special case we keep looping even if rv is ERR_IO_PENDING because
1748 // the transport IO may allow DoHandshake to make progress.
1749 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1750 rv = OK; // This causes us to stay in the loop.
1752 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1753 return rv;
1756 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1757 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1758 tracked_objects::ScopedTracker tracking_profile(
1759 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1760 "424386 SSLClientSocketNSS::Core::DoReadLoop"));
1762 DCHECK(OnNSSTaskRunner());
1763 DCHECK(false_started_ || handshake_callback_called_);
1764 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1766 if (result < 0)
1767 return result;
1769 if (!nss_bufs_) {
1770 LOG(DFATAL) << "!nss_bufs_";
1771 int rv = ERR_UNEXPECTED;
1772 PostOrRunCallback(
1773 FROM_HERE,
1774 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1775 NetLog::TYPE_SSL_READ_ERROR,
1776 CreateNetLogSSLErrorCallback(rv, 0)));
1777 return rv;
1780 bool network_moved;
1781 int rv;
1782 do {
1783 rv = DoPayloadRead();
1784 network_moved = DoTransportIO();
1785 } while (rv == ERR_IO_PENDING && network_moved);
1787 return rv;
1790 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1791 DCHECK(OnNSSTaskRunner());
1792 DCHECK(false_started_ || handshake_callback_called_);
1793 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1795 if (result < 0)
1796 return result;
1798 if (!nss_bufs_) {
1799 LOG(DFATAL) << "!nss_bufs_";
1800 int rv = ERR_UNEXPECTED;
1801 PostOrRunCallback(
1802 FROM_HERE,
1803 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1804 NetLog::TYPE_SSL_READ_ERROR,
1805 CreateNetLogSSLErrorCallback(rv, 0)));
1806 return rv;
1809 bool network_moved;
1810 int rv;
1811 do {
1812 rv = DoPayloadWrite();
1813 network_moved = DoTransportIO();
1814 } while (rv == ERR_IO_PENDING && network_moved);
1816 LeaveFunction(rv);
1817 return rv;
1820 int SSLClientSocketNSS::Core::DoHandshake() {
1821 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1822 tracked_objects::ScopedTracker tracking_profile(
1823 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1824 "424386 SSLClientSocketNSS::Core::DoHandshake"));
1826 DCHECK(OnNSSTaskRunner());
1828 int net_error = OK;
1829 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1831 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1832 tracked_objects::ScopedTracker tracking_profile1(
1833 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1834 "424386 SSLClientSocketNSS::Core::DoHandshake 1"));
1836 // Note: this function may be called multiple times during the handshake, so
1837 // even though channel id and client auth are separate else cases, they can
1838 // both be used during a single SSL handshake.
1839 if (channel_id_needed_) {
1840 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1841 net_error = ERR_IO_PENDING;
1842 } else if (client_auth_cert_needed_) {
1843 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1844 PostOrRunCallback(
1845 FROM_HERE,
1846 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1847 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1848 CreateNetLogSSLErrorCallback(net_error, 0)));
1850 // If the handshake already succeeded (because the server requests but
1851 // doesn't require a client cert), we need to invalidate the SSL session
1852 // so that we won't try to resume the non-client-authenticated session in
1853 // the next handshake. This will cause the server to ask for a client
1854 // cert again.
1855 if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess)
1856 LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError();
1857 } else if (rv == SECSuccess) {
1858 if (!handshake_callback_called_) {
1859 false_started_ = true;
1860 HandshakeSucceeded();
1862 } else {
1863 PRErrorCode prerr = PR_GetError();
1864 net_error = HandleNSSError(prerr);
1866 // If not done, stay in this state
1867 if (net_error == ERR_IO_PENDING) {
1868 GotoState(STATE_HANDSHAKE);
1869 } else {
1870 PostOrRunCallback(
1871 FROM_HERE,
1872 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1873 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1874 CreateNetLogSSLErrorCallback(net_error, prerr)));
1878 return net_error;
1881 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1882 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1883 tracked_objects::ScopedTracker tracking_profile(
1884 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1885 "424386 SSLClientSocketNSS::Core::DoGetDBCertComplete"));
1887 SECStatus rv;
1888 PostOrRunCallback(
1889 FROM_HERE,
1890 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1891 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1893 channel_id_needed_ = false;
1895 if (result != OK)
1896 return result;
1898 SECKEYPublicKey* public_key;
1899 SECKEYPrivateKey* private_key;
1900 int error = ImportChannelIDKeys(&public_key, &private_key);
1901 if (error != OK)
1902 return error;
1904 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
1905 if (rv != SECSuccess)
1906 return MapNSSError(PORT_GetError());
1908 SetChannelIDProvided();
1909 GotoState(STATE_HANDSHAKE);
1910 return OK;
1913 int SSLClientSocketNSS::Core::DoPayloadRead() {
1914 DCHECK(OnNSSTaskRunner());
1915 DCHECK(user_read_buf_.get());
1916 DCHECK_GT(user_read_buf_len_, 0);
1918 int rv;
1919 // If a previous greedy read resulted in an error that was not consumed (eg:
1920 // due to the caller having read some data successfully), then return that
1921 // pending error now.
1922 if (pending_read_result_ != kNoPendingReadResult) {
1923 rv = pending_read_result_;
1924 PRErrorCode prerr = pending_read_nss_error_;
1925 pending_read_result_ = kNoPendingReadResult;
1926 pending_read_nss_error_ = 0;
1928 if (rv == 0) {
1929 PostOrRunCallback(
1930 FROM_HERE,
1931 base::Bind(&LogByteTransferEvent, weak_net_log_,
1932 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1933 scoped_refptr<IOBuffer>(user_read_buf_)));
1934 } else {
1935 PostOrRunCallback(
1936 FROM_HERE,
1937 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1938 NetLog::TYPE_SSL_READ_ERROR,
1939 CreateNetLogSSLErrorCallback(rv, prerr)));
1941 return rv;
1944 // Perform a greedy read, attempting to read as much as the caller has
1945 // requested. In the current NSS implementation, PR_Read will return
1946 // exactly one SSL application data record's worth of data per invocation.
1947 // The record size is dictated by the server, and may be noticeably smaller
1948 // than the caller's buffer. This may be as little as a single byte, if the
1949 // server is performing 1/n-1 record splitting.
1951 // However, this greedy read may result in renegotiations/re-handshakes
1952 // happening or may lead to some data being read, followed by an EOF (such as
1953 // a TLS close-notify). If at least some data was read, then that result
1954 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1955 // data was read, it's safe to return the error or EOF immediately.
1956 int total_bytes_read = 0;
1957 do {
1958 rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
1959 user_read_buf_len_ - total_bytes_read);
1960 if (rv > 0)
1961 total_bytes_read += rv;
1962 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1963 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1964 PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
1965 amount_in_read_buffer));
1967 if (total_bytes_read == user_read_buf_len_) {
1968 // The caller's entire request was satisfied without error. No further
1969 // processing needed.
1970 rv = total_bytes_read;
1971 } else {
1972 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1973 // immediately, while the NSPR/NSS errors are still available in
1974 // thread-local storage. However, the handled/remapped error code should
1975 // only be returned if no application data was already read; if it was, the
1976 // error code should be deferred until the next call of DoPayloadRead.
1978 // If no data was read, |*next_result| will point to the return value of
1979 // this function. If at least some data was read, |*next_result| will point
1980 // to |pending_read_error_|, to be returned in a future call to
1981 // DoPayloadRead() (e.g.: after the current data is handled).
1982 int* next_result = &rv;
1983 if (total_bytes_read > 0) {
1984 pending_read_result_ = rv;
1985 rv = total_bytes_read;
1986 next_result = &pending_read_result_;
1989 if (client_auth_cert_needed_) {
1990 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1991 pending_read_nss_error_ = 0;
1992 } else if (*next_result < 0) {
1993 // If *next_result == 0, then that indicates EOF, and no special error
1994 // handling is needed.
1995 pending_read_nss_error_ = PR_GetError();
1996 *next_result = HandleNSSError(pending_read_nss_error_);
1997 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1998 // If at least some data was read from PR_Read(), do not treat
1999 // insufficient data as an error to return in the next call to
2000 // DoPayloadRead() - instead, let the call fall through to check
2001 // PR_Read() again. This is because DoTransportIO() may complete
2002 // in between the next call to DoPayloadRead(), and thus it is
2003 // important to check PR_Read() on subsequent invocations to see
2004 // if a complete record may now be read.
2005 pending_read_nss_error_ = 0;
2006 pending_read_result_ = kNoPendingReadResult;
2011 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
2013 if (rv >= 0) {
2014 PostOrRunCallback(
2015 FROM_HERE,
2016 base::Bind(&LogByteTransferEvent, weak_net_log_,
2017 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
2018 scoped_refptr<IOBuffer>(user_read_buf_)));
2019 } else if (rv != ERR_IO_PENDING) {
2020 PostOrRunCallback(
2021 FROM_HERE,
2022 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2023 NetLog::TYPE_SSL_READ_ERROR,
2024 CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
2025 pending_read_nss_error_ = 0;
2027 return rv;
2030 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2031 DCHECK(OnNSSTaskRunner());
2033 DCHECK(user_write_buf_.get());
2035 int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2036 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
2037 int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2038 // PR_Write could potentially consume the unhandled data in the memio read
2039 // buffer if a renegotiation is in progress. If the buffer is consumed,
2040 // notify the latest buffer size to NetworkRunner.
2041 if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
2042 PostOrRunCallback(
2043 FROM_HERE,
2044 base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
2046 if (rv >= 0) {
2047 PostOrRunCallback(
2048 FROM_HERE,
2049 base::Bind(&LogByteTransferEvent, weak_net_log_,
2050 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
2051 scoped_refptr<IOBuffer>(user_write_buf_)));
2052 return rv;
2054 PRErrorCode prerr = PR_GetError();
2055 if (prerr == PR_WOULD_BLOCK_ERROR)
2056 return ERR_IO_PENDING;
2058 rv = HandleNSSError(prerr);
2059 PostOrRunCallback(
2060 FROM_HERE,
2061 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2062 NetLog::TYPE_SSL_WRITE_ERROR,
2063 CreateNetLogSSLErrorCallback(rv, prerr)));
2064 return rv;
2067 // Do as much network I/O as possible between the buffer and the
2068 // transport socket. Return true if some I/O performed, false
2069 // otherwise (error or ERR_IO_PENDING).
2070 bool SSLClientSocketNSS::Core::DoTransportIO() {
2071 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2072 tracked_objects::ScopedTracker tracking_profile(
2073 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2074 "424386 SSLClientSocketNSS::Core::DoTransportIO"));
2076 DCHECK(OnNSSTaskRunner());
2078 bool network_moved = false;
2079 if (nss_bufs_ != NULL) {
2080 int rv;
2081 // Read and write as much data as we can. The loop is neccessary
2082 // because Write() may return synchronously.
2083 do {
2084 rv = BufferSend();
2085 if (rv != ERR_IO_PENDING && rv != 0)
2086 network_moved = true;
2087 } while (rv > 0);
2088 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
2089 network_moved = true;
2091 return network_moved;
2094 int SSLClientSocketNSS::Core::BufferRecv() {
2095 DCHECK(OnNSSTaskRunner());
2097 if (transport_recv_busy_)
2098 return ERR_IO_PENDING;
2100 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2101 // determine how much data NSS wants to read. If NSS was not blocked,
2102 // this will return 0.
2103 int requested = memio_GetReadRequest(nss_bufs_);
2104 if (requested == 0) {
2105 // This is not a perfect match of error codes, as no operation is
2106 // actually pending. However, returning 0 would be interpreted as a
2107 // possible sign of EOF, which is also an inappropriate match.
2108 return ERR_IO_PENDING;
2111 char* buf;
2112 int nb = memio_GetReadParams(nss_bufs_, &buf);
2113 int rv;
2114 if (!nb) {
2115 // buffer too full to read into, so no I/O possible at moment
2116 rv = ERR_IO_PENDING;
2117 } else {
2118 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
2119 if (OnNetworkTaskRunner()) {
2120 rv = DoBufferRecv(read_buffer.get(), nb);
2121 } else {
2122 bool posted = network_task_runner_->PostTask(
2123 FROM_HERE,
2124 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
2125 nb));
2126 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2129 if (rv == ERR_IO_PENDING) {
2130 transport_recv_busy_ = true;
2131 } else {
2132 if (rv > 0) {
2133 memcpy(buf, read_buffer->data(), rv);
2134 } else if (rv == 0) {
2135 transport_recv_eof_ = true;
2137 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
2140 return rv;
2143 // Return 0 if nss_bufs_ was empty,
2144 // > 0 for bytes transferred immediately,
2145 // < 0 for error (or the non-error ERR_IO_PENDING).
2146 int SSLClientSocketNSS::Core::BufferSend() {
2147 DCHECK(OnNSSTaskRunner());
2149 if (transport_send_busy_)
2150 return ERR_IO_PENDING;
2152 const char* buf1;
2153 const char* buf2;
2154 unsigned int len1, len2;
2155 if (memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2)) {
2156 // It is important this return synchronously to prevent spinning infinitely
2157 // in the off-thread NSS case. The error code itself is ignored, so just
2158 // return ERR_ABORTED. See https://crbug.com/381160.
2159 return ERR_ABORTED;
2161 const unsigned int len = len1 + len2;
2163 int rv = 0;
2164 if (len) {
2165 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
2166 memcpy(send_buffer->data(), buf1, len1);
2167 memcpy(send_buffer->data() + len1, buf2, len2);
2169 if (OnNetworkTaskRunner()) {
2170 rv = DoBufferSend(send_buffer.get(), len);
2171 } else {
2172 bool posted = network_task_runner_->PostTask(
2173 FROM_HERE,
2174 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
2175 len));
2176 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2179 if (rv == ERR_IO_PENDING) {
2180 transport_send_busy_ = true;
2181 } else {
2182 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
2186 return rv;
2189 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
2190 DCHECK(OnNSSTaskRunner());
2192 if (next_handshake_state_ == STATE_HANDSHAKE) {
2193 OnHandshakeIOComplete(result);
2194 return;
2197 // Network layer received some data, check if client requested to read
2198 // decrypted data.
2199 if (!user_read_buf_.get())
2200 return;
2202 int rv = DoReadLoop(result);
2203 if (rv != ERR_IO_PENDING)
2204 DoReadCallback(rv);
2207 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
2208 DCHECK(OnNSSTaskRunner());
2210 if (next_handshake_state_ == STATE_HANDSHAKE) {
2211 OnHandshakeIOComplete(result);
2212 return;
2215 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2216 // handshake is in progress.
2217 int rv_read = ERR_IO_PENDING;
2218 int rv_write = ERR_IO_PENDING;
2219 bool network_moved;
2220 do {
2221 if (user_read_buf_.get())
2222 rv_read = DoPayloadRead();
2223 if (user_write_buf_.get())
2224 rv_write = DoPayloadWrite();
2225 network_moved = DoTransportIO();
2226 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
2227 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
2229 // If the parent SSLClientSocketNSS is deleted during the processing of the
2230 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2231 // will be detached (and possibly deleted). Guard against deletion by taking
2232 // an extra reference, then check if the Core was detached before invoking the
2233 // next callback.
2234 scoped_refptr<Core> guard(this);
2235 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
2236 DoReadCallback(rv_read);
2238 if (OnNetworkTaskRunner() && detached_)
2239 return;
2241 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
2242 DoWriteCallback(rv_write);
2245 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2246 // handshake. This requires network IO, which in turn calls
2247 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2248 // winds its way through the state machine and ends up being passed to the
2249 // callback. For Read() and Write(), that's what we want. But for Connect(),
2250 // the caller expects OK (i.e. 0) for success.
2251 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
2252 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2253 tracked_objects::ScopedTracker tracking_profile(
2254 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2255 "424386 SSLClientSocketNSS::Core::DoConnectCallback"));
2257 DCHECK(OnNSSTaskRunner());
2258 DCHECK_NE(rv, ERR_IO_PENDING);
2259 DCHECK(!user_connect_callback_.is_null());
2261 base::Closure c = base::Bind(
2262 base::ResetAndReturn(&user_connect_callback_),
2263 rv > OK ? OK : rv);
2264 PostOrRunCallback(FROM_HERE, c);
2267 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
2268 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2269 tracked_objects::ScopedTracker tracking_profile(
2270 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2271 "424386 SSLClientSocketNSS::Core::DoReadCallback"));
2273 DCHECK(OnNSSTaskRunner());
2274 DCHECK_NE(ERR_IO_PENDING, rv);
2275 DCHECK(!user_read_callback_.is_null());
2277 user_read_buf_ = NULL;
2278 user_read_buf_len_ = 0;
2279 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2280 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2281 // the network task runner.
2282 PostOrRunCallback(
2283 FROM_HERE,
2284 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2285 PostOrRunCallback(
2286 FROM_HERE,
2287 base::Bind(&Core::DidNSSRead, this, rv));
2288 // TODO(vadimt): Remove ScopedTracker below once crbug.com/418183 is fixed.
2289 tracked_objects::ScopedTracker tracking_profile1(
2290 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2291 "SSLClientSocketNSS::Core::DoReadCallback"));
2292 PostOrRunCallback(
2293 FROM_HERE,
2294 base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
2297 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
2298 DCHECK(OnNSSTaskRunner());
2299 DCHECK_NE(ERR_IO_PENDING, rv);
2300 DCHECK(!user_write_callback_.is_null());
2302 // Since Run may result in Write being called, clear |user_write_callback_|
2303 // up front.
2304 user_write_buf_ = NULL;
2305 user_write_buf_len_ = 0;
2306 // Update buffer status because DoWriteLoop called DoTransportIO which may
2307 // perform read operations.
2308 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2309 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2310 // the network task runner.
2311 PostOrRunCallback(
2312 FROM_HERE,
2313 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2314 PostOrRunCallback(
2315 FROM_HERE,
2316 base::Bind(&Core::DidNSSWrite, this, rv));
2317 PostOrRunCallback(
2318 FROM_HERE,
2319 base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
2322 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
2323 void* arg,
2324 PRFileDesc* socket,
2325 SECKEYPublicKey **out_public_key,
2326 SECKEYPrivateKey **out_private_key) {
2327 Core* core = reinterpret_cast<Core*>(arg);
2328 DCHECK(core->OnNSSTaskRunner());
2330 core->PostOrRunCallback(
2331 FROM_HERE,
2332 base::Bind(&AddLogEvent, core->weak_net_log_,
2333 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
2335 // We have negotiated the TLS channel ID extension.
2336 core->channel_id_xtn_negotiated_ = true;
2337 std::string host = core->host_and_port_.host();
2338 int error = ERR_UNEXPECTED;
2339 if (core->OnNetworkTaskRunner()) {
2340 error = core->DoGetChannelID(host);
2341 } else {
2342 bool posted = core->network_task_runner_->PostTask(
2343 FROM_HERE,
2344 base::Bind(
2345 IgnoreResult(&Core::DoGetChannelID),
2346 core, host));
2347 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
2350 if (error == ERR_IO_PENDING) {
2351 // Asynchronous case.
2352 core->channel_id_needed_ = true;
2353 return SECWouldBlock;
2356 core->PostOrRunCallback(
2357 FROM_HERE,
2358 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
2359 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
2360 SECStatus rv = SECSuccess;
2361 if (error == OK) {
2362 // Synchronous success.
2363 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
2364 if (result == OK)
2365 core->SetChannelIDProvided();
2366 else
2367 rv = SECFailure;
2368 } else {
2369 rv = SECFailure;
2372 return rv;
2375 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
2376 SECKEYPrivateKey** key) {
2377 // Set the certificate.
2378 SECItem cert_item;
2379 cert_item.data = (unsigned char*) domain_bound_cert_.data();
2380 cert_item.len = domain_bound_cert_.size();
2381 ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2382 &cert_item,
2383 NULL,
2384 PR_FALSE,
2385 PR_TRUE));
2386 if (cert == NULL)
2387 return MapNSSError(PORT_GetError());
2389 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
2390 // Set the private key.
2391 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2392 slot.get(),
2393 ChannelIDService::kEPKIPassword,
2394 reinterpret_cast<const unsigned char*>(
2395 domain_bound_private_key_.data()),
2396 domain_bound_private_key_.size(),
2397 &cert->subjectPublicKeyInfo,
2398 false,
2399 false,
2400 key,
2401 public_key)) {
2402 int error = MapNSSError(PORT_GetError());
2403 return error;
2406 return OK;
2409 void SSLClientSocketNSS::Core::UpdateServerCert() {
2410 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
2411 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
2412 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
2413 if (nss_handshake_state_.server_cert.get()) {
2414 // Since this will be called asynchronously on another thread, it needs to
2415 // own a reference to the certificate.
2416 NetLog::ParametersCallback net_log_callback =
2417 base::Bind(&NetLogX509CertificateCallback,
2418 nss_handshake_state_.server_cert);
2419 PostOrRunCallback(
2420 FROM_HERE,
2421 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2422 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
2423 net_log_callback));
2427 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
2428 const SECItem* signed_cert_timestamps =
2429 SSL_PeerSignedCertTimestamps(nss_fd_);
2431 if (!signed_cert_timestamps || !signed_cert_timestamps->len)
2432 return;
2434 nss_handshake_state_.sct_list_from_tls_extension = std::string(
2435 reinterpret_cast<char*>(signed_cert_timestamps->data),
2436 signed_cert_timestamps->len);
2439 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2440 PRBool ocsp_requested = PR_FALSE;
2441 SSL_OptionGet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, &ocsp_requested);
2442 const SECItemArray* ocsp_responses =
2443 SSL_PeerStapledOCSPResponses(nss_fd_);
2444 bool ocsp_responses_present = ocsp_responses && ocsp_responses->len;
2445 if (ocsp_requested)
2446 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present);
2447 if (!ocsp_responses_present)
2448 return;
2450 nss_handshake_state_.stapled_ocsp_response = std::string(
2451 reinterpret_cast<char*>(ocsp_responses->items[0].data),
2452 ocsp_responses->items[0].len);
2454 if (IsOCSPStaplingSupported()) {
2455 #if defined(OS_WIN)
2456 if (nss_handshake_state_.server_cert.get()) {
2457 CRYPT_DATA_BLOB ocsp_response_blob;
2458 ocsp_response_blob.cbData = ocsp_responses->items[0].len;
2459 ocsp_response_blob.pbData = ocsp_responses->items[0].data;
2460 BOOL ok = CertSetCertificateContextProperty(
2461 nss_handshake_state_.server_cert->os_cert_handle(),
2462 CERT_OCSP_RESPONSE_PROP_ID,
2463 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
2464 &ocsp_response_blob);
2465 if (!ok) {
2466 VLOG(1) << "Failed to set OCSP response property: "
2467 << GetLastError();
2470 #elif defined(USE_NSS)
2471 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response =
2472 GetCacheOCSPResponseFromSideChannelFunction();
2474 cache_ocsp_response(
2475 CERT_GetDefaultCertDB(),
2476 nss_handshake_state_.server_cert_chain[0], PR_Now(),
2477 &ocsp_responses->items[0], NULL);
2478 #endif
2479 } // IsOCSPStaplingSupported()
2482 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2483 // Note: This function may be called multiple times for a single connection
2484 // if renegotiations occur.
2485 nss_handshake_state_.ssl_connection_status = 0;
2487 SSLChannelInfo channel_info;
2488 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2489 &channel_info, sizeof(channel_info));
2490 if (ok == SECSuccess &&
2491 channel_info.length == sizeof(channel_info) &&
2492 channel_info.cipherSuite) {
2493 nss_handshake_state_.ssl_connection_status |= channel_info.cipherSuite;
2495 nss_handshake_state_.ssl_connection_status |=
2496 (static_cast<int>(channel_info.compressionMethod) &
2497 SSL_CONNECTION_COMPRESSION_MASK) <<
2498 SSL_CONNECTION_COMPRESSION_SHIFT;
2500 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2501 if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) {
2502 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2503 // version 2.
2504 version = SSL_CONNECTION_VERSION_SSL2;
2505 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2506 version = SSL_CONNECTION_VERSION_SSL3;
2507 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_0) {
2508 version = SSL_CONNECTION_VERSION_TLS1;
2509 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
2510 version = SSL_CONNECTION_VERSION_TLS1_1;
2511 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_2) {
2512 version = SSL_CONNECTION_VERSION_TLS1_2;
2514 nss_handshake_state_.ssl_connection_status |=
2515 (version & SSL_CONNECTION_VERSION_MASK) <<
2516 SSL_CONNECTION_VERSION_SHIFT;
2519 PRBool peer_supports_renego_ext;
2520 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2521 &peer_supports_renego_ext);
2522 if (ok == SECSuccess) {
2523 if (!peer_supports_renego_ext) {
2524 nss_handshake_state_.ssl_connection_status |=
2525 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2526 // Log an informational message if the server does not support secure
2527 // renegotiation (RFC 5746).
2528 VLOG(1) << "The server " << host_and_port_.ToString()
2529 << " does not support the TLS renegotiation_info extension.";
2533 if (ssl_config_.version_fallback) {
2534 nss_handshake_state_.ssl_connection_status |=
2535 SSL_CONNECTION_VERSION_FALLBACK;
2539 void SSLClientSocketNSS::Core::UpdateNextProto() {
2540 uint8 buf[256];
2541 SSLNextProtoState state;
2542 unsigned buf_len;
2544 SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
2545 if (rv != SECSuccess)
2546 return;
2548 nss_handshake_state_.next_proto =
2549 std::string(reinterpret_cast<char*>(buf), buf_len);
2550 switch (state) {
2551 case SSL_NEXT_PROTO_NEGOTIATED:
2552 case SSL_NEXT_PROTO_SELECTED:
2553 nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
2554 break;
2555 case SSL_NEXT_PROTO_NO_OVERLAP:
2556 nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
2557 break;
2558 case SSL_NEXT_PROTO_NO_SUPPORT:
2559 nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
2560 break;
2561 default:
2562 NOTREACHED();
2563 break;
2567 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2568 PRBool negotiated_extension;
2569 SECStatus rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2570 ssl_app_layer_protocol_xtn,
2571 &negotiated_extension);
2572 if (rv == SECSuccess && negotiated_extension) {
2573 nss_handshake_state_.negotiation_extension_ = kExtensionALPN;
2574 } else {
2575 rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2576 ssl_next_proto_nego_xtn,
2577 &negotiated_extension);
2578 if (rv == SECSuccess && negotiated_extension) {
2579 nss_handshake_state_.negotiation_extension_ = kExtensionNPN;
2584 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2585 DCHECK(OnNSSTaskRunner());
2586 if (nss_handshake_state_.resumed_handshake)
2587 return;
2589 // Copy the NSS task runner-only state to the network task runner and
2590 // log histograms from there, since the histograms also need access to the
2591 // network task runner state.
2592 PostOrRunCallback(
2593 FROM_HERE,
2594 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
2595 this,
2596 channel_id_xtn_negotiated_,
2597 ssl_config_.channel_id_enabled,
2598 crypto::ECPrivateKey::IsSupported()));
2601 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2602 bool negotiated_channel_id,
2603 bool channel_id_enabled,
2604 bool supports_ecc) const {
2605 DCHECK(OnNetworkTaskRunner());
2607 RecordChannelIDSupport(channel_id_service_,
2608 negotiated_channel_id,
2609 channel_id_enabled,
2610 supports_ecc);
2613 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2614 DCHECK(OnNetworkTaskRunner());
2615 DCHECK_GT(len, 0);
2617 if (detached_)
2618 return ERR_ABORTED;
2620 int rv = transport_->socket()->Read(
2621 read_buffer, len,
2622 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2623 scoped_refptr<IOBuffer>(read_buffer)));
2625 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2626 nss_task_runner_->PostTask(
2627 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2628 scoped_refptr<IOBuffer>(read_buffer), rv));
2629 return rv;
2632 return rv;
2635 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2636 DCHECK(OnNetworkTaskRunner());
2637 DCHECK_GT(len, 0);
2639 if (detached_)
2640 return ERR_ABORTED;
2642 int rv = transport_->socket()->Write(
2643 send_buffer, len,
2644 base::Bind(&Core::BufferSendComplete,
2645 base::Unretained(this)));
2647 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2648 nss_task_runner_->PostTask(
2649 FROM_HERE,
2650 base::Bind(&Core::BufferSendComplete, this, rv));
2651 return rv;
2654 return rv;
2657 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string& host) {
2658 DCHECK(OnNetworkTaskRunner());
2660 if (detached_)
2661 return ERR_ABORTED;
2663 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2665 int rv = channel_id_service_->GetOrCreateChannelID(
2666 host,
2667 &domain_bound_private_key_,
2668 &domain_bound_cert_,
2669 base::Bind(&Core::OnGetChannelIDComplete, base::Unretained(this)),
2670 &domain_bound_cert_request_handle_);
2672 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2673 nss_task_runner_->PostTask(
2674 FROM_HERE,
2675 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2676 return ERR_IO_PENDING;
2679 return rv;
2682 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2683 const HandshakeState& state) {
2684 DCHECK(OnNetworkTaskRunner());
2685 network_handshake_state_ = state;
2688 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
2689 DCHECK(OnNetworkTaskRunner());
2690 unhandled_buffer_size_ = amount_in_read_buffer;
2693 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
2694 DCHECK(OnNetworkTaskRunner());
2695 DCHECK(nss_waiting_read_);
2696 nss_waiting_read_ = false;
2697 if (result <= 0) {
2698 nss_is_closed_ = true;
2699 } else {
2700 was_ever_used_ = true;
2704 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
2705 DCHECK(OnNetworkTaskRunner());
2706 DCHECK(nss_waiting_write_);
2707 nss_waiting_write_ = false;
2708 if (result < 0) {
2709 nss_is_closed_ = true;
2710 } else if (result > 0) {
2711 was_ever_used_ = true;
2715 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2716 // TODO(vadimt): Remove ScopedTracker below once crbug.com/418183 is fixed.
2717 tracked_objects::ScopedTracker tracking_profile(
2718 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2719 "418183 DidCompleteReadWrite => Core::BufferSendComplete"));
2721 if (!OnNSSTaskRunner()) {
2722 if (detached_)
2723 return;
2725 nss_task_runner_->PostTask(
2726 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2727 return;
2730 DCHECK(OnNSSTaskRunner());
2732 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2733 transport_send_busy_ = false;
2734 OnSendComplete(result);
2737 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2738 if (!OnNSSTaskRunner()) {
2739 if (detached_)
2740 return;
2742 nss_task_runner_->PostTask(
2743 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2744 return;
2747 DCHECK(OnNSSTaskRunner());
2749 int rv = DoHandshakeLoop(result);
2750 if (rv != ERR_IO_PENDING)
2751 DoConnectCallback(rv);
2754 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result) {
2755 DVLOG(1) << __FUNCTION__ << " " << result;
2756 DCHECK(OnNetworkTaskRunner());
2758 OnHandshakeIOComplete(result);
2761 void SSLClientSocketNSS::Core::BufferRecvComplete(
2762 IOBuffer* read_buffer,
2763 int result) {
2764 // TODO(vadimt): Remove ScopedTracker below once crbug.com/418183 is fixed.
2765 tracked_objects::ScopedTracker tracking_profile(
2766 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2767 "418183 DidCompleteReadWrite => SSLClientSocketNSS::Core::..."));
2769 DCHECK(read_buffer);
2771 if (!OnNSSTaskRunner()) {
2772 if (detached_)
2773 return;
2775 nss_task_runner_->PostTask(
2776 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2777 scoped_refptr<IOBuffer>(read_buffer), result));
2778 return;
2781 DCHECK(OnNSSTaskRunner());
2783 if (result > 0) {
2784 char* buf;
2785 int nb = memio_GetReadParams(nss_bufs_, &buf);
2786 CHECK_GE(nb, result);
2787 memcpy(buf, read_buffer->data(), result);
2788 } else if (result == 0) {
2789 transport_recv_eof_ = true;
2792 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2793 transport_recv_busy_ = false;
2794 OnRecvComplete(result);
2797 void SSLClientSocketNSS::Core::PostOrRunCallback(
2798 const tracked_objects::Location& location,
2799 const base::Closure& task) {
2800 if (!OnNetworkTaskRunner()) {
2801 network_task_runner_->PostTask(
2802 FROM_HERE,
2803 base::Bind(&Core::PostOrRunCallback, this, location, task));
2804 return;
2807 if (detached_ || task.is_null())
2808 return;
2809 task.Run();
2812 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2813 PostOrRunCallback(
2814 FROM_HERE,
2815 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2816 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2817 NetLog::IntegerCallback("cert_count", cert_count)));
2820 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2821 PostOrRunCallback(
2822 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2823 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2824 nss_handshake_state_.channel_id_sent = true;
2825 // Update the network task runner's view of the handshake state now that
2826 // channel id has been sent.
2827 PostOrRunCallback(
2828 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2829 nss_handshake_state_));
2832 SSLClientSocketNSS::SSLClientSocketNSS(
2833 base::SequencedTaskRunner* nss_task_runner,
2834 scoped_ptr<ClientSocketHandle> transport_socket,
2835 const HostPortPair& host_and_port,
2836 const SSLConfig& ssl_config,
2837 const SSLClientSocketContext& context)
2838 : nss_task_runner_(nss_task_runner),
2839 transport_(transport_socket.Pass()),
2840 host_and_port_(host_and_port),
2841 ssl_config_(ssl_config),
2842 cert_verifier_(context.cert_verifier),
2843 cert_transparency_verifier_(context.cert_transparency_verifier),
2844 channel_id_service_(context.channel_id_service),
2845 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2846 completed_handshake_(false),
2847 next_handshake_state_(STATE_NONE),
2848 nss_fd_(NULL),
2849 net_log_(transport_->socket()->NetLog()),
2850 transport_security_state_(context.transport_security_state),
2851 policy_enforcer_(context.cert_policy_enforcer),
2852 valid_thread_id_(base::kInvalidThreadId) {
2853 EnterFunction("");
2854 InitCore();
2855 LeaveFunction("");
2858 SSLClientSocketNSS::~SSLClientSocketNSS() {
2859 EnterFunction("");
2860 Disconnect();
2861 LeaveFunction("");
2864 // static
2865 void SSLClientSocket::ClearSessionCache() {
2866 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2867 // bother initializing NSS just to clear an empty SSL session cache.
2868 if (!NSS_IsInitialized())
2869 return;
2871 SSL_ClearSessionCache();
2874 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
2875 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
2876 #endif
2878 // static
2879 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
2880 if (PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)) {
2881 return SSL_PROTOCOL_VERSION_TLS1_2;
2882 } else {
2883 return SSL_PROTOCOL_VERSION_TLS1_1;
2887 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2888 EnterFunction("");
2889 ssl_info->Reset();
2890 if (core_->state().server_cert_chain.empty() ||
2891 !core_->state().server_cert_chain[0]) {
2892 return false;
2895 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2896 ssl_info->cert = server_cert_verify_result_.verified_cert;
2898 AddSCTInfoToSSLInfo(ssl_info);
2900 ssl_info->connection_status =
2901 core_->state().ssl_connection_status;
2902 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2903 ssl_info->is_issued_by_known_root =
2904 server_cert_verify_result_.is_issued_by_known_root;
2905 ssl_info->client_cert_sent =
2906 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
2907 ssl_info->channel_id_sent = WasChannelIDSent();
2908 ssl_info->pinning_failure_log = pinning_failure_log_;
2910 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2911 core_->state().ssl_connection_status);
2912 SSLCipherSuiteInfo cipher_info;
2913 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2914 &cipher_info, sizeof(cipher_info));
2915 if (ok == SECSuccess) {
2916 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2917 } else {
2918 ssl_info->security_bits = -1;
2919 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2920 << " for cipherSuite " << cipher_suite;
2923 ssl_info->handshake_type = core_->state().resumed_handshake ?
2924 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2926 LeaveFunction("");
2927 return true;
2930 std::string SSLClientSocketNSS::GetSessionCacheKey() const {
2931 NOTIMPLEMENTED();
2932 return std::string();
2935 bool SSLClientSocketNSS::InSessionCache() const {
2936 // For now, always return true so that SSLConnectJobs are never held back.
2937 return true;
2940 void SSLClientSocketNSS::SetHandshakeCompletionCallback(
2941 const base::Closure& callback) {
2942 NOTIMPLEMENTED();
2945 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2946 SSLCertRequestInfo* cert_request_info) {
2947 EnterFunction("");
2948 cert_request_info->host_and_port = host_and_port_;
2949 cert_request_info->cert_authorities = core_->state().cert_authorities;
2950 LeaveFunction("");
2953 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2954 bool has_context,
2955 const base::StringPiece& context,
2956 unsigned char* out,
2957 unsigned int outlen) {
2958 if (!IsConnected())
2959 return ERR_SOCKET_NOT_CONNECTED;
2961 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2962 // the midst of a handshake.
2963 SECStatus result = SSL_ExportKeyingMaterial(
2964 nss_fd_, label.data(), label.size(), has_context,
2965 reinterpret_cast<const unsigned char*>(context.data()),
2966 context.length(), out, outlen);
2967 if (result != SECSuccess) {
2968 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2969 return MapNSSError(PORT_GetError());
2971 return OK;
2974 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
2975 if (!IsConnected())
2976 return ERR_SOCKET_NOT_CONNECTED;
2977 unsigned char buf[64];
2978 unsigned int len;
2979 SECStatus result = SSL_GetChannelBinding(nss_fd_,
2980 SSL_CHANNEL_BINDING_TLS_UNIQUE,
2981 buf, &len, arraysize(buf));
2982 if (result != SECSuccess) {
2983 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
2984 return MapNSSError(PORT_GetError());
2986 out->assign(reinterpret_cast<char*>(buf), len);
2987 return OK;
2990 SSLClientSocket::NextProtoStatus
2991 SSLClientSocketNSS::GetNextProto(std::string* proto) {
2992 *proto = core_->state().next_proto;
2993 return core_->state().next_proto_status;
2996 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2997 EnterFunction("");
2998 DCHECK(transport_.get());
2999 // It is an error to create an SSLClientSocket whose context has no
3000 // TransportSecurityState.
3001 DCHECK(transport_security_state_);
3002 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3003 DCHECK(user_connect_callback_.is_null());
3004 DCHECK(!callback.is_null());
3006 EnsureThreadIdAssigned();
3008 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
3010 int rv = Init();
3011 if (rv != OK) {
3012 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3013 return rv;
3016 rv = InitializeSSLOptions();
3017 if (rv != OK) {
3018 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3019 return rv;
3022 rv = InitializeSSLPeerName();
3023 if (rv != OK) {
3024 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3025 return rv;
3028 GotoState(STATE_HANDSHAKE);
3030 rv = DoHandshakeLoop(OK);
3031 if (rv == ERR_IO_PENDING) {
3032 user_connect_callback_ = callback;
3033 } else {
3034 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3037 LeaveFunction("");
3038 return rv > OK ? OK : rv;
3041 void SSLClientSocketNSS::Disconnect() {
3042 EnterFunction("");
3044 CHECK(CalledOnValidThread());
3046 // Shut down anything that may call us back.
3047 core_->Detach();
3048 verifier_.reset();
3049 transport_->socket()->Disconnect();
3051 // Reset object state.
3052 user_connect_callback_.Reset();
3053 server_cert_verify_result_.Reset();
3054 completed_handshake_ = false;
3055 start_cert_verification_time_ = base::TimeTicks();
3056 InitCore();
3058 LeaveFunction("");
3061 bool SSLClientSocketNSS::IsConnected() const {
3062 EnterFunction("");
3063 bool ret = completed_handshake_ &&
3064 (core_->HasPendingAsyncOperation() ||
3065 (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
3066 transport_->socket()->IsConnected());
3067 LeaveFunction("");
3068 return ret;
3071 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
3072 EnterFunction("");
3073 bool ret = completed_handshake_ &&
3074 !core_->HasPendingAsyncOperation() &&
3075 !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
3076 transport_->socket()->IsConnectedAndIdle();
3077 LeaveFunction("");
3078 return ret;
3081 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
3082 return transport_->socket()->GetPeerAddress(address);
3085 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
3086 return transport_->socket()->GetLocalAddress(address);
3089 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
3090 return net_log_;
3093 void SSLClientSocketNSS::SetSubresourceSpeculation() {
3094 if (transport_.get() && transport_->socket()) {
3095 transport_->socket()->SetSubresourceSpeculation();
3096 } else {
3097 NOTREACHED();
3101 void SSLClientSocketNSS::SetOmniboxSpeculation() {
3102 if (transport_.get() && transport_->socket()) {
3103 transport_->socket()->SetOmniboxSpeculation();
3104 } else {
3105 NOTREACHED();
3109 bool SSLClientSocketNSS::WasEverUsed() const {
3110 DCHECK(core_.get());
3112 return core_->WasEverUsed();
3115 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
3116 if (transport_.get() && transport_->socket()) {
3117 return transport_->socket()->UsingTCPFastOpen();
3119 NOTREACHED();
3120 return false;
3123 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
3124 const CompletionCallback& callback) {
3125 DCHECK(core_.get());
3126 DCHECK(!callback.is_null());
3128 EnterFunction(buf_len);
3129 int rv = core_->Read(buf, buf_len, callback);
3130 LeaveFunction(rv);
3132 return rv;
3135 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
3136 const CompletionCallback& callback) {
3137 DCHECK(core_.get());
3138 DCHECK(!callback.is_null());
3140 EnterFunction(buf_len);
3141 int rv = core_->Write(buf, buf_len, callback);
3142 LeaveFunction(rv);
3144 return rv;
3147 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
3148 return transport_->socket()->SetReceiveBufferSize(size);
3151 int SSLClientSocketNSS::SetSendBufferSize(int32 size) {
3152 return transport_->socket()->SetSendBufferSize(size);
3155 int SSLClientSocketNSS::Init() {
3156 EnterFunction("");
3157 // Initialize the NSS SSL library in a threadsafe way. This also
3158 // initializes the NSS base library.
3159 EnsureNSSSSLInit();
3160 if (!NSS_IsInitialized())
3161 return ERR_UNEXPECTED;
3162 #if defined(USE_NSS) || defined(OS_IOS)
3163 if (ssl_config_.cert_io_enabled) {
3164 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3165 // loop by MessageLoopForIO::current().
3166 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3167 EnsureNSSHttpIOInit();
3169 #endif
3171 LeaveFunction("");
3172 return OK;
3175 void SSLClientSocketNSS::InitCore() {
3176 core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
3177 nss_task_runner_.get(),
3178 transport_.get(),
3179 host_and_port_,
3180 ssl_config_,
3181 &net_log_,
3182 channel_id_service_);
3185 int SSLClientSocketNSS::InitializeSSLOptions() {
3186 // Transport connected, now hook it up to nss
3187 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
3188 if (nss_fd_ == NULL) {
3189 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
3192 // Grab pointer to buffers
3193 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
3195 /* Create SSL state machine */
3196 /* Push SSL onto our fake I/O socket */
3197 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_) == NULL) {
3198 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
3199 PR_Close(nss_fd_);
3200 nss_fd_ = NULL;
3201 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
3203 // TODO(port): set more ssl options! Check errors!
3205 int rv;
3207 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
3208 if (rv != SECSuccess) {
3209 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
3210 return ERR_UNEXPECTED;
3213 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
3214 if (rv != SECSuccess) {
3215 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3216 return ERR_UNEXPECTED;
3219 // Don't do V2 compatible hellos because they don't support TLS extensions.
3220 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
3221 if (rv != SECSuccess) {
3222 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3223 return ERR_UNEXPECTED;
3226 SSLVersionRange version_range;
3227 version_range.min = ssl_config_.version_min;
3228 version_range.max = ssl_config_.version_max;
3229 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
3230 if (rv != SECSuccess) {
3231 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
3232 return ERR_NO_SSL_VERSIONS_ENABLED;
3235 if (ssl_config_.version_fallback) {
3236 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALLBACK_SCSV, PR_TRUE);
3237 if (rv != SECSuccess) {
3238 LogFailedNSSFunction(
3239 net_log_, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
3243 for (std::vector<uint16>::const_iterator it =
3244 ssl_config_.disabled_cipher_suites.begin();
3245 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
3246 // This will fail if the specified cipher is not implemented by NSS, but
3247 // the failure is harmless.
3248 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
3251 // Support RFC 5077
3252 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
3253 if (rv != SECSuccess) {
3254 LogFailedNSSFunction(
3255 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3258 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
3259 ssl_config_.false_start_enabled);
3260 if (rv != SECSuccess)
3261 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3263 // We allow servers to request renegotiation. Since we're a client,
3264 // prohibiting this is rather a waste of time. Only servers are in a
3265 // position to prevent renegotiation attacks.
3266 // http://extendedsubset.com/?p=8
3268 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
3269 SSL_RENEGOTIATE_TRANSITIONAL);
3270 if (rv != SECSuccess) {
3271 LogFailedNSSFunction(
3272 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3275 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
3276 if (rv != SECSuccess)
3277 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3279 // Added in NSS 3.15
3280 #ifdef SSL_ENABLE_OCSP_STAPLING
3281 // Request OCSP stapling even on platforms that don't support it, in
3282 // order to extract Certificate Transparency information.
3283 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING,
3284 (IsOCSPStaplingSupported() ||
3285 ssl_config_.signed_cert_timestamps_enabled));
3286 if (rv != SECSuccess) {
3287 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3288 "SSL_ENABLE_OCSP_STAPLING");
3290 #endif
3292 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
3293 ssl_config_.signed_cert_timestamps_enabled);
3294 if (rv != SECSuccess) {
3295 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3296 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
3299 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
3300 if (rv != SECSuccess) {
3301 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3302 return ERR_UNEXPECTED;
3305 if (!core_->Init(nss_fd_, nss_bufs))
3306 return ERR_UNEXPECTED;
3308 // Tell SSL the hostname we're trying to connect to.
3309 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
3311 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3312 SSL_ResetHandshake(nss_fd_, PR_FALSE);
3314 return OK;
3317 int SSLClientSocketNSS::InitializeSSLPeerName() {
3318 // Tell NSS who we're connected to
3319 IPEndPoint peer_address;
3320 int err = transport_->socket()->GetPeerAddress(&peer_address);
3321 if (err != OK)
3322 return err;
3324 SockaddrStorage storage;
3325 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
3326 return ERR_ADDRESS_INVALID;
3328 PRNetAddr peername;
3329 memset(&peername, 0, sizeof(peername));
3330 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
3331 size_t len = std::min(static_cast<size_t>(storage.addr_len),
3332 sizeof(peername));
3333 memcpy(&peername, storage.addr, len);
3335 // Adjust the address family field for BSD, whose sockaddr
3336 // structure has a one-byte length and one-byte address family
3337 // field at the beginning. PRNetAddr has a two-byte address
3338 // family field at the beginning.
3339 peername.raw.family = storage.addr->sa_family;
3341 memio_SetPeerName(nss_fd_, &peername);
3343 // Set the peer ID for session reuse. This is necessary when we create an
3344 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3345 // rather than the destination server's address in that case.
3346 std::string peer_id = host_and_port_.ToString();
3347 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
3348 // This will cause session cache misses between sockets with different values
3349 // of ssl_session_cache_shard_ and this is used to partition the session cache
3350 // for incognito mode.
3351 if (!ssl_session_cache_shard_.empty()) {
3352 peer_id += "/" + ssl_session_cache_shard_;
3354 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
3355 if (rv != SECSuccess)
3356 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
3358 return OK;
3361 void SSLClientSocketNSS::DoConnectCallback(int rv) {
3362 EnterFunction(rv);
3363 DCHECK_NE(ERR_IO_PENDING, rv);
3364 DCHECK(!user_connect_callback_.is_null());
3366 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
3367 LeaveFunction("");
3370 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
3371 EnterFunction(result);
3372 int rv = DoHandshakeLoop(result);
3373 if (rv != ERR_IO_PENDING) {
3374 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3375 DoConnectCallback(rv);
3377 LeaveFunction("");
3380 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
3381 EnterFunction(last_io_result);
3382 int rv = last_io_result;
3383 do {
3384 // Default to STATE_NONE for next state.
3385 // (This is a quirk carried over from the windows
3386 // implementation. It makes reading the logs a bit harder.)
3387 // State handlers can and often do call GotoState just
3388 // to stay in the current state.
3389 State state = next_handshake_state_;
3390 GotoState(STATE_NONE);
3391 switch (state) {
3392 case STATE_HANDSHAKE:
3393 rv = DoHandshake();
3394 break;
3395 case STATE_HANDSHAKE_COMPLETE:
3396 rv = DoHandshakeComplete(rv);
3397 break;
3398 case STATE_VERIFY_CERT:
3399 DCHECK(rv == OK);
3400 rv = DoVerifyCert(rv);
3401 break;
3402 case STATE_VERIFY_CERT_COMPLETE:
3403 rv = DoVerifyCertComplete(rv);
3404 break;
3405 case STATE_NONE:
3406 default:
3407 rv = ERR_UNEXPECTED;
3408 LOG(DFATAL) << "unexpected state " << state;
3409 break;
3411 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
3412 LeaveFunction("");
3413 return rv;
3416 int SSLClientSocketNSS::DoHandshake() {
3417 EnterFunction("");
3418 int rv = core_->Connect(
3419 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3420 base::Unretained(this)));
3421 GotoState(STATE_HANDSHAKE_COMPLETE);
3423 LeaveFunction(rv);
3424 return rv;
3427 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
3428 EnterFunction(result);
3430 if (result == OK) {
3431 if (ssl_config_.version_fallback &&
3432 ssl_config_.version_max < ssl_config_.version_fallback_min) {
3433 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
3436 // SSL handshake is completed. Let's verify the certificate.
3437 GotoState(STATE_VERIFY_CERT);
3438 // Done!
3440 set_channel_id_sent(core_->state().channel_id_sent);
3441 set_signed_cert_timestamps_received(
3442 !core_->state().sct_list_from_tls_extension.empty());
3443 set_stapled_ocsp_response_received(
3444 !core_->state().stapled_ocsp_response.empty());
3445 set_negotiation_extension(core_->state().negotiation_extension_);
3447 LeaveFunction(result);
3448 return result;
3451 int SSLClientSocketNSS::DoVerifyCert(int result) {
3452 DCHECK(!core_->state().server_cert_chain.empty());
3453 DCHECK(core_->state().server_cert_chain[0]);
3455 GotoState(STATE_VERIFY_CERT_COMPLETE);
3457 // If the certificate is expected to be bad we can use the expectation as
3458 // the cert status.
3459 base::StringPiece der_cert(
3460 reinterpret_cast<char*>(
3461 core_->state().server_cert_chain[0]->derCert.data),
3462 core_->state().server_cert_chain[0]->derCert.len);
3463 CertStatus cert_status;
3464 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3465 DCHECK(start_cert_verification_time_.is_null());
3466 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3467 server_cert_verify_result_.Reset();
3468 server_cert_verify_result_.cert_status = cert_status;
3469 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3470 return OK;
3473 // We may have failed to create X509Certificate object if we are
3474 // running inside sandbox.
3475 if (!core_->state().server_cert.get()) {
3476 server_cert_verify_result_.Reset();
3477 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
3478 return ERR_CERT_INVALID;
3481 start_cert_verification_time_ = base::TimeTicks::Now();
3483 int flags = 0;
3484 if (ssl_config_.rev_checking_enabled)
3485 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
3486 if (ssl_config_.verify_ev_cert)
3487 flags |= CertVerifier::VERIFY_EV_CERT;
3488 if (ssl_config_.cert_io_enabled)
3489 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
3490 if (ssl_config_.rev_checking_required_local_anchors)
3491 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3492 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
3493 return verifier_->Verify(
3494 core_->state().server_cert.get(),
3495 host_and_port_.host(),
3496 flags,
3497 SSLConfigService::GetCRLSet().get(),
3498 &server_cert_verify_result_,
3499 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3500 base::Unretained(this)),
3501 net_log_);
3504 // Derived from AuthCertificateCallback() in
3505 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3506 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3507 verifier_.reset();
3509 if (!start_cert_verification_time_.is_null()) {
3510 base::TimeDelta verify_time =
3511 base::TimeTicks::Now() - start_cert_verification_time_;
3512 if (result == OK)
3513 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3514 else
3515 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3518 // We used to remember the intermediate CA certs in the NSS database
3519 // persistently. However, NSS opens a connection to the SQLite database
3520 // during NSS initialization and doesn't close the connection until NSS
3521 // shuts down. If the file system where the database resides is gone,
3522 // the database connection goes bad. What's worse, the connection won't
3523 // recover when the file system comes back. Until this NSS or SQLite bug
3524 // is fixed, we need to avoid using the NSS database for non-essential
3525 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3526 // http://crbug.com/15630 for more info.
3528 // TODO(hclam): Skip logging if server cert was expected to be bad because
3529 // |server_cert_verify_result_| doesn't contain all the information about
3530 // the cert.
3531 if (result == OK) {
3532 int ssl_version =
3533 SSLConnectionStatusToVersion(core_->state().ssl_connection_status);
3534 RecordConnectionTypeMetrics(ssl_version);
3537 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3538 if (transport_security_state_ &&
3539 (result == OK ||
3540 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
3541 !transport_security_state_->CheckPublicKeyPins(
3542 host_and_port_.host(),
3543 server_cert_verify_result_.is_issued_by_known_root,
3544 server_cert_verify_result_.public_key_hashes,
3545 &pinning_failure_log_)) {
3546 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3549 if (result == OK) {
3550 // Only check Certificate Transparency if there were no other errors with
3551 // the connection.
3552 VerifyCT();
3554 // Only cache the session if the certificate verified successfully.
3555 core_->CacheSessionIfNecessary();
3558 completed_handshake_ = true;
3560 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3561 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3562 return result;
3565 void SSLClientSocketNSS::VerifyCT() {
3566 if (!cert_transparency_verifier_)
3567 return;
3569 // Note that this is a completely synchronous operation: The CT Log Verifier
3570 // gets all the data it needs for SCT verification and does not do any
3571 // external communication.
3572 cert_transparency_verifier_->Verify(
3573 server_cert_verify_result_.verified_cert.get(),
3574 core_->state().stapled_ocsp_response,
3575 core_->state().sct_list_from_tls_extension, &ct_verify_result_, net_log_);
3576 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3577 // from the state after verification is complete, to conserve memory.
3579 if (!policy_enforcer_) {
3580 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3581 } else {
3582 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
3583 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
3584 SSLConfigService::GetEVCertsWhitelist();
3585 if (!policy_enforcer_->DoesConformToCTEVPolicy(
3586 server_cert_verify_result_.verified_cert.get(),
3587 ev_whitelist.get(), ct_verify_result_, net_log_)) {
3588 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3589 VLOG(1) << "EV certificate for "
3590 << server_cert_verify_result_.verified_cert->subject()
3591 .GetDisplayName()
3592 << " does not conform to CT policy, removing EV status.";
3593 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3599 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3600 base::AutoLock auto_lock(lock_);
3601 if (valid_thread_id_ != base::kInvalidThreadId)
3602 return;
3603 valid_thread_id_ = base::PlatformThread::CurrentId();
3606 bool SSLClientSocketNSS::CalledOnValidThread() const {
3607 EnsureThreadIdAssigned();
3608 base::AutoLock auto_lock(lock_);
3609 return valid_thread_id_ == base::PlatformThread::CurrentId();
3612 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
3613 for (ct::SCTList::const_iterator iter =
3614 ct_verify_result_.verified_scts.begin();
3615 iter != ct_verify_result_.verified_scts.end(); ++iter) {
3616 ssl_info->signed_certificate_timestamps.push_back(
3617 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
3619 for (ct::SCTList::const_iterator iter =
3620 ct_verify_result_.invalid_scts.begin();
3621 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
3622 ssl_info->signed_certificate_timestamps.push_back(
3623 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
3625 for (ct::SCTList::const_iterator iter =
3626 ct_verify_result_.unknown_logs_scts.begin();
3627 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
3628 ssl_info->signed_certificate_timestamps.push_back(
3629 SignedCertificateTimestampAndStatus(*iter,
3630 ct::SCT_STATUS_LOG_UNKNOWN));
3634 scoped_refptr<X509Certificate>
3635 SSLClientSocketNSS::GetUnverifiedServerCertificateChain() const {
3636 return core_->state().server_cert.get();
3639 ChannelIDService* SSLClientSocketNSS::GetChannelIDService() const {
3640 return channel_id_service_;
3643 } // namespace net