ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / net / socket / ssl_client_socket_nss.cc
blob9a8f72e5bc3bf7f78dbe01cf15ed3f21f465c0ce
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_cipher_suite_names.h"
111 #include "net/ssl/ssl_connection_status_flags.h"
112 #include "net/ssl/ssl_info.h"
114 #if defined(OS_WIN)
115 #include <windows.h>
116 #include <wincrypt.h>
118 #include "base/win/windows_version.h"
119 #elif defined(OS_MACOSX)
120 #include <Security/SecBase.h>
121 #include <Security/SecCertificate.h>
122 #include <Security/SecIdentity.h>
124 #include "base/mac/mac_logging.h"
125 #include "base/synchronization/lock.h"
126 #include "crypto/mac_security_services_lock.h"
127 #elif defined(USE_NSS)
128 #include <dlfcn.h>
129 #endif
131 namespace net {
133 // State machines are easier to debug if you log state transitions.
134 // Enable these if you want to see what's going on.
135 #if 1
136 #define EnterFunction(x)
137 #define LeaveFunction(x)
138 #define GotoState(s) next_handshake_state_ = s
139 #else
140 #define EnterFunction(x)\
141 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
142 << "; next_handshake_state " << next_handshake_state_
143 #define LeaveFunction(x)\
144 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
145 << "; next_handshake_state " << next_handshake_state_
146 #define GotoState(s)\
147 do {\
148 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
149 next_handshake_state_ = s;\
150 } while (0)
151 #endif
153 #if !defined(CKM_AES_GCM)
154 #define CKM_AES_GCM 0x00001087
155 #endif
157 #if !defined(CKM_NSS_CHACHA20_POLY1305)
158 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
159 #endif
161 namespace {
163 // SSL plaintext fragments are shorter than 16KB. Although the record layer
164 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
165 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
166 // entire SSL record.
167 const int kRecvBufferSize = 17 * 1024;
168 const int kSendBufferSize = 17 * 1024;
170 // Used by SSLClientSocketNSS::Core to indicate there is no read result
171 // obtained by a previous operation waiting to be returned to the caller.
172 // This constant can be any non-negative/non-zero value (eg: it does not
173 // overlap with any value of the net::Error range, including net::OK).
174 const int kNoPendingReadResult = 1;
176 #if defined(OS_WIN)
177 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
178 // set on Windows XP without error. There is some overhead from the server
179 // sending the OCSP response if it supports the extension, for the subset of
180 // XP clients who will request it but be unable to use it, but this is an
181 // acceptable trade-off for simplicity of implementation.
182 bool IsOCSPStaplingSupported() {
183 return true;
185 #elif defined(USE_NSS)
186 typedef SECStatus
187 (*CacheOCSPResponseFromSideChannelFunction)(
188 CERTCertDBHandle *handle, CERTCertificate *cert, PRTime time,
189 SECItem *encodedResponse, void *pwArg);
191 // On Linux, we dynamically link against the system version of libnss3.so. In
192 // order to continue working on systems without up-to-date versions of NSS we
193 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
195 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
196 // runtime symbol resolution that we need.
197 class RuntimeLibNSSFunctionPointers {
198 public:
199 CacheOCSPResponseFromSideChannelFunction
200 GetCacheOCSPResponseFromSideChannelFunction() {
201 return cache_ocsp_response_from_side_channel_;
204 static RuntimeLibNSSFunctionPointers* GetInstance() {
205 return Singleton<RuntimeLibNSSFunctionPointers>::get();
208 private:
209 friend struct DefaultSingletonTraits<RuntimeLibNSSFunctionPointers>;
211 RuntimeLibNSSFunctionPointers() {
212 cache_ocsp_response_from_side_channel_ =
213 (CacheOCSPResponseFromSideChannelFunction)
214 dlsym(RTLD_DEFAULT, "CERT_CacheOCSPResponseFromSideChannel");
217 CacheOCSPResponseFromSideChannelFunction
218 cache_ocsp_response_from_side_channel_;
221 CacheOCSPResponseFromSideChannelFunction
222 GetCacheOCSPResponseFromSideChannelFunction() {
223 return RuntimeLibNSSFunctionPointers::GetInstance()
224 ->GetCacheOCSPResponseFromSideChannelFunction();
227 bool IsOCSPStaplingSupported() {
228 return GetCacheOCSPResponseFromSideChannelFunction() != NULL;
230 #else
231 bool IsOCSPStaplingSupported() {
232 return false;
234 #endif
236 #if defined(OS_WIN)
238 // This callback is intended to be used with CertFindChainInStore. In addition
239 // to filtering by extended/enhanced key usage, we do not show expired
240 // certificates and require digital signature usage in the key usage
241 // extension.
243 // This matches our behavior on Mac OS X and that of NSS. It also matches the
244 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
245 // 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
246 BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
247 void* find_arg) {
248 VLOG(1) << "Calling ClientCertFindCallback from _nss";
249 // Verify the certificate's KU is good.
250 BYTE key_usage;
251 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
252 &key_usage, 1)) {
253 if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
254 return FALSE;
255 } else {
256 DWORD err = GetLastError();
257 // If |err| is non-zero, it's an actual error. Otherwise the extension
258 // just isn't present, and we treat it as if everything was allowed.
259 if (err) {
260 DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
261 return FALSE;
265 // Verify the current time is within the certificate's validity period.
266 if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
267 return FALSE;
269 // Verify private key metadata is associated with this certificate.
270 DWORD size = 0;
271 if (!CertGetCertificateContextProperty(
272 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
273 return FALSE;
276 return TRUE;
279 #endif
281 // Helper functions to make it possible to log events from within the
282 // SSLClientSocketNSS::Core.
283 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
284 NetLog::EventType event_type) {
285 if (!net_log)
286 return;
287 net_log->AddEvent(event_type);
290 // Helper function to make it possible to log events from within the
291 // SSLClientSocketNSS::Core.
292 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
293 NetLog::EventType event_type,
294 const NetLog::ParametersCallback& callback) {
295 if (!net_log)
296 return;
297 net_log->AddEvent(event_type, callback);
300 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
301 // from within the SSLClientSocketNSS::Core.
302 // AddByteTransferEvent expects to receive a const char*, which within the
303 // Core is backed by an IOBuffer. If the "const char*" is bound via
304 // base::Bind and posted to another thread, and the IOBuffer that backs that
305 // pointer then goes out of scope on the origin thread, this would result in
306 // an invalid read of a stale pointer.
307 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
308 // to the owning IOBuffer can be bound to the Callback. This ensures that the
309 // IOBuffer will stay alive long enough to cross threads if needed.
310 void LogByteTransferEvent(
311 const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
312 int len, IOBuffer* buffer) {
313 if (!net_log)
314 return;
315 net_log->AddByteTransferEvent(event_type, len, buffer->data());
318 // PeerCertificateChain is a helper object which extracts the certificate
319 // chain, as given by the server, from an NSS socket and performs the needed
320 // resource management. The first element of the chain is the leaf certificate
321 // and the other elements are in the order given by the server.
322 class PeerCertificateChain {
323 public:
324 PeerCertificateChain() {}
325 PeerCertificateChain(const PeerCertificateChain& other);
326 ~PeerCertificateChain();
327 PeerCertificateChain& operator=(const PeerCertificateChain& other);
329 // Resets the current chain, freeing any resources, and updates the current
330 // chain to be a copy of the chain stored in |nss_fd|.
331 // If |nss_fd| is NULL, then the current certificate chain will be freed.
332 void Reset(PRFileDesc* nss_fd);
334 // Returns the current certificate chain as a vector of DER-encoded
335 // base::StringPieces. The returned vector remains valid until Reset is
336 // called.
337 std::vector<base::StringPiece> AsStringPieceVector() const;
339 bool empty() const { return certs_.empty(); }
341 CERTCertificate* operator[](size_t index) const {
342 DCHECK_LT(index, certs_.size());
343 return certs_[index];
346 private:
347 std::vector<CERTCertificate*> certs_;
350 PeerCertificateChain::PeerCertificateChain(
351 const PeerCertificateChain& other) {
352 *this = other;
355 PeerCertificateChain::~PeerCertificateChain() {
356 Reset(NULL);
359 PeerCertificateChain& PeerCertificateChain::operator=(
360 const PeerCertificateChain& other) {
361 if (this == &other)
362 return *this;
364 Reset(NULL);
365 certs_.reserve(other.certs_.size());
366 for (size_t i = 0; i < other.certs_.size(); ++i)
367 certs_.push_back(CERT_DupCertificate(other.certs_[i]));
369 return *this;
372 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
373 for (size_t i = 0; i < certs_.size(); ++i)
374 CERT_DestroyCertificate(certs_[i]);
375 certs_.clear();
377 if (nss_fd == NULL)
378 return;
380 CERTCertList* list = SSL_PeerCertificateChain(nss_fd);
381 // The handshake on |nss_fd| may not have completed.
382 if (list == NULL)
383 return;
385 for (CERTCertListNode* node = CERT_LIST_HEAD(list);
386 !CERT_LIST_END(node, list); node = CERT_LIST_NEXT(node)) {
387 certs_.push_back(CERT_DupCertificate(node->cert));
389 CERT_DestroyCertList(list);
392 std::vector<base::StringPiece>
393 PeerCertificateChain::AsStringPieceVector() const {
394 std::vector<base::StringPiece> v(certs_.size());
395 for (unsigned i = 0; i < certs_.size(); i++) {
396 v[i] = base::StringPiece(
397 reinterpret_cast<const char*>(certs_[i]->derCert.data),
398 certs_[i]->derCert.len);
401 return v;
404 // HandshakeState is a helper struct used to pass handshake state between
405 // the NSS task runner and the network task runner.
407 // It contains members that may be read or written on the NSS task runner,
408 // but which also need to be read from the network task runner. The NSS task
409 // runner will notify the network task runner whenever this state changes, so
410 // that the network task runner can safely make a copy, which avoids the need
411 // for locking.
412 struct HandshakeState {
413 HandshakeState() { Reset(); }
415 void Reset() {
416 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
417 next_proto.clear();
418 negotiation_extension_ = SSLClientSocket::kExtensionUnknown;
419 channel_id_sent = false;
420 server_cert_chain.Reset(NULL);
421 server_cert = NULL;
422 sct_list_from_tls_extension.clear();
423 stapled_ocsp_response.clear();
424 resumed_handshake = false;
425 ssl_connection_status = 0;
428 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
429 // negotiated protocol stored in |next_proto|.
430 SSLClientSocket::NextProtoStatus next_proto_status;
431 std::string next_proto;
433 // TLS extension used for protocol negotiation.
434 SSLClientSocket::SSLNegotiationExtension negotiation_extension_;
436 // True if a channel ID was sent.
437 bool channel_id_sent;
439 // List of DER-encoded X.509 DistinguishedName of certificate authorities
440 // allowed by the server.
441 std::vector<std::string> cert_authorities;
443 // Set when the handshake fully completes.
445 // The server certificate is first received from NSS as an NSS certificate
446 // chain (|server_cert_chain|) and then converted into a platform-specific
447 // X509Certificate object (|server_cert|). It's possible for some
448 // certificates to be successfully parsed by NSS, and not by the platform
449 // libraries (i.e.: when running within a sandbox, different parsing
450 // algorithms, etc), so it's not safe to assume that |server_cert| will
451 // always be non-NULL.
452 PeerCertificateChain server_cert_chain;
453 scoped_refptr<X509Certificate> server_cert;
454 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
455 std::string sct_list_from_tls_extension;
456 // Stapled OCSP response received.
457 std::string stapled_ocsp_response;
459 // True if the current handshake was the result of TLS session resumption.
460 bool resumed_handshake;
462 // The negotiated security parameters (TLS version, cipher, extensions) of
463 // the SSL connection.
464 int ssl_connection_status;
467 // Client-side error mapping functions.
469 // Map NSS error code to network error code.
470 int MapNSSClientError(PRErrorCode err) {
471 switch (err) {
472 case SSL_ERROR_BAD_CERT_ALERT:
473 case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
474 case SSL_ERROR_REVOKED_CERT_ALERT:
475 case SSL_ERROR_EXPIRED_CERT_ALERT:
476 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
477 case SSL_ERROR_UNKNOWN_CA_ALERT:
478 case SSL_ERROR_ACCESS_DENIED_ALERT:
479 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
480 default:
481 return MapNSSError(err);
485 } // namespace
487 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
488 // able to marshal data between NSS functions and an underlying transport
489 // socket.
491 // All public functions are meant to be called from the network task runner,
492 // and any callbacks supplied will be invoked there as well, provided that
493 // Detach() has not been called yet.
495 /////////////////////////////////////////////////////////////////////////////
497 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
499 // Because NSS may block on either hardware or user input during operations
500 // such as signing, creating certificates, or locating private keys, the Core
501 // handles all of the interactions with the underlying NSS SSL socket, so
502 // that these blocking calls can be executed on a dedicated task runner.
504 // Note that the network task runner and the NSS task runner may be executing
505 // on the same thread. If that happens, then it's more performant to try to
506 // complete as much work as possible synchronously, even if it might block,
507 // rather than continually PostTask-ing to the same thread.
509 // Because NSS functions should only be called on the NSS task runner, while
510 // I/O resources should only be accessed on the network task runner, most
511 // public functions are implemented via three methods, each with different
512 // task runner affinities.
514 // In the single-threaded mode (where the network and NSS task runners run on
515 // the same thread), these are all attempted synchronously, while in the
516 // multi-threaded mode, message passing is used.
518 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
519 // DoHandshake)
520 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
521 // (BufferRecv, BufferSend)
522 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
523 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
524 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
525 // data from the network task runner back to NSS (BufferRecvComplete,
526 // BufferSendComplete, OnHandshakeIOComplete)
528 /////////////////////////////////////////////////////////////////////////////
529 // Single-threaded example
531 // |--------------------------Network Task Runner--------------------------|
532 // SSLClientSocketNSS Core (Transport Socket)
533 // Read()
534 // |-------------------------V
535 // Read()
536 // |
537 // DoPayloadRead()
538 // |
539 // BufferRecv()
540 // |
541 // DoBufferRecv()
542 // |-------------------------V
543 // Read()
544 // V-------------------------|
545 // BufferRecvComplete()
546 // |
547 // PostOrRunCallback()
548 // V-------------------------|
549 // (Read Callback)
551 /////////////////////////////////////////////////////////////////////////////
552 // Multi-threaded example:
554 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
555 // SSLClientSocketNSS Core Socket Core
556 // Read()
557 // |---------------------V
558 // Read()
559 // |-------------------------------V
560 // Read()
561 // |
562 // DoPayloadRead()
563 // |
564 // BufferRecv
565 // V-------------------------------|
566 // DoBufferRecv
567 // |----------------V
568 // Read()
569 // V----------------|
570 // BufferRecvComplete()
571 // |-------------------------------V
572 // BufferRecvComplete()
573 // |
574 // PostOrRunCallback()
575 // V-------------------------------|
576 // PostOrRunCallback()
577 // V---------------------|
578 // (Read Callback)
580 /////////////////////////////////////////////////////////////////////////////
581 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
582 public:
583 // Creates a new Core.
585 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
586 // that need to operate on the underlying transport, net log, or server
587 // bound certificate fetching will happen on the |network_task_runner|, so
588 // that their lifetimes match that of the owning SSLClientSocketNSS.
590 // The caller retains ownership of |transport|, |net_log|, and
591 // |channel_id_service|, and they will not be accessed once Detach()
592 // has been called.
593 Core(base::SequencedTaskRunner* network_task_runner,
594 base::SequencedTaskRunner* nss_task_runner,
595 ClientSocketHandle* transport,
596 const HostPortPair& host_and_port,
597 const SSLConfig& ssl_config,
598 BoundNetLog* net_log,
599 ChannelIDService* channel_id_service);
601 // Called on the network task runner.
602 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
603 // underlying memio implementation, to the Core. Returns true if the Core
604 // was successfully registered with the socket.
605 bool Init(PRFileDesc* socket, memio_Private* buffers);
607 // Called on the network task runner.
609 // Attempts to perform an SSL handshake. If the handshake cannot be
610 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
611 // the network task runner once the handshake has completed. Otherwise,
612 // returns OK on success or a network error code on failure.
613 int Connect(const CompletionCallback& callback);
615 // Called on the network task runner.
616 // Signals that the resources owned by the network task runner are going
617 // away. No further callbacks will be invoked on the network task runner.
618 // May be called at any time.
619 void Detach();
621 // Called on the network task runner.
622 // Returns the current state of the underlying SSL socket. May be called at
623 // any time.
624 const HandshakeState& state() const { return network_handshake_state_; }
626 // Called on the network task runner.
627 // Read() and Write() mirror the net::Socket functions of the same name.
628 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
629 // task runner at a later point, unless the caller calls Detach().
630 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
631 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
633 // Called on the network task runner.
634 bool IsConnected() const;
635 bool HasPendingAsyncOperation() const;
636 bool HasUnhandledReceivedData() const;
637 bool WasEverUsed() const;
639 // Called on the network task runner.
640 // Causes the associated SSL/TLS session ID to be added to NSS's session
641 // cache, but only if the connection has not been False Started.
643 // This should only be called after the server's certificate has been
644 // verified, and may not be called within an NSS callback.
645 void CacheSessionIfNecessary();
647 private:
648 friend class base::RefCountedThreadSafe<Core>;
649 ~Core();
651 enum State {
652 STATE_NONE,
653 STATE_HANDSHAKE,
654 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
657 bool OnNSSTaskRunner() const;
658 bool OnNetworkTaskRunner() const;
660 ////////////////////////////////////////////////////////////////////////////
661 // Methods that are ONLY called on the NSS task runner:
662 ////////////////////////////////////////////////////////////////////////////
664 // Called by NSS during full handshakes to allow the application to
665 // verify the certificate. Instead of verifying the certificate in the midst
666 // of the handshake, SECSuccess is always returned and the peer's certificate
667 // is verified afterwards.
668 // This behaviour is an artifact of the original SSLClientSocketWin
669 // implementation, which could not verify the peer's certificate until after
670 // the handshake had completed, as well as bugs in NSS that prevent
671 // SSL_RestartHandshakeAfterCertReq from working.
672 static SECStatus OwnAuthCertHandler(void* arg,
673 PRFileDesc* socket,
674 PRBool checksig,
675 PRBool is_server);
677 // Callbacks called by NSS when the peer requests client certificate
678 // authentication.
679 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
680 // the arguments.
681 #if defined(NSS_PLATFORM_CLIENT_AUTH)
682 // When NSS has been integrated with awareness of the underlying system
683 // cryptographic libraries, this callback allows the caller to supply a
684 // native platform certificate and key for use by NSS. At most, one of
685 // either (result_certs, result_private_key) or (result_nss_certificate,
686 // result_nss_private_key) should be set.
687 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
688 static SECStatus PlatformClientAuthHandler(
689 void* arg,
690 PRFileDesc* socket,
691 CERTDistNames* ca_names,
692 CERTCertList** result_certs,
693 void** result_private_key,
694 CERTCertificate** result_nss_certificate,
695 SECKEYPrivateKey** result_nss_private_key);
696 #else
697 static SECStatus ClientAuthHandler(void* arg,
698 PRFileDesc* socket,
699 CERTDistNames* ca_names,
700 CERTCertificate** result_certificate,
701 SECKEYPrivateKey** result_private_key);
702 #endif
704 // Called by NSS to determine if we can False Start.
705 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
706 static SECStatus CanFalseStartCallback(PRFileDesc* socket,
707 void* arg,
708 PRBool* can_false_start);
710 // Called by NSS once the handshake has completed.
711 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
712 static void HandshakeCallback(PRFileDesc* socket, void* arg);
714 // Called once the handshake has succeeded.
715 void HandshakeSucceeded();
717 // Handles an NSS error generated while handshaking or performing IO.
718 // Returns a network error code mapped from the original NSS error.
719 int HandleNSSError(PRErrorCode error);
721 int DoHandshakeLoop(int last_io_result);
722 int DoReadLoop(int result);
723 int DoWriteLoop(int result);
725 int DoHandshake();
726 int DoGetDBCertComplete(int result);
728 int DoPayloadRead();
729 int DoPayloadWrite();
731 bool DoTransportIO();
732 int BufferRecv();
733 int BufferSend();
735 void OnRecvComplete(int result);
736 void OnSendComplete(int result);
738 void DoConnectCallback(int result);
739 void DoReadCallback(int result);
740 void DoWriteCallback(int result);
742 // Client channel ID handler.
743 static SECStatus ClientChannelIDHandler(
744 void* arg,
745 PRFileDesc* socket,
746 SECKEYPublicKey **out_public_key,
747 SECKEYPrivateKey **out_private_key);
749 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
750 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
751 // and an error code otherwise.
752 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
753 // set by a call to ChannelIDService->GetChannelID. The caller
754 // takes ownership of the |*cert| and |*key|.
755 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
757 // Updates the NSS and platform specific certificates.
758 void UpdateServerCert();
759 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
760 // received in the handshake via a TLS extension.
761 void UpdateSignedCertTimestamps();
762 // Update the OCSP response cache with the stapled response received in the
763 // handshake, and update nss_handshake_state_ with
764 // the SignedCertificateTimestampList received in the stapled OCSP response.
765 void UpdateStapledOCSPResponse();
766 // Updates the nss_handshake_state_ with the negotiated security parameters.
767 void UpdateConnectionStatus();
768 // Record histograms for channel id support during full handshakes - resumed
769 // handshakes are ignored.
770 void RecordChannelIDSupportOnNSSTaskRunner();
771 // UpdateNextProto gets any application-layer protocol that may have been
772 // negotiated by the TLS connection.
773 void UpdateNextProto();
774 // Record TLS extension used for protocol negotiation (NPN or ALPN).
775 void UpdateExtensionUsed();
777 ////////////////////////////////////////////////////////////////////////////
778 // Methods that are ONLY called on the network task runner:
779 ////////////////////////////////////////////////////////////////////////////
780 int DoBufferRecv(IOBuffer* buffer, int len);
781 int DoBufferSend(IOBuffer* buffer, int len);
782 int DoGetChannelID(const std::string& host);
784 void OnGetChannelIDComplete(int result);
785 void OnHandshakeStateUpdated(const HandshakeState& state);
786 void OnNSSBufferUpdated(int amount_in_read_buffer);
787 void DidNSSRead(int result);
788 void DidNSSWrite(int result);
789 void RecordChannelIDSupportOnNetworkTaskRunner(
790 bool negotiated_channel_id,
791 bool channel_id_enabled,
792 bool supports_ecc) const;
794 ////////////////////////////////////////////////////////////////////////////
795 // Methods that are called on both the network task runner and the NSS
796 // task runner.
797 ////////////////////////////////////////////////////////////////////////////
798 void OnHandshakeIOComplete(int result);
799 void BufferRecvComplete(IOBuffer* buffer, int result);
800 void BufferSendComplete(int result);
802 // PostOrRunCallback is a helper function to ensure that |callback| is
803 // invoked on the network task runner, but only if Detach() has not yet
804 // been called.
805 void PostOrRunCallback(const tracked_objects::Location& location,
806 const base::Closure& callback);
808 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
809 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
810 void AddCertProvidedEvent(int cert_count);
812 // Sets the handshake state |channel_id_sent| flag and logs the
813 // SSL_CHANNEL_ID_PROVIDED event.
814 void SetChannelIDProvided();
816 ////////////////////////////////////////////////////////////////////////////
817 // Members that are ONLY accessed on the network task runner:
818 ////////////////////////////////////////////////////////////////////////////
820 // True if the owning SSLClientSocketNSS has called Detach(). No further
821 // callbacks will be invoked nor access to members owned by the network
822 // task runner.
823 bool detached_;
825 // The underlying transport to use for network IO.
826 ClientSocketHandle* transport_;
827 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
829 // The current handshake state. Mirrors |nss_handshake_state_|.
830 HandshakeState network_handshake_state_;
832 // The service for retrieving Channel ID keys. May be NULL.
833 ChannelIDService* channel_id_service_;
834 ChannelIDService::RequestHandle domain_bound_cert_request_handle_;
836 // The information about NSS task runner.
837 int unhandled_buffer_size_;
838 bool nss_waiting_read_;
839 bool nss_waiting_write_;
840 bool nss_is_closed_;
842 // Set when Read() or Write() successfully reads or writes data to or from the
843 // network.
844 bool was_ever_used_;
846 ////////////////////////////////////////////////////////////////////////////
847 // Members that are ONLY accessed on the NSS task runner:
848 ////////////////////////////////////////////////////////////////////////////
849 HostPortPair host_and_port_;
850 SSLConfig ssl_config_;
852 // NSS SSL socket.
853 PRFileDesc* nss_fd_;
855 // Buffers for the network end of the SSL state machine
856 memio_Private* nss_bufs_;
858 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
859 // as much data as possible, without blocking.
860 // If DoPayloadRead() encounters an error after having read some data, stores
861 // the results to return on the *next* call to DoPayloadRead(). A value of
862 // kNoPendingReadResult indicates there is no pending result, otherwise 0
863 // indicates EOF and < 0 indicates an error.
864 int pending_read_result_;
865 // Contains the previously observed NSS error. Only valid when
866 // pending_read_result_ != kNoPendingReadResult.
867 PRErrorCode pending_read_nss_error_;
869 // The certificate chain, in DER form, that is expected to be received from
870 // the server.
871 std::vector<std::string> predicted_certs_;
873 State next_handshake_state_;
875 // True if channel ID extension was negotiated.
876 bool channel_id_xtn_negotiated_;
877 // True if the handshake state machine was interrupted for channel ID.
878 bool channel_id_needed_;
879 // True if the handshake state machine was interrupted for client auth.
880 bool client_auth_cert_needed_;
881 // True if NSS has False Started.
882 bool false_started_;
883 // True if NSS has called HandshakeCallback.
884 bool handshake_callback_called_;
886 HandshakeState nss_handshake_state_;
888 bool transport_recv_busy_;
889 bool transport_recv_eof_;
890 bool transport_send_busy_;
892 // Used by Read function.
893 scoped_refptr<IOBuffer> user_read_buf_;
894 int user_read_buf_len_;
896 // Used by Write function.
897 scoped_refptr<IOBuffer> user_write_buf_;
898 int user_write_buf_len_;
900 CompletionCallback user_connect_callback_;
901 CompletionCallback user_read_callback_;
902 CompletionCallback user_write_callback_;
904 ////////////////////////////////////////////////////////////////////////////
905 // Members that are accessed on both the network task runner and the NSS
906 // task runner.
907 ////////////////////////////////////////////////////////////////////////////
908 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
909 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
911 // Dereferenced only on the network task runner, but bound to tasks destined
912 // for the network task runner from the NSS task runner.
913 base::WeakPtr<BoundNetLog> weak_net_log_;
915 // Written on the network task runner by the |channel_id_service_|,
916 // prior to invoking OnHandshakeIOComplete.
917 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
918 // on the NSS task runner.
919 std::string domain_bound_private_key_;
920 std::string domain_bound_cert_;
922 DISALLOW_COPY_AND_ASSIGN(Core);
925 SSLClientSocketNSS::Core::Core(
926 base::SequencedTaskRunner* network_task_runner,
927 base::SequencedTaskRunner* nss_task_runner,
928 ClientSocketHandle* transport,
929 const HostPortPair& host_and_port,
930 const SSLConfig& ssl_config,
931 BoundNetLog* net_log,
932 ChannelIDService* channel_id_service)
933 : detached_(false),
934 transport_(transport),
935 weak_net_log_factory_(net_log),
936 channel_id_service_(channel_id_service),
937 unhandled_buffer_size_(0),
938 nss_waiting_read_(false),
939 nss_waiting_write_(false),
940 nss_is_closed_(false),
941 was_ever_used_(false),
942 host_and_port_(host_and_port),
943 ssl_config_(ssl_config),
944 nss_fd_(NULL),
945 nss_bufs_(NULL),
946 pending_read_result_(kNoPendingReadResult),
947 pending_read_nss_error_(0),
948 next_handshake_state_(STATE_NONE),
949 channel_id_xtn_negotiated_(false),
950 channel_id_needed_(false),
951 client_auth_cert_needed_(false),
952 false_started_(false),
953 handshake_callback_called_(false),
954 transport_recv_busy_(false),
955 transport_recv_eof_(false),
956 transport_send_busy_(false),
957 user_read_buf_len_(0),
958 user_write_buf_len_(0),
959 network_task_runner_(network_task_runner),
960 nss_task_runner_(nss_task_runner),
961 weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
964 SSLClientSocketNSS::Core::~Core() {
965 // TODO(wtc): Send SSL close_notify alert.
966 if (nss_fd_ != NULL) {
967 PR_Close(nss_fd_);
968 nss_fd_ = NULL;
970 nss_bufs_ = NULL;
973 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
974 memio_Private* buffers) {
975 DCHECK(OnNetworkTaskRunner());
976 DCHECK(!nss_fd_);
977 DCHECK(!nss_bufs_);
979 nss_fd_ = socket;
980 nss_bufs_ = buffers;
982 SECStatus rv = SECSuccess;
984 if (!ssl_config_.next_protos.empty()) {
985 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
986 const bool adequate_encryption =
987 PK11_TokenExists(CKM_AES_GCM) ||
988 PK11_TokenExists(CKM_NSS_CHACHA20_POLY1305);
989 const bool adequate_key_agreement = PK11_TokenExists(CKM_DH_PKCS_DERIVE) ||
990 PK11_TokenExists(CKM_ECDH1_DERIVE);
991 std::vector<uint8_t> wire_protos =
992 SerializeNextProtos(ssl_config_.next_protos,
993 adequate_encryption && adequate_key_agreement &&
994 IsTLSVersionAdequateForHTTP2(ssl_config_));
995 rv = SSL_SetNextProtoNego(
996 nss_fd_, wire_protos.empty() ? NULL : &wire_protos[0],
997 wire_protos.size());
998 if (rv != SECSuccess)
999 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoNego", "");
1000 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_ALPN, PR_TRUE);
1001 if (rv != SECSuccess)
1002 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_ALPN");
1003 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_NPN, PR_TRUE);
1004 if (rv != SECSuccess)
1005 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_NPN");
1008 rv = SSL_AuthCertificateHook(
1009 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
1010 if (rv != SECSuccess) {
1011 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
1012 return false;
1015 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1016 rv = SSL_GetPlatformClientAuthDataHook(
1017 nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler,
1018 this);
1019 #else
1020 rv = SSL_GetClientAuthDataHook(
1021 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
1022 #endif
1023 if (rv != SECSuccess) {
1024 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
1025 return false;
1028 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
1029 rv = SSL_SetClientChannelIDCallback(
1030 nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
1031 if (rv != SECSuccess) {
1032 LogFailedNSSFunction(
1033 *weak_net_log_, "SSL_SetClientChannelIDCallback", "");
1037 rv = SSL_SetCanFalseStartCallback(
1038 nss_fd_, SSLClientSocketNSS::Core::CanFalseStartCallback, this);
1039 if (rv != SECSuccess) {
1040 LogFailedNSSFunction(*weak_net_log_, "SSL_SetCanFalseStartCallback", "");
1041 return false;
1044 rv = SSL_HandshakeCallback(
1045 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
1046 if (rv != SECSuccess) {
1047 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
1048 return false;
1051 return true;
1054 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
1055 if (!OnNSSTaskRunner()) {
1056 DCHECK(!detached_);
1057 bool posted = nss_task_runner_->PostTask(
1058 FROM_HERE,
1059 base::Bind(IgnoreResult(&Core::Connect), this, callback));
1060 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1063 DCHECK(OnNSSTaskRunner());
1064 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1065 DCHECK(user_read_callback_.is_null());
1066 DCHECK(user_write_callback_.is_null());
1067 DCHECK(user_connect_callback_.is_null());
1068 DCHECK(!user_read_buf_.get());
1069 DCHECK(!user_write_buf_.get());
1071 next_handshake_state_ = STATE_HANDSHAKE;
1072 int rv = DoHandshakeLoop(OK);
1073 if (rv == ERR_IO_PENDING) {
1074 user_connect_callback_ = callback;
1075 } else if (rv > OK) {
1076 rv = OK;
1078 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
1079 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1080 return ERR_IO_PENDING;
1083 return rv;
1086 void SSLClientSocketNSS::Core::Detach() {
1087 DCHECK(OnNetworkTaskRunner());
1089 detached_ = true;
1090 transport_ = NULL;
1091 weak_net_log_factory_.InvalidateWeakPtrs();
1093 network_handshake_state_.Reset();
1095 domain_bound_cert_request_handle_.Cancel();
1098 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
1099 const CompletionCallback& callback) {
1100 if (!OnNSSTaskRunner()) {
1101 DCHECK(OnNetworkTaskRunner());
1102 DCHECK(!detached_);
1103 DCHECK(transport_);
1104 DCHECK(!nss_waiting_read_);
1106 nss_waiting_read_ = true;
1107 bool posted = nss_task_runner_->PostTask(
1108 FROM_HERE,
1109 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
1110 buf_len, callback));
1111 if (!posted) {
1112 nss_is_closed_ = true;
1113 nss_waiting_read_ = false;
1115 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1118 DCHECK(OnNSSTaskRunner());
1119 DCHECK(false_started_ || handshake_callback_called_);
1120 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1121 DCHECK(user_read_callback_.is_null());
1122 DCHECK(user_connect_callback_.is_null());
1123 DCHECK(!user_read_buf_.get());
1124 DCHECK(nss_bufs_);
1126 user_read_buf_ = buf;
1127 user_read_buf_len_ = buf_len;
1129 int rv = DoReadLoop(OK);
1130 if (rv == ERR_IO_PENDING) {
1131 if (OnNetworkTaskRunner())
1132 nss_waiting_read_ = true;
1133 user_read_callback_ = callback;
1134 } else {
1135 user_read_buf_ = NULL;
1136 user_read_buf_len_ = 0;
1138 if (!OnNetworkTaskRunner()) {
1139 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
1140 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1141 return ERR_IO_PENDING;
1142 } else {
1143 DCHECK(!nss_waiting_read_);
1144 if (rv <= 0) {
1145 nss_is_closed_ = true;
1146 } else {
1147 was_ever_used_ = true;
1152 return rv;
1155 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1156 const CompletionCallback& callback) {
1157 if (!OnNSSTaskRunner()) {
1158 DCHECK(OnNetworkTaskRunner());
1159 DCHECK(!detached_);
1160 DCHECK(transport_);
1161 DCHECK(!nss_waiting_write_);
1163 nss_waiting_write_ = true;
1164 bool posted = nss_task_runner_->PostTask(
1165 FROM_HERE,
1166 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
1167 buf_len, callback));
1168 if (!posted) {
1169 nss_is_closed_ = true;
1170 nss_waiting_write_ = false;
1172 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1175 DCHECK(OnNSSTaskRunner());
1176 DCHECK(false_started_ || handshake_callback_called_);
1177 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1178 DCHECK(user_write_callback_.is_null());
1179 DCHECK(user_connect_callback_.is_null());
1180 DCHECK(!user_write_buf_.get());
1181 DCHECK(nss_bufs_);
1183 user_write_buf_ = buf;
1184 user_write_buf_len_ = buf_len;
1186 int rv = DoWriteLoop(OK);
1187 if (rv == ERR_IO_PENDING) {
1188 if (OnNetworkTaskRunner())
1189 nss_waiting_write_ = true;
1190 user_write_callback_ = callback;
1191 } else {
1192 user_write_buf_ = NULL;
1193 user_write_buf_len_ = 0;
1195 if (!OnNetworkTaskRunner()) {
1196 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
1197 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1198 return ERR_IO_PENDING;
1199 } else {
1200 DCHECK(!nss_waiting_write_);
1201 if (rv < 0) {
1202 nss_is_closed_ = true;
1203 } else if (rv > 0) {
1204 was_ever_used_ = true;
1209 return rv;
1212 bool SSLClientSocketNSS::Core::IsConnected() const {
1213 DCHECK(OnNetworkTaskRunner());
1214 return !nss_is_closed_;
1217 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1218 DCHECK(OnNetworkTaskRunner());
1219 return nss_waiting_read_ || nss_waiting_write_;
1222 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1223 DCHECK(OnNetworkTaskRunner());
1224 return unhandled_buffer_size_ != 0;
1227 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1228 DCHECK(OnNetworkTaskRunner());
1229 return was_ever_used_;
1232 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1233 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1234 // nss_fd_. However, it happens on the network task runner in order to match
1235 // the buggy behavior of ExportKeyingMaterial.
1237 // Once http://crbug.com/330360 is fixed, this should be moved to an
1238 // implementation that exclusively does this work on the NSS TaskRunner. This
1239 // is "safe" because it is only called during the certificate verification
1240 // state machine of the main socket, which is safe because no underlying
1241 // transport IO will be occuring in that state, and NSS will not be blocking
1242 // on any PKCS#11 related locks that might block the Network TaskRunner.
1243 DCHECK(OnNetworkTaskRunner());
1245 // Only cache the session if the connection was not False Started, because
1246 // sessions should only be cached *after* the peer's Finished message is
1247 // processed.
1248 // In the case of False Start, the session will be cached once the
1249 // HandshakeCallback is called, which signals the receipt and processing of
1250 // the Finished message, and which will happen during a call to
1251 // PR_Read/PR_Write.
1252 if (!false_started_)
1253 SSL_CacheSession(nss_fd_);
1256 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1257 return nss_task_runner_->RunsTasksOnCurrentThread();
1260 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1261 return network_task_runner_->RunsTasksOnCurrentThread();
1264 // static
1265 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1266 void* arg,
1267 PRFileDesc* socket,
1268 PRBool checksig,
1269 PRBool is_server) {
1270 Core* core = reinterpret_cast<Core*>(arg);
1271 if (core->handshake_callback_called_) {
1272 // Disallow the server certificate to change in a renegotiation.
1273 CERTCertificate* old_cert = core->nss_handshake_state_.server_cert_chain[0];
1274 ScopedCERTCertificate new_cert(SSL_PeerCertificate(socket));
1275 if (new_cert->derCert.len != old_cert->derCert.len ||
1276 memcmp(new_cert->derCert.data, old_cert->derCert.data,
1277 new_cert->derCert.len) != 0) {
1278 // NSS doesn't have an error code that indicates the server certificate
1279 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1280 // for this purpose.
1281 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE);
1282 return SECFailure;
1286 // Tell NSS to not verify the certificate.
1287 return SECSuccess;
1290 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1291 // static
1292 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1293 void* arg,
1294 PRFileDesc* socket,
1295 CERTDistNames* ca_names,
1296 CERTCertList** result_certs,
1297 void** result_private_key,
1298 CERTCertificate** result_nss_certificate,
1299 SECKEYPrivateKey** result_nss_private_key) {
1300 Core* core = reinterpret_cast<Core*>(arg);
1301 DCHECK(core->OnNSSTaskRunner());
1303 core->PostOrRunCallback(
1304 FROM_HERE,
1305 base::Bind(&AddLogEvent, core->weak_net_log_,
1306 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1308 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1309 #if defined(OS_WIN)
1310 if (core->ssl_config_.send_client_cert) {
1311 if (core->ssl_config_.client_cert.get()) {
1312 PCCERT_CONTEXT cert_context =
1313 core->ssl_config_.client_cert->os_cert_handle();
1315 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
1316 DWORD key_spec = 0;
1317 BOOL must_free = FALSE;
1318 DWORD flags = 0;
1319 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
1320 flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
1322 BOOL acquired_key = CryptAcquireCertificatePrivateKey(
1323 cert_context, flags, NULL, &crypt_prov, &key_spec, &must_free);
1325 if (acquired_key) {
1326 // Should never get a cached handle back - ownership must always be
1327 // transferred.
1328 CHECK_EQ(must_free, TRUE);
1330 SECItem der_cert;
1331 der_cert.type = siDERCertBuffer;
1332 der_cert.data = cert_context->pbCertEncoded;
1333 der_cert.len = cert_context->cbCertEncoded;
1335 // TODO(rsleevi): Error checking for NSS allocation errors.
1336 CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB();
1337 CERTCertificate* user_cert = CERT_NewTempCertificate(
1338 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1339 if (!user_cert) {
1340 // Importing the certificate can fail for reasons including a serial
1341 // number collision. See crbug.com/97355.
1342 core->AddCertProvidedEvent(0);
1343 return SECFailure;
1345 CERTCertList* cert_chain = CERT_NewCertList();
1346 CERT_AddCertToListTail(cert_chain, user_cert);
1348 // Add the intermediates.
1349 X509Certificate::OSCertHandles intermediates =
1350 core->ssl_config_.client_cert->GetIntermediateCertificates();
1351 for (X509Certificate::OSCertHandles::const_iterator it =
1352 intermediates.begin(); it != intermediates.end(); ++it) {
1353 der_cert.data = (*it)->pbCertEncoded;
1354 der_cert.len = (*it)->cbCertEncoded;
1356 CERTCertificate* intermediate = CERT_NewTempCertificate(
1357 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1358 if (!intermediate) {
1359 CERT_DestroyCertList(cert_chain);
1360 core->AddCertProvidedEvent(0);
1361 return SECFailure;
1363 CERT_AddCertToListTail(cert_chain, intermediate);
1365 PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>(
1366 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT)));
1367 key_context->cbSize = sizeof(*key_context);
1368 // NSS will free this context when no longer in use.
1369 key_context->hCryptProv = crypt_prov;
1370 key_context->dwKeySpec = key_spec;
1371 *result_private_key = key_context;
1372 *result_certs = cert_chain;
1374 int cert_count = 1 + intermediates.size();
1375 core->AddCertProvidedEvent(cert_count);
1376 return SECSuccess;
1378 LOG(WARNING) << "Client cert found without private key";
1381 // Send no client certificate.
1382 core->AddCertProvidedEvent(0);
1383 return SECFailure;
1386 core->nss_handshake_state_.cert_authorities.clear();
1388 std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
1389 for (int i = 0; i < ca_names->nnames; ++i) {
1390 issuer_list[i].cbData = ca_names->names[i].len;
1391 issuer_list[i].pbData = ca_names->names[i].data;
1392 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1393 reinterpret_cast<const char*>(ca_names->names[i].data),
1394 static_cast<size_t>(ca_names->names[i].len)));
1397 // Update the network task runner's view of the handshake state now that
1398 // server certificate request has been recorded.
1399 core->PostOrRunCallback(
1400 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1401 core->nss_handshake_state_));
1403 // Tell NSS to suspend the client authentication. We will then abort the
1404 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1405 return SECWouldBlock;
1406 #elif defined(OS_MACOSX)
1407 if (core->ssl_config_.send_client_cert) {
1408 if (core->ssl_config_.client_cert.get()) {
1409 OSStatus os_error = noErr;
1410 SecIdentityRef identity = NULL;
1411 SecKeyRef private_key = NULL;
1412 X509Certificate::OSCertHandles chain;
1414 base::AutoLock lock(crypto::GetMacSecurityServicesLock());
1415 os_error = SecIdentityCreateWithCertificate(
1416 NULL, core->ssl_config_.client_cert->os_cert_handle(), &identity);
1418 if (os_error == noErr) {
1419 os_error = SecIdentityCopyPrivateKey(identity, &private_key);
1420 CFRelease(identity);
1423 if (os_error == noErr) {
1424 // TODO(rsleevi): Error checking for NSS allocation errors.
1425 *result_certs = CERT_NewCertList();
1426 *result_private_key = private_key;
1428 chain.push_back(core->ssl_config_.client_cert->os_cert_handle());
1429 const X509Certificate::OSCertHandles& intermediates =
1430 core->ssl_config_.client_cert->GetIntermediateCertificates();
1431 if (!intermediates.empty())
1432 chain.insert(chain.end(), intermediates.begin(), intermediates.end());
1434 for (size_t i = 0, chain_count = chain.size(); i < chain_count; ++i) {
1435 CSSM_DATA cert_data;
1436 SecCertificateRef cert_ref = chain[i];
1437 os_error = SecCertificateGetData(cert_ref, &cert_data);
1438 if (os_error != noErr)
1439 break;
1441 SECItem der_cert;
1442 der_cert.type = siDERCertBuffer;
1443 der_cert.data = cert_data.Data;
1444 der_cert.len = cert_data.Length;
1445 CERTCertificate* nss_cert = CERT_NewTempCertificate(
1446 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
1447 if (!nss_cert) {
1448 // In the event of an NSS error, make up an OS error and reuse
1449 // the error handling below.
1450 os_error = errSecCreateChainFailed;
1451 break;
1453 CERT_AddCertToListTail(*result_certs, nss_cert);
1457 if (os_error == noErr) {
1458 core->AddCertProvidedEvent(chain.size());
1459 return SECSuccess;
1462 OSSTATUS_LOG(WARNING, os_error)
1463 << "Client cert found, but could not be used";
1464 if (*result_certs) {
1465 CERT_DestroyCertList(*result_certs);
1466 *result_certs = NULL;
1468 if (*result_private_key)
1469 *result_private_key = NULL;
1470 if (private_key)
1471 CFRelease(private_key);
1474 // Send no client certificate.
1475 core->AddCertProvidedEvent(0);
1476 return SECFailure;
1479 core->nss_handshake_state_.cert_authorities.clear();
1481 // Retrieve the cert issuers accepted by the server.
1482 std::vector<CertPrincipal> valid_issuers;
1483 int n = ca_names->nnames;
1484 for (int i = 0; i < n; i++) {
1485 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1486 reinterpret_cast<const char*>(ca_names->names[i].data),
1487 static_cast<size_t>(ca_names->names[i].len)));
1490 // Update the network task runner's view of the handshake state now that
1491 // server certificate request has been recorded.
1492 core->PostOrRunCallback(
1493 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1494 core->nss_handshake_state_));
1496 // Tell NSS to suspend the client authentication. We will then abort the
1497 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1498 return SECWouldBlock;
1499 #else
1500 return SECFailure;
1501 #endif
1504 #elif defined(OS_IOS)
1506 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1507 void* arg,
1508 PRFileDesc* socket,
1509 CERTDistNames* ca_names,
1510 CERTCertificate** result_certificate,
1511 SECKEYPrivateKey** result_private_key) {
1512 Core* core = reinterpret_cast<Core*>(arg);
1513 DCHECK(core->OnNSSTaskRunner());
1515 core->PostOrRunCallback(
1516 FROM_HERE,
1517 base::Bind(&AddLogEvent, core->weak_net_log_,
1518 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1520 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1521 LOG(WARNING) << "Client auth is not supported";
1523 // Never send a certificate.
1524 core->AddCertProvidedEvent(0);
1525 return SECFailure;
1528 #else // NSS_PLATFORM_CLIENT_AUTH
1530 // static
1531 // Based on Mozilla's NSS_GetClientAuthData.
1532 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1533 void* arg,
1534 PRFileDesc* socket,
1535 CERTDistNames* ca_names,
1536 CERTCertificate** result_certificate,
1537 SECKEYPrivateKey** result_private_key) {
1538 Core* core = reinterpret_cast<Core*>(arg);
1539 DCHECK(core->OnNSSTaskRunner());
1541 core->PostOrRunCallback(
1542 FROM_HERE,
1543 base::Bind(&AddLogEvent, core->weak_net_log_,
1544 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1546 // Regular client certificate requested.
1547 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1548 void* wincx = SSL_RevealPinArg(socket);
1550 if (core->ssl_config_.send_client_cert) {
1551 // Second pass: a client certificate should have been selected.
1552 if (core->ssl_config_.client_cert.get()) {
1553 CERTCertificate* cert =
1554 CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
1555 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1556 if (privkey) {
1557 // TODO(jsorianopastor): We should wait for server certificate
1558 // verification before sending our credentials. See
1559 // http://crbug.com/13934.
1560 *result_certificate = cert;
1561 *result_private_key = privkey;
1562 // A cert_count of -1 means the number of certificates is unknown.
1563 // NSS will construct the certificate chain.
1564 core->AddCertProvidedEvent(-1);
1566 return SECSuccess;
1568 LOG(WARNING) << "Client cert found without private key";
1570 // Send no client certificate.
1571 core->AddCertProvidedEvent(0);
1572 return SECFailure;
1575 // First pass: client certificate is needed.
1576 core->nss_handshake_state_.cert_authorities.clear();
1578 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1579 // the server and save them in |cert_authorities|.
1580 for (int i = 0; i < ca_names->nnames; i++) {
1581 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1582 reinterpret_cast<const char*>(ca_names->names[i].data),
1583 static_cast<size_t>(ca_names->names[i].len)));
1586 // Update the network task runner's view of the handshake state now that
1587 // server certificate request has been recorded.
1588 core->PostOrRunCallback(
1589 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1590 core->nss_handshake_state_));
1592 // Tell NSS to suspend the client authentication. We will then abort the
1593 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1594 return SECWouldBlock;
1596 #endif // NSS_PLATFORM_CLIENT_AUTH
1598 // static
1599 SECStatus SSLClientSocketNSS::Core::CanFalseStartCallback(
1600 PRFileDesc* socket,
1601 void* arg,
1602 PRBool* can_false_start) {
1603 // If the server doesn't support NPN or ALPN, then we don't do False
1604 // Start with it.
1605 PRBool negotiated_extension;
1606 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1607 ssl_app_layer_protocol_xtn,
1608 &negotiated_extension);
1609 if (rv != SECSuccess || !negotiated_extension) {
1610 rv = SSL_HandshakeNegotiatedExtension(socket,
1611 ssl_next_proto_nego_xtn,
1612 &negotiated_extension);
1614 if (rv != SECSuccess || !negotiated_extension) {
1615 *can_false_start = PR_FALSE;
1616 return SECSuccess;
1619 SSLChannelInfo channel_info;
1620 SECStatus ok =
1621 SSL_GetChannelInfo(socket, &channel_info, sizeof(channel_info));
1622 if (ok != SECSuccess || channel_info.length != sizeof(channel_info) ||
1623 channel_info.protocolVersion < SSL_LIBRARY_VERSION_TLS_1_2 ||
1624 !IsSecureTLSCipherSuite(channel_info.cipherSuite)) {
1625 *can_false_start = PR_FALSE;
1626 return SECSuccess;
1629 return SSL_RecommendedCanFalseStart(socket, can_false_start);
1632 // static
1633 void SSLClientSocketNSS::Core::HandshakeCallback(
1634 PRFileDesc* socket,
1635 void* arg) {
1636 Core* core = reinterpret_cast<Core*>(arg);
1637 DCHECK(core->OnNSSTaskRunner());
1639 core->handshake_callback_called_ = true;
1640 if (core->false_started_) {
1641 core->false_started_ = false;
1642 // If the connection was False Started, then at the time of this callback,
1643 // the peer's certificate will have been verified or the caller will have
1644 // accepted the error.
1645 // This is guaranteed when using False Start because this callback will
1646 // not be invoked until processing the peer's Finished message, which
1647 // will only happen in a PR_Read/PR_Write call, which can only happen
1648 // after the peer's certificate is verified.
1649 SSL_CacheSessionUnlocked(socket);
1651 // Additionally, when False Starting, DoHandshake() will have already
1652 // called HandshakeSucceeded(), so return now.
1653 return;
1655 core->HandshakeSucceeded();
1658 void SSLClientSocketNSS::Core::HandshakeSucceeded() {
1659 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1660 tracked_objects::ScopedTracker tracking_profile(
1661 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1662 "424386 SSLClientSocketNSS::Core::HandshakeSucceeded"));
1664 DCHECK(OnNSSTaskRunner());
1666 PRBool last_handshake_resumed;
1667 SECStatus rv = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed);
1668 if (rv == SECSuccess && last_handshake_resumed) {
1669 nss_handshake_state_.resumed_handshake = true;
1670 } else {
1671 nss_handshake_state_.resumed_handshake = false;
1674 RecordChannelIDSupportOnNSSTaskRunner();
1675 UpdateServerCert();
1676 UpdateSignedCertTimestamps();
1677 UpdateStapledOCSPResponse();
1678 UpdateConnectionStatus();
1679 UpdateNextProto();
1680 UpdateExtensionUsed();
1682 // Update the network task runners view of the handshake state whenever
1683 // a handshake has completed.
1684 PostOrRunCallback(
1685 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
1686 nss_handshake_state_));
1689 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error) {
1690 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1691 tracked_objects::ScopedTracker tracking_profile(
1692 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1693 "424386 SSLClientSocketNSS::Core::HandleNSSError"));
1695 DCHECK(OnNSSTaskRunner());
1697 int net_error = MapNSSClientError(nss_error);
1699 #if defined(OS_WIN)
1700 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1701 // os_cert_handle() as an optimization. However, if the certificate
1702 // private key is stored on a smart card, and the smart card is removed,
1703 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1704 // preventing client certificate authentication. Because the
1705 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1706 // caching in X509Certificate, this failure ends up preventing client
1707 // certificate authentication with the same certificate for all future
1708 // attempts, even after the smart card has been re-inserted. By setting
1709 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1710 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1711 // the certificate on the next attempt, which should succeed if the smart
1712 // card has been re-inserted, or will typically prompt the user to
1713 // re-insert the smart card if not.
1714 if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY ||
1715 net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) &&
1716 ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
1717 CertSetCertificateContextProperty(
1718 ssl_config_.client_cert->os_cert_handle(),
1719 CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL);
1721 #endif
1723 return net_error;
1726 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1727 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1728 tracked_objects::ScopedTracker tracking_profile(
1729 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1730 "424386 SSLClientSocketNSS::Core::DoHandshakeLoop"));
1732 DCHECK(OnNSSTaskRunner());
1734 int rv = last_io_result;
1735 do {
1736 // Default to STATE_NONE for next state.
1737 State state = next_handshake_state_;
1738 GotoState(STATE_NONE);
1740 switch (state) {
1741 case STATE_HANDSHAKE:
1742 rv = DoHandshake();
1743 break;
1744 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1745 rv = DoGetDBCertComplete(rv);
1746 break;
1747 case STATE_NONE:
1748 default:
1749 rv = ERR_UNEXPECTED;
1750 LOG(DFATAL) << "unexpected state " << state;
1751 break;
1754 // Do the actual network I/O
1755 bool network_moved = DoTransportIO();
1756 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1757 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1758 // special case we keep looping even if rv is ERR_IO_PENDING because
1759 // the transport IO may allow DoHandshake to make progress.
1760 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1761 rv = OK; // This causes us to stay in the loop.
1763 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1764 return rv;
1767 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1768 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1769 tracked_objects::ScopedTracker tracking_profile(
1770 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1771 "424386 SSLClientSocketNSS::Core::DoReadLoop"));
1773 DCHECK(OnNSSTaskRunner());
1774 DCHECK(false_started_ || handshake_callback_called_);
1775 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1777 if (result < 0)
1778 return result;
1780 if (!nss_bufs_) {
1781 LOG(DFATAL) << "!nss_bufs_";
1782 int rv = ERR_UNEXPECTED;
1783 PostOrRunCallback(
1784 FROM_HERE,
1785 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1786 NetLog::TYPE_SSL_READ_ERROR,
1787 CreateNetLogSSLErrorCallback(rv, 0)));
1788 return rv;
1791 bool network_moved;
1792 int rv;
1793 do {
1794 rv = DoPayloadRead();
1795 network_moved = DoTransportIO();
1796 } while (rv == ERR_IO_PENDING && network_moved);
1798 return rv;
1801 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1802 DCHECK(OnNSSTaskRunner());
1803 DCHECK(false_started_ || handshake_callback_called_);
1804 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1806 if (result < 0)
1807 return result;
1809 if (!nss_bufs_) {
1810 LOG(DFATAL) << "!nss_bufs_";
1811 int rv = ERR_UNEXPECTED;
1812 PostOrRunCallback(
1813 FROM_HERE,
1814 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1815 NetLog::TYPE_SSL_READ_ERROR,
1816 CreateNetLogSSLErrorCallback(rv, 0)));
1817 return rv;
1820 bool network_moved;
1821 int rv;
1822 do {
1823 rv = DoPayloadWrite();
1824 network_moved = DoTransportIO();
1825 } while (rv == ERR_IO_PENDING && network_moved);
1827 LeaveFunction(rv);
1828 return rv;
1831 int SSLClientSocketNSS::Core::DoHandshake() {
1832 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1833 tracked_objects::ScopedTracker tracking_profile(
1834 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1835 "424386 SSLClientSocketNSS::Core::DoHandshake"));
1837 DCHECK(OnNSSTaskRunner());
1839 int net_error = OK;
1840 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1842 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1843 tracked_objects::ScopedTracker tracking_profile1(
1844 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1845 "424386 SSLClientSocketNSS::Core::DoHandshake 1"));
1847 // Note: this function may be called multiple times during the handshake, so
1848 // even though channel id and client auth are separate else cases, they can
1849 // both be used during a single SSL handshake.
1850 if (channel_id_needed_) {
1851 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1852 net_error = ERR_IO_PENDING;
1853 } else if (client_auth_cert_needed_) {
1854 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1855 PostOrRunCallback(
1856 FROM_HERE,
1857 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1858 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1859 CreateNetLogSSLErrorCallback(net_error, 0)));
1861 // If the handshake already succeeded (because the server requests but
1862 // doesn't require a client cert), we need to invalidate the SSL session
1863 // so that we won't try to resume the non-client-authenticated session in
1864 // the next handshake. This will cause the server to ask for a client
1865 // cert again.
1866 if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess)
1867 LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError();
1868 } else if (rv == SECSuccess) {
1869 if (!handshake_callback_called_) {
1870 false_started_ = true;
1871 HandshakeSucceeded();
1873 } else {
1874 PRErrorCode prerr = PR_GetError();
1875 net_error = HandleNSSError(prerr);
1877 // If not done, stay in this state
1878 if (net_error == ERR_IO_PENDING) {
1879 GotoState(STATE_HANDSHAKE);
1880 } else {
1881 PostOrRunCallback(
1882 FROM_HERE,
1883 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1884 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1885 CreateNetLogSSLErrorCallback(net_error, prerr)));
1889 return net_error;
1892 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1893 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1894 tracked_objects::ScopedTracker tracking_profile(
1895 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1896 "424386 SSLClientSocketNSS::Core::DoGetDBCertComplete"));
1898 SECStatus rv;
1899 PostOrRunCallback(
1900 FROM_HERE,
1901 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1902 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1904 channel_id_needed_ = false;
1906 if (result != OK)
1907 return result;
1909 SECKEYPublicKey* public_key;
1910 SECKEYPrivateKey* private_key;
1911 int error = ImportChannelIDKeys(&public_key, &private_key);
1912 if (error != OK)
1913 return error;
1915 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
1916 if (rv != SECSuccess)
1917 return MapNSSError(PORT_GetError());
1919 SetChannelIDProvided();
1920 GotoState(STATE_HANDSHAKE);
1921 return OK;
1924 int SSLClientSocketNSS::Core::DoPayloadRead() {
1925 DCHECK(OnNSSTaskRunner());
1926 DCHECK(user_read_buf_.get());
1927 DCHECK_GT(user_read_buf_len_, 0);
1929 int rv;
1930 // If a previous greedy read resulted in an error that was not consumed (eg:
1931 // due to the caller having read some data successfully), then return that
1932 // pending error now.
1933 if (pending_read_result_ != kNoPendingReadResult) {
1934 rv = pending_read_result_;
1935 PRErrorCode prerr = pending_read_nss_error_;
1936 pending_read_result_ = kNoPendingReadResult;
1937 pending_read_nss_error_ = 0;
1939 if (rv == 0) {
1940 PostOrRunCallback(
1941 FROM_HERE,
1942 base::Bind(&LogByteTransferEvent, weak_net_log_,
1943 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1944 scoped_refptr<IOBuffer>(user_read_buf_)));
1945 } else {
1946 PostOrRunCallback(
1947 FROM_HERE,
1948 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1949 NetLog::TYPE_SSL_READ_ERROR,
1950 CreateNetLogSSLErrorCallback(rv, prerr)));
1952 return rv;
1955 // Perform a greedy read, attempting to read as much as the caller has
1956 // requested. In the current NSS implementation, PR_Read will return
1957 // exactly one SSL application data record's worth of data per invocation.
1958 // The record size is dictated by the server, and may be noticeably smaller
1959 // than the caller's buffer. This may be as little as a single byte, if the
1960 // server is performing 1/n-1 record splitting.
1962 // However, this greedy read may result in renegotiations/re-handshakes
1963 // happening or may lead to some data being read, followed by an EOF (such as
1964 // a TLS close-notify). If at least some data was read, then that result
1965 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1966 // data was read, it's safe to return the error or EOF immediately.
1967 int total_bytes_read = 0;
1968 do {
1969 rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
1970 user_read_buf_len_ - total_bytes_read);
1971 if (rv > 0)
1972 total_bytes_read += rv;
1973 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1974 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1975 PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
1976 amount_in_read_buffer));
1978 if (total_bytes_read == user_read_buf_len_) {
1979 // The caller's entire request was satisfied without error. No further
1980 // processing needed.
1981 rv = total_bytes_read;
1982 } else {
1983 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1984 // immediately, while the NSPR/NSS errors are still available in
1985 // thread-local storage. However, the handled/remapped error code should
1986 // only be returned if no application data was already read; if it was, the
1987 // error code should be deferred until the next call of DoPayloadRead.
1989 // If no data was read, |*next_result| will point to the return value of
1990 // this function. If at least some data was read, |*next_result| will point
1991 // to |pending_read_error_|, to be returned in a future call to
1992 // DoPayloadRead() (e.g.: after the current data is handled).
1993 int* next_result = &rv;
1994 if (total_bytes_read > 0) {
1995 pending_read_result_ = rv;
1996 rv = total_bytes_read;
1997 next_result = &pending_read_result_;
2000 if (client_auth_cert_needed_) {
2001 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
2002 pending_read_nss_error_ = 0;
2003 } else if (*next_result < 0) {
2004 // If *next_result == 0, then that indicates EOF, and no special error
2005 // handling is needed.
2006 pending_read_nss_error_ = PR_GetError();
2007 *next_result = HandleNSSError(pending_read_nss_error_);
2008 if (rv > 0 && *next_result == ERR_IO_PENDING) {
2009 // If at least some data was read from PR_Read(), do not treat
2010 // insufficient data as an error to return in the next call to
2011 // DoPayloadRead() - instead, let the call fall through to check
2012 // PR_Read() again. This is because DoTransportIO() may complete
2013 // in between the next call to DoPayloadRead(), and thus it is
2014 // important to check PR_Read() on subsequent invocations to see
2015 // if a complete record may now be read.
2016 pending_read_nss_error_ = 0;
2017 pending_read_result_ = kNoPendingReadResult;
2022 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
2024 if (rv >= 0) {
2025 PostOrRunCallback(
2026 FROM_HERE,
2027 base::Bind(&LogByteTransferEvent, weak_net_log_,
2028 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
2029 scoped_refptr<IOBuffer>(user_read_buf_)));
2030 } else if (rv != ERR_IO_PENDING) {
2031 PostOrRunCallback(
2032 FROM_HERE,
2033 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2034 NetLog::TYPE_SSL_READ_ERROR,
2035 CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
2036 pending_read_nss_error_ = 0;
2038 return rv;
2041 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2042 DCHECK(OnNSSTaskRunner());
2044 DCHECK(user_write_buf_.get());
2046 int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2047 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
2048 int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2049 // PR_Write could potentially consume the unhandled data in the memio read
2050 // buffer if a renegotiation is in progress. If the buffer is consumed,
2051 // notify the latest buffer size to NetworkRunner.
2052 if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
2053 PostOrRunCallback(
2054 FROM_HERE,
2055 base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
2057 if (rv >= 0) {
2058 PostOrRunCallback(
2059 FROM_HERE,
2060 base::Bind(&LogByteTransferEvent, weak_net_log_,
2061 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
2062 scoped_refptr<IOBuffer>(user_write_buf_)));
2063 return rv;
2065 PRErrorCode prerr = PR_GetError();
2066 if (prerr == PR_WOULD_BLOCK_ERROR)
2067 return ERR_IO_PENDING;
2069 rv = HandleNSSError(prerr);
2070 PostOrRunCallback(
2071 FROM_HERE,
2072 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2073 NetLog::TYPE_SSL_WRITE_ERROR,
2074 CreateNetLogSSLErrorCallback(rv, prerr)));
2075 return rv;
2078 // Do as much network I/O as possible between the buffer and the
2079 // transport socket. Return true if some I/O performed, false
2080 // otherwise (error or ERR_IO_PENDING).
2081 bool SSLClientSocketNSS::Core::DoTransportIO() {
2082 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2083 tracked_objects::ScopedTracker tracking_profile(
2084 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2085 "424386 SSLClientSocketNSS::Core::DoTransportIO"));
2087 DCHECK(OnNSSTaskRunner());
2089 bool network_moved = false;
2090 if (nss_bufs_ != NULL) {
2091 int rv;
2092 // Read and write as much data as we can. The loop is neccessary
2093 // because Write() may return synchronously.
2094 do {
2095 rv = BufferSend();
2096 if (rv != ERR_IO_PENDING && rv != 0)
2097 network_moved = true;
2098 } while (rv > 0);
2099 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
2100 network_moved = true;
2102 return network_moved;
2105 int SSLClientSocketNSS::Core::BufferRecv() {
2106 DCHECK(OnNSSTaskRunner());
2108 if (transport_recv_busy_)
2109 return ERR_IO_PENDING;
2111 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2112 // determine how much data NSS wants to read. If NSS was not blocked,
2113 // this will return 0.
2114 int requested = memio_GetReadRequest(nss_bufs_);
2115 if (requested == 0) {
2116 // This is not a perfect match of error codes, as no operation is
2117 // actually pending. However, returning 0 would be interpreted as a
2118 // possible sign of EOF, which is also an inappropriate match.
2119 return ERR_IO_PENDING;
2122 char* buf;
2123 int nb = memio_GetReadParams(nss_bufs_, &buf);
2124 int rv;
2125 if (!nb) {
2126 // buffer too full to read into, so no I/O possible at moment
2127 rv = ERR_IO_PENDING;
2128 } else {
2129 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
2130 if (OnNetworkTaskRunner()) {
2131 rv = DoBufferRecv(read_buffer.get(), nb);
2132 } else {
2133 bool posted = network_task_runner_->PostTask(
2134 FROM_HERE,
2135 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
2136 nb));
2137 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2140 if (rv == ERR_IO_PENDING) {
2141 transport_recv_busy_ = true;
2142 } else {
2143 if (rv > 0) {
2144 memcpy(buf, read_buffer->data(), rv);
2145 } else if (rv == 0) {
2146 transport_recv_eof_ = true;
2148 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
2151 return rv;
2154 // Return 0 if nss_bufs_ was empty,
2155 // > 0 for bytes transferred immediately,
2156 // < 0 for error (or the non-error ERR_IO_PENDING).
2157 int SSLClientSocketNSS::Core::BufferSend() {
2158 DCHECK(OnNSSTaskRunner());
2160 if (transport_send_busy_)
2161 return ERR_IO_PENDING;
2163 const char* buf1;
2164 const char* buf2;
2165 unsigned int len1, len2;
2166 if (memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2)) {
2167 // It is important this return synchronously to prevent spinning infinitely
2168 // in the off-thread NSS case. The error code itself is ignored, so just
2169 // return ERR_ABORTED. See https://crbug.com/381160.
2170 return ERR_ABORTED;
2172 const unsigned int len = len1 + len2;
2174 int rv = 0;
2175 if (len) {
2176 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
2177 memcpy(send_buffer->data(), buf1, len1);
2178 memcpy(send_buffer->data() + len1, buf2, len2);
2180 if (OnNetworkTaskRunner()) {
2181 rv = DoBufferSend(send_buffer.get(), len);
2182 } else {
2183 bool posted = network_task_runner_->PostTask(
2184 FROM_HERE,
2185 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
2186 len));
2187 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2190 if (rv == ERR_IO_PENDING) {
2191 transport_send_busy_ = true;
2192 } else {
2193 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
2197 return rv;
2200 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
2201 DCHECK(OnNSSTaskRunner());
2203 if (next_handshake_state_ == STATE_HANDSHAKE) {
2204 OnHandshakeIOComplete(result);
2205 return;
2208 // Network layer received some data, check if client requested to read
2209 // decrypted data.
2210 if (!user_read_buf_.get())
2211 return;
2213 int rv = DoReadLoop(result);
2214 if (rv != ERR_IO_PENDING)
2215 DoReadCallback(rv);
2218 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
2219 DCHECK(OnNSSTaskRunner());
2221 if (next_handshake_state_ == STATE_HANDSHAKE) {
2222 OnHandshakeIOComplete(result);
2223 return;
2226 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2227 // handshake is in progress.
2228 int rv_read = ERR_IO_PENDING;
2229 int rv_write = ERR_IO_PENDING;
2230 bool network_moved;
2231 do {
2232 if (user_read_buf_.get())
2233 rv_read = DoPayloadRead();
2234 if (user_write_buf_.get())
2235 rv_write = DoPayloadWrite();
2236 network_moved = DoTransportIO();
2237 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
2238 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
2240 // If the parent SSLClientSocketNSS is deleted during the processing of the
2241 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2242 // will be detached (and possibly deleted). Guard against deletion by taking
2243 // an extra reference, then check if the Core was detached before invoking the
2244 // next callback.
2245 scoped_refptr<Core> guard(this);
2246 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
2247 DoReadCallback(rv_read);
2249 if (OnNetworkTaskRunner() && detached_)
2250 return;
2252 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
2253 DoWriteCallback(rv_write);
2256 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2257 // handshake. This requires network IO, which in turn calls
2258 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2259 // winds its way through the state machine and ends up being passed to the
2260 // callback. For Read() and Write(), that's what we want. But for Connect(),
2261 // the caller expects OK (i.e. 0) for success.
2262 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
2263 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2264 tracked_objects::ScopedTracker tracking_profile(
2265 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2266 "424386 SSLClientSocketNSS::Core::DoConnectCallback"));
2268 DCHECK(OnNSSTaskRunner());
2269 DCHECK_NE(rv, ERR_IO_PENDING);
2270 DCHECK(!user_connect_callback_.is_null());
2272 base::Closure c = base::Bind(
2273 base::ResetAndReturn(&user_connect_callback_),
2274 rv > OK ? OK : rv);
2275 PostOrRunCallback(FROM_HERE, c);
2278 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
2279 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2280 tracked_objects::ScopedTracker tracking_profile(
2281 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2282 "424386 SSLClientSocketNSS::Core::DoReadCallback"));
2284 DCHECK(OnNSSTaskRunner());
2285 DCHECK_NE(ERR_IO_PENDING, rv);
2286 DCHECK(!user_read_callback_.is_null());
2288 user_read_buf_ = NULL;
2289 user_read_buf_len_ = 0;
2290 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2291 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2292 // the network task runner.
2293 PostOrRunCallback(
2294 FROM_HERE,
2295 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2296 PostOrRunCallback(
2297 FROM_HERE,
2298 base::Bind(&Core::DidNSSRead, this, rv));
2299 PostOrRunCallback(
2300 FROM_HERE,
2301 base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
2304 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
2305 DCHECK(OnNSSTaskRunner());
2306 DCHECK_NE(ERR_IO_PENDING, rv);
2307 DCHECK(!user_write_callback_.is_null());
2309 // Since Run may result in Write being called, clear |user_write_callback_|
2310 // up front.
2311 user_write_buf_ = NULL;
2312 user_write_buf_len_ = 0;
2313 // Update buffer status because DoWriteLoop called DoTransportIO which may
2314 // perform read operations.
2315 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2316 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2317 // the network task runner.
2318 PostOrRunCallback(
2319 FROM_HERE,
2320 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2321 PostOrRunCallback(
2322 FROM_HERE,
2323 base::Bind(&Core::DidNSSWrite, this, rv));
2324 PostOrRunCallback(
2325 FROM_HERE,
2326 base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
2329 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
2330 void* arg,
2331 PRFileDesc* socket,
2332 SECKEYPublicKey **out_public_key,
2333 SECKEYPrivateKey **out_private_key) {
2334 Core* core = reinterpret_cast<Core*>(arg);
2335 DCHECK(core->OnNSSTaskRunner());
2337 core->PostOrRunCallback(
2338 FROM_HERE,
2339 base::Bind(&AddLogEvent, core->weak_net_log_,
2340 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
2342 // We have negotiated the TLS channel ID extension.
2343 core->channel_id_xtn_negotiated_ = true;
2344 std::string host = core->host_and_port_.host();
2345 int error = ERR_UNEXPECTED;
2346 if (core->OnNetworkTaskRunner()) {
2347 error = core->DoGetChannelID(host);
2348 } else {
2349 bool posted = core->network_task_runner_->PostTask(
2350 FROM_HERE,
2351 base::Bind(
2352 IgnoreResult(&Core::DoGetChannelID),
2353 core, host));
2354 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
2357 if (error == ERR_IO_PENDING) {
2358 // Asynchronous case.
2359 core->channel_id_needed_ = true;
2360 return SECWouldBlock;
2363 core->PostOrRunCallback(
2364 FROM_HERE,
2365 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
2366 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
2367 SECStatus rv = SECSuccess;
2368 if (error == OK) {
2369 // Synchronous success.
2370 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
2371 if (result == OK)
2372 core->SetChannelIDProvided();
2373 else
2374 rv = SECFailure;
2375 } else {
2376 rv = SECFailure;
2379 return rv;
2382 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
2383 SECKEYPrivateKey** key) {
2384 // Set the certificate.
2385 SECItem cert_item;
2386 cert_item.data = (unsigned char*) domain_bound_cert_.data();
2387 cert_item.len = domain_bound_cert_.size();
2388 ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2389 &cert_item,
2390 NULL,
2391 PR_FALSE,
2392 PR_TRUE));
2393 if (cert == NULL)
2394 return MapNSSError(PORT_GetError());
2396 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
2397 // Set the private key.
2398 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2399 slot.get(),
2400 ChannelIDService::kEPKIPassword,
2401 reinterpret_cast<const unsigned char*>(
2402 domain_bound_private_key_.data()),
2403 domain_bound_private_key_.size(),
2404 &cert->subjectPublicKeyInfo,
2405 false,
2406 false,
2407 key,
2408 public_key)) {
2409 int error = MapNSSError(PORT_GetError());
2410 return error;
2413 return OK;
2416 void SSLClientSocketNSS::Core::UpdateServerCert() {
2417 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
2418 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
2419 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
2420 if (nss_handshake_state_.server_cert.get()) {
2421 // Since this will be called asynchronously on another thread, it needs to
2422 // own a reference to the certificate.
2423 NetLog::ParametersCallback net_log_callback =
2424 base::Bind(&NetLogX509CertificateCallback,
2425 nss_handshake_state_.server_cert);
2426 PostOrRunCallback(
2427 FROM_HERE,
2428 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2429 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
2430 net_log_callback));
2434 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
2435 const SECItem* signed_cert_timestamps =
2436 SSL_PeerSignedCertTimestamps(nss_fd_);
2438 if (!signed_cert_timestamps || !signed_cert_timestamps->len)
2439 return;
2441 nss_handshake_state_.sct_list_from_tls_extension = std::string(
2442 reinterpret_cast<char*>(signed_cert_timestamps->data),
2443 signed_cert_timestamps->len);
2446 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2447 PRBool ocsp_requested = PR_FALSE;
2448 SSL_OptionGet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, &ocsp_requested);
2449 const SECItemArray* ocsp_responses =
2450 SSL_PeerStapledOCSPResponses(nss_fd_);
2451 bool ocsp_responses_present = ocsp_responses && ocsp_responses->len;
2452 if (ocsp_requested)
2453 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present);
2454 if (!ocsp_responses_present)
2455 return;
2457 nss_handshake_state_.stapled_ocsp_response = std::string(
2458 reinterpret_cast<char*>(ocsp_responses->items[0].data),
2459 ocsp_responses->items[0].len);
2461 if (IsOCSPStaplingSupported()) {
2462 #if defined(OS_WIN)
2463 if (nss_handshake_state_.server_cert.get()) {
2464 CRYPT_DATA_BLOB ocsp_response_blob;
2465 ocsp_response_blob.cbData = ocsp_responses->items[0].len;
2466 ocsp_response_blob.pbData = ocsp_responses->items[0].data;
2467 BOOL ok = CertSetCertificateContextProperty(
2468 nss_handshake_state_.server_cert->os_cert_handle(),
2469 CERT_OCSP_RESPONSE_PROP_ID,
2470 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
2471 &ocsp_response_blob);
2472 if (!ok) {
2473 VLOG(1) << "Failed to set OCSP response property: "
2474 << GetLastError();
2477 #elif defined(USE_NSS)
2478 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response =
2479 GetCacheOCSPResponseFromSideChannelFunction();
2481 cache_ocsp_response(
2482 CERT_GetDefaultCertDB(),
2483 nss_handshake_state_.server_cert_chain[0], PR_Now(),
2484 &ocsp_responses->items[0], NULL);
2485 #endif
2486 } // IsOCSPStaplingSupported()
2489 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2490 // Note: This function may be called multiple times for a single connection
2491 // if renegotiations occur.
2492 nss_handshake_state_.ssl_connection_status = 0;
2494 SSLChannelInfo channel_info;
2495 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2496 &channel_info, sizeof(channel_info));
2497 if (ok == SECSuccess &&
2498 channel_info.length == sizeof(channel_info) &&
2499 channel_info.cipherSuite) {
2500 nss_handshake_state_.ssl_connection_status |= channel_info.cipherSuite;
2502 nss_handshake_state_.ssl_connection_status |=
2503 (static_cast<int>(channel_info.compressionMethod) &
2504 SSL_CONNECTION_COMPRESSION_MASK) <<
2505 SSL_CONNECTION_COMPRESSION_SHIFT;
2507 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2508 if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) {
2509 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2510 // version 2.
2511 version = SSL_CONNECTION_VERSION_SSL2;
2512 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2513 version = SSL_CONNECTION_VERSION_SSL3;
2514 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_0) {
2515 version = SSL_CONNECTION_VERSION_TLS1;
2516 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
2517 version = SSL_CONNECTION_VERSION_TLS1_1;
2518 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_2) {
2519 version = SSL_CONNECTION_VERSION_TLS1_2;
2521 nss_handshake_state_.ssl_connection_status |=
2522 (version & SSL_CONNECTION_VERSION_MASK) <<
2523 SSL_CONNECTION_VERSION_SHIFT;
2526 PRBool peer_supports_renego_ext;
2527 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2528 &peer_supports_renego_ext);
2529 if (ok == SECSuccess) {
2530 if (!peer_supports_renego_ext) {
2531 nss_handshake_state_.ssl_connection_status |=
2532 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2533 // Log an informational message if the server does not support secure
2534 // renegotiation (RFC 5746).
2535 VLOG(1) << "The server " << host_and_port_.ToString()
2536 << " does not support the TLS renegotiation_info extension.";
2540 if (ssl_config_.version_fallback) {
2541 nss_handshake_state_.ssl_connection_status |=
2542 SSL_CONNECTION_VERSION_FALLBACK;
2546 void SSLClientSocketNSS::Core::UpdateNextProto() {
2547 uint8 buf[256];
2548 SSLNextProtoState state;
2549 unsigned buf_len;
2551 SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
2552 if (rv != SECSuccess)
2553 return;
2555 nss_handshake_state_.next_proto =
2556 std::string(reinterpret_cast<char*>(buf), buf_len);
2557 switch (state) {
2558 case SSL_NEXT_PROTO_NEGOTIATED:
2559 case SSL_NEXT_PROTO_SELECTED:
2560 nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
2561 break;
2562 case SSL_NEXT_PROTO_NO_OVERLAP:
2563 nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
2564 break;
2565 case SSL_NEXT_PROTO_NO_SUPPORT:
2566 nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
2567 break;
2568 default:
2569 NOTREACHED();
2570 break;
2574 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2575 PRBool negotiated_extension;
2576 SECStatus rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2577 ssl_app_layer_protocol_xtn,
2578 &negotiated_extension);
2579 if (rv == SECSuccess && negotiated_extension) {
2580 nss_handshake_state_.negotiation_extension_ = kExtensionALPN;
2581 } else {
2582 rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2583 ssl_next_proto_nego_xtn,
2584 &negotiated_extension);
2585 if (rv == SECSuccess && negotiated_extension) {
2586 nss_handshake_state_.negotiation_extension_ = kExtensionNPN;
2591 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2592 DCHECK(OnNSSTaskRunner());
2593 if (nss_handshake_state_.resumed_handshake)
2594 return;
2596 // Copy the NSS task runner-only state to the network task runner and
2597 // log histograms from there, since the histograms also need access to the
2598 // network task runner state.
2599 PostOrRunCallback(
2600 FROM_HERE,
2601 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
2602 this,
2603 channel_id_xtn_negotiated_,
2604 ssl_config_.channel_id_enabled,
2605 crypto::ECPrivateKey::IsSupported()));
2608 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2609 bool negotiated_channel_id,
2610 bool channel_id_enabled,
2611 bool supports_ecc) const {
2612 DCHECK(OnNetworkTaskRunner());
2614 RecordChannelIDSupport(channel_id_service_,
2615 negotiated_channel_id,
2616 channel_id_enabled,
2617 supports_ecc);
2620 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2621 DCHECK(OnNetworkTaskRunner());
2622 DCHECK_GT(len, 0);
2624 if (detached_)
2625 return ERR_ABORTED;
2627 int rv = transport_->socket()->Read(
2628 read_buffer, len,
2629 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2630 scoped_refptr<IOBuffer>(read_buffer)));
2632 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2633 nss_task_runner_->PostTask(
2634 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2635 scoped_refptr<IOBuffer>(read_buffer), rv));
2636 return rv;
2639 return rv;
2642 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2643 DCHECK(OnNetworkTaskRunner());
2644 DCHECK_GT(len, 0);
2646 if (detached_)
2647 return ERR_ABORTED;
2649 int rv = transport_->socket()->Write(
2650 send_buffer, len,
2651 base::Bind(&Core::BufferSendComplete,
2652 base::Unretained(this)));
2654 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2655 nss_task_runner_->PostTask(
2656 FROM_HERE,
2657 base::Bind(&Core::BufferSendComplete, this, rv));
2658 return rv;
2661 return rv;
2664 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string& host) {
2665 DCHECK(OnNetworkTaskRunner());
2667 if (detached_)
2668 return ERR_ABORTED;
2670 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2672 int rv = channel_id_service_->GetOrCreateChannelID(
2673 host,
2674 &domain_bound_private_key_,
2675 &domain_bound_cert_,
2676 base::Bind(&Core::OnGetChannelIDComplete, base::Unretained(this)),
2677 &domain_bound_cert_request_handle_);
2679 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2680 nss_task_runner_->PostTask(
2681 FROM_HERE,
2682 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2683 return ERR_IO_PENDING;
2686 return rv;
2689 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2690 const HandshakeState& state) {
2691 DCHECK(OnNetworkTaskRunner());
2692 network_handshake_state_ = state;
2695 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
2696 DCHECK(OnNetworkTaskRunner());
2697 unhandled_buffer_size_ = amount_in_read_buffer;
2700 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
2701 DCHECK(OnNetworkTaskRunner());
2702 DCHECK(nss_waiting_read_);
2703 nss_waiting_read_ = false;
2704 if (result <= 0) {
2705 nss_is_closed_ = true;
2706 } else {
2707 was_ever_used_ = true;
2711 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
2712 DCHECK(OnNetworkTaskRunner());
2713 DCHECK(nss_waiting_write_);
2714 nss_waiting_write_ = false;
2715 if (result < 0) {
2716 nss_is_closed_ = true;
2717 } else if (result > 0) {
2718 was_ever_used_ = true;
2722 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2723 if (!OnNSSTaskRunner()) {
2724 if (detached_)
2725 return;
2727 nss_task_runner_->PostTask(
2728 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2729 return;
2732 DCHECK(OnNSSTaskRunner());
2734 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2735 transport_send_busy_ = false;
2736 OnSendComplete(result);
2739 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2740 if (!OnNSSTaskRunner()) {
2741 if (detached_)
2742 return;
2744 nss_task_runner_->PostTask(
2745 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2746 return;
2749 DCHECK(OnNSSTaskRunner());
2751 int rv = DoHandshakeLoop(result);
2752 if (rv != ERR_IO_PENDING)
2753 DoConnectCallback(rv);
2756 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result) {
2757 DVLOG(1) << __FUNCTION__ << " " << result;
2758 DCHECK(OnNetworkTaskRunner());
2760 OnHandshakeIOComplete(result);
2763 void SSLClientSocketNSS::Core::BufferRecvComplete(
2764 IOBuffer* read_buffer,
2765 int result) {
2766 DCHECK(read_buffer);
2768 if (!OnNSSTaskRunner()) {
2769 if (detached_)
2770 return;
2772 nss_task_runner_->PostTask(
2773 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2774 scoped_refptr<IOBuffer>(read_buffer), result));
2775 return;
2778 DCHECK(OnNSSTaskRunner());
2780 if (result > 0) {
2781 char* buf;
2782 int nb = memio_GetReadParams(nss_bufs_, &buf);
2783 CHECK_GE(nb, result);
2784 memcpy(buf, read_buffer->data(), result);
2785 } else if (result == 0) {
2786 transport_recv_eof_ = true;
2789 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2790 transport_recv_busy_ = false;
2791 OnRecvComplete(result);
2794 void SSLClientSocketNSS::Core::PostOrRunCallback(
2795 const tracked_objects::Location& location,
2796 const base::Closure& task) {
2797 if (!OnNetworkTaskRunner()) {
2798 network_task_runner_->PostTask(
2799 FROM_HERE,
2800 base::Bind(&Core::PostOrRunCallback, this, location, task));
2801 return;
2804 if (detached_ || task.is_null())
2805 return;
2806 task.Run();
2809 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2810 PostOrRunCallback(
2811 FROM_HERE,
2812 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2813 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2814 NetLog::IntegerCallback("cert_count", cert_count)));
2817 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2818 PostOrRunCallback(
2819 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2820 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2821 nss_handshake_state_.channel_id_sent = true;
2822 // Update the network task runner's view of the handshake state now that
2823 // channel id has been sent.
2824 PostOrRunCallback(
2825 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2826 nss_handshake_state_));
2829 SSLClientSocketNSS::SSLClientSocketNSS(
2830 base::SequencedTaskRunner* nss_task_runner,
2831 scoped_ptr<ClientSocketHandle> transport_socket,
2832 const HostPortPair& host_and_port,
2833 const SSLConfig& ssl_config,
2834 const SSLClientSocketContext& context)
2835 : nss_task_runner_(nss_task_runner),
2836 transport_(transport_socket.Pass()),
2837 host_and_port_(host_and_port),
2838 ssl_config_(ssl_config),
2839 cert_verifier_(context.cert_verifier),
2840 cert_transparency_verifier_(context.cert_transparency_verifier),
2841 channel_id_service_(context.channel_id_service),
2842 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2843 completed_handshake_(false),
2844 next_handshake_state_(STATE_NONE),
2845 nss_fd_(NULL),
2846 net_log_(transport_->socket()->NetLog()),
2847 transport_security_state_(context.transport_security_state),
2848 policy_enforcer_(context.cert_policy_enforcer),
2849 valid_thread_id_(base::kInvalidThreadId) {
2850 EnterFunction("");
2851 InitCore();
2852 LeaveFunction("");
2855 SSLClientSocketNSS::~SSLClientSocketNSS() {
2856 EnterFunction("");
2857 Disconnect();
2858 LeaveFunction("");
2861 // static
2862 void SSLClientSocket::ClearSessionCache() {
2863 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2864 // bother initializing NSS just to clear an empty SSL session cache.
2865 if (!NSS_IsInitialized())
2866 return;
2868 SSL_ClearSessionCache();
2871 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
2872 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
2873 #endif
2875 // static
2876 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
2877 crypto::EnsureNSSInit();
2878 if (PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)) {
2879 return SSL_PROTOCOL_VERSION_TLS1_2;
2880 } else {
2881 return SSL_PROTOCOL_VERSION_TLS1_1;
2885 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2886 EnterFunction("");
2887 ssl_info->Reset();
2888 if (core_->state().server_cert_chain.empty() ||
2889 !core_->state().server_cert_chain[0]) {
2890 return false;
2893 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2894 ssl_info->cert = server_cert_verify_result_.verified_cert;
2896 AddSCTInfoToSSLInfo(ssl_info);
2898 ssl_info->connection_status =
2899 core_->state().ssl_connection_status;
2900 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2901 ssl_info->is_issued_by_known_root =
2902 server_cert_verify_result_.is_issued_by_known_root;
2903 ssl_info->client_cert_sent =
2904 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
2905 ssl_info->channel_id_sent = WasChannelIDSent();
2906 ssl_info->pinning_failure_log = pinning_failure_log_;
2908 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2909 core_->state().ssl_connection_status);
2910 SSLCipherSuiteInfo cipher_info;
2911 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2912 &cipher_info, sizeof(cipher_info));
2913 if (ok == SECSuccess) {
2914 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2915 } else {
2916 ssl_info->security_bits = -1;
2917 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2918 << " for cipherSuite " << cipher_suite;
2921 ssl_info->handshake_type = core_->state().resumed_handshake ?
2922 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2924 LeaveFunction("");
2925 return true;
2928 std::string SSLClientSocketNSS::GetSessionCacheKey() const {
2929 NOTIMPLEMENTED();
2930 return std::string();
2933 bool SSLClientSocketNSS::InSessionCache() const {
2934 // For now, always return true so that SSLConnectJobs are never held back.
2935 return true;
2938 void SSLClientSocketNSS::SetHandshakeCompletionCallback(
2939 const base::Closure& callback) {
2940 NOTIMPLEMENTED();
2943 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2944 SSLCertRequestInfo* cert_request_info) {
2945 EnterFunction("");
2946 cert_request_info->host_and_port = host_and_port_;
2947 cert_request_info->cert_authorities = core_->state().cert_authorities;
2948 LeaveFunction("");
2951 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2952 bool has_context,
2953 const base::StringPiece& context,
2954 unsigned char* out,
2955 unsigned int outlen) {
2956 if (!IsConnected())
2957 return ERR_SOCKET_NOT_CONNECTED;
2959 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2960 // the midst of a handshake.
2961 SECStatus result = SSL_ExportKeyingMaterial(
2962 nss_fd_, label.data(), label.size(), has_context,
2963 reinterpret_cast<const unsigned char*>(context.data()),
2964 context.length(), out, outlen);
2965 if (result != SECSuccess) {
2966 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2967 return MapNSSError(PORT_GetError());
2969 return OK;
2972 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
2973 if (!IsConnected())
2974 return ERR_SOCKET_NOT_CONNECTED;
2975 unsigned char buf[64];
2976 unsigned int len;
2977 SECStatus result = SSL_GetChannelBinding(nss_fd_,
2978 SSL_CHANNEL_BINDING_TLS_UNIQUE,
2979 buf, &len, arraysize(buf));
2980 if (result != SECSuccess) {
2981 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
2982 return MapNSSError(PORT_GetError());
2984 out->assign(reinterpret_cast<char*>(buf), len);
2985 return OK;
2988 SSLClientSocket::NextProtoStatus
2989 SSLClientSocketNSS::GetNextProto(std::string* proto) {
2990 *proto = core_->state().next_proto;
2991 return core_->state().next_proto_status;
2994 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2995 EnterFunction("");
2996 DCHECK(transport_.get());
2997 // It is an error to create an SSLClientSocket whose context has no
2998 // TransportSecurityState.
2999 DCHECK(transport_security_state_);
3000 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3001 DCHECK(user_connect_callback_.is_null());
3002 DCHECK(!callback.is_null());
3004 EnsureThreadIdAssigned();
3006 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
3008 int rv = Init();
3009 if (rv != OK) {
3010 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3011 return rv;
3014 rv = InitializeSSLOptions();
3015 if (rv != OK) {
3016 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3017 return rv;
3020 rv = InitializeSSLPeerName();
3021 if (rv != OK) {
3022 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3023 return rv;
3026 GotoState(STATE_HANDSHAKE);
3028 rv = DoHandshakeLoop(OK);
3029 if (rv == ERR_IO_PENDING) {
3030 user_connect_callback_ = callback;
3031 } else {
3032 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3035 LeaveFunction("");
3036 return rv > OK ? OK : rv;
3039 void SSLClientSocketNSS::Disconnect() {
3040 EnterFunction("");
3042 CHECK(CalledOnValidThread());
3044 // Shut down anything that may call us back.
3045 core_->Detach();
3046 verifier_.reset();
3047 transport_->socket()->Disconnect();
3049 // Reset object state.
3050 user_connect_callback_.Reset();
3051 server_cert_verify_result_.Reset();
3052 completed_handshake_ = false;
3053 start_cert_verification_time_ = base::TimeTicks();
3054 InitCore();
3056 LeaveFunction("");
3059 bool SSLClientSocketNSS::IsConnected() const {
3060 EnterFunction("");
3061 bool ret = completed_handshake_ &&
3062 (core_->HasPendingAsyncOperation() ||
3063 (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
3064 transport_->socket()->IsConnected());
3065 LeaveFunction("");
3066 return ret;
3069 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
3070 EnterFunction("");
3071 bool ret = completed_handshake_ &&
3072 !core_->HasPendingAsyncOperation() &&
3073 !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
3074 transport_->socket()->IsConnectedAndIdle();
3075 LeaveFunction("");
3076 return ret;
3079 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
3080 return transport_->socket()->GetPeerAddress(address);
3083 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
3084 return transport_->socket()->GetLocalAddress(address);
3087 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
3088 return net_log_;
3091 void SSLClientSocketNSS::SetSubresourceSpeculation() {
3092 if (transport_.get() && transport_->socket()) {
3093 transport_->socket()->SetSubresourceSpeculation();
3094 } else {
3095 NOTREACHED();
3099 void SSLClientSocketNSS::SetOmniboxSpeculation() {
3100 if (transport_.get() && transport_->socket()) {
3101 transport_->socket()->SetOmniboxSpeculation();
3102 } else {
3103 NOTREACHED();
3107 bool SSLClientSocketNSS::WasEverUsed() const {
3108 DCHECK(core_.get());
3110 return core_->WasEverUsed();
3113 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
3114 if (transport_.get() && transport_->socket()) {
3115 return transport_->socket()->UsingTCPFastOpen();
3117 NOTREACHED();
3118 return false;
3121 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
3122 const CompletionCallback& callback) {
3123 DCHECK(core_.get());
3124 DCHECK(!callback.is_null());
3126 EnterFunction(buf_len);
3127 int rv = core_->Read(buf, buf_len, callback);
3128 LeaveFunction(rv);
3130 return rv;
3133 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
3134 const CompletionCallback& callback) {
3135 DCHECK(core_.get());
3136 DCHECK(!callback.is_null());
3138 EnterFunction(buf_len);
3139 int rv = core_->Write(buf, buf_len, callback);
3140 LeaveFunction(rv);
3142 return rv;
3145 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
3146 return transport_->socket()->SetReceiveBufferSize(size);
3149 int SSLClientSocketNSS::SetSendBufferSize(int32 size) {
3150 return transport_->socket()->SetSendBufferSize(size);
3153 int SSLClientSocketNSS::Init() {
3154 EnterFunction("");
3155 // Initialize the NSS SSL library in a threadsafe way. This also
3156 // initializes the NSS base library.
3157 EnsureNSSSSLInit();
3158 if (!NSS_IsInitialized())
3159 return ERR_UNEXPECTED;
3160 #if defined(USE_NSS) || defined(OS_IOS)
3161 if (ssl_config_.cert_io_enabled) {
3162 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3163 // loop by MessageLoopForIO::current().
3164 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3165 EnsureNSSHttpIOInit();
3167 #endif
3169 LeaveFunction("");
3170 return OK;
3173 void SSLClientSocketNSS::InitCore() {
3174 core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
3175 nss_task_runner_.get(),
3176 transport_.get(),
3177 host_and_port_,
3178 ssl_config_,
3179 &net_log_,
3180 channel_id_service_);
3183 int SSLClientSocketNSS::InitializeSSLOptions() {
3184 // Transport connected, now hook it up to nss
3185 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
3186 if (nss_fd_ == NULL) {
3187 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
3190 // Grab pointer to buffers
3191 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
3193 /* Create SSL state machine */
3194 /* Push SSL onto our fake I/O socket */
3195 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_) == NULL) {
3196 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
3197 PR_Close(nss_fd_);
3198 nss_fd_ = NULL;
3199 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
3201 // TODO(port): set more ssl options! Check errors!
3203 int rv;
3205 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
3206 if (rv != SECSuccess) {
3207 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
3208 return ERR_UNEXPECTED;
3211 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
3212 if (rv != SECSuccess) {
3213 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3214 return ERR_UNEXPECTED;
3217 // Don't do V2 compatible hellos because they don't support TLS extensions.
3218 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
3219 if (rv != SECSuccess) {
3220 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3221 return ERR_UNEXPECTED;
3224 SSLVersionRange version_range;
3225 version_range.min = ssl_config_.version_min;
3226 version_range.max = ssl_config_.version_max;
3227 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
3228 if (rv != SECSuccess) {
3229 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
3230 return ERR_NO_SSL_VERSIONS_ENABLED;
3233 if (ssl_config_.version_fallback) {
3234 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALLBACK_SCSV, PR_TRUE);
3235 if (rv != SECSuccess) {
3236 LogFailedNSSFunction(
3237 net_log_, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
3241 for (std::vector<uint16>::const_iterator it =
3242 ssl_config_.disabled_cipher_suites.begin();
3243 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
3244 // This will fail if the specified cipher is not implemented by NSS, but
3245 // the failure is harmless.
3246 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
3249 // Support RFC 5077
3250 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
3251 if (rv != SECSuccess) {
3252 LogFailedNSSFunction(
3253 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3256 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
3257 ssl_config_.false_start_enabled);
3258 if (rv != SECSuccess)
3259 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3261 // We allow servers to request renegotiation. Since we're a client,
3262 // prohibiting this is rather a waste of time. Only servers are in a
3263 // position to prevent renegotiation attacks.
3264 // http://extendedsubset.com/?p=8
3266 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
3267 SSL_RENEGOTIATE_TRANSITIONAL);
3268 if (rv != SECSuccess) {
3269 LogFailedNSSFunction(
3270 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3273 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
3274 if (rv != SECSuccess)
3275 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3277 // Added in NSS 3.15
3278 #ifdef SSL_ENABLE_OCSP_STAPLING
3279 // Request OCSP stapling even on platforms that don't support it, in
3280 // order to extract Certificate Transparency information.
3281 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING,
3282 (IsOCSPStaplingSupported() ||
3283 ssl_config_.signed_cert_timestamps_enabled));
3284 if (rv != SECSuccess) {
3285 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3286 "SSL_ENABLE_OCSP_STAPLING");
3288 #endif
3290 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
3291 ssl_config_.signed_cert_timestamps_enabled);
3292 if (rv != SECSuccess) {
3293 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3294 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
3297 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
3298 if (rv != SECSuccess) {
3299 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3300 return ERR_UNEXPECTED;
3303 if (!core_->Init(nss_fd_, nss_bufs))
3304 return ERR_UNEXPECTED;
3306 // Tell SSL the hostname we're trying to connect to.
3307 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
3309 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3310 SSL_ResetHandshake(nss_fd_, PR_FALSE);
3312 return OK;
3315 int SSLClientSocketNSS::InitializeSSLPeerName() {
3316 // Tell NSS who we're connected to
3317 IPEndPoint peer_address;
3318 int err = transport_->socket()->GetPeerAddress(&peer_address);
3319 if (err != OK)
3320 return err;
3322 SockaddrStorage storage;
3323 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
3324 return ERR_ADDRESS_INVALID;
3326 PRNetAddr peername;
3327 memset(&peername, 0, sizeof(peername));
3328 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
3329 size_t len = std::min(static_cast<size_t>(storage.addr_len),
3330 sizeof(peername));
3331 memcpy(&peername, storage.addr, len);
3333 // Adjust the address family field for BSD, whose sockaddr
3334 // structure has a one-byte length and one-byte address family
3335 // field at the beginning. PRNetAddr has a two-byte address
3336 // family field at the beginning.
3337 peername.raw.family = storage.addr->sa_family;
3339 memio_SetPeerName(nss_fd_, &peername);
3341 // Set the peer ID for session reuse. This is necessary when we create an
3342 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3343 // rather than the destination server's address in that case.
3344 std::string peer_id = host_and_port_.ToString();
3345 // Append |ssl_session_cache_shard_| to the peer id. This is used to partition
3346 // the session cache for incognito mode.
3347 peer_id += "/" + ssl_session_cache_shard_;
3348 peer_id += "/";
3349 // Shard the session cache based on maximum protocol version. This causes
3350 // fallback connections to use a separate session cache.
3351 switch (ssl_config_.version_max) {
3352 case SSL_PROTOCOL_VERSION_SSL3:
3353 peer_id += "ssl3";
3354 break;
3355 case SSL_PROTOCOL_VERSION_TLS1:
3356 peer_id += "tls1";
3357 break;
3358 case SSL_PROTOCOL_VERSION_TLS1_1:
3359 peer_id += "tls1.1";
3360 break;
3361 case SSL_PROTOCOL_VERSION_TLS1_2:
3362 peer_id += "tls1.2";
3363 break;
3364 default:
3365 NOTREACHED();
3368 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
3369 if (rv != SECSuccess)
3370 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
3372 return OK;
3375 void SSLClientSocketNSS::DoConnectCallback(int rv) {
3376 EnterFunction(rv);
3377 DCHECK_NE(ERR_IO_PENDING, rv);
3378 DCHECK(!user_connect_callback_.is_null());
3380 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
3381 LeaveFunction("");
3384 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
3385 EnterFunction(result);
3386 int rv = DoHandshakeLoop(result);
3387 if (rv != ERR_IO_PENDING) {
3388 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3389 DoConnectCallback(rv);
3391 LeaveFunction("");
3394 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
3395 EnterFunction(last_io_result);
3396 int rv = last_io_result;
3397 do {
3398 // Default to STATE_NONE for next state.
3399 // (This is a quirk carried over from the windows
3400 // implementation. It makes reading the logs a bit harder.)
3401 // State handlers can and often do call GotoState just
3402 // to stay in the current state.
3403 State state = next_handshake_state_;
3404 GotoState(STATE_NONE);
3405 switch (state) {
3406 case STATE_HANDSHAKE:
3407 rv = DoHandshake();
3408 break;
3409 case STATE_HANDSHAKE_COMPLETE:
3410 rv = DoHandshakeComplete(rv);
3411 break;
3412 case STATE_VERIFY_CERT:
3413 DCHECK(rv == OK);
3414 rv = DoVerifyCert(rv);
3415 break;
3416 case STATE_VERIFY_CERT_COMPLETE:
3417 rv = DoVerifyCertComplete(rv);
3418 break;
3419 case STATE_NONE:
3420 default:
3421 rv = ERR_UNEXPECTED;
3422 LOG(DFATAL) << "unexpected state " << state;
3423 break;
3425 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
3426 LeaveFunction("");
3427 return rv;
3430 int SSLClientSocketNSS::DoHandshake() {
3431 EnterFunction("");
3432 int rv = core_->Connect(
3433 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3434 base::Unretained(this)));
3435 GotoState(STATE_HANDSHAKE_COMPLETE);
3437 LeaveFunction(rv);
3438 return rv;
3441 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
3442 EnterFunction(result);
3444 if (result == OK) {
3445 if (ssl_config_.version_fallback &&
3446 ssl_config_.version_max < ssl_config_.version_fallback_min) {
3447 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
3450 // SSL handshake is completed. Let's verify the certificate.
3451 GotoState(STATE_VERIFY_CERT);
3452 // Done!
3454 set_channel_id_sent(core_->state().channel_id_sent);
3455 set_signed_cert_timestamps_received(
3456 !core_->state().sct_list_from_tls_extension.empty());
3457 set_stapled_ocsp_response_received(
3458 !core_->state().stapled_ocsp_response.empty());
3459 set_negotiation_extension(core_->state().negotiation_extension_);
3461 LeaveFunction(result);
3462 return result;
3465 int SSLClientSocketNSS::DoVerifyCert(int result) {
3466 DCHECK(!core_->state().server_cert_chain.empty());
3467 DCHECK(core_->state().server_cert_chain[0]);
3469 GotoState(STATE_VERIFY_CERT_COMPLETE);
3471 // If the certificate is expected to be bad we can use the expectation as
3472 // the cert status.
3473 base::StringPiece der_cert(
3474 reinterpret_cast<char*>(
3475 core_->state().server_cert_chain[0]->derCert.data),
3476 core_->state().server_cert_chain[0]->derCert.len);
3477 CertStatus cert_status;
3478 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3479 DCHECK(start_cert_verification_time_.is_null());
3480 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3481 server_cert_verify_result_.Reset();
3482 server_cert_verify_result_.cert_status = cert_status;
3483 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3484 return OK;
3487 // We may have failed to create X509Certificate object if we are
3488 // running inside sandbox.
3489 if (!core_->state().server_cert.get()) {
3490 server_cert_verify_result_.Reset();
3491 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
3492 return ERR_CERT_INVALID;
3495 start_cert_verification_time_ = base::TimeTicks::Now();
3497 int flags = 0;
3498 if (ssl_config_.rev_checking_enabled)
3499 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
3500 if (ssl_config_.verify_ev_cert)
3501 flags |= CertVerifier::VERIFY_EV_CERT;
3502 if (ssl_config_.cert_io_enabled)
3503 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
3504 if (ssl_config_.rev_checking_required_local_anchors)
3505 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3506 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
3507 return verifier_->Verify(
3508 core_->state().server_cert.get(),
3509 host_and_port_.host(),
3510 flags,
3511 SSLConfigService::GetCRLSet().get(),
3512 &server_cert_verify_result_,
3513 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3514 base::Unretained(this)),
3515 net_log_);
3518 // Derived from AuthCertificateCallback() in
3519 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3520 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3521 verifier_.reset();
3523 if (!start_cert_verification_time_.is_null()) {
3524 base::TimeDelta verify_time =
3525 base::TimeTicks::Now() - start_cert_verification_time_;
3526 if (result == OK)
3527 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3528 else
3529 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3532 // We used to remember the intermediate CA certs in the NSS database
3533 // persistently. However, NSS opens a connection to the SQLite database
3534 // during NSS initialization and doesn't close the connection until NSS
3535 // shuts down. If the file system where the database resides is gone,
3536 // the database connection goes bad. What's worse, the connection won't
3537 // recover when the file system comes back. Until this NSS or SQLite bug
3538 // is fixed, we need to avoid using the NSS database for non-essential
3539 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3540 // http://crbug.com/15630 for more info.
3542 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3543 if (transport_security_state_ &&
3544 (result == OK ||
3545 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
3546 !transport_security_state_->CheckPublicKeyPins(
3547 host_and_port_.host(),
3548 server_cert_verify_result_.is_issued_by_known_root,
3549 server_cert_verify_result_.public_key_hashes,
3550 &pinning_failure_log_)) {
3551 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3554 if (result == OK) {
3555 // Only check Certificate Transparency if there were no other errors with
3556 // the connection.
3557 VerifyCT();
3559 // Only cache the session if the certificate verified successfully.
3560 core_->CacheSessionIfNecessary();
3563 completed_handshake_ = true;
3565 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3566 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3567 return result;
3570 void SSLClientSocketNSS::VerifyCT() {
3571 if (!cert_transparency_verifier_)
3572 return;
3574 // Note that this is a completely synchronous operation: The CT Log Verifier
3575 // gets all the data it needs for SCT verification and does not do any
3576 // external communication.
3577 cert_transparency_verifier_->Verify(
3578 server_cert_verify_result_.verified_cert.get(),
3579 core_->state().stapled_ocsp_response,
3580 core_->state().sct_list_from_tls_extension, &ct_verify_result_, net_log_);
3581 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3582 // from the state after verification is complete, to conserve memory.
3584 if (!policy_enforcer_) {
3585 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3586 } else {
3587 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
3588 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
3589 SSLConfigService::GetEVCertsWhitelist();
3590 if (!policy_enforcer_->DoesConformToCTEVPolicy(
3591 server_cert_verify_result_.verified_cert.get(),
3592 ev_whitelist.get(), ct_verify_result_, net_log_)) {
3593 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3594 VLOG(1) << "EV certificate for "
3595 << server_cert_verify_result_.verified_cert->subject()
3596 .GetDisplayName()
3597 << " does not conform to CT policy, removing EV status.";
3598 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3604 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3605 base::AutoLock auto_lock(lock_);
3606 if (valid_thread_id_ != base::kInvalidThreadId)
3607 return;
3608 valid_thread_id_ = base::PlatformThread::CurrentId();
3611 bool SSLClientSocketNSS::CalledOnValidThread() const {
3612 EnsureThreadIdAssigned();
3613 base::AutoLock auto_lock(lock_);
3614 return valid_thread_id_ == base::PlatformThread::CurrentId();
3617 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
3618 for (ct::SCTList::const_iterator iter =
3619 ct_verify_result_.verified_scts.begin();
3620 iter != ct_verify_result_.verified_scts.end(); ++iter) {
3621 ssl_info->signed_certificate_timestamps.push_back(
3622 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
3624 for (ct::SCTList::const_iterator iter =
3625 ct_verify_result_.invalid_scts.begin();
3626 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
3627 ssl_info->signed_certificate_timestamps.push_back(
3628 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
3630 for (ct::SCTList::const_iterator iter =
3631 ct_verify_result_.unknown_logs_scts.begin();
3632 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
3633 ssl_info->signed_certificate_timestamps.push_back(
3634 SignedCertificateTimestampAndStatus(*iter,
3635 ct::SCT_STATUS_LOG_UNKNOWN));
3639 scoped_refptr<X509Certificate>
3640 SSLClientSocketNSS::GetUnverifiedServerCertificateChain() const {
3641 return core_->state().server_cert.get();
3644 ChannelIDService* SSLClientSocketNSS::GetChannelIDService() const {
3645 return channel_id_service_;
3648 } // namespace net